idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
1,600
public PreprocessorContext setGlobalVariable ( final String name , final Value value ) { assertNotNull ( "Variable name is null" , name ) ; final String normalizedName = assertNotNull ( PreprocessorUtils . normalizeVariableName ( name ) ) ; if ( normalizedName . isEmpty ( ) ) { throw makeException ( "Name is empty" , null ) ; } assertNotNull ( "Value is null" , value ) ; if ( mapVariableNameToSpecialVarProcessor . containsKey ( normalizedName ) ) { mapVariableNameToSpecialVarProcessor . get ( normalizedName ) . setVariable ( normalizedName , value , this ) ; } else { if ( isVerbose ( ) ) { final String valueAsStr = value . toString ( ) ; if ( globalVarTable . containsKey ( normalizedName ) ) { logForVerbose ( "Replacing global variable [" + normalizedName + '=' + valueAsStr + ']' ) ; } else { logForVerbose ( "Defining new global variable [" + normalizedName + '=' + valueAsStr + ']' ) ; } } globalVarTable . put ( normalizedName , value ) ; } return this ; }
Set a global variable value
1,601
public boolean containsGlobalVariable ( final String name ) { if ( name == null ) { return false ; } final String normalized = assertNotNull ( PreprocessorUtils . normalizeVariableName ( name ) ) ; if ( normalized . isEmpty ( ) ) { return false ; } return mapVariableNameToSpecialVarProcessor . containsKey ( normalized ) || globalVarTable . containsKey ( normalized ) ; }
Check that there is a named global variable in the inside storage
1,602
public boolean isGlobalVariable ( final String variableName ) { boolean result = false ; if ( variableName != null ) { final String normalized = PreprocessorUtils . normalizeVariableName ( variableName ) ; result = this . globalVarTable . containsKey ( normalized ) || mapVariableNameToSpecialVarProcessor . containsKey ( normalized ) ; } return result ; }
Check that there is a global variable with such name .
1,603
public boolean isLocalVariable ( final String variableName ) { boolean result = false ; if ( variableName != null ) { final String normalized = PreprocessorUtils . normalizeVariableName ( variableName ) ; result = this . localVarTable . containsKey ( normalized ) ; } return result ; }
Check that there is a local variable with such name .
1,604
public File createDestinationFileForPath ( final String path ) { assertNotNull ( "Path is null" , path ) ; if ( path . isEmpty ( ) ) { throw makeException ( "File name is empty" , null ) ; } return new File ( this . getTarget ( ) , path ) ; }
It allows to create a File object for its path subject to the destination directory path
1,605
public File findFileInSources ( final String path ) throws IOException { if ( path == null ) { throw makeException ( "File path is null" , null ) ; } if ( path . trim ( ) . isEmpty ( ) ) { throw makeException ( "File path is empty" , null ) ; } File result = null ; final TextFileDataContainer theFile = this . getPreprocessingState ( ) . peekFile ( ) ; final String parentDir = theFile == null ? null : theFile . getFile ( ) . getParent ( ) ; final File resultFile = new File ( path ) ; if ( resultFile . isAbsolute ( ) ) { final String normalizedPath = FilenameUtils . normalizeNoEndSeparator ( resultFile . getAbsolutePath ( ) ) ; for ( final SourceFolder root : getSources ( ) ) { if ( normalizedPath . startsWith ( root . getNormalizedAbsolutePath ( true ) ) ) { result = resultFile ; break ; } } if ( result == null ) { throw makeException ( "Can't find file for path \'" + path + "\' in preprocessing source folders, allowed usage only files in preprocessing source folders!" , null ) ; } else if ( ! result . isFile ( ) ) { throw makeException ( "File \'" + result + "\' is either not found or not a file" , null ) ; } } else if ( parentDir != null ) { result = new File ( parentDir , path ) ; } else { final List < File > setOfFoundFiles = new ArrayList < > ( ) ; getSources ( ) . stream ( ) . map ( ( root ) -> new File ( root . getAsFile ( ) , path ) ) . filter ( ( variant ) -> ( variant . exists ( ) && variant . isFile ( ) ) ) . forEachOrdered ( ( variant ) -> { setOfFoundFiles . add ( variant ) ; } ) ; if ( setOfFoundFiles . size ( ) == 1 ) { result = setOfFoundFiles . get ( 0 ) ; } else if ( setOfFoundFiles . isEmpty ( ) ) { result = null ; } else { throw makeException ( "Found several variants for path \'" + path + "\' in different source roots" , null ) ; } if ( result == null ) { throw makeException ( "Can't find file for path \'" + path + "\' among source files registered for preprocessing." , null ) ; } else if ( ! result . isFile ( ) ) { throw makeException ( "File \'" + PreprocessorUtils . getFilePath ( result ) + "\' is either not found or not a file" , null ) ; } } }
Finds file in source folders the file can be found only inside source folders and external placement is disabled for security purposes .
1,606
public static Error fail ( final String message ) { final AssertionError error = new AssertionError ( GetUtils . ensureNonNull ( message , "failed" ) ) ; MetaErrorListeners . fireError ( "Asserion error" , error ) ; if ( true ) { throw error ; } return error ; }
Throw assertion error for some cause
1,607
public static < T > T [ ] assertDoesntContainNull ( final T [ ] array ) { assertNotNull ( array ) ; for ( final T obj : array ) { if ( obj == null ) { final AssertionError error = new AssertionError ( "Array must not contain NULL" ) ; MetaErrorListeners . fireError ( "Asserion error" , error ) ; throw error ; } } return array ; }
Assert that array doesn t contain null value .
1,608
public static void assertTrue ( final String message , final boolean condition ) { if ( ! condition ) { final AssertionError error = new AssertionError ( GetUtils . ensureNonNull ( message , "Condition must be TRUE" ) ) ; MetaErrorListeners . fireError ( error . getMessage ( ) , error ) ; throw error ; } }
Assert condition flag is TRUE . GEL will be notified about error .
1,609
public static < T > T assertEquals ( final T etalon , final T value ) { if ( etalon == null ) { assertNull ( value ) ; } else { if ( ! ( etalon == value || etalon . equals ( value ) ) ) { final AssertionError error = new AssertionError ( "Value is not equal to etalon" ) ; MetaErrorListeners . fireError ( error . getMessage ( ) , error ) ; throw error ; } } return value ; }
Assert that value is equal to some etalon value .
1,610
public static < T extends Collection < ? > > T assertDoesntContainNull ( final T collection ) { assertNotNull ( collection ) ; for ( final Object obj : collection ) { assertNotNull ( obj ) ; } return collection ; }
Assert that collection doesn t contain null value .
1,611
public static < T extends Disposable > T assertNotDisposed ( final T disposable ) { if ( disposable . isDisposed ( ) ) { final AlreadyDisposedError error = new AlreadyDisposedError ( "Object already disposed" ) ; MetaErrorListeners . fireError ( "Asserion error" , error ) ; throw error ; } return disposable ; }
Assert that a disposable object is not disposed .
1,612
public void addItem ( final ExpressionItem item ) { if ( item == null ) { throw new PreprocessorException ( "[Expression]Item is null" , this . sources , this . includeStack , null ) ; } if ( last . isEmptySlot ( ) ) { last = new ExpressionTreeElement ( item , this . includeStack , this . sources ) ; } else { last = last . addTreeElement ( new ExpressionTreeElement ( item , this . includeStack , this . sources ) ) ; } }
Add new expression item into tree
1,613
public void addTree ( final ExpressionTree tree ) { assertNotNull ( "Tree is null" , tree ) ; if ( last . isEmptySlot ( ) ) { final ExpressionTreeElement thatTreeRoot = tree . getRoot ( ) ; if ( ! thatTreeRoot . isEmptySlot ( ) ) { last = thatTreeRoot ; last . makeMaxPriority ( ) ; } } else { last = last . addSubTree ( tree ) ; } }
Add whole tree as a tree element also it sets the maximum priority to the new element
1,614
public ExpressionTreeElement getRoot ( ) { if ( last . isEmptySlot ( ) ) { return this . last ; } else { ExpressionTreeElement element = last ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { final ExpressionTreeElement next = element . getParent ( ) ; if ( next == null ) { return element ; } else { element = next ; } } } return ExpressionTreeElement . EMPTY_SLOT ; }
Get the root of the tree
1,615
@ Weight ( Weight . Unit . NORMAL ) public static Deferred defer ( final Deferred deferred ) { REGISTRY . get ( ) . add ( assertNotNull ( deferred ) ) ; return deferred ; }
Defer some action .
1,616
@ Weight ( Weight . Unit . NORMAL ) public static Runnable defer ( final Runnable runnable ) { assertNotNull ( runnable ) ; defer ( new Deferred ( ) { private static final long serialVersionUID = 2061489024868070733L ; private final Runnable value = runnable ; public void executeDeferred ( ) throws Exception { this . value . run ( ) ; } } ) ; return runnable ; }
Defer execution of some runnable action .
1,617
@ Weight ( Weight . Unit . NORMAL ) public static Disposable defer ( final Disposable disposable ) { assertNotNull ( disposable ) ; defer ( new Deferred ( ) { private static final long serialVersionUID = 7940162959962038010L ; private final Disposable value = disposable ; public void executeDeferred ( ) throws Exception { this . value . dispose ( ) ; } } ) ; return disposable ; }
Defer execution of some disposable object .
1,618
@ Weight ( Weight . Unit . NORMAL ) public static void cancelAllDeferredActionsGlobally ( ) { final List < Deferred > list = REGISTRY . get ( ) ; list . clear ( ) ; REGISTRY . remove ( ) ; }
Cancel all defer actions globally .
1,619
@ Weight ( value = Weight . Unit . VARIABLE , comment = "Depends on the current call stack depth" ) public static void processDeferredActions ( ) { final int stackDepth = ThreadUtils . stackDepth ( ) ; final List < Deferred > list = REGISTRY . get ( ) ; final Iterator < Deferred > iterator = list . iterator ( ) ; while ( iterator . hasNext ( ) ) { final Deferred deferred = iterator . next ( ) ; if ( deferred . getStackDepth ( ) >= stackDepth ) { try { deferred . executeDeferred ( ) ; } catch ( Exception ex ) { final UnexpectedProcessingError error = new UnexpectedProcessingError ( "Error during deferred action processing" , ex ) ; MetaErrorListeners . fireError ( error . getMessage ( ) , error ) ; } finally { iterator . remove ( ) ; } } } if ( list . isEmpty ( ) ) { REGISTRY . remove ( ) ; } }
Process all defer actions for the current stack depth level .
1,620
@ Weight ( Weight . Unit . NORMAL ) public static boolean isEmpty ( ) { final boolean result = REGISTRY . get ( ) . isEmpty ( ) ; if ( result ) { REGISTRY . remove ( ) ; } return result ; }
Check that presented defer actions for the current thread .
1,621
public ExpressionTree parse ( final String expressionStr , final PreprocessorContext context ) throws IOException { assertNotNull ( "Expression is null" , expressionStr ) ; final PushbackReader reader = new PushbackReader ( new StringReader ( expressionStr ) ) ; final ExpressionTree result ; final PreprocessingState state = context . getPreprocessingState ( ) ; result = new ExpressionTree ( state . makeIncludeStack ( ) , state . getLastReadString ( ) ) ; if ( readExpression ( reader , result , context , false , false ) != null ) { final String text = "Unexpected result during parsing [" + expressionStr + ']' ; throw context . makeException ( text , null ) ; } result . postProcess ( ) ; return result ; }
To parse an expression represented as a string and get a tree
1,622
public ExpressionItem readExpression ( final PushbackReader reader , final ExpressionTree tree , final PreprocessorContext context , final boolean insideBracket , final boolean argument ) throws IOException { boolean working = true ; ExpressionItem result = null ; final FilePositionInfo [ ] stack ; final String sourceLine ; final PreprocessingState state = context . getPreprocessingState ( ) ; stack = state . makeIncludeStack ( ) ; sourceLine = state . getLastReadString ( ) ; ExpressionItem prev = null ; while ( working ) { final ExpressionItem nextItem = nextItem ( reader , context ) ; if ( nextItem == null ) { working = false ; result = null ; } else if ( nextItem . getExpressionItemType ( ) == ExpressionItemType . SPECIAL ) { if ( nextItem == SpecialItem . BRACKET_CLOSING ) { if ( insideBracket ) { working = false ; result = nextItem ; } else if ( argument ) { working = false ; result = nextItem ; } else { final String text = "Detected alone closing bracket" ; throw context . makeException ( "Detected alone closing bracket" , null ) ; } } else if ( nextItem == SpecialItem . BRACKET_OPENING ) { if ( prev != null && prev . getExpressionItemType ( ) == ExpressionItemType . VARIABLE ) { final String text = "Unknown function detected [" + prev . toString ( ) + ']' ; throw context . makeException ( text , null ) ; } final ExpressionTree subExpression ; subExpression = new ExpressionTree ( stack , sourceLine ) ; if ( SpecialItem . BRACKET_CLOSING != readExpression ( reader , subExpression , context , true , false ) ) { final String text = "Detected unclosed bracket" ; throw context . makeException ( text , null ) ; } tree . addTree ( subExpression ) ; } else if ( nextItem == SpecialItem . COMMA ) { return nextItem ; } } else if ( nextItem . getExpressionItemType ( ) == ExpressionItemType . FUNCTION ) { final AbstractFunction function = ( AbstractFunction ) nextItem ; ExpressionTree functionTree = readFunction ( function , reader , context , stack , sourceLine ) ; tree . addTree ( functionTree ) ; } else { tree . addItem ( nextItem ) ; } prev = nextItem ; } return result ; }
It reads an expression from a reader and fill a tree
1,623
private ExpressionTree readFunction ( final AbstractFunction function , final PushbackReader reader , final PreprocessorContext context , final FilePositionInfo [ ] includeStack , final String sources ) throws IOException { final ExpressionItem expectedBracket = nextItem ( reader , context ) ; if ( expectedBracket == null ) { throw context . makeException ( "Detected function without params [" + function . getName ( ) + ']' , null ) ; } final int arity = function . getArity ( ) ; ExpressionTree functionTree ; if ( arity == 0 ) { final ExpressionTree subExpression = new ExpressionTree ( includeStack , sources ) ; final ExpressionItem lastItem = readFunctionArgument ( reader , subExpression , context , includeStack , sources ) ; if ( SpecialItem . BRACKET_CLOSING != lastItem ) { throw context . makeException ( "There is not closing bracket for function [" + function . getName ( ) + ']' , null ) ; } else if ( ! subExpression . getRoot ( ) . isEmptySlot ( ) ) { throw context . makeException ( "The function \'" + function . getName ( ) + "\' doesn't need arguments" , null ) ; } else { functionTree = new ExpressionTree ( includeStack , sources ) ; functionTree . addItem ( function ) ; } } else { final List < ExpressionTree > arguments = new ArrayList < > ( arity ) ; for ( int i = 0 ; i < function . getArity ( ) ; i ++ ) { final ExpressionTree subExpression = new ExpressionTree ( includeStack , sources ) ; final ExpressionItem lastItem = readFunctionArgument ( reader , subExpression , context , includeStack , sources ) ; if ( SpecialItem . BRACKET_CLOSING == lastItem ) { arguments . add ( subExpression ) ; break ; } else if ( SpecialItem . COMMA == lastItem ) { arguments . add ( subExpression ) ; } else { throw context . makeException ( "Wrong argument for function [" + function . getName ( ) + ']' , null ) ; } } functionTree = new ExpressionTree ( includeStack , sources ) ; functionTree . addItem ( function ) ; ExpressionTreeElement functionTreeElement = functionTree . getRoot ( ) ; if ( arguments . size ( ) != functionTreeElement . getArity ( ) ) { throw context . makeException ( "Wrong argument number detected \'" + function . getName ( ) + "\', must be " + function . getArity ( ) + " argument(s)" , null ) ; } functionTreeElement . fillArguments ( arguments ) ; } return functionTree ; }
The auxiliary method allows to form a function and its arguments as a tree
1,624
@ Weight ( value = Weight . Unit . VARIABLE , comment = "Depends on the current call stack depth" ) public static void addPoint ( final String timePointName , final TimeAlertListener listener ) { final List < TimeData > list = REGISTRY . get ( ) ; list . add ( new TimeData ( ThreadUtils . stackDepth ( ) , timePointName , - 1L , assertNotNull ( listener ) ) ) ; }
Add a named time point .
1,625
@ Weight ( value = Weight . Unit . VARIABLE , comment = "Depends on the current call stack depth" ) public static void checkPoints ( ) { final long time = System . currentTimeMillis ( ) ; final int stackDepth = ThreadUtils . stackDepth ( ) ; final List < TimeData > list = REGISTRY . get ( ) ; final Iterator < TimeData > iterator = list . iterator ( ) ; while ( iterator . hasNext ( ) ) { final TimeData timeWatchItem = iterator . next ( ) ; if ( timeWatchItem . isTimePoint ( ) && timeWatchItem . getDetectedStackDepth ( ) >= stackDepth ) { final long detectedDelay = time - timeWatchItem . getCreationTimeInMilliseconds ( ) ; try { timeWatchItem . getAlertListener ( ) . onTimeAlert ( detectedDelay , timeWatchItem ) ; } catch ( Exception ex ) { final UnexpectedProcessingError error = new UnexpectedProcessingError ( "Error during time point processing" , ex ) ; MetaErrorListeners . fireError ( error . getMessage ( ) , error ) ; } finally { iterator . remove ( ) ; } } } }
Process all time points for the current stack level .
1,626
@ Weight ( value = Weight . Unit . VARIABLE , comment = "Depends on the current call stack depth" ) public static void addGuard ( final String alertMessage , @ Constraint ( "X>0" ) final long maxAllowedDelayInMilliseconds , final TimeAlertListener timeAlertListener ) { final List < TimeData > list = REGISTRY . get ( ) ; list . add ( new TimeData ( ThreadUtils . stackDepth ( ) , alertMessage , maxAllowedDelayInMilliseconds , timeAlertListener ) ) ; }
WARNING! Don t make a call from methods of the class to not break stack depth!
1,627
@ Weight ( Weight . Unit . NORMAL ) public static void cancelAll ( ) { final List < TimeData > list = REGISTRY . get ( ) ; list . clear ( ) ; REGISTRY . remove ( ) ; }
Cancel all time watchers and time points globally for the current thread .
1,628
@ Weight ( value = Weight . Unit . VARIABLE , comment = "Depends on the current call stack depth" ) public static void check ( ) { final long time = System . currentTimeMillis ( ) ; final int stackDepth = ThreadUtils . stackDepth ( ) ; final List < TimeData > list = REGISTRY . get ( ) ; final Iterator < TimeData > iterator = list . iterator ( ) ; while ( iterator . hasNext ( ) ) { final TimeData timeWatchItem = iterator . next ( ) ; if ( timeWatchItem . getDetectedStackDepth ( ) >= stackDepth ) { final boolean timePoint = timeWatchItem . isTimePoint ( ) ; try { final long detectedDelay = time - timeWatchItem . getCreationTimeInMilliseconds ( ) ; if ( timePoint ) { try { timeWatchItem . getAlertListener ( ) . onTimeAlert ( detectedDelay , timeWatchItem ) ; } catch ( Exception ex ) { final UnexpectedProcessingError error = new UnexpectedProcessingError ( "Error during time point processing" , ex ) ; MetaErrorListeners . fireError ( error . getMessage ( ) , error ) ; } } else if ( detectedDelay > timeWatchItem . getMaxAllowedDelayInMilliseconds ( ) ) { final TimeAlertListener processor = timeWatchItem . getAlertListener ( ) ; if ( processor == NULL_TIME_ALERT_LISTENER ) { MetaErrorListeners . fireError ( "Detected time violation without defined time alert listener" , new TimeViolationError ( detectedDelay , timeWatchItem ) ) ; } else { try { processor . onTimeAlert ( detectedDelay , timeWatchItem ) ; } catch ( Exception ex ) { final UnexpectedProcessingError error = new UnexpectedProcessingError ( "Error during time alert processing" , ex ) ; MetaErrorListeners . fireError ( error . getMessage ( ) , error ) ; } } } } finally { iterator . remove ( ) ; } } } if ( list . isEmpty ( ) ) { REGISTRY . remove ( ) ; } }
Check all registered time watchers for time bound violations .
1,629
public static < E extends AbstractOperator > E findForClass ( final Class < E > operatorClass ) { for ( final AbstractOperator operator : getAllOperators ( ) ) { if ( operator . getClass ( ) == operatorClass ) { return operatorClass . cast ( operator ) ; } } return null ; }
Find an operator handler for its class
1,630
public String restoreStackTrace ( ) { return "THREAD_ID : " + this . threadDescriptor + this . eol + new String ( this . packed ? IOUtils . unpackData ( this . stacktrace ) : this . stacktrace , UTF8 ) ; }
Restore stack trace as a string from inside data representation .
1,631
protected void assertNotDisposed ( ) { if ( this . disposedFlag . get ( ) ) { final AlreadyDisposedError error = new AlreadyDisposedError ( "Object already disposed" ) ; MetaErrorListeners . fireError ( "Detected call to disposed object" , error ) ; throw error ; } }
Auxiliary method to ensure that the object is not disposed .
1,632
public static Value evalTree ( final ExpressionTree tree , final PreprocessorContext context ) { final Expression exp = new Expression ( context , tree ) ; return exp . eval ( context . getPreprocessingState ( ) ) ; }
Evaluate an expression tree
1,633
public void generateArchetypesFromGithubOrganisation ( String githubOrg , File outputDir , List < String > dirs ) throws IOException { GitHub github = GitHub . connectAnonymously ( ) ; GHOrganization organization = github . getOrganization ( githubOrg ) ; Objects . notNull ( organization , "No github organisation found for: " + githubOrg ) ; Map < String , GHRepository > repositories = organization . getRepositories ( ) ; Set < Map . Entry < String , GHRepository > > entries = repositories . entrySet ( ) ; File cloneParentDir = new File ( outputDir , "../git-clones" ) ; if ( cloneParentDir . exists ( ) ) { Files . recursiveDelete ( cloneParentDir ) ; } for ( Map . Entry < String , GHRepository > entry : entries ) { String repoName = entry . getKey ( ) ; GHRepository repo = entry . getValue ( ) ; String url = repo . getGitTransportUrl ( ) ; generateArchetypeFromGitRepo ( outputDir , dirs , cloneParentDir , repoName , url , null ) ; } }
Iterates through all projects in the given github organisation and generates an archetype for it
1,634
public void generateArchetypesFromGitRepoList ( File file , File outputDir , List < String > dirs ) throws IOException { File cloneParentDir = new File ( outputDir , "../git-clones" ) ; if ( cloneParentDir . exists ( ) ) { Files . recursiveDelete ( cloneParentDir ) ; } Properties properties = new Properties ( ) ; try ( FileInputStream is = new FileInputStream ( file ) ) { properties . load ( is ) ; } for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { LinkedList < String > values = new LinkedList < > ( Arrays . asList ( ( ( String ) entry . getValue ( ) ) . split ( "\\|" ) ) ) ; String gitrepo = values . removeFirst ( ) ; String tag = values . isEmpty ( ) ? null : values . removeFirst ( ) ; generateArchetypeFromGitRepo ( outputDir , dirs , cloneParentDir , ( String ) entry . getKey ( ) , gitrepo , tag ) ; } }
Iterates through all projects in the given properties file adn generate an archetype for it
1,635
public void generateArchetypes ( String containerType , File baseDir , File outputDir , boolean clean , List < String > dirs ) throws IOException { LOG . debug ( "Generating archetypes from {} to {}" , baseDir . getCanonicalPath ( ) , outputDir . getCanonicalPath ( ) ) ; File [ ] files = baseDir . listFiles ( ) ; if ( files != null ) { for ( File file : files ) { if ( file . isDirectory ( ) ) { File projectDir = file ; File projectPom = new File ( projectDir , "pom.xml" ) ; if ( projectPom . exists ( ) && ! skipImport ( projectDir ) ) { if ( archetypeUtils . isValidProjectPom ( projectPom ) ) { String fileName = file . getName ( ) ; String archetypeDirName = fileName . replace ( "example" , "archetype" ) ; if ( fileName . equals ( archetypeDirName ) ) { archetypeDirName += "-archetype" ; } archetypeDirName = containerType + "-" + archetypeDirName ; File archetypeDir = new File ( outputDir , archetypeDirName ) ; generateArchetype ( projectDir , projectPom , archetypeDir , clean , dirs ) ; } else { String childContainerType = file . getName ( ) ; if ( Strings . isNotBlank ( containerType ) ) { childContainerType = containerType + "-" + childContainerType ; } generateArchetypes ( childContainerType , file , outputDir , clean , dirs ) ; } } } } } }
Iterates through all nested directories and generates archetypes for all found non - pom Maven projects .
1,636
private static boolean skipImport ( File dir ) { String [ ] files = dir . list ( ) ; if ( files != null ) { for ( String name : files ) { if ( ".skipimport" . equals ( name ) ) { return true ; } } } return false ; }
We should skip importing some quickstarts and if so we should also not create an archetype for it
1,637
private boolean fileIncludesLine ( File file , String matches ) throws IOException { for ( String line : Files . readLines ( file ) ) { String trimmed = line . trim ( ) ; if ( trimmed . equals ( matches ) ) { return true ; } } return false ; }
Checks whether the file contains specific line . Partial matches do not count .
1,638
protected void copyOtherFiles ( File projectDir , File srcDir , File outDir , Replacement replaceFn , Set < String > extraIgnorefiles ) throws IOException { if ( archetypeUtils . isValidFileToCopy ( projectDir , srcDir , extraIgnorefiles ) ) { if ( srcDir . isFile ( ) ) { copyFile ( srcDir , outDir , replaceFn ) ; } else { outDir . mkdirs ( ) ; String [ ] names = srcDir . list ( ) ; if ( names != null ) { for ( String name : names ) { copyOtherFiles ( projectDir , new File ( srcDir , name ) , new File ( outDir , name ) , replaceFn , extraIgnorefiles ) ; } } } } }
Copies all other source files which are not excluded
1,639
protected boolean isSourceFile ( File file ) { String name = file . getName ( ) ; String extension = Files . getExtension ( name ) . toLowerCase ( ) ; return sourceFileExtensions . contains ( extension ) || sourceFileNames . contains ( name ) ; }
Returns true if this file is a valid source file name
1,640
protected boolean isValidRequiredPropertyName ( String name ) { return ! name . equals ( "basedir" ) && ! name . startsWith ( "project." ) && ! name . startsWith ( "pom." ) && ! name . equals ( "package" ) ; }
Returns true if this is a valid archetype property name so excluding basedir and maven project . names
1,641
protected boolean isSpecialPropertyName ( String name ) { for ( String special : specialVersions ) { if ( special . equals ( name ) ) { return true ; } } return false ; }
Returns true if its a special property name such as Camel ActiveMQ etc .
1,642
private boolean addPropertyElement ( Element element , String elementName , String textContent ) { Document doc = element . getOwnerDocument ( ) ; Element newElement = doc . createElement ( elementName ) ; newElement . setTextContent ( textContent ) ; Text textNode = doc . createTextNode ( "\n " ) ; NodeList childNodes = element . getChildNodes ( ) ; for ( int i = 0 , size = childNodes . getLength ( ) ; i < size ; i ++ ) { Node item = childNodes . item ( i ) ; if ( item instanceof Element ) { Element childElement = ( Element ) item ; int value = childElement . getTagName ( ) . compareTo ( elementName ) ; if ( value == 0 ) { return false ; } if ( value > 0 ) { element . insertBefore ( textNode , childElement ) ; element . insertBefore ( newElement , textNode ) ; return true ; } } } element . appendChild ( textNode ) ; element . appendChild ( newElement ) ; return true ; }
Lets add a child element at the right place
1,643
protected String removeInvalidHeaderCommentsAndProcessVelocityMacros ( String text ) { String answer = "" ; String [ ] lines = text . split ( "\r?\n" ) ; for ( String line : lines ) { String l = line . trim ( ) ; if ( ! l . startsWith ( "##" ) && ! l . startsWith ( "#set(" ) ) { if ( line . contains ( "${D}" ) ) { line = line . replaceAll ( "\\$\\{D\\}" , "\\$" ) ; } answer = answer . concat ( line ) ; answer = answer . concat ( System . lineSeparator ( ) ) ; } } return answer ; }
This method should do a full Velocity macro processing ...
1,644
public File findRootPackage ( File directory ) throws IOException { if ( ! directory . isDirectory ( ) ) { throw new IllegalArgumentException ( "Can't find package inside file. Argument should be valid directory." ) ; } File [ ] children = directory . listFiles ( new FileFilter ( ) { public boolean accept ( File pathname ) { return isValidSourceFileOrDir ( pathname ) ; } } ) ; if ( children != null ) { List < File > results = new LinkedList < File > ( ) ; for ( File it : children ) { if ( ! it . isDirectory ( ) ) { results . add ( directory ) ; break ; } else { File pkg = findRootPackage ( it ) ; if ( pkg != null ) { results . add ( pkg ) ; } } } if ( results . size ( ) == 1 ) { return results . get ( 0 ) ; } else { return directory ; } } return null ; }
Recursively looks for first nested directory which contains at least one source file
1,645
public boolean isValidSourceFileOrDir ( File file ) { String name = file . getName ( ) ; return ! isExcludedDotFile ( name ) && ! excludeExtensions . contains ( Files . getExtension ( file . getName ( ) ) ) ; }
Returns true if this file is a valid source file ; so excluding things like . svn directories and whatnot
1,646
public void writeXmlDocument ( Document document , File file ) throws IOException { try { Transformer tr = transformerFactory . newTransformer ( ) ; tr . setOutputProperty ( OutputKeys . ENCODING , "UTF-8" ) ; tr . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; FileOutputStream fileOutputStream = new FileOutputStream ( file ) ; tr . transform ( new DOMSource ( document ) , new StreamResult ( fileOutputStream ) ) ; fileOutputStream . close ( ) ; } catch ( Exception e ) { throw new IOException ( e . getMessage ( ) , e ) ; } }
Serializes the Document to a File .
1,647
public String writeXmlDocumentAsString ( Document document ) throws IOException { try { Transformer tr = transformerFactory . newTransformer ( ) ; tr . setOutputProperty ( OutputKeys . ENCODING , "UTF-8" ) ; tr . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; StringWriter writer = new StringWriter ( ) ; StreamResult result = new StreamResult ( writer ) ; TransformerFactory tf = TransformerFactory . newInstance ( ) ; tr . transform ( new DOMSource ( document ) , result ) ; return writer . toString ( ) ; } catch ( Exception e ) { throw new IOException ( e . getMessage ( ) , e ) ; } }
Serializes the Document to a String .
1,648
public static void notNull ( final Object object , final String argumentName ) { if ( object == null ) { throw new NullPointerException ( getMessage ( "null" , argumentName ) ) ; } }
Validates that the supplied object is not null and throws a NullPointerException otherwise .
1,649
public static void notEmpty ( final String aString , final String argumentName ) { notNull ( aString , argumentName ) ; if ( aString . length ( ) == 0 ) { throw new IllegalArgumentException ( getMessage ( "empty" , argumentName ) ) ; } }
Validates that the supplied object is not null and throws an IllegalArgumentException otherwise .
1,650
private String getNamespace ( final Attr attribute ) { final Element parent = attribute . getOwnerElement ( ) ; return parent . getAttribute ( NAMESPACE ) ; }
Retrieves the value of the namespace attribute found within the parent element of the provided attribute .
1,651
public void restore ( ) { if ( ! restored ) { rootLogger . removeHandler ( mavenLogHandler ) ; rootLogger . setLevel ( originalRootLoggerLevel ) ; for ( Handler current : originalHandlers ) { rootLogger . addHandler ( current ) ; } restored = true ; } }
Restores the original root Logger state including Level and Handlers .
1,652
public static LoggingHandlerEnvironmentFacet create ( final Log mavenLog , final Class < ? extends AbstractJaxbMojo > caller , final String encoding ) { Validate . notNull ( mavenLog , "mavenLog" ) ; Validate . notNull ( caller , "caller" ) ; Validate . notEmpty ( encoding , "encoding" ) ; final String logPrefix = caller . getClass ( ) . getCanonicalName ( ) . toUpperCase ( ) . contains ( "XJC" ) ? "XJC" : "SchemaGen" ; return new LoggingHandlerEnvironmentFacet ( logPrefix , mavenLog , encoding , DEFAULT_LOGGER_NAMES ) ; }
Factory method creating a new LoggingHandlerEnvironmentFacet wrapping the supplied properties .
1,653
public ThreadContextClassLoaderBuilder addURL ( final URL anURL ) { Validate . notNull ( anURL , "anURL" ) ; for ( URL current : urlList ) { if ( current . toString ( ) . equalsIgnoreCase ( anURL . toString ( ) ) ) { if ( log . isWarnEnabled ( ) ) { log . warn ( "Not adding URL [" + anURL . toString ( ) + "] twice. Check your plugin configuration." ) ; } return this ; } } if ( log . isDebugEnabled ( ) ) { log . debug ( "Adding URL [" + anURL . toString ( ) + "]" ) ; } urlList . add ( addSlashToDirectoryUrlIfRequired ( anURL ) ) ; return this ; }
Adds the supplied anURL to the list of internal URLs which should be used to build an URLClassLoader . Will only add an URL once and warns about trying to re - add an URL .
1,654
public static ThreadContextClassLoaderBuilder createFor ( final ClassLoader classLoader , final Log log , final String encoding ) { Validate . notNull ( classLoader , "classLoader" ) ; Validate . notNull ( log , "log" ) ; return new ThreadContextClassLoaderBuilder ( classLoader , log , encoding ) ; }
Creates a new ThreadContextClassLoaderBuilder using the supplied original classLoader as well as the supplied Maven Log .
1,655
public static ThreadContextClassLoaderBuilder createFor ( final Class < ? > aClass , final Log log , final String encoding ) { Validate . notNull ( aClass , "aClass" ) ; return createFor ( aClass . getClassLoader ( ) , log , encoding ) ; }
Creates a new ThreadContextClassLoaderBuilder using the original ClassLoader from the supplied Class as well as the given Maven Log .
1,656
public static String getClassPathElement ( final URL anURL , final String encoding ) throws IllegalArgumentException { Validate . notNull ( anURL , "anURL" ) ; final String protocol = anURL . getProtocol ( ) ; String toReturn = null ; if ( FILE . supports ( protocol ) ) { final String originalPath = anURL . getPath ( ) ; try { return URLDecoder . decode ( anURL . getPath ( ) , encoding ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalArgumentException ( "Could not URLDecode path [" + originalPath + "] using encoding [" + encoding + "]" , e ) ; } } else if ( JAR . supports ( protocol ) ) { toReturn = anURL . getPath ( ) ; } else if ( HTTP . supports ( protocol ) || HTTPS . supports ( protocol ) ) { toReturn = anURL . toString ( ) ; } else if ( BUNDLERESOURCE . supports ( protocol ) ) { toReturn = anURL . toString ( ) ; } else { throw new IllegalArgumentException ( "Unknown protocol [" + protocol + "]; could not handle URL [" + anURL + "]" ) ; } return toReturn ; }
Converts the supplied URL to a class path element .
1,657
protected String renderJavaDocTag ( final String name , final String value , final SortableLocation location ) { final String nameKey = name != null ? name . trim ( ) : "" ; final String valueKey = value != null ? value . trim ( ) : "" ; return "(" + nameKey + "): " + harmonizeNewlines ( valueKey ) ; }
Override this method to yield another
1,658
protected String harmonizeNewlines ( final String original ) { final String toReturn = original . trim ( ) . replaceAll ( "[\r\n]+" , "\n" ) ; return toReturn . endsWith ( "\n" ) ? toReturn : toReturn + "\n" ; }
Squashes newline characters into
1,659
@ SuppressWarnings ( "all" ) protected void warnAboutIncorrectPluginConfiguration ( final String propertyName , final String description ) { final StringBuilder builder = new StringBuilder ( ) ; builder . append ( "\n+=================== [Incorrect Plugin Configuration Detected]\n" ) ; builder . append ( "|\n" ) ; builder . append ( "| Property : " + propertyName + "\n" ) ; builder . append ( "| Problem : " + description + "\n" ) ; builder . append ( "|\n" ) ; builder . append ( "+=================== [End Incorrect Plugin Configuration Detected]\n\n" ) ; getLog ( ) . warn ( builder . toString ( ) . replace ( "\n" , NEWLINE ) ) ; }
Convenience method to invoke when some plugin configuration is incorrect . Will output the problem as a warning with some degree of log formatting .
1,660
protected final File getStaleFile ( ) { final String staleFileName = "." + ( getExecution ( ) == null ? "nonExecutionJaxb" : getExecution ( ) . getExecutionId ( ) ) + "-" + getStaleFileName ( ) ; return new File ( staleFileDirectory , staleFileName ) ; }
Acquires the staleFile for this execution
1,661
protected void logSystemPropertiesAndBasedir ( ) { if ( getLog ( ) . isDebugEnabled ( ) ) { final StringBuilder builder = new StringBuilder ( ) ; builder . append ( "\n+=================== [System properties]\n" ) ; builder . append ( "|\n" ) ; final SortedMap < String , Object > props = new TreeMap < String , Object > ( ) ; props . put ( "basedir" , FileSystemUtilities . getCanonicalPath ( getProject ( ) . getBasedir ( ) ) ) ; for ( Map . Entry < Object , Object > current : System . getProperties ( ) . entrySet ( ) ) { props . put ( "" + current . getKey ( ) , current . getValue ( ) ) ; } for ( Map . Entry < String , Object > current : props . entrySet ( ) ) { builder . append ( "| [" + current . getKey ( ) + "]: " + current . getValue ( ) + "\n" ) ; } builder . append ( "|\n" ) ; builder . append ( "+=================== [End System properties]\n" ) ; getLog ( ) . debug ( builder . toString ( ) . replace ( "\n" , NEWLINE ) ) ; } }
Prints out the system properties to the Maven Log at Debug level .
1,662
public static LocaleFacet createFor ( final String localeString , final Log log ) throws MojoExecutionException { Validate . notNull ( log , "log" ) ; Validate . notEmpty ( localeString , "localeString" ) ; final StringTokenizer tok = new StringTokenizer ( localeString , "," , false ) ; final int numTokens = tok . countTokens ( ) ; if ( numTokens > 3 || numTokens == 0 ) { throw new MojoExecutionException ( "A localeString must consist of up to 3 comma-separated parts on the " + "form <language>[,<country>[,<variant>]]. Received incorrect value '" + localeString + "'" ) ; } final String language = tok . nextToken ( ) . trim ( ) ; final String country = numTokens > 1 ? tok . nextToken ( ) . trim ( ) : null ; final String variant = numTokens > 2 ? tok . nextToken ( ) . trim ( ) : null ; return new LocaleFacet ( log , findOptimumLocale ( language , country , variant ) ) ; }
Helper method used to parse a locale configuration string into a Locale instance .
1,663
public static Level getJavaUtilLoggingLevelFor ( final Log mavenLog ) { Validate . notNull ( mavenLog , "mavenLog" ) ; Level toReturn = Level . SEVERE ; if ( mavenLog . isDebugEnabled ( ) ) { toReturn = Level . FINER ; } else if ( mavenLog . isInfoEnabled ( ) ) { toReturn = Level . INFO ; } else if ( mavenLog . isWarnEnabled ( ) ) { toReturn = Level . WARNING ; } return toReturn ; }
Retrieves the JUL Level matching the supplied Maven Log .
1,664
public static Filter getLoggingFilter ( final String ... requiredPrefixes ) { Validate . notNull ( requiredPrefixes , "requiredPrefixes" ) ; return new Filter ( ) { private List < String > requiredPrefs = Arrays . asList ( requiredPrefixes ) ; public boolean isLoggable ( final LogRecord record ) { final String loggerName = record . getLoggerName ( ) ; for ( String current : requiredPrefs ) { if ( loggerName . startsWith ( current ) ) { return true ; } } return false ; } } ; }
Retrieves a java . util . Logging filter used to ensure that only LogRecords whose logger names start with any of the required prefixes are logged .
1,665
public static boolean isNamedElement ( final Node aNode ) { final boolean isElementNode = aNode != null && aNode . getNodeType ( ) == Node . ELEMENT_NODE ; return isElementNode && getNamedAttribute ( aNode , NAME_ATTRIBUTE ) != null && ! getNamedAttribute ( aNode , NAME_ATTRIBUTE ) . isEmpty ( ) ; }
Checks if the supplied DOM Node is a DOM Element having a defined name attribute .
1,666
public static String getElementTagName ( final Node aNode ) { if ( aNode != null && aNode . getNodeType ( ) == Node . ELEMENT_NODE ) { final Element theElement = ( Element ) aNode ; return theElement . getTagName ( ) ; } return null ; }
Retrieves the TagName for the supplied Node if it is an Element and null otherwise .
1,667
public static String getXPathFor ( final Node aNode ) { List < String > nodeNameList = new ArrayList < String > ( ) ; for ( Node current = aNode ; current != null ; current = current . getParentNode ( ) ) { final String currentNodeName = current . getNodeName ( ) ; final String nameAttribute = DomHelper . getNameAttribute ( current ) ; if ( currentNodeName . toLowerCase ( ) . endsWith ( "enumeration" ) ) { nodeNameList . add ( currentNodeName + "[@value='" + getValueAttribute ( current ) + "']" ) ; } else if ( nameAttribute == null ) { nodeNameList . add ( current . getNodeName ( ) ) ; } else { nodeNameList . add ( current . getNodeName ( ) + "[@name='" + nameAttribute + "']" ) ; } } StringBuilder builder = new StringBuilder ( ) ; for ( ListIterator < String > it = nodeNameList . listIterator ( nodeNameList . size ( ) ) ; it . hasPrevious ( ) ; ) { builder . append ( it . previous ( ) ) ; if ( it . hasPrevious ( ) ) { builder . append ( "/" ) ; } } return builder . toString ( ) ; }
Retrieves the XPath for the supplied Node within its document .
1,668
public static ClassLocation getClassLocation ( final Node aNode , final Set < ClassLocation > classLocations ) { if ( aNode != null ) { final String nodeLocalName = aNode . getLocalName ( ) ; final boolean acceptableType = "complexType" . equalsIgnoreCase ( nodeLocalName ) || "simpleType" . equalsIgnoreCase ( nodeLocalName ) ; if ( acceptableType ) { final String nodeClassName = DomHelper . getNameAttribute ( aNode ) ; for ( ClassLocation current : classLocations ) { final String effectiveClassName = current . getAnnotationRenamedTo ( ) == null ? current . getClassName ( ) : current . getAnnotationRenamedTo ( ) ; if ( effectiveClassName . equalsIgnoreCase ( nodeClassName ) ) { return current ; } } } } return null ; }
Retrieves the ClassLocation for the supplied aNode .
1,669
public static MethodLocation getMethodLocation ( final Node aNode , final Set < MethodLocation > methodLocations ) { MethodLocation toReturn = null ; if ( aNode != null && CLASS_FIELD_METHOD_ELEMENT_NAMES . contains ( aNode . getLocalName ( ) . toLowerCase ( ) ) ) { final MethodLocation validLocation = getFieldOrMethodLocationIfValid ( aNode , getContainingClassOrNull ( aNode ) , methodLocations ) ; if ( validLocation != null && MethodLocation . NO_PARAMETERS . equalsIgnoreCase ( validLocation . getParametersAsString ( ) ) ) { toReturn = validLocation ; } } return toReturn ; }
Finds the MethodLocation within the given Set which corresponds to the supplied DOM Node .
1,670
public static FieldLocation getFieldLocation ( final Node aNode , final Set < FieldLocation > fieldLocations ) { FieldLocation toReturn = null ; if ( aNode != null ) { if ( CLASS_FIELD_METHOD_ELEMENT_NAMES . contains ( aNode . getLocalName ( ) . toLowerCase ( ) ) ) { toReturn = getFieldOrMethodLocationIfValid ( aNode , getContainingClassOrNull ( aNode ) , fieldLocations ) ; } else if ( ENUMERATION_FIELD_METHOD_ELEMENT_NAMES . contains ( aNode . getLocalName ( ) . toLowerCase ( ) ) ) { toReturn = getFieldOrMethodLocationIfValid ( aNode , getContainingClassOrNull ( aNode ) , fieldLocations ) ; } } return toReturn ; }
Retrieves a FieldLocation from the supplied Set provided that the FieldLocation matches the supplied Node .
1,671
public static < T extends FieldLocation > T getFieldOrMethodLocationIfValid ( final Node aNode , final Node containingClassNode , final Set < ? extends FieldLocation > locations ) { T toReturn = null ; if ( containingClassNode != null ) { for ( FieldLocation current : locations ) { final String fieldName = current . getAnnotationRenamedTo ( ) == null ? current . getMemberName ( ) : current . getAnnotationRenamedTo ( ) ; final String className = current . getClassName ( ) ; try { final String attributeValue = DomHelper . getNameAttribute ( aNode ) == null ? DomHelper . getValueAttribute ( aNode ) : DomHelper . getNameAttribute ( aNode ) ; if ( fieldName . equalsIgnoreCase ( attributeValue ) && className . equalsIgnoreCase ( DomHelper . getNameAttribute ( containingClassNode ) ) ) { toReturn = ( T ) current ; } } catch ( Exception e ) { throw new IllegalStateException ( "Could not acquire FieldLocation for fieldName [" + fieldName + "] and className [" + className + "]" , e ) ; } } } return toReturn ; }
Retrieves a FieldLocation or MethodLocation from the supplied Set of Field - or MethodLocations provided that the supplied Node has the given containing Node corresponding to a Class or an Enum .
1,672
public static void insertXmlDocumentationAnnotationsFor ( final Node aNode , final SortedMap < ClassLocation , JavaDocData > classJavaDocs , final SortedMap < FieldLocation , JavaDocData > fieldJavaDocs , final SortedMap < MethodLocation , JavaDocData > methodJavaDocs , final JavaDocRenderer renderer ) { JavaDocData javaDocData = null ; SortableLocation location = null ; final ClassLocation classLocation = DomHelper . getClassLocation ( aNode , classJavaDocs . keySet ( ) ) ; if ( classLocation != null ) { javaDocData = classJavaDocs . get ( classLocation ) ; location = classLocation ; } else { final FieldLocation fieldLocation = DomHelper . getFieldLocation ( aNode , fieldJavaDocs . keySet ( ) ) ; if ( fieldLocation != null ) { javaDocData = fieldJavaDocs . get ( fieldLocation ) ; location = fieldLocation ; } else { final MethodLocation methodLocation = DomHelper . getMethodLocation ( aNode , methodJavaDocs . keySet ( ) ) ; if ( methodLocation != null ) { javaDocData = methodJavaDocs . get ( methodLocation ) ; location = methodLocation ; } } } if ( javaDocData == null ) { final String nodeName = aNode . getNodeName ( ) ; String humanReadableName = DomHelper . getNameAttribute ( aNode ) ; if ( humanReadableName == null && nodeName . toLowerCase ( ) . endsWith ( "enumeration" ) ) { humanReadableName = "enumeration#" + getValueAttribute ( aNode ) ; } throw new IllegalStateException ( "Could not find JavaDocData for XSD node [" + humanReadableName + "] with XPath [" + DomHelper . getXPathFor ( aNode ) + "]" ) ; } final String processedJavaDoc = renderer . render ( javaDocData , location ) . trim ( ) ; DomHelper . addXmlDocumentAnnotationTo ( aNode , processedJavaDoc ) ; }
Processes the supplied DOM Node inserting XML Documentation annotations if applicable .
1,673
private void initialize ( final Reader xmlFileStream ) { final Document parsedDocument = XsdGeneratorHelper . parseXmlStream ( xmlFileStream ) ; XsdGeneratorHelper . process ( parsedDocument . getFirstChild ( ) , true , new NamespaceAttributeNodeProcessor ( ) ) ; }
Initializes this SimpleNamespaceResolver to collect namespace data from the provided stream .
1,674
public final void setPatternPrefix ( final String patternPrefix ) { validateDiSetterCalledBeforeInitialization ( "patternPrefix" ) ; if ( patternPrefix != null ) { this . patternPrefix = patternPrefix ; } else { addDelayedLogMessage ( "warn" , "Received null patternPrefix for configuring AbstractPatternFilter of type [" + getClass ( ) . getName ( ) + "]. Ignoring and proceeding." ) ; } }
Assigns a prefix to be prepended to any patterns submitted to this AbstractPatternFilter .
1,675
public void setConverter ( final StringConverter < T > converter ) { Validate . notNull ( converter , "converter" ) ; validateDiSetterCalledBeforeInitialization ( "converter" ) ; this . converter = converter ; }
Assigns the StringConverter used to convert T - type objects to Strings . This StringConverter is used to acquire input comparison values for all Patterns to T - object candidates .
1,676
public static < T > boolean matchAtLeastOnce ( final T object , final List < Filter < T > > filters ) { Validate . notNull ( filters , "filters" ) ; boolean acceptedByAtLeastOneFilter = false ; for ( Filter < T > current : filters ) { if ( current . accept ( object ) ) { acceptedByAtLeastOneFilter = true ; break ; } } return acceptedByAtLeastOneFilter ; }
Algorithms for accepting the supplied object if at least one of the supplied Filters accepts it .
1,677
public static < T > boolean rejectAtLeastOnce ( final T object , final List < Filter < T > > filters ) { Validate . notNull ( filters , "filters" ) ; boolean rejectedByAtLeastOneFilter = false ; for ( Filter < T > current : filters ) { if ( ! current . accept ( object ) ) { rejectedByAtLeastOneFilter = true ; break ; } } return rejectedByAtLeastOneFilter ; }
Algorithms for rejecting the supplied object if at least one of the supplied Filters does not accept it .
1,678
public static < T > boolean noFilterMatches ( final T object , final List < Filter < T > > filters ) { Validate . notNull ( filters , "filters" ) ; boolean matchedAtLeastOnce = false ; for ( Filter < T > current : filters ) { if ( current . accept ( object ) ) { matchedAtLeastOnce = true ; } } return ! matchedAtLeastOnce ; }
Algorithms for rejecting the supplied object if at least one of the supplied Filters rejects it .
1,679
public static FileFilter adapt ( final Filter < File > toAdapt ) { Validate . notNull ( toAdapt , "toAdapt" ) ; if ( toAdapt instanceof FileFilter ) { return ( FileFilter ) toAdapt ; } return new FileFilter ( ) { public boolean accept ( final File candidate ) { return toAdapt . accept ( candidate ) ; } } ; }
Adapts the Filter specification to the FileFilter interface to enable immediate use for filtering File lists .
1,680
public static List < FileFilter > adapt ( final List < Filter < File > > toAdapt ) { final List < FileFilter > toReturn = new ArrayList < FileFilter > ( ) ; if ( toAdapt != null ) { for ( Filter < File > current : toAdapt ) { toReturn . add ( adapt ( current ) ) ; } } return toReturn ; }
Adapts the supplied List of Filter specifications to a List of FileFilters .
1,681
public static < T > void initialize ( final Log log , final List < Filter < T > > filters ) { Validate . notNull ( log , "log" ) ; Validate . notNull ( filters , "filters" ) ; for ( Filter < T > current : filters ) { current . initialize ( log ) ; } }
Initializes the supplied Filters by assigning the given Log .
1,682
public static File getCanonicalFile ( final File file ) { Validate . notNull ( file , "file" ) ; try { return file . getCanonicalFile ( ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( "Could not acquire the canonical file for [" + file . getAbsolutePath ( ) + "]" , e ) ; } }
Acquires the canonical File for the supplied file .
1,683
public static URL getUrlFor ( final File aFile ) throws IllegalArgumentException { Validate . notNull ( aFile , "aFile" ) ; try { return aFile . toURI ( ) . normalize ( ) . toURL ( ) ; } catch ( MalformedURLException e ) { throw new IllegalArgumentException ( "Could not retrieve the URL from file [" + getCanonicalPath ( aFile ) + "]" , e ) ; } }
Retrieves the URL for the supplied File . Convenience method which hides exception handling for the operation in question .
1,684
public static File getFileFor ( final URL anURL , final String encoding ) { Validate . notNull ( anURL , "anURL" ) ; Validate . notNull ( encoding , "encoding" ) ; final String protocol = anURL . getProtocol ( ) ; File toReturn = null ; if ( "file" . equalsIgnoreCase ( protocol ) ) { try { final String decodedPath = URLDecoder . decode ( anURL . getPath ( ) , encoding ) ; toReturn = new File ( decodedPath ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Could not get the File for [" + anURL + "]" , e ) ; } } else if ( "jar" . equalsIgnoreCase ( protocol ) ) { try { final String tmp = URLDecoder . decode ( anURL . getFile ( ) , encoding ) ; final URL innerURL = new URL ( tmp ) ; if ( "file" . equalsIgnoreCase ( innerURL . getProtocol ( ) ) ) { final String innerUrlPath = innerURL . getPath ( ) ; final String filePath = innerUrlPath . contains ( "!" ) ? innerUrlPath . substring ( 0 , innerUrlPath . indexOf ( "!" ) ) : innerUrlPath ; toReturn = new File ( URLDecoder . decode ( filePath , encoding ) ) ; } } catch ( Exception e ) { throw new IllegalArgumentException ( "Could not get the File for [" + anURL + "]" , e ) ; } } return toReturn ; }
Acquires the file for a supplied URL provided that its protocol is is either a file or a jar .
1,685
public static void createDirectory ( final File aDirectory , final boolean cleanBeforeCreate ) throws MojoExecutionException { Validate . notNull ( aDirectory , "aDirectory" ) ; validateFileOrDirectoryName ( aDirectory ) ; if ( cleanBeforeCreate ) { try { FileUtils . deleteDirectory ( aDirectory ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Could not clean directory [" + getCanonicalPath ( aDirectory ) + "]" , e ) ; } } final boolean existsAsFile = aDirectory . exists ( ) && aDirectory . isFile ( ) ; if ( existsAsFile ) { throw new MojoExecutionException ( "[" + getCanonicalPath ( aDirectory ) + "] exists and is a file. " + "Cannot make directory" ) ; } else if ( ! aDirectory . exists ( ) && ! aDirectory . mkdirs ( ) ) { throw new MojoExecutionException ( "Could not create directory [" + getCanonicalPath ( aDirectory ) + "]" ) ; } }
Convenience method to successfully create a directory - or throw an exception if failing to create it .
1,686
public static String relativize ( final String path , final File parentDir , final boolean removeInitialFileSep ) { Validate . notNull ( path , "path" ) ; Validate . notNull ( parentDir , "parentDir" ) ; final String basedirPath = FileSystemUtilities . getCanonicalPath ( parentDir ) ; String toReturn = path ; if ( path . toLowerCase ( ) . startsWith ( basedirPath . toLowerCase ( ) ) ) { toReturn = path . substring ( basedirPath . length ( ) ) ; } return removeInitialFileSep && toReturn . startsWith ( File . separator ) ? toReturn . substring ( File . separator . length ( ) ) : toReturn ; }
If the supplied path refers to a file or directory below the supplied basedir the returned path is identical to the part below the basedir .
1,687
public String getNormalizedXml ( String filePath ) { final StringWriter toReturn = new StringWriter ( ) ; final BufferedReader in ; try { in = new BufferedReader ( new FileReader ( new File ( filePath ) ) ) ; } catch ( FileNotFoundException e ) { throw new IllegalArgumentException ( "Could not find file [" + filePath + "]" , e ) ; } final DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; Document document = null ; try { document = factory . newDocumentBuilder ( ) . parse ( new InputSource ( in ) ) ; Transformer transformer = FACTORY . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . transform ( new DOMSource ( document . getFirstChild ( ) ) , new StreamResult ( toReturn ) ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Could not transform DOM Document" , e ) ; } return toReturn . toString ( ) ; }
Reads the XML file found at the provided filePath returning a normalized XML form suitable for comparison .
1,688
public static Map < String , SimpleNamespaceResolver > getFileNameToResolverMap ( final File outputDirectory ) throws MojoExecutionException { final Map < String , SimpleNamespaceResolver > toReturn = new TreeMap < String , SimpleNamespaceResolver > ( ) ; File [ ] generatedSchemaFiles = outputDirectory . listFiles ( new FileFilter ( ) { public boolean accept ( File pathname ) { return pathname . getName ( ) . startsWith ( "schema" ) && pathname . getName ( ) . endsWith ( ".xsd" ) ; } } ) ; for ( File current : generatedSchemaFiles ) { toReturn . put ( current . getName ( ) , new SimpleNamespaceResolver ( current ) ) ; } return toReturn ; }
Acquires a map relating generated schema filename to its SimpleNamespaceResolver .
1,689
public static void validateSchemasInPluginConfiguration ( final List < TransformSchema > configuredTransformSchemas ) throws MojoExecutionException { final List < String > uris = new ArrayList < String > ( ) ; final List < String > prefixes = new ArrayList < String > ( ) ; final List < String > fileNames = new ArrayList < String > ( ) ; for ( int i = 0 ; i < configuredTransformSchemas . size ( ) ; i ++ ) { final TransformSchema current = configuredTransformSchemas . get ( i ) ; final String currentURI = current . getUri ( ) ; final String currentPrefix = current . getToPrefix ( ) ; final String currentFile = current . getToFile ( ) ; if ( StringUtils . isEmpty ( currentURI ) ) { throw new MojoExecutionException ( MISCONFIG + "Null or empty property 'uri' found in " + "plugin configuration for schema element at index [" + i + "]: " + current ) ; } if ( StringUtils . isEmpty ( currentPrefix ) && StringUtils . isEmpty ( currentFile ) ) { throw new MojoExecutionException ( MISCONFIG + "Null or empty properties 'prefix' " + "and 'file' found within plugin configuration for schema element at index [" + i + "]: " + current ) ; } if ( uris . contains ( currentURI ) ) { throw new MojoExecutionException ( getDuplicationErrorMessage ( "uri" , currentURI , uris . indexOf ( currentURI ) , i ) ) ; } uris . add ( currentURI ) ; if ( prefixes . contains ( currentPrefix ) && ! ( currentPrefix == null ) ) { throw new MojoExecutionException ( getDuplicationErrorMessage ( "prefix" , currentPrefix , prefixes . indexOf ( currentPrefix ) , i ) ) ; } prefixes . add ( currentPrefix ) ; if ( fileNames . contains ( currentFile ) ) { throw new MojoExecutionException ( getDuplicationErrorMessage ( "file" , currentFile , fileNames . indexOf ( currentFile ) , i ) ) ; } fileNames . add ( currentFile ) ; } }
Validates that the list of Schemas provided within the configuration all contain unique values . Should a MojoExecutionException be thrown it contains informative text about the exact nature of the configuration problem - we should simplify for all plugin users .
1,690
public static int insertJavaDocAsAnnotations ( final Log log , final String encoding , final File outputDir , final SearchableDocumentation docs , final JavaDocRenderer renderer ) { Validate . notNull ( docs , "docs" ) ; Validate . notNull ( log , "log" ) ; Validate . notNull ( outputDir , "outputDir" ) ; Validate . isTrue ( outputDir . isDirectory ( ) , "'outputDir' must be a Directory." ) ; Validate . notNull ( renderer , "renderer" ) ; int processedXSDs = 0 ; final List < File > foundFiles = new ArrayList < File > ( ) ; addRecursively ( foundFiles , RECURSIVE_XSD_FILTER , outputDir ) ; if ( foundFiles . size ( ) > 0 ) { final XsdAnnotationProcessor classProcessor = new XsdAnnotationProcessor ( docs , renderer ) ; final XsdEnumerationAnnotationProcessor enumProcessor = new XsdEnumerationAnnotationProcessor ( docs , renderer ) ; for ( File current : foundFiles ) { final Document generatedSchemaFileDocument = parseXmlToDocument ( current ) ; process ( generatedSchemaFileDocument . getFirstChild ( ) , true , classProcessor ) ; processedXSDs ++ ; savePrettyPrintedDocument ( generatedSchemaFileDocument , current , encoding ) ; } } else { if ( log . isWarnEnabled ( ) ) { log . warn ( "Found no generated 'vanilla' XSD files to process under [" + FileSystemUtilities . getCanonicalPath ( outputDir ) + "]. Aborting processing." ) ; } } return processedXSDs ; }
Inserts XML documentation annotations into all generated XSD files found within the supplied outputDir .
1,691
public static void replaceNamespacePrefixes ( final Map < String , SimpleNamespaceResolver > resolverMap , final List < TransformSchema > configuredTransformSchemas , final Log mavenLog , final File schemaDirectory , final String encoding ) throws MojoExecutionException { if ( mavenLog . isDebugEnabled ( ) ) { mavenLog . debug ( "Got resolverMap.keySet() [generated filenames]: " + resolverMap . keySet ( ) ) ; } for ( SimpleNamespaceResolver currentResolver : resolverMap . values ( ) ) { File generatedSchemaFile = new File ( schemaDirectory , currentResolver . getSourceFilename ( ) ) ; Document generatedSchemaFileDocument = null ; for ( TransformSchema currentTransformSchema : configuredTransformSchemas ) { final String newPrefix = currentTransformSchema . getToPrefix ( ) ; final String currentUri = currentTransformSchema . getUri ( ) ; if ( StringUtils . isNotEmpty ( newPrefix ) ) { final String oldPrefix = currentResolver . getNamespaceURI2PrefixMap ( ) . get ( currentUri ) ; if ( StringUtils . isNotEmpty ( oldPrefix ) ) { validatePrefixSubstitutionIsPossible ( oldPrefix , newPrefix , currentResolver ) ; if ( mavenLog . isDebugEnabled ( ) ) { mavenLog . debug ( "Subtituting namespace prefix [" + oldPrefix + "] with [" + newPrefix + "] in file [" + currentResolver . getSourceFilename ( ) + "]." ) ; } if ( generatedSchemaFileDocument == null ) { generatedSchemaFileDocument = parseXmlToDocument ( generatedSchemaFile ) ; } process ( generatedSchemaFileDocument . getFirstChild ( ) , true , new ChangeNamespacePrefixProcessor ( oldPrefix , newPrefix ) ) ; } } } if ( generatedSchemaFileDocument != null ) { mavenLog . debug ( "Overwriting file [" + currentResolver . getSourceFilename ( ) + "] with content [" + getHumanReadableXml ( generatedSchemaFileDocument ) + "]" ) ; savePrettyPrintedDocument ( generatedSchemaFileDocument , generatedSchemaFile , encoding ) ; } else { mavenLog . debug ( "No namespace prefix changes to generated schema file [" + generatedSchemaFile . getName ( ) + "]" ) ; } } }
Replaces all namespaces within generated schema files as instructed by the configured Schema instances .
1,692
public static void renameGeneratedSchemaFiles ( final Map < String , SimpleNamespaceResolver > resolverMap , final List < TransformSchema > configuredTransformSchemas , final Log mavenLog , final File schemaDirectory , final String charsetName ) { Map < String , String > namespaceUriToDesiredFilenameMap = new TreeMap < String , String > ( ) ; for ( TransformSchema current : configuredTransformSchemas ) { if ( StringUtils . isNotEmpty ( current . getToFile ( ) ) ) { namespaceUriToDesiredFilenameMap . put ( current . getUri ( ) , current . getToFile ( ) ) ; } } for ( SimpleNamespaceResolver currentResolver : resolverMap . values ( ) ) { File generatedSchemaFile = new File ( schemaDirectory , currentResolver . getSourceFilename ( ) ) ; Document generatedSchemaFileDocument = parseXmlToDocument ( generatedSchemaFile ) ; process ( generatedSchemaFileDocument . getFirstChild ( ) , true , new ChangeFilenameProcessor ( namespaceUriToDesiredFilenameMap ) ) ; if ( mavenLog . isDebugEnabled ( ) ) { mavenLog . debug ( "Changed schemaLocation entries within [" + currentResolver . getSourceFilename ( ) + "]. " + "Result: [" + getHumanReadableXml ( generatedSchemaFileDocument ) + "]" ) ; } savePrettyPrintedDocument ( generatedSchemaFileDocument , generatedSchemaFile , charsetName ) ; } for ( SimpleNamespaceResolver currentResolver : resolverMap . values ( ) ) { final String localNamespaceURI = currentResolver . getLocalNamespaceURI ( ) ; if ( StringUtils . isEmpty ( localNamespaceURI ) ) { mavenLog . warn ( "SimpleNamespaceResolver contained no localNamespaceURI; aborting rename." ) ; continue ; } final String newFilename = namespaceUriToDesiredFilenameMap . get ( localNamespaceURI ) ; final File originalFile = new File ( schemaDirectory , currentResolver . getSourceFilename ( ) ) ; if ( StringUtils . isNotEmpty ( newFilename ) ) { File renamedFile = FileUtils . resolveFile ( schemaDirectory , newFilename ) ; String renameResult = ( originalFile . renameTo ( renamedFile ) ? "Success " : "Failure " ) ; if ( mavenLog . isDebugEnabled ( ) ) { String suffix = "renaming [" + originalFile . getAbsolutePath ( ) + "] to [" + renamedFile + "]" ; mavenLog . debug ( renameResult + suffix ) ; } } } }
Updates all schemaLocation attributes within the generated schema files to match the file properties within the Schemas read from the plugin configuration . After that the files are physically renamed .
1,693
public static Document parseXmlStream ( final Reader xmlStream ) { final DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; try { return factory . newDocumentBuilder ( ) . parse ( new InputSource ( xmlStream ) ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Could not acquire DOM Document" , e ) ; } }
Parses the provided InputStream to create a dom Document .
1,694
protected static String getHumanReadableXml ( final Node node ) { StringWriter toReturn = new StringWriter ( ) ; try { Transformer transformer = getFactory ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( OutputKeys . STANDALONE , "yes" ) ; transformer . transform ( new DOMSource ( node ) , new StreamResult ( toReturn ) ) ; } catch ( TransformerException e ) { throw new IllegalStateException ( "Could not transform node [" + node . getNodeName ( ) + "] to XML" , e ) ; } return toReturn . toString ( ) ; }
Converts the provided DOM Node to a pretty - printed XML - formatted string .
1,695
private static Document parseXmlToDocument ( final File xmlFile ) { Document result = null ; Reader reader = null ; try { reader = new FileReader ( xmlFile ) ; result = parseXmlStream ( reader ) ; } catch ( FileNotFoundException e ) { } finally { IOUtil . close ( reader ) ; } return result ; }
Creates a Document from parsing the XML within the provided xmlFile .
1,696
public ArgumentBuilder withPreCompiledArguments ( final List < String > preCompiledArguments ) { Validate . notNull ( preCompiledArguments , "preCompiledArguments" ) ; synchronized ( lock ) { for ( String current : preCompiledArguments ) { arguments . add ( current ) ; } } return this ; }
Adds the supplied pre - compiled arguments in the same order as they were given .
1,697
public static int getJavaMajorVersion ( ) { final String [ ] versionElements = System . getProperty ( JAVA_VERSION_PROPERTY ) . split ( "\\." ) ; final int [ ] versionNumbers = new int [ versionElements . length ] ; for ( int i = 0 ; i < versionElements . length ; i ++ ) { try { versionNumbers [ i ] = Integer . parseInt ( versionElements [ i ] ) ; } catch ( NumberFormatException e ) { versionNumbers [ i ] = 0 ; } } return versionNumbers [ 0 ] == 1 ? versionNumbers [ 1 ] : versionNumbers [ 0 ] ; }
Retrieves the major java runtime version as an integer .
1,698
public < V , T extends Enum & Option > OptionsMapper env ( final String name , final T option , final Function < String , V > converter ) { register ( "env: " + name , option , System . getenv ( name ) , converter ) ; return this ; }
Map environment variable value to option .
1,699
public < V , T extends Enum & Option > OptionsMapper string ( final T option , final String value , final Function < String , V > converter ) { register ( "" , option , value , converter ) ; return this ; }
Map string to option . When value is null or empty - nothing happens .