repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
windup/windup | forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java | Compiler.accept | @Override
public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {
// Switch the current policy and compilation result for this unit to the requested one.
CompilationResult unitResult =
new CompilationResult(sourceUnit, this.totalUnits, this.totalUnits, this.options.maxProblemsPerUnit);
unitResult.checkSecondaryTypes = true;
try {
if (this.options.verbose) {
String count = String.valueOf(this.totalUnits + 1);
this.out.println(
Messages.bind(Messages.compilation_request,
new String[] {
count,
count,
new String(sourceUnit.getFileName())
}));
}
// diet parsing for large collection of unit
CompilationUnitDeclaration parsedUnit;
if (this.totalUnits < this.parseThreshold) {
parsedUnit = this.parser.parse(sourceUnit, unitResult);
} else {
parsedUnit = this.parser.dietParse(sourceUnit, unitResult);
}
// initial type binding creation
this.lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);
addCompilationUnit(sourceUnit, parsedUnit);
// binding resolution
this.lookupEnvironment.completeTypeBindings(parsedUnit);
} catch (AbortCompilationUnit e) {
// at this point, currentCompilationUnitResult may not be sourceUnit, but some other
// one requested further along to resolve sourceUnit.
if (unitResult.compilationUnit == sourceUnit) { // only report once
this.requestor.acceptResult(unitResult.tagAsAccepted());
} else {
throw e; // want to abort enclosing request to compile
}
}
} | java | @Override
public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {
// Switch the current policy and compilation result for this unit to the requested one.
CompilationResult unitResult =
new CompilationResult(sourceUnit, this.totalUnits, this.totalUnits, this.options.maxProblemsPerUnit);
unitResult.checkSecondaryTypes = true;
try {
if (this.options.verbose) {
String count = String.valueOf(this.totalUnits + 1);
this.out.println(
Messages.bind(Messages.compilation_request,
new String[] {
count,
count,
new String(sourceUnit.getFileName())
}));
}
// diet parsing for large collection of unit
CompilationUnitDeclaration parsedUnit;
if (this.totalUnits < this.parseThreshold) {
parsedUnit = this.parser.parse(sourceUnit, unitResult);
} else {
parsedUnit = this.parser.dietParse(sourceUnit, unitResult);
}
// initial type binding creation
this.lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);
addCompilationUnit(sourceUnit, parsedUnit);
// binding resolution
this.lookupEnvironment.completeTypeBindings(parsedUnit);
} catch (AbortCompilationUnit e) {
// at this point, currentCompilationUnitResult may not be sourceUnit, but some other
// one requested further along to resolve sourceUnit.
if (unitResult.compilationUnit == sourceUnit) { // only report once
this.requestor.acceptResult(unitResult.tagAsAccepted());
} else {
throw e; // want to abort enclosing request to compile
}
}
} | [
"@",
"Override",
"public",
"void",
"accept",
"(",
"ICompilationUnit",
"sourceUnit",
",",
"AccessRestriction",
"accessRestriction",
")",
"{",
"// Switch the current policy and compilation result for this unit to the requested one.",
"CompilationResult",
"unitResult",
"=",
"new",
"... | Add an additional compilation unit into the loop
-> build compilation unit declarations, their bindings and record their results. | [
"Add",
"an",
"additional",
"compilation",
"unit",
"into",
"the",
"loop",
"-",
">",
"build",
"compilation",
"unit",
"declarations",
"their",
"bindings",
"and",
"record",
"their",
"results",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java#L329-L368 | train |
windup/windup | forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java | Compiler.accept | @Override
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
this.problemReporter.abortDueToInternalError(
Messages.bind(Messages.abort_againstSourceModel, new String[] { String.valueOf(sourceTypes[0].getName()), String.valueOf(sourceTypes[0].getFileName()) }));
} | java | @Override
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
this.problemReporter.abortDueToInternalError(
Messages.bind(Messages.abort_againstSourceModel, new String[] { String.valueOf(sourceTypes[0].getName()), String.valueOf(sourceTypes[0].getFileName()) }));
} | [
"@",
"Override",
"public",
"void",
"accept",
"(",
"ISourceType",
"[",
"]",
"sourceTypes",
",",
"PackageBinding",
"packageBinding",
",",
"AccessRestriction",
"accessRestriction",
")",
"{",
"this",
".",
"problemReporter",
".",
"abortDueToInternalError",
"(",
"Messages",... | Add additional source types | [
"Add",
"additional",
"source",
"types"
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java#L373-L377 | train |
windup/windup | forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java | Compiler.reportProgress | protected void reportProgress(String taskDecription) {
if (this.progress != null) {
if (this.progress.isCanceled()) {
// Only AbortCompilation can stop the compiler cleanly.
// We check cancellation again following the call to compile.
throw new AbortCompilation(true, null);
}
this.progress.setTaskName(taskDecription);
}
} | java | protected void reportProgress(String taskDecription) {
if (this.progress != null) {
if (this.progress.isCanceled()) {
// Only AbortCompilation can stop the compiler cleanly.
// We check cancellation again following the call to compile.
throw new AbortCompilation(true, null);
}
this.progress.setTaskName(taskDecription);
}
} | [
"protected",
"void",
"reportProgress",
"(",
"String",
"taskDecription",
")",
"{",
"if",
"(",
"this",
".",
"progress",
"!=",
"null",
")",
"{",
"if",
"(",
"this",
".",
"progress",
".",
"isCanceled",
"(",
")",
")",
"{",
"// Only AbortCompilation can stop the comp... | Checks whether the compilation has been canceled and reports the given progress to the compiler progress. | [
"Checks",
"whether",
"the",
"compilation",
"has",
"been",
"canceled",
"and",
"reports",
"the",
"given",
"progress",
"to",
"the",
"compiler",
"progress",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java#L414-L423 | train |
windup/windup | forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java | Compiler.reportWorked | protected void reportWorked(int workIncrement, int currentUnitIndex) {
if (this.progress != null) {
if (this.progress.isCanceled()) {
// Only AbortCompilation can stop the compiler cleanly.
// We check cancellation again following the call to compile.
throw new AbortCompilation(true, null);
}
this.progress.worked(workIncrement, (this.totalUnits* this.remainingIterations) - currentUnitIndex - 1);
}
} | java | protected void reportWorked(int workIncrement, int currentUnitIndex) {
if (this.progress != null) {
if (this.progress.isCanceled()) {
// Only AbortCompilation can stop the compiler cleanly.
// We check cancellation again following the call to compile.
throw new AbortCompilation(true, null);
}
this.progress.worked(workIncrement, (this.totalUnits* this.remainingIterations) - currentUnitIndex - 1);
}
} | [
"protected",
"void",
"reportWorked",
"(",
"int",
"workIncrement",
",",
"int",
"currentUnitIndex",
")",
"{",
"if",
"(",
"this",
".",
"progress",
"!=",
"null",
")",
"{",
"if",
"(",
"this",
".",
"progress",
".",
"isCanceled",
"(",
")",
")",
"{",
"// Only Ab... | Checks whether the compilation has been canceled and reports the given work increment to the compiler progress. | [
"Checks",
"whether",
"the",
"compilation",
"has",
"been",
"canceled",
"and",
"reports",
"the",
"given",
"work",
"increment",
"to",
"the",
"compiler",
"progress",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java#L428-L437 | train |
windup/windup | forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java | Compiler.compile | private void compile(ICompilationUnit[] sourceUnits, boolean lastRound) {
this.stats.startTime = System.currentTimeMillis();
try {
// build and record parsed units
reportProgress(Messages.compilation_beginningToCompile);
if (this.options.complianceLevel >= ClassFileConstants.JDK9) {
// in Java 9 the compiler must never ask the oracle for a module that is contained in the input units:
sortModuleDeclarationsFirst(sourceUnits);
}
if (this.annotationProcessorManager == null) {
beginToCompile(sourceUnits);
} else {
ICompilationUnit[] originalUnits = sourceUnits.clone(); // remember source units in case a source type collision occurs
try {
beginToCompile(sourceUnits);
if (!lastRound) {
processAnnotations();
}
if (!this.options.generateClassFiles) {
// -proc:only was set on the command line
return;
}
} catch (SourceTypeCollisionException e) {
backupAptProblems();
reset();
// a generated type was referenced before it was created
// the compiler either created a MissingType or found a BinaryType for it
// so add the processor's generated files & start over,
// but remember to only pass the generated files to the annotation processor
int originalLength = originalUnits.length;
int newProcessedLength = e.newAnnotationProcessorUnits.length;
ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength];
System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength);
System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength);
this.annotationProcessorStartIndex = originalLength;
compile(combinedUnits, e.isLastRound);
return;
}
}
// Restore the problems before the results are processed and cleaned up.
restoreAptProblems();
processCompiledUnits(0, lastRound);
} catch (AbortCompilation e) {
this.handleInternalException(e, null);
}
if (this.options.verbose) {
if (this.totalUnits > 1) {
this.out.println(
Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits)));
} else {
this.out.println(
Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits)));
}
}
} | java | private void compile(ICompilationUnit[] sourceUnits, boolean lastRound) {
this.stats.startTime = System.currentTimeMillis();
try {
// build and record parsed units
reportProgress(Messages.compilation_beginningToCompile);
if (this.options.complianceLevel >= ClassFileConstants.JDK9) {
// in Java 9 the compiler must never ask the oracle for a module that is contained in the input units:
sortModuleDeclarationsFirst(sourceUnits);
}
if (this.annotationProcessorManager == null) {
beginToCompile(sourceUnits);
} else {
ICompilationUnit[] originalUnits = sourceUnits.clone(); // remember source units in case a source type collision occurs
try {
beginToCompile(sourceUnits);
if (!lastRound) {
processAnnotations();
}
if (!this.options.generateClassFiles) {
// -proc:only was set on the command line
return;
}
} catch (SourceTypeCollisionException e) {
backupAptProblems();
reset();
// a generated type was referenced before it was created
// the compiler either created a MissingType or found a BinaryType for it
// so add the processor's generated files & start over,
// but remember to only pass the generated files to the annotation processor
int originalLength = originalUnits.length;
int newProcessedLength = e.newAnnotationProcessorUnits.length;
ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength];
System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength);
System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength);
this.annotationProcessorStartIndex = originalLength;
compile(combinedUnits, e.isLastRound);
return;
}
}
// Restore the problems before the results are processed and cleaned up.
restoreAptProblems();
processCompiledUnits(0, lastRound);
} catch (AbortCompilation e) {
this.handleInternalException(e, null);
}
if (this.options.verbose) {
if (this.totalUnits > 1) {
this.out.println(
Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits)));
} else {
this.out.println(
Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits)));
}
}
} | [
"private",
"void",
"compile",
"(",
"ICompilationUnit",
"[",
"]",
"sourceUnits",
",",
"boolean",
"lastRound",
")",
"{",
"this",
".",
"stats",
".",
"startTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"try",
"{",
"// build and record parsed units",... | General API
-> compile each of supplied files
-> recompile any required types for which we have an incomplete principle structure | [
"General",
"API",
"-",
">",
"compile",
"each",
"of",
"supplied",
"files",
"-",
">",
"recompile",
"any",
"required",
"types",
"for",
"which",
"we",
"have",
"an",
"incomplete",
"principle",
"structure"
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java#L447-L502 | train |
windup/windup | forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java | Compiler.process | public void process(CompilationUnitDeclaration unit, int i) {
this.lookupEnvironment.unitBeingCompleted = unit;
long parseStart = System.currentTimeMillis();
this.parser.getMethodBodies(unit);
long resolveStart = System.currentTimeMillis();
this.stats.parseTime += resolveStart - parseStart;
// fault in fields & methods
if (unit.scope != null)
unit.scope.faultInTypes();
// verify inherited methods
if (unit.scope != null)
unit.scope.verifyMethods(this.lookupEnvironment.methodVerifier());
// type checking
unit.resolve();
long analyzeStart = System.currentTimeMillis();
this.stats.resolveTime += analyzeStart - resolveStart;
//No need of analysis or generation of code if statements are not required
if (!this.options.ignoreMethodBodies) unit.analyseCode(); // flow analysis
long generateStart = System.currentTimeMillis();
this.stats.analyzeTime += generateStart - analyzeStart;
if (!this.options.ignoreMethodBodies) unit.generateCode(); // code generation
// reference info
if (this.options.produceReferenceInfo && unit.scope != null)
unit.scope.storeDependencyInfo();
// finalize problems (suppressWarnings)
unit.finalizeProblems();
this.stats.generateTime += System.currentTimeMillis() - generateStart;
// refresh the total number of units known at this stage
unit.compilationResult.totalUnitsKnown = this.totalUnits;
this.lookupEnvironment.unitBeingCompleted = null;
} | java | public void process(CompilationUnitDeclaration unit, int i) {
this.lookupEnvironment.unitBeingCompleted = unit;
long parseStart = System.currentTimeMillis();
this.parser.getMethodBodies(unit);
long resolveStart = System.currentTimeMillis();
this.stats.parseTime += resolveStart - parseStart;
// fault in fields & methods
if (unit.scope != null)
unit.scope.faultInTypes();
// verify inherited methods
if (unit.scope != null)
unit.scope.verifyMethods(this.lookupEnvironment.methodVerifier());
// type checking
unit.resolve();
long analyzeStart = System.currentTimeMillis();
this.stats.resolveTime += analyzeStart - resolveStart;
//No need of analysis or generation of code if statements are not required
if (!this.options.ignoreMethodBodies) unit.analyseCode(); // flow analysis
long generateStart = System.currentTimeMillis();
this.stats.analyzeTime += generateStart - analyzeStart;
if (!this.options.ignoreMethodBodies) unit.generateCode(); // code generation
// reference info
if (this.options.produceReferenceInfo && unit.scope != null)
unit.scope.storeDependencyInfo();
// finalize problems (suppressWarnings)
unit.finalizeProblems();
this.stats.generateTime += System.currentTimeMillis() - generateStart;
// refresh the total number of units known at this stage
unit.compilationResult.totalUnitsKnown = this.totalUnits;
this.lookupEnvironment.unitBeingCompleted = null;
} | [
"public",
"void",
"process",
"(",
"CompilationUnitDeclaration",
"unit",
",",
"int",
"i",
")",
"{",
"this",
".",
"lookupEnvironment",
".",
"unitBeingCompleted",
"=",
"unit",
";",
"long",
"parseStart",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"thi... | Process a compilation unit already parsed and build. | [
"Process",
"a",
"compilation",
"unit",
"already",
"parsed",
"and",
"build",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/forks/jdt/src/main/java/org/eclipse/jdt/internal/compiler/Compiler.java#L888-L932 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/tags/TagServiceHolder.java | TagServiceHolder.loadTagDefinitions | @PostConstruct
public void loadTagDefinitions()
{
Map<Addon, List<URL>> addonToResourcesMap = scanner.scanForAddonMap(new FileExtensionFilter("tags.xml"));
for (Map.Entry<Addon, List<URL>> entry : addonToResourcesMap.entrySet())
{
for (URL resource : entry.getValue())
{
log.info("Reading tags definitions from: " + resource.toString() + " from addon " + entry.getKey().getId());
try(InputStream is = resource.openStream())
{
tagService.readTags(is);
}
catch( Exception ex )
{
throw new WindupException("Failed reading tags definition: " + resource.toString() + " from addon " + entry.getKey().getId() + ":\n" + ex.getMessage(), ex);
}
}
}
} | java | @PostConstruct
public void loadTagDefinitions()
{
Map<Addon, List<URL>> addonToResourcesMap = scanner.scanForAddonMap(new FileExtensionFilter("tags.xml"));
for (Map.Entry<Addon, List<URL>> entry : addonToResourcesMap.entrySet())
{
for (URL resource : entry.getValue())
{
log.info("Reading tags definitions from: " + resource.toString() + " from addon " + entry.getKey().getId());
try(InputStream is = resource.openStream())
{
tagService.readTags(is);
}
catch( Exception ex )
{
throw new WindupException("Failed reading tags definition: " + resource.toString() + " from addon " + entry.getKey().getId() + ":\n" + ex.getMessage(), ex);
}
}
}
} | [
"@",
"PostConstruct",
"public",
"void",
"loadTagDefinitions",
"(",
")",
"{",
"Map",
"<",
"Addon",
",",
"List",
"<",
"URL",
">",
">",
"addonToResourcesMap",
"=",
"scanner",
".",
"scanForAddonMap",
"(",
"new",
"FileExtensionFilter",
"(",
"\"tags.xml\"",
")",
")"... | Loads the tag definitions from the files with a ".tags.xml" suffix from the addons. | [
"Loads",
"the",
"tag",
"definitions",
"from",
"the",
"files",
"with",
"a",
".",
"tags",
".",
"xml",
"suffix",
"from",
"the",
"addons",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/tags/TagServiceHolder.java#L44-L63 | train |
windup/windup | java-ast/addon/src/main/java/org/jboss/windup/ast/java/BatchASTProcessor.java | BatchASTProcessor.analyze | public static BatchASTFuture analyze(final BatchASTListener listener, final WildcardImportResolver importResolver,
final Set<String> libraryPaths,
final Set<String> sourcePaths, Set<Path> sourceFiles)
{
final String[] encodings = null;
final String[] bindingKeys = new String[0];
final ExecutorService executor = WindupExecutors.newFixedThreadPool(WindupExecutors.getDefaultThreadCount());
final FileASTRequestor requestor = new FileASTRequestor()
{
@Override
public void acceptAST(String sourcePath, CompilationUnit ast)
{
try
{
/*
* This super() call doesn't do anything, but we call it just to be nice, in case that ever changes.
*/
super.acceptAST(sourcePath, ast);
ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, ast, sourcePath);
ast.accept(visitor);
listener.processed(Paths.get(sourcePath), visitor.getJavaClassReferences());
}
catch (WindupStopException ex)
{
throw ex;
}
catch (Throwable t)
{
listener.failed(Paths.get(sourcePath), t);
}
}
};
List<List<String>> batches = createBatches(sourceFiles);
for (final List<String> batch : batches)
{
executor.submit(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setBindingsRecovery(false);
parser.setResolveBindings(true);
Map<String, String> options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
// these options seem to slightly reduce the number of times that JDT aborts on compilation errors
options.put(JavaCore.CORE_INCOMPLETE_CLASSPATH, "warning");
options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, "warning");
options.put(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, "warning");
options.put(JavaCore.CORE_CIRCULAR_CLASSPATH, "warning");
options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, "warning");
options.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION, "warning");
options.put(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, "ignore");
options.put(JavaCore.COMPILER_PB_NULL_ANNOTATION_INFERENCE_CONFLICT, "warning");
options.put(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, "warning");
options.put(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, "warning");
parser.setCompilerOptions(options);
parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]),
sourcePaths.toArray(new String[sourcePaths.size()]),
null,
true);
parser.createASTs(batch.toArray(new String[batch.size()]), encodings, bindingKeys, requestor, null);
return null;
}
});
}
executor.shutdown();
return new BatchASTFuture()
{
@Override
public boolean isDone()
{
return executor.isTerminated();
}
};
} | java | public static BatchASTFuture analyze(final BatchASTListener listener, final WildcardImportResolver importResolver,
final Set<String> libraryPaths,
final Set<String> sourcePaths, Set<Path> sourceFiles)
{
final String[] encodings = null;
final String[] bindingKeys = new String[0];
final ExecutorService executor = WindupExecutors.newFixedThreadPool(WindupExecutors.getDefaultThreadCount());
final FileASTRequestor requestor = new FileASTRequestor()
{
@Override
public void acceptAST(String sourcePath, CompilationUnit ast)
{
try
{
/*
* This super() call doesn't do anything, but we call it just to be nice, in case that ever changes.
*/
super.acceptAST(sourcePath, ast);
ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, ast, sourcePath);
ast.accept(visitor);
listener.processed(Paths.get(sourcePath), visitor.getJavaClassReferences());
}
catch (WindupStopException ex)
{
throw ex;
}
catch (Throwable t)
{
listener.failed(Paths.get(sourcePath), t);
}
}
};
List<List<String>> batches = createBatches(sourceFiles);
for (final List<String> batch : batches)
{
executor.submit(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setBindingsRecovery(false);
parser.setResolveBindings(true);
Map<String, String> options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
// these options seem to slightly reduce the number of times that JDT aborts on compilation errors
options.put(JavaCore.CORE_INCOMPLETE_CLASSPATH, "warning");
options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, "warning");
options.put(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, "warning");
options.put(JavaCore.CORE_CIRCULAR_CLASSPATH, "warning");
options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, "warning");
options.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION, "warning");
options.put(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, "ignore");
options.put(JavaCore.COMPILER_PB_NULL_ANNOTATION_INFERENCE_CONFLICT, "warning");
options.put(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, "warning");
options.put(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, "warning");
parser.setCompilerOptions(options);
parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]),
sourcePaths.toArray(new String[sourcePaths.size()]),
null,
true);
parser.createASTs(batch.toArray(new String[batch.size()]), encodings, bindingKeys, requestor, null);
return null;
}
});
}
executor.shutdown();
return new BatchASTFuture()
{
@Override
public boolean isDone()
{
return executor.isTerminated();
}
};
} | [
"public",
"static",
"BatchASTFuture",
"analyze",
"(",
"final",
"BatchASTListener",
"listener",
",",
"final",
"WildcardImportResolver",
"importResolver",
",",
"final",
"Set",
"<",
"String",
">",
"libraryPaths",
",",
"final",
"Set",
"<",
"String",
">",
"sourcePaths",
... | Process the given batch of files and pass the results back to the listener as each file is processed. | [
"Process",
"the",
"given",
"batch",
"of",
"files",
"and",
"pass",
"the",
"results",
"back",
"to",
"the",
"listener",
"as",
"each",
"file",
"is",
"processed",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/java-ast/addon/src/main/java/org/jboss/windup/ast/java/BatchASTProcessor.java#L34-L116 | train |
windup/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/condition/annotation/AnnotationTypeCondition.java | AnnotationTypeCondition.addCondition | public AnnotationTypeCondition addCondition(String element, AnnotationCondition condition)
{
this.conditions.put(element, condition);
return this;
} | java | public AnnotationTypeCondition addCondition(String element, AnnotationCondition condition)
{
this.conditions.put(element, condition);
return this;
} | [
"public",
"AnnotationTypeCondition",
"addCondition",
"(",
"String",
"element",
",",
"AnnotationCondition",
"condition",
")",
"{",
"this",
".",
"conditions",
".",
"put",
"(",
"element",
",",
"condition",
")",
";",
"return",
"this",
";",
"}"
] | Adds another condition for an element within this annotation. | [
"Adds",
"another",
"condition",
"for",
"an",
"element",
"within",
"this",
"annotation",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/condition/annotation/AnnotationTypeCondition.java#L36-L40 | train |
windup/windup | decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/ProcyonDecompiler.java | ProcyonDecompiler.decompileClassFile | @Override
public DecompilationResult decompileClassFile(Path rootDir, Path classFilePath, Path outputDir)
throws DecompilationException
{
Checks.checkDirectoryToBeRead(rootDir.toFile(), "Classes root dir");
File classFile = classFilePath.toFile();
Checks.checkFileToBeRead(classFile, "Class file");
Checks.checkDirectoryToBeFilled(outputDir.toFile(), "Output directory");
log.info("Decompiling .class '" + classFilePath + "' to '" + outputDir + "' from: '" + rootDir + "'");
String name = classFilePath.normalize().toAbsolutePath().toString().substring(rootDir.toAbsolutePath().toString().length() + 1);
final String typeName = StringUtils.removeEnd(name, ".class");// .replace('/', '.');
DecompilationResult result = new DecompilationResult();
try
{
DecompilerSettings settings = getDefaultSettings(outputDir.toFile());
this.procyonConf.setDecompilerSettings(settings); // TODO: This is horrible mess.
final ITypeLoader typeLoader = new CompositeTypeLoader(new WindupClasspathTypeLoader(rootDir.toString()), new ClasspathTypeLoader());
WindupMetadataSystem metadataSystem = new WindupMetadataSystem(typeLoader);
File outputFile = this.decompileType(settings, metadataSystem, typeName);
result.addDecompiled(Collections.singletonList(classFilePath.toString()), outputFile.getAbsolutePath());
}
catch (Throwable e)
{
DecompilationFailure failure = new DecompilationFailure("Error during decompilation of "
+ classFilePath.toString() + ":\n " + e.getMessage(), Collections.singletonList(name), e);
log.severe(failure.getMessage());
result.addFailure(failure);
}
return result;
} | java | @Override
public DecompilationResult decompileClassFile(Path rootDir, Path classFilePath, Path outputDir)
throws DecompilationException
{
Checks.checkDirectoryToBeRead(rootDir.toFile(), "Classes root dir");
File classFile = classFilePath.toFile();
Checks.checkFileToBeRead(classFile, "Class file");
Checks.checkDirectoryToBeFilled(outputDir.toFile(), "Output directory");
log.info("Decompiling .class '" + classFilePath + "' to '" + outputDir + "' from: '" + rootDir + "'");
String name = classFilePath.normalize().toAbsolutePath().toString().substring(rootDir.toAbsolutePath().toString().length() + 1);
final String typeName = StringUtils.removeEnd(name, ".class");// .replace('/', '.');
DecompilationResult result = new DecompilationResult();
try
{
DecompilerSettings settings = getDefaultSettings(outputDir.toFile());
this.procyonConf.setDecompilerSettings(settings); // TODO: This is horrible mess.
final ITypeLoader typeLoader = new CompositeTypeLoader(new WindupClasspathTypeLoader(rootDir.toString()), new ClasspathTypeLoader());
WindupMetadataSystem metadataSystem = new WindupMetadataSystem(typeLoader);
File outputFile = this.decompileType(settings, metadataSystem, typeName);
result.addDecompiled(Collections.singletonList(classFilePath.toString()), outputFile.getAbsolutePath());
}
catch (Throwable e)
{
DecompilationFailure failure = new DecompilationFailure("Error during decompilation of "
+ classFilePath.toString() + ":\n " + e.getMessage(), Collections.singletonList(name), e);
log.severe(failure.getMessage());
result.addFailure(failure);
}
return result;
} | [
"@",
"Override",
"public",
"DecompilationResult",
"decompileClassFile",
"(",
"Path",
"rootDir",
",",
"Path",
"classFilePath",
",",
"Path",
"outputDir",
")",
"throws",
"DecompilationException",
"{",
"Checks",
".",
"checkDirectoryToBeRead",
"(",
"rootDir",
".",
"toFile"... | Decompiles the given .class file and creates the specified output source file.
@param classFilePath the .class file to be decompiled.
@param outputDir The directory where decompiled .java files will be placed. | [
"Decompiles",
"the",
"given",
".",
"class",
"file",
"and",
"creates",
"the",
"specified",
"output",
"source",
"file",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/ProcyonDecompiler.java#L225-L259 | train |
windup/windup | decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/ProcyonDecompiler.java | ProcyonDecompiler.refreshMetadataCache | private void refreshMetadataCache(final Queue<WindupMetadataSystem> metadataSystemCache, final DecompilerSettings settings)
{
metadataSystemCache.clear();
for (int i = 0; i < this.getNumberOfThreads(); i++)
{
metadataSystemCache.add(new NoRetryMetadataSystem(settings.getTypeLoader()));
}
} | java | private void refreshMetadataCache(final Queue<WindupMetadataSystem> metadataSystemCache, final DecompilerSettings settings)
{
metadataSystemCache.clear();
for (int i = 0; i < this.getNumberOfThreads(); i++)
{
metadataSystemCache.add(new NoRetryMetadataSystem(settings.getTypeLoader()));
}
} | [
"private",
"void",
"refreshMetadataCache",
"(",
"final",
"Queue",
"<",
"WindupMetadataSystem",
">",
"metadataSystemCache",
",",
"final",
"DecompilerSettings",
"settings",
")",
"{",
"metadataSystemCache",
".",
"clear",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
... | The metadata cache can become huge over time. This simply flushes it periodically. | [
"The",
"metadata",
"cache",
"can",
"become",
"huge",
"over",
"time",
".",
"This",
"simply",
"flushes",
"it",
"periodically",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/ProcyonDecompiler.java#L522-L529 | train |
windup/windup | decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/ProcyonDecompiler.java | ProcyonDecompiler.decompileType | private File decompileType(final DecompilerSettings settings, final WindupMetadataSystem metadataSystem, final String typeName) throws IOException
{
log.fine("Decompiling " + typeName);
final TypeReference type;
// Hack to get around classes whose descriptors clash with primitive types.
if (typeName.length() == 1)
{
final MetadataParser parser = new MetadataParser(IMetadataResolver.EMPTY);
final TypeReference reference = parser.parseTypeDescriptor(typeName);
type = metadataSystem.resolve(reference);
}
else
type = metadataSystem.lookupType(typeName);
if (type == null)
{
log.severe("Failed to load class: " + typeName);
return null;
}
final TypeDefinition resolvedType = type.resolve();
if (resolvedType == null)
{
log.severe("Failed to resolve type: " + typeName);
return null;
}
boolean nested = resolvedType.isNested() || resolvedType.isAnonymous() || resolvedType.isSynthetic();
if (!this.procyonConf.isIncludeNested() && nested)
return null;
settings.setJavaFormattingOptions(new JavaFormattingOptions());
final FileOutputWriter writer = createFileWriter(resolvedType, settings);
final PlainTextOutput output;
output = new PlainTextOutput(writer);
output.setUnicodeOutputEnabled(settings.isUnicodeOutputEnabled());
if (settings.getLanguage() instanceof BytecodeLanguage)
output.setIndentToken(" ");
DecompilationOptions options = new DecompilationOptions();
options.setSettings(settings); // I'm missing why these two classes are split.
// --------- DECOMPILE ---------
final TypeDecompilationResults results = settings.getLanguage().decompileType(resolvedType, output, options);
writer.flush();
writer.close();
// If we're writing to a file and we were asked to include line numbers in any way,
// then reformat the file to include that line number information.
final List<LineNumberPosition> lineNumberPositions = results.getLineNumberPositions();
if (!this.procyonConf.getLineNumberOptions().isEmpty())
{
final LineNumberFormatter lineFormatter = new LineNumberFormatter(writer.getFile(), lineNumberPositions,
this.procyonConf.getLineNumberOptions());
lineFormatter.reformatFile();
}
return writer.getFile();
} | java | private File decompileType(final DecompilerSettings settings, final WindupMetadataSystem metadataSystem, final String typeName) throws IOException
{
log.fine("Decompiling " + typeName);
final TypeReference type;
// Hack to get around classes whose descriptors clash with primitive types.
if (typeName.length() == 1)
{
final MetadataParser parser = new MetadataParser(IMetadataResolver.EMPTY);
final TypeReference reference = parser.parseTypeDescriptor(typeName);
type = metadataSystem.resolve(reference);
}
else
type = metadataSystem.lookupType(typeName);
if (type == null)
{
log.severe("Failed to load class: " + typeName);
return null;
}
final TypeDefinition resolvedType = type.resolve();
if (resolvedType == null)
{
log.severe("Failed to resolve type: " + typeName);
return null;
}
boolean nested = resolvedType.isNested() || resolvedType.isAnonymous() || resolvedType.isSynthetic();
if (!this.procyonConf.isIncludeNested() && nested)
return null;
settings.setJavaFormattingOptions(new JavaFormattingOptions());
final FileOutputWriter writer = createFileWriter(resolvedType, settings);
final PlainTextOutput output;
output = new PlainTextOutput(writer);
output.setUnicodeOutputEnabled(settings.isUnicodeOutputEnabled());
if (settings.getLanguage() instanceof BytecodeLanguage)
output.setIndentToken(" ");
DecompilationOptions options = new DecompilationOptions();
options.setSettings(settings); // I'm missing why these two classes are split.
// --------- DECOMPILE ---------
final TypeDecompilationResults results = settings.getLanguage().decompileType(resolvedType, output, options);
writer.flush();
writer.close();
// If we're writing to a file and we were asked to include line numbers in any way,
// then reformat the file to include that line number information.
final List<LineNumberPosition> lineNumberPositions = results.getLineNumberPositions();
if (!this.procyonConf.getLineNumberOptions().isEmpty())
{
final LineNumberFormatter lineFormatter = new LineNumberFormatter(writer.getFile(), lineNumberPositions,
this.procyonConf.getLineNumberOptions());
lineFormatter.reformatFile();
}
return writer.getFile();
} | [
"private",
"File",
"decompileType",
"(",
"final",
"DecompilerSettings",
"settings",
",",
"final",
"WindupMetadataSystem",
"metadataSystem",
",",
"final",
"String",
"typeName",
")",
"throws",
"IOException",
"{",
"log",
".",
"fine",
"(",
"\"Decompiling \"",
"+",
"type... | Decompiles a single type.
@param metadataSystem
@param typeName
@return
@throws IOException | [
"Decompiles",
"a",
"single",
"type",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/ProcyonDecompiler.java#L598-L663 | train |
windup/windup | decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/ProcyonDecompiler.java | ProcyonDecompiler.getDefaultSettings | private DecompilerSettings getDefaultSettings(File outputDir)
{
DecompilerSettings settings = new DecompilerSettings();
procyonConf.setDecompilerSettings(settings);
settings.setOutputDirectory(outputDir.getPath());
settings.setShowSyntheticMembers(false);
settings.setForceExplicitImports(true);
if (settings.getTypeLoader() == null)
settings.setTypeLoader(new ClasspathTypeLoader());
return settings;
} | java | private DecompilerSettings getDefaultSettings(File outputDir)
{
DecompilerSettings settings = new DecompilerSettings();
procyonConf.setDecompilerSettings(settings);
settings.setOutputDirectory(outputDir.getPath());
settings.setShowSyntheticMembers(false);
settings.setForceExplicitImports(true);
if (settings.getTypeLoader() == null)
settings.setTypeLoader(new ClasspathTypeLoader());
return settings;
} | [
"private",
"DecompilerSettings",
"getDefaultSettings",
"(",
"File",
"outputDir",
")",
"{",
"DecompilerSettings",
"settings",
"=",
"new",
"DecompilerSettings",
"(",
")",
";",
"procyonConf",
".",
"setDecompilerSettings",
"(",
"settings",
")",
";",
"settings",
".",
"se... | Default settings set type loader to ClasspathTypeLoader if not set before. | [
"Default",
"settings",
"set",
"type",
"loader",
"to",
"ClasspathTypeLoader",
"if",
"not",
"set",
"before",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/ProcyonDecompiler.java#L668-L679 | train |
windup/windup | decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/ProcyonDecompiler.java | ProcyonDecompiler.loadJar | private JarFile loadJar(File archive) throws DecompilationException
{
try
{
return new JarFile(archive);
}
catch (IOException ex)
{
throw new DecompilationException("Can't load .jar: " + archive.getPath(), ex);
}
} | java | private JarFile loadJar(File archive) throws DecompilationException
{
try
{
return new JarFile(archive);
}
catch (IOException ex)
{
throw new DecompilationException("Can't load .jar: " + archive.getPath(), ex);
}
} | [
"private",
"JarFile",
"loadJar",
"(",
"File",
"archive",
")",
"throws",
"DecompilationException",
"{",
"try",
"{",
"return",
"new",
"JarFile",
"(",
"archive",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"DecompilationException",... | Opens the jar, wraps any IOException. | [
"Opens",
"the",
"jar",
"wraps",
"any",
"IOException",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/ProcyonDecompiler.java#L684-L694 | train |
windup/windup | decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/ProcyonDecompiler.java | ProcyonDecompiler.createFileWriter | private static synchronized FileOutputWriter createFileWriter(final TypeDefinition type, final DecompilerSettings settings)
throws IOException
{
final String outputDirectory = settings.getOutputDirectory();
final String fileName = type.getName() + settings.getLanguage().getFileExtension();
final String packageName = type.getPackageName();
// foo.Bar -> foo/Bar.java
final String subDir = StringUtils.defaultIfEmpty(packageName, "").replace('.', File.separatorChar);
final String outputPath = PathHelper.combine(outputDirectory, subDir, fileName);
final File outputFile = new File(outputPath);
final File parentDir = outputFile.getParentFile();
if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs())
{
throw new IllegalStateException("Could not create directory:" + parentDir);
}
if (!outputFile.exists() && !outputFile.createNewFile())
{
throw new IllegalStateException("Could not create output file: " + outputPath);
}
return new FileOutputWriter(outputFile, settings);
} | java | private static synchronized FileOutputWriter createFileWriter(final TypeDefinition type, final DecompilerSettings settings)
throws IOException
{
final String outputDirectory = settings.getOutputDirectory();
final String fileName = type.getName() + settings.getLanguage().getFileExtension();
final String packageName = type.getPackageName();
// foo.Bar -> foo/Bar.java
final String subDir = StringUtils.defaultIfEmpty(packageName, "").replace('.', File.separatorChar);
final String outputPath = PathHelper.combine(outputDirectory, subDir, fileName);
final File outputFile = new File(outputPath);
final File parentDir = outputFile.getParentFile();
if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs())
{
throw new IllegalStateException("Could not create directory:" + parentDir);
}
if (!outputFile.exists() && !outputFile.createNewFile())
{
throw new IllegalStateException("Could not create output file: " + outputPath);
}
return new FileOutputWriter(outputFile, settings);
} | [
"private",
"static",
"synchronized",
"FileOutputWriter",
"createFileWriter",
"(",
"final",
"TypeDefinition",
"type",
",",
"final",
"DecompilerSettings",
"settings",
")",
"throws",
"IOException",
"{",
"final",
"String",
"outputDirectory",
"=",
"settings",
".",
"getOutput... | Constructs the path from FQCN, validates writability, and creates a writer. | [
"Constructs",
"the",
"path",
"from",
"FQCN",
"validates",
"writability",
"and",
"creates",
"a",
"writer",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/ProcyonDecompiler.java#L699-L725 | train |
windup/windup | bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/AbstractListCommandWithoutFurnace.java | AbstractListCommandWithoutFurnace.printValuesSorted | protected static void printValuesSorted(String message, Set<String> values)
{
System.out.println();
System.out.println(message + ":");
List<String> sorted = new ArrayList<>(values);
Collections.sort(sorted);
for (String value : sorted)
{
System.out.println("\t" + value);
}
} | java | protected static void printValuesSorted(String message, Set<String> values)
{
System.out.println();
System.out.println(message + ":");
List<String> sorted = new ArrayList<>(values);
Collections.sort(sorted);
for (String value : sorted)
{
System.out.println("\t" + value);
}
} | [
"protected",
"static",
"void",
"printValuesSorted",
"(",
"String",
"message",
",",
"Set",
"<",
"String",
">",
"values",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"message",
"+",
"\":\"",
"... | Print the given values after displaying the provided message. | [
"Print",
"the",
"given",
"values",
"after",
"displaying",
"the",
"provided",
"message",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/AbstractListCommandWithoutFurnace.java#L16-L26 | train |
windup/windup | graph/api/src/main/java/org/jboss/windup/graph/GraphTypeManager.java | GraphTypeManager.getTypeValue | public static String getTypeValue(Class<? extends WindupFrame> clazz)
{
TypeValue typeValueAnnotation = clazz.getAnnotation(TypeValue.class);
if (typeValueAnnotation == null)
throw new IllegalArgumentException("Class " + clazz.getCanonicalName() + " lacks a @TypeValue annotation");
return typeValueAnnotation.value();
} | java | public static String getTypeValue(Class<? extends WindupFrame> clazz)
{
TypeValue typeValueAnnotation = clazz.getAnnotation(TypeValue.class);
if (typeValueAnnotation == null)
throw new IllegalArgumentException("Class " + clazz.getCanonicalName() + " lacks a @TypeValue annotation");
return typeValueAnnotation.value();
} | [
"public",
"static",
"String",
"getTypeValue",
"(",
"Class",
"<",
"?",
"extends",
"WindupFrame",
">",
"clazz",
")",
"{",
"TypeValue",
"typeValueAnnotation",
"=",
"clazz",
".",
"getAnnotation",
"(",
"TypeValue",
".",
"class",
")",
";",
"if",
"(",
"typeValueAnnot... | Returns the type discriminator value for given Frames model class, extracted from the @TypeValue annotation. | [
"Returns",
"the",
"type",
"discriminator",
"value",
"for",
"given",
"Frames",
"model",
"class",
"extracted",
"from",
"the"
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/graph/api/src/main/java/org/jboss/windup/graph/GraphTypeManager.java#L59-L66 | train |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/freemarker/FreeMarkerUtil.java | FreeMarkerUtil.getDefaultFreemarkerConfiguration | public static Configuration getDefaultFreemarkerConfiguration()
{
freemarker.template.Configuration configuration = new freemarker.template.Configuration(Configuration.VERSION_2_3_26);
DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);
objectWrapperBuilder.setUseAdaptersForContainers(true);
objectWrapperBuilder.setIterableSupport(true);
configuration.setObjectWrapper(objectWrapperBuilder.build());
configuration.setAPIBuiltinEnabled(true);
configuration.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());
configuration.setTemplateUpdateDelayMilliseconds(3600);
return configuration;
} | java | public static Configuration getDefaultFreemarkerConfiguration()
{
freemarker.template.Configuration configuration = new freemarker.template.Configuration(Configuration.VERSION_2_3_26);
DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);
objectWrapperBuilder.setUseAdaptersForContainers(true);
objectWrapperBuilder.setIterableSupport(true);
configuration.setObjectWrapper(objectWrapperBuilder.build());
configuration.setAPIBuiltinEnabled(true);
configuration.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());
configuration.setTemplateUpdateDelayMilliseconds(3600);
return configuration;
} | [
"public",
"static",
"Configuration",
"getDefaultFreemarkerConfiguration",
"(",
")",
"{",
"freemarker",
".",
"template",
".",
"Configuration",
"configuration",
"=",
"new",
"freemarker",
".",
"template",
".",
"Configuration",
"(",
"Configuration",
".",
"VERSION_2_3_26",
... | Gets the default configuration for Freemarker within Windup. | [
"Gets",
"the",
"default",
"configuration",
"for",
"Freemarker",
"within",
"Windup",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/freemarker/FreeMarkerUtil.java#L34-L46 | train |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/freemarker/FreeMarkerUtil.java | FreeMarkerUtil.findFreeMarkerContextVariables | public static Map<String, Object> findFreeMarkerContextVariables(Variables variables, String... varNames)
{
Map<String, Object> results = new HashMap<>();
for (String varName : varNames)
{
WindupVertexFrame payload = null;
try
{
payload = Iteration.getCurrentPayload(variables, null, varName);
}
catch (IllegalStateException | IllegalArgumentException e)
{
// oh well
}
if (payload != null)
{
results.put(varName, payload);
}
else
{
Iterable<? extends WindupVertexFrame> var = variables.findVariable(varName);
if (var != null)
{
results.put(varName, var);
}
}
}
return results;
} | java | public static Map<String, Object> findFreeMarkerContextVariables(Variables variables, String... varNames)
{
Map<String, Object> results = new HashMap<>();
for (String varName : varNames)
{
WindupVertexFrame payload = null;
try
{
payload = Iteration.getCurrentPayload(variables, null, varName);
}
catch (IllegalStateException | IllegalArgumentException e)
{
// oh well
}
if (payload != null)
{
results.put(varName, payload);
}
else
{
Iterable<? extends WindupVertexFrame> var = variables.findVariable(varName);
if (var != null)
{
results.put(varName, var);
}
}
}
return results;
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"Object",
">",
"findFreeMarkerContextVariables",
"(",
"Variables",
"variables",
",",
"String",
"...",
"varNames",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"results",
"=",
"new",
"HashMap",
"<>",
"(",
... | Finds all variables in the context with the given names, and also attaches all WindupFreeMarkerMethods from all addons into the map.
This allows external addons to extend the capabilities in the freemarker reporting system. | [
"Finds",
"all",
"variables",
"in",
"the",
"context",
"with",
"the",
"given",
"names",
"and",
"also",
"attaches",
"all",
"WindupFreeMarkerMethods",
"from",
"all",
"addons",
"into",
"the",
"map",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/freemarker/FreeMarkerUtil.java#L121-L151 | train |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/service/ClassificationService.java | ClassificationService.attachLink | public ClassificationModel attachLink(ClassificationModel classificationModel, LinkModel linkModel)
{
for (LinkModel existing : classificationModel.getLinks())
{
if (StringUtils.equals(existing.getLink(), linkModel.getLink()))
{
return classificationModel;
}
}
classificationModel.addLink(linkModel);
return classificationModel;
} | java | public ClassificationModel attachLink(ClassificationModel classificationModel, LinkModel linkModel)
{
for (LinkModel existing : classificationModel.getLinks())
{
if (StringUtils.equals(existing.getLink(), linkModel.getLink()))
{
return classificationModel;
}
}
classificationModel.addLink(linkModel);
return classificationModel;
} | [
"public",
"ClassificationModel",
"attachLink",
"(",
"ClassificationModel",
"classificationModel",
",",
"LinkModel",
"linkModel",
")",
"{",
"for",
"(",
"LinkModel",
"existing",
":",
"classificationModel",
".",
"getLinks",
"(",
")",
")",
"{",
"if",
"(",
"StringUtils",... | Attach the given link to the classification, while checking for duplicates. | [
"Attach",
"the",
"given",
"link",
"to",
"the",
"classification",
"while",
"checking",
"for",
"duplicates",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/service/ClassificationService.java#L317-L328 | train |
windup/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/provider/DiscoverMavenProjectsRuleProvider.java | DiscoverMavenProjectsRuleProvider.getMavenStubProject | private MavenProjectModel getMavenStubProject(MavenProjectService mavenProjectService, String groupId, String artifactId, String version)
{
Iterable<MavenProjectModel> mavenProjectModels = mavenProjectService.findByGroupArtifactVersion(groupId, artifactId, version);
if (!mavenProjectModels.iterator().hasNext())
{
return null;
}
for (MavenProjectModel mavenProjectModel : mavenProjectModels)
{
if (mavenProjectModel.getRootFileModel() == null)
{
// this is a stub... we can fill it in with details
return mavenProjectModel;
}
}
return null;
} | java | private MavenProjectModel getMavenStubProject(MavenProjectService mavenProjectService, String groupId, String artifactId, String version)
{
Iterable<MavenProjectModel> mavenProjectModels = mavenProjectService.findByGroupArtifactVersion(groupId, artifactId, version);
if (!mavenProjectModels.iterator().hasNext())
{
return null;
}
for (MavenProjectModel mavenProjectModel : mavenProjectModels)
{
if (mavenProjectModel.getRootFileModel() == null)
{
// this is a stub... we can fill it in with details
return mavenProjectModel;
}
}
return null;
} | [
"private",
"MavenProjectModel",
"getMavenStubProject",
"(",
"MavenProjectService",
"mavenProjectService",
",",
"String",
"groupId",
",",
"String",
"artifactId",
",",
"String",
"version",
")",
"{",
"Iterable",
"<",
"MavenProjectModel",
">",
"mavenProjectModels",
"=",
"ma... | A Maven stub is a Maven Project for which we have found information, but the project has not yet been located
within the input application. If we have found an application of the same GAV within the input app, we should
fill out this stub instead of creating a new one. | [
"A",
"Maven",
"stub",
"is",
"a",
"Maven",
"Project",
"for",
"which",
"we",
"have",
"found",
"information",
"but",
"the",
"project",
"has",
"not",
"yet",
"been",
"located",
"within",
"the",
"input",
"application",
".",
"If",
"we",
"have",
"found",
"an",
"... | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/provider/DiscoverMavenProjectsRuleProvider.java#L401-L417 | train |
windup/windup | utils/src/main/java/org/jboss/windup/util/PathUtil.java | PathUtil.getRootFolderForSource | public static Path getRootFolderForSource(Path sourceFilePath, String packageName)
{
if (packageName == null || packageName.trim().isEmpty())
{
return sourceFilePath.getParent();
}
String[] packageNameComponents = packageName.split("\\.");
Path currentPath = sourceFilePath.getParent();
for (int i = packageNameComponents.length; i > 0; i--)
{
String packageComponent = packageNameComponents[i - 1];
if (!StringUtils.equals(packageComponent, currentPath.getFileName().toString()))
{
return null;
}
currentPath = currentPath.getParent();
}
return currentPath;
} | java | public static Path getRootFolderForSource(Path sourceFilePath, String packageName)
{
if (packageName == null || packageName.trim().isEmpty())
{
return sourceFilePath.getParent();
}
String[] packageNameComponents = packageName.split("\\.");
Path currentPath = sourceFilePath.getParent();
for (int i = packageNameComponents.length; i > 0; i--)
{
String packageComponent = packageNameComponents[i - 1];
if (!StringUtils.equals(packageComponent, currentPath.getFileName().toString()))
{
return null;
}
currentPath = currentPath.getParent();
}
return currentPath;
} | [
"public",
"static",
"Path",
"getRootFolderForSource",
"(",
"Path",
"sourceFilePath",
",",
"String",
"packageName",
")",
"{",
"if",
"(",
"packageName",
"==",
"null",
"||",
"packageName",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"... | Returns the root path for this source file, based upon the package name.
For example, if path is "/project/src/main/java/org/example/Foo.java" and the package is "org.example", then this
should return "/project/src/main/java".
Returns null if the folder structure does not match the package name. | [
"Returns",
"the",
"root",
"path",
"for",
"this",
"source",
"file",
"based",
"upon",
"the",
"package",
"name",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/PathUtil.java#L213-L231 | train |
windup/windup | utils/src/main/java/org/jboss/windup/util/PathUtil.java | PathUtil.isInSubDirectory | public static boolean isInSubDirectory(File dir, File file)
{
if (file == null)
return false;
if (file.equals(dir))
return true;
return isInSubDirectory(dir, file.getParentFile());
} | java | public static boolean isInSubDirectory(File dir, File file)
{
if (file == null)
return false;
if (file.equals(dir))
return true;
return isInSubDirectory(dir, file.getParentFile());
} | [
"public",
"static",
"boolean",
"isInSubDirectory",
"(",
"File",
"dir",
",",
"File",
"file",
")",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"return",
"false",
";",
"if",
"(",
"file",
".",
"equals",
"(",
"dir",
")",
")",
"return",
"true",
";",
"return... | Returns true if "file" is a subfile or subdirectory of "dir".
For example with the directory /path/to/a, the following return values would occur:
/path/to/a/foo.txt - true /path/to/a/bar/zoo/boo/team.txt - true /path/to/b/foo.txt - false | [
"Returns",
"true",
"if",
"file",
"is",
"a",
"subfile",
"or",
"subdirectory",
"of",
"dir",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/PathUtil.java#L241-L250 | train |
windup/windup | utils/src/main/java/org/jboss/windup/util/PathUtil.java | PathUtil.createDirectory | public static void createDirectory(Path dir, String dirDesc)
{
try
{
Files.createDirectories(dir);
}
catch (IOException ex)
{
throw new WindupException("Error creating " + dirDesc + " folder: " + dir.toString() + " due to: " + ex.getMessage(), ex);
}
} | java | public static void createDirectory(Path dir, String dirDesc)
{
try
{
Files.createDirectories(dir);
}
catch (IOException ex)
{
throw new WindupException("Error creating " + dirDesc + " folder: " + dir.toString() + " due to: " + ex.getMessage(), ex);
}
} | [
"public",
"static",
"void",
"createDirectory",
"(",
"Path",
"dir",
",",
"String",
"dirDesc",
")",
"{",
"try",
"{",
"Files",
".",
"createDirectories",
"(",
"dir",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"WindupException",... | Creates the given directory. Fails if it already exists. | [
"Creates",
"the",
"given",
"directory",
".",
"Fails",
"if",
"it",
"already",
"exists",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/PathUtil.java#L264-L274 | train |
windup/windup | java-ast/addon/src/main/java/org/jboss/windup/ast/java/ReferenceResolvingVisitor.java | ReferenceResolvingVisitor.processType | private ClassReference processType(Type type, TypeReferenceLocation typeReferenceLocation, int lineNumber, int columnNumber, int length,
String line)
{
if (type == null)
return null;
ITypeBinding resolveBinding = type.resolveBinding();
if (resolveBinding == null)
{
ResolveClassnameResult resolvedResult = resolveClassname(type.toString());
ResolutionStatus status = resolvedResult.found ? ResolutionStatus.RECOVERED : ResolutionStatus.UNRESOLVED;
PackageAndClassName packageAndClassName = PackageAndClassName.parseFromQualifiedName(resolvedResult.result);
return processTypeAsString(resolvedResult.result, packageAndClassName.packageName, packageAndClassName.className, status,
typeReferenceLocation, lineNumber,
columnNumber, length, line);
}
else
{
return processTypeBinding(type.resolveBinding(), ResolutionStatus.RESOLVED, typeReferenceLocation, lineNumber,
columnNumber, length, line);
}
} | java | private ClassReference processType(Type type, TypeReferenceLocation typeReferenceLocation, int lineNumber, int columnNumber, int length,
String line)
{
if (type == null)
return null;
ITypeBinding resolveBinding = type.resolveBinding();
if (resolveBinding == null)
{
ResolveClassnameResult resolvedResult = resolveClassname(type.toString());
ResolutionStatus status = resolvedResult.found ? ResolutionStatus.RECOVERED : ResolutionStatus.UNRESOLVED;
PackageAndClassName packageAndClassName = PackageAndClassName.parseFromQualifiedName(resolvedResult.result);
return processTypeAsString(resolvedResult.result, packageAndClassName.packageName, packageAndClassName.className, status,
typeReferenceLocation, lineNumber,
columnNumber, length, line);
}
else
{
return processTypeBinding(type.resolveBinding(), ResolutionStatus.RESOLVED, typeReferenceLocation, lineNumber,
columnNumber, length, line);
}
} | [
"private",
"ClassReference",
"processType",
"(",
"Type",
"type",
",",
"TypeReferenceLocation",
"typeReferenceLocation",
",",
"int",
"lineNumber",
",",
"int",
"columnNumber",
",",
"int",
"length",
",",
"String",
"line",
")",
"{",
"if",
"(",
"type",
"==",
"null",
... | The method determines if the type can be resolved and if not, will try to guess the qualified name using the information from the imports. | [
"The",
"method",
"determines",
"if",
"the",
"type",
"can",
"be",
"resolved",
"and",
"if",
"not",
"will",
"try",
"to",
"guess",
"the",
"qualified",
"name",
"using",
"the",
"information",
"from",
"the",
"imports",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/java-ast/addon/src/main/java/org/jboss/windup/ast/java/ReferenceResolvingVisitor.java#L299-L322 | train |
windup/windup | java-ast/addon/src/main/java/org/jboss/windup/ast/java/ReferenceResolvingVisitor.java | ReferenceResolvingVisitor.addAnnotationValues | private void addAnnotationValues(ClassReference annotatedReference, AnnotationClassReference typeRef, Annotation node)
{
Map<String, AnnotationValue> annotationValueMap = new HashMap<>();
if (node instanceof SingleMemberAnnotation)
{
SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) node;
AnnotationValue value = getAnnotationValueForExpression(annotatedReference, singleMemberAnnotation.getValue());
annotationValueMap.put("value", value);
}
else if (node instanceof NormalAnnotation)
{
@SuppressWarnings("unchecked")
List<MemberValuePair> annotationValues = ((NormalAnnotation) node).values();
for (MemberValuePair annotationValue : annotationValues)
{
String key = annotationValue.getName().toString();
Expression expression = annotationValue.getValue();
AnnotationValue value = getAnnotationValueForExpression(annotatedReference, expression);
annotationValueMap.put(key, value);
}
}
typeRef.setAnnotationValues(annotationValueMap);
} | java | private void addAnnotationValues(ClassReference annotatedReference, AnnotationClassReference typeRef, Annotation node)
{
Map<String, AnnotationValue> annotationValueMap = new HashMap<>();
if (node instanceof SingleMemberAnnotation)
{
SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) node;
AnnotationValue value = getAnnotationValueForExpression(annotatedReference, singleMemberAnnotation.getValue());
annotationValueMap.put("value", value);
}
else if (node instanceof NormalAnnotation)
{
@SuppressWarnings("unchecked")
List<MemberValuePair> annotationValues = ((NormalAnnotation) node).values();
for (MemberValuePair annotationValue : annotationValues)
{
String key = annotationValue.getName().toString();
Expression expression = annotationValue.getValue();
AnnotationValue value = getAnnotationValueForExpression(annotatedReference, expression);
annotationValueMap.put(key, value);
}
}
typeRef.setAnnotationValues(annotationValueMap);
} | [
"private",
"void",
"addAnnotationValues",
"(",
"ClassReference",
"annotatedReference",
",",
"AnnotationClassReference",
"typeRef",
",",
"Annotation",
"node",
")",
"{",
"Map",
"<",
"String",
",",
"AnnotationValue",
">",
"annotationValueMap",
"=",
"new",
"HashMap",
"<>"... | Adds parameters contained in the annotation into the annotation type reference
@param typeRef
@param node | [
"Adds",
"parameters",
"contained",
"in",
"the",
"annotation",
"into",
"the",
"annotation",
"type",
"reference"
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/java-ast/addon/src/main/java/org/jboss/windup/ast/java/ReferenceResolvingVisitor.java#L668-L690 | train |
windup/windup | java-ast/addon/src/main/java/org/jboss/windup/ast/java/ReferenceResolvingVisitor.java | ReferenceResolvingVisitor.visit | @Override
public boolean visit(VariableDeclarationStatement node)
{
for (int i = 0; i < node.fragments().size(); ++i)
{
String nodeType = node.getType().toString();
VariableDeclarationFragment frag = (VariableDeclarationFragment) node.fragments().get(i);
state.getNames().add(frag.getName().getIdentifier());
state.getNameInstance().put(frag.getName().toString(), nodeType.toString());
}
processType(node.getType(), TypeReferenceLocation.VARIABLE_DECLARATION,
compilationUnit.getLineNumber(node.getStartPosition()),
compilationUnit.getColumnNumber(node.getStartPosition()), node.getLength(), node.toString());
return super.visit(node);
} | java | @Override
public boolean visit(VariableDeclarationStatement node)
{
for (int i = 0; i < node.fragments().size(); ++i)
{
String nodeType = node.getType().toString();
VariableDeclarationFragment frag = (VariableDeclarationFragment) node.fragments().get(i);
state.getNames().add(frag.getName().getIdentifier());
state.getNameInstance().put(frag.getName().toString(), nodeType.toString());
}
processType(node.getType(), TypeReferenceLocation.VARIABLE_DECLARATION,
compilationUnit.getLineNumber(node.getStartPosition()),
compilationUnit.getColumnNumber(node.getStartPosition()), node.getLength(), node.toString());
return super.visit(node);
} | [
"@",
"Override",
"public",
"boolean",
"visit",
"(",
"VariableDeclarationStatement",
"node",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"node",
".",
"fragments",
"(",
")",
".",
"size",
"(",
")",
";",
"++",
"i",
")",
"{",
"String",
"n... | Declaration of the variable within a block | [
"Declaration",
"of",
"the",
"variable",
"within",
"a",
"block"
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/java-ast/addon/src/main/java/org/jboss/windup/ast/java/ReferenceResolvingVisitor.java#L925-L940 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/query/Query.java | Query.excludingType | @Override
public QueryBuilderFind excludingType(final Class<? extends WindupVertexFrame> type)
{
pipelineCriteria.add(new QueryGremlinCriterion()
{
@Override
public void query(GraphRewrite event, GraphTraversal<?, Vertex> pipeline)
{
pipeline.filter(it -> !GraphTypeManager.hasType(type, it.get()));
}
});
return this;
} | java | @Override
public QueryBuilderFind excludingType(final Class<? extends WindupVertexFrame> type)
{
pipelineCriteria.add(new QueryGremlinCriterion()
{
@Override
public void query(GraphRewrite event, GraphTraversal<?, Vertex> pipeline)
{
pipeline.filter(it -> !GraphTypeManager.hasType(type, it.get()));
}
});
return this;
} | [
"@",
"Override",
"public",
"QueryBuilderFind",
"excludingType",
"(",
"final",
"Class",
"<",
"?",
"extends",
"WindupVertexFrame",
">",
"type",
")",
"{",
"pipelineCriteria",
".",
"add",
"(",
"new",
"QueryGremlinCriterion",
"(",
")",
"{",
"@",
"Override",
"public",... | Excludes Vertices that are of the provided type. | [
"Excludes",
"Vertices",
"that",
"are",
"of",
"the",
"provided",
"type",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/query/Query.java#L71-L83 | train |
windup/windup | reporting/impl/src/main/java/org/jboss/windup/reporting/rules/rendering/CssJsResourceRenderingRuleProvider.java | CssJsResourceRenderingRuleProvider.addonDependsOnReporting | private boolean addonDependsOnReporting(Addon addon)
{
for (AddonDependency dep : addon.getDependencies())
{
if (dep.getDependency().equals(this.addon))
{
return true;
}
boolean subDep = addonDependsOnReporting(dep.getDependency());
if (subDep)
{
return true;
}
}
return false;
} | java | private boolean addonDependsOnReporting(Addon addon)
{
for (AddonDependency dep : addon.getDependencies())
{
if (dep.getDependency().equals(this.addon))
{
return true;
}
boolean subDep = addonDependsOnReporting(dep.getDependency());
if (subDep)
{
return true;
}
}
return false;
} | [
"private",
"boolean",
"addonDependsOnReporting",
"(",
"Addon",
"addon",
")",
"{",
"for",
"(",
"AddonDependency",
"dep",
":",
"addon",
".",
"getDependencies",
"(",
")",
")",
"{",
"if",
"(",
"dep",
".",
"getDependency",
"(",
")",
".",
"equals",
"(",
"this",
... | Returns true if the addon depends on reporting. | [
"Returns",
"true",
"if",
"the",
"addon",
"depends",
"on",
"reporting",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/impl/src/main/java/org/jboss/windup/reporting/rules/rendering/CssJsResourceRenderingRuleProvider.java#L163-L178 | train |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/service/TagGraphService.java | TagGraphService.getSingleParent | public static TagModel getSingleParent(TagModel tag)
{
final Iterator<TagModel> parents = tag.getDesignatedByTags().iterator();
if (!parents.hasNext())
throw new WindupException("Tag is not designated by any tags: " + tag);
final TagModel maybeOnlyParent = parents.next();
if (parents.hasNext()) {
StringBuilder sb = new StringBuilder();
tag.getDesignatedByTags().iterator().forEachRemaining(x -> sb.append(x).append(", "));
throw new WindupException(String.format("Tag %s is designated by multiple tags: %s", tag, sb.toString()));
}
return maybeOnlyParent;
} | java | public static TagModel getSingleParent(TagModel tag)
{
final Iterator<TagModel> parents = tag.getDesignatedByTags().iterator();
if (!parents.hasNext())
throw new WindupException("Tag is not designated by any tags: " + tag);
final TagModel maybeOnlyParent = parents.next();
if (parents.hasNext()) {
StringBuilder sb = new StringBuilder();
tag.getDesignatedByTags().iterator().forEachRemaining(x -> sb.append(x).append(", "));
throw new WindupException(String.format("Tag %s is designated by multiple tags: %s", tag, sb.toString()));
}
return maybeOnlyParent;
} | [
"public",
"static",
"TagModel",
"getSingleParent",
"(",
"TagModel",
"tag",
")",
"{",
"final",
"Iterator",
"<",
"TagModel",
">",
"parents",
"=",
"tag",
".",
"getDesignatedByTags",
"(",
")",
".",
"iterator",
"(",
")",
";",
"if",
"(",
"!",
"parents",
".",
"... | Returns a single parent of the given tag. If there are multiple parents, throws a WindupException. | [
"Returns",
"a",
"single",
"parent",
"of",
"the",
"given",
"tag",
".",
"If",
"there",
"are",
"multiple",
"parents",
"throws",
"a",
"WindupException",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/service/TagGraphService.java#L168-L183 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/query/QueryTypeCriterion.java | QueryTypeCriterion.addPipeFor | public static GraphTraversal<Vertex, Vertex> addPipeFor(GraphTraversal<Vertex, Vertex> pipeline,
Class<? extends WindupVertexFrame> clazz)
{
pipeline.has(WindupVertexFrame.TYPE_PROP, GraphTypeManager.getTypeValue(clazz));
return pipeline;
} | java | public static GraphTraversal<Vertex, Vertex> addPipeFor(GraphTraversal<Vertex, Vertex> pipeline,
Class<? extends WindupVertexFrame> clazz)
{
pipeline.has(WindupVertexFrame.TYPE_PROP, GraphTypeManager.getTypeValue(clazz));
return pipeline;
} | [
"public",
"static",
"GraphTraversal",
"<",
"Vertex",
",",
"Vertex",
">",
"addPipeFor",
"(",
"GraphTraversal",
"<",
"Vertex",
",",
"Vertex",
">",
"pipeline",
",",
"Class",
"<",
"?",
"extends",
"WindupVertexFrame",
">",
"clazz",
")",
"{",
"pipeline",
".",
"has... | Adds a criterion to given pipeline which filters out vertices representing given WindupVertexFrame. | [
"Adds",
"a",
"criterion",
"to",
"given",
"pipeline",
"which",
"filters",
"out",
"vertices",
"representing",
"given",
"WindupVertexFrame",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/query/QueryTypeCriterion.java#L35-L40 | train |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/TagUtil.java | TagUtil.strictCheckMatchingTags | public static boolean strictCheckMatchingTags(Collection<String> tags, Set<String> includeTags, Set<String> excludeTags)
{
boolean includeTagsEnabled = !includeTags.isEmpty();
for (String tag : tags)
{
boolean isIncluded = includeTags.contains(tag);
boolean isExcluded = excludeTags.contains(tag);
if ((includeTagsEnabled && isIncluded) || (!includeTagsEnabled && !isExcluded))
{
return true;
}
}
return false;
} | java | public static boolean strictCheckMatchingTags(Collection<String> tags, Set<String> includeTags, Set<String> excludeTags)
{
boolean includeTagsEnabled = !includeTags.isEmpty();
for (String tag : tags)
{
boolean isIncluded = includeTags.contains(tag);
boolean isExcluded = excludeTags.contains(tag);
if ((includeTagsEnabled && isIncluded) || (!includeTagsEnabled && !isExcluded))
{
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"strictCheckMatchingTags",
"(",
"Collection",
"<",
"String",
">",
"tags",
",",
"Set",
"<",
"String",
">",
"includeTags",
",",
"Set",
"<",
"String",
">",
"excludeTags",
")",
"{",
"boolean",
"includeTagsEnabled",
"=",
"!",
"include... | Returns true if
- includeTags is not empty and tag is in includeTags
- includeTags is empty and tag is not in excludeTags
@param tags Hint tags
@param includeTags Include tags
@param excludeTags Exclude tags
@return has tag match | [
"Returns",
"true",
"if",
"-",
"includeTags",
"is",
"not",
"empty",
"and",
"tag",
"is",
"in",
"includeTags",
"-",
"includeTags",
"is",
"empty",
"and",
"tag",
"is",
"not",
"in",
"excludeTags"
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/TagUtil.java#L35-L51 | train |
windup/windup | bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/windup/RunWindupCommand.java | RunWindupCommand.expandMultiAppInputDirs | private static List<Path> expandMultiAppInputDirs(List<Path> input)
{
List<Path> expanded = new LinkedList<>();
for (Path path : input)
{
if (Files.isRegularFile(path))
{
expanded.add(path);
continue;
}
if (!Files.isDirectory(path))
{
String pathString = (path == null) ? "" : path.toString();
log.warning("Neither a file or directory found in input: " + pathString);
continue;
}
try
{
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path))
{
for (Path subpath : directoryStream)
{
if (isJavaArchive(subpath))
{
expanded.add(subpath);
}
}
}
}
catch (IOException e)
{
throw new WindupException("Failed to read directory contents of: " + path);
}
}
return expanded;
} | java | private static List<Path> expandMultiAppInputDirs(List<Path> input)
{
List<Path> expanded = new LinkedList<>();
for (Path path : input)
{
if (Files.isRegularFile(path))
{
expanded.add(path);
continue;
}
if (!Files.isDirectory(path))
{
String pathString = (path == null) ? "" : path.toString();
log.warning("Neither a file or directory found in input: " + pathString);
continue;
}
try
{
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path))
{
for (Path subpath : directoryStream)
{
if (isJavaArchive(subpath))
{
expanded.add(subpath);
}
}
}
}
catch (IOException e)
{
throw new WindupException("Failed to read directory contents of: " + path);
}
}
return expanded;
} | [
"private",
"static",
"List",
"<",
"Path",
">",
"expandMultiAppInputDirs",
"(",
"List",
"<",
"Path",
">",
"input",
")",
"{",
"List",
"<",
"Path",
">",
"expanded",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"for",
"(",
"Path",
"path",
":",
"input",
... | Expands the directories from the given list and and returns a list of subfiles.
Files from the original list are kept as is. | [
"Expands",
"the",
"directories",
"from",
"the",
"given",
"list",
"and",
"and",
"returns",
"a",
"list",
"of",
"subfiles",
".",
"Files",
"from",
"the",
"original",
"list",
"are",
"kept",
"as",
"is",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/windup/RunWindupCommand.java#L485-L522 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/RuleUtils.java | RuleUtils.ruleToRuleContentsString | public static String ruleToRuleContentsString(Rule originalRule, int indentLevel)
{
if (originalRule instanceof Context && ((Context) originalRule).containsKey(RuleMetadataType.RULE_XML))
{
return (String) ((Context) originalRule).get(RuleMetadataType.RULE_XML);
}
if (!(originalRule instanceof RuleBuilder))
{
return wrap(originalRule.toString(), MAX_WIDTH, indentLevel);
}
final RuleBuilder rule = (RuleBuilder) originalRule;
StringBuilder result = new StringBuilder();
if (indentLevel == 0)
result.append("addRule()");
for (Condition condition : rule.getConditions())
{
String conditionToString = conditionToString(condition, indentLevel + 1);
if (!conditionToString.isEmpty())
{
result.append(System.lineSeparator());
insertPadding(result, indentLevel + 1);
result.append(".when(").append(wrap(conditionToString, MAX_WIDTH, indentLevel + 2)).append(")");
}
}
for (Operation operation : rule.getOperations())
{
String operationToString = operationToString(operation, indentLevel + 1);
if (!operationToString.isEmpty())
{
result.append(System.lineSeparator());
insertPadding(result, indentLevel + 1);
result.append(".perform(").append(wrap(operationToString, MAX_WIDTH, indentLevel + 2)).append(")");
}
}
if (rule.getId() != null && !rule.getId().isEmpty())
{
result.append(System.lineSeparator());
insertPadding(result, indentLevel);
result.append("withId(\"").append(rule.getId()).append("\")");
}
if (rule.priority() != 0)
{
result.append(System.lineSeparator());
insertPadding(result, indentLevel);
result.append(".withPriority(").append(rule.priority()).append(")");
}
return result.toString();
} | java | public static String ruleToRuleContentsString(Rule originalRule, int indentLevel)
{
if (originalRule instanceof Context && ((Context) originalRule).containsKey(RuleMetadataType.RULE_XML))
{
return (String) ((Context) originalRule).get(RuleMetadataType.RULE_XML);
}
if (!(originalRule instanceof RuleBuilder))
{
return wrap(originalRule.toString(), MAX_WIDTH, indentLevel);
}
final RuleBuilder rule = (RuleBuilder) originalRule;
StringBuilder result = new StringBuilder();
if (indentLevel == 0)
result.append("addRule()");
for (Condition condition : rule.getConditions())
{
String conditionToString = conditionToString(condition, indentLevel + 1);
if (!conditionToString.isEmpty())
{
result.append(System.lineSeparator());
insertPadding(result, indentLevel + 1);
result.append(".when(").append(wrap(conditionToString, MAX_WIDTH, indentLevel + 2)).append(")");
}
}
for (Operation operation : rule.getOperations())
{
String operationToString = operationToString(operation, indentLevel + 1);
if (!operationToString.isEmpty())
{
result.append(System.lineSeparator());
insertPadding(result, indentLevel + 1);
result.append(".perform(").append(wrap(operationToString, MAX_WIDTH, indentLevel + 2)).append(")");
}
}
if (rule.getId() != null && !rule.getId().isEmpty())
{
result.append(System.lineSeparator());
insertPadding(result, indentLevel);
result.append("withId(\"").append(rule.getId()).append("\")");
}
if (rule.priority() != 0)
{
result.append(System.lineSeparator());
insertPadding(result, indentLevel);
result.append(".withPriority(").append(rule.priority()).append(")");
}
return result.toString();
} | [
"public",
"static",
"String",
"ruleToRuleContentsString",
"(",
"Rule",
"originalRule",
",",
"int",
"indentLevel",
")",
"{",
"if",
"(",
"originalRule",
"instanceof",
"Context",
"&&",
"(",
"(",
"Context",
")",
"originalRule",
")",
".",
"containsKey",
"(",
"RuleMet... | Attempts to create a human-readable String representation of the provided rule. | [
"Attempts",
"to",
"create",
"a",
"human",
"-",
"readable",
"String",
"representation",
"of",
"the",
"provided",
"rule",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/RuleUtils.java#L54-L106 | train |
windup/windup | graph/impl/src/main/java/org/jboss/windup/graph/SetInPropertiesHandler.java | SetInPropertiesHandler.processMethod | @Override
public <E> DynamicType.Builder<E> processMethod(final DynamicType.Builder<E> builder, final Method method, final Annotation annotation)
{
String methodName = method.getName();
if (ReflectionUtility.isGetMethod(method))
return createInterceptor(builder, method);
else if (ReflectionUtility.isSetMethod(method))
return createInterceptor(builder, method);
else if (methodName.startsWith("addAll"))
return createInterceptor(builder, method);
else if (methodName.startsWith("add"))
return createInterceptor(builder, method);
else
throw new WindupException("Only get*, set*, add*, and addAll* method names are supported for @"
+ SetInProperties.class.getSimpleName() + ", found at: " + method.getName());
} | java | @Override
public <E> DynamicType.Builder<E> processMethod(final DynamicType.Builder<E> builder, final Method method, final Annotation annotation)
{
String methodName = method.getName();
if (ReflectionUtility.isGetMethod(method))
return createInterceptor(builder, method);
else if (ReflectionUtility.isSetMethod(method))
return createInterceptor(builder, method);
else if (methodName.startsWith("addAll"))
return createInterceptor(builder, method);
else if (methodName.startsWith("add"))
return createInterceptor(builder, method);
else
throw new WindupException("Only get*, set*, add*, and addAll* method names are supported for @"
+ SetInProperties.class.getSimpleName() + ", found at: " + method.getName());
} | [
"@",
"Override",
"public",
"<",
"E",
">",
"DynamicType",
".",
"Builder",
"<",
"E",
">",
"processMethod",
"(",
"final",
"DynamicType",
".",
"Builder",
"<",
"E",
">",
"builder",
",",
"final",
"Method",
"method",
",",
"final",
"Annotation",
"annotation",
")",... | The handling method. | [
"The",
"handling",
"method",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/graph/impl/src/main/java/org/jboss/windup/graph/SetInPropertiesHandler.java#L46-L61 | train |
windup/windup | rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/service/JNDIResourceService.java | JNDIResourceService.associateTypeJndiResource | public void associateTypeJndiResource(JNDIResourceModel resource, String type)
{
if (type == null || resource == null)
{
return;
}
if (StringUtils.equals(type, "javax.sql.DataSource") && !(resource instanceof DataSourceModel))
{
DataSourceModel ds = GraphService.addTypeToModel(this.getGraphContext(), resource, DataSourceModel.class);
}
else if (StringUtils.equals(type, "javax.jms.Queue") && !(resource instanceof JmsDestinationModel))
{
JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);
jms.setDestinationType(JmsDestinationType.QUEUE);
}
else if (StringUtils.equals(type, "javax.jms.QueueConnectionFactory") && !(resource instanceof JmsConnectionFactoryModel))
{
JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);
jms.setConnectionFactoryType(JmsDestinationType.QUEUE);
}
else if (StringUtils.equals(type, "javax.jms.Topic") && !(resource instanceof JmsDestinationModel))
{
JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);
jms.setDestinationType(JmsDestinationType.TOPIC);
}
else if (StringUtils.equals(type, "javax.jms.TopicConnectionFactory") && !(resource instanceof JmsConnectionFactoryModel))
{
JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);
jms.setConnectionFactoryType(JmsDestinationType.TOPIC);
}
} | java | public void associateTypeJndiResource(JNDIResourceModel resource, String type)
{
if (type == null || resource == null)
{
return;
}
if (StringUtils.equals(type, "javax.sql.DataSource") && !(resource instanceof DataSourceModel))
{
DataSourceModel ds = GraphService.addTypeToModel(this.getGraphContext(), resource, DataSourceModel.class);
}
else if (StringUtils.equals(type, "javax.jms.Queue") && !(resource instanceof JmsDestinationModel))
{
JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);
jms.setDestinationType(JmsDestinationType.QUEUE);
}
else if (StringUtils.equals(type, "javax.jms.QueueConnectionFactory") && !(resource instanceof JmsConnectionFactoryModel))
{
JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);
jms.setConnectionFactoryType(JmsDestinationType.QUEUE);
}
else if (StringUtils.equals(type, "javax.jms.Topic") && !(resource instanceof JmsDestinationModel))
{
JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);
jms.setDestinationType(JmsDestinationType.TOPIC);
}
else if (StringUtils.equals(type, "javax.jms.TopicConnectionFactory") && !(resource instanceof JmsConnectionFactoryModel))
{
JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);
jms.setConnectionFactoryType(JmsDestinationType.TOPIC);
}
} | [
"public",
"void",
"associateTypeJndiResource",
"(",
"JNDIResourceModel",
"resource",
",",
"String",
"type",
")",
"{",
"if",
"(",
"type",
"==",
"null",
"||",
"resource",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"StringUtils",
".",
"equals",
"(... | Associate a type with the given resource model. | [
"Associate",
"a",
"type",
"with",
"the",
"given",
"resource",
"model",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/service/JNDIResourceService.java#L54-L85 | train |
windup/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/FeatureBasedApiDependenciesDeducer.java | FeatureBasedApiDependenciesDeducer.addDeploymentTypeBasedDependencies | private boolean addDeploymentTypeBasedDependencies(ProjectModel projectModel, Pom modulePom)
{
if (projectModel.getProjectType() == null)
return true;
switch (projectModel.getProjectType()){
case "ear":
break;
case "war":
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_SERVLET_31));
break;
case "ejb":
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_32));
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_CDI));
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JAVAX_ANN));
break;
case "ejb-client":
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_CLIENT));
break;
}
return false;
} | java | private boolean addDeploymentTypeBasedDependencies(ProjectModel projectModel, Pom modulePom)
{
if (projectModel.getProjectType() == null)
return true;
switch (projectModel.getProjectType()){
case "ear":
break;
case "war":
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_SERVLET_31));
break;
case "ejb":
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_32));
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_CDI));
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JAVAX_ANN));
break;
case "ejb-client":
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_CLIENT));
break;
}
return false;
} | [
"private",
"boolean",
"addDeploymentTypeBasedDependencies",
"(",
"ProjectModel",
"projectModel",
",",
"Pom",
"modulePom",
")",
"{",
"if",
"(",
"projectModel",
".",
"getProjectType",
"(",
")",
"==",
"null",
")",
"return",
"true",
";",
"switch",
"(",
"projectModel",... | Adds the dependencies typical for particular deployment types.
This is not accurate and doesn't cover the real needs of the project.
Basically it's just to have "something" for the initial implementation. | [
"Adds",
"the",
"dependencies",
"typical",
"for",
"particular",
"deployment",
"types",
".",
"This",
"is",
"not",
"accurate",
"and",
"doesn",
"t",
"cover",
"the",
"real",
"needs",
"of",
"the",
"project",
".",
"Basically",
"it",
"s",
"just",
"to",
"have",
"so... | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/FeatureBasedApiDependenciesDeducer.java#L52-L72 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/tags/TagService.java | TagService.readTags | public void readTags(InputStream tagsXML)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
try
{
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(tagsXML, new TagsSaxHandler(this));
}
catch (ParserConfigurationException | SAXException | IOException ex)
{
throw new RuntimeException("Failed parsing the tags definition: " + ex.getMessage(), ex);
}
} | java | public void readTags(InputStream tagsXML)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
try
{
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(tagsXML, new TagsSaxHandler(this));
}
catch (ParserConfigurationException | SAXException | IOException ex)
{
throw new RuntimeException("Failed parsing the tags definition: " + ex.getMessage(), ex);
}
} | [
"public",
"void",
"readTags",
"(",
"InputStream",
"tagsXML",
")",
"{",
"SAXParserFactory",
"factory",
"=",
"SAXParserFactory",
".",
"newInstance",
"(",
")",
";",
"try",
"{",
"SAXParser",
"saxParser",
"=",
"factory",
".",
"newSAXParser",
"(",
")",
";",
"saxPars... | Read the tag structure from the provided stream. | [
"Read",
"the",
"tag",
"structure",
"from",
"the",
"provided",
"stream",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/tags/TagService.java#L37-L49 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/tags/TagService.java | TagService.getPrimeTags | public List<Tag> getPrimeTags()
{
return this.definedTags.values().stream()
.filter(Tag::isPrime)
.collect(Collectors.toList());
} | java | public List<Tag> getPrimeTags()
{
return this.definedTags.values().stream()
.filter(Tag::isPrime)
.collect(Collectors.toList());
} | [
"public",
"List",
"<",
"Tag",
">",
"getPrimeTags",
"(",
")",
"{",
"return",
"this",
".",
"definedTags",
".",
"values",
"(",
")",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"Tag",
"::",
"isPrime",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList... | Gets all tags that are "prime" tags. | [
"Gets",
"all",
"tags",
"that",
"are",
"prime",
"tags",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/tags/TagService.java#L54-L59 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/tags/TagService.java | TagService.getRootTags | public List<Tag> getRootTags()
{
return this.definedTags.values().stream()
.filter(Tag::isRoot)
.collect(Collectors.toList());
} | java | public List<Tag> getRootTags()
{
return this.definedTags.values().stream()
.filter(Tag::isRoot)
.collect(Collectors.toList());
} | [
"public",
"List",
"<",
"Tag",
">",
"getRootTags",
"(",
")",
"{",
"return",
"this",
".",
"definedTags",
".",
"values",
"(",
")",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"Tag",
"::",
"isRoot",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",... | Returns the tags that were root in the definition files. These serve as entry point shortcuts when browsing the graph. We could reduce this to
just fewer as the root tags may be connected through parents="...". | [
"Returns",
"the",
"tags",
"that",
"were",
"root",
"in",
"the",
"definition",
"files",
".",
"These",
"serve",
"as",
"entry",
"point",
"shortcuts",
"when",
"browsing",
"the",
"graph",
".",
"We",
"could",
"reduce",
"this",
"to",
"just",
"fewer",
"as",
"the",
... | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/tags/TagService.java#L65-L70 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/tags/TagService.java | TagService.getAncestorTags | public Set<Tag> getAncestorTags(Tag tag)
{
Set<Tag> ancestors = new HashSet<>();
getAncestorTags(tag, ancestors);
return ancestors;
} | java | public Set<Tag> getAncestorTags(Tag tag)
{
Set<Tag> ancestors = new HashSet<>();
getAncestorTags(tag, ancestors);
return ancestors;
} | [
"public",
"Set",
"<",
"Tag",
">",
"getAncestorTags",
"(",
"Tag",
"tag",
")",
"{",
"Set",
"<",
"Tag",
">",
"ancestors",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"getAncestorTags",
"(",
"tag",
",",
"ancestors",
")",
";",
"return",
"ancestors",
";",
... | Returns all tags that designate this tag. E.g., for "tesla-model3", this would return "car", "vehicle", "vendor-tesla" etc. | [
"Returns",
"all",
"tags",
"that",
"designate",
"this",
"tag",
".",
"E",
".",
"g",
".",
"for",
"tesla",
"-",
"model3",
"this",
"would",
"return",
"car",
"vehicle",
"vendor",
"-",
"tesla",
"etc",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/tags/TagService.java#L117-L122 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/tags/TagService.java | TagService.writeTagsToJavaScript | public void writeTagsToJavaScript(Writer writer) throws IOException
{
writer.append("function fillTagService(tagService) {\n");
writer.append("\t// (name, isPrime, isPseudo, color), [parent tags]\n");
for (Tag tag : definedTags.values())
{
writer.append("\ttagService.registerTag(new Tag(");
escapeOrNull(tag.getName(), writer);
writer.append(", ");
escapeOrNull(tag.getTitle(), writer);
writer.append(", ").append("" + tag.isPrime())
.append(", ").append("" + tag.isPseudo())
.append(", ");
escapeOrNull(tag.getColor(), writer);
writer.append(")").append(", [");
// We only have strings, not references, so we're letting registerTag() getOrCreate() the tag.
for (Tag parentTag : tag.getParentTags())
{
writer.append("'").append(StringEscapeUtils.escapeEcmaScript(parentTag.getName())).append("',");
}
writer.append("]);\n");
}
writer.append("}\n");
} | java | public void writeTagsToJavaScript(Writer writer) throws IOException
{
writer.append("function fillTagService(tagService) {\n");
writer.append("\t// (name, isPrime, isPseudo, color), [parent tags]\n");
for (Tag tag : definedTags.values())
{
writer.append("\ttagService.registerTag(new Tag(");
escapeOrNull(tag.getName(), writer);
writer.append(", ");
escapeOrNull(tag.getTitle(), writer);
writer.append(", ").append("" + tag.isPrime())
.append(", ").append("" + tag.isPseudo())
.append(", ");
escapeOrNull(tag.getColor(), writer);
writer.append(")").append(", [");
// We only have strings, not references, so we're letting registerTag() getOrCreate() the tag.
for (Tag parentTag : tag.getParentTags())
{
writer.append("'").append(StringEscapeUtils.escapeEcmaScript(parentTag.getName())).append("',");
}
writer.append("]);\n");
}
writer.append("}\n");
} | [
"public",
"void",
"writeTagsToJavaScript",
"(",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"writer",
".",
"append",
"(",
"\"function fillTagService(tagService) {\\n\"",
")",
";",
"writer",
".",
"append",
"(",
"\"\\t// (name, isPrime, isPseudo, color), [parent ta... | Writes the JavaScript code describing the tags as Tag classes to given writer. | [
"Writes",
"the",
"JavaScript",
"code",
"describing",
"the",
"tags",
"as",
"Tag",
"classes",
"to",
"given",
"writer",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/tags/TagService.java#L223-L247 | train |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/service/ReportService.java | ReportService.getReportDirectory | public Path getReportDirectory()
{
WindupConfigurationModel cfg = WindupConfigurationService.getConfigurationModel(getGraphContext());
Path path = cfg.getOutputPath().asFile().toPath().resolve(REPORTS_DIR);
createDirectoryIfNeeded(path);
return path.toAbsolutePath();
} | java | public Path getReportDirectory()
{
WindupConfigurationModel cfg = WindupConfigurationService.getConfigurationModel(getGraphContext());
Path path = cfg.getOutputPath().asFile().toPath().resolve(REPORTS_DIR);
createDirectoryIfNeeded(path);
return path.toAbsolutePath();
} | [
"public",
"Path",
"getReportDirectory",
"(",
")",
"{",
"WindupConfigurationModel",
"cfg",
"=",
"WindupConfigurationService",
".",
"getConfigurationModel",
"(",
"getGraphContext",
"(",
")",
")",
";",
"Path",
"path",
"=",
"cfg",
".",
"getOutputPath",
"(",
")",
".",
... | Returns the output directory for reporting. | [
"Returns",
"the",
"output",
"directory",
"for",
"reporting",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/service/ReportService.java#L52-L58 | train |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/service/ReportService.java | ReportService.getReportByName | @SuppressWarnings("unchecked")
public <T extends ReportModel> T getReportByName(String name, Class<T> clazz)
{
WindupVertexFrame model = this.getUniqueByProperty(ReportModel.REPORT_NAME, name);
try
{
return (T) model;
}
catch (ClassCastException ex)
{
throw new WindupException("The vertex is not of expected frame type " + clazz.getName() + ": " + model.toPrettyString());
}
} | java | @SuppressWarnings("unchecked")
public <T extends ReportModel> T getReportByName(String name, Class<T> clazz)
{
WindupVertexFrame model = this.getUniqueByProperty(ReportModel.REPORT_NAME, name);
try
{
return (T) model;
}
catch (ClassCastException ex)
{
throw new WindupException("The vertex is not of expected frame type " + clazz.getName() + ": " + model.toPrettyString());
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
"extends",
"ReportModel",
">",
"T",
"getReportByName",
"(",
"String",
"name",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"WindupVertexFrame",
"model",
"=",
"this",
".",
"getUniqueBy... | Returns the ReportModel with given name. | [
"Returns",
"the",
"ReportModel",
"with",
"given",
"name",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/service/ReportService.java#L79-L91 | train |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/service/ReportService.java | ReportService.getUniqueFilename | public String getUniqueFilename(String baseFileName, String extension, boolean cleanBaseFileName, String... ancestorFolders)
{
if (cleanBaseFileName)
{
baseFileName = PathUtil.cleanFileName(baseFileName);
}
if (ancestorFolders != null)
{
Path pathToFile = Paths.get("", Stream.of(ancestorFolders).map(ancestor -> PathUtil.cleanFileName(ancestor)).toArray(String[]::new)).resolve(baseFileName);
baseFileName = pathToFile.toString();
}
String filename = baseFileName + "." + extension;
// FIXME this looks nasty
while (usedFilenames.contains(filename))
{
filename = baseFileName + "." + index.getAndIncrement() + "." + extension;
}
usedFilenames.add(filename);
return filename;
} | java | public String getUniqueFilename(String baseFileName, String extension, boolean cleanBaseFileName, String... ancestorFolders)
{
if (cleanBaseFileName)
{
baseFileName = PathUtil.cleanFileName(baseFileName);
}
if (ancestorFolders != null)
{
Path pathToFile = Paths.get("", Stream.of(ancestorFolders).map(ancestor -> PathUtil.cleanFileName(ancestor)).toArray(String[]::new)).resolve(baseFileName);
baseFileName = pathToFile.toString();
}
String filename = baseFileName + "." + extension;
// FIXME this looks nasty
while (usedFilenames.contains(filename))
{
filename = baseFileName + "." + index.getAndIncrement() + "." + extension;
}
usedFilenames.add(filename);
return filename;
} | [
"public",
"String",
"getUniqueFilename",
"(",
"String",
"baseFileName",
",",
"String",
"extension",
",",
"boolean",
"cleanBaseFileName",
",",
"String",
"...",
"ancestorFolders",
")",
"{",
"if",
"(",
"cleanBaseFileName",
")",
"{",
"baseFileName",
"=",
"PathUtil",
"... | Returns a unique file name
@param baseFileName the requested base name for the file
@param extension the requested extension for the file
@param cleanBaseFileName specify if the <code>baseFileName</code> has to be cleaned before being used (i.e. 'jboss-web' should not be cleaned to avoid '-' to become '_')
@param ancestorFolders specify the ancestor folders for the file (if there's no ancestor folder, just pass 'null' value)
@return a String representing the unique file generated | [
"Returns",
"a",
"unique",
"file",
"name"
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/service/ReportService.java#L109-L131 | train |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/service/TagSetService.java | TagSetService.getOrCreate | public TagSetModel getOrCreate(GraphRewrite event, Set<String> tags)
{
Map<Set<String>, Vertex> cache = getCache(event);
Vertex vertex = cache.get(tags);
if (vertex == null)
{
TagSetModel model = create();
model.setTags(tags);
cache.put(tags, model.getElement());
return model;
}
else
{
return frame(vertex);
}
} | java | public TagSetModel getOrCreate(GraphRewrite event, Set<String> tags)
{
Map<Set<String>, Vertex> cache = getCache(event);
Vertex vertex = cache.get(tags);
if (vertex == null)
{
TagSetModel model = create();
model.setTags(tags);
cache.put(tags, model.getElement());
return model;
}
else
{
return frame(vertex);
}
} | [
"public",
"TagSetModel",
"getOrCreate",
"(",
"GraphRewrite",
"event",
",",
"Set",
"<",
"String",
">",
"tags",
")",
"{",
"Map",
"<",
"Set",
"<",
"String",
">",
",",
"Vertex",
">",
"cache",
"=",
"getCache",
"(",
"event",
")",
";",
"Vertex",
"vertex",
"="... | This essentially ensures that we only store a single Vertex for each unique "Set" of tags. | [
"This",
"essentially",
"ensures",
"that",
"we",
"only",
"store",
"a",
"single",
"Vertex",
"for",
"each",
"unique",
"Set",
"of",
"tags",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/service/TagSetService.java#L43-L58 | train |
windup/windup | reporting/impl/src/main/java/org/jboss/windup/reporting/rules/generation/techreport/GetTechReportPunchCardStatsMethod.java | GetTechReportPunchCardStatsMethod.getAllApplications | private static Set<ProjectModel> getAllApplications(GraphContext graphContext)
{
Set<ProjectModel> apps = new HashSet<>();
Iterable<ProjectModel> appProjects = graphContext.findAll(ProjectModel.class);
for (ProjectModel appProject : appProjects)
apps.add(appProject);
return apps;
} | java | private static Set<ProjectModel> getAllApplications(GraphContext graphContext)
{
Set<ProjectModel> apps = new HashSet<>();
Iterable<ProjectModel> appProjects = graphContext.findAll(ProjectModel.class);
for (ProjectModel appProject : appProjects)
apps.add(appProject);
return apps;
} | [
"private",
"static",
"Set",
"<",
"ProjectModel",
">",
"getAllApplications",
"(",
"GraphContext",
"graphContext",
")",
"{",
"Set",
"<",
"ProjectModel",
">",
"apps",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"Iterable",
"<",
"ProjectModel",
">",
"appProjects",... | Returns all ApplicationProjectModels. | [
"Returns",
"all",
"ApplicationProjectModels",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/impl/src/main/java/org/jboss/windup/reporting/rules/generation/techreport/GetTechReportPunchCardStatsMethod.java#L191-L198 | train |
windup/windup | reporting/impl/src/main/java/org/jboss/windup/reporting/rules/generation/techreport/TechReportService.java | TechReportService.processPlaceLabels | private static TechReportPlacement processPlaceLabels(GraphContext graphContext, Set<String> tagNames)
{
TagGraphService tagService = new TagGraphService(graphContext);
if (tagNames.size() < 3)
throw new WindupException("There should always be exactly 3 placement labels - row, sector, column/box. It was: " + tagNames);
if (tagNames.size() > 3)
LOG.severe("There should always be exactly 3 placement labels - row, sector, column/box. It was: " + tagNames);
TechReportPlacement placement = new TechReportPlacement();
final TagModel placeSectorsTag = tagService.getTagByName("techReport:placeSectors");
final TagModel placeBoxesTag = tagService.getTagByName("techReport:placeBoxes");
final TagModel placeRowsTag = tagService.getTagByName("techReport:placeRows");
Set<String> unknownTags = new HashSet<>();
for (String name : tagNames)
{
final TagModel tag = tagService.getTagByName(name);
if (null == tag)
continue;
if (TagGraphService.isTagUnderTagOrSame(tag, placeSectorsTag))
{
placement.sector = tag;
}
else if (TagGraphService.isTagUnderTagOrSame(tag, placeBoxesTag))
{
placement.box = tag;
}
else if (TagGraphService.isTagUnderTagOrSame(tag, placeRowsTag))
{
placement.row = tag;
}
else
{
unknownTags.add(name);
}
}
placement.unknown = unknownTags;
LOG.fine(String.format("\t\tLabels %s identified as: sector: %s, box: %s, row: %s", tagNames, placement.sector, placement.box,
placement.row));
if (placement.box == null || placement.row == null)
{
LOG.severe(String.format(
"There should always be exactly 3 placement labels - row, sector, column/box. Found: %s, of which box: %s, row: %s", tagNames,
placement.box, placement.row));
}
return placement;
} | java | private static TechReportPlacement processPlaceLabels(GraphContext graphContext, Set<String> tagNames)
{
TagGraphService tagService = new TagGraphService(graphContext);
if (tagNames.size() < 3)
throw new WindupException("There should always be exactly 3 placement labels - row, sector, column/box. It was: " + tagNames);
if (tagNames.size() > 3)
LOG.severe("There should always be exactly 3 placement labels - row, sector, column/box. It was: " + tagNames);
TechReportPlacement placement = new TechReportPlacement();
final TagModel placeSectorsTag = tagService.getTagByName("techReport:placeSectors");
final TagModel placeBoxesTag = tagService.getTagByName("techReport:placeBoxes");
final TagModel placeRowsTag = tagService.getTagByName("techReport:placeRows");
Set<String> unknownTags = new HashSet<>();
for (String name : tagNames)
{
final TagModel tag = tagService.getTagByName(name);
if (null == tag)
continue;
if (TagGraphService.isTagUnderTagOrSame(tag, placeSectorsTag))
{
placement.sector = tag;
}
else if (TagGraphService.isTagUnderTagOrSame(tag, placeBoxesTag))
{
placement.box = tag;
}
else if (TagGraphService.isTagUnderTagOrSame(tag, placeRowsTag))
{
placement.row = tag;
}
else
{
unknownTags.add(name);
}
}
placement.unknown = unknownTags;
LOG.fine(String.format("\t\tLabels %s identified as: sector: %s, box: %s, row: %s", tagNames, placement.sector, placement.box,
placement.row));
if (placement.box == null || placement.row == null)
{
LOG.severe(String.format(
"There should always be exactly 3 placement labels - row, sector, column/box. Found: %s, of which box: %s, row: %s", tagNames,
placement.box, placement.row));
}
return placement;
} | [
"private",
"static",
"TechReportPlacement",
"processPlaceLabels",
"(",
"GraphContext",
"graphContext",
",",
"Set",
"<",
"String",
">",
"tagNames",
")",
"{",
"TagGraphService",
"tagService",
"=",
"new",
"TagGraphService",
"(",
"graphContext",
")",
";",
"if",
"(",
"... | From three tagNames, if one is under sectorTag and one under rowTag, returns the remaining one, which is supposedly the a box label. Otherwise,
returns null. | [
"From",
"three",
"tagNames",
"if",
"one",
"is",
"under",
"sectorTag",
"and",
"one",
"under",
"rowTag",
"returns",
"the",
"remaining",
"one",
"which",
"is",
"supposedly",
"the",
"a",
"box",
"label",
".",
"Otherwise",
"returns",
"null",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/impl/src/main/java/org/jboss/windup/reporting/rules/generation/techreport/TechReportService.java#L74-L124 | train |
windup/windup | rules-java-project/addon/src/main/java/org/jboss/windup/project/condition/Artifact.java | Artifact.withVersion | public static Artifact withVersion(Version v)
{
Artifact artifact = new Artifact();
artifact.version = v;
return artifact;
} | java | public static Artifact withVersion(Version v)
{
Artifact artifact = new Artifact();
artifact.version = v;
return artifact;
} | [
"public",
"static",
"Artifact",
"withVersion",
"(",
"Version",
"v",
")",
"{",
"Artifact",
"artifact",
"=",
"new",
"Artifact",
"(",
")",
";",
"artifact",
".",
"version",
"=",
"v",
";",
"return",
"artifact",
";",
"}"
] | Start with specifying the artifact version | [
"Start",
"with",
"specifying",
"the",
"artifact",
"version"
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java-project/addon/src/main/java/org/jboss/windup/project/condition/Artifact.java#L28-L33 | train |
windup/windup | rules-java-project/addon/src/main/java/org/jboss/windup/project/condition/Artifact.java | Artifact.withGroupId | public static Artifact withGroupId(String groupId)
{
Artifact artifact = new Artifact();
artifact.groupId = new RegexParameterizedPatternParser(groupId);
return artifact;
} | java | public static Artifact withGroupId(String groupId)
{
Artifact artifact = new Artifact();
artifact.groupId = new RegexParameterizedPatternParser(groupId);
return artifact;
} | [
"public",
"static",
"Artifact",
"withGroupId",
"(",
"String",
"groupId",
")",
"{",
"Artifact",
"artifact",
"=",
"new",
"Artifact",
"(",
")",
";",
"artifact",
".",
"groupId",
"=",
"new",
"RegexParameterizedPatternParser",
"(",
"groupId",
")",
";",
"return",
"ar... | Start with specifying the groupId | [
"Start",
"with",
"specifying",
"the",
"groupId"
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java-project/addon/src/main/java/org/jboss/windup/project/condition/Artifact.java#L38-L44 | train |
windup/windup | rules-java-project/addon/src/main/java/org/jboss/windup/project/condition/Artifact.java | Artifact.withArtifactId | public static Artifact withArtifactId(String artifactId)
{
Artifact artifact = new Artifact();
artifact.artifactId = new RegexParameterizedPatternParser(artifactId);
return artifact;
} | java | public static Artifact withArtifactId(String artifactId)
{
Artifact artifact = new Artifact();
artifact.artifactId = new RegexParameterizedPatternParser(artifactId);
return artifact;
} | [
"public",
"static",
"Artifact",
"withArtifactId",
"(",
"String",
"artifactId",
")",
"{",
"Artifact",
"artifact",
"=",
"new",
"Artifact",
"(",
")",
";",
"artifact",
".",
"artifactId",
"=",
"new",
"RegexParameterizedPatternParser",
"(",
"artifactId",
")",
";",
"re... | Start with specifying the artifactId | [
"Start",
"with",
"specifying",
"the",
"artifactId"
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java-project/addon/src/main/java/org/jboss/windup/project/condition/Artifact.java#L49-L54 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/Variables.java | Variables.setSingletonVariable | public void setSingletonVariable(String name, WindupVertexFrame frame)
{
setVariable(name, Collections.singletonList(frame));
} | java | public void setSingletonVariable(String name, WindupVertexFrame frame)
{
setVariable(name, Collections.singletonList(frame));
} | [
"public",
"void",
"setSingletonVariable",
"(",
"String",
"name",
",",
"WindupVertexFrame",
"frame",
")",
"{",
"setVariable",
"(",
"name",
",",
"Collections",
".",
"singletonList",
"(",
"frame",
")",
")",
";",
"}"
] | Type-safe wrapper around setVariable which sets only one framed vertex. | [
"Type",
"-",
"safe",
"wrapper",
"around",
"setVariable",
"which",
"sets",
"only",
"one",
"framed",
"vertex",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/Variables.java#L90-L93 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/Variables.java | Variables.setVariable | public void setVariable(String name, Iterable<? extends WindupVertexFrame> frames)
{
Map<String, Iterable<? extends WindupVertexFrame>> frame = peek();
if (!Iteration.DEFAULT_VARIABLE_LIST_STRING.equals(name) && findVariable(name) != null)
{
throw new IllegalArgumentException("Variable \"" + name
+ "\" has already been assigned and cannot be reassigned");
}
frame.put(name, frames);
} | java | public void setVariable(String name, Iterable<? extends WindupVertexFrame> frames)
{
Map<String, Iterable<? extends WindupVertexFrame>> frame = peek();
if (!Iteration.DEFAULT_VARIABLE_LIST_STRING.equals(name) && findVariable(name) != null)
{
throw new IllegalArgumentException("Variable \"" + name
+ "\" has already been assigned and cannot be reassigned");
}
frame.put(name, frames);
} | [
"public",
"void",
"setVariable",
"(",
"String",
"name",
",",
"Iterable",
"<",
"?",
"extends",
"WindupVertexFrame",
">",
"frames",
")",
"{",
"Map",
"<",
"String",
",",
"Iterable",
"<",
"?",
"extends",
"WindupVertexFrame",
">",
">",
"frame",
"=",
"peek",
"("... | Set a variable in the top variables layer to given "collection" of the vertex frames. Can't be reassigned -
throws on attempt to reassign. | [
"Set",
"a",
"variable",
"in",
"the",
"top",
"variables",
"layer",
"to",
"given",
"collection",
"of",
"the",
"vertex",
"frames",
".",
"Can",
"t",
"be",
"reassigned",
"-",
"throws",
"on",
"attempt",
"to",
"reassign",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/Variables.java#L99-L109 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/Variables.java | Variables.removeVariable | public void removeVariable(String name)
{
Map<String, Iterable<? extends WindupVertexFrame>> frame = peek();
frame.remove(name);
} | java | public void removeVariable(String name)
{
Map<String, Iterable<? extends WindupVertexFrame>> frame = peek();
frame.remove(name);
} | [
"public",
"void",
"removeVariable",
"(",
"String",
"name",
")",
"{",
"Map",
"<",
"String",
",",
"Iterable",
"<",
"?",
"extends",
"WindupVertexFrame",
">",
">",
"frame",
"=",
"peek",
"(",
")",
";",
"frame",
".",
"remove",
"(",
"name",
")",
";",
"}"
] | Remove a variable in the top variables layer. | [
"Remove",
"a",
"variable",
"in",
"the",
"top",
"variables",
"layer",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/Variables.java#L114-L118 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/Variables.java | Variables.findVariable | public Iterable<? extends WindupVertexFrame> findVariable(String name, int maxDepth)
{
int currentDepth = 0;
Iterable<? extends WindupVertexFrame> result = null;
for (Map<String, Iterable<? extends WindupVertexFrame>> frame : deque)
{
result = frame.get(name);
if (result != null)
{
break;
}
currentDepth++;
if (currentDepth >= maxDepth)
break;
}
return result;
} | java | public Iterable<? extends WindupVertexFrame> findVariable(String name, int maxDepth)
{
int currentDepth = 0;
Iterable<? extends WindupVertexFrame> result = null;
for (Map<String, Iterable<? extends WindupVertexFrame>> frame : deque)
{
result = frame.get(name);
if (result != null)
{
break;
}
currentDepth++;
if (currentDepth >= maxDepth)
break;
}
return result;
} | [
"public",
"Iterable",
"<",
"?",
"extends",
"WindupVertexFrame",
">",
"findVariable",
"(",
"String",
"name",
",",
"int",
"maxDepth",
")",
"{",
"int",
"currentDepth",
"=",
"0",
";",
"Iterable",
"<",
"?",
"extends",
"WindupVertexFrame",
">",
"result",
"=",
"nul... | Searches the variables layers, top to bottom, for given name, and returns if found; null otherwise.
If maxDepth is set to {@link Variables#SEARCH_ALL_LAYERS}, then search all layers. | [
"Searches",
"the",
"variables",
"layers",
"top",
"to",
"bottom",
"for",
"given",
"name",
"and",
"returns",
"if",
"found",
";",
"null",
"otherwise",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/Variables.java#L180-L196 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/Variables.java | Variables.findVariableOfType | @SuppressWarnings("unchecked")
public <T extends WindupVertexFrame> Iterable<T> findVariableOfType(Class<T> type)
{
for (Map<String, Iterable<? extends WindupVertexFrame>> topOfStack : deque)
{
for (Iterable<? extends WindupVertexFrame> frames : topOfStack.values())
{
boolean empty = true;
for (WindupVertexFrame frame : frames)
{
if (!type.isAssignableFrom(frame.getClass()))
{
break;
}
else
{
empty = false;
}
}
// now we know all the frames are of the chosen type
if (!empty)
return (Iterable<T>) frames;
}
}
return null;
} | java | @SuppressWarnings("unchecked")
public <T extends WindupVertexFrame> Iterable<T> findVariableOfType(Class<T> type)
{
for (Map<String, Iterable<? extends WindupVertexFrame>> topOfStack : deque)
{
for (Iterable<? extends WindupVertexFrame> frames : topOfStack.values())
{
boolean empty = true;
for (WindupVertexFrame frame : frames)
{
if (!type.isAssignableFrom(frame.getClass()))
{
break;
}
else
{
empty = false;
}
}
// now we know all the frames are of the chosen type
if (!empty)
return (Iterable<T>) frames;
}
}
return null;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
"extends",
"WindupVertexFrame",
">",
"Iterable",
"<",
"T",
">",
"findVariableOfType",
"(",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"for",
"(",
"Map",
"<",
"String",
",",
"Iterable",
... | Searches the variables layers, top to bottom, for the iterable having all of it's items of the given type. Return
null if not found. | [
"Searches",
"the",
"variables",
"layers",
"top",
"to",
"bottom",
"for",
"the",
"iterable",
"having",
"all",
"of",
"it",
"s",
"items",
"of",
"the",
"given",
"type",
".",
"Return",
"null",
"if",
"not",
"found",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/Variables.java#L202-L227 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/operation/iteration/AbstractIterationFilter.java | AbstractIterationFilter.checkVariableName | protected void checkVariableName(GraphRewrite event, EvaluationContext context)
{
if (getInputVariablesName() == null)
{
setInputVariablesName(Iteration.getPayloadVariableName(event, context));
}
} | java | protected void checkVariableName(GraphRewrite event, EvaluationContext context)
{
if (getInputVariablesName() == null)
{
setInputVariablesName(Iteration.getPayloadVariableName(event, context));
}
} | [
"protected",
"void",
"checkVariableName",
"(",
"GraphRewrite",
"event",
",",
"EvaluationContext",
"context",
")",
"{",
"if",
"(",
"getInputVariablesName",
"(",
")",
"==",
"null",
")",
"{",
"setInputVariablesName",
"(",
"Iteration",
".",
"getPayloadVariableName",
"("... | Check the variable name and if not set, set it with the singleton variable being on the top of the stack. | [
"Check",
"the",
"variable",
"name",
"and",
"if",
"not",
"set",
"set",
"it",
"with",
"the",
"singleton",
"variable",
"being",
"on",
"the",
"top",
"of",
"the",
"stack",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/operation/iteration/AbstractIterationFilter.java#L43-L49 | train |
windup/windup | bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/windup/DiscoverPackagesCommand.java | DiscoverPackagesCommand.findClasses | private static Map<String, Integer> findClasses(Path path)
{
List<String> paths = findPaths(path, true);
Map<String, Integer> results = new HashMap<>();
for (String subPath : paths)
{
if (subPath.endsWith(".java") || subPath.endsWith(".class"))
{
String qualifiedName = PathUtil.classFilePathToClassname(subPath);
addClassToMap(results, qualifiedName);
}
}
return results;
} | java | private static Map<String, Integer> findClasses(Path path)
{
List<String> paths = findPaths(path, true);
Map<String, Integer> results = new HashMap<>();
for (String subPath : paths)
{
if (subPath.endsWith(".java") || subPath.endsWith(".class"))
{
String qualifiedName = PathUtil.classFilePathToClassname(subPath);
addClassToMap(results, qualifiedName);
}
}
return results;
} | [
"private",
"static",
"Map",
"<",
"String",
",",
"Integer",
">",
"findClasses",
"(",
"Path",
"path",
")",
"{",
"List",
"<",
"String",
">",
"paths",
"=",
"findPaths",
"(",
"path",
",",
"true",
")",
";",
"Map",
"<",
"String",
",",
"Integer",
">",
"resul... | Recursively scan the provided path and return a list of all Java packages contained therein. | [
"Recursively",
"scan",
"the",
"provided",
"path",
"and",
"return",
"a",
"list",
"of",
"all",
"Java",
"packages",
"contained",
"therein",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/windup/DiscoverPackagesCommand.java#L140-L153 | train |
windup/windup | rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/service/XsltTransformationService.java | XsltTransformationService.getTransformedXSLTPath | public Path getTransformedXSLTPath(FileModel payload)
{
ReportService reportService = new ReportService(getGraphContext());
Path outputPath = reportService.getReportDirectory();
outputPath = outputPath.resolve(this.getRelativeTransformedXSLTPath(payload));
if (!Files.isDirectory(outputPath))
{
try
{
Files.createDirectories(outputPath);
}
catch (IOException e)
{
throw new WindupException("Failed to create output directory at: " + outputPath + " due to: "
+ e.getMessage(), e);
}
}
return outputPath;
} | java | public Path getTransformedXSLTPath(FileModel payload)
{
ReportService reportService = new ReportService(getGraphContext());
Path outputPath = reportService.getReportDirectory();
outputPath = outputPath.resolve(this.getRelativeTransformedXSLTPath(payload));
if (!Files.isDirectory(outputPath))
{
try
{
Files.createDirectories(outputPath);
}
catch (IOException e)
{
throw new WindupException("Failed to create output directory at: " + outputPath + " due to: "
+ e.getMessage(), e);
}
}
return outputPath;
} | [
"public",
"Path",
"getTransformedXSLTPath",
"(",
"FileModel",
"payload",
")",
"{",
"ReportService",
"reportService",
"=",
"new",
"ReportService",
"(",
"getGraphContext",
"(",
")",
")",
";",
"Path",
"outputPath",
"=",
"reportService",
".",
"getReportDirectory",
"(",
... | Gets the path used for the results of XSLT Transforms. | [
"Gets",
"the",
"path",
"used",
"for",
"the",
"results",
"of",
"XSLT",
"Transforms",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/service/XsltTransformationService.java#L33-L51 | train |
windup/windup | rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/util/HibernateDialectDataSourceTypeResolver.java | HibernateDialectDataSourceTypeResolver.resolveDataSourceTypeFromDialect | public static String resolveDataSourceTypeFromDialect(String dialect)
{
if (StringUtils.contains(dialect, "Oracle"))
{
return "Oracle";
}
else if (StringUtils.contains(dialect, "MySQL"))
{
return "MySQL";
}
else if (StringUtils.contains(dialect, "DB2390Dialect"))
{
return "DB2/390";
}
else if (StringUtils.contains(dialect, "DB2400Dialect"))
{
return "DB2/400";
}
else if (StringUtils.contains(dialect, "DB2"))
{
return "DB2";
}
else if (StringUtils.contains(dialect, "Ingres"))
{
return "Ingres";
}
else if (StringUtils.contains(dialect, "Derby"))
{
return "Derby";
}
else if (StringUtils.contains(dialect, "Pointbase"))
{
return "Pointbase";
}
else if (StringUtils.contains(dialect, "Postgres"))
{
return "Postgres";
}
else if (StringUtils.contains(dialect, "SQLServer"))
{
return "SQLServer";
}
else if (StringUtils.contains(dialect, "Sybase"))
{
return "Sybase";
}
else if (StringUtils.contains(dialect, "HSQLDialect"))
{
return "HyperSQL";
}
else if (StringUtils.contains(dialect, "H2Dialect"))
{
return "H2";
}
return dialect;
} | java | public static String resolveDataSourceTypeFromDialect(String dialect)
{
if (StringUtils.contains(dialect, "Oracle"))
{
return "Oracle";
}
else if (StringUtils.contains(dialect, "MySQL"))
{
return "MySQL";
}
else if (StringUtils.contains(dialect, "DB2390Dialect"))
{
return "DB2/390";
}
else if (StringUtils.contains(dialect, "DB2400Dialect"))
{
return "DB2/400";
}
else if (StringUtils.contains(dialect, "DB2"))
{
return "DB2";
}
else if (StringUtils.contains(dialect, "Ingres"))
{
return "Ingres";
}
else if (StringUtils.contains(dialect, "Derby"))
{
return "Derby";
}
else if (StringUtils.contains(dialect, "Pointbase"))
{
return "Pointbase";
}
else if (StringUtils.contains(dialect, "Postgres"))
{
return "Postgres";
}
else if (StringUtils.contains(dialect, "SQLServer"))
{
return "SQLServer";
}
else if (StringUtils.contains(dialect, "Sybase"))
{
return "Sybase";
}
else if (StringUtils.contains(dialect, "HSQLDialect"))
{
return "HyperSQL";
}
else if (StringUtils.contains(dialect, "H2Dialect"))
{
return "H2";
}
return dialect;
} | [
"public",
"static",
"String",
"resolveDataSourceTypeFromDialect",
"(",
"String",
"dialect",
")",
"{",
"if",
"(",
"StringUtils",
".",
"contains",
"(",
"dialect",
",",
"\"Oracle\"",
")",
")",
"{",
"return",
"\"Oracle\"",
";",
"}",
"else",
"if",
"(",
"StringUtils... | Converts the given dislect to a human-readable datasource type. | [
"Converts",
"the",
"given",
"dislect",
"to",
"a",
"human",
"-",
"readable",
"datasource",
"type",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/util/HibernateDialectDataSourceTypeResolver.java#L15-L72 | train |
windup/windup | rules-java-archives/addon/src/main/java/org/jboss/windup/rules/apps/java/archives/ignore/SkippedArchives.java | SkippedArchives.load | public static void load(File file)
{
try(FileInputStream inputStream = new FileInputStream(file))
{
LineIterator it = IOUtils.lineIterator(inputStream, "UTF-8");
while (it.hasNext())
{
String line = it.next();
if (!line.startsWith("#") && !line.trim().isEmpty())
{
add(line);
}
}
}
catch (Exception e)
{
throw new WindupException("Failed loading archive ignore patterns from [" + file.toString() + "]", e);
}
} | java | public static void load(File file)
{
try(FileInputStream inputStream = new FileInputStream(file))
{
LineIterator it = IOUtils.lineIterator(inputStream, "UTF-8");
while (it.hasNext())
{
String line = it.next();
if (!line.startsWith("#") && !line.trim().isEmpty())
{
add(line);
}
}
}
catch (Exception e)
{
throw new WindupException("Failed loading archive ignore patterns from [" + file.toString() + "]", e);
}
} | [
"public",
"static",
"void",
"load",
"(",
"File",
"file",
")",
"{",
"try",
"(",
"FileInputStream",
"inputStream",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
")",
"{",
"LineIterator",
"it",
"=",
"IOUtils",
".",
"lineIterator",
"(",
"inputStream",
",",
... | Load the given configuration file. | [
"Load",
"the",
"given",
"configuration",
"file",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java-archives/addon/src/main/java/org/jboss/windup/rules/apps/java/archives/ignore/SkippedArchives.java#L39-L57 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/operation/Iteration.java | Iteration.perform | @Override
public void perform(Rewrite event, EvaluationContext context)
{
perform((GraphRewrite) event, context);
} | java | @Override
public void perform(Rewrite event, EvaluationContext context)
{
perform((GraphRewrite) event, context);
} | [
"@",
"Override",
"public",
"void",
"perform",
"(",
"Rewrite",
"event",
",",
"EvaluationContext",
"context",
")",
"{",
"perform",
"(",
"(",
"GraphRewrite",
")",
"event",
",",
"context",
")",
";",
"}"
] | Called internally to actually process the Iteration. | [
"Called",
"internally",
"to",
"actually",
"process",
"the",
"Iteration",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/operation/Iteration.java#L249-L253 | train |
windup/windup | config/api/src/main/java/org/jboss/windup/config/metadata/MetadataBuilder.java | MetadataBuilder.join | @SafeVarargs
private final <T> Set<T> join(Set<T>... sets)
{
Set<T> result = new HashSet<>();
if (sets == null)
return result;
for (Set<T> set : sets)
{
if (set != null)
result.addAll(set);
}
return result;
} | java | @SafeVarargs
private final <T> Set<T> join(Set<T>... sets)
{
Set<T> result = new HashSet<>();
if (sets == null)
return result;
for (Set<T> set : sets)
{
if (set != null)
result.addAll(set);
}
return result;
} | [
"@",
"SafeVarargs",
"private",
"final",
"<",
"T",
">",
"Set",
"<",
"T",
">",
"join",
"(",
"Set",
"<",
"T",
">",
"...",
"sets",
")",
"{",
"Set",
"<",
"T",
">",
"result",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"if",
"(",
"sets",
"==",
"nul... | Join N sets. | [
"Join",
"N",
"sets",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/metadata/MetadataBuilder.java#L549-L562 | train |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/category/IssueCategoryRegistry.java | IssueCategoryRegistry.getIssueCategories | public List<IssueCategory> getIssueCategories()
{
return this.issueCategories.values().stream()
.sorted((category1, category2) -> category1.getPriority() - category2.getPriority())
.collect(Collectors.toList());
} | java | public List<IssueCategory> getIssueCategories()
{
return this.issueCategories.values().stream()
.sorted((category1, category2) -> category1.getPriority() - category2.getPriority())
.collect(Collectors.toList());
} | [
"public",
"List",
"<",
"IssueCategory",
">",
"getIssueCategories",
"(",
")",
"{",
"return",
"this",
".",
"issueCategories",
".",
"values",
"(",
")",
".",
"stream",
"(",
")",
".",
"sorted",
"(",
"(",
"category1",
",",
"category2",
")",
"->",
"category1",
... | Returns a list ordered from the highest priority to the lowest. | [
"Returns",
"a",
"list",
"ordered",
"from",
"the",
"highest",
"priority",
"to",
"the",
"lowest",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/category/IssueCategoryRegistry.java#L154-L159 | train |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/category/IssueCategoryRegistry.java | IssueCategoryRegistry.addDefaults | private void addDefaults()
{
this.issueCategories.putIfAbsent(MANDATORY, new IssueCategory(MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Mandatory", MANDATORY, 1000, true));
this.issueCategories.putIfAbsent(OPTIONAL, new IssueCategory(OPTIONAL, IssueCategoryRegistry.class.getCanonicalName(), "Optional", OPTIONAL, 1000, true));
this.issueCategories.putIfAbsent(POTENTIAL, new IssueCategory(POTENTIAL, IssueCategoryRegistry.class.getCanonicalName(), "Potential Issues", POTENTIAL, 1000, true));
this.issueCategories.putIfAbsent(CLOUD_MANDATORY, new IssueCategory(CLOUD_MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Cloud Mandatory", CLOUD_MANDATORY, 1000, true));
this.issueCategories.putIfAbsent(INFORMATION, new IssueCategory(INFORMATION, IssueCategoryRegistry.class.getCanonicalName(), "Information", INFORMATION, 1000, true));
} | java | private void addDefaults()
{
this.issueCategories.putIfAbsent(MANDATORY, new IssueCategory(MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Mandatory", MANDATORY, 1000, true));
this.issueCategories.putIfAbsent(OPTIONAL, new IssueCategory(OPTIONAL, IssueCategoryRegistry.class.getCanonicalName(), "Optional", OPTIONAL, 1000, true));
this.issueCategories.putIfAbsent(POTENTIAL, new IssueCategory(POTENTIAL, IssueCategoryRegistry.class.getCanonicalName(), "Potential Issues", POTENTIAL, 1000, true));
this.issueCategories.putIfAbsent(CLOUD_MANDATORY, new IssueCategory(CLOUD_MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Cloud Mandatory", CLOUD_MANDATORY, 1000, true));
this.issueCategories.putIfAbsent(INFORMATION, new IssueCategory(INFORMATION, IssueCategoryRegistry.class.getCanonicalName(), "Information", INFORMATION, 1000, true));
} | [
"private",
"void",
"addDefaults",
"(",
")",
"{",
"this",
".",
"issueCategories",
".",
"putIfAbsent",
"(",
"MANDATORY",
",",
"new",
"IssueCategory",
"(",
"MANDATORY",
",",
"IssueCategoryRegistry",
".",
"class",
".",
"getCanonicalName",
"(",
")",
",",
"\"Mandatory... | Make sure that we have some reasonable defaults available. These would typically be provided by the rulesets
in the real world. | [
"Make",
"sure",
"that",
"we",
"have",
"some",
"reasonable",
"defaults",
"available",
".",
"These",
"would",
"typically",
"be",
"provided",
"by",
"the",
"rulesets",
"in",
"the",
"real",
"world",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/category/IssueCategoryRegistry.java#L165-L172 | train |
windup/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/MavenStructureRenderer.java | MavenStructureRenderer.renderFreemarkerTemplate | private static void renderFreemarkerTemplate(Path templatePath, Map vars, Path outputPath)
throws IOException, TemplateException
{
if(templatePath == null)
throw new WindupException("templatePath is null");
freemarker.template.Configuration freemarkerConfig = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_26);
DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
objectWrapperBuilder.setUseAdaptersForContainers(true);
objectWrapperBuilder.setIterableSupport(true);
freemarkerConfig.setObjectWrapper(objectWrapperBuilder.build());
freemarkerConfig.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());
Template template = freemarkerConfig.getTemplate(templatePath.toString().replace('\\', '/'));
try (FileWriter fw = new FileWriter(outputPath.toFile()))
{
template.process(vars, fw);
}
} | java | private static void renderFreemarkerTemplate(Path templatePath, Map vars, Path outputPath)
throws IOException, TemplateException
{
if(templatePath == null)
throw new WindupException("templatePath is null");
freemarker.template.Configuration freemarkerConfig = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_26);
DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
objectWrapperBuilder.setUseAdaptersForContainers(true);
objectWrapperBuilder.setIterableSupport(true);
freemarkerConfig.setObjectWrapper(objectWrapperBuilder.build());
freemarkerConfig.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());
Template template = freemarkerConfig.getTemplate(templatePath.toString().replace('\\', '/'));
try (FileWriter fw = new FileWriter(outputPath.toFile()))
{
template.process(vars, fw);
}
} | [
"private",
"static",
"void",
"renderFreemarkerTemplate",
"(",
"Path",
"templatePath",
",",
"Map",
"vars",
",",
"Path",
"outputPath",
")",
"throws",
"IOException",
",",
"TemplateException",
"{",
"if",
"(",
"templatePath",
"==",
"null",
")",
"throw",
"new",
"Windu... | Renders the given FreeMarker template to given directory, using given variables. | [
"Renders",
"the",
"given",
"FreeMarker",
"template",
"to",
"given",
"directory",
"using",
"given",
"variables",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/MavenStructureRenderer.java#L120-L137 | train |
windup/windup | utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java | ExecutionStatistics.get | public static synchronized ExecutionStatistics get()
{
Thread currentThread = Thread.currentThread();
if (stats.get(currentThread) == null)
{
stats.put(currentThread, new ExecutionStatistics());
}
return stats.get(currentThread);
} | java | public static synchronized ExecutionStatistics get()
{
Thread currentThread = Thread.currentThread();
if (stats.get(currentThread) == null)
{
stats.put(currentThread, new ExecutionStatistics());
}
return stats.get(currentThread);
} | [
"public",
"static",
"synchronized",
"ExecutionStatistics",
"get",
"(",
")",
"{",
"Thread",
"currentThread",
"=",
"Thread",
".",
"currentThread",
"(",
")",
";",
"if",
"(",
"stats",
".",
"get",
"(",
"currentThread",
")",
"==",
"null",
")",
"{",
"stats",
".",... | Gets the instance associated with the current thread. | [
"Gets",
"the",
"instance",
"associated",
"with",
"the",
"current",
"thread",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java#L48-L56 | train |
windup/windup | utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java | ExecutionStatistics.merge | public void merge() {
Thread currentThread = Thread.currentThread();
if(!stats.get(currentThread).equals(this) || currentThread instanceof WindupChildThread) {
throw new IllegalArgumentException("Trying to merge executionstatistics from a "
+ "different thread that is not registered as main thread of application run");
}
for (Thread thread : stats.keySet())
{
if(thread instanceof WindupChildThread && ((WindupChildThread) thread).getParentThread().equals(currentThread)) {
merge(stats.get(thread));
}
}
} | java | public void merge() {
Thread currentThread = Thread.currentThread();
if(!stats.get(currentThread).equals(this) || currentThread instanceof WindupChildThread) {
throw new IllegalArgumentException("Trying to merge executionstatistics from a "
+ "different thread that is not registered as main thread of application run");
}
for (Thread thread : stats.keySet())
{
if(thread instanceof WindupChildThread && ((WindupChildThread) thread).getParentThread().equals(currentThread)) {
merge(stats.get(thread));
}
}
} | [
"public",
"void",
"merge",
"(",
")",
"{",
"Thread",
"currentThread",
"=",
"Thread",
".",
"currentThread",
"(",
")",
";",
"if",
"(",
"!",
"stats",
".",
"get",
"(",
"currentThread",
")",
".",
"equals",
"(",
"this",
")",
"||",
"currentThread",
"instanceof",... | Merge this ExecutionStatistics with all the statistics created within the child threads. All the child threads had to be created using Windup-specific
ThreadFactory in order to contain a reference to the parent thread. | [
"Merge",
"this",
"ExecutionStatistics",
"with",
"all",
"the",
"statistics",
"created",
"within",
"the",
"child",
"threads",
".",
"All",
"the",
"child",
"threads",
"had",
"to",
"be",
"created",
"using",
"Windup",
"-",
"specific",
"ThreadFactory",
"in",
"order",
... | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java#L66-L79 | train |
windup/windup | utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java | ExecutionStatistics.merge | private void merge(ExecutionStatistics otherStatistics) {
for (String s : otherStatistics.executionInfo.keySet())
{
TimingData thisStats = this.executionInfo.get(s);
TimingData otherStats = otherStatistics.executionInfo.get(s);
if(thisStats == null) {
this.executionInfo.put(s,otherStats);
} else {
thisStats.merge(otherStats);
}
}
} | java | private void merge(ExecutionStatistics otherStatistics) {
for (String s : otherStatistics.executionInfo.keySet())
{
TimingData thisStats = this.executionInfo.get(s);
TimingData otherStats = otherStatistics.executionInfo.get(s);
if(thisStats == null) {
this.executionInfo.put(s,otherStats);
} else {
thisStats.merge(otherStats);
}
}
} | [
"private",
"void",
"merge",
"(",
"ExecutionStatistics",
"otherStatistics",
")",
"{",
"for",
"(",
"String",
"s",
":",
"otherStatistics",
".",
"executionInfo",
".",
"keySet",
"(",
")",
")",
"{",
"TimingData",
"thisStats",
"=",
"this",
".",
"executionInfo",
".",
... | Merge two ExecutionStatistics into one. This method is private in order not to be synchronized (merging.
@param otherStatistics | [
"Merge",
"two",
"ExecutionStatistics",
"into",
"one",
".",
"This",
"method",
"is",
"private",
"in",
"order",
"not",
"to",
"be",
"synchronized",
"(",
"merging",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java#L85-L97 | train |
windup/windup | utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java | ExecutionStatistics.serializeTimingData | public void serializeTimingData(Path outputPath)
{
//merge subThreads instances into the main instance
merge();
try (FileWriter fw = new FileWriter(outputPath.toFile()))
{
fw.write("Number Of Executions, Total Milliseconds, Milliseconds per execution, Type\n");
for (Map.Entry<String, TimingData> timing : executionInfo.entrySet())
{
TimingData data = timing.getValue();
long totalMillis = (data.totalNanos / 1000000);
double millisPerExecution = (double) totalMillis / (double) data.numberOfExecutions;
fw.write(String.format("%6d, %6d, %8.2f, %s\n",
data.numberOfExecutions, totalMillis, millisPerExecution,
StringEscapeUtils.escapeCsv(timing.getKey())
));
}
}
catch (Exception e)
{
e.printStackTrace();
}
} | java | public void serializeTimingData(Path outputPath)
{
//merge subThreads instances into the main instance
merge();
try (FileWriter fw = new FileWriter(outputPath.toFile()))
{
fw.write("Number Of Executions, Total Milliseconds, Milliseconds per execution, Type\n");
for (Map.Entry<String, TimingData> timing : executionInfo.entrySet())
{
TimingData data = timing.getValue();
long totalMillis = (data.totalNanos / 1000000);
double millisPerExecution = (double) totalMillis / (double) data.numberOfExecutions;
fw.write(String.format("%6d, %6d, %8.2f, %s\n",
data.numberOfExecutions, totalMillis, millisPerExecution,
StringEscapeUtils.escapeCsv(timing.getKey())
));
}
}
catch (Exception e)
{
e.printStackTrace();
}
} | [
"public",
"void",
"serializeTimingData",
"(",
"Path",
"outputPath",
")",
"{",
"//merge subThreads instances into the main instance",
"merge",
"(",
")",
";",
"try",
"(",
"FileWriter",
"fw",
"=",
"new",
"FileWriter",
"(",
"outputPath",
".",
"toFile",
"(",
")",
")",
... | Serializes the timing data to a "~" delimited file at outputPath. | [
"Serializes",
"the",
"timing",
"data",
"to",
"a",
"~",
"delimited",
"file",
"at",
"outputPath",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java#L111-L134 | train |
windup/windup | utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java | ExecutionStatistics.begin | public void begin(String key)
{
if (key == null)
{
return;
}
TimingData data = executionInfo.get(key);
if (data == null)
{
data = new TimingData(key);
executionInfo.put(key, data);
}
data.begin();
} | java | public void begin(String key)
{
if (key == null)
{
return;
}
TimingData data = executionInfo.get(key);
if (data == null)
{
data = new TimingData(key);
executionInfo.put(key, data);
}
data.begin();
} | [
"public",
"void",
"begin",
"(",
"String",
"key",
")",
"{",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"return",
";",
"}",
"TimingData",
"data",
"=",
"executionInfo",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"data",
"==",
"null",
")",
"{",
"dat... | Start timing an operation with the given identifier. | [
"Start",
"timing",
"an",
"operation",
"with",
"the",
"given",
"identifier",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java#L153-L166 | train |
windup/windup | utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java | ExecutionStatistics.end | public void end(String key)
{
if (key == null)
{
return;
}
TimingData data = executionInfo.get(key);
if (data == null)
{
LOG.info("Called end with key: " + key + " without ever calling begin");
return;
}
data.end();
} | java | public void end(String key)
{
if (key == null)
{
return;
}
TimingData data = executionInfo.get(key);
if (data == null)
{
LOG.info("Called end with key: " + key + " without ever calling begin");
return;
}
data.end();
} | [
"public",
"void",
"end",
"(",
"String",
"key",
")",
"{",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"return",
";",
"}",
"TimingData",
"data",
"=",
"executionInfo",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"data",
"==",
"null",
")",
"{",
"LOG",... | Complete timing the operation with the given identifier. If you had not previously started a timing operation with this identifier, then this
will effectively be a noop. | [
"Complete",
"timing",
"the",
"operation",
"with",
"the",
"given",
"identifier",
".",
"If",
"you",
"had",
"not",
"previously",
"started",
"a",
"timing",
"operation",
"with",
"this",
"identifier",
"then",
"this",
"will",
"effectively",
"be",
"a",
"noop",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ExecutionStatistics.java#L172-L185 | train |
windup/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/PackagesToContainingMavenArtifactsIndex.java | PackagesToContainingMavenArtifactsIndex.registerPackageInTypeInterestFactory | private void registerPackageInTypeInterestFactory(String pkg)
{
TypeInterestFactory.registerInterest(pkg + "_pkg", pkg.replace(".", "\\."), pkg, TypeReferenceLocation.IMPORT);
// TODO: Finish the implementation
} | java | private void registerPackageInTypeInterestFactory(String pkg)
{
TypeInterestFactory.registerInterest(pkg + "_pkg", pkg.replace(".", "\\."), pkg, TypeReferenceLocation.IMPORT);
// TODO: Finish the implementation
} | [
"private",
"void",
"registerPackageInTypeInterestFactory",
"(",
"String",
"pkg",
")",
"{",
"TypeInterestFactory",
".",
"registerInterest",
"(",
"pkg",
"+",
"\"_pkg\"",
",",
"pkg",
".",
"replace",
"(",
"\".\"",
",",
"\"\\\\.\"",
")",
",",
"pkg",
",",
"TypeReferen... | So that we get these packages caught Java class analysis. | [
"So",
"that",
"we",
"get",
"these",
"packages",
"caught",
"Java",
"class",
"analysis",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/PackagesToContainingMavenArtifactsIndex.java#L120-L124 | train |
windup/windup | rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/model/XMLDocumentCache.java | XMLDocumentCache.cache | public static void cache(XmlFileModel key, Document document)
{
String cacheKey = getKey(key);
map.put(cacheKey, new CacheDocument(false, document));
} | java | public static void cache(XmlFileModel key, Document document)
{
String cacheKey = getKey(key);
map.put(cacheKey, new CacheDocument(false, document));
} | [
"public",
"static",
"void",
"cache",
"(",
"XmlFileModel",
"key",
",",
"Document",
"document",
")",
"{",
"String",
"cacheKey",
"=",
"getKey",
"(",
"key",
")",
";",
"map",
".",
"put",
"(",
"cacheKey",
",",
"new",
"CacheDocument",
"(",
"false",
",",
"docume... | Add the provided document to the cache. | [
"Add",
"the",
"provided",
"document",
"to",
"the",
"cache",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/model/XMLDocumentCache.java#L51-L55 | train |
windup/windup | rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/model/XMLDocumentCache.java | XMLDocumentCache.cacheParseFailure | public static void cacheParseFailure(XmlFileModel key)
{
map.put(getKey(key), new CacheDocument(true, null));
} | java | public static void cacheParseFailure(XmlFileModel key)
{
map.put(getKey(key), new CacheDocument(true, null));
} | [
"public",
"static",
"void",
"cacheParseFailure",
"(",
"XmlFileModel",
"key",
")",
"{",
"map",
".",
"put",
"(",
"getKey",
"(",
"key",
")",
",",
"new",
"CacheDocument",
"(",
"true",
",",
"null",
")",
")",
";",
"}"
] | Cache a parse failure for this document. | [
"Cache",
"a",
"parse",
"failure",
"for",
"this",
"document",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/model/XMLDocumentCache.java#L60-L63 | train |
windup/windup | rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/model/XMLDocumentCache.java | XMLDocumentCache.get | public static Result get(XmlFileModel key)
{
String cacheKey = getKey(key);
Result result = null;
CacheDocument reference = map.get(cacheKey);
if (reference == null)
return new Result(false, null);
if (reference.parseFailure)
return new Result(true, null);
Document document = reference.getDocument();
if (document == null)
LOG.info("Cache miss on XML document: " + cacheKey);
return new Result(false, document);
} | java | public static Result get(XmlFileModel key)
{
String cacheKey = getKey(key);
Result result = null;
CacheDocument reference = map.get(cacheKey);
if (reference == null)
return new Result(false, null);
if (reference.parseFailure)
return new Result(true, null);
Document document = reference.getDocument();
if (document == null)
LOG.info("Cache miss on XML document: " + cacheKey);
return new Result(false, document);
} | [
"public",
"static",
"Result",
"get",
"(",
"XmlFileModel",
"key",
")",
"{",
"String",
"cacheKey",
"=",
"getKey",
"(",
"key",
")",
";",
"Result",
"result",
"=",
"null",
";",
"CacheDocument",
"reference",
"=",
"map",
".",
"get",
"(",
"cacheKey",
")",
";",
... | Retrieve the currently cached value for the given document. | [
"Retrieve",
"the",
"currently",
"cached",
"value",
"for",
"the",
"given",
"document",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/model/XMLDocumentCache.java#L68-L86 | train |
windup/windup | decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/LineNumberFormatter.java | LineNumberFormatter.reformatFile | public void reformatFile() throws IOException
{
List<LineNumberPosition> lineBrokenPositions = new ArrayList<>();
List<String> brokenLines = breakLines(lineBrokenPositions);
emitFormatted(brokenLines, lineBrokenPositions);
} | java | public void reformatFile() throws IOException
{
List<LineNumberPosition> lineBrokenPositions = new ArrayList<>();
List<String> brokenLines = breakLines(lineBrokenPositions);
emitFormatted(brokenLines, lineBrokenPositions);
} | [
"public",
"void",
"reformatFile",
"(",
")",
"throws",
"IOException",
"{",
"List",
"<",
"LineNumberPosition",
">",
"lineBrokenPositions",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"List",
"<",
"String",
">",
"brokenLines",
"=",
"breakLines",
"(",
"lineBroke... | Rewrites the file passed to 'this' constructor so that the actual line numbers match the recipe passed to 'this'
constructor. | [
"Rewrites",
"the",
"file",
"passed",
"to",
"this",
"constructor",
"so",
"that",
"the",
"actual",
"line",
"numbers",
"match",
"the",
"recipe",
"passed",
"to",
"this",
"constructor",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/decompiler/impl-procyon/src/main/java/org/jboss/windup/decompiler/procyon/LineNumberFormatter.java#L59-L64 | train |
windup/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/operation/packagemapping/PackageNameMapping.java | PackageNameMapping.fromPackage | public static PackageNameMappingWithPackagePattern fromPackage(String packagePattern)
{
PackageNameMapping packageNameMapping = new PackageNameMapping();
packageNameMapping.setPackagePattern(packagePattern);
return packageNameMapping;
} | java | public static PackageNameMappingWithPackagePattern fromPackage(String packagePattern)
{
PackageNameMapping packageNameMapping = new PackageNameMapping();
packageNameMapping.setPackagePattern(packagePattern);
return packageNameMapping;
} | [
"public",
"static",
"PackageNameMappingWithPackagePattern",
"fromPackage",
"(",
"String",
"packagePattern",
")",
"{",
"PackageNameMapping",
"packageNameMapping",
"=",
"new",
"PackageNameMapping",
"(",
")",
";",
"packageNameMapping",
".",
"setPackagePattern",
"(",
"packagePa... | Sets the package pattern to match against. | [
"Sets",
"the",
"package",
"pattern",
"to",
"match",
"against",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/operation/packagemapping/PackageNameMapping.java#L61-L66 | train |
windup/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/operation/packagemapping/PackageNameMapping.java | PackageNameMapping.isExclusivelyKnownArchive | public static boolean isExclusivelyKnownArchive(GraphRewrite event, String filePath)
{
String extension = StringUtils.substringAfterLast(filePath, ".");
if (!StringUtils.equalsIgnoreCase(extension, "jar"))
return false;
ZipFile archive;
try
{
archive = new ZipFile(filePath);
} catch (IOException e)
{
return false;
}
WindupJavaConfigurationService javaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());
WindupJavaConfigurationModel javaConfigurationModel = WindupJavaConfigurationService.getJavaConfigurationModel(event.getGraphContext());
// indicates that the user did specify some packages to scan explicitly (as opposed to scanning everything)
boolean customerPackagesSpecified = javaConfigurationModel.getScanJavaPackages().iterator().hasNext();
// this should only be true if:
// 1) the package does not contain *any* customer packages.
// 2) the package contains "known" vendor packages.
boolean exclusivelyKnown = false;
String organization = null;
Enumeration<?> e = archive.entries();
// go through all entries...
ZipEntry entry;
while (e.hasMoreElements())
{
entry = (ZipEntry) e.nextElement();
String entryName = entry.getName();
if (entry.isDirectory() || !StringUtils.endsWith(entryName, ".class"))
continue;
String classname = PathUtil.classFilePathToClassname(entryName);
// if the package isn't current "known", try to match against known packages for this entry.
if (!exclusivelyKnown)
{
organization = getOrganizationForPackage(event, classname);
if (organization != null)
{
exclusivelyKnown = true;
} else
{
// we couldn't find a package definitively, so ignore the archive
exclusivelyKnown = false;
break;
}
}
// If the user specified package names and this is in those package names, then scan it anyway
if (customerPackagesSpecified && javaConfigurationService.shouldScanPackage(classname))
{
return false;
}
}
if (exclusivelyKnown)
LOG.info("Known Package: " + archive.getName() + "; Organization: " + organization);
// Return the evaluated exclusively known value.
return exclusivelyKnown;
} | java | public static boolean isExclusivelyKnownArchive(GraphRewrite event, String filePath)
{
String extension = StringUtils.substringAfterLast(filePath, ".");
if (!StringUtils.equalsIgnoreCase(extension, "jar"))
return false;
ZipFile archive;
try
{
archive = new ZipFile(filePath);
} catch (IOException e)
{
return false;
}
WindupJavaConfigurationService javaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());
WindupJavaConfigurationModel javaConfigurationModel = WindupJavaConfigurationService.getJavaConfigurationModel(event.getGraphContext());
// indicates that the user did specify some packages to scan explicitly (as opposed to scanning everything)
boolean customerPackagesSpecified = javaConfigurationModel.getScanJavaPackages().iterator().hasNext();
// this should only be true if:
// 1) the package does not contain *any* customer packages.
// 2) the package contains "known" vendor packages.
boolean exclusivelyKnown = false;
String organization = null;
Enumeration<?> e = archive.entries();
// go through all entries...
ZipEntry entry;
while (e.hasMoreElements())
{
entry = (ZipEntry) e.nextElement();
String entryName = entry.getName();
if (entry.isDirectory() || !StringUtils.endsWith(entryName, ".class"))
continue;
String classname = PathUtil.classFilePathToClassname(entryName);
// if the package isn't current "known", try to match against known packages for this entry.
if (!exclusivelyKnown)
{
organization = getOrganizationForPackage(event, classname);
if (organization != null)
{
exclusivelyKnown = true;
} else
{
// we couldn't find a package definitively, so ignore the archive
exclusivelyKnown = false;
break;
}
}
// If the user specified package names and this is in those package names, then scan it anyway
if (customerPackagesSpecified && javaConfigurationService.shouldScanPackage(classname))
{
return false;
}
}
if (exclusivelyKnown)
LOG.info("Known Package: " + archive.getName() + "; Organization: " + organization);
// Return the evaluated exclusively known value.
return exclusivelyKnown;
} | [
"public",
"static",
"boolean",
"isExclusivelyKnownArchive",
"(",
"GraphRewrite",
"event",
",",
"String",
"filePath",
")",
"{",
"String",
"extension",
"=",
"StringUtils",
".",
"substringAfterLast",
"(",
"filePath",
",",
"\".\"",
")",
";",
"if",
"(",
"!",
"StringU... | Indicates that all of the packages within an archive are "known" by the package mapper. Generally
this indicates that the archive does not contain customer code. | [
"Indicates",
"that",
"all",
"of",
"the",
"packages",
"within",
"an",
"archive",
"are",
"known",
"by",
"the",
"package",
"mapper",
".",
"Generally",
"this",
"indicates",
"that",
"the",
"archive",
"does",
"not",
"contain",
"customer",
"code",
"."
] | 6668f09e7f012d24a0b4212ada8809417225b2ad | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/operation/packagemapping/PackageNameMapping.java#L89-L157 | train |
finmath/finmath-lib | src/main/java/net/finmath/montecarlo/interestrate/models/HullWhiteModel.java | HullWhiteModel.getShortRate | private RandomVariable getShortRate(int timeIndex) throws CalculationException {
double time = getProcess().getTime(timeIndex);
double timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time;
double timeNext = getProcess().getTime(timeIndex+1);
RandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time);
RandomVariable alpha = getDV(0, time);
RandomVariable value = getProcess().getProcessValue(timeIndex, 0);
value = value.add(alpha);
// value = value.sub(Math.log(value.exp().getAverage()));
value = value.add(zeroRate);
return value;
} | java | private RandomVariable getShortRate(int timeIndex) throws CalculationException {
double time = getProcess().getTime(timeIndex);
double timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time;
double timeNext = getProcess().getTime(timeIndex+1);
RandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time);
RandomVariable alpha = getDV(0, time);
RandomVariable value = getProcess().getProcessValue(timeIndex, 0);
value = value.add(alpha);
// value = value.sub(Math.log(value.exp().getAverage()));
value = value.add(zeroRate);
return value;
} | [
"private",
"RandomVariable",
"getShortRate",
"(",
"int",
"timeIndex",
")",
"throws",
"CalculationException",
"{",
"double",
"time",
"=",
"getProcess",
"(",
")",
".",
"getTime",
"(",
"timeIndex",
")",
";",
"double",
"timePrev",
"=",
"timeIndex",
">",
"0",
"?",
... | Returns the "short rate" from timeIndex to timeIndex+1.
@param timeIndex The time index (corresponding to {@link getTime()).
@return The "short rate" from timeIndex to timeIndex+1.
@throws CalculationException Thrown if simulation failed. | [
"Returns",
"the",
"short",
"rate",
"from",
"timeIndex",
"to",
"timeIndex",
"+",
"1",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/models/HullWhiteModel.java#L492-L508 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.blackScholesATMOptionValue | public static double blackScholesATMOptionValue(
double volatility,
double optionMaturity,
double forward,
double payoffUnit)
{
if(optionMaturity < 0) {
return 0.0;
}
// Calculate analytic value
double dPlus = 0.5 * volatility * Math.sqrt(optionMaturity);
double dMinus = -dPlus;
double valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit;
return valueAnalytic;
} | java | public static double blackScholesATMOptionValue(
double volatility,
double optionMaturity,
double forward,
double payoffUnit)
{
if(optionMaturity < 0) {
return 0.0;
}
// Calculate analytic value
double dPlus = 0.5 * volatility * Math.sqrt(optionMaturity);
double dMinus = -dPlus;
double valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit;
return valueAnalytic;
} | [
"public",
"static",
"double",
"blackScholesATMOptionValue",
"(",
"double",
"volatility",
",",
"double",
"optionMaturity",
",",
"double",
"forward",
",",
"double",
"payoffUnit",
")",
"{",
"if",
"(",
"optionMaturity",
"<",
"0",
")",
"{",
"return",
"0.0",
";",
"}... | Calculates the Black-Scholes option value of an atm call option.
@param volatility The Black-Scholes volatility.
@param optionMaturity The option maturity T.
@param forward The forward, i.e., the expectation of the index under the measure associated with payoff unit.
@param payoffUnit The payoff unit, i.e., the discount factor or the anuity associated with the payoff.
@return Returns the value of a European at-the-money call option under the Black-Scholes model | [
"Calculates",
"the",
"Black",
"-",
"Scholes",
"option",
"value",
"of",
"an",
"atm",
"call",
"option",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L187-L204 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.blackScholesOptionRho | public static double blackScholesOptionRho(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate rho
double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double rho = optionStrike * optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);
return rho;
}
} | java | public static double blackScholesOptionRho(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate rho
double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double rho = optionStrike * optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);
return rho;
}
} | [
"public",
"static",
"double",
"blackScholesOptionRho",
"(",
"double",
"initialStockValue",
",",
"double",
"riskFreeRate",
",",
"double",
"volatility",
",",
"double",
"optionMaturity",
",",
"double",
"optionStrike",
")",
"{",
"if",
"(",
"optionStrike",
"<=",
"0.0",
... | This static method calculated the rho of a call option under a Black-Scholes model
@param initialStockValue The initial value of the underlying, i.e., the spot.
@param riskFreeRate The risk free rate of the bank account numerarie.
@param volatility The Black-Scholes volatility.
@param optionMaturity The option maturity T.
@param optionStrike The option strike.
@return The rho of the option | [
"This",
"static",
"method",
"calculated",
"the",
"rho",
"of",
"a",
"call",
"option",
"under",
"a",
"Black",
"-",
"Scholes",
"model"
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L447-L468 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.blackScholesDigitalOptionValue | public static double blackScholesDigitalOptionValue(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 1.0;
}
else
{
// Calculate analytic value
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);
return valueAnalytic;
}
} | java | public static double blackScholesDigitalOptionValue(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 1.0;
}
else
{
// Calculate analytic value
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);
return valueAnalytic;
}
} | [
"public",
"static",
"double",
"blackScholesDigitalOptionValue",
"(",
"double",
"initialStockValue",
",",
"double",
"riskFreeRate",
",",
"double",
"volatility",
",",
"double",
"optionMaturity",
",",
"double",
"optionStrike",
")",
"{",
"if",
"(",
"optionStrike",
"<=",
... | Calculates the Black-Scholes option value of a digital call option.
@param initialStockValue The initial value of the underlying, i.e., the spot.
@param riskFreeRate The risk free rate of the bank account numerarie.
@param volatility The Black-Scholes volatility.
@param optionMaturity The option maturity T.
@param optionStrike The option strike.
@return Returns the value of a European call option under the Black-Scholes model | [
"Calculates",
"the",
"Black",
"-",
"Scholes",
"option",
"value",
"of",
"a",
"digital",
"call",
"option",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L543-L565 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.blackScholesDigitalOptionDelta | public static double blackScholesDigitalOptionDelta(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate delta
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);
return delta;
}
} | java | public static double blackScholesDigitalOptionDelta(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate delta
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);
return delta;
}
} | [
"public",
"static",
"double",
"blackScholesDigitalOptionDelta",
"(",
"double",
"initialStockValue",
",",
"double",
"riskFreeRate",
",",
"double",
"volatility",
",",
"double",
"optionMaturity",
",",
"double",
"optionStrike",
")",
"{",
"if",
"(",
"optionStrike",
"<=",
... | Calculates the delta of a digital option under a Black-Scholes model
@param initialStockValue The initial value of the underlying, i.e., the spot.
@param riskFreeRate The risk free rate of the bank account numerarie.
@param volatility The Black-Scholes volatility.
@param optionMaturity The option maturity T.
@param optionStrike The option strike.
@return The delta of the digital option | [
"Calculates",
"the",
"delta",
"of",
"a",
"digital",
"option",
"under",
"a",
"Black",
"-",
"Scholes",
"model"
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L577-L599 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.blackScholesDigitalOptionVega | public static double blackScholesDigitalOptionVega(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate vega
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility;
return vega;
}
} | java | public static double blackScholesDigitalOptionVega(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate vega
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility;
return vega;
}
} | [
"public",
"static",
"double",
"blackScholesDigitalOptionVega",
"(",
"double",
"initialStockValue",
",",
"double",
"riskFreeRate",
",",
"double",
"volatility",
",",
"double",
"optionMaturity",
",",
"double",
"optionStrike",
")",
"{",
"if",
"(",
"optionStrike",
"<=",
... | Calculates the vega of a digital option under a Black-Scholes model
@param initialStockValue The initial value of the underlying, i.e., the spot.
@param riskFreeRate The risk free rate of the bank account numerarie.
@param volatility The Black-Scholes volatility.
@param optionMaturity The option maturity T.
@param optionStrike The option strike.
@return The vega of the digital option | [
"Calculates",
"the",
"vega",
"of",
"a",
"digital",
"option",
"under",
"a",
"Black",
"-",
"Scholes",
"model"
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L611-L633 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.blackScholesDigitalOptionRho | public static double blackScholesDigitalOptionRho(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else if(optionStrike <= 0.0) {
double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity);
return rho;
}
else
{
// Calculate rho
double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus)
+ Math.sqrt(optionMaturity)/volatility * Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI);
return rho;
}
} | java | public static double blackScholesDigitalOptionRho(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else if(optionStrike <= 0.0) {
double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity);
return rho;
}
else
{
// Calculate rho
double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus)
+ Math.sqrt(optionMaturity)/volatility * Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI);
return rho;
}
} | [
"public",
"static",
"double",
"blackScholesDigitalOptionRho",
"(",
"double",
"initialStockValue",
",",
"double",
"riskFreeRate",
",",
"double",
"volatility",
",",
"double",
"optionMaturity",
",",
"double",
"optionStrike",
")",
"{",
"if",
"(",
"optionMaturity",
"<=",
... | Calculates the rho of a digital option under a Black-Scholes model
@param initialStockValue The initial value of the underlying, i.e., the spot.
@param riskFreeRate The risk free rate of the bank account numerarie.
@param volatility The Black-Scholes volatility.
@param optionMaturity The option maturity T.
@param optionStrike The option strike.
@return The rho of the digital option | [
"Calculates",
"the",
"rho",
"of",
"a",
"digital",
"option",
"under",
"a",
"Black",
"-",
"Scholes",
"model"
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L645-L672 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.blackModelCapletValue | public static double blackModelCapletValue(
double forward,
double volatility,
double optionMaturity,
double optionStrike,
double periodLength,
double discountFactor)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor);
} | java | public static double blackModelCapletValue(
double forward,
double volatility,
double optionMaturity,
double optionStrike,
double periodLength,
double discountFactor)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor);
} | [
"public",
"static",
"double",
"blackModelCapletValue",
"(",
"double",
"forward",
",",
"double",
"volatility",
",",
"double",
"optionMaturity",
",",
"double",
"optionStrike",
",",
"double",
"periodLength",
",",
"double",
"discountFactor",
")",
"{",
"// May be interpret... | Calculate the value of a caplet assuming the Black'76 model.
@param forward The forward (spot).
@param volatility The Black'76 volatility.
@param optionMaturity The option maturity
@param optionStrike The option strike.
@param periodLength The period length of the underlying forward rate.
@param discountFactor The discount factor corresponding to the payment date (option maturity + period length).
@return Returns the value of a caplet under the Black'76 model | [
"Calculate",
"the",
"value",
"of",
"a",
"caplet",
"assuming",
"the",
"Black",
"76",
"model",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L685-L695 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.blackModelDgitialCapletValue | public static double blackModelDgitialCapletValue(
double forward,
double volatility,
double periodLength,
double discountFactor,
double optionMaturity,
double optionStrike)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor;
} | java | public static double blackModelDgitialCapletValue(
double forward,
double volatility,
double periodLength,
double discountFactor,
double optionMaturity,
double optionStrike)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor;
} | [
"public",
"static",
"double",
"blackModelDgitialCapletValue",
"(",
"double",
"forward",
",",
"double",
"volatility",
",",
"double",
"periodLength",
",",
"double",
"discountFactor",
",",
"double",
"optionMaturity",
",",
"double",
"optionStrike",
")",
"{",
"// May be in... | Calculate the value of a digital caplet assuming the Black'76 model.
@param forward The forward (spot).
@param volatility The Black'76 volatility.
@param periodLength The period length of the underlying forward rate.
@param discountFactor The discount factor corresponding to the payment date (option maturity + period length).
@param optionMaturity The option maturity
@param optionStrike The option strike.
@return Returns the price of a digital caplet under the Black'76 model | [
"Calculate",
"the",
"value",
"of",
"a",
"digital",
"caplet",
"assuming",
"the",
"Black",
"76",
"model",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L708-L718 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.blackModelSwaptionValue | public static double blackModelSwaptionValue(
double forwardSwaprate,
double volatility,
double optionMaturity,
double optionStrike,
double swapAnnuity)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);
} | java | public static double blackModelSwaptionValue(
double forwardSwaprate,
double volatility,
double optionMaturity,
double optionStrike,
double swapAnnuity)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);
} | [
"public",
"static",
"double",
"blackModelSwaptionValue",
"(",
"double",
"forwardSwaprate",
",",
"double",
"volatility",
",",
"double",
"optionMaturity",
",",
"double",
"optionStrike",
",",
"double",
"swapAnnuity",
")",
"{",
"// May be interpreted as a special version of the... | Calculate the value of a swaption assuming the Black'76 model.
@param forwardSwaprate The forward (spot)
@param volatility The Black'76 volatility.
@param optionMaturity The option maturity.
@param optionStrike The option strike.
@param swapAnnuity The swap annuity corresponding to the underlying swap.
@return Returns the value of a Swaption under the Black'76 model | [
"Calculate",
"the",
"value",
"of",
"a",
"swaption",
"assuming",
"the",
"Black",
"76",
"model",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L730-L739 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.huntKennedyCMSOptionValue | public static double huntKennedyCMSOptionValue(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit,
double optionStrike)
{
double a = 1.0/swapMaturity;
double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;
double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);
double valueUnadjusted = blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);
double valueAdjusted = blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity);
return a * valueUnadjusted + b * forwardSwaprate * valueAdjusted;
} | java | public static double huntKennedyCMSOptionValue(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit,
double optionStrike)
{
double a = 1.0/swapMaturity;
double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;
double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);
double valueUnadjusted = blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);
double valueAdjusted = blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity);
return a * valueUnadjusted + b * forwardSwaprate * valueAdjusted;
} | [
"public",
"static",
"double",
"huntKennedyCMSOptionValue",
"(",
"double",
"forwardSwaprate",
",",
"double",
"volatility",
",",
"double",
"swapAnnuity",
",",
"double",
"optionMaturity",
",",
"double",
"swapMaturity",
",",
"double",
"payoffUnit",
",",
"double",
"optionS... | Calculate the value of a CMS option using the Black-Scholes model for the swap rate together with
the Hunt-Kennedy convexity adjustment.
@param forwardSwaprate The forward swap rate
@param volatility Volatility of the log of the swap rate
@param swapAnnuity The swap annuity
@param optionMaturity The option maturity
@param swapMaturity The swap maturity
@param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
@param optionStrike The option strike
@return Value of the CMS option | [
"Calculate",
"the",
"value",
"of",
"a",
"CMS",
"option",
"using",
"the",
"Black",
"-",
"Scholes",
"model",
"for",
"the",
"swap",
"rate",
"together",
"with",
"the",
"Hunt",
"-",
"Kennedy",
"convexity",
"adjustment",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L908-L925 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.huntKennedyCMSFloorValue | public static double huntKennedyCMSFloorValue(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit,
double optionStrike)
{
double huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);
// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)
return huntKennedyCMSOptionValue + optionStrike * payoffUnit;
} | java | public static double huntKennedyCMSFloorValue(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit,
double optionStrike)
{
double huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);
// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)
return huntKennedyCMSOptionValue + optionStrike * payoffUnit;
} | [
"public",
"static",
"double",
"huntKennedyCMSFloorValue",
"(",
"double",
"forwardSwaprate",
",",
"double",
"volatility",
",",
"double",
"swapAnnuity",
",",
"double",
"optionMaturity",
",",
"double",
"swapMaturity",
",",
"double",
"payoffUnit",
",",
"double",
"optionSt... | Calculate the value of a CMS strike using the Black-Scholes model for the swap rate together with
the Hunt-Kennedy convexity adjustment.
@param forwardSwaprate The forward swap rate
@param volatility Volatility of the log of the swap rate
@param swapAnnuity The swap annuity
@param optionMaturity The option maturity
@param swapMaturity The swap maturity
@param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
@param optionStrike The option strike
@return Value of the CMS strike | [
"Calculate",
"the",
"value",
"of",
"a",
"CMS",
"strike",
"using",
"the",
"Black",
"-",
"Scholes",
"model",
"for",
"the",
"swap",
"rate",
"together",
"with",
"the",
"Hunt",
"-",
"Kennedy",
"convexity",
"adjustment",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L940-L953 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.huntKennedyCMSAdjustedRate | public static double huntKennedyCMSAdjustedRate(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit)
{
double a = 1.0/swapMaturity;
double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;
double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);
double rateUnadjusted = forwardSwaprate;
double rateAdjusted = forwardSwaprate * convexityAdjustment;
return (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit;
} | java | public static double huntKennedyCMSAdjustedRate(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit)
{
double a = 1.0/swapMaturity;
double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;
double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);
double rateUnadjusted = forwardSwaprate;
double rateAdjusted = forwardSwaprate * convexityAdjustment;
return (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit;
} | [
"public",
"static",
"double",
"huntKennedyCMSAdjustedRate",
"(",
"double",
"forwardSwaprate",
",",
"double",
"volatility",
",",
"double",
"swapAnnuity",
",",
"double",
"optionMaturity",
",",
"double",
"swapMaturity",
",",
"double",
"payoffUnit",
")",
"{",
"double",
... | Calculate the adjusted forward swaprate corresponding to a change of payoff unit from the given swapAnnuity to the given payoffUnit
using the Black-Scholes model for the swap rate together with the Hunt-Kennedy convexity adjustment.
@param forwardSwaprate The forward swap rate
@param volatility Volatility of the log of the swap rate
@param swapAnnuity The swap annuity
@param optionMaturity The option maturity
@param swapMaturity The swap maturity
@param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
@return Convexity adjusted forward rate | [
"Calculate",
"the",
"adjusted",
"forward",
"swaprate",
"corresponding",
"to",
"a",
"change",
"of",
"payoff",
"unit",
"from",
"the",
"given",
"swapAnnuity",
"to",
"the",
"given",
"payoffUnit",
"using",
"the",
"Black",
"-",
"Scholes",
"model",
"for",
"the",
"swa... | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L967-L983 | train |
finmath/finmath-lib | src/main/java6/net/finmath/functions/AnalyticFormulas.java | AnalyticFormulas.volatilityConversionLognormalATMtoNormalATM | public static double volatilityConversionLognormalATMtoNormalATM(double forward, double displacement, double maturity, double lognormalVolatiltiy) {
double x = lognormalVolatiltiy * Math.sqrt(maturity / 8);
double y = org.apache.commons.math3.special.Erf.erf(x);
double normalVol = Math.sqrt(2*Math.PI / maturity) * (forward+displacement) * y;
return normalVol;
} | java | public static double volatilityConversionLognormalATMtoNormalATM(double forward, double displacement, double maturity, double lognormalVolatiltiy) {
double x = lognormalVolatiltiy * Math.sqrt(maturity / 8);
double y = org.apache.commons.math3.special.Erf.erf(x);
double normalVol = Math.sqrt(2*Math.PI / maturity) * (forward+displacement) * y;
return normalVol;
} | [
"public",
"static",
"double",
"volatilityConversionLognormalATMtoNormalATM",
"(",
"double",
"forward",
",",
"double",
"displacement",
",",
"double",
"maturity",
",",
"double",
"lognormalVolatiltiy",
")",
"{",
"double",
"x",
"=",
"lognormalVolatiltiy",
"*",
"Math",
"."... | Exact conversion of displaced lognormal ATM volatiltiy to normal ATM volatility.
@param forward The forward
@param displacement The displacement (considering a displaced lognormal model, otherwise 0.
@param maturity The maturity
@param lognormalVolatiltiy The (implied) lognormal volatility.
@return The (implied) normal volatility.
@see <a href="http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2687742">Dimitroff, Fries, Lichtner and Rodi: Lognormal vs Normal Volatilities and Sensitivities in Practice</a> | [
"Exact",
"conversion",
"of",
"displaced",
"lognormal",
"ATM",
"volatiltiy",
"to",
"normal",
"ATM",
"volatility",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L1301-L1307 | train |
finmath/finmath-lib | src/main/java/net/finmath/modelling/descriptor/xmlparser/FIPXMLParser.java | FIPXMLParser.getSwapLegProductDescriptor | private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName,
DayCountConvention daycountConvention) {
boolean isFixed = leg.getElementsByTagName("interestType").item(0).getTextContent().equalsIgnoreCase("FIX");
ArrayList<Period> periods = new ArrayList<>();
ArrayList<Double> notionalsList = new ArrayList<>();
ArrayList<Double> rates = new ArrayList<>();
//extracting data for each period
NodeList periodsXML = leg.getElementsByTagName("incomePayment");
for(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) {
Element periodXML = (Element) periodsXML.item(periodIndex);
LocalDate startDate = LocalDate.parse(periodXML.getElementsByTagName("startDate").item(0).getTextContent());
LocalDate endDate = LocalDate.parse(periodXML.getElementsByTagName("endDate").item(0).getTextContent());
LocalDate fixingDate = startDate;
LocalDate paymentDate = LocalDate.parse(periodXML.getElementsByTagName("payDate").item(0).getTextContent());
if(! isFixed) {
fixingDate = LocalDate.parse(periodXML.getElementsByTagName("fixingDate").item(0).getTextContent());
}
periods.add(new Period(fixingDate, paymentDate, startDate, endDate));
double notional = Double.parseDouble(periodXML.getElementsByTagName("nominal").item(0).getTextContent());
notionalsList.add(new Double(notional));
if(isFixed) {
double fixedRate = Double.parseDouble(periodXML.getElementsByTagName("fixedRate").item(0).getTextContent());
rates.add(new Double(fixedRate));
} else {
rates.add(new Double(0));
}
}
ScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention);
double[] notionals = notionalsList.stream().mapToDouble(Double::doubleValue).toArray();
double[] spreads = rates.stream().mapToDouble(Double::doubleValue).toArray();
return new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false);
} | java | private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName,
DayCountConvention daycountConvention) {
boolean isFixed = leg.getElementsByTagName("interestType").item(0).getTextContent().equalsIgnoreCase("FIX");
ArrayList<Period> periods = new ArrayList<>();
ArrayList<Double> notionalsList = new ArrayList<>();
ArrayList<Double> rates = new ArrayList<>();
//extracting data for each period
NodeList periodsXML = leg.getElementsByTagName("incomePayment");
for(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) {
Element periodXML = (Element) periodsXML.item(periodIndex);
LocalDate startDate = LocalDate.parse(periodXML.getElementsByTagName("startDate").item(0).getTextContent());
LocalDate endDate = LocalDate.parse(periodXML.getElementsByTagName("endDate").item(0).getTextContent());
LocalDate fixingDate = startDate;
LocalDate paymentDate = LocalDate.parse(periodXML.getElementsByTagName("payDate").item(0).getTextContent());
if(! isFixed) {
fixingDate = LocalDate.parse(periodXML.getElementsByTagName("fixingDate").item(0).getTextContent());
}
periods.add(new Period(fixingDate, paymentDate, startDate, endDate));
double notional = Double.parseDouble(periodXML.getElementsByTagName("nominal").item(0).getTextContent());
notionalsList.add(new Double(notional));
if(isFixed) {
double fixedRate = Double.parseDouble(periodXML.getElementsByTagName("fixedRate").item(0).getTextContent());
rates.add(new Double(fixedRate));
} else {
rates.add(new Double(0));
}
}
ScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention);
double[] notionals = notionalsList.stream().mapToDouble(Double::doubleValue).toArray();
double[] spreads = rates.stream().mapToDouble(Double::doubleValue).toArray();
return new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false);
} | [
"private",
"static",
"InterestRateSwapLegProductDescriptor",
"getSwapLegProductDescriptor",
"(",
"Element",
"leg",
",",
"String",
"forwardCurveName",
",",
"String",
"discountCurveName",
",",
"DayCountConvention",
"daycountConvention",
")",
"{",
"boolean",
"isFixed",
"=",
"l... | Construct an InterestRateSwapLegProductDescriptor from a node in a FIPXML file.
@param leg The node containing the leg.
@param forwardCurveName Forward curve name form outside the node.
@param discountCurveName Discount curve name form outside the node.
@param daycountConvention Daycount convention from outside the node.
@return Descriptor of the swap leg. | [
"Construct",
"an",
"InterestRateSwapLegProductDescriptor",
"from",
"a",
"node",
"in",
"a",
"FIPXML",
"file",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/modelling/descriptor/xmlparser/FIPXMLParser.java#L152-L196 | train |
finmath/finmath-lib | src/main/java/net/finmath/modelling/productfactory/InterestRateMonteCarloProductFactory.java | InterestRateMonteCarloProductFactory.constructLiborIndex | private static AbstractIndex constructLiborIndex(String forwardCurveName, Schedule schedule) {
if(forwardCurveName != null) {
//determine average fixing offset and period length
double fixingOffset = 0;
double periodLength = 0;
for(int i = 0; i < schedule.getNumberOfPeriods(); i++) {
fixingOffset *= ((double) i) / (i+1);
fixingOffset += (schedule.getPeriodStart(i) - schedule.getFixing(i)) / (i+1);
periodLength *= ((double) i) / (i+1);
periodLength += schedule.getPeriodLength(i) / (i+1);
}
return new LIBORIndex(forwardCurveName, fixingOffset, periodLength);
} else {
return null;
}
} | java | private static AbstractIndex constructLiborIndex(String forwardCurveName, Schedule schedule) {
if(forwardCurveName != null) {
//determine average fixing offset and period length
double fixingOffset = 0;
double periodLength = 0;
for(int i = 0; i < schedule.getNumberOfPeriods(); i++) {
fixingOffset *= ((double) i) / (i+1);
fixingOffset += (schedule.getPeriodStart(i) - schedule.getFixing(i)) / (i+1);
periodLength *= ((double) i) / (i+1);
periodLength += schedule.getPeriodLength(i) / (i+1);
}
return new LIBORIndex(forwardCurveName, fixingOffset, periodLength);
} else {
return null;
}
} | [
"private",
"static",
"AbstractIndex",
"constructLiborIndex",
"(",
"String",
"forwardCurveName",
",",
"Schedule",
"schedule",
")",
"{",
"if",
"(",
"forwardCurveName",
"!=",
"null",
")",
"{",
"//determine average fixing offset and period length",
"double",
"fixingOffset",
"... | Construct a Libor index for a given curve and schedule.
@param forwardCurveName
@param schedule
@return The Libor index or null, if forwardCurveName is null. | [
"Construct",
"a",
"Libor",
"index",
"for",
"a",
"given",
"curve",
"and",
"schedule",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/modelling/productfactory/InterestRateMonteCarloProductFactory.java#L88-L108 | train |
finmath/finmath-lib | src/main/java/net/finmath/montecarlo/interestrate/products/SwaptionATM.java | SwaptionATM.getImpliedBachelierATMOptionVolatility | public RandomVariable getImpliedBachelierATMOptionVolatility(RandomVariable optionValue, double optionMaturity, double swapAnnuity){
return optionValue.average().mult(Math.sqrt(2.0 * Math.PI / optionMaturity) / swapAnnuity);
} | java | public RandomVariable getImpliedBachelierATMOptionVolatility(RandomVariable optionValue, double optionMaturity, double swapAnnuity){
return optionValue.average().mult(Math.sqrt(2.0 * Math.PI / optionMaturity) / swapAnnuity);
} | [
"public",
"RandomVariable",
"getImpliedBachelierATMOptionVolatility",
"(",
"RandomVariable",
"optionValue",
",",
"double",
"optionMaturity",
",",
"double",
"swapAnnuity",
")",
"{",
"return",
"optionValue",
".",
"average",
"(",
")",
".",
"mult",
"(",
"Math",
".",
"sq... | Calculates ATM Bachelier implied volatilities.
@see net.finmath.functions.AnalyticFormulas#bachelierOptionImpliedVolatility(double, double, double, double, double)
@param optionValue RandomVarable representing the value of the option
@param optionMaturity Time to maturity.
@param swapAnnuity The swap annuity as seen on valuation time.
@return The Bachelier implied volatility. | [
"Calculates",
"ATM",
"Bachelier",
"implied",
"volatilities",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/SwaptionATM.java#L73-L75 | train |
finmath/finmath-lib | src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaption.java | BermudanSwaption.getBasisFunctions | public RandomVariable[] getBasisFunctions(double fixingDate, LIBORModelMonteCarloSimulationModel model) throws CalculationException {
ArrayList<RandomVariable> basisFunctions = new ArrayList<>();
// Constant
RandomVariable basisFunction = new RandomVariableFromDoubleArray(1.0);//.getRandomVariableForConstant(1.0);
basisFunctions.add(basisFunction);
int fixingDateIndex = Arrays.binarySearch(fixingDates, fixingDate);
if(fixingDateIndex < 0) {
fixingDateIndex = -fixingDateIndex;
}
if(fixingDateIndex >= fixingDates.length) {
fixingDateIndex = fixingDates.length-1;
}
// forward rate to the next period
RandomVariable rateShort = model.getLIBOR(fixingDate, fixingDate, paymentDates[fixingDateIndex]);
RandomVariable discountShort = rateShort.mult(paymentDates[fixingDateIndex]-fixingDate).add(1.0).invert();
basisFunctions.add(discountShort);
basisFunctions.add(discountShort.pow(2.0));
// basisFunctions.add(rateShort.pow(3.0));
// forward rate to the end of the product
RandomVariable rateLong = model.getLIBOR(fixingDate, fixingDates[fixingDateIndex], paymentDates[paymentDates.length-1]);
RandomVariable discountLong = rateLong.mult(paymentDates[paymentDates.length-1]-fixingDates[fixingDateIndex]).add(1.0).invert();
basisFunctions.add(discountLong);
basisFunctions.add(discountLong.pow(2.0));
// basisFunctions.add(rateLong.pow(3.0));
// Numeraire
RandomVariable numeraire = model.getNumeraire(fixingDate).invert();
basisFunctions.add(numeraire);
// basisFunctions.add(numeraire.pow(2.0));
// basisFunctions.add(numeraire.pow(3.0));
return basisFunctions.toArray(new RandomVariable[basisFunctions.size()]);
} | java | public RandomVariable[] getBasisFunctions(double fixingDate, LIBORModelMonteCarloSimulationModel model) throws CalculationException {
ArrayList<RandomVariable> basisFunctions = new ArrayList<>();
// Constant
RandomVariable basisFunction = new RandomVariableFromDoubleArray(1.0);//.getRandomVariableForConstant(1.0);
basisFunctions.add(basisFunction);
int fixingDateIndex = Arrays.binarySearch(fixingDates, fixingDate);
if(fixingDateIndex < 0) {
fixingDateIndex = -fixingDateIndex;
}
if(fixingDateIndex >= fixingDates.length) {
fixingDateIndex = fixingDates.length-1;
}
// forward rate to the next period
RandomVariable rateShort = model.getLIBOR(fixingDate, fixingDate, paymentDates[fixingDateIndex]);
RandomVariable discountShort = rateShort.mult(paymentDates[fixingDateIndex]-fixingDate).add(1.0).invert();
basisFunctions.add(discountShort);
basisFunctions.add(discountShort.pow(2.0));
// basisFunctions.add(rateShort.pow(3.0));
// forward rate to the end of the product
RandomVariable rateLong = model.getLIBOR(fixingDate, fixingDates[fixingDateIndex], paymentDates[paymentDates.length-1]);
RandomVariable discountLong = rateLong.mult(paymentDates[paymentDates.length-1]-fixingDates[fixingDateIndex]).add(1.0).invert();
basisFunctions.add(discountLong);
basisFunctions.add(discountLong.pow(2.0));
// basisFunctions.add(rateLong.pow(3.0));
// Numeraire
RandomVariable numeraire = model.getNumeraire(fixingDate).invert();
basisFunctions.add(numeraire);
// basisFunctions.add(numeraire.pow(2.0));
// basisFunctions.add(numeraire.pow(3.0));
return basisFunctions.toArray(new RandomVariable[basisFunctions.size()]);
} | [
"public",
"RandomVariable",
"[",
"]",
"getBasisFunctions",
"(",
"double",
"fixingDate",
",",
"LIBORModelMonteCarloSimulationModel",
"model",
")",
"throws",
"CalculationException",
"{",
"ArrayList",
"<",
"RandomVariable",
">",
"basisFunctions",
"=",
"new",
"ArrayList",
"... | Return the basis functions for the regression suitable for this product.
@param fixingDate The condition time.
@param model The model
@return The basis functions for the regression suitable for this product.
@throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. | [
"Return",
"the",
"basis",
"functions",
"for",
"the",
"regression",
"suitable",
"for",
"this",
"product",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaption.java#L214-L251 | train |
finmath/finmath-lib | src/main/java6/net/finmath/montecarlo/interestrate/LIBORMarketModelStandard.java | LIBORMarketModelStandard.getDrift | private RandomVariableInterface getDrift(int timeIndex, int componentIndex, RandomVariableInterface[] realizationAtTimeIndex, RandomVariableInterface[] realizationPredictor) {
// Check if this LIBOR is already fixed
if(getTime(timeIndex) >= this.getLiborPeriod(componentIndex)) {
return null;
}
/*
* We implemented several different methods to calculate the drift
*/
if(driftApproximationMethod == Driftapproximation.PREDICTOR_CORRECTOR && realizationPredictor != null) {
RandomVariableInterface drift = getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex);
RandomVariableInterface driftEulerWithPredictor = getDriftEuler(timeIndex, componentIndex, realizationPredictor);
drift = drift.add(driftEulerWithPredictor).div(2.0);
return drift;
}
else if(driftApproximationMethod == Driftapproximation.LINE_INTEGRAL && realizationPredictor != null) {
return getDriftLineIntegral(timeIndex, componentIndex, realizationAtTimeIndex, realizationPredictor);
}
else {
return getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex);
}
} | java | private RandomVariableInterface getDrift(int timeIndex, int componentIndex, RandomVariableInterface[] realizationAtTimeIndex, RandomVariableInterface[] realizationPredictor) {
// Check if this LIBOR is already fixed
if(getTime(timeIndex) >= this.getLiborPeriod(componentIndex)) {
return null;
}
/*
* We implemented several different methods to calculate the drift
*/
if(driftApproximationMethod == Driftapproximation.PREDICTOR_CORRECTOR && realizationPredictor != null) {
RandomVariableInterface drift = getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex);
RandomVariableInterface driftEulerWithPredictor = getDriftEuler(timeIndex, componentIndex, realizationPredictor);
drift = drift.add(driftEulerWithPredictor).div(2.0);
return drift;
}
else if(driftApproximationMethod == Driftapproximation.LINE_INTEGRAL && realizationPredictor != null) {
return getDriftLineIntegral(timeIndex, componentIndex, realizationAtTimeIndex, realizationPredictor);
}
else {
return getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex);
}
} | [
"private",
"RandomVariableInterface",
"getDrift",
"(",
"int",
"timeIndex",
",",
"int",
"componentIndex",
",",
"RandomVariableInterface",
"[",
"]",
"realizationAtTimeIndex",
",",
"RandomVariableInterface",
"[",
"]",
"realizationPredictor",
")",
"{",
"// Check if this LIBOR i... | Alternative implementation for the drift. For experimental purposes.
@param timeIndex
@param componentIndex
@param realizationAtTimeIndex
@param realizationPredictor
@return | [
"Alternative",
"implementation",
"for",
"the",
"drift",
".",
"For",
"experimental",
"purposes",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/interestrate/LIBORMarketModelStandard.java#L638-L661 | train |
finmath/finmath-lib | src/main/java6/net/finmath/randomnumbers/HaltonSequence.java | HaltonSequence.getHaltonNumberForGivenBase | public static double getHaltonNumberForGivenBase(long index, int base) {
index += 1;
double x = 0.0;
double factor = 1.0 / base;
while(index > 0) {
x += (index % base) * factor;
factor /= base;
index /= base;
}
return x;
} | java | public static double getHaltonNumberForGivenBase(long index, int base) {
index += 1;
double x = 0.0;
double factor = 1.0 / base;
while(index > 0) {
x += (index % base) * factor;
factor /= base;
index /= base;
}
return x;
} | [
"public",
"static",
"double",
"getHaltonNumberForGivenBase",
"(",
"long",
"index",
",",
"int",
"base",
")",
"{",
"index",
"+=",
"1",
";",
"double",
"x",
"=",
"0.0",
";",
"double",
"factor",
"=",
"1.0",
"/",
"base",
";",
"while",
"(",
"index",
">",
"0",... | Return a Halton number, sequence starting at index = 0, base > 1.
@param index The index of the sequence.
@param base The base of the sequence. Has to be greater than one (this is not checked).
@return The Halton number. | [
"Return",
"a",
"Halton",
"number",
"sequence",
"starting",
"at",
"index",
"=",
"0",
"base",
">",
";",
"1",
"."
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/randomnumbers/HaltonSequence.java#L66-L78 | train |
finmath/finmath-lib | src/main/java/net/finmath/montecarlo/automaticdifferentiation/backward/alternative/RandomVariableAAD.java | RandomVariableAAD.getGradient | public Map<Integer, RandomVariable> getGradient(){
int numberOfCalculationSteps = getFunctionList().size();
RandomVariable[] omegaHat = new RandomVariable[numberOfCalculationSteps];
omegaHat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);
for(int variableIndex = numberOfCalculationSteps-2; variableIndex >= 0; variableIndex--){
omegaHat[variableIndex] = new RandomVariableFromDoubleArray(0.0);
ArrayList<Integer> childrenList = getAADRandomVariableFromList(variableIndex).getChildrenIndices();
for(int functionIndex:childrenList){
RandomVariable D_i_j = getPartialDerivative(functionIndex, variableIndex);
omegaHat[variableIndex] = omegaHat[variableIndex].addProduct(D_i_j, omegaHat[functionIndex]);
}
}
ArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables();
Map<Integer, RandomVariable> gradient = new HashMap<Integer, RandomVariable>();
for(Integer indexOfDependentRandomVariable: arrayListOfAllIndicesOfDependentRandomVariables){
gradient.put(indexOfDependentRandomVariable, omegaHat[arrayListOfAllIndicesOfDependentRandomVariables.get(indexOfDependentRandomVariable)]);
}
return gradient;
} | java | public Map<Integer, RandomVariable> getGradient(){
int numberOfCalculationSteps = getFunctionList().size();
RandomVariable[] omegaHat = new RandomVariable[numberOfCalculationSteps];
omegaHat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);
for(int variableIndex = numberOfCalculationSteps-2; variableIndex >= 0; variableIndex--){
omegaHat[variableIndex] = new RandomVariableFromDoubleArray(0.0);
ArrayList<Integer> childrenList = getAADRandomVariableFromList(variableIndex).getChildrenIndices();
for(int functionIndex:childrenList){
RandomVariable D_i_j = getPartialDerivative(functionIndex, variableIndex);
omegaHat[variableIndex] = omegaHat[variableIndex].addProduct(D_i_j, omegaHat[functionIndex]);
}
}
ArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables();
Map<Integer, RandomVariable> gradient = new HashMap<Integer, RandomVariable>();
for(Integer indexOfDependentRandomVariable: arrayListOfAllIndicesOfDependentRandomVariables){
gradient.put(indexOfDependentRandomVariable, omegaHat[arrayListOfAllIndicesOfDependentRandomVariables.get(indexOfDependentRandomVariable)]);
}
return gradient;
} | [
"public",
"Map",
"<",
"Integer",
",",
"RandomVariable",
">",
"getGradient",
"(",
")",
"{",
"int",
"numberOfCalculationSteps",
"=",
"getFunctionList",
"(",
")",
".",
"size",
"(",
")",
";",
"RandomVariable",
"[",
"]",
"omegaHat",
"=",
"new",
"RandomVariable",
... | Implements the AAD Algorithm
@return HashMap where the key is the internal index of the random variable with respect to which the partial derivative was computed. This key then gives access to the actual derivative. | [
"Implements",
"the",
"AAD",
"Algorithm"
] | a3c067d52dd33feb97d851df6cab130e4116759f | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/automaticdifferentiation/backward/alternative/RandomVariableAAD.java#L529-L558 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.