idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
146,400 | public static boolean xpathExists ( Node document , String xpathExpression , Map < String , String > namespaceMapping ) throws XPathException , MarshallingException { Boolean result = ( Boolean ) executeXPath ( document , xpathExpression , namespaceMapping , XPathConstants . BOOLEAN ) ; return result != null && result ; } | Runs the given xpath and returns a boolean result . | 76 | 12 |
146,401 | public static Object executeXPath ( Node document , String xpathExpression , Map < String , String > namespaceMapping , QName result ) throws XPathException , MarshallingException { NamespaceMapContext mapContext = new NamespaceMapContext ( namespaceMapping ) ; try { XPathFactory xPathfactory = XPathFactory . newInstance ( ) ; XPath xpath = xPathfactory . newXPath ( ) ; xpath . setNamespaceContext ( mapContext ) ; XPathExpression expr = xpath . compile ( xpathExpression ) ; return executeXPath ( document , expr , result ) ; } catch ( XPathExpressionException e ) { throw new XPathException ( "Xpath(" + xpathExpression + ") cannot be compiled" , e ) ; } catch ( Exception e ) { throw new MarshallingException ( "Exception unmarshalling XML." , e ) ; } } | Executes the given xpath and returns the result with the type specified . | 196 | 15 |
146,402 | String deriveGroupIdFromPackages ( ProjectModel projectModel ) { Map < Object , Long > pkgsMap = new HashMap <> ( ) ; Set < String > pkgs = new HashSet <> ( 1000 ) ; GraphTraversal < Vertex , Vertex > pipeline = new GraphTraversalSource ( graphContext . getGraph ( ) ) . V ( projectModel ) ; pkgsMap = pipeline . out ( ProjectModel . PROJECT_MODEL_TO_FILE ) . has ( WindupVertexFrame . TYPE_PROP , new P ( new BiPredicate < String , String > ( ) { @ Override public boolean test ( String o , String o2 ) { return o . contains ( o2 ) ; } } , GraphTypeManager . getTypeValue ( JavaClassFileModel . class ) ) ) . hasKey ( JavaClassFileModel . PROPERTY_PACKAGE_NAME ) . groupCount ( ) . by ( v -> upToThirdDot ( graphContext , ( Vertex ) v ) ) . toList ( ) . get ( 0 ) ; Map . Entry < Object , Long > biggest = null ; for ( Map . Entry < Object , Long > entry : pkgsMap . entrySet ( ) ) { if ( biggest == null || biggest . getValue ( ) < entry . getValue ( ) ) biggest = entry ; } // More than a half is of this package. if ( biggest != null && biggest . getValue ( ) > pkgsMap . size ( ) / 2 ) return biggest . getKey ( ) . toString ( ) ; return null ; } | Counts the packages prefixes appearing in this project and if some of them make more than half of the total of existing packages this prefix is returned . Otherwise returns null . | 347 | 34 |
146,403 | @ Override public JavaClassBuilderAt at ( TypeReferenceLocation ... locations ) { if ( locations != null ) this . locations = Arrays . asList ( locations ) ; return this ; } | Only match if the TypeReference is at the specified location within the file . | 40 | 15 |
146,404 | @ Override public ConditionBuilder as ( String variable ) { Assert . notNull ( variable , "Variable name must not be null." ) ; this . setOutputVariablesName ( variable ) ; return this ; } | Optionally specify the variable name to use for the output of this condition | 45 | 14 |
146,405 | protected void setResults ( GraphRewrite event , String variable , Iterable < ? extends WindupVertexFrame > results ) { Variables variables = Variables . instance ( event ) ; Iterable < ? extends WindupVertexFrame > existingVariables = variables . findVariable ( variable , 1 ) ; if ( existingVariables != null ) { variables . setVariable ( variable , Iterables . concat ( existingVariables , results ) ) ; } else { variables . setVariable ( variable , results ) ; } } | This sets the variable with the given name to the given value . If there is already a variable with the same name in the top - most stack frame we will combine them here . | 109 | 36 |
146,406 | private Map < String , Class < ? extends RulePhase > > loadPhases ( ) { Map < String , Class < ? extends RulePhase > > phases ; phases = new HashMap <> ( ) ; Furnace furnace = FurnaceHolder . getFurnace ( ) ; for ( RulePhase phase : furnace . getAddonRegistry ( ) . getServices ( RulePhase . class ) ) { @ SuppressWarnings ( "unchecked" ) Class < ? extends RulePhase > unwrappedClass = ( Class < ? extends RulePhase > ) Proxies . unwrap ( phase ) . getClass ( ) ; String simpleName = unwrappedClass . getSimpleName ( ) ; phases . put ( classNameToMapKey ( simpleName ) , unwrappedClass ) ; } return Collections . unmodifiableMap ( phases ) ; } | Loads the currently known phases from Furnace to the map . | 181 | 13 |
146,407 | private void allInput ( List < FileModel > vertices , GraphRewrite event , ParameterStore store ) { if ( StringUtils . isBlank ( getInputVariablesName ( ) ) && this . filenamePattern == null ) { FileService fileModelService = new FileService ( event . getGraphContext ( ) ) ; for ( FileModel fileModel : fileModelService . findAll ( ) ) { vertices . add ( fileModel ) ; } } } | Generating the input vertices is quite complex . Therefore there are multiple methods that handles the input vertices based on the attribute specified in specific order . This method generates all the vertices if there is no other way how to handle the input . | 99 | 49 |
146,408 | @ Override public T getById ( Object id ) { return context . getFramed ( ) . getFramedVertex ( this . type , id ) ; } | Returns the vertex with given ID framed into given interface . | 35 | 11 |
146,409 | public static < T extends WindupVertexFrame > T addTypeToModel ( GraphContext graphContext , WindupVertexFrame frame , Class < T > type ) { Vertex vertex = frame . getElement ( ) ; graphContext . getGraphTypeManager ( ) . addTypeToElement ( type , vertex ) ; return graphContext . getFramed ( ) . frameElement ( vertex , type ) ; } | Adds the specified type to this frame and returns a new object that implements this type . | 86 | 17 |
146,410 | public static < T extends WindupVertexFrame > WindupVertexFrame removeTypeFromModel ( GraphContext graphContext , WindupVertexFrame frame , Class < T > type ) { Vertex vertex = frame . getElement ( ) ; graphContext . getGraphTypeManager ( ) . removeTypeFromElement ( type , vertex ) ; return graphContext . getFramed ( ) . frameElement ( vertex , WindupVertexFrame . class ) ; } | Removes the specified type from the frame . | 96 | 9 |
146,411 | @ SuppressWarnings ( "unchecked" ) private static synchronized Map < String , Boolean > getCache ( GraphRewrite event ) { Map < String , Boolean > result = ( Map < String , Boolean > ) event . getRewriteContext ( ) . get ( ClassificationServiceCache . class ) ; if ( result == null ) { result = Collections . synchronizedMap ( new LRUMap ( 30000 ) ) ; event . getRewriteContext ( ) . put ( ClassificationServiceCache . class , result ) ; } return result ; } | Keep a cache of items files associated with classification in order to improve performance . | 113 | 15 |
146,412 | public static String getEffortLevelDescription ( Verbosity verbosity , int points ) { EffortLevel level = EffortLevel . forPoints ( points ) ; switch ( verbosity ) { case ID : return level . name ( ) ; case VERBOSE : return level . getVerboseDescription ( ) ; case SHORT : default : return level . getShortDescription ( ) ; } } | Returns the right string representation of the effort level based on given number of points . | 83 | 16 |
146,413 | public WindupConfiguration setOptionValue ( String name , Object value ) { configurationOptions . put ( name , value ) ; return this ; } | Sets a configuration option to the specified value . | 29 | 10 |
146,414 | @ SuppressWarnings ( "unchecked" ) public < T > T getOptionValue ( String name ) { return ( T ) configurationOptions . get ( name ) ; } | Returns the configuration value with the specified name . | 38 | 9 |
146,415 | private void logTimeTakenByRuleProvider ( GraphContext graphContext , Context context , int ruleIndex , int timeTaken ) { AbstractRuleProvider ruleProvider = ( AbstractRuleProvider ) context . get ( RuleMetadataType . RULE_PROVIDER ) ; if ( ruleProvider == null ) return ; if ( ! timeTakenByProvider . containsKey ( ruleProvider ) ) { RuleProviderExecutionStatisticsModel model = new RuleProviderExecutionStatisticsService ( graphContext ) . create ( ) ; model . setRuleIndex ( ruleIndex ) ; model . setRuleProviderID ( ruleProvider . getMetadata ( ) . getID ( ) ) ; model . setTimeTaken ( timeTaken ) ; timeTakenByProvider . put ( ruleProvider , model . getElement ( ) . id ( ) ) ; } else { RuleProviderExecutionStatisticsService service = new RuleProviderExecutionStatisticsService ( graphContext ) ; RuleProviderExecutionStatisticsModel model = service . getById ( timeTakenByProvider . get ( ruleProvider ) ) ; int prevTimeTaken = model . getTimeTaken ( ) ; model . setTimeTaken ( prevTimeTaken + timeTaken ) ; } logTimeTakenByPhase ( graphContext , ruleProvider . getMetadata ( ) . getPhase ( ) , timeTaken ) ; } | Logs the time taken by this rule and attaches this to the total for the RuleProvider | 284 | 18 |
146,416 | private void logTimeTakenByPhase ( GraphContext graphContext , Class < ? extends RulePhase > phase , int timeTaken ) { if ( ! timeTakenByPhase . containsKey ( phase ) ) { RulePhaseExecutionStatisticsModel model = new GraphService <> ( graphContext , RulePhaseExecutionStatisticsModel . class ) . create ( ) ; model . setRulePhase ( phase . toString ( ) ) ; model . setTimeTaken ( timeTaken ) ; model . setOrderExecuted ( timeTakenByPhase . size ( ) ) ; timeTakenByPhase . put ( phase , model . getElement ( ) . id ( ) ) ; } else { GraphService < RulePhaseExecutionStatisticsModel > service = new GraphService <> ( graphContext , RulePhaseExecutionStatisticsModel . class ) ; RulePhaseExecutionStatisticsModel model = service . getById ( timeTakenByPhase . get ( phase ) ) ; int prevTimeTaken = model . getTimeTaken ( ) ; model . setTimeTaken ( prevTimeTaken + timeTaken ) ; } } | Logs the time taken by this rule and adds this to the total time taken for this phase | 235 | 19 |
146,417 | public static String transformXPath ( String originalXPath ) { // use a list to maintain the multiple joined xqueries (if there are multiple queries joined with the "|" operator) List < StringBuilder > compiledXPaths = new ArrayList <> ( 1 ) ; int frameIdx = - 1 ; boolean inQuote = false ; int conditionLevel = 0 ; char startQuoteChar = 0 ; StringBuilder currentXPath = new StringBuilder ( ) ; compiledXPaths . add ( currentXPath ) ; for ( int i = 0 ; i < originalXPath . length ( ) ; i ++ ) { char curChar = originalXPath . charAt ( i ) ; if ( ! inQuote && curChar == ' ' ) { frameIdx ++ ; conditionLevel ++ ; currentXPath . append ( "[windup:startFrame(" ) . append ( frameIdx ) . append ( ") and windup:evaluate(" ) . append ( frameIdx ) . append ( ", " ) ; } else if ( ! inQuote && curChar == ' ' ) { conditionLevel -- ; currentXPath . append ( ")]" ) ; } else if ( ! inQuote && conditionLevel == 0 && curChar == ' ' ) { // joining multiple xqueries currentXPath = new StringBuilder ( ) ; compiledXPaths . add ( currentXPath ) ; } else { if ( inQuote && curChar == startQuoteChar ) { inQuote = false ; startQuoteChar = 0 ; } else if ( curChar == ' ' || curChar == ' ' ) { inQuote = true ; startQuoteChar = curChar ; } if ( ! inQuote && originalXPath . startsWith ( WINDUP_MATCHES_FUNCTION_PREFIX , i ) ) { i += ( WINDUP_MATCHES_FUNCTION_PREFIX . length ( ) - 1 ) ; currentXPath . append ( "windup:matches(" ) . append ( frameIdx ) . append ( ", " ) ; } else { currentXPath . append ( curChar ) ; } } } Pattern leadingAndTrailingWhitespace = Pattern . compile ( "(\\s*)(.*?)(\\s*)" ) ; StringBuilder finalResult = new StringBuilder ( ) ; for ( StringBuilder compiledXPath : compiledXPaths ) { if ( StringUtils . isNotBlank ( compiledXPath ) ) { Matcher whitespaceMatcher = leadingAndTrailingWhitespace . matcher ( compiledXPath ) ; if ( ! whitespaceMatcher . matches ( ) ) continue ; compiledXPath = new StringBuilder ( ) ; compiledXPath . append ( whitespaceMatcher . group ( 1 ) ) ; compiledXPath . append ( whitespaceMatcher . group ( 2 ) ) ; compiledXPath . append ( "/self::node()[windup:persist(" ) . append ( frameIdx ) . append ( ", " ) . append ( ".)]" ) ; compiledXPath . append ( whitespaceMatcher . group ( 3 ) ) ; if ( StringUtils . isNotBlank ( finalResult ) ) finalResult . append ( "|" ) ; finalResult . append ( compiledXPath ) ; } } return finalResult . toString ( ) ; } | Performs the conversion from standard XPath to xpath with parameterization support . | 705 | 16 |
146,418 | @ Override public void accept ( IBinaryType binaryType , PackageBinding packageBinding , AccessRestriction accessRestriction ) { if ( this . options . verbose ) { this . out . println ( Messages . bind ( Messages . compilation_loadBinary , new String ( binaryType . getName ( ) ) ) ) ; // new Exception("TRACE BINARY").printStackTrace(System.out); // System.out.println(); } LookupEnvironment env = packageBinding . environment ; env . createBinaryTypeFrom ( binaryType , packageBinding , accessRestriction ) ; } | Add an additional binary type | 129 | 5 |
146,419 | @ 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 } } } | Add an additional compilation unit into the loop - > build compilation unit declarations their bindings and record their results . | 370 | 21 |
146,420 | @ 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 ( ) ) } ) ) ; } | Add additional source types | 98 | 4 |
146,421 | 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 ) ; } } | Checks whether the compilation has been canceled and reports the given progress to the compiler progress . | 86 | 18 |
146,422 | 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 ) ; } } | Checks whether the compilation has been canceled and reports the given work increment to the compiler progress . | 110 | 19 |
146,423 | 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 ) ) ) ; } } } | General API - > compile each of supplied files - > recompile any required types for which we have an incomplete principle structure | 564 | 24 |
146,424 | 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 ; } | Process a compilation unit already parsed and build . | 360 | 9 |
146,425 | @ 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 ) ; } } } } | Loads the tag definitions from the files with a . tags . xml suffix from the addons . | 214 | 20 |
146,426 | 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 ( ) ; } } ; } | Process the given batch of files and pass the results back to the listener as each file is processed . | 847 | 20 |
146,427 | public AnnotationTypeCondition addCondition ( String element , AnnotationCondition condition ) { this . conditions . put ( element , condition ) ; return this ; } | Adds another condition for an element within this annotation . | 32 | 10 |
146,428 | @ 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 ; } | Decompiles the given . class file and creates the specified output source file . | 480 | 16 |
146,429 | 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 ( ) ) ) ; } } | The metadata cache can become huge over time . This simply flushes it periodically . | 86 | 16 |
146,430 | 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 ( ) ; } | Decompiles a single type . | 574 | 7 |
146,431 | 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 ; } | Default settings set type loader to ClasspathTypeLoader if not set before . | 112 | 15 |
146,432 | 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 ) ; } } | Opens the jar wraps any IOException . | 61 | 9 |
146,433 | 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 ) ; } | Constructs the path from FQCN validates writability and creates a writer . | 263 | 17 |
146,434 | 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 ) ; } } | Print the given values after displaying the provided message . | 83 | 10 |
146,435 | 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 ( ) ; } | Returns the type discriminator value for given Frames model class extracted from the | 91 | 14 |
146,436 | 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 ; } | Gets the default configuration for Freemarker within Windup . | 166 | 13 |
146,437 | 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 ; } | Finds all variables in the context with the given names and also attaches all WindupFreeMarkerMethods from all addons into the map . | 165 | 29 |
146,438 | 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 ; } | Attach the given link to the classification while checking for duplicates . | 78 | 13 |
146,439 | 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 ; } | 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 . | 151 | 56 |
146,440 | 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 ; } | Returns the root path for this source file based upon the package name . | 164 | 14 |
146,441 | public static boolean isInSubDirectory ( File dir , File file ) { if ( file == null ) return false ; if ( file . equals ( dir ) ) return true ; return isInSubDirectory ( dir , file . getParentFile ( ) ) ; } | Returns true if file is a subfile or subdirectory of dir . | 54 | 14 |
146,442 | 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 ) ; } } | Creates the given directory . Fails if it already exists . | 77 | 13 |
146,443 | 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 ) ; } } | 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 . | 222 | 26 |
146,444 | 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 ) ; } | Adds parameters contained in the annotation into the annotation type reference | 248 | 11 |
146,445 | @ 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 ) ; } | Declaration of the variable within a block | 213 | 8 |
146,446 | @ 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 ; } | Excludes Vertices that are of the provided type . | 96 | 11 |
146,447 | 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 ; } | Returns true if the addon depends on reporting . | 90 | 9 |
146,448 | 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 ; } | Returns a single parent of the given tag . If there are multiple parents throws a WindupException . | 179 | 20 |
146,449 | public static GraphTraversal < Vertex , Vertex > addPipeFor ( GraphTraversal < Vertex , Vertex > pipeline , Class < ? extends WindupVertexFrame > clazz ) { pipeline . has ( WindupVertexFrame . TYPE_PROP , GraphTypeManager . getTypeValue ( clazz ) ) ; return pipeline ; } | Adds a criterion to given pipeline which filters out vertices representing given WindupVertexFrame . | 77 | 19 |
146,450 | 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 ; } | Returns true if - includeTags is not empty and tag is in includeTags - includeTags is empty and tag is not in excludeTags | 112 | 27 |
146,451 | 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 ; } | Expands the directories from the given list and and returns a list of subfiles . Files from the original list are kept as is . | 208 | 27 |
146,452 | 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 ( ) ; } | Attempts to create a human - readable String representation of the provided rule . | 519 | 14 |
146,453 | @ 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 ( ) ) ; } | The handling method . | 201 | 4 |
146,454 | 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 ) ; } } | Associate a type with the given resource model . | 467 | 10 |
146,455 | 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 ; } | 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 . | 315 | 36 |
146,456 | 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 ) ; } } | Read the tag structure from the provided stream . | 107 | 9 |
146,457 | public List < Tag > getPrimeTags ( ) { return this . definedTags . values ( ) . stream ( ) . filter ( Tag :: isPrime ) . collect ( Collectors . toList ( ) ) ; } | Gets all tags that are prime tags . | 45 | 9 |
146,458 | 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 = ... . | 45 | 41 |
146,459 | 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 . | 44 | 31 |
146,460 | 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" ) ; } | Writes the JavaScript code describing the tags as Tag classes to given writer . | 301 | 15 |
146,461 | public Path getReportDirectory ( ) { WindupConfigurationModel cfg = WindupConfigurationService . getConfigurationModel ( getGraphContext ( ) ) ; Path path = cfg . getOutputPath ( ) . asFile ( ) . toPath ( ) . resolve ( REPORTS_DIR ) ; createDirectoryIfNeeded ( path ) ; return path . toAbsolutePath ( ) ; } | Returns the output directory for reporting . | 82 | 7 |
146,462 | @ 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 ( ) ) ; } } | Returns the ReportModel with given name . | 117 | 8 |
146,463 | 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 ; } | Returns a unique file name | 203 | 5 |
146,464 | 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 ) ; } } | This essentially ensures that we only store a single Vertex for each unique Set of tags . | 101 | 18 |
146,465 | private static Set < ProjectModel > getAllApplications ( GraphContext graphContext ) { Set < ProjectModel > apps = new HashSet <> ( ) ; Iterable < ProjectModel > appProjects = graphContext . findAll ( ProjectModel . class ) ; for ( ProjectModel appProject : appProjects ) apps . ( appProject ) ; return apps ; } | Returns all ApplicationProjectModels . | 76 | 7 |
146,466 | 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 ; } | 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 . | 505 | 31 |
146,467 | public static Artifact withVersion ( Version v ) { Artifact artifact = new Artifact ( ) ; artifact . version = v ; return artifact ; } | Start with specifying the artifact version | 28 | 6 |
146,468 | public static Artifact withGroupId ( String groupId ) { Artifact artifact = new Artifact ( ) ; artifact . groupId = new RegexParameterizedPatternParser ( groupId ) ; return artifact ; } | Start with specifying the groupId | 41 | 6 |
146,469 | public static Artifact withArtifactId ( String artifactId ) { Artifact artifact = new Artifact ( ) ; artifact . artifactId = new RegexParameterizedPatternParser ( artifactId ) ; return artifact ; } | Start with specifying the artifactId | 42 | 6 |
146,470 | public void setSingletonVariable ( String name , WindupVertexFrame frame ) { setVariable ( name , Collections . singletonList ( frame ) ) ; } | Type - safe wrapper around setVariable which sets only one framed vertex . | 34 | 14 |
146,471 | 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 ) ; } | Set a variable in the top variables layer to given collection of the vertex frames . Can t be reassigned - throws on attempt to reassign . | 116 | 29 |
146,472 | public void removeVariable ( String name ) { Map < String , Iterable < ? extends WindupVertexFrame > > frame = peek ( ) ; frame . remove ( name ) ; } | Remove a variable in the top variables layer . | 39 | 9 |
146,473 | 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 ; } | Searches the variables layers top to bottom for given name and returns if found ; null otherwise . | 106 | 20 |
146,474 | @ 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 ; } | 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 . | 170 | 30 |
146,475 | protected void checkVariableName ( GraphRewrite event , EvaluationContext context ) { if ( getInputVariablesName ( ) == null ) { setInputVariablesName ( Iteration . getPayloadVariableName ( event , context ) ) ; } } | Check the variable name and if not set set it with the singleton variable being on the top of the stack . | 52 | 23 |
146,476 | 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 ; } | Recursively scan the provided path and return a list of all Java packages contained therein . | 117 | 18 |
146,477 | 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 ; } | Gets the path used for the results of XSLT Transforms . | 144 | 15 |
146,478 | 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 ; } | Converts the given dislect to a human - readable datasource type . | 359 | 15 |
146,479 | 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 ) ; } } | Load the given configuration file . | 137 | 6 |
146,480 | @ Override public void perform ( Rewrite event , EvaluationContext context ) { perform ( ( GraphRewrite ) event , context ) ; } | Called internally to actually process the Iteration . | 29 | 10 |
146,481 | @ 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 ; } | Join N sets . | 76 | 4 |
146,482 | public List < IssueCategory > getIssueCategories ( ) { return this . issueCategories . values ( ) . stream ( ) . sorted ( ( category1 , category2 ) -> category1 . getPriority ( ) - category2 . getPriority ( ) ) . collect ( Collectors . toList ( ) ) ; } | Returns a list ordered from the highest priority to the lowest . | 69 | 12 |
146,483 | 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 ) ) ; } | Make sure that we have some reasonable defaults available . These would typically be provided by the rulesets in the real world . | 288 | 24 |
146,484 | 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 ) ; } } | Renders the given FreeMarker template to given directory using given variables . | 261 | 15 |
146,485 | public static synchronized ExecutionStatistics get ( ) { Thread currentThread = Thread . currentThread ( ) ; if ( stats . get ( currentThread ) == null ) { stats . put ( currentThread , new ExecutionStatistics ( ) ) ; } return stats . get ( currentThread ) ; } | Gets the instance associated with the current thread . | 58 | 10 |
146,486 | 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 ) ) ; } } } | 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 . | 138 | 41 |
146,487 | 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 ) ; } } } | Merge two ExecutionStatistics into one . This method is private in order not to be synchronized ( merging . | 96 | 21 |
146,488 | 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 ( ) ; } } | Serializes the timing data to a ~ delimited file at outputPath . | 237 | 15 |
146,489 | 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 ( ) ; } | Start timing an operation with the given identifier . | 66 | 9 |
146,490 | 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 ( ) ; } | 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 . | 71 | 30 |
146,491 | private void registerPackageInTypeInterestFactory ( String pkg ) { TypeInterestFactory . registerInterest ( pkg + "_pkg" , pkg . replace ( "." , "\\." ) , pkg , TypeReferenceLocation . IMPORT ) ; // TODO: Finish the implementation } | So that we get these packages caught Java class analysis . | 60 | 11 |
146,492 | public static void cache ( XmlFileModel key , Document document ) { String cacheKey = getKey ( key ) ; map . put ( cacheKey , new CacheDocument ( false , document ) ) ; } | Add the provided document to the cache . | 43 | 8 |
146,493 | public static void cacheParseFailure ( XmlFileModel key ) { map . put ( getKey ( key ) , new CacheDocument ( true , null ) ) ; } | Cache a parse failure for this document . | 36 | 8 |
146,494 | 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 ) ; } | Retrieve the currently cached value for the given document . | 113 | 11 |
146,495 | public void reformatFile ( ) throws IOException { List < LineNumberPosition > lineBrokenPositions = new ArrayList <> ( ) ; List < String > brokenLines = breakLines ( lineBrokenPositions ) ; emitFormatted ( brokenLines , lineBrokenPositions ) ; } | Rewrites the file passed to this constructor so that the actual line numbers match the recipe passed to this constructor . | 66 | 22 |
146,496 | public static PackageNameMappingWithPackagePattern fromPackage ( String packagePattern ) { PackageNameMapping packageNameMapping = new PackageNameMapping ( ) ; packageNameMapping . setPackagePattern ( packagePattern ) ; return packageNameMapping ; } | Sets the package pattern to match against . | 54 | 9 |
146,497 | 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 ; } | 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 . | 508 | 30 |
146,498 | 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 ; } | Returns the short rate from timeIndex to timeIndex + 1 . | 199 | 13 |
146,499 | 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 ; } | Calculates the Black - Scholes option value of an atm call option . | 119 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.