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-core/src/main/java/org/apache/maven/plugin/DefaultPluginRealmCache.java
|
CacheKey
|
equals
|
class CacheKey implements Key {
private final Plugin plugin;
private final WorkspaceRepository workspace;
private final LocalRepository localRepo;
private final List<RemoteRepository> repositories;
private final ClassLoader parentRealm;
private final Map<String, ClassLoader> foreignImports;
private final DependencyFilter filter;
private final int hashCode;
public CacheKey(
Plugin plugin,
ClassLoader parentRealm,
Map<String, ClassLoader> foreignImports,
DependencyFilter dependencyFilter,
List<RemoteRepository> repositories,
RepositorySystemSession session) {
this.plugin = plugin.clone();
this.workspace = RepositoryUtils.getWorkspace(session);
this.localRepo = session.getLocalRepository();
this.repositories = new ArrayList<>(repositories.size());
for (RemoteRepository repository : repositories) {
if (repository.isRepositoryManager()) {
this.repositories.addAll(repository.getMirroredRepositories());
} else {
this.repositories.add(repository);
}
}
this.parentRealm = parentRealm;
this.foreignImports = (foreignImports != null) ? foreignImports : Collections.emptyMap();
this.filter = dependencyFilter;
int hash = 17;
hash = hash * 31 + CacheUtils.pluginHashCode(plugin);
hash = hash * 31 + Objects.hashCode(workspace);
hash = hash * 31 + Objects.hashCode(localRepo);
hash = hash * 31 + RepositoryUtils.repositoriesHashCode(repositories);
hash = hash * 31 + Objects.hashCode(parentRealm);
hash = hash * 31 + this.foreignImports.hashCode();
hash = hash * 31 + Objects.hashCode(dependencyFilter);
this.hashCode = hash;
}
@Override
public String toString() {
return plugin.getId();
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
}
|
if (o == this) {
return true;
}
if (!(o instanceof CacheKey)) {
return false;
}
CacheKey that = (CacheKey) o;
return parentRealm == that.parentRealm
&& CacheUtils.pluginEquals(plugin, that.plugin)
&& Objects.equals(workspace, that.workspace)
&& Objects.equals(localRepo, that.localRepo)
&& RepositoryUtils.repositoriesEquals(this.repositories, that.repositories)
&& Objects.equals(filter, that.filter)
&& Objects.equals(foreignImports, that.foreignImports);
| 575
| 173
| 748
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/InvalidPluginDescriptorException.java
|
InvalidPluginDescriptorException
|
toMessage
|
class InvalidPluginDescriptorException extends Exception {
public InvalidPluginDescriptorException(String message, List<String> errors) {
super(toMessage(message, errors));
}
private static String toMessage(String message, List<String> errors) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder buffer = new StringBuilder(256);
buffer.append(message);
for (String error : errors) {
buffer.append(", ").append(error);
}
return buffer.toString();
| 75
| 58
| 133
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/MojoExecution.java
|
MojoExecution
|
toString
|
class MojoExecution {
private Plugin plugin;
private String goal;
private String executionId;
private MojoDescriptor mojoDescriptor;
private org.codehaus.plexus.util.xml.Xpp3Dom configuration;
/**
* Describes the source of an execution.
*/
public enum Source {
/**
* An execution that originates from the direct invocation of a goal from the CLI.
*/
CLI,
/**
* An execution that originates from a goal bound to a lifecycle phase.
*/
LIFECYCLE,
}
private Source source = Source.LIFECYCLE;
/**
* The phase may or may not have been bound to a phase but once the plan has been calculated we know what phase
* this mojo execution is going to run in.
*/
private String lifecyclePhase;
/**
* The executions to fork before this execution, indexed by the groupId:artifactId:version of the project on which
* the forked execution are to be run and in reactor build order.
*/
private Map<String, List<MojoExecution>> forkedExecutions = new LinkedHashMap<>();
public MojoExecution(Plugin plugin, String goal, String executionId) {
this.plugin = plugin;
this.goal = goal;
this.executionId = executionId;
}
public MojoExecution(MojoDescriptor mojoDescriptor) {
this.mojoDescriptor = mojoDescriptor;
this.executionId = null;
this.configuration = null;
}
public MojoExecution(MojoDescriptor mojoDescriptor, String executionId, Source source) {
this.mojoDescriptor = mojoDescriptor;
this.executionId = executionId;
this.configuration = null;
this.source = source;
}
public MojoExecution(MojoDescriptor mojoDescriptor, String executionId) {
this.mojoDescriptor = mojoDescriptor;
this.executionId = executionId;
this.configuration = null;
}
public MojoExecution(MojoDescriptor mojoDescriptor, org.codehaus.plexus.util.xml.Xpp3Dom configuration) {
this.mojoDescriptor = mojoDescriptor;
this.configuration = configuration;
this.executionId = null;
}
public MojoExecution(MojoDescriptor mojoDescriptor, XmlNode configuration) {
this.mojoDescriptor = mojoDescriptor;
this.configuration = new org.codehaus.plexus.util.xml.Xpp3Dom(configuration);
this.executionId = null;
}
/**
* Gets the source of this execution.
*
* @return The source of this execution or {@code null} if unknown.
*/
public Source getSource() {
return source;
}
public String getExecutionId() {
return executionId;
}
public Plugin getPlugin() {
if (mojoDescriptor != null) {
return mojoDescriptor.getPluginDescriptor().getPlugin();
}
return plugin;
}
public MojoDescriptor getMojoDescriptor() {
return mojoDescriptor;
}
public org.codehaus.plexus.util.xml.Xpp3Dom getConfiguration() {
return configuration;
}
public void setConfiguration(org.codehaus.plexus.util.xml.Xpp3Dom configuration) {
this.configuration = configuration;
}
public void setConfiguration(XmlNode configuration) {
this.configuration = configuration != null ? new org.codehaus.plexus.util.xml.Xpp3Dom(configuration) : null;
}
public String identify() {
StringBuilder sb = new StringBuilder(256);
sb.append(executionId);
sb.append(configuration.toString());
return sb.toString();
}
public String getLifecyclePhase() {
return lifecyclePhase;
}
public void setLifecyclePhase(String lifecyclePhase) {
this.lifecyclePhase = lifecyclePhase;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public String getGroupId() {
if (mojoDescriptor != null) {
return mojoDescriptor.getPluginDescriptor().getGroupId();
}
return plugin.getGroupId();
}
public String getArtifactId() {
if (mojoDescriptor != null) {
return mojoDescriptor.getPluginDescriptor().getArtifactId();
}
return plugin.getArtifactId();
}
public String getVersion() {
if (mojoDescriptor != null) {
return mojoDescriptor.getPluginDescriptor().getVersion();
}
return plugin.getVersion();
}
public String getGoal() {
if (mojoDescriptor != null) {
return mojoDescriptor.getGoal();
}
return goal;
}
public void setMojoDescriptor(MojoDescriptor mojoDescriptor) {
this.mojoDescriptor = mojoDescriptor;
}
public Map<String, List<MojoExecution>> getForkedExecutions() {
return forkedExecutions;
}
public void setForkedExecutions(String projectKey, List<MojoExecution> forkedExecutions) {
this.forkedExecutions.put(projectKey, forkedExecutions);
}
}
|
StringBuilder buffer = new StringBuilder(128);
if (mojoDescriptor != null) {
buffer.append(mojoDescriptor.getId());
}
buffer.append(" {execution: ").append(executionId).append('}');
return buffer.toString();
| 1,389
| 71
| 1,460
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/PluginDescriptorParsingException.java
|
PluginDescriptorParsingException
|
createMessage
|
class PluginDescriptorParsingException extends Exception {
public PluginDescriptorParsingException(Plugin plugin, String descriptorLocation, Throwable e) {
super(createMessage(plugin, descriptorLocation, e), e);
}
private static String createMessage(Plugin plugin, String descriptorLocation, Throwable e) {<FILL_FUNCTION_BODY>}
}
|
String message = "Failed to parse plugin descriptor";
if (plugin != null) {
message += " for " + plugin.getId();
}
if (descriptorLocation != null) {
message += " (" + descriptorLocation + ")";
}
if (e != null) {
message += ": " + e.getMessage();
}
return message;
| 92
| 101
| 193
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/PluginExecutionException.java
|
PluginExecutionException
|
constructMessage
|
class PluginExecutionException extends PluginManagerException {
private final MojoExecution mojoExecution;
public PluginExecutionException(MojoExecution mojoExecution, MavenProject project, String message) {
super(mojoExecution.getMojoDescriptor(), project, message);
this.mojoExecution = mojoExecution;
}
public PluginExecutionException(
MojoExecution mojoExecution, MavenProject project, String message, Throwable cause) {
super(mojoExecution.getMojoDescriptor(), project, message, cause);
this.mojoExecution = mojoExecution;
}
public PluginExecutionException(MojoExecution mojoExecution, MavenProject project, Exception cause) {
super(mojoExecution.getMojoDescriptor(), project, constructMessage(mojoExecution, cause), cause);
this.mojoExecution = mojoExecution;
}
public PluginExecutionException(
MojoExecution mojoExecution, MavenProject project, DuplicateArtifactAttachmentException cause) {
super(mojoExecution.getMojoDescriptor(), project, constructMessage(mojoExecution, cause), cause);
this.mojoExecution = mojoExecution;
}
public MojoExecution getMojoExecution() {
return mojoExecution;
}
private static String constructMessage(MojoExecution mojoExecution, Throwable cause) {<FILL_FUNCTION_BODY>}
}
|
String message;
if (mojoExecution != null) {
message = "Execution " + mojoExecution.getExecutionId() + " of goal "
+ mojoExecution.getMojoDescriptor().getId() + " failed";
} else {
message = "Mojo execution failed";
}
if (cause != null && cause.getMessage() != null && !cause.getMessage().isEmpty()) {
message += ": " + cause.getMessage();
} else {
message += ".";
}
return message;
| 346
| 137
| 483
|
<methods>public void <init>(Plugin, java.lang.String, java.lang.Throwable) ,public void <init>(Plugin, org.apache.maven.artifact.versioning.InvalidVersionSpecificationException) ,public void <init>(Plugin, java.lang.String, org.codehaus.plexus.configuration.PlexusConfigurationException) ,public void <init>(Plugin, java.lang.String, org.codehaus.plexus.component.repository.exception.ComponentRepositoryException) ,public void <init>(org.apache.maven.plugin.descriptor.MojoDescriptor, org.apache.maven.project.MavenProject, java.lang.String, org.codehaus.plexus.classworlds.realm.NoSuchRealmException) ,public void <init>(org.apache.maven.plugin.descriptor.MojoDescriptor, java.lang.String, org.apache.maven.project.MavenProject, org.codehaus.plexus.PlexusContainerException) ,public void <init>(Plugin, java.lang.String, org.codehaus.plexus.PlexusContainerException) ,public void <init>(Plugin, java.lang.String, org.apache.maven.project.MavenProject) ,public java.lang.String getGoal() ,public java.lang.String getPluginArtifactId() ,public java.lang.String getPluginGroupId() ,public java.lang.String getPluginVersion() ,public org.apache.maven.project.MavenProject getProject() <variables>private java.lang.String goal,private final non-sealed java.lang.String pluginArtifactId,private final non-sealed java.lang.String pluginGroupId,private final non-sealed java.lang.String pluginVersion,private org.apache.maven.project.MavenProject project
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java
|
PluginParameterException
|
format
|
class PluginParameterException extends PluginConfigurationException {
private static final String LS = System.lineSeparator();
private final List<Parameter> parameters;
private final MojoDescriptor mojo;
public PluginParameterException(MojoDescriptor mojo, List<Parameter> parameters) {
super(
mojo.getPluginDescriptor(),
"The parameters " + format(parameters) + " for goal " + mojo.getRoleHint() + " are missing or invalid");
this.mojo = mojo;
this.parameters = parameters;
}
private static String format(List<Parameter> parameters) {<FILL_FUNCTION_BODY>}
public MojoDescriptor getMojoDescriptor() {
return mojo;
}
public List<Parameter> getParameters() {
return parameters;
}
private static void decomposeParameterIntoUserInstructions(
MojoDescriptor mojo, Parameter param, StringBuilder messageBuffer) {
String expression = param.getExpression();
if (param.isEditable()) {
boolean isArray = param.getType().endsWith("[]");
boolean isCollection = false;
boolean isMap = false;
boolean isProperties = false;
if (!isArray) {
try {
// assuming Type is available in current ClassLoader
isCollection = Collection.class.isAssignableFrom(Class.forName(param.getType()));
isMap = Map.class.isAssignableFrom(Class.forName(param.getType()));
isProperties = Properties.class.isAssignableFrom(Class.forName(param.getType()));
} catch (ClassNotFoundException e) {
// assume it is not assignable from Collection or Map
}
}
messageBuffer.append("Inside the definition for plugin '");
messageBuffer.append(mojo.getPluginDescriptor().getArtifactId());
messageBuffer.append("', specify the following:").append(LS).append(LS);
messageBuffer.append("<configuration>").append(LS).append(" ...").append(LS);
messageBuffer.append(" <").append(param.getName()).append('>');
if (isArray || isCollection) {
messageBuffer.append(LS);
messageBuffer.append(" <item>");
} else if (isProperties) {
messageBuffer.append(LS);
messageBuffer.append(" <property>").append(LS);
messageBuffer.append(" <name>KEY</name>").append(LS);
messageBuffer.append(" <value>");
} else if (isMap) {
messageBuffer.append(LS);
messageBuffer.append(" <KEY>");
}
messageBuffer.append("VALUE");
if (isArray || isCollection) {
messageBuffer.append("</item>").append(LS);
messageBuffer.append(" ");
} else if (isProperties) {
messageBuffer.append("</value>").append(LS);
messageBuffer.append(" </property>").append(LS);
messageBuffer.append(" ");
} else if (isMap) {
messageBuffer.append("</KEY>").append(LS);
messageBuffer.append(" ");
}
messageBuffer.append("</").append(param.getName()).append(">").append(LS);
messageBuffer.append("</configuration>");
String alias = param.getAlias();
if ((alias != null && !alias.isEmpty()) && !alias.equals(param.getName())) {
messageBuffer.append(LS).append(LS).append("-OR-").append(LS).append(LS);
messageBuffer
.append("<configuration>")
.append(LS)
.append(" ...")
.append(LS);
messageBuffer
.append(" <")
.append(alias)
.append(">VALUE</")
.append(alias)
.append(">")
.append(LS)
.append("</configuration>")
.append(LS);
}
}
if (expression == null || expression.isEmpty()) {
messageBuffer.append('.');
} else {
if (param.isEditable()) {
messageBuffer.append(LS).append(LS).append("-OR-").append(LS).append(LS);
}
// addParameterUsageInfo( expression, messageBuffer );
}
}
public String buildDiagnosticMessage() {
StringBuilder messageBuffer = new StringBuilder(256);
List<Parameter> params = getParameters();
MojoDescriptor mojo = getMojoDescriptor();
messageBuffer
.append("One or more required plugin parameters are invalid/missing for '")
.append(mojo.getPluginDescriptor().getGoalPrefix())
.append(':')
.append(mojo.getGoal())
.append("'")
.append(LS);
int idx = 0;
for (Iterator<Parameter> it = params.iterator(); it.hasNext(); idx++) {
Parameter param = it.next();
messageBuffer.append(LS).append("[").append(idx).append("] ");
decomposeParameterIntoUserInstructions(mojo, param, messageBuffer);
messageBuffer.append(LS);
}
return messageBuffer.toString();
}
}
|
StringBuilder buffer = new StringBuilder(128);
if (parameters != null) {
for (Parameter parameter : parameters) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append('\'').append(parameter.getName()).append('\'');
}
}
return buffer.toString();
| 1,325
| 92
| 1,417
|
<methods>public void <init>(org.apache.maven.plugin.descriptor.PluginDescriptor, java.lang.String) ,public void <init>(org.apache.maven.plugin.descriptor.PluginDescriptor, java.lang.String, java.lang.Throwable) ,public void <init>(org.apache.maven.plugin.descriptor.PluginDescriptor, java.lang.String, org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException) ,public void <init>(org.apache.maven.plugin.descriptor.PluginDescriptor, java.lang.String, org.codehaus.plexus.component.configurator.ComponentConfigurationException) ,public void <init>(org.apache.maven.plugin.descriptor.PluginDescriptor, java.lang.String, org.codehaus.plexus.component.repository.exception.ComponentLookupException) <variables>private java.lang.String originalMessage,private org.apache.maven.plugin.descriptor.PluginDescriptor pluginDescriptor
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterExpressionEvaluatorV4.java
|
PluginParameterExpressionEvaluatorV4
|
evaluate
|
class PluginParameterExpressionEvaluatorV4 implements TypeAwareExpressionEvaluator {
private final Session session;
private final MojoExecution mojoExecution;
private final Project project;
private final Path basedir;
private final Map<String, String> properties;
public PluginParameterExpressionEvaluatorV4(Session session, Project project) {
this(session, project, null);
}
public PluginParameterExpressionEvaluatorV4(Session session, Project project, MojoExecution mojoExecution) {
this.session = session;
this.mojoExecution = mojoExecution;
this.properties = session.getEffectiveProperties(project);
this.project = project;
Path basedir = null;
if (project != null) {
Path projectFile = project.getBasedir();
basedir = projectFile.toAbsolutePath();
}
if (basedir == null) {
basedir = session.getTopDirectory();
}
if (basedir == null) {
basedir = Paths.get(System.getProperty("user.dir"));
}
this.basedir = basedir;
}
@Override
public Object evaluate(String expr) throws ExpressionEvaluationException {
return evaluate(expr, null);
}
@Override
@SuppressWarnings("checkstyle:methodlength")
public Object evaluate(String expr, Class<?> type) throws ExpressionEvaluationException {<FILL_FUNCTION_BODY>}
private static boolean isTypeCompatible(Class<?> type, Object value) {
if (type.isInstance(value)) {
return true;
}
// likely Boolean -> boolean, Short -> int etc. conversions, it's not the problem case we try to avoid
return ((type.isPrimitive() || type.getName().startsWith("java.lang."))
&& value.getClass().getName().startsWith("java.lang."));
}
private String stripTokens(String expr) {
if (expr.startsWith("${") && (expr.indexOf('}') == expr.length() - 1)) {
expr = expr.substring(2, expr.length() - 1);
}
return expr;
}
@Override
public File alignToBaseDirectory(File file) {
// TODO Copied from the DefaultInterpolator. We likely want to resurrect the PathTranslator or at least a
// similar component for re-usage
if (file != null) {
if (file.isAbsolute()) {
// path was already absolute, just normalize file separator and we're done
} else if (file.getPath().startsWith(File.separator)) {
// drive-relative Windows path, don't align with project directory but with drive root
file = file.getAbsoluteFile();
} else {
// an ordinary relative path, align with project directory
file = basedir.resolve(file.getPath())
.normalize()
.toAbsolutePath()
.toFile();
}
}
return file;
}
}
|
Object value = null;
if (expr == null) {
return null;
}
String expression = stripTokens(expr);
if (expression.equals(expr)) {
int index = expr.indexOf("${");
if (index >= 0) {
int lastIndex = expr.indexOf('}', index);
if (lastIndex >= 0) {
String retVal = expr.substring(0, index);
if ((index > 0) && (expr.charAt(index - 1) == '$')) {
retVal += expr.substring(index + 1, lastIndex + 1);
} else {
Object subResult = evaluate(expr.substring(index, lastIndex + 1));
if (subResult != null) {
retVal += subResult;
} else {
retVal += "$" + expr.substring(index + 1, lastIndex + 1);
}
}
retVal += evaluate(expr.substring(lastIndex + 1));
return retVal;
}
}
// Was not an expression
return expression.replace("$$", "$");
}
Map<String, Object> objects = new HashMap<>();
objects.put("session.", session);
objects.put("project.", project);
objects.put("mojo.", mojoExecution);
objects.put("settings.", session.getSettings());
for (Map.Entry<String, Object> ctx : objects.entrySet()) {
if (expression.startsWith(ctx.getKey())) {
try {
int pathSeparator = expression.indexOf('/');
if (pathSeparator > 0) {
String pathExpression = expression.substring(0, pathSeparator);
value = ReflectionValueExtractor.evaluate(pathExpression, ctx.getValue());
if (pathSeparator < expression.length() - 1) {
if (value instanceof Path) {
value = ((Path) value).resolve(expression.substring(pathSeparator + 1));
} else {
value = value + expression.substring(pathSeparator);
}
}
} else {
value = ReflectionValueExtractor.evaluate(expression, ctx.getValue());
}
break;
} catch (Exception e) {
// TODO don't catch exception
throw new ExpressionEvaluationException(
"Error evaluating plugin parameter expression: " + expression, e);
}
}
}
/*
* MNG-4312: We neither have reserved all of the above magic expressions nor is their set fixed/well-known (it
* gets occasionally extended by newer Maven versions). This imposes the risk for existing plugins to
* unintentionally use such a magic expression for an ordinary property. So here we check whether we
* ended up with a magic value that is not compatible with the type of the configured mojo parameter (a string
* could still be converted by the configurator so we leave those alone). If so, back off to evaluating the
* expression from properties only.
*/
if (value != null && type != null && !(value instanceof String) && !isTypeCompatible(type, value)) {
value = null;
}
if (value == null) {
// The CLI should win for defining properties
if (properties != null) {
// We will attempt to get nab a property as a way to specify a parameter
// to a plugin. My particular case here is allowing the surefire plugin
// to run a single test so I want to specify that class on the cli as
// a parameter.
value = properties.get(expression);
}
}
if (value instanceof String) {
// TODO without #, this could just be an evaluate call...
String val = (String) value;
int exprStartDelimiter = val.indexOf("${");
if (exprStartDelimiter >= 0) {
if (exprStartDelimiter > 0) {
value = val.substring(0, exprStartDelimiter) + evaluate(val.substring(exprStartDelimiter));
} else {
value = evaluate(val.substring(exprStartDelimiter));
}
}
}
return value;
| 794
| 1,055
| 1,849
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/AbstractMavenPluginDependenciesValidator.java
|
AbstractMavenPluginDependenciesValidator
|
validate
|
class AbstractMavenPluginDependenciesValidator implements MavenPluginDependenciesValidator {
protected final PluginValidationManager pluginValidationManager;
protected AbstractMavenPluginDependenciesValidator(PluginValidationManager pluginValidationManager) {
this.pluginValidationManager = requireNonNull(pluginValidationManager);
}
@Override
public void validate(
RepositorySystemSession session,
Artifact pluginArtifact,
ArtifactDescriptorResult artifactDescriptorResult) {<FILL_FUNCTION_BODY>}
protected abstract void doValidate(
RepositorySystemSession session,
Artifact pluginArtifact,
ArtifactDescriptorResult artifactDescriptorResult);
}
|
if (artifactDescriptorResult.getDependencies() != null) {
doValidate(session, pluginArtifact, artifactDescriptorResult);
}
| 157
| 39
| 196
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/AbstractMavenPluginDescriptorSourcedParametersValidator.java
|
AbstractMavenPluginDescriptorSourcedParametersValidator
|
isIgnoredProperty
|
class AbstractMavenPluginDescriptorSourcedParametersValidator extends AbstractMavenPluginParametersValidator {
// plugin author can provide @Parameter( property = "session" ) in this case property will always evaluate
// so, we need ignore those
// source org.apache.maven.plugin.PluginParameterExpressionEvaluator
private static final List<String> IGNORED_PROPERTY_VALUES = Arrays.asList(
"basedir",
"executedProject",
"localRepository",
"mojo",
"mojoExecution",
"plugin",
"project",
"reactorProjects",
"session",
"settings");
private static final List<String> IGNORED_PROPERTY_PREFIX =
Arrays.asList("mojo.", "pom.", "plugin.", "project.", "session.", "settings.");
protected AbstractMavenPluginDescriptorSourcedParametersValidator(PluginValidationManager pluginValidationManager) {
super(pluginValidationManager);
}
@Override
protected boolean isIgnoredProperty(String strValue) {<FILL_FUNCTION_BODY>}
}
|
if (!strValue.startsWith("${")) {
return false;
}
String propertyName = strValue.replace("${", "").replace("}", "");
if (IGNORED_PROPERTY_VALUES.contains(propertyName)) {
return true;
}
return IGNORED_PROPERTY_PREFIX.stream().anyMatch(propertyName::startsWith);
| 275
| 107
| 382
|
<methods>public final void validate(org.apache.maven.execution.MavenSession, org.apache.maven.plugin.descriptor.MojoDescriptor, Class<?>, org.codehaus.plexus.configuration.PlexusConfiguration, org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator) <variables>protected final non-sealed org.apache.maven.plugin.PluginValidationManager pluginValidationManager
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/AbstractMavenPluginParametersValidator.java
|
AbstractMavenPluginParametersValidator
|
isValueSet
|
class AbstractMavenPluginParametersValidator implements MavenPluginConfigurationValidator {
protected final PluginValidationManager pluginValidationManager;
protected AbstractMavenPluginParametersValidator(PluginValidationManager pluginValidationManager) {
this.pluginValidationManager = requireNonNull(pluginValidationManager);
}
protected boolean isValueSet(PlexusConfiguration config, ExpressionEvaluator expressionEvaluator) {<FILL_FUNCTION_BODY>}
@Override
public final void validate(
MavenSession mavenSession,
MojoDescriptor mojoDescriptor,
Class<?> mojoClass,
PlexusConfiguration pomConfiguration,
ExpressionEvaluator expressionEvaluator) {
doValidate(mavenSession, mojoDescriptor, mojoClass, pomConfiguration, expressionEvaluator);
}
protected abstract void doValidate(
MavenSession mavenSession,
MojoDescriptor mojoDescriptor,
Class<?> mojoClass,
PlexusConfiguration pomConfiguration,
ExpressionEvaluator expressionEvaluator);
protected boolean isIgnoredProperty(String strValue) {
return false;
}
protected abstract String getParameterLogReason(Parameter parameter);
protected String formatParameter(Parameter parameter) {
StringBuilder stringBuilder = new StringBuilder()
.append("Parameter '")
.append(parameter.getName())
.append('\'');
if (parameter.getExpression() != null) {
String userProperty = parameter.getExpression().replace("${", "'").replace('}', '\'');
stringBuilder.append(" (user property ").append(userProperty).append(")");
}
stringBuilder.append(" ").append(getParameterLogReason(parameter));
return stringBuilder.toString();
}
}
|
if (config == null) {
return false;
}
// there are sub items ... so configuration is declared
if (config.getChildCount() > 0) {
return true;
}
String strValue = config.getValue();
if (strValue == null || strValue.isEmpty()) {
return false;
}
if (isIgnoredProperty(strValue)) {
return false;
}
// for declaration like @Parameter( property = "config.property" )
// the value will contain ${config.property}
try {
return expressionEvaluator.evaluate(strValue) != null;
} catch (ExpressionEvaluationException e) {
// not important
// will be reported during Mojo fields populate
}
// fallback - in case of error in expressionEvaluator
return false;
| 437
| 219
| 656
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultLegacySupport.java
|
DefaultLegacySupport
|
setSession
|
class DefaultLegacySupport implements LegacySupport {
private static final ThreadLocal<AtomicReference<MavenSession>> SESSION = new InheritableThreadLocal<>();
public void setSession(MavenSession session) {<FILL_FUNCTION_BODY>}
public MavenSession getSession() {
AtomicReference<MavenSession> currentSession = DefaultLegacySupport.SESSION.get();
return currentSession != null ? currentSession.get() : null;
}
public RepositorySystemSession getRepositorySession() {
MavenSession session = getSession();
return (session != null) ? session.getRepositorySession() : null;
}
}
|
AtomicReference<MavenSession> reference = DefaultLegacySupport.SESSION.get();
if (reference != null) {
reference.set(null);
}
if (session == null && reference != null) {
DefaultLegacySupport.SESSION.remove();
} else {
DefaultLegacySupport.SESSION.set(new AtomicReference<>(session));
}
| 165
| 98
| 263
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginValidator.java
|
DefaultMavenPluginValidator
|
validate
|
class DefaultMavenPluginValidator implements MavenPluginValidator {
@Override
public void validate(Artifact pluginArtifact, PluginDescriptor pluginDescriptor, List<String> errors) {<FILL_FUNCTION_BODY>}
}
|
if (!pluginArtifact.getGroupId().equals(pluginDescriptor.getGroupId())) {
errors.add("Plugin's descriptor contains the wrong group ID: " + pluginDescriptor.getGroupId());
}
if (!pluginArtifact.getArtifactId().equals(pluginDescriptor.getArtifactId())) {
errors.add("Plugin's descriptor contains the wrong artifact ID: " + pluginDescriptor.getArtifactId());
}
if (!pluginArtifact.getBaseVersion().equals(pluginDescriptor.getVersion())) {
errors.add("Plugin's descriptor contains the wrong version: " + pluginDescriptor.getVersion());
}
| 57
| 155
| 212
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginDependenciesResolver.java
|
DefaultPluginDependenciesResolver
|
resolve
|
class DefaultPluginDependenciesResolver implements PluginDependenciesResolver {
private static final String REPOSITORY_CONTEXT = "plugin";
private final Logger logger = LoggerFactory.getLogger(getClass());
private final RepositorySystem repoSystem;
private final List<MavenPluginDependenciesValidator> dependenciesValidators;
@Inject
public DefaultPluginDependenciesResolver(
RepositorySystem repoSystem, List<MavenPluginDependenciesValidator> dependenciesValidators) {
this.repoSystem = repoSystem;
this.dependenciesValidators = dependenciesValidators;
}
private Artifact toArtifact(Plugin plugin, RepositorySystemSession session) {
return new DefaultArtifact(
plugin.getGroupId(),
plugin.getArtifactId(),
null,
"jar",
plugin.getVersion(),
session.getArtifactTypeRegistry().get("maven-plugin"));
}
public Artifact resolve(Plugin plugin, List<RemoteRepository> repositories, RepositorySystemSession session)
throws PluginResolutionException {<FILL_FUNCTION_BODY>}
/**
* @since 3.3.0
*/
public DependencyResult resolveCoreExtension(
Plugin plugin,
DependencyFilter dependencyFilter,
List<RemoteRepository> repositories,
RepositorySystemSession session)
throws PluginResolutionException {
return resolveInternal(plugin, null /* pluginArtifact */, dependencyFilter, repositories, session);
}
public DependencyResult resolvePlugin(
Plugin plugin,
Artifact pluginArtifact,
DependencyFilter dependencyFilter,
List<RemoteRepository> repositories,
RepositorySystemSession session)
throws PluginResolutionException {
return resolveInternal(plugin, pluginArtifact, dependencyFilter, repositories, session);
}
public DependencyNode resolve(
Plugin plugin,
Artifact pluginArtifact,
DependencyFilter dependencyFilter,
List<RemoteRepository> repositories,
RepositorySystemSession session)
throws PluginResolutionException {
return resolveInternal(plugin, pluginArtifact, dependencyFilter, repositories, session)
.getRoot();
}
private DependencyResult resolveInternal(
Plugin plugin,
Artifact pluginArtifact,
DependencyFilter dependencyFilter,
List<RemoteRepository> repositories,
RepositorySystemSession session)
throws PluginResolutionException {
RequestTrace trace = RequestTrace.newChild(null, plugin);
if (pluginArtifact == null) {
pluginArtifact = toArtifact(plugin, session);
}
DependencyFilter collectionFilter = new ScopeDependencyFilter("provided", "test");
DependencyFilter resolutionFilter = AndDependencyFilter.newInstance(collectionFilter, dependencyFilter);
DependencyNode node;
try {
DefaultRepositorySystemSession pluginSession = new DefaultRepositorySystemSession(session);
pluginSession.setDependencySelector(session.getDependencySelector());
pluginSession.setDependencyGraphTransformer(session.getDependencyGraphTransformer());
CollectRequest request = new CollectRequest();
request.setRequestContext(REPOSITORY_CONTEXT);
request.setRepositories(repositories);
request.setRoot(new org.eclipse.aether.graph.Dependency(pluginArtifact, null));
for (Dependency dependency : plugin.getDependencies()) {
org.eclipse.aether.graph.Dependency pluginDep =
RepositoryUtils.toDependency(dependency, session.getArtifactTypeRegistry());
if (!DependencyScope.SYSTEM.is(pluginDep.getScope())) {
pluginDep = pluginDep.setScope(DependencyScope.RUNTIME.id());
}
request.addDependency(pluginDep);
}
DependencyRequest depRequest = new DependencyRequest(request, resolutionFilter);
depRequest.setTrace(trace);
request.setTrace(RequestTrace.newChild(trace, depRequest));
node = repoSystem.collectDependencies(pluginSession, request).getRoot();
if (logger.isDebugEnabled()) {
node.accept(new DependencyGraphDumper(logger::debug));
}
depRequest.setRoot(node);
return repoSystem.resolveDependencies(session, depRequest);
} catch (DependencyCollectionException e) {
throw new PluginResolutionException(plugin, e);
} catch (DependencyResolutionException e) {
throw new PluginResolutionException(plugin, e.getCause());
}
}
}
|
RequestTrace trace = RequestTrace.newChild(null, plugin);
Artifact pluginArtifact = toArtifact(plugin, session);
try {
DefaultRepositorySystemSession pluginSession = new DefaultRepositorySystemSession(session);
pluginSession.setArtifactDescriptorPolicy(new SimpleArtifactDescriptorPolicy(true, false));
ArtifactDescriptorRequest request =
new ArtifactDescriptorRequest(pluginArtifact, repositories, REPOSITORY_CONTEXT);
request.setTrace(trace);
ArtifactDescriptorResult result = repoSystem.readArtifactDescriptor(pluginSession, request);
for (MavenPluginDependenciesValidator dependenciesValidator : dependenciesValidators) {
dependenciesValidator.validate(session, pluginArtifact, result);
}
pluginArtifact = result.getArtifact();
if (logger.isWarnEnabled() && !result.getRelocations().isEmpty()) {
String message =
pluginArtifact instanceof org.apache.maven.internal.impl.resolver.RelocatedArtifact relocated
? ": " + relocated.getMessage()
: "";
logger.warn(
"The artifact {} has been relocated to {}{}",
result.getRelocations().get(0),
pluginArtifact,
message);
}
String requiredMavenVersion = (String) result.getProperties().get("prerequisites.maven");
if (requiredMavenVersion != null) {
Map<String, String> props = new LinkedHashMap<>(pluginArtifact.getProperties());
props.put("requiredMavenVersion", requiredMavenVersion);
pluginArtifact = pluginArtifact.setProperties(props);
}
} catch (ArtifactDescriptorException e) {
throw new PluginResolutionException(plugin, e);
}
try {
ArtifactRequest request = new ArtifactRequest(pluginArtifact, repositories, REPOSITORY_CONTEXT);
request.setTrace(trace);
pluginArtifact = repoSystem.resolveArtifact(session, request).getArtifact();
} catch (ArtifactResolutionException e) {
throw new PluginResolutionException(plugin, e);
}
return pluginArtifact;
| 1,114
| 537
| 1,651
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginValidationManager.java
|
PluginValidationIssues
|
reportPluginIssue
|
class PluginValidationIssues {
private final LinkedHashSet<String> pluginDeclarations;
private final HashMap<IssueLocality, LinkedHashSet<String>> pluginIssues;
private final HashMap<IssueLocality, LinkedHashMap<String, LinkedHashSet<String>>> mojoIssues;
private PluginValidationIssues() {
this.pluginDeclarations = new LinkedHashSet<>();
this.pluginIssues = new HashMap<>();
this.mojoIssues = new HashMap<>();
}
private synchronized void reportPluginIssue(
IssueLocality issueLocality, String pluginDeclaration, String issue) {<FILL_FUNCTION_BODY>}
private synchronized void reportPluginMojoIssue(
IssueLocality issueLocality, String pluginDeclaration, String mojoInfo, String issue) {
if (pluginDeclaration != null) {
pluginDeclarations.add(pluginDeclaration);
}
mojoIssues
.computeIfAbsent(issueLocality, k -> new LinkedHashMap<>())
.computeIfAbsent(mojoInfo, k -> new LinkedHashSet<>())
.add(issue);
}
}
|
if (pluginDeclaration != null) {
pluginDeclarations.add(pluginDeclaration);
}
pluginIssues
.computeIfAbsent(issueLocality, k -> new LinkedHashSet<>())
.add(issue);
| 298
| 62
| 360
|
<methods>public non-sealed void <init>() ,public void close() throws java.lang.Exception,public void init(org.apache.maven.eventspy.EventSpy.Context) throws java.lang.Exception,public void onEvent(java.lang.Object) throws java.lang.Exception<variables>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/DeprecatedCoreExpressionValidator.java
|
DeprecatedCoreExpressionValidator
|
doValidate
|
class DeprecatedCoreExpressionValidator extends AbstractMavenPluginParametersValidator {
private static final HashMap<String, String> DEPRECATED_CORE_PARAMETERS;
private static final String ARTIFACT_REPOSITORY_REASON =
"ArtifactRepository type is deprecated and its use in Mojos should be avoided.";
static {
HashMap<String, String> deprecatedCoreParameters = new HashMap<>();
deprecatedCoreParameters.put("${localRepository}", ARTIFACT_REPOSITORY_REASON);
deprecatedCoreParameters.put("${session.localRepository}", ARTIFACT_REPOSITORY_REASON);
DEPRECATED_CORE_PARAMETERS = deprecatedCoreParameters;
}
@Inject
DeprecatedCoreExpressionValidator(PluginValidationManager pluginValidationManager) {
super(pluginValidationManager);
}
@Override
protected String getParameterLogReason(Parameter parameter) {
return "uses deprecated parameter expression '" + parameter.getDefaultValue() + "': "
+ DEPRECATED_CORE_PARAMETERS.get(parameter.getDefaultValue());
}
@Override
protected void doValidate(
MavenSession mavenSession,
MojoDescriptor mojoDescriptor,
Class<?> mojoClass,
PlexusConfiguration pomConfiguration,
ExpressionEvaluator expressionEvaluator) {<FILL_FUNCTION_BODY>}
private boolean isDeprecated(Parameter parameter) {
return Objects.equals(
org.apache.maven.artifact.repository.ArtifactRepository.class.getName(), parameter.getType())
&& DEPRECATED_CORE_PARAMETERS.containsKey(parameter.getDefaultValue());
}
}
|
if (mojoDescriptor.getParameters() == null) {
return;
}
mojoDescriptor.getParameters().stream()
.filter(this::isDeprecated)
.map(this::formatParameter)
.forEach(m -> pluginValidationManager.reportPluginMojoValidationIssue(
PluginValidationManager.IssueLocality.EXTERNAL, mavenSession, mojoDescriptor, mojoClass, m));
| 436
| 108
| 544
|
<methods>public final void validate(org.apache.maven.execution.MavenSession, org.apache.maven.plugin.descriptor.MojoDescriptor, Class<?>, org.codehaus.plexus.configuration.PlexusConfiguration, org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator) <variables>protected final non-sealed org.apache.maven.plugin.PluginValidationManager pluginValidationManager
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/DeprecatedPluginValidator.java
|
DeprecatedPluginValidator
|
doValidate
|
class DeprecatedPluginValidator extends AbstractMavenPluginDescriptorSourcedParametersValidator {
private final MessageBuilderFactory messageBuilderFactory;
@Inject
DeprecatedPluginValidator(
PluginValidationManager pluginValidationManager, MessageBuilderFactory messageBuilderFactory) {
super(pluginValidationManager);
this.messageBuilderFactory = messageBuilderFactory;
}
@Override
protected String getParameterLogReason(Parameter parameter) {
return "is deprecated: " + parameter.getDeprecated();
}
@Override
protected void doValidate(
MavenSession mavenSession,
MojoDescriptor mojoDescriptor,
Class<?> mojoClass,
PlexusConfiguration pomConfiguration,
ExpressionEvaluator expressionEvaluator) {<FILL_FUNCTION_BODY>}
private void checkParameter(
MavenSession mavenSession,
MojoDescriptor mojoDescriptor,
Class<?> mojoClass,
Parameter parameter,
PlexusConfiguration pomConfiguration,
ExpressionEvaluator expressionEvaluator) {
PlexusConfiguration config = pomConfiguration.getChild(parameter.getName(), false);
if (isValueSet(config, expressionEvaluator)) {
pluginValidationManager.reportPluginMojoValidationIssue(
PluginValidationManager.IssueLocality.INTERNAL,
mavenSession,
mojoDescriptor,
mojoClass,
formatParameter(parameter));
}
}
private String logDeprecatedMojo(MojoDescriptor mojoDescriptor) {
return messageBuilderFactory
.builder()
.warning("Goal '")
.warning(mojoDescriptor.getGoal())
.warning("' is deprecated: ")
.warning(mojoDescriptor.getDeprecated())
.toString();
}
}
|
if (mojoDescriptor.getDeprecated() != null) {
pluginValidationManager.reportPluginMojoValidationIssue(
PluginValidationManager.IssueLocality.INTERNAL,
mavenSession,
mojoDescriptor,
mojoClass,
logDeprecatedMojo(mojoDescriptor));
}
if (mojoDescriptor.getParameters() != null) {
mojoDescriptor.getParameters().stream()
.filter(parameter -> parameter.getDeprecated() != null)
.filter(Parameter::isEditable)
.forEach(parameter -> checkParameter(
mavenSession, mojoDescriptor, mojoClass, parameter, pomConfiguration, expressionEvaluator));
}
| 447
| 179
| 626
|
<methods><variables>private static final List<java.lang.String> IGNORED_PROPERTY_PREFIX,private static final List<java.lang.String> IGNORED_PROPERTY_VALUES
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/Maven2DependenciesValidator.java
|
Maven2DependenciesValidator
|
doValidate
|
class Maven2DependenciesValidator extends AbstractMavenPluginDependenciesValidator {
@Inject
Maven2DependenciesValidator(PluginValidationManager pluginValidationManager) {
super(pluginValidationManager);
}
@Override
protected void doValidate(
RepositorySystemSession session,
Artifact pluginArtifact,
ArtifactDescriptorResult artifactDescriptorResult) {<FILL_FUNCTION_BODY>}
}
|
Set<String> maven2Versions = artifactDescriptorResult.getDependencies().stream()
.map(Dependency::getArtifact)
.filter(d -> "org.apache.maven".equals(d.getGroupId()))
.filter(d -> !DefaultPluginValidationManager.EXPECTED_PROVIDED_SCOPE_EXCLUSIONS_GA.contains(
d.getGroupId() + ":" + d.getArtifactId()))
.map(Artifact::getVersion)
.filter(v -> v.startsWith("2."))
.collect(Collectors.toSet());
if (!maven2Versions.isEmpty()) {
pluginValidationManager.reportPluginValidationIssue(
PluginValidationManager.IssueLocality.EXTERNAL,
session,
pluginArtifact,
"Plugin is a Maven 2.x plugin, which will be not supported in Maven 4.x");
}
| 105
| 233
| 338
|
<methods>public void validate(RepositorySystemSession, Artifact, ArtifactDescriptorResult) <variables>protected final non-sealed org.apache.maven.plugin.PluginValidationManager pluginValidationManager
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/Maven3CompatDependenciesValidator.java
|
Maven3CompatDependenciesValidator
|
doValidate
|
class Maven3CompatDependenciesValidator extends AbstractMavenPluginDependenciesValidator {
@Inject
Maven3CompatDependenciesValidator(PluginValidationManager pluginValidationManager) {
super(pluginValidationManager);
}
@Override
protected void doValidate(
RepositorySystemSession session,
Artifact pluginArtifact,
ArtifactDescriptorResult artifactDescriptorResult) {<FILL_FUNCTION_BODY>}
}
|
for (org.eclipse.aether.graph.Dependency dependency : artifactDescriptorResult.getDependencies()) {
if ("org.apache.maven".equals(dependency.getArtifact().getGroupId())
&& "maven-compat".equals(dependency.getArtifact().getArtifactId())
&& !DependencyScope.TEST.is(dependency.getScope())) {
pluginValidationManager.reportPluginValidationIssue(
PluginValidationManager.IssueLocality.EXTERNAL,
session,
pluginArtifact,
"Plugin depends on the deprecated Maven 2.x compatibility layer, which will be not supported in Maven 4.x");
}
}
| 107
| 163
| 270
|
<methods>public void validate(RepositorySystemSession, Artifact, ArtifactDescriptorResult) <variables>protected final non-sealed org.apache.maven.plugin.PluginValidationManager pluginValidationManager
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenMixedDependenciesValidator.java
|
MavenMixedDependenciesValidator
|
doValidate
|
class MavenMixedDependenciesValidator extends AbstractMavenPluginDependenciesValidator {
@Inject
MavenMixedDependenciesValidator(PluginValidationManager pluginValidationManager) {
super(pluginValidationManager);
}
@Override
protected void doValidate(
RepositorySystemSession session,
Artifact pluginArtifact,
ArtifactDescriptorResult artifactDescriptorResult) {<FILL_FUNCTION_BODY>}
}
|
Set<String> mavenVersions = artifactDescriptorResult.getDependencies().stream()
.map(Dependency::getArtifact)
.filter(d -> "org.apache.maven".equals(d.getGroupId()))
.filter(d -> !DefaultPluginValidationManager.EXPECTED_PROVIDED_SCOPE_EXCLUSIONS_GA.contains(
d.getGroupId() + ":" + d.getArtifactId()))
.map(Artifact::getVersion)
.collect(Collectors.toSet());
if (mavenVersions.size() > 1) {
pluginValidationManager.reportPluginValidationIssue(
PluginValidationManager.IssueLocality.EXTERNAL,
session,
pluginArtifact,
"Plugin mixes multiple Maven versions: " + mavenVersions);
}
| 107
| 208
| 315
|
<methods>public void validate(RepositorySystemSession, Artifact, ArtifactDescriptorResult) <variables>protected final non-sealed org.apache.maven.plugin.PluginValidationManager pluginValidationManager
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginJavaPrerequisiteChecker.java
|
MavenPluginJavaPrerequisiteChecker
|
matchesVersion
|
class MavenPluginJavaPrerequisiteChecker implements MavenPluginPrerequisitesChecker {
private final VersionScheme versionScheme;
@Inject
public MavenPluginJavaPrerequisiteChecker(VersionScheme versionScheme) {
this.versionScheme = versionScheme;
}
@Override
public void accept(PluginDescriptor pluginDescriptor) {
String requiredJavaVersion = pluginDescriptor.getRequiredJavaVersion();
if (requiredJavaVersion != null && !requiredJavaVersion.isEmpty()) {
String currentJavaVersion = System.getProperty("java.version");
if (!matchesVersion(requiredJavaVersion, currentJavaVersion)) {
throw new IllegalStateException("Required Java version " + requiredJavaVersion
+ " is not met by current version: " + currentJavaVersion);
}
}
}
boolean matchesVersion(String requiredVersion, String currentVersion) {<FILL_FUNCTION_BODY>}
}
|
VersionConstraint constraint;
try {
constraint = versionScheme.parseVersionConstraint(requiredVersion);
} catch (InvalidVersionSpecificationException e) {
throw new IllegalArgumentException("Invalid 'requiredJavaVersion' given in plugin descriptor", e);
}
Version current;
try {
current = versionScheme.parseVersion(currentVersion);
} catch (InvalidVersionSpecificationException e) {
throw new IllegalStateException("Could not parse current Java version", e);
}
if (constraint.getRange() == null) {
return constraint.getVersion().compareTo(current) <= 0;
}
return constraint.containsVersion(current);
| 233
| 162
| 395
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenPluginMavenPrerequisiteChecker.java
|
MavenPluginMavenPrerequisiteChecker
|
accept
|
class MavenPluginMavenPrerequisiteChecker implements MavenPluginPrerequisitesChecker {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final RuntimeInformation runtimeInformation;
@Inject
public MavenPluginMavenPrerequisiteChecker(RuntimeInformation runtimeInformation) {
super();
this.runtimeInformation = runtimeInformation;
}
@Override
public void accept(PluginDescriptor pluginDescriptor) {<FILL_FUNCTION_BODY>}
}
|
String requiredMavenVersion = pluginDescriptor.getRequiredMavenVersion();
boolean isBlankVersion =
requiredMavenVersion == null || requiredMavenVersion.trim().isEmpty();
if (!isBlankVersion) {
boolean isRequirementMet = false;
try {
isRequirementMet = runtimeInformation.isMavenVersion(requiredMavenVersion);
} catch (IllegalArgumentException e) {
logger.warn(
"Could not verify plugin's Maven prerequisite as an invalid version is given in "
+ requiredMavenVersion,
e);
return;
}
if (!isRequirementMet) {
throw new IllegalStateException("Required Maven version " + requiredMavenVersion
+ " is not met by current version " + runtimeInformation.getMavenVersion());
}
}
| 126
| 205
| 331
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/MavenScopeDependenciesValidator.java
|
MavenScopeDependenciesValidator
|
doValidate
|
class MavenScopeDependenciesValidator extends AbstractMavenPluginDependenciesValidator {
@Inject
MavenScopeDependenciesValidator(PluginValidationManager pluginValidationManager) {
super(pluginValidationManager);
}
@Override
protected void doValidate(
RepositorySystemSession session,
Artifact pluginArtifact,
ArtifactDescriptorResult artifactDescriptorResult) {<FILL_FUNCTION_BODY>}
}
|
Set<String> mavenArtifacts = artifactDescriptorResult.getDependencies().stream()
.filter(d -> !DependencyScope.PROVIDED.is(d.getScope()) && !DependencyScope.TEST.is(d.getScope()))
.map(org.eclipse.aether.graph.Dependency::getArtifact)
.filter(a -> "org.apache.maven".equals(a.getGroupId()))
.filter(a -> !DefaultPluginValidationManager.EXPECTED_PROVIDED_SCOPE_EXCLUSIONS_GA.contains(
a.getGroupId() + ":" + a.getArtifactId()))
.filter(a -> a.getVersion().startsWith("3."))
.map(a -> a.getGroupId() + ":" + a.getArtifactId() + ":" + a.getVersion())
.collect(Collectors.toSet());
if (!mavenArtifacts.isEmpty()) {
pluginValidationManager.reportPluginValidationIssue(
PluginValidationManager.IssueLocality.EXTERNAL,
session,
pluginArtifact,
"Plugin should declare Maven artifacts in `provided` scope. If the plugin already declares them in `provided` scope, update the maven-plugin-plugin to latest version. Artifacts found with wrong scope: "
+ mavenArtifacts);
}
| 105
| 339
| 444
|
<methods>public void validate(RepositorySystemSession, Artifact, ArtifactDescriptorResult) <variables>protected final non-sealed org.apache.maven.plugin.PluginValidationManager pluginValidationManager
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/MojoLogWrapper.java
|
MojoLogWrapper
|
toString
|
class MojoLogWrapper implements Log {
private final Logger logger;
public MojoLogWrapper(Logger logger) {
this.logger = requireNonNull(logger);
}
public void debug(CharSequence content) {
if (isDebugEnabled()) {
logger.debug(toString(content));
}
}
private String toString(CharSequence content) {<FILL_FUNCTION_BODY>}
@Override
public void debug(CharSequence content, Throwable error) {
if (isDebugEnabled()) {
logger.debug(toString(content), error);
}
}
@Override
public void debug(Throwable error) {
logger.debug("", error);
}
@Override
public void info(CharSequence content) {
if (isInfoEnabled()) {
logger.info(toString(content));
}
}
@Override
public void info(CharSequence content, Throwable error) {
if (isInfoEnabled()) {
logger.info(toString(content), error);
}
}
@Override
public void info(Throwable error) {
logger.info("", error);
}
@Override
public void warn(CharSequence content) {
if (isWarnEnabled()) {
logger.warn(toString(content));
}
}
@Override
public void warn(CharSequence content, Throwable error) {
if (isWarnEnabled()) {
logger.warn(toString(content), error);
}
}
@Override
public void warn(Throwable error) {
logger.warn("", error);
}
@Override
public void error(CharSequence content) {
if (isErrorEnabled()) {
logger.error(toString(content));
}
}
@Override
public void error(CharSequence content, Throwable error) {
if (isErrorEnabled()) {
logger.error(toString(content), error);
}
}
@Override
public void error(Throwable error) {
logger.error("", error);
}
@Override
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
@Override
public boolean isInfoEnabled() {
return logger.isInfoEnabled();
}
@Override
public boolean isWarnEnabled() {
return logger.isWarnEnabled();
}
@Override
public boolean isErrorEnabled() {
return logger.isErrorEnabled();
}
}
|
if (content == null) {
return "";
} else {
return content.toString();
}
| 644
| 31
| 675
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/PlexusContainerDefaultDependenciesValidator.java
|
PlexusContainerDefaultDependenciesValidator
|
doValidate
|
class PlexusContainerDefaultDependenciesValidator extends AbstractMavenPluginDependenciesValidator {
@Inject
PlexusContainerDefaultDependenciesValidator(PluginValidationManager pluginValidationManager) {
super(pluginValidationManager);
}
protected void doValidate(
RepositorySystemSession session,
Artifact pluginArtifact,
ArtifactDescriptorResult artifactDescriptorResult) {<FILL_FUNCTION_BODY>}
}
|
boolean pcdPresent = artifactDescriptorResult.getDependencies().stream()
.filter(d -> "org.codehaus.plexus".equals(d.getArtifact().getGroupId()))
.anyMatch(d -> "plexus-container-default".equals(d.getArtifact().getArtifactId()));
if (pcdPresent) {
pluginValidationManager.reportPluginValidationIssue(
PluginValidationManager.IssueLocality.EXTERNAL,
session,
pluginArtifact,
"Plugin depends on plexus-container-default, which is EOL");
}
| 105
| 149
| 254
|
<methods>public void validate(RepositorySystemSession, Artifact, ArtifactDescriptorResult) <variables>protected final non-sealed org.apache.maven.plugin.PluginValidationManager pluginValidationManager
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/PluginConfigurationModule.java
|
PluginConfigurationModule
|
configure
|
class PluginConfigurationModule implements Module {
private final Plugin plugin;
PluginConfigurationModule(Plugin plugin) {
this.plugin = plugin;
}
@Override
public void configure(Binder binder) {<FILL_FUNCTION_BODY>}
}
|
if (plugin.getKey() != null) {
XmlNode configuration = plugin.getConfiguration();
if (configuration == null) {
configuration = new XmlNodeImpl("configuration");
}
binder.bind(XmlNode.class)
.annotatedWith(Names.named(plugin.getKey()))
.toInstance(configuration);
binder.bind(PlexusConfiguration.class)
.annotatedWith(Names.named(plugin.getKey()))
.toInstance(XmlPlexusConfiguration.toPlexusConfiguration(configuration));
}
| 72
| 144
| 216
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/ReadOnlyPluginParametersValidator.java
|
ReadOnlyPluginParametersValidator
|
checkParameter
|
class ReadOnlyPluginParametersValidator extends AbstractMavenPluginDescriptorSourcedParametersValidator {
@Inject
ReadOnlyPluginParametersValidator(PluginValidationManager pluginValidationManager) {
super(pluginValidationManager);
}
@Override
protected String getParameterLogReason(Parameter parameter) {
return "is read-only, must not be used in configuration";
}
@Override
protected void doValidate(
MavenSession mavenSession,
MojoDescriptor mojoDescriptor,
Class<?> mojoClass,
PlexusConfiguration pomConfiguration,
ExpressionEvaluator expressionEvaluator) {
if (mojoDescriptor.getParameters() == null) {
return;
}
mojoDescriptor.getParameters().stream()
.filter(parameter -> !parameter.isEditable())
.forEach(parameter -> checkParameter(
mavenSession, mojoDescriptor, mojoClass, parameter, pomConfiguration, expressionEvaluator));
}
private void checkParameter(
MavenSession mavenSession,
MojoDescriptor mojoDescriptor,
Class<?> mojoClass,
Parameter parameter,
PlexusConfiguration pomConfiguration,
ExpressionEvaluator expressionEvaluator) {<FILL_FUNCTION_BODY>}
}
|
PlexusConfiguration config = pomConfiguration.getChild(parameter.getName(), false);
if (isValueSet(config, expressionEvaluator)) {
pluginValidationManager.reportPluginMojoValidationIssue(
PluginValidationManager.IssueLocality.INTERNAL,
mavenSession,
mojoDescriptor,
mojoClass,
formatParameter(parameter));
}
| 320
| 99
| 419
|
<methods><variables>private static final List<java.lang.String> IGNORED_PROPERTY_PREFIX,private static final List<java.lang.String> IGNORED_PROPERTY_VALUES
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/internal/ValidatingConfigurationListener.java
|
ValidatingConfigurationListener
|
notifyFieldChangeUsingSetter
|
class ValidatingConfigurationListener implements ConfigurationListener {
private final Object mojo;
private final ConfigurationListener delegate;
private final Map<String, Parameter> missingParameters;
ValidatingConfigurationListener(Object mojo, MojoDescriptor mojoDescriptor, ConfigurationListener delegate) {
this.mojo = mojo;
this.delegate = delegate;
this.missingParameters = new HashMap<>();
if (mojoDescriptor.getParameters() != null) {
for (Parameter param : mojoDescriptor.getParameters()) {
if (param.isRequired()) {
missingParameters.put(param.getName(), param);
}
}
}
}
public Collection<Parameter> getMissingParameters() {
return missingParameters.values();
}
public void notifyFieldChangeUsingSetter(String fieldName, Object value, Object target) {<FILL_FUNCTION_BODY>}
public void notifyFieldChangeUsingReflection(String fieldName, Object value, Object target) {
delegate.notifyFieldChangeUsingReflection(fieldName, value, target);
if (mojo == target) {
notify(fieldName, value);
}
}
private void notify(String fieldName, Object value) {
if (value != null) {
missingParameters.remove(fieldName);
}
}
}
|
delegate.notifyFieldChangeUsingSetter(fieldName, value, target);
if (mojo == target) {
notify(fieldName, value);
}
| 335
| 44
| 379
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/prefix/DefaultPluginPrefixRequest.java
|
DefaultPluginPrefixRequest
|
setPluginGroups
|
class DefaultPluginPrefixRequest implements PluginPrefixRequest {
private String prefix;
private List<String> pluginGroups = Collections.emptyList();
private Model pom;
private List<RemoteRepository> repositories = Collections.emptyList();
private RepositorySystemSession session;
/**
* Creates an empty request.
*/
public DefaultPluginPrefixRequest() {}
/**
* Creates a request for the specified plugin prefix and build session. The provided build session will be used to
* configure repository settings. If the session has a current project, its plugin repositories and model will be
* used as well.
*
* @param prefix The plugin prefix to resolve, must not be {@code null}.
* @param session The build session from which to derive further settings, must not be {@code null}.
*/
public DefaultPluginPrefixRequest(String prefix, MavenSession session) {
setPrefix(prefix);
setRepositorySession(session.getRepositorySession());
MavenProject project = session.getCurrentProject();
if (project != null) {
setRepositories(project.getRemotePluginRepositories());
setPom(project.getModel());
}
setPluginGroups(session.getPluginGroups());
}
public String getPrefix() {
return prefix;
}
public DefaultPluginPrefixRequest setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
public List<String> getPluginGroups() {
return pluginGroups;
}
public DefaultPluginPrefixRequest setPluginGroups(List<String> pluginGroups) {<FILL_FUNCTION_BODY>}
public Model getPom() {
return pom;
}
public DefaultPluginPrefixRequest setPom(Model pom) {
this.pom = pom;
return this;
}
public List<RemoteRepository> getRepositories() {
return repositories;
}
public DefaultPluginPrefixRequest setRepositories(List<RemoteRepository> repositories) {
if (repositories != null) {
this.repositories = Collections.unmodifiableList(repositories);
} else {
this.repositories = Collections.emptyList();
}
return this;
}
public RepositorySystemSession getRepositorySession() {
return session;
}
public DefaultPluginPrefixRequest setRepositorySession(RepositorySystemSession session) {
this.session = session;
return this;
}
}
|
if (pluginGroups != null) {
this.pluginGroups = Collections.unmodifiableList(pluginGroups);
} else {
this.pluginGroups = Collections.emptyList();
}
return this;
| 639
| 59
| 698
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/prefix/NoPluginFoundForPrefixException.java
|
NoPluginFoundForPrefixException
|
format
|
class NoPluginFoundForPrefixException extends Exception {
public NoPluginFoundForPrefixException(
String prefix,
List<String> pluginGroups,
LocalRepository localRepository,
List<RemoteRepository> remoteRepositories) {
super("No plugin found for prefix '" + prefix + "' in the current project and in the plugin groups "
+ pluginGroups + " available from the repositories " + format(localRepository, remoteRepositories));
}
private static String format(LocalRepository localRepository, List<RemoteRepository> remoteRepositories) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder repos = new StringBuilder("[");
if (localRepository != null) {
repos.append(localRepository.getId())
.append(" (")
.append(localRepository.getBasedir())
.append(")");
}
if (remoteRepositories != null && !remoteRepositories.isEmpty()) {
for (RemoteRepository repository : remoteRepositories) {
repos.append(", ");
if (repository != null) {
repos.append(repository.getId())
.append(" (")
.append(repository.getUrl())
.append(")");
}
}
}
repos.append("]");
return repos.toString();
| 148
| 191
| 339
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/prefix/internal/DefaultPluginPrefixResolver.java
|
DefaultPluginPrefixResolver
|
resolve
|
class DefaultPluginPrefixResolver implements PluginPrefixResolver {
private static final String REPOSITORY_CONTEXT = "plugin";
private final Logger logger = LoggerFactory.getLogger(getClass());
private final BuildPluginManager pluginManager;
private final RepositorySystem repositorySystem;
private final MetadataReader metadataReader;
@Inject
public DefaultPluginPrefixResolver(
BuildPluginManager pluginManager, RepositorySystem repositorySystem, MetadataReader metadataReader) {
this.pluginManager = pluginManager;
this.repositorySystem = repositorySystem;
this.metadataReader = metadataReader;
}
public PluginPrefixResult resolve(PluginPrefixRequest request) throws NoPluginFoundForPrefixException {<FILL_FUNCTION_BODY>}
private PluginPrefixResult resolveFromProject(PluginPrefixRequest request) {
PluginPrefixResult result = null;
if (request.getPom() != null && request.getPom().getBuild() != null) {
Build build = request.getPom().getBuild();
result = resolveFromProject(request, build.getPlugins());
if (result == null && build.getPluginManagement() != null) {
result = resolveFromProject(request, build.getPluginManagement().getPlugins());
}
}
return result;
}
private PluginPrefixResult resolveFromProject(PluginPrefixRequest request, List<Plugin> plugins) {
for (Plugin plugin : plugins) {
try {
PluginDescriptor pluginDescriptor =
pluginManager.loadPlugin(plugin, request.getRepositories(), request.getRepositorySession());
if (request.getPrefix().equals(pluginDescriptor.getGoalPrefix())) {
return new DefaultPluginPrefixResult(plugin);
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.warn("Failed to retrieve plugin descriptor for {}: {}", plugin.getId(), e.getMessage(), e);
} else {
logger.warn("Failed to retrieve plugin descriptor for {}: {}", plugin.getId(), e.getMessage());
}
}
}
return null;
}
private PluginPrefixResult resolveFromRepository(PluginPrefixRequest request) {
RequestTrace trace = RequestTrace.newChild(null, request);
List<MetadataRequest> requests = new ArrayList<>();
for (String pluginGroup : request.getPluginGroups()) {
org.eclipse.aether.metadata.Metadata metadata =
new DefaultMetadata(pluginGroup, "maven-metadata.xml", DefaultMetadata.Nature.RELEASE_OR_SNAPSHOT);
requests.add(new MetadataRequest(metadata, null, REPOSITORY_CONTEXT).setTrace(trace));
for (RemoteRepository repository : request.getRepositories()) {
requests.add(new MetadataRequest(metadata, repository, REPOSITORY_CONTEXT).setTrace(trace));
}
}
// initial try, use locally cached metadata
List<MetadataResult> results = repositorySystem.resolveMetadata(request.getRepositorySession(), requests);
requests.clear();
PluginPrefixResult result = processResults(request, trace, results, requests);
if (result != null) {
return result;
}
// second try, refetch all (possibly outdated) metadata that wasn't updated in the first attempt
if (!request.getRepositorySession().isOffline() && !requests.isEmpty()) {
DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(request.getRepositorySession());
session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS);
results = repositorySystem.resolveMetadata(session, requests);
return processResults(request, trace, results, null);
}
return null;
}
private PluginPrefixResult processResults(
PluginPrefixRequest request,
RequestTrace trace,
List<MetadataResult> results,
List<MetadataRequest> requests) {
for (MetadataResult res : results) {
org.eclipse.aether.metadata.Metadata metadata = res.getMetadata();
if (metadata != null) {
ArtifactRepository repository = res.getRequest().getRepository();
if (repository == null) {
repository = request.getRepositorySession().getLocalRepository();
}
PluginPrefixResult result =
resolveFromRepository(request, trace, metadata.getGroupId(), metadata, repository);
if (result != null) {
return result;
}
}
if (requests != null && !res.isUpdated()) {
requests.add(res.getRequest());
}
}
return null;
}
private PluginPrefixResult resolveFromRepository(
PluginPrefixRequest request,
RequestTrace trace,
String pluginGroup,
org.eclipse.aether.metadata.Metadata metadata,
ArtifactRepository repository) {
if (metadata != null && metadata.getFile() != null && metadata.getFile().isFile()) {
try {
Map<String, ?> options = Collections.singletonMap(MetadataReader.IS_STRICT, Boolean.FALSE);
Metadata pluginGroupMetadata = metadataReader.read(metadata.getFile(), options);
List<org.apache.maven.artifact.repository.metadata.Plugin> plugins = pluginGroupMetadata.getPlugins();
if (plugins != null) {
for (org.apache.maven.artifact.repository.metadata.Plugin plugin : plugins) {
if (request.getPrefix().equals(plugin.getPrefix())) {
return new DefaultPluginPrefixResult(pluginGroup, plugin.getArtifactId(), repository);
}
}
}
} catch (IOException e) {
invalidMetadata(request.getRepositorySession(), trace, metadata, repository, e);
}
}
return null;
}
private void invalidMetadata(
RepositorySystemSession session,
RequestTrace trace,
org.eclipse.aether.metadata.Metadata metadata,
ArtifactRepository repository,
Exception exception) {
RepositoryListener listener = session.getRepositoryListener();
if (listener != null) {
RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_INVALID);
event.setTrace(trace);
event.setMetadata(metadata);
event.setException(exception);
event.setRepository(repository);
listener.metadataInvalid(event.build());
}
}
}
|
logger.debug("Resolving plugin prefix {} from {}", request.getPrefix(), request.getPluginGroups());
PluginPrefixResult result = resolveFromProject(request);
if (result == null) {
result = resolveFromRepository(request);
if (result == null) {
throw new NoPluginFoundForPrefixException(
request.getPrefix(),
request.getPluginGroups(),
request.getRepositorySession().getLocalRepository(),
request.getRepositories());
} else {
logger.debug(
"Resolved plugin prefix {} to {}:{} from repository {}",
request.getPrefix(),
result.getGroupId(),
result.getArtifactId(),
(result.getRepository() != null ? result.getRepository().getId() : "null"));
}
} else {
logger.debug(
"Resolved plugin prefix {} to {}:{} from POM {}",
request.getPrefix(),
result.getGroupId(),
result.getArtifactId(),
request.getPom());
}
return result;
| 1,596
| 267
| 1,863
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/version/DefaultPluginVersionRequest.java
|
DefaultPluginVersionRequest
|
setRepositories
|
class DefaultPluginVersionRequest implements PluginVersionRequest {
private String groupId;
private String artifactId;
private Model pom;
private List<RemoteRepository> repositories = Collections.emptyList();
private RepositorySystemSession session;
/**
* Creates an empty request.
*/
public DefaultPluginVersionRequest() {}
/**
* Creates a request for the specified plugin by copying settings from the specified build session. If the session
* has a current project, its plugin repositories will be used as well.
*
* @param plugin The plugin for which to resolve a version, must not be {@code null}.
* @param session The Maven session to use, must not be {@code null}.
*/
public DefaultPluginVersionRequest(Plugin plugin, MavenSession session) {
setGroupId(plugin.getGroupId());
setArtifactId(plugin.getArtifactId());
setRepositorySession(session.getRepositorySession());
MavenProject project = session.getCurrentProject();
if (project != null) {
setRepositories(project.getRemotePluginRepositories());
}
}
/**
* Creates a request for the specified plugin using the given repository session and plugin repositories.
*
* @param plugin The plugin for which to resolve a version, must not be {@code null}.
* @param session The repository session to use, must not be {@code null}.
* @param repositories The plugin repositories to query, may be {@code null}.
*/
public DefaultPluginVersionRequest(
Plugin plugin, RepositorySystemSession session, List<RemoteRepository> repositories) {
setGroupId(plugin.getGroupId());
setArtifactId(plugin.getArtifactId());
setRepositorySession(session);
setRepositories(repositories);
}
public String getGroupId() {
return groupId;
}
public DefaultPluginVersionRequest setGroupId(String groupId) {
this.groupId = groupId;
return this;
}
public String getArtifactId() {
return artifactId;
}
public DefaultPluginVersionRequest setArtifactId(String artifactId) {
this.artifactId = artifactId;
return this;
}
public Model getPom() {
return pom;
}
public DefaultPluginVersionRequest setPom(Model pom) {
this.pom = pom;
return this;
}
public List<RemoteRepository> getRepositories() {
return repositories;
}
public DefaultPluginVersionRequest setRepositories(List<RemoteRepository> repositories) {<FILL_FUNCTION_BODY>}
public RepositorySystemSession getRepositorySession() {
return session;
}
public DefaultPluginVersionRequest setRepositorySession(RepositorySystemSession session) {
this.session = session;
return this;
}
}
|
if (repositories != null) {
this.repositories = Collections.unmodifiableList(repositories);
} else {
this.repositories = Collections.emptyList();
}
return this;
| 741
| 63
| 804
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/plugin/version/PluginVersionResolutionException.java
|
PluginVersionResolutionException
|
format
|
class PluginVersionResolutionException extends Exception {
private final String groupId;
private final String artifactId;
private final String baseMessage;
public PluginVersionResolutionException(String groupId, String artifactId, String baseMessage, Throwable cause) {
super("Error resolving version for plugin '" + groupId + ":" + artifactId + "': " + baseMessage, cause);
this.groupId = groupId;
this.artifactId = artifactId;
this.baseMessage = baseMessage;
}
public PluginVersionResolutionException(String groupId, String artifactId, String baseMessage) {
super("Error resolving version for plugin '" + groupId + ":" + artifactId + "': " + baseMessage);
this.groupId = groupId;
this.artifactId = artifactId;
this.baseMessage = baseMessage;
}
public PluginVersionResolutionException(
String groupId,
String artifactId,
LocalRepository localRepository,
List<RemoteRepository> remoteRepositories,
String baseMessage) {
super("Error resolving version for plugin '" + groupId + ":" + artifactId + "' from the repositories "
+ format(localRepository, remoteRepositories) + ": " + baseMessage);
this.groupId = groupId;
this.artifactId = artifactId;
this.baseMessage = baseMessage;
}
public String getGroupId() {
return groupId;
}
public String getArtifactId() {
return artifactId;
}
public String getBaseMessage() {
return baseMessage;
}
private static String format(LocalRepository localRepository, List<RemoteRepository> remoteRepositories) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder repos = new StringBuilder("[");
if (localRepository != null) {
repos.append(localRepository.getId())
.append(" (")
.append(localRepository.getBasedir())
.append(")");
}
if (remoteRepositories != null && !remoteRepositories.isEmpty()) {
for (RemoteRepository repository : remoteRepositories) {
repos.append(", ");
if (repository != null) {
repos.append(repository.getId())
.append(" (")
.append(repository.getUrl())
.append(")");
}
}
}
repos.append("]");
return repos.toString();
| 440
| 191
| 631
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/DefaultMavenProjectHelper.java
|
DefaultMavenProjectHelper
|
attachArtifact
|
class DefaultMavenProjectHelper extends AbstractLogEnabled implements MavenProjectHelper {
private final ArtifactHandlerManager artifactHandlerManager;
@Inject
public DefaultMavenProjectHelper(ArtifactHandlerManager artifactHandlerManager) {
this.artifactHandlerManager = artifactHandlerManager;
}
public void attachArtifact(
MavenProject project, String artifactType, String artifactClassifier, File artifactFile) {
ArtifactHandler handler = null;
if (artifactType != null) {
handler = artifactHandlerManager.getArtifactHandler(artifactType);
}
if (handler == null) {
handler = artifactHandlerManager.getArtifactHandler("jar");
}
Artifact artifact = new AttachedArtifact(project.getArtifact(), artifactType, artifactClassifier, handler);
artifact.setFile(artifactFile);
artifact.setResolved(true);
attachArtifact(project, artifact);
}
public void attachArtifact(MavenProject project, String artifactType, File artifactFile) {<FILL_FUNCTION_BODY>}
public void attachArtifact(MavenProject project, File artifactFile, String artifactClassifier) {
Artifact projectArtifact = project.getArtifact();
Artifact artifact = new AttachedArtifact(
projectArtifact, projectArtifact.getType(), artifactClassifier, projectArtifact.getArtifactHandler());
artifact.setFile(artifactFile);
artifact.setResolved(true);
attachArtifact(project, artifact);
}
/**
* Add an attached artifact or replace the file for an existing artifact.
*
* @see MavenProject#addAttachedArtifact(org.apache.maven.artifact.Artifact)
* @param project project reference.
* @param artifact artifact to add or replace.
*/
public void attachArtifact(MavenProject project, Artifact artifact) {
project.addAttachedArtifact(artifact);
}
public void addResource(
MavenProject project, String resourceDirectory, List<String> includes, List<String> excludes) {
Resource resource = new Resource();
resource.setDirectory(resourceDirectory);
resource.setIncludes(includes);
resource.setExcludes(excludes);
project.addResource(resource);
}
public void addTestResource(
MavenProject project, String resourceDirectory, List<String> includes, List<String> excludes) {
Resource resource = new Resource();
resource.setDirectory(resourceDirectory);
resource.setIncludes(includes);
resource.setExcludes(excludes);
project.addTestResource(resource);
}
}
|
ArtifactHandler handler = artifactHandlerManager.getArtifactHandler(artifactType);
Artifact artifact = new AttachedArtifact(project.getArtifact(), artifactType, handler);
artifact.setFile(artifactFile);
artifact.setResolved(true);
attachArtifact(project, artifact);
| 656
| 78
| 734
|
<methods>public void <init>() ,public void enableLogging(org.codehaus.plexus.logging.Logger) <variables>private org.codehaus.plexus.logging.Logger logger
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/DefaultModelBuildingListener.java
|
DefaultModelBuildingListener
|
buildExtensionsAssembled
|
class DefaultModelBuildingListener implements ModelBuildingListener {
private final MavenProject project;
private final ProjectBuildingHelper projectBuildingHelper;
private final ProjectBuildingRequest projectBuildingRequest;
private List<ArtifactRepository> remoteRepositories;
private List<ArtifactRepository> pluginRepositories;
public DefaultModelBuildingListener(
MavenProject project,
ProjectBuildingHelper projectBuildingHelper,
ProjectBuildingRequest projectBuildingRequest) {
this.project = Objects.requireNonNull(project, "project cannot be null");
this.projectBuildingHelper =
Objects.requireNonNull(projectBuildingHelper, "projectBuildingHelper cannot be null");
this.projectBuildingRequest =
Objects.requireNonNull(projectBuildingRequest, "projectBuildingRequest cannot be null");
this.remoteRepositories = projectBuildingRequest.getRemoteRepositories();
this.pluginRepositories = projectBuildingRequest.getPluginArtifactRepositories();
}
/**
* Gets the project whose model is being built.
*
* @return The project, never {@code null}.
*/
public MavenProject getProject() {
return project;
}
@Override
public void buildExtensionsAssembled(ModelBuildingEvent event) {<FILL_FUNCTION_BODY>}
}
|
Model model = new Model(event.model());
try {
pluginRepositories = projectBuildingHelper.createArtifactRepositories(
model.getPluginRepositories(), pluginRepositories, projectBuildingRequest);
} catch (Exception e) {
event.problems()
.add(
BuilderProblem.Severity.ERROR,
ModelProblem.Version.BASE,
"Invalid plugin repository: " + e.getMessage(),
e);
}
project.setPluginArtifactRepositories(pluginRepositories);
if (event.request().isProcessPlugins()) {
try {
ProjectRealmCache.CacheRecord record =
projectBuildingHelper.createProjectRealm(project, model, projectBuildingRequest);
project.setClassRealm(record.getRealm());
project.setExtensionDependencyFilter(record.getExtensionArtifactFilter());
} catch (PluginResolutionException | PluginManagerException | PluginVersionResolutionException e) {
event.problems()
.add(
BuilderProblem.Severity.ERROR,
ModelProblem.Version.BASE,
"Unresolvable build extension: " + e.getMessage(),
e);
}
projectBuildingHelper.selectProjectRealm(project);
}
// build the regular repos after extensions are loaded to allow for custom layouts
try {
remoteRepositories = projectBuildingHelper.createArtifactRepositories(
model.getRepositories(), remoteRepositories, projectBuildingRequest);
} catch (Exception e) {
event.problems()
.add(
BuilderProblem.Severity.ERROR,
ModelProblem.Version.BASE,
"Invalid artifact repository: " + e.getMessage(),
e);
}
project.setRemoteArtifactRepositories(remoteRepositories);
if (model.getDelegate() != event.model()) {
event.update().accept(model.getDelegate());
}
| 326
| 501
| 827
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/DefaultProjectDependenciesResolver.java
|
DefaultProjectDependenciesResolver
|
resolve
|
class DefaultProjectDependenciesResolver implements ProjectDependenciesResolver {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final RepositorySystem repoSystem;
private final List<RepositorySessionDecorator> decorators;
@Inject
public DefaultProjectDependenciesResolver(
RepositorySystem repoSystem, List<RepositorySessionDecorator> decorators) {
this.repoSystem = repoSystem;
this.decorators = decorators;
}
public DependencyResolutionResult resolve(DependencyResolutionRequest request)
throws DependencyResolutionException {<FILL_FUNCTION_BODY>}
private void process(DefaultDependencyResolutionResult result, Collection<ArtifactResult> results) {
for (ArtifactResult ar : results) {
DependencyNode node = ar.getRequest().getDependencyNode();
if (ar.isResolved()) {
result.addResolvedDependency(node.getDependency());
} else {
result.setResolutionErrors(node.getDependency(), ar.getExceptions());
}
}
}
}
|
final RequestTrace trace = RequestTrace.newChild(null, request);
final DefaultDependencyResolutionResult result = new DefaultDependencyResolutionResult();
final MavenProject project = request.getMavenProject();
final DependencyFilter filter = request.getResolutionFilter();
RepositorySystemSession session = request.getRepositorySession();
ArtifactTypeRegistry stereotypes = session.getArtifactTypeRegistry();
if (logger.isDebugEnabled()
&& session.getConfigProperties().get(DependencyManagerUtils.CONFIG_PROP_VERBOSE) == null) {
DefaultRepositorySystemSession verbose = new DefaultRepositorySystemSession(session);
verbose.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, Boolean.TRUE);
session = verbose;
}
for (RepositorySessionDecorator decorator : decorators) {
RepositorySystemSession decorated = decorator.decorate(project, session);
if (decorated != null) {
session = decorated;
}
}
CollectRequest collect = new CollectRequest();
collect.setRootArtifact(RepositoryUtils.toArtifact(project.getArtifact()));
collect.setRequestContext("project");
collect.setRepositories(project.getRemoteProjectRepositories());
if (project.getDependencyArtifacts() == null) {
for (Dependency dependency : project.getDependencies()) {
if (dependency.getGroupId() == null
|| dependency.getGroupId().isEmpty()
|| dependency.getArtifactId() == null
|| dependency.getArtifactId().isEmpty()
|| dependency.getVersion() == null
|| dependency.getVersion().isEmpty()) {
// guard against case where best-effort resolution for invalid models is requested
continue;
}
collect.addDependency(RepositoryUtils.toDependency(dependency, stereotypes));
}
} else {
Map<String, Dependency> dependencies = new HashMap<>();
for (Dependency dependency : project.getDependencies()) {
String classifier = dependency.getClassifier();
if (classifier == null) {
ArtifactType type = stereotypes.get(dependency.getType());
if (type != null) {
classifier = type.getClassifier();
}
}
String key = ArtifactIdUtils.toVersionlessId(
dependency.getGroupId(), dependency.getArtifactId(), dependency.getType(), classifier);
dependencies.put(key, dependency);
}
for (Artifact artifact : project.getDependencyArtifacts()) {
String key = artifact.getDependencyConflictId();
Dependency dependency = dependencies.get(key);
Collection<Exclusion> exclusions = dependency != null ? dependency.getExclusions() : null;
org.eclipse.aether.graph.Dependency dep = RepositoryUtils.toDependency(artifact, exclusions);
if (!DependencyScope.SYSTEM.is(dep.getScope())
&& dep.getArtifact().getFile() != null) {
// enable re-resolution
org.eclipse.aether.artifact.Artifact art = dep.getArtifact();
art = art.setFile(null).setVersion(art.getBaseVersion());
dep = dep.setArtifact(art);
}
collect.addDependency(dep);
}
}
DependencyManagement depMgmt = project.getDependencyManagement();
if (depMgmt != null) {
for (Dependency dependency : depMgmt.getDependencies()) {
collect.addManagedDependency(RepositoryUtils.toDependency(dependency, stereotypes));
}
}
DependencyRequest depRequest = new DependencyRequest(collect, filter);
depRequest.setTrace(trace);
DependencyNode node;
try {
collect.setTrace(RequestTrace.newChild(trace, depRequest));
node = repoSystem.collectDependencies(session, collect).getRoot();
result.setDependencyGraph(node);
} catch (DependencyCollectionException e) {
result.setDependencyGraph(e.getResult().getRoot());
result.setCollectionErrors(e.getResult().getExceptions());
throw new DependencyResolutionException(
result, "Could not resolve dependencies for project " + project.getId() + ": " + e.getMessage(), e);
}
depRequest.setRoot(node);
if (logger.isWarnEnabled()) {
for (DependencyNode child : node.getChildren()) {
if (!child.getRelocations().isEmpty()) {
org.eclipse.aether.artifact.Artifact artifact =
child.getDependency().getArtifact();
String message =
artifact instanceof org.apache.maven.internal.impl.resolver.RelocatedArtifact relocated
? relocated.getMessage()
: null;
logger.warn("The artifact " + child.getRelocations().get(0) + " has been relocated to " + artifact
+ (message != null ? ": " + message : ""));
}
}
}
if (logger.isDebugEnabled()) {
node.accept(new DependencyGraphDumper(logger::debug));
}
try {
process(result, repoSystem.resolveDependencies(session, depRequest).getArtifactResults());
} catch (org.eclipse.aether.resolution.DependencyResolutionException e) {
process(result, e.getResult().getArtifactResults());
throw new DependencyResolutionException(
result, "Could not resolve dependencies for project " + project.getId() + ": " + e.getMessage(), e);
}
return result;
| 267
| 1,395
| 1,662
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/DefaultProjectRealmCache.java
|
CacheKey
|
flush
|
class CacheKey implements Key {
private final List<? extends ClassRealm> extensionRealms;
private final int hashCode;
public CacheKey(List<? extends ClassRealm> extensionRealms) {
this.extensionRealms =
(extensionRealms != null) ? Collections.unmodifiableList(extensionRealms) : Collections.emptyList();
this.hashCode = this.extensionRealms.hashCode();
}
@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 extensionRealms.equals(other.extensionRealms);
}
@Override
public String toString() {
return extensionRealms.toString();
}
}
protected final Map<Key, CacheRecord> cache = new ConcurrentHashMap<>();
@Override
public Key createKey(List<? extends ClassRealm> extensionRealms) {
return new CacheKey(extensionRealms);
}
public CacheRecord get(Key key) {
return cache.get(key);
}
public CacheRecord put(Key key, ClassRealm projectRealm, DependencyFilter extensionArtifactFilter) {
Objects.requireNonNull(projectRealm, "projectRealm cannot be null");
if (cache.containsKey(key)) {
throw new IllegalStateException("Duplicate project realm for extensions " + key);
}
CacheRecord record = new CacheRecord(projectRealm, extensionArtifactFilter);
cache.put(key, record);
return record;
}
public void flush() {<FILL_FUNCTION_BODY>
|
for (CacheRecord record : cache.values()) {
ClassRealm realm = record.getRealm();
try {
realm.getWorld().disposeRealm(realm.getId());
} catch (NoSuchRealmException e) {
// ignore
}
}
cache.clear();
| 471
| 79
| 550
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/DuplicateArtifactAttachmentException.java
|
DuplicateArtifactAttachmentException
|
constructMessage
|
class DuplicateArtifactAttachmentException extends RuntimeException {
private static final String DEFAULT_MESSAGE = "Duplicate artifact attachment detected.";
private Artifact artifact;
private final MavenProject project;
public DuplicateArtifactAttachmentException(MavenProject project, Artifact artifact) {
super(constructMessage(project, artifact));
this.project = project;
this.artifact = artifact;
}
private static String constructMessage(MavenProject project, Artifact artifact) {<FILL_FUNCTION_BODY>}
public MavenProject getProject() {
return project;
}
public Artifact getArtifact() {
return artifact;
}
}
|
return DEFAULT_MESSAGE + " (project: " + project.getId() + "; illegal attachment: " + artifact.getId() + ")";
| 175
| 36
| 211
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptor.java
|
ExtensionDescriptor
|
setExportedPackages
|
class ExtensionDescriptor {
private List<String> exportedPackages;
private List<String> exportedArtifacts;
ExtensionDescriptor() {
// hide constructor
}
public List<String> getExportedPackages() {
if (exportedPackages == null) {
exportedPackages = new ArrayList<>();
}
return exportedPackages;
}
public void setExportedPackages(List<String> exportedPackages) {<FILL_FUNCTION_BODY>}
public List<String> getExportedArtifacts() {
if (exportedArtifacts == null) {
exportedArtifacts = new ArrayList<>();
}
return exportedArtifacts;
}
public void setExportedArtifacts(List<String> exportedArtifacts) {
if (exportedArtifacts == null) {
this.exportedArtifacts = null;
} else {
this.exportedArtifacts = new ArrayList<>(exportedArtifacts);
}
}
}
|
if (exportedPackages == null) {
this.exportedPackages = null;
} else {
this.exportedPackages = new ArrayList<>(exportedPackages);
}
| 271
| 52
| 323
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptorBuilder.java
|
ExtensionDescriptorBuilder
|
build
|
class ExtensionDescriptorBuilder {
/**
* @since 3.3.0
*/
public String getExtensionDescriptorLocation() {
return "META-INF/maven/extension.xml";
}
/**
* Extracts the extension descriptor (if any) from the specified JAR file.
*
* @param extensionJar The JAR file or directory to extract the descriptor from, must not be {@code null}.
* @return The extracted descriptor or {@code null} if no descriptor was found.
* @throws IOException If the descriptor is present but could not be parsed.
*/
public ExtensionDescriptor build(File extensionJar) throws IOException {<FILL_FUNCTION_BODY>}
/**
* @since 3.3.0
*/
public ExtensionDescriptor build(InputStream is) throws IOException {
ExtensionDescriptor extensionDescriptor = new ExtensionDescriptor();
XmlNode dom;
try {
XMLStreamReader reader = WstxInputFactory.newFactory().createXMLStreamReader(is);
dom = XmlNodeStaxBuilder.build(reader);
} catch (XMLStreamException e) {
throw new IOException(e.getMessage(), e);
}
if (!"extension".equals(dom.getName())) {
throw new IOException("Unexpected root element \"" + dom.getName() + "\", expected \"extension\"");
}
extensionDescriptor.setExportedPackages(parseStrings(dom.getChild("exportedPackages")));
extensionDescriptor.setExportedArtifacts(parseStrings(dom.getChild("exportedArtifacts")));
return extensionDescriptor;
}
private List<String> parseStrings(XmlNode dom) {
List<String> strings = null;
if (dom != null) {
strings = new ArrayList<>();
for (XmlNode child : dom.getChildren()) {
String string = child.getValue();
if (string != null) {
string = string.trim();
if (!string.isEmpty()) {
strings.add(string);
}
}
}
}
return strings;
}
}
|
ExtensionDescriptor extensionDescriptor = null;
if (extensionJar.isFile()) {
try (JarFile pluginJar = new JarFile(extensionJar, false)) {
ZipEntry pluginDescriptorEntry = pluginJar.getEntry(getExtensionDescriptorLocation());
if (pluginDescriptorEntry != null) {
try (InputStream is = pluginJar.getInputStream(pluginDescriptorEntry)) {
extensionDescriptor = build(is);
}
}
}
} else {
File pluginXml = new File(extensionJar, getExtensionDescriptorLocation());
if (pluginXml.canRead()) {
try (InputStream is = Files.newInputStream(pluginXml.toPath())) {
extensionDescriptor = build(is);
}
}
}
return extensionDescriptor;
| 529
| 197
| 726
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/Graph.java
|
Graph
|
addEdge
|
class Graph {
private enum DfsState {
VISITING,
VISITED
}
final Map<String, Vertex> vertices = new LinkedHashMap<>();
public Vertex getVertex(String id) {
return vertices.get(id);
}
public Collection<Vertex> getVertices() {
return vertices.values();
}
Vertex addVertex(String label) {
return vertices.computeIfAbsent(label, Vertex::new);
}
void addEdge(Vertex from, Vertex to) throws CycleDetectedException {<FILL_FUNCTION_BODY>}
void removeEdge(Vertex from, Vertex to) {
from.children.remove(to);
to.parents.remove(from);
}
List<String> visitAll() {
return visitAll(vertices.values(), new HashMap<>(), new ArrayList<>());
}
List<String> findCycle(Vertex vertex) {
return visitCycle(Collections.singleton(vertex), new HashMap<>(), new LinkedList<>());
}
private static List<String> visitAll(
Collection<Vertex> children, Map<Vertex, DfsState> stateMap, List<String> list) {
for (Vertex v : children) {
DfsState state = stateMap.putIfAbsent(v, DfsState.VISITING);
if (state == null) {
visitAll(v.children, stateMap, list);
stateMap.put(v, DfsState.VISITED);
list.add(v.label);
}
}
return list;
}
private static List<String> visitCycle(
Collection<Vertex> children, Map<Vertex, DfsState> stateMap, LinkedList<String> cycle) {
for (Vertex v : children) {
DfsState state = stateMap.putIfAbsent(v, DfsState.VISITING);
if (state == null) {
cycle.addLast(v.label);
List<String> ret = visitCycle(v.children, stateMap, cycle);
if (ret != null) {
return ret;
}
cycle.removeLast();
stateMap.put(v, DfsState.VISITED);
} else if (state == DfsState.VISITING) {
// we are already visiting this vertex, this mean we have a cycle
int pos = cycle.lastIndexOf(v.label);
List<String> ret = cycle.subList(pos, cycle.size());
ret.add(v.label);
return ret;
}
}
return null;
}
static class Vertex {
final String label;
final List<Vertex> children = new ArrayList<>();
final List<Vertex> parents = new ArrayList<>();
Vertex(String label) {
this.label = label;
}
String getLabel() {
return label;
}
List<Vertex> getChildren() {
return children;
}
List<Vertex> getParents() {
return parents;
}
}
}
|
from.children.add(to);
to.parents.add(from);
List<String> cycle = findCycle(to);
if (cycle != null) {
// remove edge which introduced cycle
removeEdge(from, to);
throw new CycleDetectedException(
"Edge between '" + from.label + "' and '" + to.label + "' introduces to cycle in the graph", cycle);
}
| 791
| 106
| 897
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/InvalidProjectVersionException.java
|
InvalidProjectVersionException
|
formatMessage
|
class InvalidProjectVersionException extends ProjectBuildingException {
private final String locationInPom;
private final String offendingVersion;
public InvalidProjectVersionException(
String projectId,
String locationInPom,
String offendingVersion,
File pomFile,
InvalidVersionSpecificationException cause) {
super(projectId, formatMessage(projectId, locationInPom, offendingVersion, cause), pomFile, cause);
this.locationInPom = locationInPom;
this.offendingVersion = offendingVersion;
}
private static String formatMessage(
String projectId,
String locationInPom,
String offendingVersion,
InvalidVersionSpecificationException cause) {<FILL_FUNCTION_BODY>}
public String getOffendingVersion() {
return offendingVersion;
}
public String getLocationInPom() {
return locationInPom;
}
}
|
return "Invalid version: " + offendingVersion + " found for: " + locationInPom + " in project: " + projectId
+ ". Reason: " + cause.getMessage();
| 236
| 48
| 284
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.String, java.io.File) ,public void <init>(List<org.apache.maven.project.ProjectBuildingResult>) ,public java.io.File getPomFile() ,public java.lang.String getPomLocation() ,public java.lang.String getProjectId() ,public List<org.apache.maven.project.ProjectBuildingResult> getResults() <variables>private java.io.File pomFile,private final non-sealed java.lang.String projectId,private List<org.apache.maven.project.ProjectBuildingResult> results
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingException.java
|
ProjectBuildingException
|
getPomLocation
|
class ProjectBuildingException extends Exception {
private final String projectId;
private File pomFile;
private List<ProjectBuildingResult> results;
public ProjectBuildingException(String projectId, String message, Throwable cause) {
super(createMessage(message, projectId, null), cause);
this.projectId = projectId;
}
/**
* @param projectId
* @param message
* @param pomFile pom file location
*/
public ProjectBuildingException(String projectId, String message, File pomFile) {
super(createMessage(message, projectId, pomFile));
this.projectId = projectId;
this.pomFile = pomFile;
}
/**
* @param projectId
* @param message
* @param pomFile pom file location
* @param cause
*/
protected ProjectBuildingException(String projectId, String message, File pomFile, Throwable cause) {
super(createMessage(message, projectId, pomFile), cause);
this.projectId = projectId;
this.pomFile = pomFile;
}
public ProjectBuildingException(List<ProjectBuildingResult> results) {
super("Some problems were encountered while processing the POMs");
this.projectId = "";
this.results = results;
}
public File getPomFile() {
return pomFile;
}
/**
* @deprecated use {@link #getPomFile()}
*/
@Deprecated
public String getPomLocation() {<FILL_FUNCTION_BODY>}
public String getProjectId() {
return projectId;
}
public List<ProjectBuildingResult> getResults() {
return results;
}
private static String createMessage(String message, String projectId, File pomFile) {
StringBuilder buffer = new StringBuilder(256);
buffer.append(message);
buffer.append(" for project ").append(projectId);
if (pomFile != null) {
buffer.append(" at ").append(pomFile.getAbsolutePath());
}
return buffer.toString();
}
}
|
if (getPomFile() != null) {
return getPomFile().getAbsolutePath();
} else {
return "null";
}
| 556
| 44
| 600
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/ReactorModelPool.java
|
GAKey
|
equals
|
class GAKey {
private final String groupId;
private final String artifactId;
private final int hashCode;
GAKey(String groupId, String artifactId) {
this.groupId = (groupId != null) ? groupId : "";
this.artifactId = (artifactId != null) ? artifactId : "";
hashCode = Objects.hash(this.groupId, this.artifactId);
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return hashCode;
}
@Override
public String toString() {
return groupId + ':' + artifactId;
}
}
|
if (this == obj) {
return true;
}
if (!(obj instanceof GAKey)) {
return false;
}
GAKey that = (GAKey) obj;
return artifactId.equals(that.artifactId) && groupId.equals(that.groupId);
| 183
| 73
| 256
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/artifact/DefaultProjectArtifactsCache.java
|
CacheKey
|
put
|
class CacheKey implements Key {
private final String groupId;
private final String artifactId;
private final String version;
private final Set<String> dependencyArtifacts;
private final WorkspaceRepository workspace;
private final LocalRepository localRepo;
private final List<RemoteRepository> repositories;
private final Set<String> collect;
private final Set<String> resolve;
private boolean aggregating;
private final int hashCode;
public CacheKey(
MavenProject project,
List<RemoteRepository> repositories,
Collection<String> scopesToCollect,
Collection<String> scopesToResolve,
boolean aggregating,
RepositorySystemSession session) {
groupId = project.getGroupId();
artifactId = project.getArtifactId();
version = project.getVersion();
Set<String> deps = new LinkedHashSet<>();
if (project.getDependencyArtifacts() != null) {
for (Artifact dep : project.getDependencyArtifacts()) {
deps.add(dep.toString());
}
}
dependencyArtifacts = Collections.unmodifiableSet(deps);
workspace = RepositoryUtils.getWorkspace(session);
this.localRepo = session.getLocalRepository();
this.repositories = new ArrayList<>(repositories.size());
for (RemoteRepository repository : repositories) {
if (repository.isRepositoryManager()) {
this.repositories.addAll(repository.getMirroredRepositories());
} else {
this.repositories.add(repository);
}
}
collect = scopesToCollect == null
? Collections.emptySet()
: Collections.unmodifiableSet(new HashSet<>(scopesToCollect));
resolve = scopesToResolve == null
? Collections.emptySet()
: Collections.unmodifiableSet(new HashSet<>(scopesToResolve));
this.aggregating = aggregating;
int hash = 17;
hash = hash * 31 + Objects.hashCode(groupId);
hash = hash * 31 + Objects.hashCode(artifactId);
hash = hash * 31 + Objects.hashCode(version);
hash = hash * 31 + Objects.hashCode(dependencyArtifacts);
hash = hash * 31 + Objects.hashCode(workspace);
hash = hash * 31 + Objects.hashCode(localRepo);
hash = hash * 31 + RepositoryUtils.repositoriesHashCode(repositories);
hash = hash * 31 + Objects.hashCode(collect);
hash = hash * 31 + Objects.hashCode(resolve);
hash = hash * 31 + Objects.hashCode(aggregating);
this.hashCode = hash;
}
@Override
public String toString() {
return groupId + ":" + artifactId + ":" + version;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof CacheKey)) {
return false;
}
CacheKey that = (CacheKey) o;
return Objects.equals(groupId, that.groupId)
&& Objects.equals(artifactId, that.artifactId)
&& Objects.equals(version, that.version)
&& Objects.equals(dependencyArtifacts, that.dependencyArtifacts)
&& Objects.equals(workspace, that.workspace)
&& Objects.equals(localRepo, that.localRepo)
&& RepositoryUtils.repositoriesEquals(repositories, that.repositories)
&& Objects.equals(collect, that.collect)
&& Objects.equals(resolve, that.resolve)
&& aggregating == that.aggregating;
}
}
protected final Map<Key, CacheRecord> cache = new ConcurrentHashMap<>();
protected final Map<Key, Key> keys = new ConcurrentHashMap<>();
@Override
public Key createKey(
MavenProject project,
Collection<String> scopesToCollect,
Collection<String> scopesToResolve,
boolean aggregating,
RepositorySystemSession session) {
Key key = new CacheKey(
project,
project.getRemoteProjectRepositories(),
scopesToCollect,
scopesToResolve,
aggregating,
session);
return keys.computeIfAbsent(key, k -> k);
}
@Override
public CacheRecord get(Key key) throws LifecycleExecutionException {
CacheRecord cacheRecord = cache.get(key);
if (cacheRecord != null && cacheRecord.getException() != null) {
throw cacheRecord.getException();
}
return cacheRecord;
}
@Override
public CacheRecord put(Key key, Set<Artifact> projectArtifacts) {<FILL_FUNCTION_BODY>
|
Objects.requireNonNull(projectArtifacts, "projectArtifacts cannot be null");
assertUniqueKey(key);
SetWithResolutionResult artifacts;
if (projectArtifacts instanceof SetWithResolutionResult) {
artifacts = (SetWithResolutionResult) projectArtifacts;
} else if (projectArtifacts instanceof ArtifactsSetWithResult) {
artifacts = new SetWithResolutionResult(
((ArtifactsSetWithResult) projectArtifacts).getResult(), projectArtifacts);
} else {
throw new IllegalArgumentException("projectArtifacts must implement ArtifactsSetWithResult");
}
CacheRecord record = new CacheRecord(artifacts);
cache.put(key, record);
return record;
| 1,289
| 190
| 1,479
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/collector/DefaultProjectsSelector.java
|
DefaultProjectsSelector
|
selectProjects
|
class DefaultProjectsSelector implements ProjectsSelector {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultProjectsSelector.class);
private final ProjectBuilder projectBuilder;
@Inject
public DefaultProjectsSelector(ProjectBuilder projectBuilder) {
this.projectBuilder = projectBuilder;
}
@Override
public List<MavenProject> selectProjects(List<File> files, MavenExecutionRequest request)
throws ProjectBuildingException {<FILL_FUNCTION_BODY>}
}
|
ProjectBuildingRequest projectBuildingRequest = request.getProjectBuildingRequest();
boolean hasProjectSelection = !request.getProjectActivation().isEmpty();
boolean isRecursive = hasProjectSelection || request.isRecursive();
List<ProjectBuildingResult> results = projectBuilder.build(files, isRecursive, projectBuildingRequest);
List<MavenProject> projects = new ArrayList<>(results.size());
boolean problems = false;
for (ProjectBuildingResult result : results) {
projects.add(result.getProject());
if (!result.getProblems().isEmpty() && LOGGER.isWarnEnabled()) {
LOGGER.warn("");
LOGGER.warn(
"Some problems were encountered while building the effective model for '{}'",
result.getProject().getId());
for (ModelProblem problem : result.getProblems()) {
String loc = ModelProblemUtils.formatLocation(problem, result.getProjectId());
LOGGER.warn("{}{}", problem.getMessage(), ((loc != null && !loc.isEmpty()) ? " @ " + loc : ""));
}
problems = true;
}
}
if (problems) {
LOGGER.warn("");
LOGGER.warn("It is highly recommended to fix these problems"
+ " because they threaten the stability of your build.");
LOGGER.warn("");
LOGGER.warn("For this reason, future Maven versions might no"
+ " longer support building such malformed projects.");
LOGGER.warn("");
}
return projects;
| 128
| 387
| 515
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/collector/MultiModuleCollectionStrategy.java
|
MultiModuleCollectionStrategy
|
getMultiModuleProjectPomFile
|
class MultiModuleCollectionStrategy implements ProjectCollectionStrategy {
private static final Logger LOGGER = LoggerFactory.getLogger(MultiModuleCollectionStrategy.class);
private final ModelLocator modelLocator;
private final ProjectsSelector projectsSelector;
@Inject
public MultiModuleCollectionStrategy(ModelLocator modelLocator, ProjectsSelector projectsSelector) {
this.modelLocator = modelLocator;
this.projectsSelector = projectsSelector;
}
@Override
public List<MavenProject> collectProjects(MavenExecutionRequest request) throws ProjectBuildingException {
File moduleProjectPomFile = getMultiModuleProjectPomFile(request);
List<File> files = Collections.singletonList(moduleProjectPomFile.getAbsoluteFile());
try {
List<MavenProject> projects = projectsSelector.selectProjects(files, request);
boolean isRequestedProjectCollected = isRequestedProjectCollected(request, projects);
if (isRequestedProjectCollected) {
return projects;
} else {
LOGGER.debug(
"Multi module project collection failed:{}"
+ "Detected a POM file next to a .mvn directory in a parent directory ({}). "
+ "Maven assumed that POM file to be the parent of the requested project ({}), but it turned "
+ "out that it was not. Another project collection strategy will be executed as result.",
System.lineSeparator(),
moduleProjectPomFile.getAbsolutePath(),
request.getPom().getAbsolutePath());
return Collections.emptyList();
}
} catch (ProjectBuildingException e) {
boolean fallThrough = isModuleOutsideRequestScopeDependingOnPluginModule(request, e);
if (fallThrough) {
LOGGER.debug(
"Multi module project collection failed:{}"
+ "Detected that one of the modules of this multi-module project uses another module as "
+ "plugin extension which still needed to be built. This is not possible within the same "
+ "reactor build. Another project collection strategy will be executed as result.",
System.lineSeparator());
return Collections.emptyList();
}
throw e;
}
}
private File getMultiModuleProjectPomFile(MavenExecutionRequest request) {<FILL_FUNCTION_BODY>}
/**
* multiModuleProjectDirectory in MavenExecutionRequest is not always the parent of the request pom.
* We should always check whether the request pom project is collected.
* The integration tests for MNG-6223 are examples for this scenario.
*
* @return true if the collected projects contain the requested project (for example with -f)
*/
private boolean isRequestedProjectCollected(MavenExecutionRequest request, List<MavenProject> projects) {
return projects.stream().map(MavenProject::getFile).anyMatch(request.getPom()::equals);
}
/**
* This method finds out whether collecting projects failed because of the following scenario:
* - A multi-module project containing a module which is a plugin and another module which depends on it.
* - Just the plugin is being built with the -f <pom> flag.
* - Because of inter-module dependency collection, all projects in the multi-module project are collected.
* - The plugin is not yet installed in a repository.
*
* Therefore the build fails because the plugin is not found and plugins cannot be built in the same session.
*
* The integration test for <a href="https://issues.apache.org/jira/browse/MNG-5572">MNG-5572</a> is an
* example of this scenario.
*
* @return true if the module which fails to collect the inter-module plugin is not part of the build.
*/
private boolean isModuleOutsideRequestScopeDependingOnPluginModule(
MavenExecutionRequest request, ProjectBuildingException exception) {
return exception.getResults().stream()
.map(ProjectBuildingResult::getProject)
.filter(Objects::nonNull)
.filter(project -> request.getPom().equals(project.getFile()))
.findFirst()
.map(requestPomProject -> {
List<MavenProject> modules = requestPomProject.getCollectedProjects() != null
? requestPomProject.getCollectedProjects()
: Collections.emptyList();
List<MavenProject> projectsInRequestScope = new ArrayList<>(modules);
projectsInRequestScope.add(requestPomProject);
Predicate<ProjectBuildingResult> projectsOutsideOfRequestScope =
pr -> !projectsInRequestScope.contains(pr.getProject());
Predicate<Exception> pluginArtifactNotFoundException = exc -> exc instanceof PluginManagerException
&& exc.getCause() instanceof PluginResolutionException
&& exc.getCause().getCause() instanceof ArtifactResolutionException
&& exc.getCause().getCause().getCause() instanceof ArtifactNotFoundException;
Predicate<Plugin> isPluginPartOfRequestScope = plugin -> projectsInRequestScope.stream()
.anyMatch(project -> project.getGroupId().equals(plugin.getGroupId())
&& project.getArtifactId().equals(plugin.getArtifactId())
&& project.getVersion().equals(plugin.getVersion()));
return exception.getResults().stream()
.filter(projectsOutsideOfRequestScope)
.flatMap(projectBuildingResult -> projectBuildingResult.getProblems().stream())
.map(ModelProblem::getException)
.filter(pluginArtifactNotFoundException)
.map(exc -> ((PluginResolutionException) exc.getCause()).getPlugin())
.anyMatch(isPluginPartOfRequestScope);
})
.orElse(false);
}
}
|
File multiModuleProjectDirectory = request.getMultiModuleProjectDirectory();
if (request.getPom().getParentFile().equals(multiModuleProjectDirectory)) {
return request.getPom();
} else {
File multiModuleProjectPom = modelLocator.locateExistingPom(multiModuleProjectDirectory);
if (multiModuleProjectPom == null) {
LOGGER.info(
"Maven detected that the requested POM file is part of a multi-module project, "
+ "but could not find a pom.xml file in the multi-module root directory '{}'.",
multiModuleProjectDirectory);
LOGGER.info(
"The reactor is limited to all projects under: {}",
request.getPom().getParent());
return request.getPom();
}
return multiModuleProjectPom;
}
| 1,438
| 212
| 1,650
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/collector/PomlessCollectionStrategy.java
|
PomlessCollectionStrategy
|
collectProjects
|
class PomlessCollectionStrategy implements ProjectCollectionStrategy {
private final ProjectBuilder projectBuilder;
@Inject
public PomlessCollectionStrategy(ProjectBuilder projectBuilder) {
this.projectBuilder = projectBuilder;
}
@Override
public List<MavenProject> collectProjects(final MavenExecutionRequest request) throws ProjectBuildingException {<FILL_FUNCTION_BODY>}
}
|
ProjectBuildingRequest buildingRequest = request.getProjectBuildingRequest();
ModelSource modelSource = new UrlModelSource(DefaultMaven.class.getResource("project/standalone.xml"));
MavenProject project =
projectBuilder.build(modelSource, buildingRequest).getProject();
project.setExecutionRoot(true);
request.setProjectPresent(false);
return Arrays.asList(project);
| 97
| 102
| 199
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/properties/internal/EnvironmentUtils.java
|
EnvironmentUtils
|
addEnvVars
|
class EnvironmentUtils {
private static Properties envVars;
/**
* Adds the environment variables in the form of properties whose keys are prefixed with {@code env.}, e.g. {@code
* env.PATH}. Unlike native environment variables, properties are always case-sensitive. For the sake of
* determinism, the environment variable names will be normalized to upper case on platforms with case-insensitive
* variable lookup.
*
* @param props The properties to add the environment variables to, may be {@code null}.
*/
public static void addEnvVars(Properties props) {<FILL_FUNCTION_BODY>}
}
|
if (props != null) {
if (envVars == null) {
Properties tmp = new Properties();
boolean caseSensitive = !Os.IS_WINDOWS;
for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
String key = "env."
+ (caseSensitive ? entry.getKey() : entry.getKey().toUpperCase(Locale.ENGLISH));
tmp.setProperty(key, entry.getValue());
}
envVars = tmp;
}
props.putAll(envVars);
}
| 157
| 153
| 310
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/properties/internal/SystemProperties.java
|
SystemProperties
|
copyProperties
|
class SystemProperties {
/**
* Thread-safe System.properties copy implementation.
*/
public static void addSystemProperties(Properties props) {
props.putAll(getSystemProperties());
}
/**
* Returns a copy of {@link System#getProperties()} in a thread-safe manner.
*
* @return {@link System#getProperties()} obtained in a thread-safe manner.
*/
public static Properties getSystemProperties() {
return copyProperties(System.getProperties());
}
/**
* Copies the given {@link Properties} object into a new {@link Properties} object, in a thread-safe manner.
* @param properties Properties to copy.
* @return Copy of the given properties.
*/
public static Properties copyProperties(Properties properties) {<FILL_FUNCTION_BODY>}
}
|
final Properties copyProperties = new Properties();
// guard against modification/removal of keys in the given properties (MNG-5670, MNG-6053, MNG-6105)
synchronized (properties) {
copyProperties.putAll(properties);
}
return copyProperties;
| 209
| 80
| 289
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/resolver/MavenChainedWorkspaceReader.java
|
Key
|
of
|
class Key {
private final List<Object> keys;
private final String type;
Key(Collection<WorkspaceReader> readers) {
keys = readers.stream().map(r -> r.getRepository().getKey()).collect(Collectors.toList());
type = readers.stream().map(r -> r.getRepository().getContentType()).collect(Collectors.joining("+"));
}
public String getContentType() {
return type;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else {
return obj != null && this.getClass().equals(obj.getClass()) && this.keys.equals(((Key) obj).keys);
}
}
public int hashCode() {
return this.keys.hashCode();
}
}
/**
* chains a collection of {@link WorkspaceReader}s
* @param workspaceReaderCollection the collection of readers, might be empty but never <code>null</code>
* @return if the collection contains only one item returns the single item, otherwise creates a new
* {@link MavenChainedWorkspaceReader} chaining all readers in the order of the given collection.
*/
public static WorkspaceReader of(Collection<WorkspaceReader> workspaceReaderCollection) {<FILL_FUNCTION_BODY>
|
WorkspaceReader[] readers = workspaceReaderCollection.toArray(new WorkspaceReader[0]);
if (readers.length == 1) {
return readers[0];
}
return new MavenChainedWorkspaceReader(readers);
| 339
| 63
| 402
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformation.java
|
DefaultRuntimeInformation
|
isMavenVersion
|
class DefaultRuntimeInformation implements RuntimeInformation {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final VersionScheme versionScheme;
private final String mavenVersion;
@Inject
public DefaultRuntimeInformation(VersionScheme versionScheme) {
this.versionScheme = versionScheme;
this.mavenVersion = loadMavenVersion();
}
@Override
public String getMavenVersion() {
return mavenVersion;
}
private String loadMavenVersion() {
Properties props = new Properties();
String resource = "META-INF/maven/org.apache.maven/maven-core/pom.properties";
try (InputStream is = DefaultRuntimeInformation.class.getResourceAsStream("/" + resource)) {
if (is != null) {
props.load(is);
} else {
logger.warn("Could not locate " + resource + " on classpath, Maven runtime information not available");
}
} catch (IOException e) {
String msg = "Could not parse " + resource + ", Maven runtime information not available";
if (logger.isDebugEnabled()) {
logger.warn(msg, e);
} else {
logger.warn(msg);
}
}
String version = props.getProperty("version", "").trim();
if (!version.startsWith("${")) {
return version;
} else {
return "";
}
}
@Override
public boolean isMavenVersion(String versionRange) {<FILL_FUNCTION_BODY>}
}
|
if (Objects.requireNonNull(versionRange, "versionRange cannot be null").isEmpty()) {
throw new IllegalArgumentException("versionRange cannot be empty");
}
VersionConstraint constraint;
try {
constraint = versionScheme.parseVersionConstraint(versionRange);
} catch (InvalidVersionSpecificationException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
Version current;
try {
String mavenVersion = getMavenVersion();
if (mavenVersion.isEmpty()) {
throw new IllegalArgumentException("Could not determine current Maven version");
}
current = versionScheme.parseVersion(mavenVersion);
} catch (InvalidVersionSpecificationException e) {
throw new IllegalStateException("Could not parse current Maven version: " + e.getMessage(), e);
}
if (constraint.getRange() == null) {
return constraint.getVersion().compareTo(current) <= 0;
}
return constraint.containsVersion(current);
| 401
| 245
| 646
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScope.java
|
CachingProvider
|
get
|
class CachingProvider<T> implements Provider<T> {
private final Provider<T> provider;
private volatile T value;
CachingProvider(Provider<T> provider) {
this.provider = provider;
}
public T value() {
return value;
}
@Override
public T get() {<FILL_FUNCTION_BODY>}
}
|
if (value == null) {
synchronized (this) {
if (value == null) {
value = provider.get();
}
}
}
return value;
| 101
| 51
| 152
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScopeModule.java
|
SessionScopeModule
|
configure
|
class SessionScopeModule extends AbstractModule {
private final SessionScope scope;
@Inject
public SessionScopeModule() {
this(new SessionScope());
}
public SessionScopeModule(SessionScope scope) {
this.scope = scope;
}
@Override
protected void configure() {<FILL_FUNCTION_BODY>}
}
|
bindScope(SessionScoped.class, scope);
// bindScope(org.apache.maven.api.di.SessionScoped.class, scope);
bind(SessionScope.class).toInstance(scope);
bind(MavenSession.class)
.toProvider(SessionScope.seededKeyProvider(MavenSession.class))
.in(scope);
bind(Session.class)
.toProvider(SessionScope.seededKeyProvider(Session.class))
.in(scope);
bind(InternalMavenSession.class)
.toProvider(SessionScope.seededKeyProvider(InternalMavenSession.class))
.in(scope);
| 92
| 164
| 256
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/settings/SettingsUtils.java
|
SettingsUtils
|
merge
|
class SettingsUtils {
private SettingsUtils() {
// don't allow construction.
}
/**
* @param dominant
* @param recessive
* @param recessiveSourceLevel
*/
public static void merge(Settings dominant, Settings recessive, String recessiveSourceLevel) {<FILL_FUNCTION_BODY>}
/**
* @param modelProfile
* @return a profile
*/
public static Profile convertToSettingsProfile(org.apache.maven.model.Profile modelProfile) {
return new Profile(SettingsUtilsV4.convertToSettingsProfile(modelProfile.getDelegate()));
}
/**
* @param settingsProfile
* @return a profile
*/
public static org.apache.maven.model.Profile convertFromSettingsProfile(Profile settingsProfile) {
return new org.apache.maven.model.Profile(
SettingsUtilsV4.convertFromSettingsProfile(settingsProfile.getDelegate()));
}
/**
* @param settings could be null
* @return a new instance of settings or null if settings was null.
*/
public static Settings copySettings(Settings settings) {
if (settings == null) {
return null;
}
return new Settings(settings.getDelegate());
}
}
|
if (dominant != null && recessive != null) {
dominant.delegate = SettingsUtilsV4.merge(dominant.getDelegate(), recessive.getDelegate());
}
| 318
| 54
| 372
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchain.java
|
DefaultToolchain
|
toString
|
class DefaultToolchain // should have been AbstractToolchain...
implements Toolchain, ToolchainPrivate {
private final Logger logger;
private String type;
private Map<String, RequirementMatcher> provides = new HashMap<>();
public static final String KEY_TYPE = "type"; // NOI18N
private ToolchainModel model;
/**
*
* @param model the model, must not be {@code null}
* @param logger the logger, must not be {@code null}
*/
protected DefaultToolchain(ToolchainModel model, Logger logger) {
this.model = model;
this.logger = logger;
}
/**
*
* @param model the model, must not be {@code null}
* @param type the type
* @param logger the logger, must not be {@code null}
*/
protected DefaultToolchain(ToolchainModel model, String type, Logger logger) {
this(model, logger);
this.type = type;
}
@Override
public final String getType() {
return type != null ? type : model.getType();
}
@Override
public final ToolchainModel getModel() {
return model;
}
public final void addProvideToken(String type, RequirementMatcher matcher) {
provides.put(type, matcher);
}
@Override
public boolean matchesRequirements(Map<String, String> requirements) {
for (Map.Entry<String, String> requirement : requirements.entrySet()) {
String key = requirement.getKey();
RequirementMatcher matcher = provides.get(key);
if (matcher == null) {
getLog().debug("Toolchain {} is missing required property: {}", this, key);
return false;
}
if (!matcher.matches(requirement.getValue())) {
getLog().debug("Toolchain {} doesn't match required property: {}", this, key);
return false;
}
}
return true;
}
protected Logger getLog() {
return logger;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
if (!(obj instanceof DefaultToolchain)) {
return false;
}
DefaultToolchain other = (DefaultToolchain) obj;
if (!Objects.equals(type, other.type)) {
return false;
}
Properties thisProvides = this.getModel().getProvides();
Properties otherProvides = other.getModel().getProvides();
return Objects.equals(thisProvides, otherProvides);
}
@Override
public int hashCode() {
int hashCode = (type == null) ? 0 : type.hashCode();
if (this.getModel().getProvides() != null) {
hashCode = 31 * hashCode + this.getModel().getProvides().hashCode();
}
return hashCode;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder builder = new StringBuilder();
builder.append("type:").append(getType());
builder.append('{');
Iterator<Map.Entry<String, RequirementMatcher>> providesIter =
provides.entrySet().iterator();
while (providesIter.hasNext()) {
Map.Entry<String, RequirementMatcher> provideEntry = providesIter.next();
builder.append(provideEntry.getKey()).append(" = ").append(provideEntry.getValue());
if (providesIter.hasNext()) {
builder.append(';');
}
}
builder.append('}');
return builder.toString();
| 810
| 168
| 978
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManager.java
|
DefaultToolchainManager
|
getToolchainFromBuildContext
|
class DefaultToolchainManager implements ToolchainManager {
protected final Logger logger; // TODO this class is extended, needs refactoring
final Map<String, ToolchainFactory> factories;
@Inject
public DefaultToolchainManager(Map<String, ToolchainFactory> factories) {
this.factories = factories;
this.logger = LoggerFactory.getLogger(DefaultToolchainManager.class);
}
/**
* Ctor needed for UT.
*/
DefaultToolchainManager(Map<String, ToolchainFactory> factories, Logger logger) {
this.factories = factories;
this.logger = requireNonNull(logger);
}
@Override
public Toolchain getToolchainFromBuildContext(String type, MavenSession session) {<FILL_FUNCTION_BODY>}
@Override
public List<Toolchain> getToolchains(MavenSession session, String type, Map<String, String> requirements) {
List<ToolchainModel> models = session.getRequest().getToolchains().get(type);
return selectToolchains(models, type, requirements);
}
private List<Toolchain> selectToolchains(
List<ToolchainModel> models, String type, Map<String, String> requirements) {
List<Toolchain> toolchains = new ArrayList<>();
if (models != null) {
ToolchainFactory fact = factories.get(type);
if (fact == null) {
logger.error(
"Missing toolchain factory for type: " + type + ". Possibly caused by misconfigured project.");
} else {
for (ToolchainModel model : models) {
try {
ToolchainPrivate toolchain = fact.createToolchain(model);
if (requirements == null || toolchain.matchesRequirements(requirements)) {
toolchains.add(toolchain);
}
} catch (MisconfiguredToolchainException ex) {
logger.error("Misconfigured toolchain.", ex);
}
}
}
}
return toolchains;
}
Map<String, Object> retrieveContext(MavenSession session) {
Map<String, Object> context = null;
if (session != null) {
PluginDescriptor desc = new PluginDescriptor();
desc.setGroupId(PluginDescriptor.getDefaultPluginGroupId());
desc.setArtifactId(PluginDescriptor.getDefaultPluginArtifactId("toolchains"));
MavenProject current = session.getCurrentProject();
if (current != null) {
// TODO why is this using the context
context = session.getPluginContext(desc, current);
}
}
return (context != null) ? context : new HashMap<>();
}
public static final String getStorageKey(String type) {
return "toolchain-" + type; // NOI18N
}
}
|
Map<String, Object> context = retrieveContext(session);
ToolchainModel model = (ToolchainModel) context.get(getStorageKey(type));
if (model != null) {
List<Toolchain> toolchains = selectToolchains(Collections.singletonList(model), type, null);
if (!toolchains.isEmpty()) {
return toolchains.get(0);
}
}
return null;
| 730
| 115
| 845
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivate.java
|
DefaultToolchainManagerPrivate
|
getToolchainsForType
|
class DefaultToolchainManagerPrivate extends DefaultToolchainManager implements ToolchainManagerPrivate {
@Inject
public DefaultToolchainManagerPrivate(Map<String, ToolchainFactory> factories) {
super(factories);
}
/**
* Ctor needed for UT.
*/
DefaultToolchainManagerPrivate(Map<String, ToolchainFactory> factories, Logger logger) {
super(factories, logger);
}
@Override
public ToolchainPrivate[] getToolchainsForType(String type, MavenSession session)
throws MisconfiguredToolchainException {<FILL_FUNCTION_BODY>}
@Override
public void storeToolchainToBuildContext(ToolchainPrivate toolchain, MavenSession session) {
Map<String, Object> context = retrieveContext(session);
context.put(getStorageKey(toolchain.getType()), toolchain.getModel());
}
}
|
List<ToolchainPrivate> toRet = new ArrayList<>();
ToolchainFactory fact = factories.get(type);
if (fact == null) {
logger.error("Missing toolchain factory for type: " + type + ". Possibly caused by misconfigured project.");
} else {
List<ToolchainModel> availableToolchains =
org.apache.maven.toolchain.model.ToolchainModel.toolchainModelToApiV4(
session.getRequest().getToolchains().get(type));
if (availableToolchains != null) {
for (ToolchainModel toolchainModel : availableToolchains) {
org.apache.maven.toolchain.model.ToolchainModel tm =
new org.apache.maven.toolchain.model.ToolchainModel(toolchainModel);
toRet.add(fact.createToolchain(tm));
}
}
// add default toolchain
ToolchainPrivate tool = fact.createDefaultToolchain();
if (tool != null) {
toRet.add(tool);
}
}
return toRet.toArray(new ToolchainPrivate[0]);
| 227
| 286
| 513
|
<methods>public void <init>(Map<java.lang.String,org.apache.maven.toolchain.ToolchainFactory>) ,public static final java.lang.String getStorageKey(java.lang.String) ,public org.apache.maven.toolchain.Toolchain getToolchainFromBuildContext(java.lang.String, org.apache.maven.execution.MavenSession) ,public List<org.apache.maven.toolchain.Toolchain> getToolchains(org.apache.maven.execution.MavenSession, java.lang.String, Map<java.lang.String,java.lang.String>) <variables>final non-sealed Map<java.lang.String,org.apache.maven.toolchain.ToolchainFactory> factories,protected final non-sealed Logger logger
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/toolchain/RequirementMatcherFactory.java
|
VersionMatcher
|
matches
|
class VersionMatcher implements RequirementMatcher {
DefaultArtifactVersion version;
private VersionMatcher(String version) {
this.version = new DefaultArtifactVersion(version);
}
@Override
public boolean matches(String requirement) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return version.toString();
}
}
|
try {
VersionRange range = VersionRange.createFromVersionSpec(requirement);
if (range.hasRestrictions()) {
return range.containsVersion(version);
} else {
return range.getRecommendedVersion().compareTo(version) == 0;
}
} catch (InvalidVersionSpecificationException ex) {
return false;
}
| 102
| 93
| 195
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchainFactory.java
|
JavaToolchainFactory
|
createToolchain
|
class JavaToolchainFactory implements ToolchainFactory {
private final Logger logger = LoggerFactory.getLogger(getClass());
public ToolchainPrivate createToolchain(ToolchainModel model) throws MisconfiguredToolchainException {<FILL_FUNCTION_BODY>}
public ToolchainPrivate createDefaultToolchain() {
// not sure it's necessary to provide a default toolchain here.
// only version can be eventually supplied, and
return null;
}
protected Logger getLogger() {
return logger;
}
}
|
if (model == null) {
return null;
}
// use DefaultJavaToolChain for compatibility with maven 3.2.3 and earlier
@SuppressWarnings("deprecation")
JavaToolchainImpl jtc = new DefaultJavaToolChain(model, logger);
// populate the provides section
Properties provides = model.getProvides();
for (Entry<Object, Object> provide : provides.entrySet()) {
String key = (String) provide.getKey();
String value = (String) provide.getValue();
if (value == null) {
throw new MisconfiguredToolchainException(
"Provides token '" + key + "' doesn't have any value configured.");
}
RequirementMatcher matcher;
if ("version".equals(key)) {
matcher = RequirementMatcherFactory.createVersionMatcher(value);
} else {
matcher = RequirementMatcherFactory.createExactMatcher(value);
}
jtc.addProvideToken(key, matcher);
}
// populate the configuration section
Xpp3Dom dom = (Xpp3Dom) model.getConfiguration();
Xpp3Dom javahome = dom != null ? dom.getChild(JavaToolchainImpl.KEY_JAVAHOME) : null;
if (javahome == null) {
throw new MisconfiguredToolchainException(
"Java toolchain without the " + JavaToolchainImpl.KEY_JAVAHOME + " configuration element.");
}
Path normal = Paths.get(javahome.getValue()).normalize();
if (Files.exists(normal)) {
jtc.setJavaHome(Paths.get(javahome.getValue()).normalize().toString());
} else {
throw new MisconfiguredToolchainException(
"Non-existing JDK home configuration at " + normal.toAbsolutePath());
}
return jtc;
| 135
| 484
| 619
|
<no_super_class>
|
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/toolchain/java/JavaToolchainImpl.java
|
JavaToolchainImpl
|
findTool
|
class JavaToolchainImpl extends DefaultToolchain implements JavaToolchain {
private String javaHome;
public static final String KEY_JAVAHOME = "jdkHome"; // NOI18N
JavaToolchainImpl(ToolchainModel model, Logger logger) {
super(model, "jdk", logger);
}
public String getJavaHome() {
return javaHome;
}
public void setJavaHome(String javaHome) {
this.javaHome = javaHome;
}
public String toString() {
return "JDK[" + getJavaHome() + "]";
}
public String findTool(String toolName) {
Path toRet = findTool(toolName, Paths.get(getJavaHome()).normalize());
if (toRet != null) {
return toRet.toAbsolutePath().toString();
}
return null;
}
private static Path findTool(String toolName, Path installDir) {<FILL_FUNCTION_BODY>}
}
|
Path bin = installDir.resolve("bin"); // NOI18N
if (Files.isDirectory(bin)) {
if (Os.IS_WINDOWS) {
Path tool = bin.resolve(toolName + ".exe");
if (Files.exists(tool)) {
return tool;
}
}
Path tool = bin.resolve(toolName);
if (Files.exists(tool)) {
return tool;
}
}
return null;
| 256
| 123
| 379
|
<methods>public final void addProvideToken(java.lang.String, org.apache.maven.toolchain.RequirementMatcher) ,public boolean equals(java.lang.Object) ,public final ToolchainModel getModel() ,public final java.lang.String getType() ,public int hashCode() ,public boolean matchesRequirements(Map<java.lang.String,java.lang.String>) ,public java.lang.String toString() <variables>public static final java.lang.String KEY_TYPE,private final non-sealed Logger logger,private ToolchainModel model,private Map<java.lang.String,org.apache.maven.toolchain.RequirementMatcher> provides,private java.lang.String type
|
apache_maven
|
maven/maven-di/src/main/java/org/apache/maven/di/Key.java
|
KeyImpl
|
equals
|
class KeyImpl<T> extends Key<T> {
KeyImpl(Type type, Object qualifier) {
super(type, qualifier);
}
}
public static <T> Key<T> of(Class<T> type) {
return new KeyImpl<>(type, null);
}
public static <T> Key<T> of(Class<T> type, @Nullable Object qualifier) {
return new KeyImpl<>(type, qualifier);
}
public static <T> Key<T> ofType(Type type) {
return new KeyImpl<>(type, null);
}
public static <T> Key<T> ofType(Type type, @Nullable Object qualifier) {
return new KeyImpl<>(type, qualifier);
}
private Type getTypeParameter() {
// this cannot possibly fail so not even a check here
Type typeArgument = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
Object outerInstance = ReflectionUtils.getOuterClassInstance(this);
// // the outer instance is null in static context
return outerInstance != null
? Types.bind(typeArgument, Types.getAllTypeBindings(outerInstance.getClass()))
: typeArgument;
}
public Type getType() {
return type;
}
/**
* A shortcut for <code>{@link Types#getRawType(Type)}(key.getType())</code>.
* Also casts the result to a properly parameterized class.
*/
@SuppressWarnings("unchecked")
public Class<T> getRawType() {
return (Class<T>) Types.getRawType(type);
}
/**
* Returns a type parameter of the underlying type wrapped as a key with no qualifier.
*
* @throws IllegalStateException when underlying type is not a parameterized one.
*/
public <U> Key<U> getTypeParameter(int index) {
if (type instanceof ParameterizedType) {
return new KeyImpl<>(((ParameterizedType) type).getActualTypeArguments()[index], null);
}
throw new IllegalStateException("Expected type from key " + getDisplayString() + " to be parameterized");
}
public @Nullable Object getQualifier() {
return qualifier;
}
/**
* Returns an underlying type with display string formatting (package names stripped)
* and prepended qualifier display string if this key has a qualifier.
*/
public String getDisplayString() {
return (qualifier != null ? Utils.getDisplayString(qualifier) + " " : "")
+ ReflectionUtils.getDisplayName(type);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>
|
if (this == o) {
return true;
}
if (!(o instanceof Key<?>)) {
return false;
}
Key<?> that = (Key<?>) o;
return type.equals(that.type) && Objects.equals(qualifier, that.qualifier);
| 711
| 82
| 793
|
<no_super_class>
|
apache_maven
|
maven/maven-di/src/main/java/org/apache/maven/di/impl/Binding.java
|
BindingToConstructor
|
compile
|
class BindingToConstructor<T> extends Binding<T> {
final TupleConstructorN<T> constructor;
final Key<?>[] args;
BindingToConstructor(
Key<? extends T> key, TupleConstructorN<T> constructor, Key<?>[] dependencies, int priority) {
super(key, new HashSet<>(Arrays.asList(dependencies)), null, priority);
this.constructor = constructor;
this.args = dependencies;
}
@Override
public Supplier<T> compile(Function<Key<?>, Supplier<?>> compiler) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "BindingToConstructor[" + constructor + "]" + getDependencies();
}
}
|
return () -> {
Object[] args =
Stream.of(this.args).map(compiler).map(Supplier::get).toArray();
return constructor.create(args);
};
| 198
| 52
| 250
|
<no_super_class>
|
apache_maven
|
maven/maven-di/src/main/java/org/apache/maven/di/impl/BindingInitializer.java
|
BindingInitializer
|
combine
|
class BindingInitializer<T> {
private final Set<Key<?>> dependencies;
protected BindingInitializer(Set<Key<?>> dependencies) {
this.dependencies = dependencies;
}
public Set<Key<?>> getDependencies() {
return dependencies;
}
public abstract Consumer<T> compile(Function<Key<?>, Supplier<?>> compiler);
public static <T> BindingInitializer<T> combine(List<BindingInitializer<T>> bindingInitializers) {<FILL_FUNCTION_BODY>}
}
|
Set<Key<?>> deps = bindingInitializers.stream()
.map(BindingInitializer::getDependencies)
.flatMap(Collection::stream)
.collect(toSet());
return new BindingInitializer<T>(deps) {
@Override
public Consumer<T> compile(Function<Key<?>, Supplier<?>> compiler) {
return instance -> bindingInitializers.stream()
.map(bindingInitializer -> bindingInitializer.compile(compiler))
.forEach(i -> i.accept(instance));
}
};
| 146
| 146
| 292
|
<no_super_class>
|
apache_maven
|
maven/maven-di/src/main/java/org/apache/maven/di/impl/Utils.java
|
Utils
|
getDisplayString
|
class Utils {
public static String getDisplayString(Class<? extends Annotation> annotationType, @Nullable Annotation annotation) {<FILL_FUNCTION_BODY>}
public static String getDisplayString(Object object) {
if (object instanceof Class && ((Class<?>) object).isAnnotation()) {
//noinspection unchecked
return getDisplayString((Class<? extends Annotation>) object, null);
}
if (object instanceof Annotation) {
Annotation annotation = (Annotation) object;
return getDisplayString(annotation.annotationType(), annotation);
}
return object.toString();
}
public static boolean isMarker(Class<? extends Annotation> annotationType) {
return annotationType.getDeclaredMethods().length == 0;
}
}
|
if (annotation == null) {
return "@" + ReflectionUtils.getDisplayName(annotationType);
}
String typeName = annotationType.getName();
String str = annotation.toString();
return str.startsWith("@" + typeName)
? "@" + ReflectionUtils.getDisplayName(annotationType) + str.substring(typeName.length() + 1)
: str;
| 196
| 105
| 301
|
<no_super_class>
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/CLIReportingUtils.java
|
CLIReportingUtils
|
showVersion
|
class CLIReportingUtils {
// CHECKSTYLE_OFF: MagicNumber
public static final long MB = 1024 * 1024;
private static final long ONE_SECOND = 1000L;
private static final long ONE_MINUTE = 60 * ONE_SECOND;
private static final long ONE_HOUR = 60 * ONE_MINUTE;
private static final long ONE_DAY = 24 * ONE_HOUR;
// CHECKSTYLE_ON: MagicNumber
public static final String BUILD_VERSION_PROPERTY = "version";
public static String showVersion() {<FILL_FUNCTION_BODY>}
public static String showVersionMinimal() {
Properties properties = getBuildProperties();
String version = reduce(properties.getProperty(BUILD_VERSION_PROPERTY));
return (version != null ? version : "<version unknown>");
}
/**
* Create a human-readable string containing the Maven version, buildnumber, and time of build
*
* @param buildProperties The build properties
* @return Readable build info
*/
static String createMavenVersionString(Properties buildProperties) {
String timestamp = reduce(buildProperties.getProperty("timestamp"));
String version = reduce(buildProperties.getProperty(BUILD_VERSION_PROPERTY));
String rev = reduce(buildProperties.getProperty("buildNumber"));
String distributionName = reduce(buildProperties.getProperty("distributionName"));
String msg = distributionName + " ";
msg += (version != null ? version : "<version unknown>");
if (rev != null || timestamp != null) {
msg += " (";
msg += (rev != null ? rev : "");
if (timestamp != null && !timestamp.isEmpty()) {
String ts = formatTimestamp(Long.parseLong(timestamp));
msg += (rev != null ? "; " : "") + ts;
}
msg += ")";
}
return msg;
}
private static String reduce(String s) {
return (s != null ? (s.startsWith("${") && s.endsWith("}") ? null : s) : null);
}
static Properties getBuildProperties() {
Properties properties = new Properties();
try (InputStream resourceAsStream =
MavenCli.class.getResourceAsStream("/org/apache/maven/messages/build.properties")) {
if (resourceAsStream != null) {
properties.load(resourceAsStream);
}
} catch (IOException e) {
System.err.println("Unable determine version from JAR file: " + e.getMessage());
}
return properties;
}
public static void showError(Logger logger, String message, Throwable e, boolean showStackTrace) {
if (logger == null) {
System.err.println(message);
if (showStackTrace && e != null) {
e.printStackTrace(System.err);
}
return;
}
if (showStackTrace) {
logger.error(message, e);
} else {
logger.error(message);
if (e != null) {
logger.error(e.getMessage());
for (Throwable cause = e.getCause();
cause != null && cause != cause.getCause();
cause = cause.getCause()) {
logger.error("Caused by: {}", cause.getMessage());
}
}
}
}
public static String formatTimestamp(long timestamp) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
return sdf.format(new Date(timestamp));
}
public static String formatDuration(long duration) {
// CHECKSTYLE_OFF: MagicNumber
long ms = duration % 1000;
long s = (duration / ONE_SECOND) % 60;
long m = (duration / ONE_MINUTE) % 60;
long h = (duration / ONE_HOUR) % 24;
long d = duration / ONE_DAY;
// CHECKSTYLE_ON: MagicNumber
String format;
if (d > 0) {
// Length 11+ chars
format = "%d d %02d:%02d h";
} else if (h > 0) {
// Length 7 chars
format = "%2$02d:%3$02d h";
} else if (m > 0) {
// Length 9 chars
format = "%3$02d:%4$02d min";
} else {
// Length 7-8 chars
format = "%4$d.%5$03d s";
}
return String.format(format, d, h, m, s, ms);
}
}
|
final String ls = System.lineSeparator();
Properties properties = getBuildProperties();
StringBuilder version = new StringBuilder(256);
version.append(MessageUtils.builder().strong(createMavenVersionString(properties)))
.append(ls);
version.append(reduce(properties.getProperty("distributionShortName") + " home: "
+ System.getProperty("maven.home", "<unknown Maven " + "home>")))
.append(ls);
version.append("Java version: ")
.append(System.getProperty("java.version", "<unknown Java version>"))
.append(", vendor: ")
.append(System.getProperty("java.vendor", "<unknown vendor>"))
.append(", runtime: ")
.append(System.getProperty("java.home", "<unknown runtime>"))
.append(ls);
version.append("Default locale: ")
.append(Locale.getDefault())
.append(", platform encoding: ")
.append(System.getProperty("file.encoding", "<unknown encoding>"))
.append(ls);
version.append("OS name: \"")
.append(Os.OS_NAME)
.append("\", version: \"")
.append(Os.OS_VERSION)
.append("\", arch: \"")
.append(Os.OS_ARCH)
.append("\", family: \"")
.append(Os.OS_FAMILY)
.append('\"');
return version.toString();
| 1,253
| 376
| 1,629
|
<no_super_class>
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/CleanArgument.java
|
CleanArgument
|
cleanArgs
|
class CleanArgument {
public static String[] cleanArgs(String[] args) {<FILL_FUNCTION_BODY>}
}
|
List<String> cleaned = new ArrayList<>();
StringBuilder currentArg = null;
for (String arg : args) {
boolean addedToBuffer = false;
if (arg.startsWith("\"")) {
// if we're in the process of building up another arg, push it and start over.
// this is for the case: "-Dfoo=bar "-Dfoo2=bar two" (note the first unterminated quote)
if (currentArg != null) {
cleaned.add(currentArg.toString());
}
// start building an argument here.
currentArg = new StringBuilder(arg.substring(1));
addedToBuffer = true;
}
// this has to be a separate "if" statement, to capture the case of: "-Dfoo=bar"
if (addedToBuffer && arg.endsWith("\"")) {
String cleanArgPart = arg.substring(0, arg.length() - 1);
// if we're building an argument, keep doing so.
if (currentArg != null) {
// if this is the case of "-Dfoo=bar", then we need to adjust the buffer.
if (addedToBuffer) {
currentArg.setLength(currentArg.length() - 1);
}
// otherwise, we trim the trailing " and append to the buffer.
else {
// TODO introducing a space here...not sure what else to do but collapse whitespace
currentArg.append(' ').append(cleanArgPart);
}
cleaned.add(currentArg.toString());
} else {
cleaned.add(cleanArgPart);
}
currentArg = null;
addedToBuffer = false;
continue;
}
// if we haven't added this arg to the buffer, and we ARE building an argument
// buffer, then append it with a preceding space...again, not sure what else to
// do other than collapse whitespace.
// NOTE: The case of a trailing quote is handled by nullifying the arg buffer.
if (!addedToBuffer) {
if (currentArg != null) {
currentArg.append(' ').append(arg);
} else {
cleaned.add(arg);
}
}
}
if (currentArg != null) {
cleaned.add(currentArg.toString());
}
int cleanedSz = cleaned.size();
String[] cleanArgs;
if (cleanedSz == 0) {
cleanArgs = args;
} else {
cleanArgs = cleaned.toArray(new String[0]);
}
return cleanArgs;
| 33
| 654
| 687
|
<no_super_class>
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/ExtensionConfigurationModule.java
|
ExtensionConfigurationModule
|
configure
|
class ExtensionConfigurationModule implements Module {
private final CoreExtensionEntry extension;
private final Iterable<ValueSource> valueSources;
public ExtensionConfigurationModule(CoreExtensionEntry extension, ValueSource... valueSources) {
this.extension = extension;
this.valueSources = Arrays.asList(valueSources);
}
@Override
public void configure(Binder binder) {<FILL_FUNCTION_BODY>}
class Interpolator extends MavenTransformer {
final StringSearchInterpolator interpolator;
Interpolator() {
super(null);
interpolator = new StringSearchInterpolator();
interpolator.setCacheAnswers(true);
valueSources.forEach(interpolator::addValueSource);
}
public XmlNode transform(XmlNode node) {
return super.transform(node);
}
protected String transform(String str) {
try {
return interpolator.interpolate(str);
} catch (InterpolationException e) {
throw new RuntimeException(e);
}
}
}
}
|
if (extension.getKey() != null) {
XmlNode configuration = extension.getConfiguration();
if (configuration == null) {
configuration = new XmlNodeImpl("configuration");
}
configuration = new Interpolator().transform(configuration);
binder.bind(XmlNode.class)
.annotatedWith(Names.named(extension.getKey()))
.toInstance(configuration);
binder.bind(PlexusConfiguration.class)
.annotatedWith(Names.named(extension.getKey()))
.toInstance(XmlPlexusConfiguration.toPlexusConfiguration(configuration));
}
| 278
| 158
| 436
|
<no_super_class>
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/ResolveFile.java
|
ResolveFile
|
resolveFile
|
class ResolveFile {
public static File resolveFile(File file, String baseDirectory) {<FILL_FUNCTION_BODY>}
}
|
if (file == null) {
return null;
} else if (file.isAbsolute()) {
return file;
} else if (file.getPath().startsWith(File.separator)) {
// drive-relative Windows path
return file.getAbsoluteFile();
} else {
return Paths.get(baseDirectory, file.getPath()).normalize().toFile();
}
| 37
| 104
| 141
|
<no_super_class>
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jConfigurationFactory.java
|
Slf4jConfigurationFactory
|
getConfiguration
|
class Slf4jConfigurationFactory {
public static final String RESOURCE = "META-INF/maven/slf4j-configuration.properties";
public static Slf4jConfiguration getConfiguration(ILoggerFactory loggerFactory) {<FILL_FUNCTION_BODY>}
}
|
String slf4jBinding = loggerFactory.getClass().getCanonicalName();
try {
Enumeration<URL> resources =
Slf4jConfigurationFactory.class.getClassLoader().getResources(RESOURCE);
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
try {
InputStream is = resource.openStream();
final Properties properties = new Properties();
if (is != null) {
try (InputStream in = is) {
properties.load(in);
}
}
String impl = properties.getProperty(slf4jBinding);
if (impl != null) {
return (Slf4jConfiguration) Class.forName(impl).newInstance();
}
} catch (IOException | ClassNotFoundException | IllegalAccessException | InstantiationException ex) {
// ignore and move on to the next
}
}
} catch (IOException ex) {
// ignore
}
return new UnsupportedSlf4jBindingConfiguration();
| 72
| 257
| 329
|
<no_super_class>
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jLoggerManager.java
|
Slf4jLoggerManager
|
getLoggerForComponent
|
class Slf4jLoggerManager implements LoggerManager {
private ILoggerFactory loggerFactory;
public Slf4jLoggerManager() {
loggerFactory = LoggerFactory.getILoggerFactory();
}
public Logger getLoggerForComponent(String role) {
return new Slf4jLogger(loggerFactory.getLogger(role));
}
/**
* The logger name for a component with a non-null hint is <code>role.hint</code>.
* <b>Warning</b>: this does not conform to logger name as class name convention.
* (and what about <code>null</code> and <code>default</code> hint equivalence?)
*/
public Logger getLoggerForComponent(String role, String hint) {<FILL_FUNCTION_BODY>}
//
// Trying to give loggers back is a bad idea. Ceki said so :-)
// notice to self: what was this method supposed to do?
//
/**
* <b>Warning</b>: ignored.
*/
public void returnComponentLogger(String role) {}
/**
* <b>Warning</b>: ignored.
*/
public void returnComponentLogger(String role, String hint) {}
/**
* <b>Warning</b>: ignored (always return <code>0</code>).
*/
public int getThreshold() {
return 0;
}
/**
* <b>Warning</b>: ignored.
*/
public void setThreshold(int threshold) {}
/**
* <b>Warning</b>: ignored.
*/
public void setThresholds(int threshold) {}
/**
* <b>Warning</b>: ignored (always return <code>0</code>).
*/
public int getActiveLoggerCount() {
return 0;
}
}
|
return (null == hint
? getLoggerForComponent(role)
: new Slf4jLogger(loggerFactory.getLogger(role + '.' + hint)));
| 486
| 43
| 529
|
<no_super_class>
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/Log4j2Configuration.java
|
Log4j2Configuration
|
setRootLoggerLevel
|
class Log4j2Configuration extends BaseSlf4jConfiguration {
@Override
public void setRootLoggerLevel(Level level) {<FILL_FUNCTION_BODY>}
@Override
public void activate() {
// no op
}
}
|
String value;
switch (level) {
case DEBUG:
value = "debug";
break;
case INFO:
value = "info";
break;
default:
value = "error";
break;
}
System.setProperty("maven.logging.root.level", value);
| 66
| 85
| 151
|
<methods>public non-sealed void <init>() ,public void activate() ,public void setRootLoggerLevel(org.apache.maven.cli.logging.Slf4jConfiguration.Level) <variables>private static final Logger LOGGER
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/LogbackConfiguration.java
|
LogbackConfiguration
|
setRootLoggerLevel
|
class LogbackConfiguration extends BaseSlf4jConfiguration {
@Override
public void setRootLoggerLevel(Level level) {<FILL_FUNCTION_BODY>}
@Override
public void activate() {
// no op
}
}
|
ch.qos.logback.classic.Level value;
switch (level) {
case DEBUG:
value = ch.qos.logback.classic.Level.DEBUG;
break;
case INFO:
value = ch.qos.logback.classic.Level.INFO;
break;
default:
value = ch.qos.logback.classic.Level.ERROR;
break;
}
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(value);
| 64
| 153
| 217
|
<methods>public non-sealed void <init>() ,public void activate() ,public void setRootLoggerLevel(org.apache.maven.cli.logging.Slf4jConfiguration.Level) <variables>private static final Logger LOGGER
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/logging/impl/Slf4jSimpleConfiguration.java
|
Slf4jSimpleConfiguration
|
setRootLoggerLevel
|
class Slf4jSimpleConfiguration extends BaseSlf4jConfiguration {
@Override
public void setRootLoggerLevel(Level level) {<FILL_FUNCTION_BODY>}
@Override
public void activate() {
// property for root logger level or System.out redirection need to be taken into account
MavenSlf4jSimpleFriend.init();
}
}
|
String value;
switch (level) {
case DEBUG:
value = "debug";
break;
case INFO:
value = "info";
break;
default:
value = "error";
break;
}
System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", value);
| 95
| 91
| 186
|
<methods>public non-sealed void <init>() ,public void activate() ,public void setRootLoggerLevel(org.apache.maven.cli.logging.Slf4jConfiguration.Level) <variables>private static final Logger LOGGER
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/transfer/AbstractMavenTransferListener.java
|
AbstractMavenTransferListener
|
transferCorrupted
|
class AbstractMavenTransferListener extends AbstractTransferListener {
public static final String STYLE = ".transfer:-faint";
protected final MessageBuilderFactory messageBuilderFactory;
protected final PrintStream out;
protected AbstractMavenTransferListener(MessageBuilderFactory messageBuilderFactory, PrintStream out) {
this.messageBuilderFactory = messageBuilderFactory;
this.out = out;
}
@Override
public void transferInitiated(TransferEvent event) {
String action = event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploading" : "Downloading";
String direction = event.getRequestType() == TransferEvent.RequestType.PUT ? "to" : "from";
TransferResource resource = event.getResource();
MessageBuilder message = messageBuilderFactory.builder();
message.style(STYLE).append(action).append(' ').append(direction).append(' ');
message.resetStyle().append(resource.getRepositoryId());
message.style(STYLE).append(": ").append(resource.getRepositoryUrl());
message.resetStyle().append(resource.getResourceName());
out.println(message.toString());
}
@Override
public void transferCorrupted(TransferEvent event) throws TransferCancelledException {<FILL_FUNCTION_BODY>}
@Override
public void transferSucceeded(TransferEvent event) {
String action = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
String direction = event.getRequestType() == TransferEvent.RequestType.PUT ? "to" : "from";
TransferResource resource = event.getResource();
long contentLength = event.getTransferredBytes();
FileSizeFormat format = new FileSizeFormat(Locale.ENGLISH);
MessageBuilder message = messageBuilderFactory.builder();
message.append(action).style(STYLE).append(' ').append(direction).append(' ');
message.resetStyle().append(resource.getRepositoryId());
message.style(STYLE).append(": ").append(resource.getRepositoryUrl());
message.resetStyle().append(resource.getResourceName());
message.style(STYLE).append(" (").append(format.format(contentLength));
long duration = System.currentTimeMillis() - resource.getTransferStartTime();
if (duration > 0L) {
double bytesPerSecond = contentLength / (duration / 1000.0);
message.append(" at ");
format.format(message, (long) bytesPerSecond);
message.append("/s");
}
message.append(')').resetStyle();
out.println(message.toString());
}
}
|
TransferResource resource = event.getResource();
// TODO This needs to be colorized
out.println("[WARNING] " + event.getException().getMessage() + " from " + resource.getRepositoryId() + " for "
+ resource.getRepositoryUrl() + resource.getResourceName());
| 678
| 73
| 751
|
<no_super_class>
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/transfer/ConsoleMavenTransferListener.java
|
ConsoleMavenTransferListener
|
transferProgressed
|
class ConsoleMavenTransferListener extends AbstractMavenTransferListener {
private Map<TransferResource, Long> transfers = new LinkedHashMap<>();
private FileSizeFormat format = new FileSizeFormat(Locale.ENGLISH); // use in a synchronized fashion
private StringBuilder buffer = new StringBuilder(128); // use in a synchronized fashion
private boolean printResourceNames;
private int lastLength;
public ConsoleMavenTransferListener(
MessageBuilderFactory messageBuilderFactory, PrintStream out, boolean printResourceNames) {
super(messageBuilderFactory, out);
this.printResourceNames = printResourceNames;
}
@Override
public void transferInitiated(TransferEvent event) {
overridePreviousTransfer(event);
super.transferInitiated(event);
}
@Override
public void transferCorrupted(TransferEvent event) throws TransferCancelledException {
overridePreviousTransfer(event);
super.transferCorrupted(event);
}
@Override
public void transferProgressed(TransferEvent event) throws TransferCancelledException {<FILL_FUNCTION_BODY>}
private void pad(StringBuilder buffer, int spaces) {
String block = " ";
while (spaces > 0) {
int n = Math.min(spaces, block.length());
buffer.append(block, 0, n);
spaces -= n;
}
}
@Override
public void transferSucceeded(TransferEvent event) {
transfers.remove(event.getResource());
overridePreviousTransfer(event);
super.transferSucceeded(event);
}
@Override
public void transferFailed(TransferEvent event) {
transfers.remove(event.getResource());
overridePreviousTransfer(event);
super.transferFailed(event);
}
private void overridePreviousTransfer(TransferEvent event) {
if (lastLength > 0) {
pad(buffer, lastLength);
buffer.append('\r');
out.print(buffer);
out.flush();
lastLength = 0;
buffer.setLength(0);
}
}
}
|
TransferResource resource = event.getResource();
transfers.put(resource, event.getTransferredBytes());
buffer.append("Progress (").append(transfers.size()).append("): ");
Iterator<Map.Entry<TransferResource, Long>> entries =
transfers.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<TransferResource, Long> entry = entries.next();
long total = entry.getKey().getContentLength();
Long complete = entry.getValue();
String resourceName = entry.getKey().getResourceName();
if (printResourceNames) {
int idx = resourceName.lastIndexOf('/');
if (idx < 0) {
buffer.append(resourceName);
} else {
buffer.append(resourceName, idx + 1, resourceName.length());
}
buffer.append(" (");
}
format.formatProgress(buffer, complete, total);
if (printResourceNames) {
buffer.append(")");
}
if (entries.hasNext()) {
buffer.append(" | ");
}
}
int pad = lastLength - buffer.length();
lastLength = buffer.length();
pad(buffer, pad);
buffer.append('\r');
out.print(buffer);
out.flush();
buffer.setLength(0);
| 555
| 351
| 906
|
<methods>public void transferCorrupted(TransferEvent) throws TransferCancelledException,public void transferInitiated(TransferEvent) ,public void transferSucceeded(TransferEvent) <variables>public static final java.lang.String STYLE,protected final non-sealed org.apache.maven.api.services.MessageBuilderFactory messageBuilderFactory,protected final non-sealed java.io.PrintStream out
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/transfer/FileSizeFormat.java
|
FileSizeFormat
|
getScaleUnit
|
class FileSizeFormat {
public enum ScaleUnit {
BYTE {
@Override
public long bytes() {
return 1L;
}
@Override
public String symbol() {
return "B";
}
},
KILOBYTE {
@Override
public long bytes() {
return 1000L;
}
@Override
public String symbol() {
return "kB";
}
},
MEGABYTE {
@Override
public long bytes() {
return KILOBYTE.bytes() * KILOBYTE.bytes();
}
@Override
public String symbol() {
return "MB";
}
},
GIGABYTE {
@Override
public long bytes() {
return MEGABYTE.bytes() * KILOBYTE.bytes();
}
;
@Override
public String symbol() {
return "GB";
}
};
public abstract long bytes();
public abstract String symbol();
public static ScaleUnit getScaleUnit(long size) {<FILL_FUNCTION_BODY>}
}
public FileSizeFormat(Locale locale) {}
public String format(long size) {
return format(size, null);
}
public String format(long size, ScaleUnit unit) {
return format(size, unit, false);
}
public String format(long size, ScaleUnit unit, boolean omitSymbol) {
StringBuilder sb = new StringBuilder();
format(sb, size, unit, omitSymbol);
return sb.toString();
}
public void format(StringBuilder builder, long size) {
format(builder, size, null, false);
}
public void format(StringBuilder builder, long size, ScaleUnit unit) {
format(builder, size, unit, false);
}
@SuppressWarnings("checkstyle:magicnumber")
private void format(StringBuilder builder, long size, ScaleUnit unit, boolean omitSymbol) {
if (size < 0L) {
throw new IllegalArgumentException("file size cannot be negative: " + size);
}
if (unit == null) {
unit = ScaleUnit.getScaleUnit(size);
}
double scaledSize = (double) size / unit.bytes();
if (unit == ScaleUnit.BYTE) {
builder.append(size);
} else if (scaledSize < 0.05d || scaledSize >= 10.0d) {
builder.append(Math.round(scaledSize));
} else {
builder.append(Math.round(scaledSize * 10d) / 10d);
}
if (!omitSymbol) {
builder.append(" ").append(unit.symbol());
}
}
public void format(MessageBuilder builder, long size) {
format(builder, size, null, false);
}
public void format(MessageBuilder builder, long size, ScaleUnit unit) {
format(builder, size, unit, false);
}
@SuppressWarnings("checkstyle:magicnumber")
private void format(MessageBuilder builder, long size, ScaleUnit unit, boolean omitSymbol) {
if (size < 0L) {
throw new IllegalArgumentException("file size cannot be negative: " + size);
}
if (unit == null) {
unit = ScaleUnit.getScaleUnit(size);
}
double scaledSize = (double) size / unit.bytes();
if (unit == ScaleUnit.BYTE) {
builder.append(Long.toString(size));
} else if (scaledSize < 0.05d || scaledSize >= 10.0d) {
builder.append(Long.toString(Math.round(scaledSize)));
} else {
builder.append(Double.toString(Math.round(scaledSize * 10d) / 10d));
}
if (!omitSymbol) {
builder.append(" ").append(unit.symbol());
}
}
public String formatProgress(long progressedSize, long size) {
StringBuilder sb = new StringBuilder();
formatProgress(sb, progressedSize, size);
return sb.toString();
}
public void formatProgress(StringBuilder builder, long progressedSize, long size) {
if (progressedSize < 0L) {
throw new IllegalArgumentException("progressed file size cannot be negative: " + size);
}
if (size >= 0 && progressedSize > size) {
throw new IllegalArgumentException(
"progressed file size cannot be greater than size: " + progressedSize + " > " + size);
}
if (size >= 0L && progressedSize != size) {
ScaleUnit unit = ScaleUnit.getScaleUnit(size);
format(builder, progressedSize, unit, true);
builder.append("/");
format(builder, size, unit, false);
} else {
ScaleUnit unit = ScaleUnit.getScaleUnit(progressedSize);
format(builder, progressedSize, unit, false);
}
}
}
|
if (size < 0L) {
throw new IllegalArgumentException("file size cannot be negative: " + size);
}
if (size >= GIGABYTE.bytes()) {
return GIGABYTE;
} else if (size >= MEGABYTE.bytes()) {
return MEGABYTE;
} else if (size >= KILOBYTE.bytes()) {
return KILOBYTE;
} else {
return BYTE;
}
| 1,310
| 124
| 1,434
|
<no_super_class>
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/transfer/SimplexTransferListener.java
|
SimplexTransferListener
|
demux
|
class SimplexTransferListener extends AbstractTransferListener {
private static final Logger LOGGER = LoggerFactory.getLogger(SimplexTransferListener.class);
private static final int QUEUE_SIZE = 1024;
private static final int BATCH_MAX_SIZE = 500;
private final TransferListener delegate;
private final int batchMaxSize;
private final boolean blockOnLastEvent;
private final ArrayBlockingQueue<Exchange> eventQueue;
/**
* Constructor that makes passed in delegate run on single thread, and will block on last event.
*/
public SimplexTransferListener(TransferListener delegate) {
this(delegate, QUEUE_SIZE, BATCH_MAX_SIZE, true);
}
/**
* Constructor that may alter behaviour of this listener.
*
* @param delegate The delegate that should run on single thread.
* @param queueSize The event queue size (default {@code 1024}).
* @param batchMaxSize The maximum batch size delegate should receive (default {@code 500}).
* @param blockOnLastEvent Should this listener block on last transfer end (completed or corrupted) block? (default {@code true}).
*/
public SimplexTransferListener(
TransferListener delegate, int queueSize, int batchMaxSize, boolean blockOnLastEvent) {
this.delegate = requireNonNull(delegate);
if (queueSize < 1 || batchMaxSize < 1) {
throw new IllegalArgumentException("Queue and batch sizes must be greater than 1");
}
this.batchMaxSize = batchMaxSize;
this.blockOnLastEvent = blockOnLastEvent;
this.eventQueue = new ArrayBlockingQueue<>(queueSize);
Thread updater = new Thread(this::feedConsumer);
updater.setDaemon(true);
updater.start();
}
public TransferListener getDelegate() {
return delegate;
}
private void feedConsumer() {
final ArrayList<Exchange> batch = new ArrayList<>(batchMaxSize);
try {
while (true) {
batch.clear();
if (eventQueue.drainTo(batch, BATCH_MAX_SIZE) == 0) {
batch.add(eventQueue.take());
}
demux(batch);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private void demux(List<Exchange> exchanges) {<FILL_FUNCTION_BODY>}
private void put(TransferEvent event, boolean last) {
try {
Exchange exchange;
if (blockOnLastEvent && last) {
exchange = new BlockingExchange(event);
} else {
exchange = new Exchange(event);
}
eventQueue.put(exchange);
exchange.waitForProcessed();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private final ConcurrentHashMap<File, Boolean> ongoing = new ConcurrentHashMap<>();
@Override
public void transferInitiated(TransferEvent event) {
ongoing.putIfAbsent(event.getResource().getFile(), Boolean.TRUE);
put(event, false);
}
@Override
public void transferStarted(TransferEvent event) throws TransferCancelledException {
if (ongoing.get(event.getResource().getFile()) == Boolean.FALSE) {
throw new TransferCancelledException();
}
put(event, false);
}
@Override
public void transferProgressed(TransferEvent event) throws TransferCancelledException {
if (ongoing.get(event.getResource().getFile()) == Boolean.FALSE) {
throw new TransferCancelledException();
}
put(event, false);
}
@Override
public void transferCorrupted(TransferEvent event) throws TransferCancelledException {
if (ongoing.get(event.getResource().getFile()) == Boolean.FALSE) {
throw new TransferCancelledException();
}
put(event, false);
}
@Override
public void transferSucceeded(TransferEvent event) {
ongoing.remove(event.getResource().getFile());
put(event, ongoing.isEmpty());
}
@Override
public void transferFailed(TransferEvent event) {
ongoing.remove(event.getResource().getFile());
put(event, ongoing.isEmpty());
}
private static class Exchange {
private final TransferEvent event;
private Exchange(TransferEvent event) {
this.event = event;
}
public void process(Consumer<TransferEvent> consumer) {
consumer.accept(event);
}
public void waitForProcessed() throws InterruptedException {
// nothing, is async
}
}
private static class BlockingExchange extends Exchange {
private final CountDownLatch latch = new CountDownLatch(1);
private BlockingExchange(TransferEvent event) {
super(event);
}
@Override
public void process(Consumer<TransferEvent> consumer) {
super.process(consumer);
latch.countDown();
}
@Override
public void waitForProcessed() throws InterruptedException {
latch.await();
}
}
}
|
for (Exchange exchange : exchanges) {
exchange.process(transferEvent -> {
TransferEvent.EventType type = transferEvent.getType();
try {
switch (type) {
case INITIATED:
delegate.transferInitiated(transferEvent);
break;
case STARTED:
delegate.transferStarted(transferEvent);
break;
case PROGRESSED:
delegate.transferProgressed(transferEvent);
break;
case CORRUPTED:
delegate.transferCorrupted(transferEvent);
break;
case SUCCEEDED:
delegate.transferSucceeded(transferEvent);
break;
case FAILED:
delegate.transferFailed(transferEvent);
break;
default:
LOGGER.warn("Invalid TransferEvent.EventType={}; ignoring it", type);
}
} catch (TransferCancelledException e) {
ongoing.put(transferEvent.getResource().getFile(), Boolean.FALSE);
}
});
}
| 1,348
| 276
| 1,624
|
<no_super_class>
|
apache_maven
|
maven/maven-embedder/src/main/java/org/apache/maven/cli/transfer/Slf4jMavenTransferListener.java
|
Slf4jMavenTransferListener
|
transferSucceeded
|
class Slf4jMavenTransferListener extends AbstractTransferListener {
protected final Logger out;
public Slf4jMavenTransferListener() {
this.out = LoggerFactory.getLogger(Slf4jMavenTransferListener.class);
}
// TODO should we deprecate?
public Slf4jMavenTransferListener(Logger out) {
this.out = out;
}
@Override
public void transferInitiated(TransferEvent event) {
String action = event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploading" : "Downloading";
String direction = event.getRequestType() == TransferEvent.RequestType.PUT ? "to" : "from";
TransferResource resource = event.getResource();
StringBuilder message = new StringBuilder();
message.append(action).append(' ').append(direction).append(' ').append(resource.getRepositoryId());
message.append(": ");
message.append(resource.getRepositoryUrl()).append(resource.getResourceName());
out.info(message.toString());
}
@Override
public void transferCorrupted(TransferEvent event) throws TransferCancelledException {
TransferResource resource = event.getResource();
out.warn(
"{} from {} for {}{}",
event.getException().getMessage(),
resource.getRepositoryId(),
resource.getRepositoryUrl(),
resource.getResourceName());
}
@Override
public void transferSucceeded(TransferEvent event) {<FILL_FUNCTION_BODY>}
}
|
String action = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
String direction = event.getRequestType() == TransferEvent.RequestType.PUT ? "to" : "from";
TransferResource resource = event.getResource();
long contentLength = event.getTransferredBytes();
FileSizeFormat format = new FileSizeFormat(Locale.ENGLISH);
StringBuilder message = new StringBuilder();
message.append(action).append(' ').append(direction).append(' ').append(resource.getRepositoryId());
message.append(": ");
message.append(resource.getRepositoryUrl())
.append(resource.getResourceName())
.append(" (");
format.format(message, contentLength);
long duration = System.currentTimeMillis() - resource.getTransferStartTime();
if (duration > 0L) {
double bytesPerSecond = contentLength / (duration / 1000.0);
message.append(" at ");
format.format(message, (long) bytesPerSecond);
message.append("/s");
}
message.append(')');
out.info(message.toString());
| 398
| 299
| 697
|
<no_super_class>
|
apache_maven
|
maven/maven-embedder/src/main/java/org/fusesource/jansi/Ansi.java
|
NoAnsi
|
fgRgb
|
class NoAnsi extends Ansi {
NoAnsi() {
super();
}
NoAnsi(int size) {
super(size);
}
NoAnsi(StringBuilder builder) {
super(builder);
}
@Override
public Ansi fg(Color color) {
return this;
}
@Override
public Ansi bg(Color color) {
return this;
}
@Override
public Ansi fgBright(Color color) {
return this;
}
@Override
public Ansi bgBright(Color color) {
return this;
}
@Override
public Ansi fg(int color) {
return this;
}
@Override
public Ansi fgRgb(int r, int g, int b) {
return this;
}
@Override
public Ansi bg(int color) {
return this;
}
@Override
public Ansi bgRgb(int r, int g, int b) {
return this;
}
@Override
public Ansi a(Attribute attribute) {
return this;
}
@Override
public Ansi cursor(int row, int column) {
return this;
}
@Override
public Ansi cursorToColumn(int x) {
return this;
}
@Override
public Ansi cursorUp(int y) {
return this;
}
@Override
public Ansi cursorRight(int x) {
return this;
}
@Override
public Ansi cursorDown(int y) {
return this;
}
@Override
public Ansi cursorLeft(int x) {
return this;
}
@Override
public Ansi cursorDownLine() {
return this;
}
@Override
public Ansi cursorDownLine(final int n) {
return this;
}
@Override
public Ansi cursorUpLine() {
return this;
}
@Override
public Ansi cursorUpLine(final int n) {
return this;
}
@Override
public Ansi eraseScreen() {
return this;
}
@Override
public Ansi eraseScreen(Erase kind) {
return this;
}
@Override
public Ansi eraseLine() {
return this;
}
@Override
public Ansi eraseLine(Erase kind) {
return this;
}
@Override
public Ansi scrollUp(int rows) {
return this;
}
@Override
public Ansi scrollDown(int rows) {
return this;
}
@Override
public Ansi saveCursorPosition() {
return this;
}
@Override
@Deprecated
public Ansi restorCursorPosition() {
return this;
}
@Override
public Ansi restoreCursorPosition() {
return this;
}
@Override
public Ansi reset() {
return this;
}
}
private final StringBuilder builder;
private final ArrayList<Integer> attributeOptions = new ArrayList<>(5);
public Ansi() {
this(new StringBuilder(80));
}
public Ansi(Ansi parent) {
this(new StringBuilder(parent.builder));
attributeOptions.addAll(parent.attributeOptions);
}
public Ansi(int size) {
this(new StringBuilder(size));
}
public Ansi(StringBuilder builder) {
this.builder = builder;
}
public Ansi fg(Color color) {
attributeOptions.add(color.fg());
return this;
}
public Ansi fg(int color) {
attributeOptions.add(38);
attributeOptions.add(5);
attributeOptions.add(color & 0xff);
return this;
}
public Ansi fgRgb(int color) {
return fgRgb(color >> 16, color >> 8, color);
}
public Ansi fgRgb(int r, int g, int b) {<FILL_FUNCTION_BODY>
|
attributeOptions.add(38);
attributeOptions.add(2);
attributeOptions.add(r & 0xff);
attributeOptions.add(g & 0xff);
attributeOptions.add(b & 0xff);
return this;
| 1,098
| 69
| 1,167
|
<no_super_class>
|
apache_maven
|
maven/maven-embedder/src/main/java/org/slf4j/simple/MavenSlf4jSimpleFriend.java
|
MavenSlf4jSimpleFriend
|
init
|
class MavenSlf4jSimpleFriend {
public static void init() {<FILL_FUNCTION_BODY>}
}
|
SimpleLogger.init();
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
if (loggerFactory instanceof SimpleLoggerFactory) {
((SimpleLoggerFactory) loggerFactory).reset();
}
| 33
| 55
| 88
|
<no_super_class>
|
apache_maven
|
maven/maven-jline/src/main/java/org/apache/maven/jline/FastTerminal.java
|
FastTerminal
|
getTerminal
|
class FastTerminal implements TerminalExt {
final Future<Terminal> terminal;
public FastTerminal(Callable<Terminal> builder, Consumer<Terminal> consumer) {
ExecutorService executor = Executors.newSingleThreadExecutor();
terminal = executor.submit(() -> {
try {
Terminal terminal = builder.call();
consumer.accept(terminal);
return terminal;
} catch (Exception e) {
throw new MavenException(e);
} finally {
executor.shutdown();
}
});
}
public TerminalExt getTerminal() {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return getTerminal().getName();
}
@Override
public SignalHandler handle(Signal signal, SignalHandler signalHandler) {
return getTerminal().handle(signal, signalHandler);
}
@Override
public void raise(Signal signal) {
getTerminal().raise(signal);
}
@Override
public NonBlockingReader reader() {
return getTerminal().reader();
}
@Override
public PrintWriter writer() {
return getTerminal().writer();
}
@Override
public Charset encoding() {
return getTerminal().encoding();
}
@Override
public InputStream input() {
return getTerminal().input();
}
@Override
public OutputStream output() {
return getTerminal().output();
}
@Override
public boolean canPauseResume() {
return getTerminal().canPauseResume();
}
@Override
public void pause() {
getTerminal().pause();
}
@Override
public void pause(boolean b) throws InterruptedException {
getTerminal().pause(b);
}
@Override
public void resume() {
getTerminal().resume();
}
@Override
public boolean paused() {
return getTerminal().paused();
}
@Override
public Attributes enterRawMode() {
return getTerminal().enterRawMode();
}
@Override
public boolean echo() {
return getTerminal().echo();
}
@Override
public boolean echo(boolean b) {
return getTerminal().echo(b);
}
@Override
public Attributes getAttributes() {
return getTerminal().getAttributes();
}
@Override
public void setAttributes(Attributes attributes) {
getTerminal().setAttributes(attributes);
}
@Override
public Size getSize() {
return getTerminal().getSize();
}
@Override
public void setSize(Size size) {
getTerminal().setSize(size);
}
@Override
public int getWidth() {
return getTerminal().getWidth();
}
@Override
public int getHeight() {
return getTerminal().getHeight();
}
@Override
public Size getBufferSize() {
return getTerminal().getBufferSize();
}
@Override
public void flush() {
getTerminal().flush();
}
@Override
public String getType() {
return getTerminal().getType();
}
@Override
public boolean puts(InfoCmp.Capability capability, Object... objects) {
return getTerminal().puts(capability, objects);
}
@Override
public boolean getBooleanCapability(InfoCmp.Capability capability) {
return getTerminal().getBooleanCapability(capability);
}
@Override
public Integer getNumericCapability(InfoCmp.Capability capability) {
return getTerminal().getNumericCapability(capability);
}
@Override
public String getStringCapability(InfoCmp.Capability capability) {
return getTerminal().getStringCapability(capability);
}
@Override
public Cursor getCursorPosition(IntConsumer intConsumer) {
return getTerminal().getCursorPosition(intConsumer);
}
@Override
public boolean hasMouseSupport() {
return getTerminal().hasMouseSupport();
}
@Override
public boolean trackMouse(MouseTracking mouseTracking) {
return getTerminal().trackMouse(mouseTracking);
}
@Override
public MouseEvent readMouseEvent() {
return getTerminal().readMouseEvent();
}
@Override
public MouseEvent readMouseEvent(IntSupplier intSupplier) {
return getTerminal().readMouseEvent(intSupplier);
}
@Override
public boolean hasFocusSupport() {
return getTerminal().hasFocusSupport();
}
@Override
public boolean trackFocus(boolean b) {
return getTerminal().trackFocus(b);
}
@Override
public ColorPalette getPalette() {
return getTerminal().getPalette();
}
@Override
public void close() throws IOException {
getTerminal().close();
}
@Override
public TerminalProvider getProvider() {
return getTerminal().getProvider();
}
@Override
public SystemStream getSystemStream() {
return getTerminal().getSystemStream();
}
}
|
try {
return (TerminalExt) terminal.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
| 1,356
| 40
| 1,396
|
<no_super_class>
|
apache_maven
|
maven/maven-jline/src/main/java/org/apache/maven/jline/JLineMessageBuilderFactory.java
|
JLineMessageBuilderFactory
|
doPrompt
|
class JLineMessageBuilderFactory implements MessageBuilderFactory, Prompter, InputHandler, OutputHandler {
private final StyleResolver resolver;
public JLineMessageBuilderFactory() {
this.resolver = new MavenStyleResolver();
}
@Override
public boolean isColorEnabled() {
return false;
}
@Override
public int getTerminalWidth() {
return MessageUtils.getTerminalWidth();
}
@Override
public MessageBuilder builder() {
return new JlineMessageBuilder();
}
@Override
public MessageBuilder builder(int size) {
return new JlineMessageBuilder(size);
}
@Override
public String readLine() throws IOException {
return doPrompt(null, true);
}
@Override
public String readPassword() throws IOException {
return doPrompt(null, true);
}
@Override
public List<String> readMultipleLines() throws IOException {
List<String> lines = new ArrayList<>();
for (String line = this.readLine(); line != null && !line.isEmpty(); line = readLine()) {
lines.add(line);
}
return lines;
}
@Override
public void write(String line) throws IOException {
doDisplay(line);
}
@Override
public void writeLine(String line) throws IOException {
doDisplay(line + System.lineSeparator());
}
@Override
public String prompt(String message) throws PrompterException {
return prompt(message, null, null);
}
@Override
public String prompt(String message, String defaultReply) throws PrompterException {
return prompt(message, null, defaultReply);
}
@Override
public String prompt(String message, List possibleValues) throws PrompterException {
return prompt(message, possibleValues, null);
}
@Override
public String prompt(String message, List possibleValues, String defaultReply) throws PrompterException {
return doPrompt(message, possibleValues, defaultReply, false);
}
@Override
public String promptForPassword(String message) throws PrompterException {
return doPrompt(message, null, null, true);
}
@Override
public void showMessage(String message) throws PrompterException {
try {
doDisplay(message);
} catch (IOException e) {
throw new PrompterException("Failed to present prompt", e);
}
}
String doPrompt(String message, List<Object> possibleValues, String defaultReply, boolean password)
throws PrompterException {
String formattedMessage = formatMessage(message, possibleValues, defaultReply);
String line;
do {
try {
line = doPrompt(formattedMessage, password);
if (line == null && defaultReply == null) {
throw new IOException("EOF");
}
} catch (IOException e) {
throw new PrompterException("Failed to prompt user", e);
}
if (line == null || line.isEmpty()) {
line = defaultReply;
}
if (line != null && (possibleValues != null && !possibleValues.contains(line))) {
try {
doDisplay("Invalid selection.\n");
} catch (IOException e) {
throw new PrompterException("Failed to present feedback", e);
}
}
} while (line == null || (possibleValues != null && !possibleValues.contains(line)));
return line;
}
private String formatMessage(String message, List<Object> possibleValues, String defaultReply) {
StringBuilder formatted = new StringBuilder(message.length() * 2);
formatted.append(message);
if (possibleValues != null && !possibleValues.isEmpty()) {
formatted.append(" (");
for (Iterator<?> it = possibleValues.iterator(); it.hasNext(); ) {
String possibleValue = String.valueOf(it.next());
formatted.append(possibleValue);
if (it.hasNext()) {
formatted.append('/');
}
}
formatted.append(')');
}
if (defaultReply != null) {
formatted.append(' ').append(defaultReply).append(": ");
}
return formatted.toString();
}
private void doDisplay(String message) throws IOException {
try {
MessageUtils.terminal.writer().print(message);
MessageUtils.terminal.flush();
} catch (Exception e) {
throw new IOException("Unable to display message", e);
}
}
private String doPrompt(String message, boolean password) throws IOException {<FILL_FUNCTION_BODY>}
class JlineMessageBuilder implements MessageBuilder {
final AttributedStringBuilder builder;
JlineMessageBuilder() {
builder = new AttributedStringBuilder();
}
JlineMessageBuilder(int size) {
builder = new AttributedStringBuilder(size);
}
@Override
public MessageBuilder style(String style) {
if (MessageUtils.isColorEnabled()) {
builder.style(resolver.resolve(style));
}
return this;
}
@Override
public MessageBuilder resetStyle() {
builder.style(AttributedStyle.DEFAULT);
return this;
}
@Override
public MessageBuilder append(CharSequence cs) {
builder.append(cs);
return this;
}
@Override
public MessageBuilder append(CharSequence cs, int start, int end) {
builder.append(cs, start, end);
return this;
}
@Override
public MessageBuilder append(char c) {
builder.append(c);
return this;
}
@Override
public MessageBuilder setLength(int length) {
builder.setLength(length);
return this;
}
@Override
public String build() {
return builder.toAnsi(MessageUtils.terminal);
}
@Override
public String toString() {
return build();
}
}
static class MavenStyleResolver extends StyleResolver {
private final Map<String, AttributedStyle> styles = new ConcurrentHashMap<>();
MavenStyleResolver() {
super(s -> System.getProperty("style." + s));
}
@Override
public AttributedStyle resolve(String spec) {
return styles.computeIfAbsent(spec, this::doResolve);
}
@Override
public AttributedStyle resolve(String spec, String defaultSpec) {
return resolve(defaultSpec != null ? spec + ":-" + defaultSpec : spec);
}
private AttributedStyle doResolve(String spec) {
String def = null;
int i = spec.indexOf(":-");
if (i != -1) {
String[] parts = spec.split(":-");
spec = parts[0].trim();
def = parts[1].trim();
}
return super.resolve(spec, def);
}
}
}
|
try {
return MessageUtils.reader.readLine(message != null ? message + ": " : null, password ? '*' : null);
} catch (Exception e) {
throw new IOException("Unable to prompt user", e);
}
| 1,788
| 65
| 1,853
|
<no_super_class>
|
apache_maven
|
maven/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
|
MessageUtils
|
systemUninstall
|
class MessageUtils {
static Terminal terminal;
static LineReader reader;
static MessageBuilderFactory messageBuilderFactory = new JLineMessageBuilderFactory();
static boolean colorEnabled = true;
static Thread shutdownHook;
static final Object STARTUP_SHUTDOWN_MONITOR = new Object();
static PrintStream prevOut;
static PrintStream prevErr;
public static void systemInstall() {
terminal = new FastTerminal(
() -> TerminalBuilder.builder().name("Maven").dumb(true).build(), t -> {
reader = LineReaderBuilder.builder().terminal(t).build();
AnsiConsole.setTerminal(t);
AnsiConsole.systemInstall();
});
}
public static void registerShutdownHook() {
if (shutdownHook == null) {
shutdownHook = new Thread(() -> {
synchronized (MessageUtils.STARTUP_SHUTDOWN_MONITOR) {
MessageUtils.doSystemUninstall();
}
});
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
}
public static void systemUninstall() {<FILL_FUNCTION_BODY>}
private static void doSystemUninstall() {
try {
AnsiConsole.systemUninstall();
} finally {
terminal = null;
}
}
public static void setColorEnabled(boolean enabled) {
colorEnabled = enabled;
}
public static boolean isColorEnabled() {
return colorEnabled && terminal != null;
}
public static int getTerminalWidth() {
return terminal != null ? terminal.getWidth() : -1;
}
public static MessageBuilder builder() {
return messageBuilderFactory.builder();
}
}
|
doSystemUninstall();
if (shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
} catch (IllegalStateException var3) {
// ignore
}
}
| 441
| 65
| 506
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/ArtifactModelSource.java
|
ArtifactModelSource
|
equals
|
class ArtifactModelSource extends FileSource implements ModelSource {
private final String groupId;
private final String artifactId;
private final String version;
private final int hashCode;
@Deprecated
public ArtifactModelSource(File file, String groupId, String artifactId, String version) {
super(file);
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
this.hashCode = Objects.hash(groupId, artifactId, version);
}
public ArtifactModelSource(Path path, String groupId, String artifactId, String version) {
super(path);
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
this.hashCode = Objects.hash(groupId, artifactId, version);
}
public String getGroupId() {
return groupId;
}
public String getArtifactId() {
return artifactId;
}
public String getVersion() {
return version;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return groupId + ":" + artifactId + ":" + version;
}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!ArtifactModelSource.class.equals(obj.getClass())) {
return false;
}
ArtifactModelSource other = (ArtifactModelSource) obj;
return Objects.equals(artifactId, other.artifactId)
&& Objects.equals(groupId, other.groupId)
&& Objects.equals(version, other.version);
| 348
| 124
| 472
|
<methods>public void <init>(java.io.File) ,public void <init>(java.nio.file.Path) ,public boolean equals(java.lang.Object) ,public java.io.File getFile() ,public java.io.InputStream getInputStream() throws java.io.IOException,public java.lang.String getLocation() ,public java.nio.file.Path getPath() ,public int hashCode() ,public java.lang.String toString() <variables>private final non-sealed int hashCode,private final non-sealed java.nio.file.Path path
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/BuildModelSourceTransformer.java
|
BuildModelSourceTransformer
|
handleParent
|
class BuildModelSourceTransformer implements ModelSourceTransformer {
public static final String NAMESPACE_PREFIX = "http://maven.apache.org/POM/";
@Override
public void transform(Path pomFile, TransformerContext context, Model model) {
handleModelVersion(model);
handleParent(pomFile, context, model);
handleReactorDependencies(context, model);
handleCiFriendlyVersion(context, model);
}
//
// Infer modelVersion from namespace URI
//
void handleModelVersion(Model model) {
String namespace = model.getDelegate().getNamespaceUri();
if (model.getModelVersion() == null && namespace != null && namespace.startsWith(NAMESPACE_PREFIX)) {
model.setModelVersion(namespace.substring(NAMESPACE_PREFIX.length()));
}
}
//
// Infer parent information
//
void handleParent(Path pomFile, TransformerContext context, Model model) {<FILL_FUNCTION_BODY>}
//
// CI friendly versions
//
void handleCiFriendlyVersion(TransformerContext context, Model model) {
String version = model.getVersion();
String modVersion = replaceCiFriendlyVersion(context, version);
model.setVersion(modVersion);
Parent parent = model.getParent();
if (parent != null) {
version = parent.getVersion();
modVersion = replaceCiFriendlyVersion(context, version);
parent.setVersion(modVersion);
}
}
//
// Infer inner reactor dependencies version
//
void handleReactorDependencies(TransformerContext context, Model model) {
for (Dependency dep : model.getDependencies()) {
if (dep.getVersion() == null) {
Model depModel =
context.getRawModel(model.getDelegate().getPomFile(), dep.getGroupId(), dep.getArtifactId());
if (depModel != null) {
String v = depModel.getVersion();
if (v == null && depModel.getParent() != null) {
v = depModel.getParent().getVersion();
}
dep.setVersion(v);
}
}
}
}
protected String replaceCiFriendlyVersion(TransformerContext context, String version) {
if (version != null) {
for (String key : Arrays.asList("changelist", "revision", "sha1")) {
String val = context.getUserProperty(key);
if (val != null) {
version = version.replace("${" + key + "}", val);
}
}
}
return version;
}
protected Optional<RelativeProject> resolveRelativePath(
Path pomFile, TransformerContext context, Path relativePath, String groupId, String artifactId) {
Path pomPath = pomFile.resolveSibling(relativePath).normalize();
if (Files.isDirectory(pomPath)) {
pomPath = context.locate(pomPath);
}
if (pomPath == null || !Files.isRegularFile(pomPath)) {
return Optional.empty();
}
Optional<RelativeProject> mappedProject = Optional.ofNullable(context.getRawModel(pomFile, pomPath.normalize()))
.map(BuildModelSourceTransformer::toRelativeProject);
if (mappedProject.isPresent()) {
RelativeProject project = mappedProject.get();
if (Objects.equals(groupId, project.getGroupId()) && Objects.equals(artifactId, project.getArtifactId())) {
return mappedProject;
}
}
return Optional.empty();
}
private static RelativeProject toRelativeProject(final org.apache.maven.model.Model m) {
String groupId = m.getGroupId();
if (groupId == null && m.getParent() != null) {
groupId = m.getParent().getGroupId();
}
String version = m.getVersion();
if (version == null && m.getParent() != null) {
version = m.getParent().getVersion();
}
return new RelativeProject(groupId, m.getArtifactId(), version);
}
static class RelativeProject {
private final String groupId;
private final String artifactId;
private final String version;
RelativeProject(String groupId, String artifactId, String version) {
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
}
public String getGroupId() {
return groupId;
}
public String getArtifactId() {
return artifactId;
}
public String getVersion() {
return version;
}
}
}
|
Parent parent = model.getParent();
if (parent != null) {
String version = parent.getVersion();
String path = Optional.ofNullable(parent.getRelativePath()).orElse("..");
if (version == null && !path.isEmpty()) {
Optional<RelativeProject> resolvedParent = resolveRelativePath(
pomFile, context, Paths.get(path), parent.getGroupId(), parent.getArtifactId());
resolvedParent.ifPresent(relativeProject -> parent.setVersion(relativeProject.getVersion()));
}
}
| 1,224
| 143
| 1,367
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/DefaultModelBuildingResult.java
|
DefaultModelBuildingResult
|
setActivePomProfiles
|
class DefaultModelBuildingResult implements ModelBuildingResult {
private Model fileModel;
private Model effectiveModel;
private List<String> modelIds;
private Map<String, Model> rawModels;
private Map<String, List<Profile>> activePomProfiles;
private List<Profile> activeExternalProfiles;
private List<ModelProblem> problems;
DefaultModelBuildingResult() {
modelIds = new ArrayList<>();
rawModels = new HashMap<>();
activePomProfiles = new HashMap<>();
activeExternalProfiles = new ArrayList<>();
problems = new ArrayList<>();
}
DefaultModelBuildingResult(ModelBuildingResult result) {
this();
this.activeExternalProfiles.addAll(result.getActiveExternalProfiles());
this.effectiveModel = result.getEffectiveModel();
this.fileModel = result.getFileModel();
this.problems.addAll(result.getProblems());
for (String modelId : result.getModelIds()) {
this.modelIds.add(modelId);
this.rawModels.put(modelId, result.getRawModel(modelId));
this.activePomProfiles.put(modelId, result.getActivePomProfiles(modelId));
}
}
@Override
public Model getFileModel() {
return fileModel;
}
public DefaultModelBuildingResult setFileModel(Model fileModel) {
this.fileModel = fileModel;
return this;
}
@Override
public Model getEffectiveModel() {
return effectiveModel;
}
public DefaultModelBuildingResult setEffectiveModel(Model model) {
this.effectiveModel = model;
return this;
}
@Override
public List<String> getModelIds() {
return modelIds;
}
public DefaultModelBuildingResult addModelId(String modelId) {
// Intentionally notNull because Super POM may not contain a modelId
Objects.requireNonNull(modelId, "modelId cannot null");
modelIds.add(modelId);
return this;
}
@Override
public Model getRawModel() {
return rawModels.get(modelIds.get(0));
}
@Override
public Model getRawModel(String modelId) {
return rawModels.get(modelId);
}
public DefaultModelBuildingResult setRawModel(String modelId, Model rawModel) {
// Intentionally notNull because Super POM may not contain a modelId
Objects.requireNonNull(modelId, "modelId cannot null");
rawModels.put(modelId, rawModel);
return this;
}
@Override
public List<Profile> getActivePomProfiles(String modelId) {
return activePomProfiles.get(modelId);
}
public DefaultModelBuildingResult setActivePomProfiles(String modelId, List<Profile> activeProfiles) {<FILL_FUNCTION_BODY>}
@Override
public List<Profile> getActiveExternalProfiles() {
return activeExternalProfiles;
}
public DefaultModelBuildingResult setActiveExternalProfiles(List<Profile> activeProfiles) {
if (activeProfiles != null) {
this.activeExternalProfiles = new ArrayList<>(activeProfiles);
} else {
this.activeExternalProfiles.clear();
}
return this;
}
@Override
public List<ModelProblem> getProblems() {
return problems;
}
public DefaultModelBuildingResult setProblems(List<ModelProblem> problems) {
if (problems != null) {
this.problems = new ArrayList<>(problems);
} else {
this.problems.clear();
}
return this;
}
}
|
// Intentionally notNull because Super POM may not contain a modelId
Objects.requireNonNull(modelId, "modelId cannot null");
if (activeProfiles != null) {
this.activePomProfiles.put(modelId, new ArrayList<>(activeProfiles));
} else {
this.activePomProfiles.remove(modelId);
}
return this;
| 972
| 104
| 1,076
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/DefaultModelProblem.java
|
DefaultModelProblem
|
getMessage
|
class DefaultModelProblem implements ModelProblem {
private final String source;
private final int lineNumber;
private final int columnNumber;
private final String modelId;
private final String message;
private final Exception exception;
private final Severity severity;
private final Version version;
/**
* Creates a new problem with the specified message and exception.
*
* @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 ModelProblem.Severity#ERROR}.
* @param source The source of the problem, may be {@code null}.
* @param lineNumber The one-based index of the line containing the error or {@code -1} if unknown.
* @param columnNumber The one-based index of the column containing the error or {@code -1} if unknown.
* @param exception The exception that caused this problem, may be {@code null}.
*/
// mkleint: does this need to be public?
public DefaultModelProblem(
String message,
Severity severity,
Version version,
Model source,
int lineNumber,
int columnNumber,
Exception exception) {
this(
message,
severity,
version,
ModelProblemUtils.toPath(source),
lineNumber,
columnNumber,
ModelProblemUtils.toId(source),
exception);
}
/**
* Creates a new problem with the specified message and exception.
*
* @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 ModelProblem.Severity#ERROR}.
* @param version The version since the problem is relevant
* @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 modelId The identifier of the model that exhibits the problem, may be {@code null}.
* @param exception The exception that caused this problem, may be {@code null}.
*/
// mkleint: does this need to be public?
@SuppressWarnings("checkstyle:parameternumber")
public DefaultModelProblem(
String message,
Severity severity,
Version version,
String source,
int lineNumber,
int columnNumber,
String modelId,
Exception exception) {
this.message = message;
this.severity = (severity != null) ? severity : Severity.ERROR;
this.source = (source != null) ? source : "";
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.modelId = (modelId != null) ? modelId : "";
this.exception = exception;
this.version = version;
}
@Override
public String getSource() {
return source;
}
@Override
public int getLineNumber() {
return lineNumber;
}
@Override
public int getColumnNumber() {
return columnNumber;
}
@Override
public String getModelId() {
return modelId;
}
@Override
public Exception getException() {
return exception;
}
@Override
public String getMessage() {<FILL_FUNCTION_BODY>}
@Override
public Severity getSeverity() {
return severity;
}
@Override
public Version getVersion() {
return version;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder(128);
buffer.append('[').append(getSeverity()).append("] ");
buffer.append(getMessage());
String location = ModelProblemUtils.formatLocation(this, null);
if (!location.isEmpty()) {
buffer.append(" @ ");
buffer.append(location);
}
return buffer.toString();
}
}
|
String msg = null;
if (message != null && !message.isEmpty()) {
msg = message;
} else if (exception != null) {
msg = exception.getMessage();
}
if (msg == null) {
msg = "";
}
return msg;
| 1,081
| 79
| 1,160
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/DefaultModelProblemCollector.java
|
DefaultModelProblemCollector
|
newModelBuildingException
|
class DefaultModelProblemCollector implements ModelProblemCollectorExt {
private final ModelBuildingResult result;
private List<ModelProblem> problems;
private String source;
private Model sourceModel;
private Model rootModel;
private Set<ModelProblem.Severity> severities = EnumSet.noneOf(ModelProblem.Severity.class);
DefaultModelProblemCollector(ModelBuildingResult result) {
this.result = result;
this.problems = result.getProblems();
for (ModelProblem problem : this.problems) {
severities.add(problem.getSeverity());
}
}
public boolean hasFatalErrors() {
return severities.contains(ModelProblem.Severity.FATAL);
}
public boolean hasErrors() {
return severities.contains(ModelProblem.Severity.ERROR) || severities.contains(ModelProblem.Severity.FATAL);
}
@Override
public List<ModelProblem> getProblems() {
return problems;
}
public void setSource(String source) {
this.source = source;
this.sourceModel = null;
}
public void setSource(Model source) {
this.sourceModel = source;
this.source = null;
if (rootModel == null) {
rootModel = source;
}
}
private String getSource() {
if (source == null && sourceModel != null) {
source = ModelProblemUtils.toPath(sourceModel);
}
return source;
}
private String getModelId() {
return ModelProblemUtils.toId(sourceModel);
}
public void setRootModel(Model rootModel) {
this.rootModel = rootModel;
}
public Model getRootModel() {
return rootModel;
}
public String getRootModelId() {
return ModelProblemUtils.toId(rootModel);
}
public void add(ModelProblem problem) {
problems.add(problem);
severities.add(problem.getSeverity());
}
public void addAll(List<ModelProblem> problems) {
this.problems.addAll(problems);
for (ModelProblem problem : problems) {
severities.add(problem.getSeverity());
}
}
@Override
public void add(ModelProblemCollectorRequest req) {
int line = -1;
int column = -1;
String source = null;
String modelId = null;
if (req.getLocation() != null) {
line = req.getLocation().getLineNumber();
column = req.getLocation().getColumnNumber();
if (req.getLocation().getSource() != null) {
modelId = req.getLocation().getSource().getModelId();
source = req.getLocation().getSource().getLocation();
}
}
if (modelId == null) {
modelId = getModelId();
source = getSource();
}
if (line <= 0 && column <= 0 && req.getException() instanceof ModelParseException) {
ModelParseException e = (ModelParseException) req.getException();
line = e.getLineNumber();
column = e.getColumnNumber();
}
ModelProblem problem = new DefaultModelProblem(
req.getMessage(),
req.getSeverity(),
req.getVersion(),
source,
line,
column,
modelId,
req.getException());
add(problem);
}
public ModelBuildingException newModelBuildingException() {<FILL_FUNCTION_BODY>}
}
|
ModelBuildingResult result = this.result;
if (result.getModelIds().isEmpty()) {
DefaultModelBuildingResult tmp = new DefaultModelBuildingResult();
tmp.setEffectiveModel(result.getEffectiveModel());
tmp.setProblems(getProblems());
tmp.setActiveExternalProfiles(result.getActiveExternalProfiles());
String id = getRootModelId();
tmp.addModelId(id);
tmp.setRawModel(id, getRootModel());
result = tmp;
}
return new ModelBuildingException(result);
| 953
| 140
| 1,093
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/DefaultModelProcessor.java
|
DefaultModelProcessor
|
read
|
class DefaultModelProcessor implements ModelProcessor {
private final Collection<ModelParser> modelParsers;
private final ModelLocator modelLocator;
private final ModelReader modelReader;
@Inject
public DefaultModelProcessor(List<ModelParser> modelParsers, ModelLocator modelLocator, ModelReader modelReader) {
this.modelParsers = modelParsers;
this.modelLocator = modelLocator;
this.modelReader = modelReader;
}
@Deprecated
@Override
public File locatePom(File projectDirectory) {
return locatePom(projectDirectory.toPath()).toFile();
}
@Override
public Path locatePom(Path projectDirectory) {
// Note that the ModelProcessor#locatePom never returns null
// while the ModelParser#locatePom needs to return an existing path!
Path pom = modelParsers.stream()
.map(m -> m.locate(projectDirectory)
.map(org.apache.maven.api.services.Source::getPath)
.orElse(null))
.filter(Objects::nonNull)
.findFirst()
.orElseGet(() -> modelLocator.locatePom(projectDirectory));
if (!pom.equals(projectDirectory) && !pom.getParent().equals(projectDirectory)) {
throw new IllegalArgumentException("The POM found does not belong to the given directory: " + pom);
}
return pom;
}
@Deprecated
@Override
public File locateExistingPom(File projectDirectory) {
Path path = locateExistingPom(projectDirectory.toPath());
return path != null ? path.toFile() : null;
}
@Override
public Path locateExistingPom(Path projectDirectory) {
// Note that the ModelProcessor#locatePom never returns null
// while the ModelParser#locatePom needs to return an existing path!
Path pom = modelParsers.stream()
.map(m -> m.locate(projectDirectory)
.map(org.apache.maven.api.services.Source::getPath)
.orElse(null))
.filter(Objects::nonNull)
.findFirst()
.orElseGet(() -> modelLocator.locateExistingPom(projectDirectory));
if (pom != null && !pom.equals(projectDirectory) && !pom.getParent().equals(projectDirectory)) {
throw new IllegalArgumentException("The POM found does not belong to the given directory: " + pom);
}
return pom;
}
protected org.apache.maven.api.model.Model read(
Path pomFile, InputStream input, Reader reader, Map<String, ?> options) throws IOException {<FILL_FUNCTION_BODY>}
private org.apache.maven.api.model.Model readXmlModel(
Path pomFile, InputStream input, Reader reader, Map<String, ?> options) throws IOException {
if (pomFile != null) {
return modelReader.read(pomFile, options).getDelegate();
} else if (input != null) {
return modelReader.read(input, options).getDelegate();
} else {
return modelReader.read(reader, options).getDelegate();
}
}
@Deprecated
@Override
public org.apache.maven.model.Model read(File file, Map<String, ?> options) throws IOException {
Objects.requireNonNull(file, "file cannot be null");
return read(file.toPath(), options);
}
@Override
public org.apache.maven.model.Model read(Path path, Map<String, ?> options) throws IOException {
Objects.requireNonNull(path, "path cannot be null");
org.apache.maven.api.model.Model model = read(path, null, null, options);
return new org.apache.maven.model.Model(model);
}
@Override
public org.apache.maven.model.Model read(InputStream input, Map<String, ?> options) throws IOException {
Objects.requireNonNull(input, "input cannot be null");
try (InputStream in = input) {
org.apache.maven.api.model.Model model = read(null, in, null, options);
return new org.apache.maven.model.Model(model);
} catch (ModelParserException e) {
throw new ModelParseException("Unable to read model: " + e, e.getLineNumber(), e.getColumnNumber(), e);
}
}
@Override
public org.apache.maven.model.Model read(Reader reader, Map<String, ?> options) throws IOException {
Objects.requireNonNull(reader, "reader cannot be null");
try (Reader r = reader) {
org.apache.maven.api.model.Model model = read(null, null, r, options);
return new org.apache.maven.model.Model(model);
}
}
}
|
Source source = (Source) options.get(ModelProcessor.SOURCE);
if (pomFile == null && source instanceof org.apache.maven.building.FileSource) {
pomFile = ((org.apache.maven.building.FileSource) source).getPath();
}
if (pomFile != null) {
Path projectDirectory = pomFile.getParent();
List<ModelParserException> exceptions = new ArrayList<>();
for (ModelParser parser : modelParsers) {
try {
Optional<Model> model = parser.locateAndParse(projectDirectory, options);
if (model.isPresent()) {
return model.get().withPomFile(pomFile);
}
} catch (ModelParserException e) {
exceptions.add(e);
}
}
try {
return readXmlModel(pomFile, null, null, options);
} catch (IOException e) {
exceptions.forEach(e::addSuppressed);
throw e;
}
} else {
return readXmlModel(pomFile, input, reader, options);
}
| 1,258
| 277
| 1,535
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/DefaultTransformerContext.java
|
GAKey
|
equals
|
class GAKey {
private final String groupId;
private final String artifactId;
private final int hashCode;
GAKey(String groupId, String artifactId) {
this.groupId = groupId;
this.artifactId = artifactId;
this.hashCode = Objects.hash(groupId, artifactId);
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (!(obj instanceof GAKey)) {
return false;
}
GAKey other = (GAKey) obj;
return Objects.equals(artifactId, other.artifactId) && Objects.equals(groupId, other.groupId);
| 134
| 78
| 212
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/DefaultTransformerContextBuilder.java
|
DefaultTransformerContextBuilder
|
initialize
|
class DefaultTransformerContextBuilder implements TransformerContextBuilder {
private final Graph dag = new Graph();
private final DefaultModelBuilder defaultModelBuilder;
private final DefaultTransformerContext context;
private final Map<String, Set<FileModelSource>> mappedSources = new ConcurrentHashMap<>(64);
private volatile boolean fullReactorLoaded;
DefaultTransformerContextBuilder(DefaultModelBuilder defaultModelBuilder) {
this.defaultModelBuilder = defaultModelBuilder;
this.context = new DefaultTransformerContext(defaultModelBuilder.getModelProcessor());
}
/**
* If an interface could be extracted, DefaultModelProblemCollector should be ModelProblemCollectorExt
*/
@Override
public TransformerContext initialize(ModelBuildingRequest request, ModelProblemCollector collector) {<FILL_FUNCTION_BODY>}
private boolean addEdge(Path from, Path p, DefaultModelProblemCollector problems) {
try {
dag.addEdge(from.toString(), p.toString());
return true;
} catch (Graph.CycleDetectedException e) {
problems.add(new DefaultModelProblem(
"Cycle detected between models at " + from + " and " + p,
ModelProblem.Severity.FATAL,
null,
null,
0,
0,
null,
e));
return false;
}
}
@Override
public TransformerContext build() {
return context;
}
public FileModelSource getSource(String groupId, String artifactId) {
Set<FileModelSource> sources = mappedSources.get(groupId + ":" + artifactId);
if (sources == null) {
return null;
}
return sources.stream()
.reduce((a, b) -> {
throw new IllegalStateException(String.format(
"No unique Source for %s:%s: %s and %s",
groupId, artifactId, a.getLocation(), b.getLocation()));
})
.orElse(null);
}
public void putSource(String groupId, String artifactId, FileModelSource source) {
mappedSources
.computeIfAbsent(groupId + ":" + artifactId, k -> new HashSet<>())
.add(source);
}
}
|
// We must assume the TransformerContext was created using this.newTransformerContextBuilder()
DefaultModelProblemCollector problems = (DefaultModelProblemCollector) collector;
return new TransformerContext() {
@Override
public Path locate(Path path) {
return context.locate(path);
}
@Override
public String getUserProperty(String key) {
return context.userProperties.computeIfAbsent(
key, k -> request.getUserProperties().getProperty(key));
}
@Override
public Model getRawModel(Path from, String gId, String aId) {
Model model = findRawModel(from, gId, aId);
if (model != null) {
context.modelByGA.put(new GAKey(gId, aId), new Holder(model));
context.modelByPath.put(model.getPomPath(), new Holder(model));
}
return model;
}
@Override
public Model getRawModel(Path from, Path path) {
Model model = findRawModel(from, path);
if (model != null) {
String groupId = defaultModelBuilder.getGroupId(model);
context.modelByGA.put(
new DefaultTransformerContext.GAKey(groupId, model.getArtifactId()), new Holder(model));
context.modelByPath.put(path, new Holder(model));
}
return model;
}
private Model findRawModel(Path from, String groupId, String artifactId) {
FileModelSource source = getSource(groupId, artifactId);
if (source == null) {
// we need to check the whole reactor in case it's a dependency
loadFullReactor();
source = getSource(groupId, artifactId);
}
if (source != null) {
if (!addEdge(from, source.getPath(), problems)) {
return null;
}
try {
ModelBuildingRequest gaBuildingRequest =
new DefaultModelBuildingRequest(request).setModelSource(source);
return defaultModelBuilder.readRawModel(gaBuildingRequest, problems);
} catch (ModelBuildingException e) {
// gathered with problem collector
}
}
return null;
}
private void loadFullReactor() {
if (!fullReactorLoaded) {
synchronized (DefaultTransformerContextBuilder.this) {
if (!fullReactorLoaded) {
doLoadFullReactor();
fullReactorLoaded = true;
}
}
}
}
private void doLoadFullReactor() {
Path rootDirectory = request.getRootDirectory();
if (rootDirectory == null) {
return;
}
List<Path> toLoad = new ArrayList<>();
Path root = defaultModelBuilder.getModelProcessor().locateExistingPom(rootDirectory);
toLoad.add(root);
while (!toLoad.isEmpty()) {
Path pom = toLoad.remove(0);
try {
ModelBuildingRequest gaBuildingRequest =
new DefaultModelBuildingRequest(request).setModelSource(new FileModelSource(pom));
Model rawModel = defaultModelBuilder.readFileModel(gaBuildingRequest, problems);
for (String module : rawModel.getModules()) {
Path moduleFile = defaultModelBuilder
.getModelProcessor()
.locateExistingPom(pom.getParent().resolve(module));
if (moduleFile != null) {
toLoad.add(moduleFile);
}
}
} catch (ModelBuildingException e) {
// gathered with problem collector
}
}
}
private Model findRawModel(Path from, Path p) {
if (!Files.isRegularFile(p)) {
throw new IllegalArgumentException("Not a regular file: " + p);
}
if (!addEdge(from, p, problems)) {
return null;
}
DefaultModelBuildingRequest req =
new DefaultModelBuildingRequest(request).setPomPath(p).setModelSource(new FileModelSource(p));
try {
return defaultModelBuilder.readRawModel(req, problems);
} catch (ModelBuildingException e) {
// gathered with problem collector
}
return null;
}
};
| 578
| 1,073
| 1,651
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/FileModelSource.java
|
FileModelSource
|
equals
|
class FileModelSource extends FileSource implements ModelSource3 {
/**
* Creates a new model source backed by the specified file.
*
* @param pomFile The POM file, must not be {@code null}.
* @deprecated Use {@link #FileModelSource(Path)} instead.
*/
@Deprecated
public FileModelSource(File pomFile) {
super(pomFile);
}
/**
* Creates a new model source backed by the specified file.
*
* @param pomPath The POM file, must not be {@code null}.
* @since 4.0.0
*/
public FileModelSource(Path pomPath) {
super(pomPath);
}
/**
*
* @return the file of this source
*
* @deprecated instead use {@link #getFile()}
*/
@Deprecated
public File getPomFile() {
return getFile();
}
@Override
public ModelSource3 getRelatedSource(ModelLocator locator, String relPath) {
relPath = relPath.replace('\\', File.separatorChar).replace('/', File.separatorChar);
Path path = getPath().getParent().resolve(relPath);
Path relatedPom = locator.locateExistingPom(path);
if (relatedPom != null) {
return new FileModelSource(relatedPom.normalize());
}
return null;
}
@Override
public URI getLocationURI() {
return getPath().toUri();
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return getPath().hashCode();
}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!FileModelSource.class.equals(obj.getClass())) {
return false;
}
FileModelSource other = (FileModelSource) obj;
return getPath().equals(other.getPath());
| 455
| 92
| 547
|
<methods>public void <init>(java.io.File) ,public void <init>(java.nio.file.Path) ,public boolean equals(java.lang.Object) ,public java.io.File getFile() ,public java.io.InputStream getInputStream() throws java.io.IOException,public java.lang.String getLocation() ,public java.nio.file.Path getPath() ,public int hashCode() ,public java.lang.String toString() <variables>private final non-sealed int hashCode,private final non-sealed java.nio.file.Path path
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/FileToRawModelMerger.java
|
FileToRawModelMerger
|
mergeModelBase_Dependencies
|
class FileToRawModelMerger extends MavenMerger {
@Override
protected void mergeBuild_Extensions(
Build.Builder builder, Build target, Build source, boolean sourceDominant, Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeBuildBase_Resources(
BuildBase.Builder builder,
BuildBase target,
BuildBase source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeBuildBase_TestResources(
BuildBase.Builder builder,
BuildBase target,
BuildBase source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeCiManagement_Notifiers(
CiManagement.Builder builder,
CiManagement target,
CiManagement source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeDependencyManagement_Dependencies(
DependencyManagement.Builder builder,
DependencyManagement target,
DependencyManagement source,
boolean sourceDominant,
Map<Object, Object> context) {
Iterator<Dependency> sourceIterator = source.getDependencies().iterator();
builder.dependencies(target.getDependencies().stream()
.map(d -> mergeDependency(d, sourceIterator.next(), sourceDominant, context))
.collect(Collectors.toList()));
}
@Override
protected void mergeDependency_Exclusions(
Dependency.Builder builder,
Dependency target,
Dependency source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeModel_Contributors(
Model.Builder builder, Model target, Model source, boolean sourceDominant, Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeModel_Developers(
Model.Builder builder, Model target, Model source, boolean sourceDominant, Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeModel_Licenses(
Model.Builder builder, Model target, Model source, boolean sourceDominant, Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeModel_MailingLists(
Model.Builder builder, Model target, Model source, boolean sourceDominant, Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeModel_Profiles(
Model.Builder builder, Model target, Model source, boolean sourceDominant, Map<Object, Object> context) {
Iterator<Profile> sourceIterator = source.getProfiles().iterator();
builder.profiles(target.getProfiles().stream()
.map(d -> mergeProfile(d, sourceIterator.next(), sourceDominant, context))
.collect(Collectors.toList()));
}
@Override
protected void mergeModelBase_Dependencies(
ModelBase.Builder builder,
ModelBase target,
ModelBase source,
boolean sourceDominant,
Map<Object, Object> context) {<FILL_FUNCTION_BODY>}
@Override
protected void mergeModelBase_PluginRepositories(
ModelBase.Builder builder,
ModelBase target,
ModelBase source,
boolean sourceDominant,
Map<Object, Object> context) {
builder.pluginRepositories(source.getPluginRepositories());
}
@Override
protected void mergeModelBase_Repositories(
ModelBase.Builder builder,
ModelBase target,
ModelBase source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergePlugin_Dependencies(
Plugin.Builder builder, Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context) {
Iterator<Dependency> sourceIterator = source.getDependencies().iterator();
builder.dependencies(target.getDependencies().stream()
.map(d -> mergeDependency(d, sourceIterator.next(), sourceDominant, context))
.collect(Collectors.toList()));
}
@Override
protected void mergePlugin_Executions(
Plugin.Builder builder, Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeReporting_Plugins(
Reporting.Builder builder,
Reporting target,
Reporting source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeReportPlugin_ReportSets(
ReportPlugin.Builder builder,
ReportPlugin target,
ReportPlugin source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergePluginContainer_Plugins(
PluginContainer.Builder builder,
PluginContainer target,
PluginContainer source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
}
|
Iterator<Dependency> sourceIterator = source.getDependencies().iterator();
builder.dependencies(target.getDependencies().stream()
.map(d -> mergeDependency(d, sourceIterator.next(), sourceDominant, context))
.collect(Collectors.toList()));
| 1,385
| 72
| 1,457
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/ModelBuildingException.java
|
ModelBuildingException
|
toMessage
|
class ModelBuildingException extends Exception {
private final ModelBuildingResult result;
/**
* Creates a new exception with the specified problems.
*
* @param model The model that could not be built, may be {@code null}.
* @param modelId The identifier of the model that could not be built, may be {@code null}.
* @param problems The problems that cause this exception, may be {@code null}.
* @deprecated Use {@link #ModelBuildingException(ModelBuildingResult)} instead.
*/
@Deprecated
public ModelBuildingException(Model model, String modelId, List<ModelProblem> problems) {
super(toMessage(modelId, problems));
if (model != null) {
DefaultModelBuildingResult tmp = new DefaultModelBuildingResult();
if (modelId == null) {
modelId = "";
}
tmp.addModelId(modelId);
tmp.setRawModel(modelId, model);
tmp.setProblems(problems);
result = tmp;
} else {
result = null;
}
}
/**
* Creates a new exception from the specified interim result and its associated problems.
*
* @param result The interim result, may be {@code null}.
*/
public ModelBuildingException(ModelBuildingResult result) {
super(toMessage(result));
this.result = result;
}
/**
* Gets the interim result of the model building up to the point where it failed.
*
* @return The interim model building result or {@code null} if not available.
*/
public ModelBuildingResult getResult() {
return result;
}
/**
* Gets the model that could not be built properly.
*
* @return The erroneous model or {@code null} if not available.
*/
public Model getModel() {
if (result == null) {
return null;
}
if (result.getEffectiveModel() != null) {
return result.getEffectiveModel();
}
return result.getRawModel();
}
/**
* Gets the identifier of the POM whose effective model could not be built. The general format of the identifier is
* {@code <groupId>:<artifactId>:<version>} but some of these coordinates may still be unknown at the point the
* exception is thrown so this information is merely meant to assist the user.
*
* @return The identifier of the POM or an empty string if not known, never {@code null}.
*/
public String getModelId() {
if (result == null || result.getModelIds().isEmpty()) {
return "";
}
return result.getModelIds().get(0);
}
/**
* Gets the problems that caused this exception.
*
* @return The problems that caused this exception, never {@code null}.
*/
public List<ModelProblem> getProblems() {
if (result == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(result.getProblems());
}
private static String toMessage(ModelBuildingResult result) {
if (result != null && !result.getModelIds().isEmpty()) {
return toMessage(result.getModelIds().get(0), result.getProblems());
}
return null;
}
// Package protected for test
static String toMessage(String modelId, List<ModelProblem> problems) {<FILL_FUNCTION_BODY>}
}
|
StringWriter buffer = new StringWriter(1024);
PrintWriter writer = new PrintWriter(buffer);
writer.print(problems.size());
writer.print((problems.size() == 1) ? " problem was " : " problems were ");
writer.print("encountered while building the effective model");
if (modelId != null && !modelId.isEmpty()) {
writer.print(" for ");
writer.print(modelId);
}
for (ModelProblem problem : problems) {
writer.println();
writer.print(" - [");
writer.print(problem.getSeverity());
writer.print("] ");
writer.print(problem.getMessage());
String location = ModelProblemUtils.formatLocation(problem, modelId);
if (!location.isEmpty()) {
writer.print(" @ ");
writer.print(location);
}
}
return buffer.toString();
| 877
| 235
| 1,112
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/ModelProblemUtils.java
|
ModelProblemUtils
|
toId
|
class ModelProblemUtils {
/**
* Creates a user-friendly source hint for the specified model.
*
* @param model The model to create a source hint for, may be {@code null}.
* @return The user-friendly source hint, never {@code null}.
*/
static String toSourceHint(Model model) {
if (model == null) {
return "";
}
StringBuilder buffer = new StringBuilder(128);
buffer.append(toId(model));
Path pomPath = model.getPomPath();
if (pomPath != null) {
buffer.append(" (").append(pomPath).append(')');
}
return buffer.toString();
}
static String toPath(Model model) {
String path = "";
if (model != null) {
Path pomPath = model.getPomPath();
if (pomPath != null) {
path = pomPath.toAbsolutePath().toString();
}
}
return path;
}
static String toId(Model model) {
if (model == null) {
return "";
}
return toId(model.getDelegate());
}
static String toId(org.apache.maven.api.model.Model model) {<FILL_FUNCTION_BODY>}
/**
* Creates a user-friendly artifact id from the specified coordinates.
*
* @param groupId The group id, may be {@code null}.
* @param artifactId The artifact id, may be {@code null}.
* @param version The version, may be {@code null}.
* @return The user-friendly artifact id, never {@code null}.
*/
static String toId(String groupId, String artifactId, String version) {
StringBuilder buffer = new StringBuilder(128);
buffer.append((groupId != null && !groupId.isEmpty()) ? groupId : "[unknown-group-id]");
buffer.append(':');
buffer.append((artifactId != null && !artifactId.isEmpty()) ? artifactId : "[unknown-artifact-id]");
buffer.append(':');
buffer.append((version != null && !version.isEmpty()) ? version : "[unknown-version]");
return buffer.toString();
}
/**
* Creates a string with all location details for the specified model problem. If the project identifier is
* provided, the generated location will omit the model id and source information and only give line/column
* information for problems originating directly from this POM.
*
* @param problem The problem whose location should be formatted, must not be {@code null}.
* @param projectId The {@code <groupId>:<artifactId>:<version>} of the corresponding project, may be {@code null}
* to force output of model id and source.
* @return The formatted problem location or an empty string if unknown, never {@code null}.
*/
public static String formatLocation(ModelProblem problem, String projectId) {
StringBuilder buffer = new StringBuilder(256);
if (!problem.getModelId().equals(projectId)) {
buffer.append(problem.getModelId());
if (!problem.getSource().isEmpty()) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append(problem.getSource());
}
}
if (problem.getLineNumber() > 0) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append("line ").append(problem.getLineNumber());
}
if (problem.getColumnNumber() > 0) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append("column ").append(problem.getColumnNumber());
}
return buffer.toString();
}
}
|
String groupId = model.getGroupId();
if (groupId == null && model.getParent() != null) {
groupId = model.getParent().getGroupId();
}
String artifactId = model.getArtifactId();
String version = model.getVersion();
if (version == null && model.getParent() != null) {
version = model.getParent().getVersion();
}
if (version == null) {
version = "[unknown-version]";
}
return toId(groupId, artifactId, version);
| 981
| 144
| 1,125
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/Result.java
|
Result
|
newResultSet
|
class Result<T> {
/**
* Success without warnings
*
* @param model
*/
public static <T> Result<T> success(T model) {
return success(model, Collections.emptyList());
}
/**
* Success with warnings
*
* @param model
* @param problems
*/
public static <T> Result<T> success(T model, Iterable<? extends ModelProblem> problems) {
assert !hasErrors(problems);
return new Result<>(false, model, problems);
}
/**
* Success with warnings
*
* @param model
* @param results
*/
public static <T> Result<T> success(T model, Result<?>... results) {
final List<ModelProblem> problemsList = new ArrayList<>();
for (Result<?> result1 : results) {
for (ModelProblem modelProblem : result1.getProblems()) {
problemsList.add(modelProblem);
}
}
return success(model, problemsList);
}
/**
* Error with problems describing the cause
*
* @param problems
*/
public static <T> Result<T> error(Iterable<? extends ModelProblem> problems) {
return error(null, problems);
}
public static <T> Result<T> error(T model) {
return error(model, Collections.emptyList());
}
public static <T> Result<T> error(Result<?> result) {
return error(result.getProblems());
}
public static <T> Result<T> error(Result<?>... results) {
final List<ModelProblem> problemsList = new ArrayList<>();
for (Result<?> result1 : results) {
for (ModelProblem modelProblem : result1.getProblems()) {
problemsList.add(modelProblem);
}
}
return error(problemsList);
}
/**
* Error with partial result and problems describing the cause
*
* @param model
* @param problems
*/
public static <T> Result<T> error(T model, Iterable<? extends ModelProblem> problems) {
return new Result<>(true, model, problems);
}
/**
* New result - determine whether error or success by checking problems for errors
*
* @param model
* @param problems
*/
public static <T> Result<T> newResult(T model, Iterable<? extends ModelProblem> problems) {
return new Result<>(hasErrors(problems), model, problems);
}
/**
* New result consisting of given result and new problem. Convenience for newResult(result.get(),
* concat(result.getProblems(),problems)).
*
* @param result
* @param problem
*/
public static <T> Result<T> addProblem(Result<T> result, ModelProblem problem) {
return addProblems(result, singleton(problem));
}
/**
* New result that includes the given
*
* @param result
* @param problems
*/
public static <T> Result<T> addProblems(Result<T> result, Iterable<? extends ModelProblem> problems) {
Collection<ModelProblem> list = new ArrayList<>();
for (ModelProblem item : problems) {
list.add(item);
}
for (ModelProblem item : result.getProblems()) {
list.add(item);
}
return new Result<>(result.hasErrors() || hasErrors(problems), result.get(), list);
}
public static <T> Result<T> addProblems(Result<T> result, Result<?>... results) {
final List<ModelProblem> problemsList = new ArrayList<>();
for (Result<?> result1 : results) {
for (ModelProblem modelProblem : result1.getProblems()) {
problemsList.add(modelProblem);
}
}
return addProblems(result, problemsList);
}
/**
* Turns the given results into a single result by combining problems and models into single collection.
*
* @param results
*/
public static <T> Result<Iterable<T>> newResultSet(Iterable<? extends Result<? extends T>> results) {<FILL_FUNCTION_BODY>}
// helper to determine if problems contain error
private static boolean hasErrors(Iterable<? extends ModelProblem> problems) {
for (ModelProblem input : problems) {
if (input.getSeverity().equals(ERROR) || input.getSeverity().equals(FATAL)) {
return true;
}
}
return false;
}
/**
* Class definition
*/
private final boolean errors;
private final T value;
private final Iterable<? extends ModelProblem> problems;
private Result(boolean errors, T model, Iterable<? extends ModelProblem> problems) {
this.errors = errors;
this.value = model;
this.problems = problems;
}
public Iterable<? extends ModelProblem> getProblems() {
return problems;
}
public T get() {
return value;
}
public boolean hasErrors() {
return errors;
}
}
|
boolean hasErrors = false;
List<T> modelsList = new ArrayList<>();
List<ModelProblem> problemsList = new ArrayList<>();
for (Result<? extends T> result : results) {
modelsList.add(result.get());
for (ModelProblem modelProblem : result.getProblems()) {
problemsList.add(modelProblem);
}
if (result.hasErrors()) {
hasErrors = true;
}
}
return new Result<>(hasErrors, (Iterable<T>) modelsList, problemsList);
| 1,377
| 146
| 1,523
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/composition/DefaultDependencyManagementImporter.java
|
DefaultDependencyManagementImporter
|
equals
|
class DefaultDependencyManagementImporter implements DependencyManagementImporter {
@Override
public Model importManagement(
Model target,
List<? extends DependencyManagement> sources,
ModelBuildingRequest request,
ModelProblemCollector problems) {
if (sources != null && !sources.isEmpty()) {
Map<String, Dependency> dependencies = new LinkedHashMap<>();
DependencyManagement depMgmt = target.getDependencyManagement();
if (depMgmt != null) {
for (Dependency dependency : depMgmt.getDependencies()) {
dependencies.put(dependency.getManagementKey(), dependency);
}
} else {
depMgmt = DependencyManagement.newInstance();
}
Set<String> directDependencies = new HashSet<>(dependencies.keySet());
for (DependencyManagement source : sources) {
for (Dependency dependency : source.getDependencies()) {
String key = dependency.getManagementKey();
Dependency present = dependencies.putIfAbsent(key, dependency);
if (present != null && !equals(dependency, present) && !directDependencies.contains(key)) {
// TODO: https://issues.apache.org/jira/browse/MNG-8004
problems.add(new ModelProblemCollectorRequest(
ModelProblem.Severity.WARNING, ModelProblem.Version.V40)
.setMessage("Ignored POM import for: " + toString(dependency) + " as already imported "
+ toString(present) + ". Add a the conflicting managed dependency directly "
+ "to the dependencyManagement section of the POM."));
}
}
}
return target.withDependencyManagement(depMgmt.withDependencies(dependencies.values()));
}
return target;
}
private String toString(Dependency dependency) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder
.append(dependency.getGroupId())
.append(":")
.append(dependency.getArtifactId())
.append(":")
.append(dependency.getType());
if (dependency.getClassifier() != null && !dependency.getClassifier().isEmpty()) {
stringBuilder.append(":").append(dependency.getClassifier());
}
stringBuilder
.append(":")
.append(dependency.getVersion())
.append("@")
.append(dependency.getScope() == null ? "compile" : dependency.getScope());
if (dependency.isOptional()) {
stringBuilder.append("[optional]");
}
if (!dependency.getExclusions().isEmpty()) {
stringBuilder.append("[").append(dependency.getExclusions().size()).append(" exclusions]");
}
return stringBuilder.toString();
}
private boolean equals(Dependency d1, Dependency d2) {<FILL_FUNCTION_BODY>}
private boolean equals(Collection<Exclusion> ce1, Collection<Exclusion> ce2) {
if (ce1.size() == ce2.size()) {
Iterator<Exclusion> i1 = ce1.iterator();
Iterator<Exclusion> i2 = ce2.iterator();
while (i1.hasNext() && i2.hasNext()) {
if (!equals(i1.next(), i2.next())) {
return false;
}
}
return !i1.hasNext() && !i2.hasNext();
}
return false;
}
private boolean equals(Exclusion e1, Exclusion e2) {
return Objects.equals(e1.getGroupId(), e2.getGroupId())
&& Objects.equals(e1.getArtifactId(), e2.getArtifactId());
}
}
|
return Objects.equals(d1.getGroupId(), d2.getGroupId())
&& Objects.equals(d1.getArtifactId(), d2.getArtifactId())
&& Objects.equals(d1.getVersion(), d2.getVersion())
&& Objects.equals(d1.getType(), d2.getType())
&& Objects.equals(d1.getClassifier(), d2.getClassifier())
&& Objects.equals(d1.getScope(), d2.getScope())
&& Objects.equals(d1.getSystemPath(), d2.getSystemPath())
&& Objects.equals(d1.getOptional(), d2.getOptional())
&& equals(d1.getExclusions(), d2.getExclusions());
| 945
| 192
| 1,137
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/BuildTimestampValueSource.java
|
BuildTimestampValueSource
|
getValue
|
class BuildTimestampValueSource extends AbstractValueSource {
private final Date startTime;
private final Map<String, String> properties;
BuildTimestampValueSource(Date startTime, Map<String, String> properties) {
super(false);
this.startTime = startTime;
this.properties = properties;
}
@Override
public Object getValue(String expression) {<FILL_FUNCTION_BODY>}
}
|
if ("build.timestamp".equals(expression) || "maven.build.timestamp".equals(expression)) {
return new MavenBuildTimestamp(startTime, properties).formattedTimestamp();
}
return null;
| 109
| 54
| 163
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/DefaultModelVersionProcessor.java
|
DefaultModelVersionProcessor
|
overwriteModelProperties
|
class DefaultModelVersionProcessor implements ModelVersionProcessor {
private static final String SHA1_PROPERTY = "sha1";
private static final String CHANGELIST_PROPERTY = "changelist";
private static final String REVISION_PROPERTY = "revision";
@Override
public boolean isValidProperty(String property) {
return REVISION_PROPERTY.equals(property)
|| CHANGELIST_PROPERTY.equals(property)
|| SHA1_PROPERTY.equals(property);
}
@Override
public void overwriteModelProperties(Properties modelProperties, ModelBuildingRequest request) {<FILL_FUNCTION_BODY>}
}
|
if (request.getUserProperties().containsKey(REVISION_PROPERTY)) {
modelProperties.put(REVISION_PROPERTY, request.getUserProperties().get(REVISION_PROPERTY));
}
if (request.getUserProperties().containsKey(CHANGELIST_PROPERTY)) {
modelProperties.put(CHANGELIST_PROPERTY, request.getUserProperties().get(CHANGELIST_PROPERTY));
}
if (request.getUserProperties().containsKey(SHA1_PROPERTY)) {
modelProperties.put(SHA1_PROPERTY, request.getUserProperties().get(SHA1_PROPERTY));
}
| 176
| 177
| 353
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/ObjectBasedValueSource.java
|
ObjectBasedValueSource
|
getValue
|
class ObjectBasedValueSource extends AbstractValueSource {
private final Object root;
/**
* Construct a new value source, using the supplied object as the root from
* which to start, and using expressions split at the dot ('.') to navigate
* the object graph beneath this root.
* @param root the root of the graph.
*/
public ObjectBasedValueSource(Object root) {
super(true);
this.root = root;
}
/**
* <p>Split the expression into parts, tokenized on the dot ('.') character. Then,
* starting at the root object contained in this value source, apply each part
* to the object graph below this root, using either 'getXXX()' or 'isXXX()'
* accessor types to resolve the value for each successive expression part.
* Finally, return the result of the last expression part's resolution.</p>
*
* <p><b>NOTE:</b> The object-graph nagivation actually takes place via the
* {@link ReflectionValueExtractor} class.</p>
*/
public Object getValue(String expression) {<FILL_FUNCTION_BODY>}
}
|
if (expression == null || expression.trim().isEmpty()) {
return null;
}
try {
return ReflectionValueExtractor.evaluate(expression, root, false);
} catch (Exception e) {
addFeedback("Failed to extract \'" + expression + "\' from: " + root, e);
}
return null;
| 297
| 91
| 388
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.