code
stringlengths
73
34.1k
label
stringclasses
1 value
@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(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
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 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
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
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
@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
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 AnnotationTypeCondition addCondition(String element, AnnotationCondition condition) { this.conditions.put(element, condition); return this; }
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; }
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())); } }
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(); }
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; }
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); } }
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); }
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); } }
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(); }
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; }
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; }
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; }
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; }
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; }
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()); }
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); } }
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); } }
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); }
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); }
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; }
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; }
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; }
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; }
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; }
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; }
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(); }
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()); }
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); } }
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; }
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); } }
java
public List<Tag> getPrimeTags() { return this.definedTags.values().stream() .filter(Tag::isPrime) .collect(Collectors.toList()); }
java
public List<Tag> getRootTags() { return this.definedTags.values().stream() .filter(Tag::isRoot) .collect(Collectors.toList()); }
java
public Set<Tag> getAncestorTags(Tag tag) { Set<Tag> ancestors = new HashSet<>(); getAncestorTags(tag, ancestors); return ancestors; }
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"); }
java
public Path getReportDirectory() { WindupConfigurationModel cfg = WindupConfigurationService.getConfigurationModel(getGraphContext()); Path path = cfg.getOutputPath().asFile().toPath().resolve(REPORTS_DIR); createDirectoryIfNeeded(path); return path.toAbsolutePath(); }
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()); } }
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; }
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); } }
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; }
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; }
java
public static Artifact withVersion(Version v) { Artifact artifact = new Artifact(); artifact.version = v; return artifact; }
java
public static Artifact withGroupId(String groupId) { Artifact artifact = new Artifact(); artifact.groupId = new RegexParameterizedPatternParser(groupId); return artifact; }
java
public static Artifact withArtifactId(String artifactId) { Artifact artifact = new Artifact(); artifact.artifactId = new RegexParameterizedPatternParser(artifactId); return artifact; }
java
public void setSingletonVariable(String name, WindupVertexFrame frame) { setVariable(name, Collections.singletonList(frame)); }
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); }
java
public void removeVariable(String name) { Map<String, Iterable<? extends WindupVertexFrame>> frame = peek(); frame.remove(name); }
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; }
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; }
java
protected void checkVariableName(GraphRewrite event, EvaluationContext context) { if (getInputVariablesName() == null) { setInputVariablesName(Iteration.getPayloadVariableName(event, context)); } }
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; }
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; }
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; }
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); } }
java
@Override public void perform(Rewrite event, EvaluationContext context) { perform((GraphRewrite) event, context); }
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; }
java
public List<IssueCategory> getIssueCategories() { return this.issueCategories.values().stream() .sorted((category1, category2) -> category1.getPriority() - category2.getPriority()) .collect(Collectors.toList()); }
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)); }
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); } }
java
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 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
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
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 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 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
private void registerPackageInTypeInterestFactory(String pkg) { TypeInterestFactory.registerInterest(pkg + "_pkg", pkg.replace(".", "\\."), pkg, TypeReferenceLocation.IMPORT); // TODO: Finish the implementation }
java
public static void cache(XmlFileModel key, Document document) { String cacheKey = getKey(key); map.put(cacheKey, new CacheDocument(false, document)); }
java
public static void cacheParseFailure(XmlFileModel key) { map.put(getKey(key), new CacheDocument(true, null)); }
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); }
java
public void reformatFile() throws IOException { List<LineNumberPosition> lineBrokenPositions = new ArrayList<>(); List<String> brokenLines = breakLines(lineBrokenPositions); emitFormatted(brokenLines, lineBrokenPositions); }
java
public static PackageNameMappingWithPackagePattern fromPackage(String packagePattern) { PackageNameMapping packageNameMapping = new PackageNameMapping(); packageNameMapping.setPackagePattern(packagePattern); return packageNameMapping; }
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; }
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; }
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; }
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; } }
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; } }
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; } }
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; } }
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; } }
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); }
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; }
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); }
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; }
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; }
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; }
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; }
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); }
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; } }
java
public RandomVariable getImpliedBachelierATMOptionVolatility(RandomVariable optionValue, double optionMaturity, double swapAnnuity){ return optionValue.average().mult(Math.sqrt(2.0 * Math.PI / optionMaturity) / swapAnnuity); }
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()]); }
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); } }
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; }
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; }
java