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-model-builder/src/main/java/org/apache/maven/model/interpolation/PathTranslatingPostProcessor.java
|
PathTranslatingPostProcessor
|
execute
|
class PathTranslatingPostProcessor implements InterpolationPostProcessor {
private final Collection<String> unprefixedPathKeys;
private final Path projectDir;
private final PathTranslator pathTranslator;
private final List<String> expressionPrefixes;
PathTranslatingPostProcessor(
List<String> expressionPrefixes,
Collection<String> unprefixedPathKeys,
Path projectDir,
PathTranslator pathTranslator) {
this.expressionPrefixes = expressionPrefixes;
this.unprefixedPathKeys = unprefixedPathKeys;
this.projectDir = projectDir;
this.pathTranslator = pathTranslator;
}
@Override
public Object execute(String expression, Object value) {<FILL_FUNCTION_BODY>}
}
|
if (value != null) {
expression = ValueSourceUtils.trimPrefix(expression, expressionPrefixes, true);
if (unprefixedPathKeys.contains(expression)) {
return pathTranslator.alignToBaseDirectory(String.valueOf(value), projectDir);
}
}
return null;
| 200
| 83
| 283
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/ProblemDetectingValueSource.java
|
ProblemDetectingValueSource
|
getValue
|
class ProblemDetectingValueSource implements ValueSource {
private final ValueSource valueSource;
private final String bannedPrefix;
private final String newPrefix;
private final ModelProblemCollector problems;
ProblemDetectingValueSource(
ValueSource valueSource, String bannedPrefix, String newPrefix, ModelProblemCollector problems) {
this.valueSource = valueSource;
this.bannedPrefix = bannedPrefix;
this.newPrefix = newPrefix;
this.problems = problems;
}
@Override
public Object getValue(String expression) {<FILL_FUNCTION_BODY>}
@Override
public List getFeedback() {
return valueSource.getFeedback();
}
@Override
public void clearFeedback() {
valueSource.clearFeedback();
}
}
|
Object value = valueSource.getValue(expression);
if (value != null && expression.startsWith(bannedPrefix)) {
String msg = "The expression ${" + expression + "} is deprecated.";
if (newPrefix != null && !newPrefix.isEmpty()) {
msg += " Please use ${" + newPrefix + expression.substring(bannedPrefix.length()) + "} instead.";
}
problems.add(new ModelProblemCollectorRequest(Severity.WARNING, Version.V20).setMessage(msg));
}
return value;
| 214
| 146
| 360
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/StringVisitorModelInterpolator.java
|
StringVisitorModelInterpolator
|
interpolateModel
|
class StringVisitorModelInterpolator extends AbstractStringBasedModelInterpolator {
@Inject
public StringVisitorModelInterpolator(
PathTranslator pathTranslator, UrlNormalizer urlNormalizer, RootLocator rootLocator) {
super(pathTranslator, urlNormalizer, rootLocator);
}
interface InnerInterpolator {
String interpolate(String value);
}
@Deprecated
@Override
public Model interpolateModel(
Model model, File projectDir, ModelBuildingRequest config, ModelProblemCollector problems) {
return interpolateModel(model, projectDir != null ? projectDir.toPath() : null, config, problems);
}
@Override
public Model interpolateModel(
Model model, Path projectDir, ModelBuildingRequest config, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
private InnerInterpolator createInterpolator(
List<? extends ValueSource> valueSources,
List<? extends InterpolationPostProcessor> postProcessors,
final ModelProblemCollector problems,
ModelBuildingRequest config) {
final Map<String, String> cache = new HashMap<>();
final StringSearchInterpolator interpolator = new StringSearchInterpolator();
interpolator.setCacheAnswers(true);
for (ValueSource vs : valueSources) {
interpolator.addValueSource(vs);
}
for (InterpolationPostProcessor postProcessor : postProcessors) {
interpolator.addPostProcessor(postProcessor);
}
final RecursionInterceptor recursionInterceptor = createRecursionInterceptor(config);
return value -> {
if (value != null && value.contains("${")) {
String c = cache.get(value);
if (c == null) {
try {
c = interpolator.interpolate(value, recursionInterceptor);
} catch (InterpolationException e) {
problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
.setMessage(e.getMessage())
.setException(e));
}
cache.put(value, c);
}
return c;
}
return value;
};
}
}
|
List<? extends ValueSource> valueSources = createValueSources(model, projectDir, config, problems);
List<? extends InterpolationPostProcessor> postProcessors = createPostProcessors(model, projectDir, config);
InnerInterpolator innerInterpolator = createInterpolator(valueSources, postProcessors, problems, config);
return new MavenTransformer(innerInterpolator::interpolate).visit(model);
| 571
| 112
| 683
|
<methods>public void <init>(org.apache.maven.model.path.PathTranslator, org.apache.maven.model.path.UrlNormalizer, org.apache.maven.model.root.RootLocator) ,public org.apache.maven.model.Model interpolateModel(org.apache.maven.model.Model, java.io.File, org.apache.maven.model.building.ModelBuildingRequest, org.apache.maven.model.building.ModelProblemCollector) ,public org.apache.maven.model.Model interpolateModel(org.apache.maven.model.Model, java.nio.file.Path, org.apache.maven.model.building.ModelBuildingRequest, org.apache.maven.model.building.ModelProblemCollector) <variables>private static final java.lang.String PREFIX_POM,private static final java.lang.String PREFIX_PROJECT,private static final List<java.lang.String> PROJECT_PREFIXES_3_1,private static final List<java.lang.String> PROJECT_PREFIXES_4_0,private static final non-sealed Collection<java.lang.String> TRANSLATED_PATH_EXPRESSIONS,private final non-sealed org.apache.maven.model.path.PathTranslator pathTranslator,private final non-sealed org.apache.maven.model.root.RootLocator rootLocator,private final non-sealed org.apache.maven.model.path.UrlNormalizer urlNormalizer
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/UrlNormalizingPostProcessor.java
|
UrlNormalizingPostProcessor
|
execute
|
class UrlNormalizingPostProcessor implements InterpolationPostProcessor {
private static final Set<String> URL_EXPRESSIONS;
static {
Set<String> expressions = new HashSet<>();
expressions.add("project.url");
expressions.add("project.scm.url");
expressions.add("project.scm.connection");
expressions.add("project.scm.developerConnection");
expressions.add("project.distributionManagement.site.url");
URL_EXPRESSIONS = expressions;
}
private UrlNormalizer normalizer;
UrlNormalizingPostProcessor(UrlNormalizer normalizer) {
this.normalizer = normalizer;
}
@Override
public Object execute(String expression, Object value) {<FILL_FUNCTION_BODY>}
}
|
if (value != null && URL_EXPRESSIONS.contains(expression)) {
return normalizer.normalize(value.toString());
}
return null;
| 204
| 46
| 250
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/reflection/ReflectionValueExtractor.java
|
Tokenizer
|
evaluate
|
class Tokenizer {
final String expression;
int idx;
Tokenizer(String expression) {
this.expression = expression;
}
public int peekChar() {
return idx < expression.length() ? expression.charAt(idx) : EOF;
}
public int skipChar() {
return idx < expression.length() ? expression.charAt(idx++) : EOF;
}
public String nextToken(char delimiter) {
int start = idx;
while (idx < expression.length() && delimiter != expression.charAt(idx)) {
idx++;
}
// delimiter MUST be present
if (idx <= start || idx >= expression.length()) {
return null;
}
return expression.substring(start, idx++);
}
public String nextPropertyName() {
final int start = idx;
while (idx < expression.length() && Character.isJavaIdentifierPart(expression.charAt(idx))) {
idx++;
}
// property name does not require delimiter
if (idx <= start || idx > expression.length()) {
return null;
}
return expression.substring(start, idx);
}
public int getPosition() {
return idx < expression.length() ? idx : EOF;
}
// to make tokenizer look pretty in debugger
@Override
public String toString() {
return idx < expression.length() ? expression.substring(idx) : "<EOF>";
}
}
private ReflectionValueExtractor() {}
/**
* <p>The implementation supports indexed, nested and mapped properties.</p>
* <ul>
* <li>nested properties should be defined by a dot, i.e. "user.address.street"</li>
* <li>indexed properties (java.util.List or array instance) should be contains <code>(\\w+)\\[(\\d+)\\]</code>
* pattern, i.e. "user.addresses[1].street"</li>
* <li>mapped properties should be contains <code>(\\w+)\\((.+)\\)</code> pattern,
* i.e. "user.addresses(myAddress).street"</li>
* </ul>
*
* @param expression not null expression
* @param root not null object
* @return the object defined by the expression
* @throws IntrospectionException if any
*/
public static Object evaluate(@Nonnull String expression, @Nullable Object root) throws IntrospectionException {
return evaluate(expression, root, true);
}
/**
* <p>
* The implementation supports indexed, nested and mapped properties.
* </p>
* <ul>
* <li>nested properties should be defined by a dot, i.e. "user.address.street"</li>
* <li>indexed properties (java.util.List or array instance) should be contains <code>(\\w+)\\[(\\d+)\\]</code>
* pattern, i.e. "user.addresses[1].street"</li>
* <li>mapped properties should be contains <code>(\\w+)\\((.+)\\)</code> pattern, i.e.
* "user.addresses(myAddress).street"</li>
* </ul>
*
* @param expression not null expression
* @param root not null object
* @param trimRootToken trim root token yes/no.
* @return the object defined by the expression
* @throws IntrospectionException if any
*/
public static Object evaluate(@Nonnull String expression, @Nullable Object root, boolean trimRootToken)
throws IntrospectionException {<FILL_FUNCTION_BODY>
|
Object value = root;
// ----------------------------------------------------------------------
// Walk the dots and retrieve the ultimate value desired from the
// MavenProject instance.
// ----------------------------------------------------------------------
if (expression == null || expression.isEmpty() || !Character.isJavaIdentifierStart(expression.charAt(0))) {
return null;
}
boolean hasDots = expression.indexOf(PROPERTY_START) >= 0;
final Tokenizer tokenizer;
if (trimRootToken && hasDots) {
tokenizer = new Tokenizer(expression);
tokenizer.nextPropertyName();
if (tokenizer.getPosition() == EOF) {
return null;
}
} else {
tokenizer = new Tokenizer("." + expression);
}
int propertyPosition = tokenizer.getPosition();
while (value != null && tokenizer.peekChar() != EOF) {
switch (tokenizer.skipChar()) {
case INDEXED_START:
value = getIndexedValue(
expression,
propertyPosition,
tokenizer.getPosition(),
value,
tokenizer.nextToken(INDEXED_END));
break;
case MAPPED_START:
value = getMappedValue(
expression,
propertyPosition,
tokenizer.getPosition(),
value,
tokenizer.nextToken(MAPPED_END));
break;
case PROPERTY_START:
propertyPosition = tokenizer.getPosition();
value = getPropertyValue(value, tokenizer.nextPropertyName());
break;
default:
// could not parse expression
return null;
}
}
if (value instanceof Optional) {
value = ((Optional<?>) value).orElse(null);
}
return value;
| 975
| 449
| 1,424
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/io/DefaultModelReader.java
|
DefaultModelReader
|
read
|
class DefaultModelReader implements ModelReader {
private final ModelSourceTransformer transformer;
@Inject
public DefaultModelReader(ModelSourceTransformer transformer) {
this.transformer = transformer;
}
@Override
public Model read(File input, Map<String, ?> options) throws IOException {
Objects.requireNonNull(input, "input cannot be null");
return read(input.toPath(), options);
}
@Override
public Model read(Path path, Map<String, ?> options) throws IOException {
Objects.requireNonNull(path, "path cannot be null");
try (InputStream in = Files.newInputStream(path)) {
Model model = read(in, path, options);
model.setPomPath(path);
return model;
}
}
@Override
public Model read(Reader input, Map<String, ?> options) throws IOException {
Objects.requireNonNull(input, "input cannot be null");
try (Reader in = input) {
return read(in, null, options);
}
}
@Override
public Model read(InputStream input, Map<String, ?> options) throws IOException {
Objects.requireNonNull(input, "input cannot be null");
try (InputStream in = input) {
return read(input, null, options);
}
}
private boolean isStrict(Map<String, ?> options) {
Object value = (options != null) ? options.get(IS_STRICT) : null;
return value == null || Boolean.parseBoolean(value.toString());
}
private InputSource getSource(Map<String, ?> options) {
Object value = (options != null) ? options.get(INPUT_SOURCE) : null;
return (InputSource) value;
}
private Path getRootDirectory(Map<String, ?> options) {
Object value = (options != null) ? options.get(ROOT_DIRECTORY) : null;
return (Path) value;
}
private Model read(InputStream input, Path pomFile, Map<String, ?> options) throws IOException {<FILL_FUNCTION_BODY>}
private Model read(Reader reader, Path pomFile, Map<String, ?> options) throws IOException {
try {
XMLInputFactory factory = new com.ctc.wstx.stax.WstxInputFactory();
factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
XMLStreamReader parser = factory.createXMLStreamReader(reader);
InputSource source = getSource(options);
boolean strict = isStrict(options);
MavenStaxReader mr = new MavenStaxReader();
mr.setAddLocationInformation(source != null);
Model model = new Model(mr.read(parser, strict, source != null ? source.toApiSource() : null));
return model;
} catch (XMLStreamException e) {
Location location = e.getLocation();
throw new ModelParseException(
e.getMessage(),
location != null ? location.getLineNumber() : -1,
location != null ? location.getColumnNumber() : -1,
e);
} catch (Exception e) {
throw new IOException("Unable to transform pom", e);
}
}
}
|
try {
XMLInputFactory factory = new com.ctc.wstx.stax.WstxInputFactory();
factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
XMLStreamReader parser = factory.createXMLStreamReader(input);
InputSource source = getSource(options);
boolean strict = isStrict(options);
MavenStaxReader mr = new MavenStaxReader();
mr.setAddLocationInformation(source != null);
Model model = new Model(mr.read(parser, strict, source != null ? source.toApiSource() : null));
return model;
} catch (XMLStreamException e) {
Location location = e.getLocation();
throw new ModelParseException(
e.getMessage(),
location != null ? location.getLineNumber() : -1,
location != null ? location.getColumnNumber() : -1,
e);
} catch (Exception e) {
throw new IOException("Unable to transform pom", e);
}
| 848
| 267
| 1,115
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/io/DefaultModelWriter.java
|
DefaultModelWriter
|
write
|
class DefaultModelWriter implements ModelWriter {
@Override
public void write(File output, Map<String, Object> options, Model model) throws IOException {
Objects.requireNonNull(output, "output cannot be null");
Objects.requireNonNull(model, "model cannot be null");
output.getParentFile().mkdirs();
write(new XmlStreamWriter(Files.newOutputStream(output.toPath())), options, model);
}
@Override
public void write(Writer output, Map<String, Object> options, Model model) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void write(OutputStream output, Map<String, Object> options, Model model) throws IOException {
Objects.requireNonNull(output, "output cannot be null");
Objects.requireNonNull(model, "model cannot be null");
String encoding = model.getModelEncoding();
if (encoding == null || encoding.isEmpty()) {
encoding = "UTF-8";
}
try (Writer out = new OutputStreamWriter(output, encoding)) {
write(out, options, model);
}
}
@Override
public void write(File output, Map<String, Object> options, org.apache.maven.model.Model model) throws IOException {
write(output, options, model.getDelegate());
}
@Override
public void write(Writer output, Map<String, Object> options, org.apache.maven.model.Model model)
throws IOException {
write(output, options, model.getDelegate());
}
@Override
public void write(OutputStream output, Map<String, Object> options, org.apache.maven.model.Model model)
throws IOException {
write(output, options, model.getDelegate());
}
}
|
Objects.requireNonNull(output, "output cannot be null");
Objects.requireNonNull(model, "model cannot be null");
try (Writer out = output) {
new MavenStaxWriter().write(out, model);
} catch (XMLStreamException e) {
throw new IOException(e);
}
| 448
| 85
| 533
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/locator/DefaultModelLocator.java
|
DefaultModelLocator
|
locateExistingPom
|
class DefaultModelLocator implements ModelLocator {
@Deprecated
@Override
public File locatePom(File projectDirectory) {
Path path = locatePom(projectDirectory != null ? projectDirectory.toPath() : null);
return path != null ? path.toFile() : null;
}
@Override
public Path locatePom(Path projectDirectory) {
return projectDirectory != null ? projectDirectory : Paths.get(System.getProperty("user.dir"));
}
@Deprecated
@Override
public File locateExistingPom(File project) {
Path path = locateExistingPom(project != null ? project.toPath() : null);
return path != null ? path.toFile() : null;
}
@Override
public Path locateExistingPom(Path project) {<FILL_FUNCTION_BODY>}
}
|
if (project == null || Files.isDirectory(project)) {
project = locatePom(project);
}
if (Files.isDirectory(project)) {
Path pom = project.resolve("pom.xml");
return Files.isRegularFile(pom) ? pom : null;
} else if (Files.isRegularFile(project)) {
return project;
} else {
return null;
}
| 224
| 112
| 336
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/management/DefaultDependencyManagementInjector.java
|
ManagementModelMerger
|
mergeManagedDependencies
|
class ManagementModelMerger extends MavenModelMerger {
public Model mergeManagedDependencies(Model model) {<FILL_FUNCTION_BODY>}
@Override
protected void mergeDependency_Optional(
Dependency.Builder builder,
Dependency target,
Dependency source,
boolean sourceDominant,
Map<Object, Object> context) {
// optional flag is not managed
}
@Override
protected void mergeDependency_Exclusions(
Dependency.Builder builder,
Dependency target,
Dependency source,
boolean sourceDominant,
Map<Object, Object> context) {
List<Exclusion> tgt = target.getExclusions();
if (tgt.isEmpty()) {
List<Exclusion> src = source.getExclusions();
builder.exclusions(src);
}
}
}
|
DependencyManagement dependencyManagement = model.getDependencyManagement();
if (dependencyManagement != null) {
Map<Object, Dependency> dependencies = new HashMap<>();
Map<Object, Object> context = Collections.emptyMap();
for (Dependency dependency : model.getDependencies()) {
Object key = getDependencyKey().apply(dependency);
dependencies.put(key, dependency);
}
boolean modified = false;
for (Dependency managedDependency : dependencyManagement.getDependencies()) {
Object key = getDependencyKey().apply(managedDependency);
Dependency dependency = dependencies.get(key);
if (dependency != null) {
Dependency merged = mergeDependency(dependency, managedDependency, false, context);
if (merged != dependency) {
dependencies.put(key, merged);
modified = true;
}
}
}
if (modified) {
List<Dependency> newDeps = new ArrayList<>(dependencies.size());
for (Dependency dep : model.getDependencies()) {
Object key = getDependencyKey().apply(dep);
Dependency dependency = dependencies.get(key);
newDeps.add(dependency);
}
return Model.newBuilder(model).dependencies(newDeps).build();
}
}
return model;
| 225
| 331
| 556
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/management/DefaultPluginManagementInjector.java
|
ManagementModelMerger
|
mergePluginContainerPlugins
|
class ManagementModelMerger extends MavenModelMerger {
public Model mergeManagedBuildPlugins(Model model) {
Build build = model.getBuild();
if (build != null) {
PluginManagement pluginManagement = build.getPluginManagement();
if (pluginManagement != null) {
return model.withBuild(mergePluginContainerPlugins(build, pluginManagement));
}
}
return model;
}
private Build mergePluginContainerPlugins(Build target, PluginContainer source) {<FILL_FUNCTION_BODY>}
@Override
protected void mergePlugin_Executions(
Plugin.Builder builder,
Plugin target,
Plugin source,
boolean sourceDominant,
Map<Object, Object> context) {
List<PluginExecution> src = source.getExecutions();
if (!src.isEmpty()) {
List<PluginExecution> tgt = target.getExecutions();
Map<Object, PluginExecution> merged = new LinkedHashMap<>((src.size() + tgt.size()) * 2);
for (PluginExecution element : src) {
Object key = getPluginExecutionKey().apply(element);
merged.put(key, element);
}
for (PluginExecution element : tgt) {
Object key = getPluginExecutionKey().apply(element);
PluginExecution existing = merged.get(key);
if (existing != null) {
element = mergePluginExecution(element, existing, sourceDominant, context);
}
merged.put(key, element);
}
builder.executions(merged.values());
}
}
}
|
List<Plugin> src = source.getPlugins();
if (!src.isEmpty()) {
Map<Object, Plugin> managedPlugins = new LinkedHashMap<>(src.size() * 2);
Map<Object, Object> context = Collections.emptyMap();
for (Plugin element : src) {
Object key = getPluginKey().apply(element);
managedPlugins.put(key, element);
}
List<Plugin> newPlugins = new ArrayList<>();
for (Plugin element : target.getPlugins()) {
Object key = getPluginKey().apply(element);
Plugin managedPlugin = managedPlugins.get(key);
if (managedPlugin != null) {
element = mergePlugin(element, managedPlugin, false, context);
}
newPlugins.add(element);
}
return target.withPlugins(newPlugins);
}
return target;
| 418
| 240
| 658
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/merge/MavenModelMerger.java
|
MavenModelMerger
|
merge
|
class MavenModelMerger extends org.apache.maven.internal.impl.model.MavenModelMerger {
/**
* Merges the specified source object into the given target object.
*
* @param target The target object whose existing contents should be merged with the source, must not be
* <code>null</code>.
* @param source The (read-only) source object that should be merged into the target object, may be
* <code>null</code>.
* @param sourceDominant A flag indicating whether either the target object or the source object provides the
* dominant data.
* @param hints A set of key-value pairs that customized merger implementations can use to carry domain-specific
* information along, may be <code>null</code>.
*/
public void merge(
org.apache.maven.model.Model target,
org.apache.maven.model.Model source,
boolean sourceDominant,
Map<?, ?> hints) {<FILL_FUNCTION_BODY>}
}
|
Objects.requireNonNull(target, "target cannot be null");
if (source == null) {
return;
}
target.update(merge(target.getDelegate(), source.getDelegate(), sourceDominant, hints));
| 263
| 61
| 324
|
<methods>public void <init>() ,public Model merge(Model, Model, boolean, Map<?,?>) <variables>public static final java.lang.String ARTIFACT_ID,public static final java.lang.String CHILD_PATH_ADJUSTMENT
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/normalization/DefaultModelNormalizer.java
|
DefaultModelNormalizer
|
mergeDuplicates
|
class DefaultModelNormalizer implements ModelNormalizer {
private DuplicateMerger merger = new DuplicateMerger();
@Override
public void mergeDuplicates(
org.apache.maven.model.Model model, ModelBuildingRequest request, ModelProblemCollector problems) {
model.update(mergeDuplicates(model.getDelegate(), request, problems));
}
@Override
public void injectDefaultValues(
org.apache.maven.model.Model model, ModelBuildingRequest request, ModelProblemCollector problems) {
model.update(injectDefaultValues(model.getDelegate(), request, problems));
}
@Override
public Model mergeDuplicates(Model model, ModelBuildingRequest request, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
/**
* DuplicateMerger
*/
protected static class DuplicateMerger extends MavenModelMerger {
public Plugin mergePlugin(Plugin target, Plugin source) {
return super.mergePlugin(target, source, false, Collections.emptyMap());
}
}
@Override
public Model injectDefaultValues(Model model, ModelBuildingRequest request, ModelProblemCollector problems) {
Model.Builder builder = Model.newBuilder(model);
builder.dependencies(injectList(model.getDependencies(), this::injectDependency));
Build build = model.getBuild();
if (build != null) {
Build newBuild = Build.newBuilder(build)
.plugins(injectList(build.getPlugins(), this::injectPlugin))
.build();
builder.build(newBuild != build ? newBuild : null);
}
return builder.build();
}
private Plugin injectPlugin(Plugin p) {
return Plugin.newBuilder(p)
.dependencies(injectList(p.getDependencies(), this::injectDependency))
.build();
}
private Dependency injectDependency(Dependency d) {
// we cannot set this directly in the MDO due to the interactions with dependency management
return (d.getScope() == null || d.getScope().isEmpty()) ? d.withScope("compile") : d;
}
/**
* Returns a list suited for the builders, i.e. null if not modified
*/
private <T> List<T> injectList(List<T> list, Function<T, T> modifer) {
List<T> newList = null;
for (int i = 0; i < list.size(); i++) {
T oldT = list.get(i);
T newT = modifer.apply(oldT);
if (newT != oldT) {
if (newList == null) {
newList = new ArrayList<>(list);
}
newList.set(i, newT);
}
}
return newList;
}
}
|
Model.Builder builder = Model.newBuilder(model);
Build build = model.getBuild();
if (build != null) {
List<Plugin> plugins = build.getPlugins();
Map<Object, Plugin> normalized = new LinkedHashMap<>(plugins.size() * 2);
for (Plugin plugin : plugins) {
Object key = plugin.getKey();
Plugin first = normalized.get(key);
if (first != null) {
plugin = merger.mergePlugin(plugin, first);
}
normalized.put(key, plugin);
}
if (plugins.size() != normalized.size()) {
builder.build(
Build.newBuilder(build).plugins(normalized.values()).build());
}
}
/*
* NOTE: This is primarily to keep backward-compat with Maven 2.x which did not validate that dependencies are
* unique within a single POM. Upon multiple declarations, 2.x just kept the last one but retained the order of
* the first occurrence. So when we're in lenient/compat mode, we have to deal with such broken POMs and mimic
* the way 2.x works. When we're in strict mode, the removal of duplicates just saves other merging steps from
* aftereffects and bogus error messages.
*/
List<Dependency> dependencies = model.getDependencies();
Map<String, Dependency> normalized = new LinkedHashMap<>(dependencies.size() * 2);
for (Dependency dependency : dependencies) {
normalized.put(dependency.getManagementKey(), dependency);
}
if (dependencies.size() != normalized.size()) {
builder.dependencies(normalized.values());
}
return builder.build();
| 728
| 448
| 1,176
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/path/DefaultModelPathTranslator.java
|
DefaultModelPathTranslator
|
alignToBaseDirectory
|
class DefaultModelPathTranslator implements ModelPathTranslator {
private final PathTranslator pathTranslator;
@Inject
public DefaultModelPathTranslator(PathTranslator pathTranslator) {
this.pathTranslator = pathTranslator;
}
@Deprecated
@Override
public void alignToBaseDirectory(org.apache.maven.model.Model modelV3, File basedir, ModelBuildingRequest request) {
if (modelV3 == null || basedir == null) {
return;
}
alignToBaseDirectory(modelV3, basedir.toPath(), request);
}
@Override
public void alignToBaseDirectory(org.apache.maven.model.Model modelV3, Path basedir, ModelBuildingRequest request) {
if (modelV3 == null || basedir == null) {
return;
}
Model model = modelV3.getDelegate();
Build build = model.getBuild();
Build newBuild = null;
if (build != null) {
newBuild = Build.newBuilder(build)
.directory(alignToBaseDirectory(build.getDirectory(), basedir))
.sourceDirectory(alignToBaseDirectory(build.getSourceDirectory(), basedir))
.testSourceDirectory(alignToBaseDirectory(build.getTestSourceDirectory(), basedir))
.scriptSourceDirectory(alignToBaseDirectory(build.getScriptSourceDirectory(), basedir))
.resources(map(build.getResources(), r -> alignToBaseDirectory(r, basedir)))
.testResources(map(build.getTestResources(), r -> alignToBaseDirectory(r, basedir)))
.filters(map(build.getFilters(), s -> alignToBaseDirectory(s, basedir)))
.outputDirectory(alignToBaseDirectory(build.getOutputDirectory(), basedir))
.testOutputDirectory(alignToBaseDirectory(build.getTestOutputDirectory(), basedir))
.build();
}
Reporting reporting = model.getReporting();
Reporting newReporting = null;
if (reporting != null) {
newReporting = Reporting.newBuilder(reporting)
.outputDirectory(alignToBaseDirectory(reporting.getOutputDirectory(), basedir))
.build();
}
if (newBuild != build || newReporting != reporting) {
modelV3.update(Model.newBuilder(model)
.build(newBuild)
.reporting(newReporting)
.build());
}
}
private <T> List<T> map(List<T> resources, Function<T, T> mapper) {
List<T> newResources = null;
if (resources != null) {
for (int i = 0; i < resources.size(); i++) {
T resource = resources.get(i);
T newResource = mapper.apply(resource);
if (newResource != null) {
if (newResources == null) {
newResources = new ArrayList<>(resources);
}
newResources.set(i, newResource);
}
}
}
return newResources;
}
private Resource alignToBaseDirectory(Resource resource, Path basedir) {<FILL_FUNCTION_BODY>}
private String alignToBaseDirectory(String path, Path basedir) {
String newPath = pathTranslator.alignToBaseDirectory(path, basedir);
return Objects.equals(path, newPath) ? null : newPath;
}
}
|
if (resource != null) {
String newDir = alignToBaseDirectory(resource.getDirectory(), basedir);
if (newDir != null) {
return resource.withDirectory(newDir);
}
}
return resource;
| 874
| 65
| 939
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/path/DefaultModelUrlNormalizer.java
|
DefaultModelUrlNormalizer
|
normalize
|
class DefaultModelUrlNormalizer implements ModelUrlNormalizer {
private final UrlNormalizer urlNormalizer;
@Inject
public DefaultModelUrlNormalizer(UrlNormalizer urlNormalizer) {
this.urlNormalizer = urlNormalizer;
}
@Override
public void normalize(Model model, ModelBuildingRequest request) {<FILL_FUNCTION_BODY>}
private String normalize(String url) {
return urlNormalizer.normalize(url);
}
}
|
if (model == null) {
return;
}
model.setUrl(normalize(model.getUrl()));
Scm scm = model.getScm();
if (scm != null) {
scm.setUrl(normalize(scm.getUrl()));
scm.setConnection(normalize(scm.getConnection()));
scm.setDeveloperConnection(normalize(scm.getDeveloperConnection()));
}
DistributionManagement dist = model.getDistributionManagement();
if (dist != null) {
Site site = dist.getSite();
if (site != null) {
site.setUrl(normalize(site.getUrl()));
}
}
| 126
| 184
| 310
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/path/DefaultPathTranslator.java
|
DefaultPathTranslator
|
alignToBaseDirectory
|
class DefaultPathTranslator implements PathTranslator {
@Override
public String alignToBaseDirectory(String path, File basedir) {
return alignToBaseDirectory(path, basedir != null ? basedir.toPath() : null);
}
@Override
public String alignToBaseDirectory(String path, Path basedir) {<FILL_FUNCTION_BODY>}
}
|
String result = path;
if (path != null && basedir != null) {
path = path.replace('\\', File.separatorChar).replace('/', File.separatorChar);
File file = new File(path);
if (file.isAbsolute()) {
// path was already absolute, just normalize file separator and we're done
result = file.getPath();
} else if (file.getPath().startsWith(File.separator)) {
// drive-relative Windows path, don't align with project directory but with drive root
result = file.getAbsolutePath();
} else {
// an ordinary relative path, align with project directory
result = basedir.resolve(path).normalize().toString();
}
}
return result;
| 99
| 199
| 298
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/path/DefaultUrlNormalizer.java
|
DefaultUrlNormalizer
|
normalize
|
class DefaultUrlNormalizer implements UrlNormalizer {
@Override
public String normalize(String url) {<FILL_FUNCTION_BODY>}
}
|
String result = url;
if (result != null) {
while (true) {
int idx = result.indexOf("/../");
if (idx < 0) {
break;
} else if (idx == 0) {
result = result.substring(3);
continue;
}
int parent = idx - 1;
while (parent >= 0 && result.charAt(parent) == '/') {
parent--;
}
parent = result.lastIndexOf('/', parent);
if (parent < 0) {
result = result.substring(idx + 4);
} else {
result = result.substring(0, parent) + result.substring(idx + 3);
}
}
}
return result;
| 42
| 196
| 238
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/path/ProfileActivationFilePathInterpolator.java
|
ProfileActivationFilePathInterpolator
|
interpolate
|
class ProfileActivationFilePathInterpolator {
private final PathTranslator pathTranslator;
private final RootLocator rootLocator;
@Inject
public ProfileActivationFilePathInterpolator(PathTranslator pathTranslator, RootLocator rootLocator) {
this.pathTranslator = pathTranslator;
this.rootLocator = rootLocator;
}
/**
* Interpolates given {@code path}.
*
* @return absolute path or {@code null} if the input was {@code null}
*/
public String interpolate(String path, ProfileActivationContext context) throws InterpolationException {<FILL_FUNCTION_BODY>}
}
|
if (path == null) {
return null;
}
RegexBasedInterpolator interpolator = new RegexBasedInterpolator();
final File basedir = context.getProjectDirectory();
if (basedir != null) {
interpolator.addValueSource(new AbstractValueSource(false) {
@Override
public Object getValue(String expression) {
if ("basedir".equals(expression) || "project.basedir".equals(expression)) {
return basedir.getAbsolutePath();
}
return null;
}
});
} else if (path.contains("${basedir}")) {
return null;
}
interpolator.addValueSource(new AbstractValueSource(false) {
@Override
public Object getValue(String expression) {
if ("rootDirectory".equals(expression)) {
Path base = basedir != null ? basedir.toPath() : null;
Path root = rootLocator.findMandatoryRoot(base);
return root.toFile().getAbsolutePath();
}
return null;
}
});
interpolator.addValueSource(new MapBasedValueSource(context.getProjectProperties()));
interpolator.addValueSource(new MapBasedValueSource(context.getUserProperties()));
interpolator.addValueSource(new MapBasedValueSource(context.getSystemProperties()));
String absolutePath = interpolator.interpolate(path, "");
return pathTranslator.alignToBaseDirectory(absolutePath, basedir);
| 178
| 385
| 563
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/plugin/DefaultPluginConfigurationExpander.java
|
DefaultPluginConfigurationExpander
|
expandPluginConfiguration
|
class DefaultPluginConfigurationExpander implements PluginConfigurationExpander {
@Override
public void expandPluginConfiguration(Model model, ModelBuildingRequest request, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
private void expand(List<Plugin> plugins) {
for (Plugin plugin : plugins) {
XmlNode pluginConfiguration = plugin.getDelegate().getConfiguration();
if (pluginConfiguration != null) {
for (PluginExecution execution : plugin.getExecutions()) {
XmlNode executionConfiguration = execution.getDelegate().getConfiguration();
executionConfiguration = XmlNode.merge(executionConfiguration, pluginConfiguration);
execution.update(execution.getDelegate().withConfiguration(executionConfiguration));
}
}
}
}
}
|
Build build = model.getBuild();
if (build != null) {
expand(build.getPlugins());
PluginManagement pluginManagement = build.getPluginManagement();
if (pluginManagement != null) {
expand(pluginManagement.getPlugins());
}
}
| 186
| 80
| 266
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/plugin/DefaultReportConfigurationExpander.java
|
DefaultReportConfigurationExpander
|
expandPluginConfiguration
|
class DefaultReportConfigurationExpander implements ReportConfigurationExpander {
@Override
public void expandPluginConfiguration(Model model, ModelBuildingRequest request, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
}
|
Reporting reporting = model.getReporting();
if (reporting != null) {
for (ReportPlugin reportPlugin : reporting.getPlugins()) {
XmlNode parentDom = reportPlugin.getDelegate().getConfiguration();
if (parentDom != null) {
for (ReportSet execution : reportPlugin.getReportSets()) {
XmlNode childDom = execution.getDelegate().getConfiguration();
childDom = XmlNode.merge(childDom, parentDom);
execution.update(execution.getDelegate().withConfiguration(childDom));
}
}
}
}
| 56
| 152
| 208
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/profile/DefaultProfileActivationContext.java
|
DefaultProfileActivationContext
|
toMap
|
class DefaultProfileActivationContext implements ProfileActivationContext {
private List<String> activeProfileIds = Collections.emptyList();
private List<String> inactiveProfileIds = Collections.emptyList();
private Map<String, String> systemProperties = Collections.emptyMap();
private Map<String, String> userProperties = Collections.emptyMap();
private Map<String, String> projectProperties = Collections.emptyMap();
private File projectDirectory;
@Override
public List<String> getActiveProfileIds() {
return activeProfileIds;
}
/**
* Sets the identifiers of those profiles that should be activated by explicit demand.
*
* @param activeProfileIds The identifiers of those profiles to activate, may be {@code null}.
* @return This context, never {@code null}.
*/
public DefaultProfileActivationContext setActiveProfileIds(List<String> activeProfileIds) {
this.activeProfileIds = unmodifiable(activeProfileIds);
return this;
}
@Override
public List<String> getInactiveProfileIds() {
return inactiveProfileIds;
}
/**
* Sets the identifiers of those profiles that should be deactivated by explicit demand.
*
* @param inactiveProfileIds The identifiers of those profiles to deactivate, may be {@code null}.
* @return This context, never {@code null}.
*/
public DefaultProfileActivationContext setInactiveProfileIds(List<String> inactiveProfileIds) {
this.inactiveProfileIds = unmodifiable(inactiveProfileIds);
return this;
}
@Override
public Map<String, String> getSystemProperties() {
return systemProperties;
}
/**
* Sets the system properties to use for interpolation and profile activation. The system properties are collected
* from the runtime environment like {@link System#getProperties()} and environment variables.
*
* @param systemProperties The system properties, may be {@code null}.
* @return This context, never {@code null}.
*/
@SuppressWarnings("unchecked")
public DefaultProfileActivationContext setSystemProperties(Properties systemProperties) {
return setSystemProperties(toMap(systemProperties));
}
/**
* Sets the system properties to use for interpolation and profile activation. The system properties are collected
* from the runtime environment like {@link System#getProperties()} and environment variables.
*
* @param systemProperties The system properties, may be {@code null}.
* @return This context, never {@code null}.
*/
public DefaultProfileActivationContext setSystemProperties(Map<String, String> systemProperties) {
this.systemProperties = unmodifiable(systemProperties);
return this;
}
@Override
public Map<String, String> getUserProperties() {
return userProperties;
}
/**
* Sets the user properties to use for interpolation and profile activation. The user properties have been
* configured directly by the user on his discretion, e.g. via the {@code -Dkey=value} parameter on the command
* line.
*
* @param userProperties The user properties, may be {@code null}.
* @return This context, never {@code null}.
*/
@SuppressWarnings("unchecked")
public DefaultProfileActivationContext setUserProperties(Properties userProperties) {
return setUserProperties(toMap(userProperties));
}
/**
* Sets the user properties to use for interpolation and profile activation. The user properties have been
* configured directly by the user on his discretion, e.g. via the {@code -Dkey=value} parameter on the command
* line.
*
* @param userProperties The user properties, may be {@code null}.
* @return This context, never {@code null}.
*/
public DefaultProfileActivationContext setUserProperties(Map<String, String> userProperties) {
this.userProperties = unmodifiable(userProperties);
return this;
}
@Override
public File getProjectDirectory() {
return projectDirectory;
}
/**
* Sets the base directory of the current project.
*
* @param projectDirectory The base directory of the current project, may be {@code null} if profile activation
* happens in the context of metadata retrieval rather than project building.
* @return This context, never {@code null}.
*/
public DefaultProfileActivationContext setProjectDirectory(File projectDirectory) {
this.projectDirectory = projectDirectory;
return this;
}
@Override
public Map<String, String> getProjectProperties() {
return projectProperties;
}
public DefaultProfileActivationContext setProjectProperties(Properties projectProperties) {
return setProjectProperties(toMap(projectProperties));
}
public DefaultProfileActivationContext setProjectProperties(Map<String, String> projectProperties) {
this.projectProperties = unmodifiable(projectProperties);
return this;
}
private static List<String> unmodifiable(List<String> list) {
return list != null ? Collections.unmodifiableList(list) : Collections.emptyList();
}
private static Map<String, String> unmodifiable(Map<String, String> map) {
return map != null ? Collections.unmodifiableMap(map) : Collections.emptyMap();
}
private static Map<String, String> toMap(Properties properties) {<FILL_FUNCTION_BODY>}
}
|
if (properties != null && !properties.isEmpty()) {
return properties.entrySet().stream()
.collect(Collectors.toMap(e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue())));
} else {
return null;
}
| 1,365
| 79
| 1,444
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/profile/DefaultProfileInjector.java
|
ProfileModelMerger
|
mergeReporting_Plugins
|
class ProfileModelMerger extends MavenModelMerger {
public void mergeModelBase(ModelBase.Builder builder, ModelBase target, ModelBase source) {
mergeModelBase(builder, target, source, true, Collections.emptyMap());
}
public void mergeBuildBase(BuildBase.Builder builder, BuildBase target, BuildBase source) {
mergeBuildBase(builder, target, source, true, Collections.emptyMap());
}
@Override
protected void mergePluginContainer_Plugins(
PluginContainer.Builder builder,
PluginContainer target,
PluginContainer source,
boolean sourceDominant,
Map<Object, Object> context) {
List<Plugin> src = source.getPlugins();
if (!src.isEmpty()) {
List<Plugin> tgt = target.getPlugins();
Map<Object, Plugin> master = new LinkedHashMap<>(tgt.size() * 2);
for (Plugin element : tgt) {
Object key = getPluginKey().apply(element);
master.put(key, element);
}
Map<Object, List<Plugin>> predecessors = new LinkedHashMap<>();
List<Plugin> pending = new ArrayList<>();
for (Plugin element : src) {
Object key = getPluginKey().apply(element);
Plugin existing = master.get(key);
if (existing != null) {
existing = mergePlugin(existing, element, sourceDominant, context);
master.put(key, existing);
if (!pending.isEmpty()) {
predecessors.put(key, pending);
pending = new ArrayList<>();
}
} else {
pending.add(element);
}
}
List<Plugin> result = new ArrayList<>(src.size() + tgt.size());
for (Map.Entry<Object, Plugin> entry : master.entrySet()) {
List<Plugin> pre = predecessors.get(entry.getKey());
if (pre != null) {
result.addAll(pre);
}
result.add(entry.getValue());
}
result.addAll(pending);
builder.plugins(result);
}
}
@Override
protected void mergePlugin_Executions(
Plugin.Builder builder,
Plugin target,
Plugin source,
boolean sourceDominant,
Map<Object, Object> context) {
List<PluginExecution> src = source.getExecutions();
if (!src.isEmpty()) {
List<PluginExecution> tgt = target.getExecutions();
Map<Object, PluginExecution> merged = new LinkedHashMap<>((src.size() + tgt.size()) * 2);
for (PluginExecution element : tgt) {
Object key = getPluginExecutionKey().apply(element);
merged.put(key, element);
}
for (PluginExecution element : src) {
Object key = getPluginExecutionKey().apply(element);
PluginExecution existing = merged.get(key);
if (existing != null) {
element = mergePluginExecution(existing, element, sourceDominant, context);
}
merged.put(key, element);
}
builder.executions(merged.values());
}
}
@Override
protected void mergeReporting_Plugins(
Reporting.Builder builder,
Reporting target,
Reporting source,
boolean sourceDominant,
Map<Object, Object> context) {<FILL_FUNCTION_BODY>}
@Override
protected void mergeReportPlugin_ReportSets(
ReportPlugin.Builder builder,
ReportPlugin target,
ReportPlugin source,
boolean sourceDominant,
Map<Object, Object> context) {
List<ReportSet> src = source.getReportSets();
if (!src.isEmpty()) {
List<ReportSet> tgt = target.getReportSets();
Map<Object, ReportSet> merged = new LinkedHashMap<>((src.size() + tgt.size()) * 2);
for (ReportSet element : tgt) {
Object key = getReportSetKey().apply(element);
merged.put(key, element);
}
for (ReportSet element : src) {
Object key = getReportSetKey().apply(element);
ReportSet existing = merged.get(key);
if (existing != null) {
element = mergeReportSet(existing, element, sourceDominant, context);
}
merged.put(key, element);
}
builder.reportSets(merged.values());
}
}
}
|
List<ReportPlugin> src = source.getPlugins();
if (!src.isEmpty()) {
List<ReportPlugin> tgt = target.getPlugins();
Map<Object, ReportPlugin> merged = new LinkedHashMap<>((src.size() + tgt.size()) * 2);
for (ReportPlugin element : tgt) {
Object key = getReportPluginKey().apply(element);
merged.put(key, element);
}
for (ReportPlugin element : src) {
Object key = getReportPluginKey().apply(element);
ReportPlugin existing = merged.get(key);
if (existing != null) {
element = mergeReportPlugin(existing, element, sourceDominant, context);
}
merged.put(key, element);
}
builder.plugins(merged.values());
}
| 1,166
| 216
| 1,382
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/profile/DefaultProfileSelector.java
|
DefaultProfileSelector
|
getActiveProfiles
|
class DefaultProfileSelector implements ProfileSelector {
private final List<ProfileActivator> activators;
public DefaultProfileSelector() {
this.activators = new ArrayList<>();
}
@Inject
public DefaultProfileSelector(List<ProfileActivator> activators) {
this.activators = new ArrayList<>(activators);
}
public DefaultProfileSelector addProfileActivator(ProfileActivator profileActivator) {
if (profileActivator != null) {
activators.add(profileActivator);
}
return this;
}
@Override
public List<org.apache.maven.api.model.Profile> getActiveProfilesV4(
Collection<org.apache.maven.api.model.Profile> profiles,
ProfileActivationContext context,
ModelProblemCollector problems) {
return getActiveProfiles(profiles.stream().map(Profile::new).collect(Collectors.toList()), context, problems)
.stream()
.map(Profile::getDelegate)
.collect(Collectors.toList());
}
@Override
public List<Profile> getActiveProfiles(
Collection<Profile> profiles, ProfileActivationContext context, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
private boolean isActive(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {
boolean isActive = false;
for (ProfileActivator activator : activators) {
if (activator.presentInConfig(profile, context, problems)) {
isActive = true;
try {
if (!activator.isActive(profile, context, problems)) {
return false;
}
} catch (RuntimeException e) {
problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
.setMessage("Failed to determine activation for profile " + profile.getId())
.setLocation(profile.getLocation(""))
.setException(e));
return false;
}
}
}
return isActive;
}
private boolean isActiveByDefault(Profile profile) {
Activation activation = profile.getActivation();
return activation != null && activation.isActiveByDefault();
}
}
|
Collection<String> activatedIds = new HashSet<>(context.getActiveProfileIds());
Collection<String> deactivatedIds = new HashSet<>(context.getInactiveProfileIds());
List<Profile> activeProfiles = new ArrayList<>(profiles.size());
List<Profile> activePomProfilesByDefault = new ArrayList<>();
boolean activatedPomProfileNotByDefault = false;
for (Profile profile : profiles) {
if (!deactivatedIds.contains(profile.getId())) {
if (activatedIds.contains(profile.getId()) || isActive(profile, context, problems)) {
activeProfiles.add(profile);
if (Profile.SOURCE_POM.equals(profile.getSource())) {
activatedPomProfileNotByDefault = true;
}
} else if (isActiveByDefault(profile)) {
if (Profile.SOURCE_POM.equals(profile.getSource())) {
activePomProfilesByDefault.add(profile);
} else {
activeProfiles.add(profile);
}
}
}
}
if (!activatedPomProfileNotByDefault) {
activeProfiles.addAll(activePomProfilesByDefault);
}
return activeProfiles;
| 558
| 315
| 873
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/FileProfileActivator.java
|
FileProfileActivator
|
isActive
|
class FileProfileActivator implements ProfileActivator {
private final ProfileActivationFilePathInterpolator profileActivationFilePathInterpolator;
@Inject
public FileProfileActivator(ProfileActivationFilePathInterpolator profileActivationFilePathInterpolator) {
this.profileActivationFilePathInterpolator = profileActivationFilePathInterpolator;
}
@Override
public boolean isActive(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
@Override
public boolean presentInConfig(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
ActivationFile file = activation.getFile();
return file != null;
}
}
|
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
ActivationFile file = activation.getFile();
if (file == null) {
return false;
}
String path;
boolean missing;
if (file.getExists() != null && !file.getExists().isEmpty()) {
path = file.getExists();
missing = false;
} else if (file.getMissing() != null && !file.getMissing().isEmpty()) {
path = file.getMissing();
missing = true;
} else {
return false;
}
try {
path = profileActivationFilePathInterpolator.interpolate(path, context);
} catch (InterpolationException e) {
problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
.setMessage("Failed to interpolate file location " + path + " for profile " + profile.getId() + ": "
+ e.getMessage())
.setLocation(file.getLocation(missing ? "missing" : "exists"))
.setException(e));
return false;
}
if (path == null) {
return false;
}
File f = new File(path);
if (!f.isAbsolute()) {
return false;
}
boolean fileExists = f.exists();
return missing != fileExists;
| 219
| 372
| 591
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java
|
JdkVersionProfileActivator
|
getRelationOrder
|
class JdkVersionProfileActivator implements ProfileActivator {
private static final Pattern FILTER_1 = Pattern.compile("[^\\d._-]");
private static final Pattern FILTER_2 = Pattern.compile("[._-]");
private static final Pattern FILTER_3 = Pattern.compile("\\."); // used for split now
@Override
public boolean isActive(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
String jdk = activation.getJdk();
if (jdk == null) {
return false;
}
String version = context.getSystemProperties().get("java.version");
if (version == null || version.isEmpty()) {
problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
.setMessage("Failed to determine Java version for profile " + profile.getId())
.setLocation(activation.getLocation("jdk")));
return false;
}
return isJavaVersionCompatible(jdk, version);
}
public static boolean isJavaVersionCompatible(String requiredJdkRange, String currentJavaVersion) {
if (requiredJdkRange.startsWith("!")) {
return !currentJavaVersion.startsWith(requiredJdkRange.substring(1));
} else if (isRange(requiredJdkRange)) {
return isInRange(currentJavaVersion, getRange(requiredJdkRange));
} else {
return currentJavaVersion.startsWith(requiredJdkRange);
}
}
@Override
public boolean presentInConfig(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
String jdk = activation.getJdk();
return jdk != null;
}
private static boolean isInRange(String value, List<RangeValue> range) {
int leftRelation = getRelationOrder(value, range.get(0), true);
if (leftRelation == 0) {
return true;
}
if (leftRelation < 0) {
return false;
}
return getRelationOrder(value, range.get(1), false) <= 0;
}
private static int getRelationOrder(String value, RangeValue rangeValue, boolean isLeft) {<FILL_FUNCTION_BODY>}
private static void addZeroTokens(List<String> tokens, int max) {
while (tokens.size() < max) {
tokens.add("0");
}
}
private static boolean isRange(String value) {
return value.startsWith("[") || value.startsWith("(");
}
private static List<RangeValue> getRange(String range) {
List<RangeValue> ranges = new ArrayList<>();
for (String token : range.split(",")) {
if (token.startsWith("[")) {
ranges.add(new RangeValue(token.replace("[", ""), true));
} else if (token.startsWith("(")) {
ranges.add(new RangeValue(token.replace("(", ""), false));
} else if (token.endsWith("]")) {
ranges.add(new RangeValue(token.replace("]", ""), true));
} else if (token.endsWith(")")) {
ranges.add(new RangeValue(token.replace(")", ""), false));
} else if (token.isEmpty()) {
ranges.add(new RangeValue("", false));
}
}
if (ranges.size() < 2) {
ranges.add(new RangeValue("99999999", false));
}
return ranges;
}
private static class RangeValue {
private String value;
private boolean closed;
RangeValue(String value, boolean closed) {
this.value = value.trim();
this.closed = closed;
}
@Override
public String toString() {
return value;
}
}
}
|
if (rangeValue.value.isEmpty()) {
return isLeft ? 1 : -1;
}
value = FILTER_1.matcher(value).replaceAll("");
List<String> valueTokens = new ArrayList<>(Arrays.asList(FILTER_2.split(value)));
List<String> rangeValueTokens = new ArrayList<>(Arrays.asList(FILTER_3.split(rangeValue.value)));
addZeroTokens(valueTokens, 3);
addZeroTokens(rangeValueTokens, 3);
for (int i = 0; i < 3; i++) {
int x = Integer.parseInt(valueTokens.get(i));
int y = Integer.parseInt(rangeValueTokens.get(i));
if (x < y) {
return -1;
} else if (x > y) {
return 1;
}
}
if (!rangeValue.closed) {
return isLeft ? -1 : 1;
}
return 0;
| 1,068
| 269
| 1,337
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/OperatingSystemProfileActivator.java
|
OperatingSystemProfileActivator
|
isActive
|
class OperatingSystemProfileActivator implements ProfileActivator {
private static final String REGEX_PREFIX = "regex:";
@Override
public boolean isActive(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
@Override
public boolean presentInConfig(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
ActivationOS os = activation.getOs();
return os != null;
}
private boolean ensureAtLeastOneNonNull(ActivationOS os) {
return os.getArch() != null || os.getFamily() != null || os.getName() != null || os.getVersion() != null;
}
private boolean determineVersionMatch(String expectedVersion, String actualVersion) {
String test = expectedVersion;
boolean reverse = false;
final boolean result;
if (test.startsWith(REGEX_PREFIX)) {
result = actualVersion.matches(test.substring(REGEX_PREFIX.length()));
} else {
if (test.startsWith("!")) {
reverse = true;
test = test.substring(1);
}
result = actualVersion.equals(test);
}
return reverse != result;
}
private boolean determineArchMatch(String expectedArch, String actualArch) {
String test = expectedArch;
boolean reverse = false;
if (test.startsWith("!")) {
reverse = true;
test = test.substring(1);
}
boolean result = actualArch.equals(test);
return reverse != result;
}
private boolean determineNameMatch(String expectedName, String actualName) {
String test = expectedName;
boolean reverse = false;
if (test.startsWith("!")) {
reverse = true;
test = test.substring(1);
}
boolean result = actualName.equals(test);
return reverse != result;
}
private boolean determineFamilyMatch(String family, String actualName) {
String test = family;
boolean reverse = false;
if (test.startsWith("!")) {
reverse = true;
test = test.substring(1);
}
boolean result = Os.isFamily(test, actualName);
return reverse != result;
}
}
|
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
ActivationOS os = activation.getOs();
if (os == null) {
return false;
}
boolean active = ensureAtLeastOneNonNull(os);
String actualOsName = context.getSystemProperties().get("os.name").toLowerCase(Locale.ENGLISH);
String actualOsArch = context.getSystemProperties().get("os.arch").toLowerCase(Locale.ENGLISH);
String actualOsVersion = context.getSystemProperties().get("os.version").toLowerCase(Locale.ENGLISH);
if (active && os.getFamily() != null) {
active = determineFamilyMatch(os.getFamily(), actualOsName);
}
if (active && os.getName() != null) {
active = determineNameMatch(os.getName(), actualOsName);
}
if (active && os.getArch() != null) {
active = determineArchMatch(os.getArch(), actualOsArch);
}
if (active && os.getVersion() != null) {
active = determineVersionMatch(os.getVersion(), actualOsVersion);
}
return active;
| 640
| 321
| 961
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/PropertyProfileActivator.java
|
PropertyProfileActivator
|
isActive
|
class PropertyProfileActivator implements ProfileActivator {
@Override
public boolean isActive(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
@Override
public boolean presentInConfig(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
ActivationProperty property = activation.getProperty();
return property != null;
}
}
|
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
ActivationProperty property = activation.getProperty();
if (property == null) {
return false;
}
String name = property.getName();
boolean reverseName = false;
if (name != null && name.startsWith("!")) {
reverseName = true;
name = name.substring(1);
}
if (name == null || name.isEmpty()) {
problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE)
.setMessage("The property name is required to activate the profile " + profile.getId())
.setLocation(property.getLocation("")));
return false;
}
String sysValue = context.getUserProperties().get(name);
if (sysValue == null) {
sysValue = context.getSystemProperties().get(name);
}
String propValue = property.getValue();
if (propValue != null && !propValue.isEmpty()) {
boolean reverseValue = false;
if (propValue.startsWith("!")) {
reverseValue = true;
propValue = propValue.substring(1);
}
// we have a value, so it has to match the system value...
return reverseValue != propValue.equals(sysValue);
} else {
return reverseName != (sysValue != null && !sysValue.isEmpty());
}
| 140
| 382
| 522
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/root/DefaultRootLocator.java
|
DefaultRootLocator
|
isRootDirectory
|
class DefaultRootLocator implements RootLocator {
public boolean isRootDirectory(Path dir) {<FILL_FUNCTION_BODY>}
}
|
if (Files.isDirectory(dir.resolve(".mvn"))) {
return true;
}
// we're too early to use the modelProcessor ...
Path pom = dir.resolve("pom.xml");
try (InputStream is = Files.newInputStream(pom)) {
XMLStreamReader parser = new WstxInputFactory().createXMLStreamReader(is);
if (parser.nextTag() == XMLStreamReader.START_ELEMENT
&& parser.getLocalName().equals("project")) {
for (int i = 0; i < parser.getAttributeCount(); i++) {
if ("root".equals(parser.getAttributeLocalName(i))) {
return Boolean.parseBoolean(parser.getAttributeValue(i));
}
}
}
} catch (IOException | XMLStreamException e) {
// The root locator can be used very early during the setup of Maven,
// even before the arguments from the command line are parsed. Any exception
// that would happen here should cause the build to fail at a later stage
// (when actually parsing the POM) and will lead to a better exception being
// displayed to the user, so just bail out and return false.
}
return false;
| 38
| 302
| 340
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/superpom/DefaultSuperPomProvider.java
|
DefaultSuperPomProvider
|
getSuperModel
|
class DefaultSuperPomProvider implements SuperPomProvider {
private final ModelProcessor modelProcessor;
/**
* The cached super POM, lazily created.
*/
private static final Map<String, Model> SUPER_MODELS = new ConcurrentHashMap<>();
@Inject
public DefaultSuperPomProvider(ModelProcessor modelProcessor) {
this.modelProcessor = modelProcessor;
}
@Override
public Model getSuperModel(String version) {<FILL_FUNCTION_BODY>}
}
|
return SUPER_MODELS.computeIfAbsent(Objects.requireNonNull(version), v -> {
String resource = "/org/apache/maven/model/pom-" + v + ".xml";
InputStream is = getClass().getResourceAsStream(resource);
if (is == null) {
throw new IllegalStateException("The super POM " + resource + " was not found"
+ ", please verify the integrity of your Maven installation");
}
try {
Map<String, Object> options = new HashMap<>(2);
options.put("xml:" + version, "xml:" + version);
String modelId = "org.apache.maven:maven-model-builder:" + version + "-"
+ this.getClass().getPackage().getImplementationVersion() + ":super-pom";
InputSource inputSource = new InputSource(
modelId, getClass().getResource(resource).toExternalForm());
options.put(ModelProcessor.INPUT_SOURCE, new org.apache.maven.model.InputSource(inputSource));
return modelProcessor.read(is, options);
} catch (IOException e) {
throw new IllegalStateException(
"The super POM " + resource + " is damaged"
+ ", please verify the integrity of your Maven installation",
e);
}
});
| 134
| 333
| 467
|
<no_super_class>
|
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/utils/Os.java
|
Os
|
isFamily
|
class Os {
/**
* The OS Name.
*/
public static final String OS_NAME = System.getProperty("os.name").toLowerCase(Locale.ENGLISH);
/**
* The OA architecture.
*/
public static final String OS_ARCH = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH);
/**
* The OS version.
*/
public static final String OS_VERSION = System.getProperty("os.version").toLowerCase(Locale.ENGLISH);
/**
* OS Family
*/
public static final String OS_FAMILY;
/**
* Boolean indicating if the running OS is a Windows system.
*/
public static final boolean IS_WINDOWS;
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_WINDOWS = "windows";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_WIN9X = "win9x";
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_NT = "winnt";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_OS2 = "os/2";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_NETWARE = "netware";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_DOS = "dos";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_MAC = "mac";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_TANDEM = "tandem";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_UNIX = "unix";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_OPENVMS = "openvms";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_ZOS = "z/os";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_OS390 = "os/390";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_OS400 = "os/400";
/**
* OpenJDK is reported to call MacOS X "Darwin"
*
* @see <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=44889">bugzilla issue</a>
* @see <a href="https://issues.apache.org/jira/browse/HADOOP-3318">HADOOP-3318</a>
*/
private static final String DARWIN = "darwin";
/**
* The path separator.
*/
private static final String PATH_SEP = System.getProperty("path.separator");
static {
// Those two public constants are initialized here, as they need all the private constants
// above to be initialized first, but the code style imposes the public constants to be
// defined above the private ones...
OS_FAMILY = getOsFamily();
IS_WINDOWS = isFamily(FAMILY_WINDOWS);
}
private Os() {}
/**
* Determines if the OS on which Maven is executing matches the
* given OS family.
*
* @param family the family to check for
* @return true if the OS matches
*
*/
public static boolean isFamily(String family) {
return isFamily(family, OS_NAME);
}
/**
* Determines if the OS on which Maven is executing matches the
* given OS family derived from the given OS name
*
* @param family the family to check for
* @param actualOsName the OS name to check against
* @return true if the OS matches
*
*/
public static boolean isFamily(String family, String actualOsName) {<FILL_FUNCTION_BODY>}
/**
* Helper method to determine the current OS family.
*
* @return name of current OS family.
*/
private static String getOsFamily() {
return Stream.of(
FAMILY_DOS,
FAMILY_MAC,
FAMILY_NETWARE,
FAMILY_NT,
FAMILY_OPENVMS,
FAMILY_OS2,
FAMILY_OS400,
FAMILY_TANDEM,
FAMILY_UNIX,
FAMILY_WIN9X,
FAMILY_WINDOWS,
FAMILY_ZOS)
.filter(Os::isFamily)
.findFirst()
.orElse(null);
}
}
|
// windows probing logic relies on the word 'windows' in the OS
boolean isWindows = actualOsName.contains(FAMILY_WINDOWS);
boolean is9x = false;
boolean isNT = false;
if (isWindows) {
// there are only four 9x platforms that we look for
is9x = (actualOsName.contains("95")
|| actualOsName.contains("98")
|| actualOsName.contains("me")
// wince isn't really 9x, but crippled enough to
// be a muchness. Maven doesnt run on CE, anyway.
|| actualOsName.contains("ce"));
isNT = !is9x;
}
switch (family) {
case FAMILY_WINDOWS:
return isWindows;
case FAMILY_WIN9X:
return isWindows && is9x;
case FAMILY_NT:
return isWindows && isNT;
case FAMILY_OS2:
return actualOsName.contains(FAMILY_OS2);
case FAMILY_NETWARE:
return actualOsName.contains(FAMILY_NETWARE);
case FAMILY_DOS:
return PATH_SEP.equals(";") && !isFamily(FAMILY_NETWARE, actualOsName) && !isWindows;
case FAMILY_MAC:
return actualOsName.contains(FAMILY_MAC) || actualOsName.contains(DARWIN);
case FAMILY_TANDEM:
return actualOsName.contains("nonstop_kernel");
case FAMILY_UNIX:
return PATH_SEP.equals(":")
&& !isFamily(FAMILY_OPENVMS, actualOsName)
&& (!isFamily(FAMILY_MAC, actualOsName) || actualOsName.endsWith("x"));
case FAMILY_ZOS:
return actualOsName.contains(FAMILY_ZOS) || actualOsName.contains(FAMILY_OS390);
case FAMILY_OS400:
return actualOsName.contains(FAMILY_OS400);
case FAMILY_OPENVMS:
return actualOsName.contains(FAMILY_OPENVMS);
default:
return actualOsName.contains(family.toLowerCase(Locale.US));
}
| 1,384
| 622
| 2,006
|
<no_super_class>
|
apache_maven
|
maven/maven-model/src/main/java/org/apache/maven/model/BaseObject.java
|
BaseObject
|
update
|
class BaseObject implements Serializable, Cloneable, InputLocationTracker {
protected transient ChildrenTracking childrenTracking;
protected Object delegate;
public BaseObject() {}
public BaseObject(Object delegate, BaseObject parent) {
this.delegate = delegate;
this.childrenTracking = parent != null ? parent::replace : null;
}
public BaseObject(Object delegate, ChildrenTracking parent) {
this.delegate = delegate;
this.childrenTracking = parent;
}
public Object getDelegate() {
return delegate;
}
public void update(Object newDelegate) {<FILL_FUNCTION_BODY>}
protected boolean replace(Object oldDelegate, Object newDelegate) {
return false;
}
@FunctionalInterface
protected interface ChildrenTracking {
boolean replace(Object oldDelegate, Object newDelegate);
}
}
|
if (delegate != newDelegate) {
if (childrenTracking != null) {
childrenTracking.replace(delegate, newDelegate);
}
delegate = newDelegate;
}
| 227
| 56
| 283
|
<no_super_class>
|
apache_maven
|
maven/maven-model/src/main/java/org/apache/maven/model/InputSource.java
|
InputSource
|
clone
|
class InputSource implements java.io.Serializable, Cloneable {
// --------------------------/
// - Class/Member Variables -/
// --------------------------/
/**
*
*
* The identifier of the POM in the format {@code
* <groupId>:<artifactId>:<version>}.
*
*
*/
private String modelId;
/**
*
*
* The path/URL of the POM or {@code null} if
* unknown.
*
*
*/
private String location;
// ----------------/
// - Constructors -/
// ----------------/
public InputSource() {}
public InputSource(org.apache.maven.api.model.InputSource source) {
this.modelId = source.getModelId();
this.location = source.getLocation();
}
// -----------/
// - Methods -/
// -----------/
/**
* Method clone.
*
* @return InputSource
*/
public InputSource clone() {<FILL_FUNCTION_BODY>} // -- InputSource clone()
/**
* Get the path/URL of the POM or {@code null} if unknown.
*
* @return String
*/
public String getLocation() {
return this.location;
} // -- String getLocation()
/**
* Get the identifier of the POM in the format {@code
* <groupId>:<artifactId>:<version>}.
*
* @return String
*/
public String getModelId() {
return this.modelId;
} // -- String getModelId()
/**
* Set the path/URL of the POM or {@code null} if unknown.
*
* @param location
*/
public void setLocation(String location) {
this.location = location;
} // -- void setLocation( String )
/**
* Set the identifier of the POM in the format {@code
* <groupId>:<artifactId>:<version>}.
*
* @param modelId
*/
public void setModelId(String modelId) {
this.modelId = modelId;
} // -- void setModelId( String )
@Override
public String toString() {
return getModelId() + " " + getLocation();
}
public org.apache.maven.api.model.InputSource toApiSource() {
return new org.apache.maven.api.model.InputSource(modelId, location);
}
}
|
try {
InputSource copy = (InputSource) super.clone();
return copy;
} catch (Exception ex) {
throw (RuntimeException)
new UnsupportedOperationException(getClass().getName() + " does not support clone()").initCause(ex);
}
| 652
| 73
| 725
|
<no_super_class>
|
apache_maven
|
maven/maven-model/src/main/java/org/apache/maven/model/io/xpp3/MavenXpp3Reader.java
|
MavenXpp3Reader
|
read
|
class MavenXpp3Reader {
private MavenStaxReader delegate;
public MavenXpp3Reader() {
this(null, false);
}
public MavenXpp3Reader(ContentTransformer contentTransformer) {
this(contentTransformer, false);
}
protected MavenXpp3Reader(ContentTransformer contentTransformer, boolean addLocationInformation) {
delegate =
contentTransformer != null ? new MavenStaxReader(contentTransformer::transform) : new MavenStaxReader();
delegate.setAddLocationInformation(addLocationInformation);
}
/**
* Returns the state of the "add default entities" flag.
*
* @return boolean
*/
public boolean getAddDefaultEntities() {
return delegate.getAddDefaultEntities();
} // -- boolean getAddDefaultEntities()
/**
* Sets the state of the "add default entities" flag.
*
* @param addDefaultEntities a addDefaultEntities object.
*/
public void setAddDefaultEntities(boolean addDefaultEntities) {
delegate.setAddLocationInformation(addDefaultEntities);
} // -- void setAddDefaultEntities( boolean )
protected Model read(Reader reader, boolean strict, InputSource source) throws IOException, XmlPullParserException {<FILL_FUNCTION_BODY>}
/**
*
* @param reader a reader object.
* @param strict a strict object.
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
* @return Model
*/
public Model read(Reader reader, boolean strict) throws IOException, XmlPullParserException {
return read(reader, strict, null);
} // -- Model read( Reader, boolean )
/**
*
* @param reader a reader object.
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
* @return Model
*/
public Model read(Reader reader) throws IOException, XmlPullParserException {
return read(reader, true);
} // -- Model read( Reader )
protected Model read(InputStream is, boolean strict, InputSource source)
throws IOException, XmlPullParserException {
try {
org.apache.maven.api.model.Model model =
delegate.read(is, strict, source != null ? source.toApiSource() : null);
return new Model(model);
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
/**
* Method read.
*
* @param in a in object.
* @param strict a strict object.
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
* @return Model
*/
public Model read(InputStream in, boolean strict) throws IOException, XmlPullParserException {
return read(in, strict, null);
} // -- Model read( InputStream, boolean )
/**
* Method read.
*
* @param in a in object.
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
* @return Model
*/
public Model read(InputStream in) throws IOException, XmlPullParserException {
return read(in, true);
} // -- Model read( InputStream )
public interface ContentTransformer {
/**
* Interpolate the value read from the xpp3 document
* @param source The source value
* @param fieldName A description of the field being interpolated. The implementation may use this to
* log stuff.
* @return The interpolated value.
*/
String transform(String source, String fieldName);
}
}
|
try {
org.apache.maven.api.model.Model model =
delegate.read(reader, strict, source != null ? source.toApiSource() : null);
return new Model(model);
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
| 985
| 87
| 1,072
|
<no_super_class>
|
apache_maven
|
maven/maven-model/src/main/java/org/apache/maven/model/io/xpp3/MavenXpp3Writer.java
|
MavenXpp3Writer
|
write
|
class MavenXpp3Writer {
// --------------------------/
// - Class/Member Variables -/
// --------------------------/
private final MavenStaxWriter delegate = new MavenStaxWriter();
// -----------/
// - Methods -/
// -----------/
public MavenXpp3Writer() {
this(false);
}
protected MavenXpp3Writer(boolean addLocationInformation) {
delegate.setAddLocationInformation(addLocationInformation);
}
/**
* Method setFileComment.
*
* @param fileComment a fileComment object.
*/
public void setFileComment(String fileComment) {
delegate.setFileComment(fileComment);
} // -- void setFileComment( String )
/**
* Method setStringFormatter.
*
* @param stringFormatter
*/
public void setStringFormatter(InputLocation.StringFormatter stringFormatter) {
delegate.setStringFormatter(
stringFormatter != null
? new org.apache.maven.api.model.InputLocation.StringFormatter() {
@Override
public String toString(org.apache.maven.api.model.InputLocation location) {
return stringFormatter.toString(new InputLocation(location));
}
}
: null);
} // -- void setStringFormatter( InputLocation.StringFormatter )
/**
* Method write.
*
* @param writer a writer object.
* @param model a model object.
* @throws IOException java.io.IOException if any.
*/
public void write(Writer writer, Model model) throws IOException {
try {
delegate.write(writer, model.getDelegate());
} catch (XMLStreamException e) {
throw new IOException(e);
}
} // -- void write( Writer, Model )
/**
* Method write.
*
* @param stream a stream object.
* @param model a model object.
* @throws IOException java.io.IOException if any.
*/
public void write(OutputStream stream, Model model) throws IOException {<FILL_FUNCTION_BODY>} // -- void write( OutputStream, Model )
}
|
try {
delegate.write(stream, model.getDelegate());
} catch (XMLStreamException e) {
throw new IOException(e);
}
| 555
| 42
| 597
|
<no_super_class>
|
apache_maven
|
maven/maven-plugin-api/src/main/java/org/apache/maven/plugin/AbstractMojo.java
|
AbstractMojo
|
getLog
|
class AbstractMojo implements Mojo, ContextEnabled {
/** Instance logger */
private Log log;
/** Plugin container context */
private Map pluginContext;
/**
* @deprecated Use SLF4J directly
*/
@Deprecated
@Override
public void setLog(Log log) {
this.log = log;
}
/**
* <p>
* Returns the logger that has been injected into this mojo. If no logger has been setup yet, a
* <code>SystemStreamLog</code> logger will be created and returned.
* </p>
* <strong>Note:</strong>
* The logger returned by this method must not be cached in an instance field during the construction of the mojo.
* This would cause the mojo to use a wrongly configured default logger when being run by Maven. The proper logger
* gets injected by the Plexus container <em>after</em> the mojo has been constructed. Therefore, simply call this
* method directly whenever you need the logger, it is fast enough and needs no caching.
*
* @see org.apache.maven.plugin.Mojo#getLog()
* @deprecated Use SLF4J directly
*/
@Deprecated
@Override
public Log getLog() {<FILL_FUNCTION_BODY>}
@Override
public Map getPluginContext() {
return pluginContext;
}
@Override
public void setPluginContext(Map pluginContext) {
this.pluginContext = pluginContext;
}
}
|
if (log == null) {
log = new SystemStreamLog();
}
return log;
| 390
| 30
| 420
|
<no_super_class>
|
apache_maven
|
maven/maven-plugin-api/src/main/java/org/apache/maven/plugin/MojoNotFoundException.java
|
MojoNotFoundException
|
toMessage
|
class MojoNotFoundException extends Exception {
private String goal;
private PluginDescriptor pluginDescriptor;
public MojoNotFoundException(String goal, PluginDescriptor pluginDescriptor) {
super(toMessage(goal, pluginDescriptor));
this.goal = goal;
this.pluginDescriptor = pluginDescriptor;
}
public String getGoal() {
return goal;
}
public PluginDescriptor getPluginDescriptor() {
return pluginDescriptor;
}
private static String toMessage(String goal, PluginDescriptor pluginDescriptor) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder buffer = new StringBuilder(256);
buffer.append("Could not find goal '").append(goal).append('\'');
if (pluginDescriptor != null) {
buffer.append(" in plugin ").append(pluginDescriptor.getId());
buffer.append(" among available goals ");
List<MojoDescriptor> mojos = pluginDescriptor.getMojos();
if (mojos != null) {
for (Iterator<MojoDescriptor> it = mojos.iterator(); it.hasNext(); ) {
MojoDescriptor mojo = it.next();
if (mojo != null) {
buffer.append(mojo.getGoal());
}
if (it.hasNext()) {
buffer.append(", ");
}
}
}
}
return buffer.toString();
| 152
| 209
| 361
|
<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-plugin-api/src/main/java/org/apache/maven/plugin/descriptor/Parameter.java
|
Parameter
|
clone
|
class Parameter implements Cloneable {
private String alias;
private String name;
private String type;
private boolean required;
private boolean editable = true;
private String description;
private String expression;
private String deprecated;
private String defaultValue;
private String implementation;
private Requirement requirement;
private String since;
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
public Parameter() {}
public Parameter(org.apache.maven.api.plugin.descriptor.Parameter p) {
this.setAlias(p.getAlias());
this.setName(p.getName());
this.setRequired(p.isRequired());
this.setEditable(p.isEditable());
this.setDescription(p.getDescription());
this.setExpression(p.getExpression());
this.setDeprecated(p.getDeprecated());
this.setDefaultValue(p.getDefaultValue());
this.setType(p.getType());
this.setSince(p.getSince());
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
public String getDeprecated() {
return deprecated;
}
public void setDeprecated(String deprecated) {
this.deprecated = deprecated;
}
public int hashCode() {
return name.hashCode();
}
public boolean equals(Object other) {
return (other instanceof Parameter) && getName().equals(((Parameter) other).getName());
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public String getDefaultValue() {
return defaultValue;
}
public String toString() {
return "Mojo parameter [name: '" + getName() + "'; alias: '" + getAlias() + "']";
}
public Requirement getRequirement() {
return requirement;
}
public void setRequirement(Requirement requirement) {
this.requirement = requirement;
}
public String getImplementation() {
return implementation;
}
public void setImplementation(String implementation) {
this.implementation = implementation;
}
public String getSince() {
return since;
}
public void setSince(String since) {
this.since = since;
}
/**
* Creates a shallow copy of this parameter.
*/
@Override
public Parameter clone() {<FILL_FUNCTION_BODY>}
public org.apache.maven.api.plugin.descriptor.Parameter getParameterV4() {
return org.apache.maven.api.plugin.descriptor.Parameter.newBuilder()
.alias(alias)
.name(name)
.type(type)
.required(required)
.editable(editable)
.description(description)
.expression(expression)
.deprecated(deprecated)
.defaultValue(defaultValue)
.since(since)
.build();
}
}
|
try {
return (Parameter) super.clone();
} catch (CloneNotSupportedException e) {
throw new UnsupportedOperationException(e);
}
| 1,067
| 45
| 1,112
|
<no_super_class>
|
apache_maven
|
maven/maven-plugin-api/src/main/java/org/apache/maven/plugin/descriptor/Requirement.java
|
Requirement
|
clone
|
class Requirement implements Cloneable {
private final String role;
private final String roleHint;
public Requirement(String role) {
this.role = role;
this.roleHint = null;
}
public Requirement(String role, String roleHint) {
this.role = role;
this.roleHint = roleHint;
}
public String getRole() {
return role;
}
public String getRoleHint() {
return roleHint;
}
/**
* Creates a shallow copy of this requirement.
*/
@Override
public Requirement clone() {<FILL_FUNCTION_BODY>}
}
|
try {
return (Requirement) super.clone();
} catch (CloneNotSupportedException e) {
throw new UnsupportedOperationException(e);
}
| 184
| 46
| 230
|
<no_super_class>
|
apache_maven
|
maven/maven-plugin-api/src/main/java/org/apache/maven/plugin/logging/SystemStreamLog.java
|
SystemStreamLog
|
error
|
class SystemStreamLog implements Log {
/**
* @see org.apache.maven.plugin.logging.Log#debug(java.lang.CharSequence)
*/
public void debug(CharSequence content) {
print("debug", content);
}
/**
* @see org.apache.maven.plugin.logging.Log#debug(java.lang.CharSequence, java.lang.Throwable)
*/
public void debug(CharSequence content, Throwable error) {
print("debug", content, error);
}
/**
* @see org.apache.maven.plugin.logging.Log#debug(java.lang.Throwable)
*/
public void debug(Throwable error) {
print("debug", error);
}
/**
* @see org.apache.maven.plugin.logging.Log#info(java.lang.CharSequence)
*/
public void info(CharSequence content) {
print("info", content);
}
/**
* @see org.apache.maven.plugin.logging.Log#info(java.lang.CharSequence, java.lang.Throwable)
*/
public void info(CharSequence content, Throwable error) {
print("info", content, error);
}
/**
* @see org.apache.maven.plugin.logging.Log#info(java.lang.Throwable)
*/
public void info(Throwable error) {
print("info", error);
}
/**
* @see org.apache.maven.plugin.logging.Log#warn(java.lang.CharSequence)
*/
public void warn(CharSequence content) {
print("warn", content);
}
/**
* @see org.apache.maven.plugin.logging.Log#warn(java.lang.CharSequence, java.lang.Throwable)
*/
public void warn(CharSequence content, Throwable error) {
print("warn", content, error);
}
/**
* @see org.apache.maven.plugin.logging.Log#warn(java.lang.Throwable)
*/
public void warn(Throwable error) {
print("warn", error);
}
/**
* @see org.apache.maven.plugin.logging.Log#error(java.lang.CharSequence)
*/
public void error(CharSequence content) {
System.err.println("[error] " + content.toString());
}
/**
* @see org.apache.maven.plugin.logging.Log#error(java.lang.CharSequence, java.lang.Throwable)
*/
public void error(CharSequence content, Throwable error) {
StringWriter sWriter = new StringWriter();
PrintWriter pWriter = new PrintWriter(sWriter);
error.printStackTrace(pWriter);
System.err.println(
"[error] " + content.toString() + System.lineSeparator() + System.lineSeparator() + sWriter.toString());
}
/**
* @see org.apache.maven.plugin.logging.Log#error(java.lang.Throwable)
*/
public void error(Throwable error) {<FILL_FUNCTION_BODY>}
/**
* @see org.apache.maven.plugin.logging.Log#isDebugEnabled()
*/
public boolean isDebugEnabled() {
// TODO Not sure how best to set these for this implementation...
return false;
}
/**
* @see org.apache.maven.plugin.logging.Log#isInfoEnabled()
*/
public boolean isInfoEnabled() {
return true;
}
/**
* @see org.apache.maven.plugin.logging.Log#isWarnEnabled()
*/
public boolean isWarnEnabled() {
return true;
}
/**
* @see org.apache.maven.plugin.logging.Log#isErrorEnabled()
*/
public boolean isErrorEnabled() {
return true;
}
private void print(String prefix, CharSequence content) {
System.out.println("[" + prefix + "] " + content.toString());
}
private void print(String prefix, Throwable error) {
StringWriter sWriter = new StringWriter();
PrintWriter pWriter = new PrintWriter(sWriter);
error.printStackTrace(pWriter);
System.out.println("[" + prefix + "] " + sWriter.toString());
}
private void print(String prefix, CharSequence content, Throwable error) {
StringWriter sWriter = new StringWriter();
PrintWriter pWriter = new PrintWriter(sWriter);
error.printStackTrace(pWriter);
System.out.println("[" + prefix + "] " + content.toString() + System.lineSeparator() + System.lineSeparator()
+ sWriter.toString());
}
}
|
StringWriter sWriter = new StringWriter();
PrintWriter pWriter = new PrintWriter(sWriter);
error.printStackTrace(pWriter);
System.err.println("[error] " + sWriter.toString());
| 1,218
| 59
| 1,277
|
<no_super_class>
|
apache_maven
|
maven/maven-repository-metadata/src/main/java/org/apache/maven/artifact/repository/metadata/BaseObject.java
|
BaseObject
|
update
|
class BaseObject implements Serializable, Cloneable {
protected transient ChildrenTracking childrenTracking;
protected Object delegate;
public BaseObject() {}
public BaseObject(Object delegate, BaseObject parent) {
this.delegate = delegate;
this.childrenTracking = parent != null ? parent::replace : null;
}
public BaseObject(Object delegate, ChildrenTracking parent) {
this.delegate = delegate;
this.childrenTracking = parent;
}
public Object getDelegate() {
return delegate;
}
public void update(Object newDelegate) {<FILL_FUNCTION_BODY>}
protected boolean replace(Object oldDelegate, Object newDelegate) {
return false;
}
@FunctionalInterface
protected interface ChildrenTracking {
boolean replace(Object oldDelegate, Object newDelegate);
}
}
|
if (delegate != newDelegate) {
if (childrenTracking != null) {
childrenTracking.replace(delegate, newDelegate);
}
delegate = newDelegate;
}
| 222
| 56
| 278
|
<no_super_class>
|
apache_maven
|
maven/maven-repository-metadata/src/main/java/org/apache/maven/artifact/repository/metadata/io/xpp3/MetadataXpp3Reader.java
|
MetadataXpp3Reader
|
read
|
class MetadataXpp3Reader {
private final MetadataStaxReader delegate;
/**
* Default constructor
*/
public MetadataXpp3Reader() {
delegate = new MetadataStaxReader();
}
/**
* Constructor with ContentTransformer
*
* @param contentTransformer a transformer
*/
public MetadataXpp3Reader(ContentTransformer contentTransformer) {
delegate = new MetadataStaxReader(contentTransformer::transform);
}
/**
* Returns the state of the "add default entities" flag.
*
* @return boolean a field value
*/
public boolean getAddDefaultEntities() {
return delegate.getAddDefaultEntities();
}
/**
* Sets the state of the "add default entities" flag.
*
* @param addDefaultEntities a addDefaultEntities object.
*/
public void setAddDefaultEntities(boolean addDefaultEntities) {
delegate.setAddDefaultEntities(addDefaultEntities);
}
/**
* Method read.
*
* @param reader a reader object.
* @param strict a strict object.
* @return Metadata
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
*/
public Metadata read(Reader reader, boolean strict) throws IOException, XmlPullParserException {
try {
return new Metadata(delegate.read(reader, strict));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
/**
* Method read.
*
* @param reader a reader object.
* @return Metadata
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
*/
public Metadata read(Reader reader) throws IOException, XmlPullParserException {<FILL_FUNCTION_BODY>}
/**
* Method read.
*
* @param in a in object.
* @param strict a strict object.
* @return Metadata
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
*/
public Metadata read(InputStream in, boolean strict) throws IOException, XmlPullParserException {
try {
return new Metadata(delegate.read(in, strict));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
/**
* Method read.
*
* @param in a in object.
* @return Metadata
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
*/
public Metadata read(InputStream in) throws IOException, XmlPullParserException {
try {
return new Metadata(delegate.read(in));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
/**
* Method read.
*
* @param parser a parser object.
* @param strict a strict object.
* @return Metadata
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
*/
public Metadata read(XMLStreamReader parser, boolean strict) throws IOException, XmlPullParserException {
try {
return new Metadata(delegate.read(parser, strict));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
/**
* {@link MetadataStaxReader.ContentTransformer}
*/
public interface ContentTransformer {
/**
* Interpolate the value read from the xpp3 document
*
* @param source The source value
* @param fieldName A description of the field being interpolated. The implementation may use this to
* log stuff.
* @return The interpolated value.
*/
String transform(String source, String fieldName);
}
}
|
try {
return new Metadata(delegate.read(reader));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
| 1,100
| 55
| 1,155
|
<no_super_class>
|
apache_maven
|
maven/maven-repository-metadata/src/main/java/org/apache/maven/artifact/repository/metadata/io/xpp3/MetadataXpp3Writer.java
|
MetadataXpp3Writer
|
write
|
class MetadataXpp3Writer {
private final MetadataStaxWriter delegate;
/**
* Default constructor
*/
public MetadataXpp3Writer() {
delegate = new MetadataStaxWriter();
}
/**
* Method setFileComment.
*
* @param fileComment a fileComment object.
*/
public void setFileComment(String fileComment) {
delegate.setFileComment(fileComment);
}
/**
* Method write.
*
* @param writer a writer object
* @param metadata a Metadata object
* @throws java.io.IOException java.io.IOException if any
*/
public void write(Writer writer, Metadata metadata) throws java.io.IOException {
try {
delegate.write(writer, metadata.getDelegate());
} catch (XMLStreamException e) {
throw new IOException(e);
}
}
/**
* Method write.
*
* @param stream a stream object
* @param metadata a Metadata object
* @throws java.io.IOException java.io.IOException if any
*/
public void write(OutputStream stream, Metadata metadata) throws java.io.IOException {<FILL_FUNCTION_BODY>}
}
|
try {
delegate.write(stream, metadata.getDelegate());
} catch (XMLStreamException e) {
throw new IOException(e);
}
| 316
| 42
| 358
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/ArtifactDescriptorReaderDelegate.java
|
ArtifactDescriptorReaderDelegate
|
setArtifactProperties
|
class ArtifactDescriptorReaderDelegate {
public void populateResult(RepositorySystemSession session, ArtifactDescriptorResult result, Model model) {
ArtifactTypeRegistry stereotypes = session.getArtifactTypeRegistry();
for (Repository r : model.getRepositories()) {
result.addRepository(ArtifactDescriptorUtils.toRemoteRepository(r));
}
for (org.apache.maven.model.Dependency dependency : model.getDependencies()) {
result.addDependency(convert(dependency, stereotypes));
}
DependencyManagement mgmt = model.getDependencyManagement();
if (mgmt != null) {
for (org.apache.maven.model.Dependency dependency : mgmt.getDependencies()) {
result.addManagedDependency(convert(dependency, stereotypes));
}
}
Map<String, Object> properties = new LinkedHashMap<>();
Prerequisites prerequisites = model.getPrerequisites();
if (prerequisites != null) {
properties.put("prerequisites.maven", prerequisites.getMaven());
}
List<License> licenses = model.getLicenses();
properties.put("license.count", licenses.size());
for (int i = 0; i < licenses.size(); i++) {
License license = licenses.get(i);
properties.put("license." + i + ".name", license.getName());
properties.put("license." + i + ".url", license.getUrl());
properties.put("license." + i + ".comments", license.getComments());
properties.put("license." + i + ".distribution", license.getDistribution());
}
result.setProperties(properties);
setArtifactProperties(result, model);
}
private Dependency convert(org.apache.maven.model.Dependency dependency, ArtifactTypeRegistry stereotypes) {
ArtifactType stereotype = stereotypes.get(dependency.getType());
if (stereotype == null) {
// TODO: this here is fishy
stereotype = new DefaultType(dependency.getType(), Language.NONE, "", null, false);
}
boolean system = dependency.getSystemPath() != null
&& !dependency.getSystemPath().isEmpty();
Map<String, String> props = null;
if (system) {
props = Collections.singletonMap(MavenArtifactProperties.LOCAL_PATH, dependency.getSystemPath());
}
Artifact artifact = new DefaultArtifact(
dependency.getGroupId(),
dependency.getArtifactId(),
dependency.getClassifier(),
null,
dependency.getVersion(),
props,
stereotype);
List<Exclusion> exclusions = new ArrayList<>(dependency.getExclusions().size());
for (org.apache.maven.model.Exclusion exclusion : dependency.getExclusions()) {
exclusions.add(convert(exclusion));
}
return new Dependency(
artifact,
dependency.getScope(),
dependency.getOptional() != null ? dependency.isOptional() : null,
exclusions);
}
private Exclusion convert(org.apache.maven.model.Exclusion exclusion) {
return new Exclusion(exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*");
}
private void setArtifactProperties(ArtifactDescriptorResult result, Model model) {<FILL_FUNCTION_BODY>}
}
|
String downloadUrl = null;
DistributionManagement distMgmt = model.getDistributionManagement();
if (distMgmt != null) {
downloadUrl = distMgmt.getDownloadUrl();
}
if (downloadUrl != null && !downloadUrl.isEmpty()) {
Artifact artifact = result.getArtifact();
Map<String, String> props = new HashMap<>(artifact.getProperties());
props.put(ArtifactProperties.DOWNLOAD_URL, downloadUrl);
result.setArtifact(artifact.setProperties(props));
}
| 876
| 144
| 1,020
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/ArtifactDescriptorUtils.java
|
ArtifactDescriptorUtils
|
toRepositoryPolicy
|
class ArtifactDescriptorUtils {
public static Artifact toPomArtifact(Artifact artifact) {
Artifact pomArtifact = artifact;
if (!pomArtifact.getClassifier().isEmpty() || !"pom".equals(pomArtifact.getExtension())) {
pomArtifact =
new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), "pom", artifact.getVersion());
}
return pomArtifact;
}
/**
* Creates POM artifact out of passed in artifact by dropping classifier (if exists) and rewriting extension to
* "pom". Unconditionally, unlike {@link #toPomArtifact(Artifact)} that does this only for artifacts without
* classifiers.
*
* @since 4.0.0
*/
public static Artifact toPomArtifactUnconditionally(Artifact artifact) {
return new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), "pom", artifact.getVersion());
}
public static RemoteRepository toRemoteRepository(Repository repository) {
RemoteRepository.Builder builder =
new RemoteRepository.Builder(repository.getId(), repository.getLayout(), repository.getUrl());
builder.setSnapshotPolicy(toRepositoryPolicy(repository.getSnapshots()));
builder.setReleasePolicy(toRepositoryPolicy(repository.getReleases()));
return builder.build();
}
public static RepositoryPolicy toRepositoryPolicy(org.apache.maven.model.RepositoryPolicy policy) {<FILL_FUNCTION_BODY>}
public static String toRepositoryChecksumPolicy(final String artifactRepositoryPolicy) {
switch (artifactRepositoryPolicy) {
case RepositoryPolicy.CHECKSUM_POLICY_FAIL:
return RepositoryPolicy.CHECKSUM_POLICY_FAIL;
case RepositoryPolicy.CHECKSUM_POLICY_IGNORE:
return RepositoryPolicy.CHECKSUM_POLICY_IGNORE;
case RepositoryPolicy.CHECKSUM_POLICY_WARN:
return RepositoryPolicy.CHECKSUM_POLICY_WARN;
default:
throw new IllegalArgumentException("unknown repository checksum policy: " + artifactRepositoryPolicy);
}
}
}
|
boolean enabled = true;
String checksums = toRepositoryChecksumPolicy(RepositoryPolicy.CHECKSUM_POLICY_WARN); // the default
String updates = RepositoryPolicy.UPDATE_POLICY_DAILY;
if (policy != null) {
enabled = policy.isEnabled();
if (policy.getUpdatePolicy() != null) {
updates = policy.getUpdatePolicy();
}
if (policy.getChecksumPolicy() != null) {
checksums = policy.getChecksumPolicy();
}
}
return new RepositoryPolicy(enabled, updates, checksums);
| 563
| 161
| 724
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/DefaultModelCache.java
|
GavCacheKey
|
equals
|
class GavCacheKey {
private final String gav;
private final String tag;
private final int hash;
GavCacheKey(String groupId, String artifactId, String version, String tag) {
this(gav(groupId, artifactId, version), tag);
}
GavCacheKey(String gav, String tag) {
this.gav = gav;
this.tag = tag;
this.hash = Objects.hash(gav, tag);
}
private static String gav(String groupId, String artifactId, String version) {
StringBuilder sb = new StringBuilder();
if (groupId != null) {
sb.append(groupId);
}
sb.append(":");
if (artifactId != null) {
sb.append(artifactId);
}
sb.append(":");
if (version != null) {
sb.append(version);
}
return sb.toString();
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return hash;
}
@Override
public String toString() {
return "GavCacheKey{" + "gav='" + gav + '\'' + ", tag='" + tag + '\'' + '}';
}
}
|
if (this == obj) {
return true;
}
if (null == obj || !getClass().equals(obj.getClass())) {
return false;
}
GavCacheKey that = (GavCacheKey) obj;
return Objects.equals(this.gav, that.gav) && Objects.equals(this.tag, that.tag);
| 349
| 96
| 445
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/DefaultModelVersionParser.java
|
DefaultVersionConstraint
|
contains
|
class DefaultVersionConstraint implements VersionConstraint {
private final VersionScheme versionScheme;
private final org.eclipse.aether.version.VersionConstraint delegate;
DefaultVersionConstraint(VersionScheme versionScheme, String delegateValue) {
this.versionScheme = versionScheme;
try {
this.delegate = versionScheme.parseVersionConstraint(delegateValue);
} catch (InvalidVersionSpecificationException e) {
throw new VersionParserException("Unable to parse version constraint: " + delegateValue, e);
}
}
@Override
public boolean contains(Version version) {<FILL_FUNCTION_BODY>}
@Override
public String asString() {
return delegate.toString();
}
@Override
public VersionRange getVersionRange() {
if (delegate.getRange() == null) {
return null;
}
return new DefaultVersionRange(versionScheme, delegate.getRange());
}
@Override
public Version getRecommendedVersion() {
if (delegate.getVersion() == null) {
return null;
}
return new DefaultVersion(versionScheme, delegate.getVersion());
}
@Override
public String toString() {
return asString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultVersionConstraint that = (DefaultVersionConstraint) o;
return delegate.equals(that.delegate);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
}
|
if (version instanceof DefaultVersion) {
return delegate.containsVersion(((DefaultVersion) version).delegate);
} else {
return contains(new DefaultVersion(versionScheme, version.asString()));
}
| 437
| 57
| 494
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/DefaultVersionRangeResolver.java
|
DefaultVersionRangeResolver
|
invalidMetadata
|
class DefaultVersionRangeResolver implements VersionRangeResolver {
private static final String MAVEN_METADATA_XML = "maven-metadata.xml";
private final MetadataResolver metadataResolver;
private final SyncContextFactory syncContextFactory;
private final RepositoryEventDispatcher repositoryEventDispatcher;
private final VersionScheme versionScheme;
@Inject
public DefaultVersionRangeResolver(
MetadataResolver metadataResolver,
SyncContextFactory syncContextFactory,
RepositoryEventDispatcher repositoryEventDispatcher,
VersionScheme versionScheme) {
this.metadataResolver = Objects.requireNonNull(metadataResolver, "metadataResolver cannot be null");
this.syncContextFactory = Objects.requireNonNull(syncContextFactory, "syncContextFactory cannot be null");
this.repositoryEventDispatcher =
Objects.requireNonNull(repositoryEventDispatcher, "repositoryEventDispatcher cannot be null");
this.versionScheme = Objects.requireNonNull(versionScheme, "versionScheme cannot be null");
}
@Override
public VersionRangeResult resolveVersionRange(RepositorySystemSession session, VersionRangeRequest request)
throws VersionRangeResolutionException {
VersionRangeResult result = new VersionRangeResult(request);
VersionConstraint versionConstraint;
try {
versionConstraint =
versionScheme.parseVersionConstraint(request.getArtifact().getVersion());
} catch (InvalidVersionSpecificationException e) {
result.addException(e);
throw new VersionRangeResolutionException(result);
}
result.setVersionConstraint(versionConstraint);
if (versionConstraint.getRange() == null) {
result.addVersion(versionConstraint.getVersion());
} else {
VersionRange.Bound lowerBound = versionConstraint.getRange().getLowerBound();
if (lowerBound != null
&& lowerBound.equals(versionConstraint.getRange().getUpperBound())) {
result.addVersion(lowerBound.getVersion());
} else {
Map<String, ArtifactRepository> versionIndex = getVersions(session, result, request);
List<Version> versions = new ArrayList<>();
for (Map.Entry<String, ArtifactRepository> v : versionIndex.entrySet()) {
try {
Version ver = versionScheme.parseVersion(v.getKey());
if (versionConstraint.containsVersion(ver)) {
versions.add(ver);
result.setRepository(ver, v.getValue());
}
} catch (InvalidVersionSpecificationException e) {
result.addException(e);
}
}
Collections.sort(versions);
result.setVersions(versions);
}
}
return result;
}
private Map<String, ArtifactRepository> getVersions(
RepositorySystemSession session, VersionRangeResult result, VersionRangeRequest request) {
RequestTrace trace = RequestTrace.newChild(request.getTrace(), request);
Map<String, ArtifactRepository> versionIndex = new HashMap<>();
Metadata metadata = new DefaultMetadata(
request.getArtifact().getGroupId(),
request.getArtifact().getArtifactId(),
MAVEN_METADATA_XML,
Metadata.Nature.RELEASE_OR_SNAPSHOT);
List<MetadataRequest> metadataRequests =
new ArrayList<>(request.getRepositories().size());
metadataRequests.add(new MetadataRequest(metadata, null, request.getRequestContext()));
for (RemoteRepository repository : request.getRepositories()) {
MetadataRequest metadataRequest = new MetadataRequest(metadata, repository, request.getRequestContext());
metadataRequest.setDeleteLocalCopyIfMissing(true);
metadataRequest.setTrace(trace);
metadataRequests.add(metadataRequest);
}
List<MetadataResult> metadataResults = metadataResolver.resolveMetadata(session, metadataRequests);
WorkspaceReader workspace = session.getWorkspaceReader();
if (workspace != null) {
List<String> versions = workspace.findVersions(request.getArtifact());
for (String version : versions) {
versionIndex.put(version, workspace.getRepository());
}
}
for (MetadataResult metadataResult : metadataResults) {
result.addException(metadataResult.getException());
ArtifactRepository repository = metadataResult.getRequest().getRepository();
if (repository == null) {
repository = session.getLocalRepository();
}
Versioning versioning = readVersions(session, trace, metadataResult.getMetadata(), repository, result);
versioning = filterVersionsByRepositoryType(
versioning, metadataResult.getRequest().getRepository());
for (String version : versioning.getVersions()) {
if (!versionIndex.containsKey(version)) {
versionIndex.put(version, repository);
}
}
}
return versionIndex;
}
private Versioning readVersions(
RepositorySystemSession session,
RequestTrace trace,
Metadata metadata,
ArtifactRepository repository,
VersionRangeResult result) {
Versioning versioning = null;
try {
if (metadata != null) {
try (SyncContext syncContext = syncContextFactory.newInstance(session, true)) {
syncContext.acquire(null, Collections.singleton(metadata));
if (metadata.getPath() != null && Files.exists(metadata.getPath())) {
try (InputStream in = Files.newInputStream(metadata.getPath())) {
versioning = new Versioning(
new MetadataStaxReader().read(in, false).getVersioning());
}
}
}
}
} catch (Exception e) {
invalidMetadata(session, trace, metadata, repository, e);
result.addException(e);
}
return (versioning != null) ? versioning : new Versioning();
}
private Versioning filterVersionsByRepositoryType(Versioning versioning, RemoteRepository remoteRepository) {
if (remoteRepository == null) {
return versioning;
}
Versioning filteredVersions = versioning.clone();
for (String version : versioning.getVersions()) {
if (!remoteRepository
.getPolicy(DefaultModelVersionParser.checkSnapshot(version))
.isEnabled()) {
filteredVersions.removeVersion(version);
}
}
return filteredVersions;
}
private void invalidMetadata(
RepositorySystemSession session,
RequestTrace trace,
Metadata metadata,
ArtifactRepository repository,
Exception exception) {<FILL_FUNCTION_BODY>}
}
|
RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_INVALID);
event.setTrace(trace);
event.setMetadata(metadata);
event.setException(exception);
event.setRepository(repository);
repositoryEventDispatcher.dispatch(event.build());
| 1,646
| 82
| 1,728
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/LocalSnapshotMetadata.java
|
LocalSnapshotMetadata
|
merge
|
class LocalSnapshotMetadata extends MavenMetadata {
private final Collection<Artifact> artifacts = new ArrayList<>();
LocalSnapshotMetadata(Artifact artifact, Date timestamp) {
super(createMetadata(artifact), (Path) null, timestamp);
}
LocalSnapshotMetadata(Metadata metadata, Path path, Date timestamp) {
super(metadata, path, timestamp);
}
private static Metadata createMetadata(Artifact artifact) {
Snapshot snapshot = new Snapshot();
snapshot.setLocalCopy(true);
Versioning versioning = new Versioning();
versioning.setSnapshot(snapshot);
Metadata metadata = new Metadata();
metadata.setVersioning(versioning);
metadata.setGroupId(artifact.getGroupId());
metadata.setArtifactId(artifact.getArtifactId());
metadata.setVersion(artifact.getBaseVersion());
metadata.setModelVersion("1.1.0");
return metadata;
}
public void bind(Artifact artifact) {
artifacts.add(artifact);
}
@Deprecated
@Override
public MavenMetadata setFile(File file) {
return new LocalSnapshotMetadata(metadata, file.toPath(), timestamp);
}
@Override
public MavenMetadata setPath(Path path) {
return new LocalSnapshotMetadata(metadata, path, timestamp);
}
public Object getKey() {
return getGroupId() + ':' + getArtifactId() + ':' + getVersion();
}
public static Object getKey(Artifact artifact) {
return artifact.getGroupId() + ':' + artifact.getArtifactId() + ':' + artifact.getBaseVersion();
}
@Override
protected void merge(Metadata recessive) {<FILL_FUNCTION_BODY>}
private String getKey(String classifier, String extension) {
return classifier + ':' + extension;
}
@Override
public String getGroupId() {
return metadata.getGroupId();
}
@Override
public String getArtifactId() {
return metadata.getArtifactId();
}
@Override
public String getVersion() {
return metadata.getVersion();
}
@Override
public Nature getNature() {
return Nature.SNAPSHOT;
}
}
|
metadata.getVersioning().setLastUpdatedTimestamp(timestamp);
String lastUpdated = metadata.getVersioning().getLastUpdated();
Map<String, SnapshotVersion> versions = new LinkedHashMap<>();
for (Artifact artifact : artifacts) {
SnapshotVersion sv = new SnapshotVersion();
sv.setClassifier(artifact.getClassifier());
sv.setExtension(artifact.getExtension());
sv.setVersion(getVersion());
sv.setUpdated(lastUpdated);
versions.put(getKey(sv.getClassifier(), sv.getExtension()), sv);
}
Versioning versioning = recessive.getVersioning();
if (versioning != null) {
for (SnapshotVersion sv : versioning.getSnapshotVersions()) {
String key = getKey(sv.getClassifier(), sv.getExtension());
if (!versions.containsKey(key)) {
versions.put(key, sv);
}
}
}
metadata.getVersioning().setSnapshotVersions(new ArrayList<>(versions.values()));
artifacts.clear();
| 585
| 274
| 859
|
<methods>public java.io.File getFile() ,public java.nio.file.Path getPath() ,public Map<java.lang.String,java.lang.String> getProperties() ,public java.lang.String getType() ,public boolean isMerged() ,public void merge(java.io.File, java.io.File) throws RepositoryException,public void merge(java.nio.file.Path, java.nio.file.Path) throws RepositoryException,public org.eclipse.aether.metadata.Metadata setProperties(Map<java.lang.String,java.lang.String>) <variables>static final java.lang.String MAVEN_METADATA_XML,private boolean merged,protected org.apache.maven.artifact.repository.metadata.Metadata metadata,private final non-sealed java.nio.file.Path path,protected final non-sealed java.util.Date timestamp
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/LocalSnapshotMetadataGenerator.java
|
LocalSnapshotMetadataGenerator
|
prepare
|
class LocalSnapshotMetadataGenerator implements MetadataGenerator {
private final Map<Object, LocalSnapshotMetadata> snapshots;
private final Date timestamp;
LocalSnapshotMetadataGenerator(RepositorySystemSession session, InstallRequest request) {
timestamp = (Date) ConfigUtils.getObject(session, new Date(), "maven.startTime");
snapshots = new LinkedHashMap<>();
}
@Override
public Collection<? extends Metadata> prepare(Collection<? extends Artifact> artifacts) {<FILL_FUNCTION_BODY>}
@Override
public Artifact transformArtifact(Artifact artifact) {
return artifact;
}
@Override
public Collection<? extends Metadata> finish(Collection<? extends Artifact> artifacts) {
return snapshots.values();
}
}
|
for (Artifact artifact : artifacts) {
if (artifact.isSnapshot()) {
Object key = LocalSnapshotMetadata.getKey(artifact);
LocalSnapshotMetadata snapshotMetadata = snapshots.get(key);
if (snapshotMetadata == null) {
snapshotMetadata = new LocalSnapshotMetadata(artifact, timestamp);
snapshots.put(key, snapshotMetadata);
}
snapshotMetadata.bind(artifact);
}
}
return Collections.emptyList();
| 200
| 119
| 319
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/MavenMetadata.java
|
MavenMetadata
|
write
|
class MavenMetadata extends AbstractMetadata implements MergeableMetadata {
static final String MAVEN_METADATA_XML = "maven-metadata.xml";
protected Metadata metadata;
private final Path path;
protected final Date timestamp;
private boolean merged;
@Deprecated
protected MavenMetadata(Metadata metadata, File file, Date timestamp) {
this(metadata, file != null ? file.toPath() : null, timestamp);
}
protected MavenMetadata(Metadata metadata, Path path, Date timestamp) {
this.metadata = metadata;
this.path = path;
this.timestamp = timestamp;
}
@Override
public String getType() {
return MAVEN_METADATA_XML;
}
@Deprecated
@Override
public File getFile() {
return path != null ? path.toFile() : null;
}
@Override
public Path getPath() {
return path;
}
public void merge(File existing, File result) throws RepositoryException {
merge(existing != null ? existing.toPath() : null, result != null ? result.toPath() : null);
}
@Override
public void merge(Path existing, Path result) throws RepositoryException {
Metadata recessive = read(existing);
merge(recessive);
write(result, metadata);
merged = true;
}
@Override
public boolean isMerged() {
return merged;
}
protected abstract void merge(Metadata recessive);
static Metadata read(Path metadataPath) throws RepositoryException {
if (!Files.exists(metadataPath)) {
return new Metadata();
}
try (InputStream input = Files.newInputStream(metadataPath)) {
return new Metadata(new MetadataStaxReader().read(input, false));
} catch (IOException | XMLStreamException e) {
throw new RepositoryException("Could not parse metadata " + metadataPath + ": " + e.getMessage(), e);
}
}
private void write(Path metadataPath, Metadata metadata) throws RepositoryException {<FILL_FUNCTION_BODY>}
@Override
public Map<String, String> getProperties() {
return Collections.emptyMap();
}
@Override
public org.eclipse.aether.metadata.Metadata setProperties(Map<String, String> properties) {
return this;
}
}
|
try {
Files.createDirectories(metadataPath.getParent());
try (OutputStream output = Files.newOutputStream(metadataPath)) {
new MetadataStaxWriter().write(output, metadata.getDelegate());
}
} catch (IOException | XMLStreamException e) {
throw new RepositoryException("Could not write metadata " + metadataPath + ": " + e.getMessage(), e);
}
| 624
| 101
| 725
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/MavenRepositorySystemUtils.java
|
MavenRepositorySystemUtils
|
newSession
|
class MavenRepositorySystemUtils {
private MavenRepositorySystemUtils() {
// hide constructor
}
/**
* This method is deprecated, nobody should use it.
*
* @deprecated This method is here only for legacy uses (like UTs), nothing else should use it.
*/
@Deprecated
public static DefaultRepositorySystemSession newSession() {<FILL_FUNCTION_BODY>}
}
|
DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(h -> false); // no close handle
MavenSessionBuilderSupplier builder = new MavenSessionBuilderSupplier();
session.setDependencyTraverser(builder.getDependencyTraverser());
session.setDependencyManager(new ClassicDependencyManager()); // Maven 3 behavior
session.setDependencySelector(builder.getDependencySelector());
session.setDependencyGraphTransformer(builder.getDependencyGraphTransformer());
session.setArtifactTypeRegistry(builder.getArtifactTypeRegistry());
session.setArtifactDescriptorPolicy(builder.getArtifactDescriptorPolicy());
return session;
| 107
| 154
| 261
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/MavenSessionBuilderSupplier.java
|
MavenSessionBuilderSupplier
|
getDependencySelector
|
class MavenSessionBuilderSupplier implements Supplier<SessionBuilder> {
protected final RepositorySystem repositorySystem;
protected final InternalScopeManager scopeManager;
public MavenSessionBuilderSupplier(RepositorySystem repositorySystem) {
this.repositorySystem = requireNonNull(repositorySystem);
this.scopeManager = new ScopeManagerImpl(Maven4ScopeManagerConfiguration.INSTANCE);
}
/**
* Package protected constructor, only for use with {@link MavenRepositorySystemUtils}.
*/
@Deprecated
MavenSessionBuilderSupplier() {
this.repositorySystem = null;
this.scopeManager = new ScopeManagerImpl(Maven4ScopeManagerConfiguration.INSTANCE);
}
protected InternalScopeManager getScopeManager() {
return scopeManager;
}
protected DependencyTraverser getDependencyTraverser() {
return new FatArtifactTraverser();
}
protected DependencyManager getDependencyManager() {
return getDependencyManager(true); // same default as in Maven4
}
public DependencyManager getDependencyManager(boolean transitive) {
return new ClassicDependencyManager(transitive, getScopeManager());
}
protected DependencySelector getDependencySelector() {<FILL_FUNCTION_BODY>}
protected DependencyGraphTransformer getDependencyGraphTransformer() {
return new ChainedDependencyGraphTransformer(
new ConflictResolver(
new NearestVersionSelector(), new ManagedScopeSelector(getScopeManager()),
new SimpleOptionalitySelector(), new ManagedScopeDeriver(getScopeManager())),
new ManagedDependencyContextRefiner(getScopeManager()));
}
/**
* This method produces "surrogate" type registry that is static: it aims users that want to use
* Maven-Resolver without involving Maven Core and related things.
* <p>
* This type registry is NOT used by Maven Core: Maven replaces it during Session creation with a type registry
* that supports extending it (i.e. via Maven Extensions).
* <p>
* Important: this "static" list of types should be in-sync with core provided types.
*/
protected ArtifactTypeRegistry getArtifactTypeRegistry() {
DefaultArtifactTypeRegistry stereotypes = new DefaultArtifactTypeRegistry();
new DefaultTypeProvider().types().forEach(stereotypes::add);
return stereotypes;
}
protected ArtifactDescriptorPolicy getArtifactDescriptorPolicy() {
return new SimpleArtifactDescriptorPolicy(true, true);
}
protected void configureSessionBuilder(SessionBuilder session) {
session.setDependencyTraverser(getDependencyTraverser());
session.setDependencyManager(getDependencyManager());
session.setDependencySelector(getDependencySelector());
session.setDependencyGraphTransformer(getDependencyGraphTransformer());
session.setArtifactTypeRegistry(getArtifactTypeRegistry());
session.setArtifactDescriptorPolicy(getArtifactDescriptorPolicy());
session.setScopeManager(getScopeManager());
}
/**
* Creates a new Maven-like repository system session by initializing the session with values typical for
* Maven-based resolution. In more detail, this method configures settings relevant for the processing of dependency
* graphs, most other settings remain at their generic default value. Use the various setters to further configure
* the session with authentication, mirror, proxy and other information required for your environment. At least,
* local repository manager needs to be configured to make session be able to create session instance.
*
* @return SessionBuilder configured with minimally required things for "Maven-based resolution". At least LRM must
* be set on builder to make it able to create session instances.
*/
@Override
public SessionBuilder get() {
requireNonNull(repositorySystem, "repositorySystem");
SessionBuilder builder = repositorySystem.createSessionBuilder();
configureSessionBuilder(builder);
return builder;
}
}
|
return new AndDependencySelector(
ScopeDependencySelector.legacy(
null, Arrays.asList(DependencyScope.TEST.id(), DependencyScope.PROVIDED.id())),
OptionalDependencySelector.fromDirect(),
new ExclusionDependencySelector());
| 960
| 67
| 1,027
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/PluginsMetadata.java
|
PluginInfo
|
merge
|
class PluginInfo {
final String groupId;
private final String artifactId;
private final String goalPrefix;
private final String name;
PluginInfo(String groupId, String artifactId, String goalPrefix, String name) {
this.groupId = groupId;
this.artifactId = artifactId;
this.goalPrefix = goalPrefix;
this.name = name;
}
}
private final PluginInfo pluginInfo;
PluginsMetadata(PluginInfo pluginInfo, Date timestamp) {
super(createRepositoryMetadata(pluginInfo), (Path) null, timestamp);
this.pluginInfo = pluginInfo;
}
PluginsMetadata(PluginInfo pluginInfo, Path path, Date timestamp) {
super(createRepositoryMetadata(pluginInfo), path, timestamp);
this.pluginInfo = pluginInfo;
}
private static Metadata createRepositoryMetadata(PluginInfo pluginInfo) {
Metadata result = new Metadata();
Plugin plugin = new Plugin();
plugin.setPrefix(pluginInfo.goalPrefix);
plugin.setArtifactId(pluginInfo.artifactId);
plugin.setName(pluginInfo.name);
result.getPlugins().add(plugin);
return result;
}
@Override
protected void merge(Metadata recessive) {<FILL_FUNCTION_BODY>
|
List<Plugin> recessivePlugins = recessive.getPlugins();
List<Plugin> plugins = metadata.getPlugins();
if (!plugins.isEmpty()) {
LinkedHashMap<String, Plugin> mergedPlugins = new LinkedHashMap<>();
recessivePlugins.forEach(p -> mergedPlugins.put(p.getPrefix(), p));
plugins.forEach(p -> mergedPlugins.put(p.getPrefix(), p));
metadata.setPlugins(new ArrayList<>(mergedPlugins.values()));
}
| 338
| 146
| 484
|
<methods>public java.io.File getFile() ,public java.nio.file.Path getPath() ,public Map<java.lang.String,java.lang.String> getProperties() ,public java.lang.String getType() ,public boolean isMerged() ,public void merge(java.io.File, java.io.File) throws RepositoryException,public void merge(java.nio.file.Path, java.nio.file.Path) throws RepositoryException,public org.eclipse.aether.metadata.Metadata setProperties(Map<java.lang.String,java.lang.String>) <variables>static final java.lang.String MAVEN_METADATA_XML,private boolean merged,protected org.apache.maven.artifact.repository.metadata.Metadata metadata,private final non-sealed java.nio.file.Path path,protected final non-sealed java.util.Date timestamp
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/PluginsMetadataGenerator.java
|
PluginsMetadataGenerator
|
finish
|
class PluginsMetadataGenerator implements MetadataGenerator {
private static final String PLUGIN_DESCRIPTOR_LOCATION = "META-INF/maven/plugin.xml";
private final Map<Object, PluginsMetadata> processedPlugins;
private final Date timestamp;
PluginsMetadataGenerator(RepositorySystemSession session, InstallRequest request) {
this(session, request.getMetadata());
}
PluginsMetadataGenerator(RepositorySystemSession session, DeployRequest request) {
this(session, request.getMetadata());
}
private PluginsMetadataGenerator(RepositorySystemSession session, Collection<? extends Metadata> metadatas) {
this.processedPlugins = new LinkedHashMap<>();
this.timestamp = (Date) ConfigUtils.getObject(session, new Date(), "maven.startTime");
/*
* NOTE: This should be considered a quirk to support interop with Maven's legacy ArtifactDeployer which
* processes one artifact at a time and hence cannot associate the artifacts from the same project to use the
* same version index. Allowing the caller to pass in metadata from a previous deployment allows to re-establish
* the association between the artifacts of the same project.
*/
for (Iterator<? extends Metadata> it = metadatas.iterator(); it.hasNext(); ) {
Metadata metadata = it.next();
if (metadata instanceof PluginsMetadata) {
it.remove();
PluginsMetadata pluginMetadata = (PluginsMetadata) metadata;
processedPlugins.put(pluginMetadata.getGroupId(), pluginMetadata);
}
}
}
@Override
public Collection<? extends Metadata> prepare(Collection<? extends Artifact> artifacts) {
return Collections.emptyList();
}
@Override
public Artifact transformArtifact(Artifact artifact) {
return artifact;
}
@Override
public Collection<? extends Metadata> finish(Collection<? extends Artifact> artifacts) {<FILL_FUNCTION_BODY>}
private PluginInfo extractPluginInfo(Artifact artifact) {
// sanity: jar, no classifier and file exists
if (artifact != null
&& "jar".equals(artifact.getExtension())
&& "".equals(artifact.getClassifier())
&& artifact.getPath() != null) {
Path artifactPath = artifact.getPath();
if (Files.isRegularFile(artifactPath)) {
try (JarFile artifactJar = new JarFile(artifactPath.toFile(), false)) {
ZipEntry pluginDescriptorEntry = artifactJar.getEntry(PLUGIN_DESCRIPTOR_LOCATION);
if (pluginDescriptorEntry != null) {
try (InputStream is = artifactJar.getInputStream(pluginDescriptorEntry)) {
// Note: using DOM instead of use of
// org.apache.maven.plugin.descriptor.PluginDescriptor
// as it would pull in dependency on:
// - maven-plugin-api (for model)
// - Plexus Container (for model supporting classes and exceptions)
XmlNode root = XmlNodeBuilder.build(is, null);
String groupId = root.getChild("groupId").getValue();
String artifactId = root.getChild("artifactId").getValue();
String goalPrefix = root.getChild("goalPrefix").getValue();
String name = root.getChild("name").getValue();
return new PluginInfo(groupId, artifactId, goalPrefix, name);
}
}
} catch (Exception e) {
// here we can have: IO. ZIP or Plexus Conf Ex: but we should not interfere with user intent
}
}
}
return null;
}
}
|
LinkedHashMap<String, PluginsMetadata> plugins = new LinkedHashMap<>();
for (Artifact artifact : artifacts) {
PluginInfo pluginInfo = extractPluginInfo(artifact);
if (pluginInfo != null) {
String key = pluginInfo.groupId;
if (processedPlugins.get(key) == null) {
PluginsMetadata pluginMetadata = plugins.get(key);
if (pluginMetadata == null) {
pluginMetadata = new PluginsMetadata(pluginInfo, timestamp);
plugins.put(key, pluginMetadata);
}
}
}
}
return plugins.values();
| 925
| 160
| 1,085
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/RelocatedArtifact.java
|
RelocatedArtifact
|
getVersion
|
class RelocatedArtifact extends AbstractArtifact {
private final Artifact artifact;
private final String groupId;
private final String artifactId;
private final String classifier;
private final String extension;
private final String version;
private final String message;
public RelocatedArtifact(
Artifact artifact,
String groupId,
String artifactId,
String classifier,
String extension,
String version,
String message) {
this.artifact = Objects.requireNonNull(artifact, "artifact cannot be null");
this.groupId = (groupId != null && !groupId.isEmpty()) ? groupId : null;
this.artifactId = (artifactId != null && !artifactId.isEmpty()) ? artifactId : null;
this.classifier = (classifier != null && !classifier.isEmpty()) ? classifier : null;
this.extension = (extension != null && !extension.isEmpty()) ? extension : null;
this.version = (version != null && !version.isEmpty()) ? version : null;
this.message = (message != null && !message.isEmpty()) ? message : null;
}
@Override
public String getGroupId() {
if (groupId != null) {
return groupId;
} else {
return artifact.getGroupId();
}
}
@Override
public String getArtifactId() {
if (artifactId != null) {
return artifactId;
} else {
return artifact.getArtifactId();
}
}
@Override
public String getClassifier() {
if (classifier != null) {
return classifier;
} else {
return artifact.getClassifier();
}
}
@Override
public String getExtension() {
if (extension != null) {
return extension;
} else {
return artifact.getExtension();
}
}
@Override
public String getVersion() {<FILL_FUNCTION_BODY>}
// Revise these three methods when MRESOLVER-233 is delivered
@Override
public Artifact setVersion(String version) {
String current = getVersion();
if (current.equals(version) || (version == null && current.isEmpty())) {
return this;
}
return new RelocatedArtifact(artifact, groupId, artifactId, classifier, extension, version, message);
}
@Deprecated
@Override
public Artifact setFile(File file) {
File current = getFile();
if (Objects.equals(current, file)) {
return this;
}
return new RelocatedArtifact(
artifact.setFile(file), groupId, artifactId, classifier, extension, version, message);
}
@Override
public Artifact setPath(Path path) {
Path current = getPath();
if (Objects.equals(current, path)) {
return this;
}
return new RelocatedArtifact(
artifact.setPath(path), groupId, artifactId, classifier, extension, version, message);
}
@Override
public Artifact setProperties(Map<String, String> properties) {
Map<String, String> current = getProperties();
if (current.equals(properties) || (properties == null && current.isEmpty())) {
return this;
}
return new RelocatedArtifact(
artifact.setProperties(properties), groupId, artifactId, classifier, extension, version, message);
}
@Deprecated
@Override
public File getFile() {
return artifact.getFile();
}
@Override
public Path getPath() {
return artifact.getPath();
}
@Override
public String getProperty(String key, String defaultValue) {
return artifact.getProperty(key, defaultValue);
}
@Override
public Map<String, String> getProperties() {
return artifact.getProperties();
}
public String getMessage() {
return message;
}
}
|
if (version != null) {
return version;
} else {
return artifact.getVersion();
}
| 1,021
| 34
| 1,055
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/RemoteSnapshotMetadata.java
|
RemoteSnapshotMetadata
|
merge
|
class RemoteSnapshotMetadata extends MavenSnapshotMetadata {
public static final String DEFAULT_SNAPSHOT_TIMESTAMP_FORMAT = "yyyyMMdd.HHmmss";
public static final TimeZone DEFAULT_SNAPSHOT_TIME_ZONE = TimeZone.getTimeZone("Etc/UTC");
private final Map<String, SnapshotVersion> versions = new LinkedHashMap<>();
private final Integer buildNumber;
RemoteSnapshotMetadata(Artifact artifact, Date timestamp, Integer buildNumber) {
super(createRepositoryMetadata(artifact), null, timestamp);
this.buildNumber = buildNumber;
}
private RemoteSnapshotMetadata(Metadata metadata, Path path, Date timestamp, Integer buildNumber) {
super(metadata, path, timestamp);
this.buildNumber = buildNumber;
}
@Deprecated
@Override
public MavenMetadata setFile(File file) {
return new RemoteSnapshotMetadata(metadata, file.toPath(), timestamp, buildNumber);
}
@Override
public MavenMetadata setPath(Path path) {
return new RemoteSnapshotMetadata(metadata, path, timestamp, buildNumber);
}
public String getExpandedVersion(Artifact artifact) {
String key = getKey(artifact.getClassifier(), artifact.getExtension());
return versions.get(key).getVersion();
}
@Override
protected void merge(Metadata recessive) {<FILL_FUNCTION_BODY>}
private static int getBuildNumber(Metadata metadata) {
int number = 0;
Versioning versioning = metadata.getVersioning();
if (versioning != null) {
Snapshot snapshot = versioning.getSnapshot();
if (snapshot != null && snapshot.getBuildNumber() > 0) {
number = snapshot.getBuildNumber();
}
}
return number;
}
}
|
Snapshot snapshot;
String lastUpdated;
if (metadata.getVersioning() == null) {
DateFormat utcDateFormatter = new SimpleDateFormat(DEFAULT_SNAPSHOT_TIMESTAMP_FORMAT);
utcDateFormatter.setCalendar(new GregorianCalendar());
utcDateFormatter.setTimeZone(DEFAULT_SNAPSHOT_TIME_ZONE);
snapshot = new Snapshot();
snapshot.setBuildNumber(buildNumber != null ? buildNumber : getBuildNumber(recessive) + 1);
snapshot.setTimestamp(utcDateFormatter.format(timestamp));
Versioning versioning = new Versioning();
versioning.setSnapshot(snapshot);
versioning.setLastUpdatedTimestamp(timestamp);
lastUpdated = versioning.getLastUpdated();
metadata.setVersioning(versioning);
} else {
snapshot = metadata.getVersioning().getSnapshot();
lastUpdated = metadata.getVersioning().getLastUpdated();
}
for (Artifact artifact : artifacts) {
String version = artifact.getVersion();
if (version.endsWith(SNAPSHOT)) {
String qualifier = snapshot.getTimestamp() + '-' + snapshot.getBuildNumber();
version = version.substring(0, version.length() - SNAPSHOT.length()) + qualifier;
}
SnapshotVersion sv = new SnapshotVersion();
sv.setClassifier(artifact.getClassifier());
sv.setExtension(artifact.getExtension());
sv.setVersion(version);
sv.setUpdated(lastUpdated);
versions.put(getKey(sv.getClassifier(), sv.getExtension()), sv);
}
artifacts.clear();
Versioning versioning = recessive.getVersioning();
if (versioning != null) {
for (SnapshotVersion sv : versioning.getSnapshotVersions()) {
String key = getKey(sv.getClassifier(), sv.getExtension());
if (!versions.containsKey(key)) {
versions.put(key, sv);
}
}
}
metadata.getVersioning().setSnapshotVersions(new ArrayList<>(versions.values()));
| 461
| 546
| 1,007
|
<methods>public void bind(Artifact) ,public java.lang.String getArtifactId() ,public java.lang.String getGroupId() ,public java.lang.Object getKey() ,public static java.lang.Object getKey(Artifact) ,public Nature getNature() ,public java.lang.String getVersion() <variables>static final java.lang.String SNAPSHOT,protected final Collection<Artifact> artifacts
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/RemoteSnapshotMetadataGenerator.java
|
RemoteSnapshotMetadataGenerator
|
transformArtifact
|
class RemoteSnapshotMetadataGenerator implements MetadataGenerator {
private final Map<Object, RemoteSnapshotMetadata> snapshots;
private final Date timestamp;
private final Integer buildNumber;
RemoteSnapshotMetadataGenerator(RepositorySystemSession session, DeployRequest request) {
timestamp = (Date) ConfigUtils.getObject(session, new Date(), "maven.startTime");
Object bn = ConfigUtils.getObject(session, null, "maven.buildNumber");
if (bn instanceof Integer) {
this.buildNumber = (Integer) bn;
} else if (bn instanceof String) {
this.buildNumber = Integer.valueOf((String) bn);
} else {
this.buildNumber = null;
}
snapshots = new LinkedHashMap<>();
/*
* NOTE: This should be considered a quirk to support interop with Maven's legacy ArtifactDeployer which
* processes one artifact at a time and hence cannot associate the artifacts from the same project to use the
* same timestamp+buildno for the snapshot versions. Allowing the caller to pass in metadata from a previous
* deployment allows to re-establish the association between the artifacts of the same project.
*/
for (Metadata metadata : request.getMetadata()) {
if (metadata instanceof RemoteSnapshotMetadata) {
RemoteSnapshotMetadata snapshotMetadata = (RemoteSnapshotMetadata) metadata;
snapshots.put(snapshotMetadata.getKey(), snapshotMetadata);
}
}
}
@Override
public Collection<? extends Metadata> prepare(Collection<? extends Artifact> artifacts) {
for (Artifact artifact : artifacts) {
if (artifact.isSnapshot()) {
Object key = RemoteSnapshotMetadata.getKey(artifact);
RemoteSnapshotMetadata snapshotMetadata = snapshots.get(key);
if (snapshotMetadata == null) {
snapshotMetadata = new RemoteSnapshotMetadata(artifact, timestamp, buildNumber);
snapshots.put(key, snapshotMetadata);
}
snapshotMetadata.bind(artifact);
}
}
return snapshots.values();
}
@Override
public Artifact transformArtifact(Artifact artifact) {<FILL_FUNCTION_BODY>}
@Override
public Collection<? extends Metadata> finish(Collection<? extends Artifact> artifacts) {
return Collections.emptyList();
}
}
|
if (artifact.isSnapshot() && artifact.getVersion().equals(artifact.getBaseVersion())) {
Object key = RemoteSnapshotMetadata.getKey(artifact);
RemoteSnapshotMetadata snapshotMetadata = snapshots.get(key);
if (snapshotMetadata != null) {
artifact = artifact.setVersion(snapshotMetadata.getExpandedVersion(artifact));
}
}
return artifact;
| 580
| 100
| 680
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/VersionsMetadata.java
|
VersionsMetadata
|
createRepositoryMetadata
|
class VersionsMetadata extends MavenMetadata {
private final Artifact artifact;
VersionsMetadata(Artifact artifact, Date timestamp) {
super(createRepositoryMetadata(artifact), (Path) null, timestamp);
this.artifact = artifact;
}
VersionsMetadata(Artifact artifact, Path path, Date timestamp) {
super(createRepositoryMetadata(artifact), path, timestamp);
this.artifact = artifact;
}
private static Metadata createRepositoryMetadata(Artifact artifact) {<FILL_FUNCTION_BODY>}
@Override
protected void merge(Metadata recessive) {
Versioning versioning = metadata.getVersioning();
versioning.setLastUpdatedTimestamp(timestamp);
if (recessive.getVersioning() != null) {
if (versioning.getLatest() == null) {
versioning.setLatest(recessive.getVersioning().getLatest());
}
if (versioning.getRelease() == null) {
versioning.setRelease(recessive.getVersioning().getRelease());
}
Collection<String> versions =
new LinkedHashSet<>(recessive.getVersioning().getVersions());
versions.addAll(versioning.getVersions());
versioning.setVersions(new ArrayList<>(versions));
}
}
public Object getKey() {
return getGroupId() + ':' + getArtifactId();
}
public static Object getKey(Artifact artifact) {
return artifact.getGroupId() + ':' + artifact.getArtifactId();
}
@Deprecated
@Override
public MavenMetadata setFile(File file) {
return new VersionsMetadata(artifact, file.toPath(), timestamp);
}
@Override
public MavenMetadata setPath(Path path) {
return new VersionsMetadata(artifact, path, timestamp);
}
@Override
public String getGroupId() {
return artifact.getGroupId();
}
@Override
public String getArtifactId() {
return artifact.getArtifactId();
}
@Override
public String getVersion() {
return "";
}
@Override
public Nature getNature() {
return artifact.isSnapshot() ? Nature.RELEASE_OR_SNAPSHOT : Nature.RELEASE;
}
}
|
Metadata metadata = new Metadata();
metadata.setGroupId(artifact.getGroupId());
metadata.setArtifactId(artifact.getArtifactId());
Versioning versioning = new Versioning();
versioning.addVersion(artifact.getBaseVersion());
if (!artifact.isSnapshot()) {
versioning.setRelease(artifact.getBaseVersion());
}
if ("maven-plugin".equals(artifact.getProperty(ArtifactProperties.TYPE, ""))) {
versioning.setLatest(artifact.getBaseVersion());
}
metadata.setVersioning(versioning);
return metadata;
| 594
| 157
| 751
|
<methods>public java.io.File getFile() ,public java.nio.file.Path getPath() ,public Map<java.lang.String,java.lang.String> getProperties() ,public java.lang.String getType() ,public boolean isMerged() ,public void merge(java.io.File, java.io.File) throws RepositoryException,public void merge(java.nio.file.Path, java.nio.file.Path) throws RepositoryException,public org.eclipse.aether.metadata.Metadata setProperties(Map<java.lang.String,java.lang.String>) <variables>static final java.lang.String MAVEN_METADATA_XML,private boolean merged,protected org.apache.maven.artifact.repository.metadata.Metadata metadata,private final non-sealed java.nio.file.Path path,protected final non-sealed java.util.Date timestamp
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/VersionsMetadataGenerator.java
|
VersionsMetadataGenerator
|
finish
|
class VersionsMetadataGenerator implements MetadataGenerator {
private final Map<Object, VersionsMetadata> versions;
private final Map<Object, VersionsMetadata> processedVersions;
private final Date timestamp;
VersionsMetadataGenerator(RepositorySystemSession session, InstallRequest request) {
this(session, request.getMetadata());
}
VersionsMetadataGenerator(RepositorySystemSession session, DeployRequest request) {
this(session, request.getMetadata());
}
private VersionsMetadataGenerator(RepositorySystemSession session, Collection<? extends Metadata> metadatas) {
versions = new LinkedHashMap<>();
processedVersions = new LinkedHashMap<>();
timestamp = (Date) ConfigUtils.getObject(session, new Date(), "maven.startTime");
/*
* NOTE: This should be considered a quirk to support interop with Maven's legacy ArtifactDeployer which
* processes one artifact at a time and hence cannot associate the artifacts from the same project to use the
* same version index. Allowing the caller to pass in metadata from a previous deployment allows to re-establish
* the association between the artifacts of the same project.
*/
for (Iterator<? extends Metadata> it = metadatas.iterator(); it.hasNext(); ) {
Metadata metadata = it.next();
if (metadata instanceof VersionsMetadata) {
it.remove();
VersionsMetadata versionsMetadata = (VersionsMetadata) metadata;
processedVersions.put(versionsMetadata.getKey(), versionsMetadata);
}
}
}
@Override
public Collection<? extends Metadata> prepare(Collection<? extends Artifact> artifacts) {
return Collections.emptyList();
}
@Override
public Artifact transformArtifact(Artifact artifact) {
return artifact;
}
@Override
public Collection<? extends Metadata> finish(Collection<? extends Artifact> artifacts) {<FILL_FUNCTION_BODY>}
}
|
for (Artifact artifact : artifacts) {
Object key = VersionsMetadata.getKey(artifact);
if (processedVersions.get(key) == null) {
VersionsMetadata versionsMetadata = versions.get(key);
if (versionsMetadata == null) {
versionsMetadata = new VersionsMetadata(artifact, timestamp);
versions.put(key, versionsMetadata);
}
}
}
return versions.values();
| 492
| 112
| 604
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/artifact/FatArtifactTraverser.java
|
FatArtifactTraverser
|
traverseDependency
|
class FatArtifactTraverser implements DependencyTraverser {
public FatArtifactTraverser() {}
@Override
public boolean traverseDependency(Dependency dependency) {<FILL_FUNCTION_BODY>}
@Override
public DependencyTraverser deriveChildTraverser(DependencyCollectionContext context) {
requireNonNull(context, "context cannot be null");
return this;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (null == obj || !getClass().equals(obj.getClass())) {
return false;
}
return true;
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
|
requireNonNull(dependency, "dependency cannot be null");
String prop = dependency.getArtifact().getProperty(MavenArtifactProperties.INCLUDES_DEPENDENCIES, "");
return !Boolean.parseBoolean(prop);
| 199
| 63
| 262
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/relocation/DistributionManagementArtifactRelocationSource.java
|
DistributionManagementArtifactRelocationSource
|
relocatedTarget
|
class DistributionManagementArtifactRelocationSource implements MavenArtifactRelocationSource {
public static final String NAME = "distributionManagement";
private static final Logger LOGGER = LoggerFactory.getLogger(DistributionManagementArtifactRelocationSource.class);
@Override
public Artifact relocatedTarget(
RepositorySystemSession session, ArtifactDescriptorResult artifactDescriptorResult, Model model) {<FILL_FUNCTION_BODY>}
}
|
DistributionManagement distMgmt = model.getDistributionManagement();
if (distMgmt != null) {
Relocation relocation = distMgmt.getRelocation();
if (relocation != null) {
Artifact result = new RelocatedArtifact(
artifactDescriptorResult.getRequest().getArtifact(),
relocation.getGroupId(),
relocation.getArtifactId(),
null,
null,
relocation.getVersion(),
relocation.getMessage());
LOGGER.debug(
"The artifact {} has been relocated to {}: {}",
artifactDescriptorResult.getRequest().getArtifact(),
result,
relocation.getMessage());
return result;
}
}
return null;
| 108
| 191
| 299
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/relocation/UserPropertiesArtifactRelocationSource.java
|
Relocations
|
parseRelocations
|
class Relocations {
private final List<Relocation> relocations;
private Relocations(List<Relocation> relocations) {
this.relocations = relocations;
}
private Relocation getRelocation(Artifact artifact) {
return relocations.stream()
.filter(r -> r.predicate.test(artifact))
.findFirst()
.orElse(null);
}
}
private Relocations parseRelocations(RepositorySystemSession session) {<FILL_FUNCTION_BODY>
|
String relocationsEntries = (String) session.getConfigProperties().get(CONFIG_PROP_RELOCATIONS_ENTRIES);
if (relocationsEntries == null) {
return null;
}
String[] entries = relocationsEntries.split(",");
try (Stream<String> lines = Arrays.stream(entries)) {
List<Relocation> relocationList = lines.filter(
l -> l != null && !l.trim().isEmpty())
.map(l -> {
boolean global;
String splitExpr;
if (l.contains(">>")) {
global = true;
splitExpr = ">>";
} else if (l.contains(">")) {
global = false;
splitExpr = ">";
} else {
throw new IllegalArgumentException("Unrecognized entry: " + l);
}
String[] parts = l.split(splitExpr);
if (parts.length < 1) {
throw new IllegalArgumentException("Unrecognized entry: " + l);
}
Artifact s = parseArtifact(parts[0]);
Artifact t;
if (parts.length > 1) {
t = parseArtifact(parts[1]);
} else {
t = SENTINEL;
}
return new Relocation(global, s, t);
})
.collect(Collectors.toList());
LOGGER.info("Parsed {} user relocations", relocationList.size());
return new Relocations(relocationList);
}
| 143
| 387
| 530
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/scopes/Maven3ScopeManagerConfiguration.java
|
Maven3ScopeManagerConfiguration
|
buildResolutionScopes
|
class Maven3ScopeManagerConfiguration implements ScopeManagerConfiguration {
public static final Maven3ScopeManagerConfiguration INSTANCE = new Maven3ScopeManagerConfiguration();
public static final String DS_COMPILE = "compile";
public static final String DS_RUNTIME = "runtime";
public static final String DS_PROVIDED = "provided";
public static final String DS_SYSTEM = "system";
public static final String DS_TEST = "test";
public static final String RS_NONE = "none";
public static final String RS_MAIN_COMPILE = "main-compile";
public static final String RS_MAIN_COMPILE_PLUS_RUNTIME = "main-compilePlusRuntime";
public static final String RS_MAIN_RUNTIME = "main-runtime";
public static final String RS_MAIN_RUNTIME_PLUS_SYSTEM = "main-runtimePlusSystem";
public static final String RS_TEST_COMPILE = "test-compile";
public static final String RS_TEST_RUNTIME = "test-runtime";
private Maven3ScopeManagerConfiguration() {}
@Override
public String getId() {
return "Maven3";
}
@Override
public boolean isStrictDependencyScopes() {
return false;
}
@Override
public boolean isStrictResolutionScopes() {
return false;
}
@Override
public BuildScopeSource getBuildScopeSource() {
return new BuildScopeMatrixSource(
Collections.singletonList(CommonBuilds.PROJECT_PATH_MAIN),
Arrays.asList(CommonBuilds.BUILD_PATH_COMPILE, CommonBuilds.BUILD_PATH_RUNTIME),
CommonBuilds.MAVEN_TEST_BUILD_SCOPE);
}
@Override
public Collection<DependencyScope> buildDependencyScopes(InternalScopeManager internalScopeManager) {
ArrayList<DependencyScope> result = new ArrayList<>();
result.add(internalScopeManager.createDependencyScope(DS_COMPILE, true, all()));
result.add(internalScopeManager.createDependencyScope(
DS_RUNTIME, true, byBuildPath(CommonBuilds.BUILD_PATH_RUNTIME)));
result.add(internalScopeManager.createDependencyScope(
DS_PROVIDED,
false,
union(
byBuildPath(CommonBuilds.BUILD_PATH_COMPILE),
select(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_RUNTIME))));
result.add(internalScopeManager.createDependencyScope(
DS_TEST, false, byProjectPath(CommonBuilds.PROJECT_PATH_TEST)));
result.add(internalScopeManager.createSystemDependencyScope(
DS_SYSTEM, false, all(), ArtifactProperties.LOCAL_PATH));
return result;
}
@Override
public Collection<ResolutionScope> buildResolutionScopes(InternalScopeManager internalScopeManager) {<FILL_FUNCTION_BODY>}
// ===
public static void main(String... args) {
ScopeManagerDump.dump(Maven3ScopeManagerConfiguration.INSTANCE);
}
}
|
Collection<DependencyScope> allDependencyScopes = internalScopeManager.getDependencyScopeUniverse();
Collection<DependencyScope> nonTransitiveDependencyScopes =
allDependencyScopes.stream().filter(s -> !s.isTransitive()).collect(Collectors.toSet());
DependencyScope system =
internalScopeManager.getDependencyScope(DS_SYSTEM).orElse(null);
ArrayList<ResolutionScope> result = new ArrayList<>();
result.add(internalScopeManager.createResolutionScope(
RS_NONE,
InternalScopeManager.Mode.REMOVE,
Collections.emptySet(),
Collections.emptySet(),
allDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_COMPILE,
InternalScopeManager.Mode.ELIMINATE,
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_COMPILE),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_COMPILE_PLUS_RUNTIME,
InternalScopeManager.Mode.ELIMINATE,
byProjectPath(CommonBuilds.PROJECT_PATH_MAIN),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_RUNTIME,
InternalScopeManager.Mode.ELIMINATE,
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_RUNTIME),
Collections.emptySet(),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_RUNTIME_PLUS_SYSTEM,
InternalScopeManager.Mode.ELIMINATE,
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_RUNTIME),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_TEST_COMPILE,
InternalScopeManager.Mode.ELIMINATE,
select(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_COMPILE),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_TEST_RUNTIME,
InternalScopeManager.Mode.ELIMINATE,
select(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_RUNTIME),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
return result;
| 791
| 694
| 1,485
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/scopes/Maven4ScopeManagerConfiguration.java
|
Maven4ScopeManagerConfiguration
|
buildDependencyScopes
|
class Maven4ScopeManagerConfiguration implements ScopeManagerConfiguration {
public static final Maven4ScopeManagerConfiguration INSTANCE = new Maven4ScopeManagerConfiguration();
public static final String RS_NONE = "none";
public static final String RS_MAIN_COMPILE = "main-compile";
public static final String RS_MAIN_COMPILE_PLUS_RUNTIME = "main-compilePlusRuntime";
public static final String RS_MAIN_RUNTIME = "main-runtime";
public static final String RS_MAIN_RUNTIME_PLUS_SYSTEM = "main-runtimePlusSystem";
public static final String RS_TEST_COMPILE = "test-compile";
public static final String RS_TEST_RUNTIME = "test-runtime";
private Maven4ScopeManagerConfiguration() {}
@Override
public String getId() {
return "Maven4";
}
@Override
public boolean isStrictDependencyScopes() {
return false;
}
@Override
public boolean isStrictResolutionScopes() {
return false;
}
@Override
public BuildScopeSource getBuildScopeSource() {
return new BuildScopeMatrixSource(
Arrays.asList(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.PROJECT_PATH_TEST),
Arrays.asList(CommonBuilds.BUILD_PATH_COMPILE, CommonBuilds.BUILD_PATH_RUNTIME));
}
@Override
public Collection<org.eclipse.aether.scope.DependencyScope> buildDependencyScopes(
InternalScopeManager internalScopeManager) {<FILL_FUNCTION_BODY>}
@Override
public Collection<org.eclipse.aether.scope.ResolutionScope> buildResolutionScopes(
InternalScopeManager internalScopeManager) {
Collection<org.eclipse.aether.scope.DependencyScope> allDependencyScopes =
internalScopeManager.getDependencyScopeUniverse();
Collection<org.eclipse.aether.scope.DependencyScope> nonTransitiveDependencyScopes =
allDependencyScopes.stream().filter(s -> !s.isTransitive()).collect(Collectors.toSet());
org.eclipse.aether.scope.DependencyScope system = internalScopeManager
.getDependencyScope(DependencyScope.SYSTEM.id())
.orElse(null);
ArrayList<org.eclipse.aether.scope.ResolutionScope> result = new ArrayList<>();
result.add(internalScopeManager.createResolutionScope(
RS_NONE,
InternalScopeManager.Mode.REMOVE,
Collections.emptySet(),
Collections.emptySet(),
allDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_COMPILE,
InternalScopeManager.Mode.ELIMINATE,
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_COMPILE),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_COMPILE_PLUS_RUNTIME,
InternalScopeManager.Mode.ELIMINATE,
byProjectPath(CommonBuilds.PROJECT_PATH_MAIN),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_RUNTIME,
InternalScopeManager.Mode.REMOVE,
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_RUNTIME),
Collections.emptySet(),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_RUNTIME_PLUS_SYSTEM,
InternalScopeManager.Mode.REMOVE,
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_RUNTIME),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_TEST_COMPILE,
InternalScopeManager.Mode.ELIMINATE,
select(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_COMPILE),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_TEST_RUNTIME,
InternalScopeManager.Mode.ELIMINATE,
select(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_RUNTIME),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
return result;
}
// ===
public static void main(String... args) {
ScopeManagerDump.dump(Maven4ScopeManagerConfiguration.INSTANCE);
}
}
|
ArrayList<org.eclipse.aether.scope.DependencyScope> result = new ArrayList<>();
result.add(internalScopeManager.createDependencyScope(
DependencyScope.COMPILE.id(), DependencyScope.COMPILE.isTransitive(), all()));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.RUNTIME.id(),
DependencyScope.RUNTIME.isTransitive(),
byBuildPath(CommonBuilds.BUILD_PATH_RUNTIME)));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.PROVIDED.id(),
DependencyScope.PROVIDED.isTransitive(),
union(
byBuildPath(CommonBuilds.BUILD_PATH_COMPILE),
select(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_RUNTIME))));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.TEST.id(),
DependencyScope.TEST.isTransitive(),
byProjectPath(CommonBuilds.PROJECT_PATH_TEST)));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.NONE.id(), DependencyScope.NONE.isTransitive(), Collections.emptySet()));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.COMPILE_ONLY.id(),
DependencyScope.COMPILE_ONLY.isTransitive(),
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_COMPILE)));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.TEST_RUNTIME.id(),
DependencyScope.TEST_RUNTIME.isTransitive(),
singleton(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_RUNTIME)));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.TEST_ONLY.id(),
DependencyScope.TEST_ONLY.isTransitive(),
singleton(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_COMPILE)));
// system
result.add(internalScopeManager.createSystemDependencyScope(
DependencyScope.SYSTEM.id(),
DependencyScope.SYSTEM.isTransitive(),
all(),
MavenArtifactProperties.LOCAL_PATH));
// == sanity check
if (result.size() != org.apache.maven.api.DependencyScope.values().length - 1) { // sans "undefined"
throw new IllegalStateException("Maven4 API dependency scope mismatch");
}
return result;
| 1,231
| 674
| 1,905
|
<no_super_class>
|
apache_maven
|
maven/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/type/DefaultTypeProvider.java
|
DefaultTypeProvider
|
types
|
class DefaultTypeProvider implements TypeProvider {
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public Collection<Type> provides() {
return (Collection) types();
}
public Collection<DefaultType> types() {<FILL_FUNCTION_BODY>}
}
|
return Arrays.asList(
// Maven types
new DefaultType(Type.POM, Language.NONE, "pom", null, false),
new DefaultType(Type.BOM, Language.NONE, "pom", null, false),
new DefaultType(Type.MAVEN_PLUGIN, Language.JAVA_FAMILY, "jar", null, false, JavaPathType.CLASSES),
// Java types
new DefaultType(
Type.JAR, Language.JAVA_FAMILY, "jar", null, false, JavaPathType.CLASSES, JavaPathType.MODULES),
new DefaultType(Type.JAVADOC, Language.JAVA_FAMILY, "jar", "javadoc", false, JavaPathType.CLASSES),
new DefaultType(Type.JAVA_SOURCE, Language.JAVA_FAMILY, "jar", "sources", false),
new DefaultType(
Type.TEST_JAR,
Language.JAVA_FAMILY,
"jar",
"tests",
false,
JavaPathType.CLASSES,
JavaPathType.PATCH_MODULE),
new DefaultType(Type.MODULAR_JAR, Language.JAVA_FAMILY, "jar", null, false, JavaPathType.MODULES),
new DefaultType(Type.CLASSPATH_JAR, Language.JAVA_FAMILY, "jar", null, false, JavaPathType.CLASSES),
new DefaultType(Type.FATJAR, Language.JAVA_FAMILY, "jar", null, true, JavaPathType.CLASSES),
// j2ee types
new DefaultType("ejb", Language.JAVA_FAMILY, "jar", null, false, JavaPathType.CLASSES),
new DefaultType("ejb-client", Language.JAVA_FAMILY, "jar", "client", false, JavaPathType.CLASSES),
new DefaultType("war", Language.JAVA_FAMILY, "war", null, true),
new DefaultType("ear", Language.JAVA_FAMILY, "ear", null, true),
new DefaultType("rar", Language.JAVA_FAMILY, "rar", null, true),
new DefaultType("par", Language.JAVA_FAMILY, "par", null, true));
| 78
| 610
| 688
|
<no_super_class>
|
apache_maven
|
maven/maven-settings-builder/src/main/java/org/apache/maven/settings/building/DefaultSettingsBuilder.java
|
DefaultSettingsBuilder
|
toSource
|
class DefaultSettingsBuilder implements SettingsBuilder {
private final org.apache.maven.internal.impl.DefaultSettingsBuilder builder;
private final org.apache.maven.internal.impl.DefaultSettingsXmlFactory settingsXmlFactory;
@Inject
public DefaultSettingsBuilder(
org.apache.maven.internal.impl.DefaultSettingsBuilder builder,
org.apache.maven.internal.impl.DefaultSettingsXmlFactory settingsXmlFactory) {
this.builder = builder;
this.settingsXmlFactory = settingsXmlFactory;
}
@Override
public SettingsBuildingResult build(SettingsBuildingRequest request) throws SettingsBuildingException {
try {
SettingsBuilderResult result = builder.build(SettingsBuilderRequest.builder()
.session((Session) java.lang.reflect.Proxy.newProxyInstance(
Session.class.getClassLoader(),
new Class[] {Session.class},
(Object proxy, Method method, Object[] args) -> {
if ("getSystemProperties".equals(method.getName())) {
return request.getSystemProperties().entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().toString(),
e -> e.getValue().toString()));
} else if ("getUserProperties".equals(method.getName())) {
return request.getUserProperties().entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().toString(),
e -> e.getValue().toString()));
} else if ("getService".equals(method.getName())) {
if (args[0] == SettingsXmlFactory.class) {
return settingsXmlFactory;
}
}
return null;
}))
.globalSettingsSource(toSource(request.getGlobalSettingsFile(), request.getGlobalSettingsSource()))
.projectSettingsSource(
toSource(request.getProjectSettingsFile(), request.getProjectSettingsSource()))
.userSettingsSource(toSource(request.getUserSettingsFile(), request.getUserSettingsSource()))
.build());
return new DefaultSettingsBuildingResult(
new Settings(result.getEffectiveSettings()), convert(result.getProblems()));
} catch (SettingsBuilderException e) {
throw new SettingsBuildingException(convert(e.getProblems()));
}
}
private org.apache.maven.api.services.Source toSource(File file, Source source) {<FILL_FUNCTION_BODY>}
private List<SettingsProblem> convert(List<BuilderProblem> problems) {
return problems.stream().map(this::convert).toList();
}
private SettingsProblem convert(BuilderProblem problem) {
return new DefaultSettingsProblem(
problem.getMessage(),
SettingsProblem.Severity.valueOf(problem.getSeverity().name()),
problem.getSource(),
problem.getLineNumber(),
problem.getColumnNumber(),
problem.getException());
}
}
|
if (file != null && file.exists()) {
return org.apache.maven.api.services.Source.fromPath(file.toPath());
} else if (source instanceof FileSource fs) {
return org.apache.maven.api.services.Source.fromPath(fs.getPath());
} else if (source != null) {
return new org.apache.maven.api.services.Source() {
@Override
public Path getPath() {
return null;
}
@Override
public InputStream openStream() throws IOException {
return source.getInputStream();
}
@Override
public String getLocation() {
return source.getLocation();
}
@Override
public org.apache.maven.api.services.Source resolve(String relative) {
return null;
}
};
} else {
return null;
}
| 717
| 225
| 942
|
<no_super_class>
|
apache_maven
|
maven/maven-settings-builder/src/main/java/org/apache/maven/settings/building/DefaultSettingsBuildingRequest.java
|
DefaultSettingsBuildingRequest
|
setSystemProperties
|
class DefaultSettingsBuildingRequest implements SettingsBuildingRequest {
private File globalSettingsFile;
private File projectSettingsFile;
private File userSettingsFile;
private SettingsSource globalSettingsSource;
private SettingsSource projectSettingsSource;
private SettingsSource userSettingsSource;
private Properties systemProperties;
private Properties userProperties;
@Override
public File getGlobalSettingsFile() {
return globalSettingsFile;
}
@Override
public DefaultSettingsBuildingRequest setGlobalSettingsFile(File globalSettingsFile) {
this.globalSettingsFile = globalSettingsFile;
return this;
}
@Override
public SettingsSource getGlobalSettingsSource() {
return globalSettingsSource;
}
@Override
public DefaultSettingsBuildingRequest setGlobalSettingsSource(SettingsSource globalSettingsSource) {
this.globalSettingsSource = globalSettingsSource;
return this;
}
@Override
public File getProjectSettingsFile() {
return projectSettingsFile;
}
@Override
public DefaultSettingsBuildingRequest setProjectSettingsFile(File projectSettingsFile) {
this.projectSettingsFile = projectSettingsFile;
return this;
}
@Override
public SettingsSource getProjectSettingsSource() {
return projectSettingsSource;
}
@Override
public DefaultSettingsBuildingRequest setProjectSettingsSource(SettingsSource projectSettingsSource) {
this.projectSettingsSource = projectSettingsSource;
return this;
}
@Override
public File getUserSettingsFile() {
return userSettingsFile;
}
@Override
public DefaultSettingsBuildingRequest setUserSettingsFile(File userSettingsFile) {
this.userSettingsFile = userSettingsFile;
return this;
}
@Override
public SettingsSource getUserSettingsSource() {
return userSettingsSource;
}
@Override
public DefaultSettingsBuildingRequest setUserSettingsSource(SettingsSource userSettingsSource) {
this.userSettingsSource = userSettingsSource;
return this;
}
@Override
public Properties getSystemProperties() {
if (systemProperties == null) {
systemProperties = new Properties();
}
return systemProperties;
}
@Override
public DefaultSettingsBuildingRequest setSystemProperties(Properties systemProperties) {<FILL_FUNCTION_BODY>}
@Override
public Properties getUserProperties() {
if (userProperties == null) {
userProperties = new Properties();
}
return userProperties;
}
@Override
public DefaultSettingsBuildingRequest setUserProperties(Properties userProperties) {
if (userProperties != null) {
this.userProperties = new Properties();
this.userProperties.putAll(userProperties);
} else {
this.userProperties = null;
}
return this;
}
}
|
if (systemProperties != null) {
this.systemProperties = new Properties();
synchronized (systemProperties) { // avoid concurrent modification if someone else sets/removes an unrelated
// system property
this.systemProperties.putAll(systemProperties);
}
} else {
this.systemProperties = null;
}
return this;
| 710
| 92
| 802
|
<no_super_class>
|
apache_maven
|
maven/maven-settings-builder/src/main/java/org/apache/maven/settings/building/DefaultSettingsProblem.java
|
DefaultSettingsProblem
|
toString
|
class DefaultSettingsProblem implements SettingsProblem {
private final String source;
private final int lineNumber;
private final int columnNumber;
private final String message;
private final Exception exception;
private final Severity severity;
/**
* Creates a new problem with the specified message and exception.
*
* @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 SettingsProblem.Severity#ERROR}.
* @param source A hint about the source of the problem like a file path, may be {@code null}.
* @param lineNumber The one-based index of the line containing the problem or {@code -1} if unknown.
* @param columnNumber The one-based index of the column containing the problem or {@code -1} if unknown.
* @param exception The exception that caused this problem, may be {@code null}.
*/
public DefaultSettingsProblem(
String message, Severity severity, String source, int lineNumber, int columnNumber, Exception exception) {
this.message = message;
this.severity = (severity != null) ? severity : Severity.ERROR;
this.source = (source != null) ? source : "";
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.exception = exception;
}
@Override
public String getSource() {
return source;
}
@Override
public int getLineNumber() {
return lineNumber;
}
@Override
public int getColumnNumber() {
return columnNumber;
}
@Override
public String getLocation() {
StringBuilder buffer = new StringBuilder(256);
if (!getSource().isEmpty()) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append(getSource());
}
if (getLineNumber() > 0) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append("line ").append(getLineNumber());
}
if (getColumnNumber() > 0) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append("column ").append(getColumnNumber());
}
return buffer.toString();
}
@Override
public Exception getException() {
return exception;
}
@Override
public String getMessage() {
String msg;
if (message != null && !message.isEmpty()) {
msg = message;
} else {
msg = exception.getMessage();
if (msg == null) {
msg = "";
}
}
return msg;
}
@Override
public Severity getSeverity() {
return severity;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder buffer = new StringBuilder(128);
buffer.append('[').append(getSeverity()).append("] ");
buffer.append(getMessage());
String location = getLocation();
if (!location.isEmpty()) {
buffer.append(" @ ");
buffer.append(location);
}
return buffer.toString();
| 774
| 89
| 863
|
<no_super_class>
|
apache_maven
|
maven/maven-settings-builder/src/main/java/org/apache/maven/settings/building/DefaultSettingsProblemCollector.java
|
DefaultSettingsProblemCollector
|
add
|
class DefaultSettingsProblemCollector implements SettingsProblemCollector {
private List<SettingsProblem> problems;
private String source;
DefaultSettingsProblemCollector(List<SettingsProblem> problems) {
this.problems = (problems != null) ? problems : new ArrayList<>();
}
public List<SettingsProblem> getProblems() {
return problems;
}
public void setSource(String source) {
this.source = source;
}
@Override
public void add(SettingsProblem.Severity severity, String message, int line, int column, Exception cause) {<FILL_FUNCTION_BODY>}
}
|
if (line <= 0 && column <= 0 && (cause instanceof SettingsParseException)) {
SettingsParseException e = (SettingsParseException) cause;
line = e.getLineNumber();
column = e.getColumnNumber();
}
SettingsProblem problem = new DefaultSettingsProblem(message, severity, source, line, column, cause);
problems.add(problem);
| 171
| 96
| 267
|
<no_super_class>
|
apache_maven
|
maven/maven-settings-builder/src/main/java/org/apache/maven/settings/building/SettingsBuildingException.java
|
SettingsBuildingException
|
toMessage
|
class SettingsBuildingException extends Exception {
private final List<SettingsProblem> problems;
/**
* Creates a new exception with the specified problems.
*
* @param problems The problems that cause this exception, may be {@code null}.
*/
public SettingsBuildingException(List<SettingsProblem> problems) {
super(toMessage(problems));
this.problems = new ArrayList<>();
if (problems != null) {
this.problems.addAll(problems);
}
}
/**
* Gets the problems that caused this exception.
*
* @return The problems that caused this exception, never {@code null}.
*/
public List<SettingsProblem> getProblems() {
return problems;
}
private static String toMessage(List<SettingsProblem> 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 settings");
writer.println();
for (SettingsProblem problem : problems) {
writer.print("[");
writer.print(problem.getSeverity());
writer.print("] ");
writer.print(problem.getMessage());
String location = problem.getLocation();
if (!location.isEmpty()) {
writer.print(" @ ");
writer.println(location);
}
}
return buffer.toString();
| 223
| 188
| 411
|
<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-settings-builder/src/main/java/org/apache/maven/settings/crypto/DefaultSettingsDecrypter.java
|
DefaultSettingsDecrypter
|
decrypt
|
class DefaultSettingsDecrypter implements SettingsDecrypter {
private final SecDispatcher securityDispatcher;
@Inject
public DefaultSettingsDecrypter(@Named("maven") SecDispatcher securityDispatcher) {
this.securityDispatcher = securityDispatcher;
}
@Override
public SettingsDecryptionResult decrypt(SettingsDecryptionRequest request) {<FILL_FUNCTION_BODY>}
private String decrypt(String str) throws SecDispatcherException {
return (str == null) ? null : securityDispatcher.decrypt(str);
}
}
|
List<SettingsProblem> problems = new ArrayList<>();
List<Server> servers = new ArrayList<>();
for (Server server : request.getServers()) {
server = server.clone();
try {
server.setPassword(decrypt(server.getPassword()));
} catch (SecDispatcherException e) {
problems.add(new DefaultSettingsProblem(
"Failed to decrypt password for server " + server.getId() + ": " + e.getMessage(),
Severity.ERROR,
"server: " + server.getId(),
-1,
-1,
e));
}
try {
server.setPassphrase(decrypt(server.getPassphrase()));
} catch (SecDispatcherException e) {
problems.add(new DefaultSettingsProblem(
"Failed to decrypt passphrase for server " + server.getId() + ": " + e.getMessage(),
Severity.ERROR,
"server: " + server.getId(),
-1,
-1,
e));
}
servers.add(server);
}
List<Proxy> proxies = new ArrayList<>();
for (Proxy proxy : request.getProxies()) {
try {
proxy.setPassword(decrypt(proxy.getPassword()));
} catch (SecDispatcherException e) {
problems.add(new DefaultSettingsProblem(
"Failed to decrypt password for proxy " + proxy.getId() + ": " + e.getMessage(),
Severity.ERROR,
"proxy: " + proxy.getId(),
-1,
-1,
e));
}
proxies.add(proxy);
}
return new DefaultSettingsDecryptionResult(servers, proxies, problems);
| 145
| 446
| 591
|
<no_super_class>
|
apache_maven
|
maven/maven-settings-builder/src/main/java/org/apache/maven/settings/crypto/DefaultSettingsDecryptionRequest.java
|
DefaultSettingsDecryptionRequest
|
getServers
|
class DefaultSettingsDecryptionRequest implements SettingsDecryptionRequest {
private List<Server> servers;
private List<Proxy> proxies;
/**
* Creates an empty request.
*/
public DefaultSettingsDecryptionRequest() {
// does nothing
}
/**
* Creates a new request to decrypt the specified settings.
*
* @param settings The settings to decrypt, must not be {@code null}.
*/
public DefaultSettingsDecryptionRequest(Settings settings) {
setServers(settings.getServers());
setProxies(settings.getProxies());
}
/**
* Creates a new request to decrypt the specified server.
*
* @param server The server to decrypt, must not be {@code null}.
*/
public DefaultSettingsDecryptionRequest(Server server) {
this.servers = new ArrayList<>(Arrays.asList(server));
}
/**
* Creates a new request to decrypt the specified proxy.
*
* @param proxy The proxy to decrypt, must not be {@code null}.
*/
public DefaultSettingsDecryptionRequest(Proxy proxy) {
this.proxies = new ArrayList<>(Arrays.asList(proxy));
}
@Override
public List<Server> getServers() {<FILL_FUNCTION_BODY>}
@Override
public DefaultSettingsDecryptionRequest setServers(List<Server> servers) {
this.servers = servers;
return this;
}
@Override
public List<Proxy> getProxies() {
if (proxies == null) {
proxies = new ArrayList<>();
}
return proxies;
}
@Override
public DefaultSettingsDecryptionRequest setProxies(List<Proxy> proxies) {
this.proxies = proxies;
return this;
}
}
|
if (servers == null) {
servers = new ArrayList<>();
}
return servers;
| 486
| 29
| 515
|
<no_super_class>
|
apache_maven
|
maven/maven-settings-builder/src/main/java/org/apache/maven/settings/io/DefaultSettingsReader.java
|
DefaultSettingsReader
|
read
|
class DefaultSettingsReader implements SettingsReader {
@Override
public Settings read(File input, Map<String, ?> options) throws IOException {
Objects.requireNonNull(input, "input cannot be null");
try (InputStream in = Files.newInputStream(input.toPath())) {
InputSource source = new InputSource(input.toString());
return new Settings(new SettingsStaxReader().read(in, isStrict(options), source));
} catch (XMLStreamException e) {
throw new SettingsParseException(
e.getMessage(),
e.getLocation().getLineNumber(),
e.getLocation().getColumnNumber(),
e);
}
}
@Override
public Settings read(Reader input, Map<String, ?> options) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Settings read(InputStream input, Map<String, ?> options) throws IOException {
Objects.requireNonNull(input, "input cannot be null");
try (InputStream in = input) {
InputSource source = (InputSource) options.get(InputSource.class.getName());
return new Settings(new SettingsStaxReader().read(in, isStrict(options), source));
} catch (XMLStreamException e) {
throw new SettingsParseException(
e.getMessage(),
e.getLocation().getLineNumber(),
e.getLocation().getColumnNumber(),
e);
}
}
private boolean isStrict(Map<String, ?> options) {
Object value = (options != null) ? options.get(IS_STRICT) : null;
return value == null || Boolean.parseBoolean(value.toString());
}
}
|
Objects.requireNonNull(input, "input cannot be null");
try (Reader in = input) {
InputSource source = (InputSource) options.get(InputSource.class.getName());
return new Settings(new SettingsStaxReader().read(in, isStrict(options), source));
} catch (XMLStreamException e) {
throw new SettingsParseException(
e.getMessage(),
e.getLocation().getLineNumber(),
e.getLocation().getColumnNumber(),
e);
}
| 421
| 130
| 551
|
<no_super_class>
|
apache_maven
|
maven/maven-settings-builder/src/main/java/org/apache/maven/settings/io/DefaultSettingsWriter.java
|
DefaultSettingsWriter
|
write
|
class DefaultSettingsWriter implements SettingsWriter {
@Override
public void write(File output, Map<String, Object> options, Settings settings) throws IOException {
Objects.requireNonNull(output, "output cannot be null");
Objects.requireNonNull(settings, "settings cannot be null");
output.getParentFile().mkdirs();
write(Files.newOutputStream(output.toPath()), options, settings);
}
@Override
public void write(Writer output, Map<String, Object> options, Settings settings) throws IOException {
Objects.requireNonNull(output, "output cannot be null");
Objects.requireNonNull(settings, "settings cannot be null");
try (Writer out = output) {
new SettingsStaxWriter().write(out, settings.getDelegate());
} catch (XMLStreamException e) {
throw new IOException("Error writing settings", e);
}
}
@Override
public void write(OutputStream output, Map<String, Object> options, Settings settings) throws IOException {<FILL_FUNCTION_BODY>}
}
|
Objects.requireNonNull(output, "output cannot be null");
Objects.requireNonNull(settings, "settings cannot be null");
try (OutputStream out = output) {
new SettingsStaxWriter().write(out, settings.getDelegate());
} catch (XMLStreamException e) {
throw new IOException("Error writing settings", e);
}
| 267
| 91
| 358
|
<no_super_class>
|
apache_maven
|
maven/maven-settings-builder/src/main/java/org/apache/maven/settings/merge/MavenSettingsMerger.java
|
MavenSettingsMerger
|
merge
|
class MavenSettingsMerger {
/**
* @param dominant
* @param recessive
* @param recessiveSourceLevel
*/
public void merge(Settings dominant, Settings recessive, String recessiveSourceLevel) {<FILL_FUNCTION_BODY>}
/**
* @param dominant
* @param recessive
* @param recessiveSourceLevel
*/
private static <T extends IdentifiableBase> void shallowMergeById(
List<T> dominant, List<T> recessive, String recessiveSourceLevel) {
Map<String, T> dominantById = mapById(dominant);
final List<T> identifiables = new ArrayList<>(recessive.size());
for (T identifiable : recessive) {
if (!dominantById.containsKey(identifiable.getId())) {
identifiable.setSourceLevel(recessiveSourceLevel);
identifiables.add(identifiable);
}
}
dominant.addAll(0, identifiables);
}
/**
* @param identifiables
* @return a map
*/
private static <T extends IdentifiableBase> Map<String, T> mapById(List<T> identifiables) {
Map<String, T> byId = new HashMap<>();
for (T identifiable : identifiables) {
byId.put(identifiable.getId(), identifiable);
}
return byId;
}
}
|
if (dominant == null || recessive == null) {
return;
}
recessive.setSourceLevel(recessiveSourceLevel);
List<String> dominantActiveProfiles = dominant.getActiveProfiles();
List<String> recessiveActiveProfiles = recessive.getActiveProfiles();
if (recessiveActiveProfiles != null) {
if (dominantActiveProfiles == null) {
dominantActiveProfiles = new ArrayList<>();
dominant.setActiveProfiles(dominantActiveProfiles);
}
for (String profileId : recessiveActiveProfiles) {
if (!dominantActiveProfiles.contains(profileId)) {
dominantActiveProfiles.add(profileId);
}
}
}
List<String> dominantPluginGroupIds = dominant.getPluginGroups();
List<String> recessivePluginGroupIds = recessive.getPluginGroups();
if (recessivePluginGroupIds != null) {
if (dominantPluginGroupIds == null) {
dominantPluginGroupIds = new ArrayList<>();
dominant.setPluginGroups(dominantPluginGroupIds);
}
for (String pluginGroupId : recessivePluginGroupIds) {
if (!dominantPluginGroupIds.contains(pluginGroupId)) {
dominantPluginGroupIds.add(pluginGroupId);
}
}
}
if (dominant.getLocalRepository() == null
|| dominant.getLocalRepository().isEmpty()) {
dominant.setLocalRepository(recessive.getLocalRepository());
}
shallowMergeById(dominant.getMirrors(), recessive.getMirrors(), recessiveSourceLevel);
shallowMergeById(dominant.getServers(), recessive.getServers(), recessiveSourceLevel);
shallowMergeById(dominant.getProxies(), recessive.getProxies(), recessiveSourceLevel);
shallowMergeById(dominant.getProfiles(), recessive.getProfiles(), recessiveSourceLevel);
shallowMergeById(dominant.getRepositories(), recessive.getRepositories(), recessiveSourceLevel);
shallowMergeById(dominant.getPluginRepositories(), recessive.getPluginRepositories(), recessiveSourceLevel);
| 378
| 592
| 970
|
<no_super_class>
|
apache_maven
|
maven/maven-settings-builder/src/main/java/org/apache/maven/settings/validation/DefaultSettingsValidator.java
|
DefaultSettingsValidator
|
validate
|
class DefaultSettingsValidator implements SettingsValidator {
private static final String ID = "[\\w.-]+";
private static final Pattern ID_REGEX = Pattern.compile(ID);
private final SettingsBuilder settingsBuilder;
@Inject
public DefaultSettingsValidator(SettingsBuilder settingsBuilder) {
this.settingsBuilder = settingsBuilder;
}
@Override
public void validate(Settings settings, SettingsProblemCollector problems) {
validate(settings, false, problems);
}
@Override
public void validate(Settings settings, boolean isProjectSettings, SettingsProblemCollector problems) {<FILL_FUNCTION_BODY>}
// ----------------------------------------------------------------------
// Field validation
// ----------------------------------------------------------------------
private static void addViolation(SettingsProblemCollector problems, Severity severity, String message) {
problems.add(severity, message, -1, -1, null);
}
}
|
List<BuilderProblem> list = settingsBuilder.validate(settings.getDelegate(), isProjectSettings);
for (BuilderProblem problem : list) {
addViolation(problems, Severity.valueOf(problem.getSeverity().name()), problem.getMessage());
}
| 228
| 72
| 300
|
<no_super_class>
|
apache_maven
|
maven/maven-settings/src/main/java/org/apache/maven/settings/BaseObject.java
|
BaseObject
|
update
|
class BaseObject implements Serializable, Cloneable {
protected transient ChildrenTracking childrenTracking;
protected Object delegate;
public BaseObject() {}
public BaseObject(Object delegate, BaseObject parent) {
this.delegate = delegate;
this.childrenTracking = parent != null ? parent::replace : null;
}
public BaseObject(Object delegate, ChildrenTracking parent) {
this.delegate = delegate;
this.childrenTracking = parent;
}
public Object getDelegate() {
return delegate;
}
public void update(Object newDelegate) {<FILL_FUNCTION_BODY>}
protected boolean replace(Object oldDelegate, Object newDelegate) {
return false;
}
@FunctionalInterface
protected interface ChildrenTracking {
boolean replace(Object oldDelegate, Object newDelegate);
}
}
|
if (delegate != newDelegate) {
if (childrenTracking != null) {
childrenTracking.replace(delegate, newDelegate);
}
delegate = newDelegate;
}
| 222
| 56
| 278
|
<no_super_class>
|
apache_maven
|
maven/maven-settings/src/main/java/org/apache/maven/settings/io/xpp3/SettingsXpp3Reader.java
|
SettingsXpp3Reader
|
read
|
class SettingsXpp3Reader {
private final SettingsStaxReader delegate;
public SettingsXpp3Reader() {
delegate = new SettingsStaxReader();
}
public SettingsXpp3Reader(ContentTransformer contentTransformer) {
delegate = new SettingsStaxReader(contentTransformer::transform);
}
/**
* Returns the state of the "add default entities" flag.
*
* @return boolean
*/
public boolean getAddDefaultEntities() {
return delegate.getAddDefaultEntities();
}
/**
* Sets the state of the "add default entities" flag.
*
* @param addDefaultEntities a addDefaultEntities object.
*/
public void setAddDefaultEntities(boolean addDefaultEntities) {
delegate.setAddDefaultEntities(addDefaultEntities);
}
/**
* @param reader a reader object.
* @param strict a strict object.
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
* @return Settings
*/
public Settings read(Reader reader, boolean strict) throws IOException, XmlPullParserException {
try {
return new Settings(delegate.read(reader, strict, null));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
/**
* @param reader a reader object.
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
* @return Model
*/
public Settings read(Reader reader) throws IOException, XmlPullParserException {
try {
return new Settings(delegate.read(reader));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
/**
* Method read.
*
* @param in a in object.
* @param strict a strict object.
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
* @return Settings
*/
public Settings read(InputStream in, boolean strict) throws IOException, XmlPullParserException {<FILL_FUNCTION_BODY>}
/**
* Method read.
*
* @param in a in object.
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
* @return Settings
*/
public Settings read(InputStream in) throws IOException, XmlPullParserException {
try {
return new Settings(delegate.read(in));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
/**
* Method read.
*
* @param parser a parser object.
* @param strict a strict object.
* @throws IOException IOException if any.
* @throws XmlPullParserException XmlPullParserException if
* any.
* @return Settings
*/
public Settings read(XMLStreamReader parser, boolean strict) throws IOException, XmlPullParserException {
try {
return new Settings(delegate.read(parser, strict, null));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
}
public interface ContentTransformer {
/**
* Interpolate the value read from the xpp3 document
* @param source The source value
* @param fieldName A description of the field being interpolated. The implementation may use this to
* log stuff.
* @return The interpolated value.
*/
String transform(String source, String fieldName);
}
}
|
try {
return new Settings(delegate.read(in, strict, null));
} catch (XMLStreamException e) {
throw new XmlPullParserException(e.getMessage(), null, e);
}
| 986
| 58
| 1,044
|
<no_super_class>
|
apache_maven
|
maven/maven-settings/src/main/java/org/apache/maven/settings/io/xpp3/SettingsXpp3Writer.java
|
SettingsXpp3Writer
|
write
|
class SettingsXpp3Writer {
private final SettingsStaxWriter delegate;
public SettingsXpp3Writer() {
delegate = new SettingsStaxWriter();
delegate.setAddLocationInformation(false);
}
/**
* Method setFileComment.
*
* @param fileComment a fileComment object.
*/
public void setFileComment(String fileComment) {
delegate.setFileComment(fileComment);
}
/**
* Method write.
*
* @param writer a writer object.
* @param settings a settings object.
* @throws IOException java.io.IOException if any.
*/
public void write(Writer writer, Settings settings) throws IOException {
try {
delegate.write(writer, settings.getDelegate());
} catch (XMLStreamException e) {
throw new IOException(e);
}
}
/**
* Method write.
*
* @param stream a stream object.
* @param settings a settings object.
* @throws IOException java.io.IOException if any.
*/
public void write(OutputStream stream, Settings settings) throws IOException {<FILL_FUNCTION_BODY>}
}
|
try {
delegate.write(stream, settings.getDelegate());
} catch (XMLStreamException e) {
throw new IOException(e);
}
| 296
| 42
| 338
|
<no_super_class>
|
apache_maven
|
maven/maven-slf4j-provider/src/main/java/org/apache/maven/slf4j/MavenLoggerFactory.java
|
MavenLoggerFactory
|
createLogger
|
class MavenLoggerFactory extends SimpleLoggerFactory implements MavenSlf4jWrapperFactory {
private LogLevelRecorder logLevelRecorder = null;
public MavenLoggerFactory() {}
@Override
public void setLogLevelRecorder(LogLevelRecorder logLevelRecorder) {
if (this.logLevelRecorder != null) {
throw new IllegalStateException("LogLevelRecorder has already been set.");
}
this.logLevelRecorder = logLevelRecorder;
reset();
}
@Override
public Optional<LogLevelRecorder> getLogLevelRecorder() {
return Optional.ofNullable(logLevelRecorder);
}
protected Logger createLogger(String name) {<FILL_FUNCTION_BODY>}
}
|
if (logLevelRecorder == null) {
return new MavenSimpleLogger(name);
} else {
return new MavenFailOnSeverityLogger(name, logLevelRecorder);
}
| 190
| 54
| 244
|
<no_super_class>
|
apache_maven
|
maven/maven-slf4j-provider/src/main/java/org/apache/maven/slf4j/MavenSimpleLogger.java
|
MavenSimpleLogger
|
doWrite
|
class MavenSimpleLogger extends ExtSimpleLogger {
private String traceRenderedLevel;
private String debugRenderedLevel;
private String infoRenderedLevel;
private String warnRenderedLevel;
private String errorRenderedLevel;
static Consumer<String> logSink;
public static void setLogSink(Consumer<String> logSink) {
MavenSimpleLogger.logSink = logSink;
}
MavenSimpleLogger(String name) {
super(name);
}
@Override
protected String renderLevel(int level) {
if (traceRenderedLevel == null) {
traceRenderedLevel = builder().trace("TRACE").build();
debugRenderedLevel = builder().debug("DEBUG").build();
infoRenderedLevel = builder().info("INFO").build();
warnRenderedLevel = builder().warning("WARNING").build();
errorRenderedLevel = builder().error("ERROR").build();
}
switch (level) {
case LOG_LEVEL_TRACE:
return traceRenderedLevel;
case LOG_LEVEL_DEBUG:
return debugRenderedLevel;
case LOG_LEVEL_INFO:
return infoRenderedLevel;
case LOG_LEVEL_WARN:
return warnRenderedLevel;
case LOG_LEVEL_ERROR:
default:
return errorRenderedLevel;
}
}
@Override
protected void doWrite(StringBuilder buf, Throwable t) {<FILL_FUNCTION_BODY>}
@Override
protected void writeThrowable(Throwable t, PrintStream stream) {
if (t == null) {
return;
}
MessageBuilder builder = builder().failure(t.getClass().getName());
if (t.getMessage() != null) {
builder.a(": ").failure(t.getMessage());
}
stream.println(builder);
printStackTrace(t, stream, "");
}
private void printStackTrace(Throwable t, PrintStream stream, String prefix) {
MessageBuilder builder = builder();
for (StackTraceElement e : t.getStackTrace()) {
builder.a(prefix);
builder.a(" ");
builder.strong("at");
builder.a(" ");
builder.a(e.getClassName());
builder.a(".");
builder.a(e.getMethodName());
builder.a("(");
builder.strong(getLocation(e));
builder.a(")");
stream.println(builder);
builder.setLength(0);
}
for (Throwable se : t.getSuppressed()) {
writeThrowable(se, stream, "Suppressed", prefix + " ");
}
Throwable cause = t.getCause();
if (cause != null && t != cause) {
writeThrowable(cause, stream, "Caused by", prefix);
}
}
private void writeThrowable(Throwable t, PrintStream stream, String caption, String prefix) {
MessageBuilder builder =
builder().a(prefix).strong(caption).a(": ").a(t.getClass().getName());
if (t.getMessage() != null) {
builder.a(": ").failure(t.getMessage());
}
stream.println(builder);
printStackTrace(t, stream, prefix);
}
protected String getLocation(final StackTraceElement e) {
assert e != null;
if (e.isNativeMethod()) {
return "Native Method";
} else if (e.getFileName() == null) {
return "Unknown Source";
} else if (e.getLineNumber() >= 0) {
return e.getFileName() + ":" + e.getLineNumber();
} else {
return e.getFileName();
}
}
}
|
Consumer<String> sink = logSink;
if (sink != null) {
sink.accept(buf.toString());
} else {
super.doWrite(buf, t);
}
| 965
| 56
| 1,021
|
<methods>public void <init>(java.lang.String) <variables>
|
apache_maven
|
maven/maven-slf4j-wrapper/src/main/java/org/apache/maven/logwrapper/LogLevelRecorder.java
|
LogLevelRecorder
|
record
|
class LogLevelRecorder {
private static final Map<String, Level> ACCEPTED_LEVELS = new HashMap<>();
static {
ACCEPTED_LEVELS.put("WARN", Level.WARN);
ACCEPTED_LEVELS.put("WARNING", Level.WARN);
ACCEPTED_LEVELS.put("ERROR", Level.ERROR);
}
private final Level logThreshold;
private boolean metThreshold = false;
public LogLevelRecorder(String threshold) {
logThreshold = determineThresholdLevel(threshold);
}
private Level determineThresholdLevel(String input) {
final Level result = ACCEPTED_LEVELS.get(input);
if (result == null) {
String message = String.format(
"%s is not a valid log severity threshold. Valid severities are WARN/WARNING and ERROR.", input);
throw new IllegalArgumentException(message);
}
return result;
}
public void record(Level logLevel) {<FILL_FUNCTION_BODY>}
public boolean metThreshold() {
return metThreshold;
}
}
|
if (!metThreshold && logLevel.toInt() >= logThreshold.toInt()) {
metThreshold = true;
}
| 288
| 37
| 325
|
<no_super_class>
|
apache_maven
|
maven/maven-toolchain-builder/src/main/java/org/apache/maven/toolchain/building/DefaultToolchainsBuilder.java
|
DefaultToolchainsBuilder
|
convert
|
class DefaultToolchainsBuilder implements ToolchainsBuilder {
private final org.apache.maven.api.services.ToolchainsBuilder builder;
private final ToolchainsXmlFactory toolchainsXmlFactory;
@Inject
public DefaultToolchainsBuilder(
org.apache.maven.api.services.ToolchainsBuilder builder, ToolchainsXmlFactory toolchainsXmlFactory) {
this.builder = builder;
this.toolchainsXmlFactory = toolchainsXmlFactory;
}
@Override
public ToolchainsBuildingResult build(ToolchainsBuildingRequest request) throws ToolchainsBuildingException {
try {
ToolchainsBuilderResult result = builder.build(ToolchainsBuilderRequest.builder()
.session((Session) java.lang.reflect.Proxy.newProxyInstance(
Session.class.getClassLoader(),
new Class[] {Session.class},
(Object proxy, Method method, Object[] args) -> {
if ("getSystemProperties".equals(method.getName())) {
Map<String, String> properties = new HashMap<>();
Properties env = OperatingSystemUtils.getSystemEnvVars();
env.stringPropertyNames()
.forEach(k -> properties.put("env." + k, env.getProperty(k)));
return properties;
} else if ("getUserProperties".equals(method.getName())) {
return Map.of();
} else if ("getService".equals(method.getName())) {
if (args[0] == ToolchainsXmlFactory.class) {
return toolchainsXmlFactory;
}
}
return null;
}))
.globalToolchainsSource(convert(request.getGlobalToolchainsSource()))
.userToolchainsSource(convert(request.getUserToolchainsSource()))
.build());
return new DefaultToolchainsBuildingResult(
new PersistedToolchains(result.getEffectiveToolchains()), convert(result.getProblems()));
} catch (ToolchainsBuilderException e) {
throw new ToolchainsBuildingException(convert(e.getProblems()));
}
}
private Source convert(org.apache.maven.building.Source source) {<FILL_FUNCTION_BODY>}
private List<Problem> convert(List<BuilderProblem> problems) {
ProblemCollector collector = ProblemCollectorFactory.newInstance(null);
problems.forEach(p -> collector.add(
Problem.Severity.valueOf(p.getSeverity().name()),
p.getMessage(),
p.getLineNumber(),
p.getColumnNumber(),
p.getException()));
return collector.getProblems();
}
}
|
if (source instanceof FileSource fs) {
return Source.fromPath(fs.getPath());
} else if (source != null) {
return new Source() {
@Override
public Path getPath() {
return null;
}
@Override
public InputStream openStream() throws IOException {
return source.getInputStream();
}
@Override
public String getLocation() {
return source.getLocation();
}
@Override
public Source resolve(String relative) {
return null;
}
};
} else {
return null;
}
| 658
| 156
| 814
|
<no_super_class>
|
apache_maven
|
maven/maven-toolchain-builder/src/main/java/org/apache/maven/toolchain/building/ToolchainsBuildingException.java
|
ToolchainsBuildingException
|
toMessage
|
class ToolchainsBuildingException extends Exception {
private final List<Problem> problems;
/**
* Creates a new exception with the specified problems.
*
* @param problems The problems that cause this exception, must not be {@code null}.
*/
public ToolchainsBuildingException(List<Problem> problems) {
super(toMessage(problems));
this.problems = new ArrayList<>();
if (problems != null) {
this.problems.addAll(problems);
}
}
/**
* Gets the problems that caused this exception.
*
* @return The problems that caused this exception, never {@code null}.
*/
public List<Problem> getProblems() {
return problems;
}
private static String toMessage(List<Problem> 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 toolchains");
writer.println();
for (Problem problem : problems) {
writer.print("[");
writer.print(problem.getSeverity());
writer.print("] ");
writer.print(problem.getMessage());
String location = problem.getLocation();
if (!location.isEmpty()) {
writer.print(" @ ");
writer.print(location);
}
writer.println();
}
return buffer.toString();
| 224
| 195
| 419
|
<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-toolchain-builder/src/main/java/org/apache/maven/toolchain/io/DefaultToolchainsReader.java
|
DefaultToolchainsReader
|
isStrict
|
class DefaultToolchainsReader implements ToolchainsReader {
@Override
public PersistedToolchains read(File input, Map<String, ?> options) throws IOException {
Objects.requireNonNull(input, "input cannot be null");
try (InputStream in = Files.newInputStream(input.toPath())) {
return new PersistedToolchains(new MavenToolchainsStaxReader().read(in, isStrict(options)));
} catch (XMLStreamException e) {
throw new ToolchainsParseException(
e.getMessage(),
e.getLocation().getLineNumber(),
e.getLocation().getColumnNumber(),
e);
}
}
@Override
public PersistedToolchains read(Reader input, Map<String, ?> options) throws IOException {
Objects.requireNonNull(input, "input cannot be null");
try (Reader in = input) {
return new PersistedToolchains(new MavenToolchainsStaxReader().read(in, isStrict(options)));
} catch (XMLStreamException e) {
throw new ToolchainsParseException(
e.getMessage(),
e.getLocation().getLineNumber(),
e.getLocation().getColumnNumber(),
e);
}
}
@Override
public PersistedToolchains read(InputStream input, Map<String, ?> options) throws IOException {
Objects.requireNonNull(input, "input cannot be null");
try (InputStream in = input) {
return new PersistedToolchains(new MavenToolchainsStaxReader().read(in, isStrict(options)));
} catch (XMLStreamException e) {
throw new ToolchainsParseException(
e.getMessage(),
e.getLocation().getLineNumber(),
e.getLocation().getColumnNumber(),
e);
}
}
private boolean isStrict(Map<String, ?> options) {<FILL_FUNCTION_BODY>}
}
|
Object value = (options != null) ? options.get(IS_STRICT) : null;
return value == null || Boolean.parseBoolean(value.toString());
| 491
| 44
| 535
|
<no_super_class>
|
apache_maven
|
maven/maven-toolchain-builder/src/main/java/org/apache/maven/toolchain/io/DefaultToolchainsWriter.java
|
DefaultToolchainsWriter
|
write
|
class DefaultToolchainsWriter implements ToolchainsWriter {
@Override
public void write(Writer output, Map<String, Object> options, PersistedToolchains toolchains) throws IOException {<FILL_FUNCTION_BODY>}
}
|
Objects.requireNonNull(output, "output cannot be null");
Objects.requireNonNull(toolchains, "toolchains cannot be null");
try (Writer out = output) {
new MavenToolchainsStaxWriter().write(out, toolchains.getDelegate());
} catch (XMLStreamException e) {
throw new IOException("Error writing toolchains", e);
}
| 61
| 103
| 164
|
<no_super_class>
|
apache_maven
|
maven/maven-toolchain-builder/src/main/java/org/apache/maven/toolchain/merge/MavenToolchainMerger.java
|
MavenToolchainMerger
|
merge
|
class MavenToolchainMerger {
public void merge(PersistedToolchains dominant, PersistedToolchains recessive, String recessiveSourceLevel) {<FILL_FUNCTION_BODY>}
}
|
if (dominant == null || recessive == null) {
return;
}
recessive.setSourceLevel(recessiveSourceLevel);
dominant.update(new org.apache.maven.toolchain.v4.MavenToolchainsMerger()
.merge(dominant.getDelegate(), recessive.getDelegate(), true, null));
| 55
| 96
| 151
|
<no_super_class>
|
apache_maven
|
maven/maven-toolchain-model/src/main/java/org/apache/maven/toolchain/model/BaseObject.java
|
BaseObject
|
update
|
class BaseObject implements Serializable, Cloneable {
protected transient ChildrenTracking childrenTracking;
protected Object delegate;
public BaseObject() {}
public BaseObject(Object delegate, BaseObject parent) {
this.delegate = delegate;
this.childrenTracking = parent != null ? parent::replace : null;
}
public BaseObject(Object delegate, ChildrenTracking parent) {
this.delegate = delegate;
this.childrenTracking = parent;
}
public Object getDelegate() {
return delegate;
}
public void update(Object newDelegate) {<FILL_FUNCTION_BODY>}
protected boolean replace(Object oldDelegate, Object newDelegate) {
return false;
}
@FunctionalInterface
protected interface ChildrenTracking {
boolean replace(Object oldDelegate, Object newDelegate);
}
}
|
if (delegate != newDelegate) {
if (childrenTracking != null) {
childrenTracking.replace(delegate, newDelegate);
}
delegate = newDelegate;
}
| 222
| 56
| 278
|
<no_super_class>
|
apache_maven
|
maven/maven-xml-impl/src/main/java/org/apache/maven/internal/xml/ImmutableCollections.java
|
Map1
|
entrySet
|
class Map1<K, V> extends AbstractImmutableMap<K, V> {
private final Entry<K, V> entry;
private Map1(K key, V value) {
this.entry = new SimpleImmutableEntry<>(key, value);
}
@Override
public Set<Entry<K, V>> entrySet() {<FILL_FUNCTION_BODY>}
}
|
return new AbstractImmutableSet<Entry<K, V>>() {
@Override
public Iterator<Entry<K, V>> iterator() {
return new Iterator<Entry<K, V>>() {
int index = 0;
@Override
public boolean hasNext() {
return index == 0;
}
@Override
public Entry<K, V> next() {
if (index++ == 0) {
return entry;
}
throw new NoSuchElementException();
}
};
}
@Override
public int size() {
return 1;
}
};
| 101
| 162
| 263
|
<no_super_class>
|
apache_maven
|
maven/maven-xml-impl/src/main/java/org/apache/maven/internal/xml/XmlNodeBuilder.java
|
XmlNodeBuilder
|
build
|
class XmlNodeBuilder {
private static final boolean DEFAULT_TRIM = true;
public static XmlNodeImpl build(Reader reader) throws XmlPullParserException, IOException {
return build(reader, (InputLocationBuilder) null);
}
/**
* @param reader the reader
* @param locationBuilder the builder
* @since 3.2.0
* @return DOM
* @throws XmlPullParserException XML well-formedness error
* @throws IOException I/O error reading file or stream
*/
public static XmlNodeImpl build(Reader reader, InputLocationBuilder locationBuilder)
throws XmlPullParserException, IOException {
return build(reader, DEFAULT_TRIM, locationBuilder);
}
public static XmlNodeImpl build(InputStream is, String encoding) throws XmlPullParserException, IOException {
return build(is, encoding, DEFAULT_TRIM);
}
public static XmlNodeImpl build(InputStream is, String encoding, boolean trim)
throws XmlPullParserException, IOException {
XmlPullParser parser = new MXParser();
parser.setInput(is, encoding);
return build(parser, trim);
}
public static XmlNodeImpl build(Reader reader, boolean trim) throws XmlPullParserException, IOException {
return build(reader, trim, null);
}
/**
* @param reader the reader
* @param trim to trim
* @param locationBuilder the builder
* @since 3.2.0
* @return DOM
* @throws XmlPullParserException XML well-formedness error
* @throws IOException I/O error reading file or stream
*/
public static XmlNodeImpl build(Reader reader, boolean trim, InputLocationBuilder locationBuilder)
throws XmlPullParserException, IOException {
XmlPullParser parser = new MXParser();
parser.setInput(reader);
return build(parser, trim, locationBuilder);
}
public static XmlNodeImpl build(XmlPullParser parser) throws XmlPullParserException, IOException {
return build(parser, DEFAULT_TRIM);
}
public static XmlNodeImpl build(XmlPullParser parser, boolean trim) throws XmlPullParserException, IOException {
return build(parser, trim, null);
}
/**
* @since 3.2.0
* @param locationBuilder builder
* @param parser the parser
* @param trim do trim
* @return DOM
* @throws XmlPullParserException XML well-formedness error
* @throws IOException I/O error reading file or stream
*/
public static XmlNodeImpl build(XmlPullParser parser, boolean trim, InputLocationBuilder locationBuilder)
throws XmlPullParserException, IOException {<FILL_FUNCTION_BODY>}
/**
* Input location builder interface, to be implemented to choose how to store data.
*
* @since 3.2.0
*/
public interface InputLocationBuilder {
Object toInputLocation(XmlPullParser parser);
}
}
|
boolean spacePreserve = false;
String name = null;
String value = null;
Object location = null;
Map<String, String> attrs = null;
List<XmlNode> children = null;
int eventType = parser.getEventType();
boolean emptyTag = false;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
emptyTag = parser.isEmptyElementTag();
if (name == null) {
name = parser.getName();
location = locationBuilder != null ? locationBuilder.toInputLocation(parser) : null;
int attributesSize = parser.getAttributeCount();
if (attributesSize > 0) {
attrs = new HashMap<>();
for (int i = 0; i < attributesSize; i++) {
String aname = parser.getAttributeName(i);
String avalue = parser.getAttributeValue(i);
attrs.put(aname, avalue);
spacePreserve = spacePreserve || ("xml:space".equals(aname) && "preserve".equals(avalue));
}
}
} else {
if (children == null) {
children = new ArrayList<>();
}
XmlNode child = build(parser, trim, locationBuilder);
children.add(child);
}
} else if (eventType == XmlPullParser.TEXT) {
String text = parser.getText();
if (trim && !spacePreserve) {
text = text.trim();
}
value = value != null ? value + text : text;
} else if (eventType == XmlPullParser.END_TAG) {
return new XmlNodeImpl(
name,
children == null ? (value != null ? value : emptyTag ? null : "") : null,
attrs,
children,
location);
}
eventType = parser.next();
}
throw new IllegalStateException("End of document found before returning to 0 depth");
| 767
| 515
| 1,282
|
<no_super_class>
|
apache_maven
|
maven/maven-xml-impl/src/main/java/org/apache/maven/internal/xml/XmlNodeStaxBuilder.java
|
XmlNodeStaxBuilder
|
build
|
class XmlNodeStaxBuilder {
private static final boolean DEFAULT_TRIM = true;
public static XmlNodeImpl build(InputStream stream, InputLocationBuilderStax locationBuilder)
throws XMLStreamException {
XMLStreamReader parser = WstxInputFactory.newFactory().createXMLStreamReader(stream);
return build(parser, DEFAULT_TRIM, locationBuilder);
}
public static XmlNodeImpl build(Reader reader, InputLocationBuilderStax locationBuilder) throws XMLStreamException {
XMLStreamReader parser = WstxInputFactory.newFactory().createXMLStreamReader(reader);
return build(parser, DEFAULT_TRIM, locationBuilder);
}
public static XmlNodeImpl build(XMLStreamReader parser) throws XMLStreamException {
return build(parser, DEFAULT_TRIM, null);
}
public static XmlNodeImpl build(XMLStreamReader parser, InputLocationBuilderStax locationBuilder)
throws XMLStreamException {
return build(parser, DEFAULT_TRIM, locationBuilder);
}
public static XmlNodeImpl build(XMLStreamReader parser, boolean trim, InputLocationBuilderStax locationBuilder)
throws XMLStreamException {<FILL_FUNCTION_BODY>}
/**
* Input location builder interface, to be implemented to choose how to store data.
*
* @since 3.2.0
*/
public interface InputLocationBuilderStax {
Object toInputLocation(XMLStreamReader parser);
}
}
|
boolean spacePreserve = false;
String lPrefix = null;
String lNamespaceUri = null;
String lName = null;
String lValue = null;
Object location = null;
Map<String, String> attrs = null;
List<XmlNode> children = null;
int eventType = parser.getEventType();
int lastStartTag = -1;
while (eventType != XMLStreamReader.END_DOCUMENT) {
if (eventType == XMLStreamReader.START_ELEMENT) {
lastStartTag = parser.getLocation().getLineNumber() * 1000
+ parser.getLocation().getColumnNumber();
if (lName == null) {
int namespacesSize = parser.getNamespaceCount();
lPrefix = parser.getPrefix();
lNamespaceUri = parser.getNamespaceURI();
lName = parser.getLocalName();
location = locationBuilder != null ? locationBuilder.toInputLocation(parser) : null;
int attributesSize = parser.getAttributeCount();
if (attributesSize > 0 || namespacesSize > 0) {
attrs = new HashMap<>();
for (int i = 0; i < namespacesSize; i++) {
String nsPrefix = parser.getNamespacePrefix(i);
String nsUri = parser.getNamespaceURI(i);
attrs.put(nsPrefix != null && !nsPrefix.isEmpty() ? "xmlns:" + nsPrefix : "xmlns", nsUri);
}
for (int i = 0; i < attributesSize; i++) {
String aName = parser.getAttributeLocalName(i);
String aValue = parser.getAttributeValue(i);
String aPrefix = parser.getAttributePrefix(i);
if (aPrefix != null && !aPrefix.isEmpty()) {
aName = aPrefix + ":" + aName;
}
attrs.put(aName, aValue);
spacePreserve = spacePreserve || ("xml:space".equals(aName) && "preserve".equals(aValue));
}
}
} else {
if (children == null) {
children = new ArrayList<>();
}
XmlNode child = build(parser, trim, locationBuilder);
children.add(child);
}
} else if (eventType == XMLStreamReader.CHARACTERS || eventType == XMLStreamReader.CDATA) {
String text = parser.getText();
lValue = lValue != null ? lValue + text : text;
} else if (eventType == XMLStreamReader.END_ELEMENT) {
boolean emptyTag = lastStartTag
== parser.getLocation().getLineNumber() * 1000
+ parser.getLocation().getColumnNumber();
if (lValue != null && trim && !spacePreserve) {
lValue = lValue.trim();
}
return new XmlNodeImpl(
lPrefix,
lNamespaceUri,
lName,
children == null ? (lValue != null ? lValue : emptyTag ? null : "") : null,
attrs,
children,
location);
}
eventType = parser.next();
}
throw new IllegalStateException("End of document found before returning to 0 depth");
| 359
| 807
| 1,166
|
<no_super_class>
|
apache_maven
|
maven/maven-xml-impl/src/main/java/org/apache/maven/internal/xml/XmlNodeWriter.java
|
IndentingXMLStreamWriter
|
indent
|
class IndentingXMLStreamWriter extends StreamWriterDelegate {
int depth = 0;
boolean hasChildren = false;
boolean anew = true;
IndentingXMLStreamWriter(XMLStreamWriter parent) {
super(parent);
}
@Override
public void writeStartDocument() throws XMLStreamException {
super.writeStartDocument();
anew = false;
}
@Override
public void writeStartDocument(String version) throws XMLStreamException {
super.writeStartDocument(version);
anew = false;
}
@Override
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
super.writeStartDocument(encoding, version);
anew = false;
}
@Override
public void writeEmptyElement(String localName) throws XMLStreamException {
indent();
super.writeEmptyElement(localName);
hasChildren = true;
anew = false;
}
@Override
public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException {
indent();
super.writeEmptyElement(namespaceURI, localName);
hasChildren = true;
anew = false;
}
@Override
public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
indent();
super.writeEmptyElement(prefix, localName, namespaceURI);
hasChildren = true;
anew = false;
}
@Override
public void writeStartElement(String localName) throws XMLStreamException {
indent();
super.writeStartElement(localName);
depth++;
hasChildren = false;
anew = false;
}
@Override
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
indent();
super.writeStartElement(namespaceURI, localName);
depth++;
hasChildren = false;
anew = false;
}
@Override
public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
indent();
super.writeStartElement(prefix, localName, namespaceURI);
depth++;
hasChildren = false;
anew = false;
}
@Override
public void writeEndElement() throws XMLStreamException {
depth--;
if (hasChildren) {
indent();
}
super.writeEndElement();
hasChildren = true;
anew = false;
}
private void indent() throws XMLStreamException {<FILL_FUNCTION_BODY>}
}
|
if (!anew) {
super.writeCharacters("\n");
}
for (int i = 0; i < depth; i++) {
super.writeCharacters(" ");
}
| 660
| 54
| 714
|
<no_super_class>
|
apache_maven
|
maven/maven-xml-impl/src/main/java/org/apache/maven/internal/xml/XmlPlexusConfiguration.java
|
XmlPlexusConfiguration
|
toString
|
class XmlPlexusConfiguration extends DefaultPlexusConfiguration {
public static PlexusConfiguration toPlexusConfiguration(XmlNode node) {
return new XmlPlexusConfiguration(node);
}
public XmlPlexusConfiguration(XmlNode node) {
super(node.getName(), node.getValue());
node.getAttributes().forEach(this::setAttribute);
node.getChildren().forEach(c -> this.addChild(new XmlPlexusConfiguration(c)));
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
final StringBuilder buf = new StringBuilder().append('<').append(getName());
for (final String a : getAttributeNames()) {
buf.append(' ').append(a).append("=\"").append(getAttribute(a)).append('"');
}
if (getChildCount() > 0) {
buf.append('>');
for (int i = 0, size = getChildCount(); i < size; i++) {
buf.append(getChild(i));
}
buf.append("</").append(getName()).append('>');
} else if (null != getValue()) {
buf.append('>').append(getValue()).append("</").append(getName()).append('>');
} else {
buf.append("/>");
}
return buf.append('\n').toString();
| 149
| 207
| 356
|
<no_super_class>
|
tonikelope_megabasterd
|
megabasterd/src/main/java/com/tonikelope/megabasterd/BoundedExecutor.java
|
BoundedExecutor
|
submitTask
|
class BoundedExecutor {
private final ExecutorService exec;
private final Semaphore semaphore;
public BoundedExecutor(ExecutorService exec, int bound) {
this.exec = exec;
this.semaphore = new Semaphore(bound);
}
public void submitTask(final Runnable command)
throws InterruptedException {<FILL_FUNCTION_BODY>}
}
|
semaphore.acquire();
try {
exec.execute(new Runnable() {
public void run() {
try {
command.run();
} finally {
semaphore.release();
}
}
});
} catch (RejectedExecutionException e) {
semaphore.release();
}
| 104
| 94
| 198
|
<no_super_class>
|
tonikelope_megabasterd
|
megabasterd/src/main/java/com/tonikelope/megabasterd/ChunkDownloaderMono.java
|
ChunkDownloaderMono
|
run
|
class ChunkDownloaderMono extends ChunkDownloader {
private static final Logger LOG = Logger.getLogger(ChunkDownloaderMono.class.getName());
public static final int READ_TIMEOUT_RETRY = 3;
public ChunkDownloaderMono(Download download) {
super(1, download);
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
LOG.log(Level.INFO, "{0} Worker [{1}]: let''s do some work! {2}", new Object[]{Thread.currentThread().getName(), getId(), getDownload().getFile_name()});
HttpURLConnection con = null;
try {
String worker_url = null;
int http_error = 0, http_status = 0, conta_error = 0;
boolean chunk_error = false, timeout = false;
long chunk_id, bytes_downloaded = getDownload().getProgress();
byte[] byte_file_key = initMEGALinkKey(getDownload().getFile_key());
byte[] byte_iv = initMEGALinkKeyIV(getDownload().getFile_key());
byte[] buffer = new byte[DEFAULT_BYTE_BUFFER_SIZE];
CipherInputStream cis = null;
while (!getDownload().getMain_panel().isExit() && !isExit() && !getDownload().isStopped()) {
if (worker_url == null || http_error == 403) {
worker_url = getDownload().getDownloadUrlForWorker();
}
chunk_id = getDownload().nextChunkId();
long chunk_offset = ChunkWriterManager.calculateChunkOffset(chunk_id, 1);
long chunk_size = ChunkWriterManager.calculateChunkSize(chunk_id, getDownload().getFile_size(), chunk_offset, 1);
ChunkWriterManager.checkChunkID(chunk_id, getDownload().getFile_size(), chunk_offset);
long chunk_reads = 0;
try {
if (con == null || chunk_error) {
if (http_error == 509 && MainPanel.isRun_command()) {
MainPanel.run_external_command();
}
URL url = new URL(worker_url + "/" + chunk_offset);
if (MainPanel.isUse_proxy()) {
con = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(MainPanel.getProxy_host(), MainPanel.getProxy_port())));
if (MainPanel.getProxy_user() != null && !"".equals(MainPanel.getProxy_user())) {
con.setRequestProperty("Proxy-Authorization", "Basic " + MiscTools.Bin2BASE64((MainPanel.getProxy_user() + ":" + MainPanel.getProxy_pass()).getBytes("UTF-8")));
}
} else {
con = (HttpURLConnection) url.openConnection();
}
con.setUseCaches(false);
con.setRequestProperty("User-Agent", MainPanel.DEFAULT_USER_AGENT);
http_status = con.getResponseCode();
cis = new CipherInputStream(new ThrottledInputStream(con.getInputStream(), getDownload().getMain_panel().getStream_supervisor()), genDecrypter("AES", "AES/CTR/NoPadding", byte_file_key, forwardMEGALinkKeyIV(byte_iv, bytes_downloaded)));
}
chunk_error = true;
timeout = false;
http_error = 0;
if (http_status != 200) {
LOG.log(Level.INFO, "{0} Failed : HTTP error code : {1} {2}", new Object[]{Thread.currentThread().getName(), http_status, getDownload().getFile_name()});
http_error = http_status;
getDownload().rejectChunkId(chunk_id);
if (!isExit() && http_error != 403) {
setError_wait(true);
try {
Thread.sleep(1000);
} catch (InterruptedException excep) {
}
setError_wait(false);
}
} else {
if (!isExit() && !getDownload().isStopped() && cis != null) {
int reads = 0;
while (!getDownload().isStopped() && chunk_reads < chunk_size && (reads = cis.read(buffer, 0, Math.min((int) (chunk_size - chunk_reads), buffer.length))) != -1) {
getDownload().getOutput_stream().write(buffer, 0, reads);
chunk_reads += reads;
getDownload().getPartialProgress().add((long) reads);
getDownload().getProgress_meter().secureNotify();
if (getDownload().isPaused() && !getDownload().isStopped() && chunk_reads < chunk_size) {
getDownload().pause_worker_mono();
secureWait();
}
}
if (chunk_reads == chunk_size) {
bytes_downloaded += chunk_reads;
chunk_error = false;
http_error = 0;
conta_error = 0;
}
}
}
} catch (IOException ex) {
if (ex instanceof SocketTimeoutException) {
timeout = true;
LOG.log(Level.SEVERE, "{0} TIMEOUT downloading chunk {1}", new Object[]{Thread.currentThread().getName(), chunk_id});
} else {
LOG.log(Level.SEVERE, ex.getMessage());
}
} finally {
if (chunk_error) {
getDownload().rejectChunkId(chunk_id);
if (chunk_reads > 0) {
getDownload().getPartialProgress().add(-1 * chunk_reads);
getDownload().getProgress_meter().secureNotify();
}
if (!isExit() && !getDownload().isStopped() && !timeout && http_error != 403) {
setError_wait(true);
try {
Thread.sleep(MiscTools.getWaitTimeExpBackOff(++conta_error) * 1000);
} catch (InterruptedException exc) {
}
setError_wait(false);
}
if (con != null) {
con.disconnect();
con = null;
}
}
}
}
} catch (ChunkInvalidException e) {
} catch (OutOfMemoryError | Exception error) {
getDownload().stopDownloader(error.getMessage());
LOG.log(Level.SEVERE, error.getMessage());
}
getDownload().stopThisSlot(this);
getDownload().secureNotify();
LOG.log(Level.INFO, "{0} ChunkDownloaderMONO {1}: bye bye", new Object[]{Thread.currentThread().getName(), getDownload().getFile_name()});
| 110
| 1,726
| 1,836
|
<methods>public void <init>(int, com.tonikelope.megabasterd.Download) ,public void RESET_CURRENT_CHUNK() ,public java.lang.String getCurrent_smart_proxy() ,public com.tonikelope.megabasterd.Download getDownload() ,public int getId() ,public boolean isChunk_exception() ,public boolean isError_wait() ,public boolean isExit() ,public void run() ,public void secureNotify() ,public void secureWait() ,public void setError_wait(boolean) ,public void setExit(boolean) <variables>private static final java.util.logging.Logger LOG,public static final int SMART_PROXY_RECHECK_509_TIME,private volatile long _509_timestamp,private volatile boolean _chunk_exception,private volatile java.io.InputStream _chunk_inputstream,private java.lang.String _current_smart_proxy,private final non-sealed com.tonikelope.megabasterd.Download _download,private volatile boolean _error_wait,private final non-sealed ArrayList<java.lang.String> _excluded_proxy_list,private volatile boolean _exit,private final non-sealed int _id,private volatile boolean _notified,private volatile boolean _reset_current_chunk,private final non-sealed java.lang.Object _secure_notify_lock
|
tonikelope_megabasterd
|
megabasterd/src/main/java/com/tonikelope/megabasterd/ClipboardSpy.java
|
ClipboardSpy
|
gainOwnership
|
class ClipboardSpy implements Runnable, ClipboardOwner, SecureSingleThreadNotifiable, ClipboardChangeObservable {
private static final int SLEEP = 250;
private static final Logger LOG = Logger.getLogger(ClipboardSpy.class.getName());
private final Clipboard _sysClip;
private volatile boolean _notified;
private final ConcurrentLinkedQueue<ClipboardChangeObserver> _observers;
private Transferable _contents;
private final Object _secure_notify_lock;
private volatile boolean _enabled;
public ClipboardSpy() {
_sysClip = getDefaultToolkit().getSystemClipboard();
_notified = false;
_enabled = false;
_contents = null;
_secure_notify_lock = new Object();
_observers = new ConcurrentLinkedQueue<>();
}
@Override
public Transferable getContents() {
return _contents;
}
private void _setEnabled(boolean enabled) {
_enabled = enabled;
boolean monitor_clipboard = true;
String monitor_clipboard_string = DBTools.selectSettingValue("clipboardspy");
if (monitor_clipboard_string != null) {
monitor_clipboard = monitor_clipboard_string.equals("yes");
}
if (_enabled && monitor_clipboard) {
_contents = getClipboardContents();
notifyChangeToMyObservers();
gainOwnership(_contents);
LOG.log(Level.INFO, "{0} Monitoring clipboard ON...", Thread.currentThread().getName());
} else if (monitor_clipboard) {
LOG.log(Level.INFO, "{0} Monitoring clipboard OFF...", Thread.currentThread().getName());
}
}
@Override
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait(1000);
} catch (InterruptedException ex) {
LOG.log(SEVERE, ex.getMessage());
}
}
_notified = false;
}
}
@Override
public void run() {
secureWait();
}
@Override
public void lostOwnership(Clipboard c, Transferable t) {
if (_enabled) {
_contents = getClipboardContents();
notifyChangeToMyObservers();
gainOwnership(_contents);
}
}
private Transferable getClipboardContents() {
boolean error;
Transferable c = null;
do {
error = false;
try {
c = _sysClip.getContents(this);
} catch (Exception ex) {
error = true;
try {
sleep(SLEEP);
} catch (InterruptedException ex1) {
LOG.log(SEVERE, ex1.getMessage());
}
}
} while (error);
return c;
}
private void gainOwnership(Transferable t) {<FILL_FUNCTION_BODY>}
@Override
public void attachObserver(ClipboardChangeObserver observer) {
if (!_observers.contains(observer)) {
_observers.add(observer);
}
if (!_observers.isEmpty() && !_enabled) {
_setEnabled(true);
}
}
@Override
public void detachObserver(ClipboardChangeObserver observer) {
if (_observers.contains(observer)) {
_observers.remove(observer);
if (_observers.isEmpty() && _enabled) {
_setEnabled(false);
}
}
}
@Override
public void notifyChangeToMyObservers() {
_observers.forEach((o) -> {
o.notifyClipboardChange();
});
}
}
|
boolean error;
do {
error = false;
try {
_sysClip.setContents(t, this);
} catch (Exception ex) {
error = true;
try {
sleep(SLEEP);
} catch (InterruptedException ex1) {
LOG.log(SEVERE, ex1.getMessage());
}
}
} while (error);
| 1,083
| 112
| 1,195
|
<no_super_class>
|
tonikelope_megabasterd
|
megabasterd/src/main/java/com/tonikelope/megabasterd/ContextMenuMouseListener.java
|
ContextMenuMouseListener
|
mouseClicked
|
class ContextMenuMouseListener extends MouseAdapter {
private static final Logger LOG = Logger.getLogger(ContextMenuMouseListener.class.getName());
private final JPopupMenu _popup;
private final Action _cutAction;
private final Action _copyAction;
private final Action _pasteAction;
private final Action _undoAction;
private final Action _selectAllAction;
private JTextComponent _textComponent;
private String _savedString;
private _Actions _lastActionSelected;
public ContextMenuMouseListener() {
_savedString = "";
_popup = new JPopupMenu();
_undoAction = new AbstractAction("Undo") {
@Override
public void actionPerformed(ActionEvent ae) {
_textComponent.setText("");
_textComponent.replaceSelection(_savedString);
_lastActionSelected = _Actions.UNDO;
}
};
_popup.add(_undoAction);
_popup.addSeparator();
_cutAction = new AbstractAction("Cut") {
@Override
public void actionPerformed(ActionEvent ae) {
_lastActionSelected = _Actions.CUT;
_savedString = _textComponent.getText();
_textComponent.cut();
}
};
_popup.add(_cutAction);
_copyAction = new AbstractAction("Copy") {
@Override
public void actionPerformed(ActionEvent ae) {
_lastActionSelected = _Actions.COPY;
_textComponent.copy();
}
};
_popup.add(_copyAction);
_pasteAction = new AbstractAction("Paste") {
@Override
public void actionPerformed(ActionEvent ae) {
_lastActionSelected = _Actions.PASTE;
_savedString = _textComponent.getText();
_textComponent.paste();
}
};
_popup.add(_pasteAction);
_popup.addSeparator();
_selectAllAction = new AbstractAction("Select All") {
@Override
public void actionPerformed(ActionEvent ae) {
_lastActionSelected = _Actions.SELECT_ALL;
_textComponent.selectAll();
}
};
_popup.add(_selectAllAction);
}
@Override
public void mouseClicked(MouseEvent e) {<FILL_FUNCTION_BODY>}
private enum _Actions {
UNDO, CUT, COPY, PASTE, SELECT_ALL
}
}
|
if (e.getModifiers() == InputEvent.BUTTON3_MASK) {
if (!(e.getSource() instanceof JTextComponent)) {
return;
}
_textComponent = (JTextComponent) e.getSource();
_textComponent.requestFocus();
boolean enabled = _textComponent.isEnabled();
boolean editable = _textComponent.isEditable();
boolean nonempty = !(_textComponent.getText() == null || _textComponent.getText().isEmpty());
boolean marked = _textComponent.getSelectedText() != null;
boolean pasteAvailable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).isDataFlavorSupported(DataFlavor.stringFlavor);
_undoAction.setEnabled(enabled && editable && (_lastActionSelected == _Actions.CUT || _lastActionSelected == _Actions.PASTE));
_cutAction.setEnabled(enabled && editable && marked);
_copyAction.setEnabled(enabled && marked);
_pasteAction.setEnabled(enabled && editable && pasteAvailable);
_selectAllAction.setEnabled(enabled && nonempty);
int nx = e.getX();
if (nx > 500) {
nx -= _popup.getSize().width;
}
_popup.show(e.getComponent(), nx, e.getY() - _popup.getSize().height);
}
| 646
| 362
| 1,008
|
<methods>public void mouseClicked(java.awt.event.MouseEvent) ,public void mouseDragged(java.awt.event.MouseEvent) ,public void mouseEntered(java.awt.event.MouseEvent) ,public void mouseExited(java.awt.event.MouseEvent) ,public void mouseMoved(java.awt.event.MouseEvent) ,public void mousePressed(java.awt.event.MouseEvent) ,public void mouseReleased(java.awt.event.MouseEvent) ,public void mouseWheelMoved(java.awt.event.MouseWheelEvent) <variables>
|
tonikelope_megabasterd
|
megabasterd/src/main/java/com/tonikelope/megabasterd/DownloadManager.java
|
DownloadManager
|
remove
|
class DownloadManager extends TransferenceManager {
private static final Logger LOG = Logger.getLogger(DownloadManager.class.getName());
public DownloadManager(MainPanel main_panel) {
super(main_panel, main_panel.getMax_dl(), main_panel.getView().getStatus_down_label(), main_panel.getView().getjPanel_scroll_down(), main_panel.getView().getClose_all_finished_down_button(), main_panel.getView().getPause_all_down_button(), main_panel.getView().getClean_all_down_menu());
}
public synchronized void forceResetAllChunks() {
THREAD_POOL.execute(() -> {
ConcurrentLinkedQueue<Transference> transference_running_list = getMain_panel().getDownload_manager().getTransference_running_list();
if (!transference_running_list.isEmpty()) {
transference_running_list.forEach((transference) -> {
ArrayList<ChunkDownloader> chunkworkers = ((Download) transference).getChunkworkers();
chunkworkers.forEach((worker) -> {
worker.RESET_CURRENT_CHUNK();
});
});
MiscTools.GUIRun(() -> {
getMain_panel().getView().getForce_chunk_reset_button().setEnabled(true);
});
JOptionPane.showMessageDialog(getMain_panel().getView(), LabelTranslatorSingleton.getInstance().translate("CURRENT DOWNLOAD CHUNKS RESET!"));
}
});
}
@Override
public void closeAllFinished() {
_transference_finished_queue.stream().filter((t) -> (!t.isCanceled())).map((t) -> {
_transference_finished_queue.remove(t);
return t;
}).forEachOrdered((t) -> {
_transference_remove_queue.add(t);
});
secureNotify();
}
public int copyAllLinksToClipboard() {
int total = 0;
ArrayList<String> links = new ArrayList<>();
String out = "***PROVISIONING DOWNLOADS***\r\n\r\n";
for (Transference t : _transference_provision_queue) {
links.add(((Download) t).getUrl());
}
out += String.join("\r\n", links);
total += links.size();
links.clear();
out += "\r\n\r\n***WAITING DOWNLOADS***\r\n\r\n";
for (Transference t : _transference_waitstart_aux_queue) {
links.add(((Download) t).getUrl());
}
for (Transference t : _transference_waitstart_queue) {
links.add(((Download) t).getUrl());
}
out += String.join("\r\n", links);
total += links.size();
links.clear();
out += "\r\n\r\n***RUNNING DOWNLOADS***\r\n\r\n";
for (Transference t : _transference_running_list) {
links.add(((Download) t).getUrl());
}
out += String.join("\r\n", links);
total += links.size();
links.clear();
out += "\r\n\r\n***FINISHED DOWNLOADS***\r\n\r\n";
for (Transference t : _transference_finished_queue) {
links.add(((Download) t).getUrl());
}
out += String.join("\r\n", links);
total += links.size();
MiscTools.copyTextToClipboard(out);
return total;
}
@Override
public void remove(Transference[] downloads) {<FILL_FUNCTION_BODY>}
@Override
public void provision(final Transference download) {
MiscTools.GUIRun(() -> {
getScroll_panel().add(((Download) download).getView());
});
try {
_provision((Download) download, false);
secureNotify();
} catch (APIException ex) {
LOG.log(Level.INFO, "{0} Provision failed! Retrying in separated thread...", Thread.currentThread().getName());
THREAD_POOL.execute(() -> {
try {
_provision((Download) download, true);
} catch (APIException ex1) {
LOG.log(SEVERE, null, ex1);
}
secureNotify();
});
}
}
private void _provision(Download download, boolean retry) throws APIException {
download.provisionIt(retry);
if (download.isProvision_ok()) {
increment_total_size(download.getFile_size());
getTransference_waitstart_aux_queue().add(download);
} else {
getTransference_finished_queue().add(download);
}
}
}
|
ArrayList<String> delete_down = new ArrayList<>();
for (final Transference d : downloads) {
MiscTools.GUIRun(() -> {
getScroll_panel().remove(((Download) d).getView());
});
getTransference_waitstart_queue().remove(d);
getTransference_running_list().remove(d);
getTransference_finished_queue().remove(d);
if (((Download) d).isProvision_ok()) {
increment_total_size(-1 * d.getFile_size());
increment_total_progress(-1 * d.getProgress());
if (!d.isCanceled() || d.isClosed()) {
delete_down.add(((Download) d).getUrl());
}
}
}
try {
deleteDownloads(delete_down.toArray(new String[delete_down.size()]));
} catch (SQLException ex) {
LOG.log(SEVERE, null, ex);
}
secureNotify();
| 1,351
| 274
| 1,625
|
<methods>public void <init>(com.tonikelope.megabasterd.MainPanel, int, javax.swing.JLabel, javax.swing.JPanel, javax.swing.JButton, javax.swing.JButton, javax.swing.MenuElement) ,public void bottomWaitQueue(com.tonikelope.megabasterd.Transference) ,public int calcTotalSlotsCount() ,public void cancelAllTransferences() ,public void closeAllFinished() ,public void closeAllPreProWaiting() ,public void downWaitQueue(com.tonikelope.megabasterd.Transference) ,public com.tonikelope.megabasterd.MainPanel getMain_panel() ,public javax.swing.JPanel getScroll_panel() ,public java.lang.Boolean getSort_wait_start_queue() ,public ConcurrentLinkedQueue<com.tonikelope.megabasterd.Transference> getTransference_finished_queue() ,public ConcurrentLinkedQueue<java.lang.Object> getTransference_preprocess_global_queue() ,public ConcurrentLinkedQueue<java.lang.Runnable> getTransference_preprocess_queue() ,public ConcurrentLinkedQueue<com.tonikelope.megabasterd.Transference> getTransference_provision_queue() ,public ConcurrentLinkedQueue<com.tonikelope.megabasterd.Transference> getTransference_remove_queue() ,public ConcurrentLinkedQueue<com.tonikelope.megabasterd.Transference> getTransference_running_list() ,public ConcurrentLinkedQueue<com.tonikelope.megabasterd.Transference> getTransference_waitstart_aux_queue() ,public ConcurrentLinkedQueue<com.tonikelope.megabasterd.Transference> getTransference_waitstart_queue() ,public java.lang.Object getWait_queue_lock() ,public long get_total_progress() ,public long get_total_size() ,public void increment_total_progress(long) ,public void increment_total_size(long) ,public boolean isAll_finished() ,public boolean isPaused_all() ,public boolean isPreprocessing_transferences() ,public boolean isProvisioning_transferences() ,public boolean isRemoving_transferences() ,public boolean isStarting_transferences() ,public boolean no_transferences() ,public void pauseAll() ,public abstract void provision(com.tonikelope.megabasterd.Transference) ,public abstract void remove(com.tonikelope.megabasterd.Transference[]) ,public void resumeAll() ,public void run() ,public void secureNotify() ,public void secureWait() ,public void setAll_finished(boolean) ,public void setMax_running_trans(int) ,public void setPaused_all(boolean) ,public void setPreprocessing_transferences(boolean) ,public void setProvisioning_transferences(boolean) ,public void setRemoving_transferences(boolean) ,public void setSort_wait_start_queue(java.lang.Boolean) ,public void setStarting_transferences(boolean) ,public void start(com.tonikelope.megabasterd.Transference) ,public void topWaitQueue(com.tonikelope.megabasterd.Transference) ,public void upWaitQueue(com.tonikelope.megabasterd.Transference) <variables>private static final java.util.logging.Logger LOG,public static final int MAX_PROVISION_WORKERS,public static final int MAX_WAIT_QUEUE,protected volatile boolean _all_finished,private final non-sealed javax.swing.MenuElement _clean_all_menu,private final non-sealed javax.swing.JButton _close_all_button,private final non-sealed com.tonikelope.megabasterd.MainPanel _main_panel,private int _max_running_trans,private volatile boolean _notified,private final non-sealed javax.swing.JButton _pause_all_button,private final non-sealed java.lang.Object _pause_all_lock,private volatile boolean _paused_all,private volatile boolean _preprocessing_transferences,private volatile boolean _provisioning_transferences,private volatile boolean _removing_transferences,private final non-sealed javax.swing.JPanel _scroll_panel,private final non-sealed java.lang.Object _secure_notify_lock,private volatile java.lang.Boolean _sort_wait_start_queue,private volatile boolean _starting_transferences,private final non-sealed javax.swing.JLabel _status,protected volatile long _total_progress,protected final non-sealed java.lang.Object _total_progress_lock,protected volatile long _total_size,protected final non-sealed java.lang.Object _total_size_lock,protected final non-sealed ConcurrentLinkedQueue<com.tonikelope.megabasterd.Transference> _transference_finished_queue,protected final non-sealed ConcurrentLinkedQueue<java.lang.Object> _transference_preprocess_global_queue,protected final non-sealed ConcurrentLinkedQueue<java.lang.Runnable> _transference_preprocess_queue,protected final non-sealed ConcurrentLinkedQueue<com.tonikelope.megabasterd.Transference> _transference_provision_queue,protected final non-sealed java.lang.Object _transference_queue_sort_lock,protected final non-sealed ConcurrentLinkedQueue<com.tonikelope.megabasterd.Transference> _transference_remove_queue,protected final non-sealed ConcurrentLinkedQueue<com.tonikelope.megabasterd.Transference> _transference_running_list,protected final non-sealed ConcurrentLinkedQueue<com.tonikelope.megabasterd.Transference> _transference_waitstart_aux_queue,protected final non-sealed ConcurrentLinkedQueue<com.tonikelope.megabasterd.Transference> _transference_waitstart_queue,private boolean _tray_icon_finish,private final non-sealed java.lang.Object _wait_queue_lock
|
tonikelope_megabasterd
|
megabasterd/src/main/java/com/tonikelope/megabasterd/MegaMutableTreeNode.java
|
MegaMutableTreeNode
|
clone
|
class MegaMutableTreeNode extends DefaultMutableTreeNode {
protected long mega_node_size = 0L;
protected Comparator nodeComparator = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return MiscTools.naturalCompare(o1.toString(), o2.toString(), true);
}
@Override
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
public boolean equals(Object obj) {
return false;
}
};
public void setMega_node_size(long mega_node_size) {
this.mega_node_size = mega_node_size;
}
public long getMega_node_size() {
return mega_node_size;
}
public MegaMutableTreeNode() {
super();
}
public MegaMutableTreeNode(Object o) {
super(o);
this.mega_node_size = (long) ((HashMap<String, Object>) o).get("size");
}
@Override
public String toString() {
if (userObject instanceof HashMap) {
HashMap<String, Object> user_object = (HashMap<String, Object>) userObject;
return user_object.get("name") + " [" + formatBytes(mega_node_size) + "]";
} else if (userObject instanceof Object) {
return userObject.toString();
} else {
return "";
}
}
@Override
public Object clone() {<FILL_FUNCTION_BODY>}
@Override
public void insert(MutableTreeNode newChild, int childIndex) {
super.insert(newChild, childIndex);
}
}
|
return super.clone(); //To change body of generated methods, choose Tools | Templates.
| 460
| 24
| 484
|
<methods>public void <init>() ,public void <init>(java.lang.Object) ,public void <init>(java.lang.Object, boolean) ,public void add(javax.swing.tree.MutableTreeNode) ,public Enumeration<javax.swing.tree.TreeNode> breadthFirstEnumeration() ,public Enumeration<javax.swing.tree.TreeNode> children() ,public java.lang.Object clone() ,public Enumeration<javax.swing.tree.TreeNode> depthFirstEnumeration() ,public boolean getAllowsChildren() ,public javax.swing.tree.TreeNode getChildAfter(javax.swing.tree.TreeNode) ,public javax.swing.tree.TreeNode getChildAt(int) ,public javax.swing.tree.TreeNode getChildBefore(javax.swing.tree.TreeNode) ,public int getChildCount() ,public int getDepth() ,public javax.swing.tree.TreeNode getFirstChild() ,public javax.swing.tree.DefaultMutableTreeNode getFirstLeaf() ,public int getIndex(javax.swing.tree.TreeNode) ,public javax.swing.tree.TreeNode getLastChild() ,public javax.swing.tree.DefaultMutableTreeNode getLastLeaf() ,public int getLeafCount() ,public int getLevel() ,public javax.swing.tree.DefaultMutableTreeNode getNextLeaf() ,public javax.swing.tree.DefaultMutableTreeNode getNextNode() ,public javax.swing.tree.DefaultMutableTreeNode getNextSibling() ,public javax.swing.tree.TreeNode getParent() ,public javax.swing.tree.TreeNode[] getPath() ,public javax.swing.tree.DefaultMutableTreeNode getPreviousLeaf() ,public javax.swing.tree.DefaultMutableTreeNode getPreviousNode() ,public javax.swing.tree.DefaultMutableTreeNode getPreviousSibling() ,public javax.swing.tree.TreeNode getRoot() ,public javax.swing.tree.TreeNode getSharedAncestor(javax.swing.tree.DefaultMutableTreeNode) ,public int getSiblingCount() ,public java.lang.Object getUserObject() ,public java.lang.Object[] getUserObjectPath() ,public void insert(javax.swing.tree.MutableTreeNode, int) ,public boolean isLeaf() ,public boolean isNodeAncestor(javax.swing.tree.TreeNode) ,public boolean isNodeChild(javax.swing.tree.TreeNode) ,public boolean isNodeDescendant(javax.swing.tree.DefaultMutableTreeNode) ,public boolean isNodeRelated(javax.swing.tree.DefaultMutableTreeNode) ,public boolean isNodeSibling(javax.swing.tree.TreeNode) ,public boolean isRoot() ,public Enumeration<javax.swing.tree.TreeNode> pathFromAncestorEnumeration(javax.swing.tree.TreeNode) ,public Enumeration<javax.swing.tree.TreeNode> postorderEnumeration() ,public Enumeration<javax.swing.tree.TreeNode> preorderEnumeration() ,public void remove(int) ,public void remove(javax.swing.tree.MutableTreeNode) ,public void removeAllChildren() ,public void removeFromParent() ,public void setAllowsChildren(boolean) ,public void setParent(javax.swing.tree.MutableTreeNode) ,public void setUserObject(java.lang.Object) ,public java.lang.String toString() <variables>public static final Enumeration<javax.swing.tree.TreeNode> EMPTY_ENUMERATION,protected boolean allowsChildren,protected Vector<javax.swing.tree.TreeNode> children,protected javax.swing.tree.MutableTreeNode parent,private static final long serialVersionUID,protected transient java.lang.Object userObject
|
tonikelope_megabasterd
|
megabasterd/src/main/java/com/tonikelope/megabasterd/MegaProxyServer.java
|
Handler
|
run
|
class Handler extends Thread {
public static final Pattern CONNECT_PATTERN = Pattern.compile("CONNECT (.*mega(?:\\.co)?\\.nz):(443) HTTP/(1\\.[01])", Pattern.CASE_INSENSITIVE);
public static final Pattern AUTH_PATTERN = Pattern.compile("Proxy-Authorization: Basic +(.+)", Pattern.CASE_INSENSITIVE);
private static void forwardData(Socket inputSocket, Socket outputSocket) {
try {
InputStream inputStream = inputSocket.getInputStream();
try {
OutputStream outputStream = outputSocket.getOutputStream();
try {
byte[] buffer = new byte[4096];
int read;
do {
read = inputStream.read(buffer);
if (read > 0) {
outputStream.write(buffer, 0, read);
if (inputStream.available() < 1) {
outputStream.flush();
}
}
} while (read >= 0);
} finally {
if (!outputSocket.isOutputShutdown()) {
outputSocket.shutdownOutput();
}
}
} finally {
if (!inputSocket.isInputShutdown()) {
inputSocket.shutdownInput();
}
}
} catch (IOException e) {
}
}
private final Socket _clientSocket;
private boolean _previousWasR = false;
private final String _password;
public Handler(Socket clientSocket, String password) {
_clientSocket = clientSocket;
_password = password;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
private String readLine(Socket socket) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int next;
readerLoop:
while ((next = socket.getInputStream().read()) != -1) {
if (_previousWasR && next == '\n') {
_previousWasR = false;
continue;
}
_previousWasR = false;
switch (next) {
case '\r':
_previousWasR = true;
break readerLoop;
case '\n':
break readerLoop;
default:
byteArrayOutputStream.write(next);
break;
}
}
return byteArrayOutputStream.toString("UTF-8");
}
}
|
try {
String request = readLine(_clientSocket);
LOG.log(Level.INFO, request);
Matcher matcher = CONNECT_PATTERN.matcher(request);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(_clientSocket.getOutputStream(), "UTF-8");
if (matcher.matches()) {
String header;
String proxy_auth = null;
do {
header = readLine(_clientSocket);
Matcher matcher_auth = AUTH_PATTERN.matcher(header);
if (matcher_auth.matches()) {
proxy_auth = new String(BASE642Bin(matcher_auth.group(1).trim()), "UTF-8");
}
LOG.log(Level.INFO, header);
} while (!"".equals(header));
if (proxy_auth != null && proxy_auth.matches(".*?: *?" + _password)) {
final Socket forwardSocket;
try {
forwardSocket = new Socket(matcher.group(1), Integer.parseInt(matcher.group(2)));
} catch (IOException | NumberFormatException e) {
outputStreamWriter.write("HTTP/" + matcher.group(3) + " 502 Bad Gateway\r\n");
outputStreamWriter.write("Proxy-agent: MegaBasterd/0.1\r\n");
outputStreamWriter.write("\r\n");
outputStreamWriter.flush();
return;
}
try {
outputStreamWriter.write("HTTP/" + matcher.group(3) + " 200 Connection established\r\n");
outputStreamWriter.write("Proxy-agent: MegaBasterd/0.1\r\n");
outputStreamWriter.write("\r\n");
outputStreamWriter.flush();
Thread remoteToClient = new Thread() {
@Override
public void run() {
forwardData(forwardSocket, _clientSocket);
}
};
remoteToClient.start();
try {
if (_previousWasR) {
int read = _clientSocket.getInputStream().read();
if (read != -1) {
if (read != '\n') {
forwardSocket.getOutputStream().write(read);
}
forwardData(_clientSocket, forwardSocket);
} else {
if (!forwardSocket.isOutputShutdown()) {
forwardSocket.shutdownOutput();
}
if (!_clientSocket.isInputShutdown()) {
_clientSocket.shutdownInput();
}
}
} else {
forwardData(_clientSocket, forwardSocket);
}
} finally {
try {
remoteToClient.join();
} catch (InterruptedException e) {
}
}
} finally {
forwardSocket.close();
}
} else {
outputStreamWriter.write("HTTP/1.1 403 Unauthorized\r\n");
outputStreamWriter.write("Proxy-agent: MegaBasterd/0.1\r\n");
outputStreamWriter.write("\r\n");
outputStreamWriter.flush();
}
} else {
outputStreamWriter.write("HTTP/1.1 403 Unauthorized\r\n");
outputStreamWriter.write("Proxy-agent: MegaBasterd/0.1\r\n");
outputStreamWriter.write("\r\n");
outputStreamWriter.flush();
}
} catch (IOException e) {
} finally {
try {
_clientSocket.close();
} catch (IOException e) {
}
}
| 608
| 928
| 1,536
|
<no_super_class>
|
tonikelope_megabasterd
|
megabasterd/src/main/java/com/tonikelope/megabasterd/ProgressMeter.java
|
ProgressMeter
|
run
|
class ProgressMeter implements Runnable, SecureSingleThreadNotifiable {
private static final Logger LOG = Logger.getLogger(ProgressMeter.class.getName());
private final Transference _transference;
private volatile boolean _exit;
private final Object _secure_notify_lock;
private volatile boolean _notified;
private long _progress;
ProgressMeter(Transference transference) {
_notified = false;
_secure_notify_lock = new Object();
_transference = transference;
_progress = 0;
_exit = false;
}
public void setExit(boolean value) {
_exit = value;
}
@Override
public void secureNotify() {
synchronized (_secure_notify_lock) {
_notified = true;
_secure_notify_lock.notify();
}
}
@Override
public void secureWait() {
synchronized (_secure_notify_lock) {
while (!_notified) {
try {
_secure_notify_lock.wait(1000);
} catch (InterruptedException ex) {
_exit = true;
LOG.log(SEVERE, null, ex);
}
}
_notified = false;
}
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
LOG.log(Level.INFO, "{0} ProgressMeter hello! {1}", new Object[]{Thread.currentThread().getName(), _transference.getFile_name()});
_progress = _transference.getProgress();
while (!_exit || !_transference.getPartialProgress().isEmpty()) {
Long reads;
while ((reads = _transference.getPartialProgress().poll()) != null) {
_progress += reads;
_transference.setProgress(_progress);
}
if (!_exit) {
secureWait();
}
}
LOG.log(Level.INFO, "{0} ProgressMeter bye bye! {1}", new Object[]{Thread.currentThread().getName(), _transference.getFile_name()});
| 362
| 206
| 568
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.