idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
144,400
private String escapeText ( StringBuilder sb , String text ) { int length = text . length ( ) ; char c ; sb . setLength ( 0 ) ; for ( int loop = 0 ; loop < length ; loop ++ ) { c = text . charAt ( loop ) ; switch ( c ) { case ' ' : { sb . append ( "&lt;" ) ; break ; } case ' ' : { sb . append ( "&gt;" ) ; break ; } case ' ' : { sb . append ( "&amp;" ) ; break ; } default : { if ( validXMLCharacter ( c ) ) { if ( c > 127 ) { sb . append ( "&#" + ( int ) c + ";" ) ; } else { sb . append ( c ) ; } } break ; } } } return ( sb . toString ( ) ) ; }
Quick and dirty XML text escape .
192
7
144,401
public static String rset ( String input , int width ) { String result ; // result to return StringBuilder pad = new StringBuilder ( ) ; if ( input == null ) { for ( int i = 0 ; i < width - 1 ; i ++ ) { pad . append ( ' ' ) ; // put blanks into buffer } result = " " + pad ; // one short to use + overload } else { if ( input . length ( ) >= width ) { result = input . substring ( 0 , width ) ; // when input is too long, truncate } else { int padLength = width - input . length ( ) ; // number of blanks to add for ( int i = 0 ; i < padLength ; i ++ ) { pad . append ( ' ' ) ; // actually put blanks into buffer } result = pad + input ; // concatenate } } return result ; }
Another method to force an input string into a fixed width field and set it on the right with the left side filled with space characters .
188
27
144,402
public static String workDays ( ProjectCalendar input ) { StringBuilder result = new StringBuilder ( ) ; DayType [ ] test = input . getDays ( ) ; // get the array from MPXJ ProjectCalendar for ( DayType i : test ) { // go through every day in the given array if ( i == DayType . NON_WORKING ) { result . append ( "N" ) ; // only put N for non-working day of the week } else { result . append ( "Y" ) ; // Assume WORKING day unless NON_WORKING } } return result . toString ( ) ; // According to USACE specs., exceptions will be specified in HOLI records }
This method takes a calendar of MPXJ library type then returns a String of the general working days USACE format . For example the regular 5 - day work week is NYYYYYN
147
38
144,403
public static File writeStreamToTempFile ( InputStream inputStream , String tempFileSuffix ) throws IOException { FileOutputStream outputStream = null ; try { File file = File . createTempFile ( "mpxj" , tempFileSuffix ) ; outputStream = new FileOutputStream ( file ) ; byte [ ] buffer = new byte [ 1024 ] ; while ( true ) { int bytesRead = inputStream . read ( buffer ) ; if ( bytesRead == - 1 ) { break ; } outputStream . write ( buffer , 0 , bytesRead ) ; } return file ; } finally { if ( outputStream != null ) { outputStream . close ( ) ; } } }
Copy the data from an InputStream to a temp file .
146
12
144,404
public static Record getRecord ( String text ) { Record root ; try { root = new Record ( text ) ; } // // I've come across invalid calendar data in an otherwise fine Primavera // database belonging to a customer. We deal with this gracefully here // rather than propagating an exception. // catch ( Exception ex ) { root = null ; } return root ; }
Create a structured Record instance from the flat text data . Null is returned if errors are encountered during parse .
79
21
144,405
public Record getChild ( String key ) { Record result = null ; if ( key != null ) { for ( Record record : m_records ) { if ( key . equals ( record . getField ( ) ) ) { result = record ; break ; } } } return result ; }
Retrieve a child record by name .
60
8
144,406
private int getClosingParenthesisPosition ( String text , int opening ) { if ( text . charAt ( opening ) != ' ' ) { return - 1 ; } int count = 0 ; for ( int i = opening ; i < text . length ( ) ; i ++ ) { char c = text . charAt ( i ) ; switch ( c ) { case ' ' : { ++ count ; break ; } case ' ' : { -- count ; if ( count == 0 ) { return i ; } break ; } } } return - 1 ; }
Look for the closing parenthesis corresponding to the one at position represented by the opening index .
115
18
144,407
public static final long getLong ( byte [ ] data , int offset ) { if ( data . length != 8 ) { throw new UnexpectedStructureException ( ) ; } long result = 0 ; int i = offset ; for ( int shiftBy = 0 ; shiftBy < 64 ; shiftBy += 8 ) { result |= ( ( long ) ( data [ i ] & 0xff ) ) << shiftBy ; ++ i ; } return result ; }
This method reads an eight byte integer from the input array .
94
12
144,408
public static final TimeUnit getTimeUnit ( int value ) { TimeUnit result = null ; switch ( value ) { case 1 : { // Appears to mean "use the document format" result = TimeUnit . ELAPSED_DAYS ; break ; } case 2 : { result = TimeUnit . HOURS ; break ; } case 4 : { result = TimeUnit . DAYS ; break ; } case 6 : { result = TimeUnit . WEEKS ; break ; } case 8 : case 10 : { result = TimeUnit . MONTHS ; break ; } case 12 : { result = TimeUnit . YEARS ; break ; } default : { break ; } } return result ; }
Convert an integer value into a TimeUnit instance .
144
11
144,409
public static int skipToNextMatchingShort ( byte [ ] buffer , int offset , int value ) { int nextOffset = offset ; while ( getShort ( buffer , nextOffset ) != value ) { ++ nextOffset ; } nextOffset += 2 ; return nextOffset ; }
Skip to the next matching short value .
57
8
144,410
public static final String hexdump ( byte [ ] buffer , int offset , int length , boolean ascii , int columns , String prefix ) { StringBuilder sb = new StringBuilder ( ) ; if ( buffer != null ) { int index = offset ; DecimalFormat df = new DecimalFormat ( "00000" ) ; while ( index < ( offset + length ) ) { if ( index + columns > ( offset + length ) ) { columns = ( offset + length ) - index ; } sb . append ( prefix ) ; sb . append ( df . format ( index - offset ) ) ; sb . append ( ":" ) ; sb . append ( hexdump ( buffer , index , columns , ascii ) ) ; sb . append ( ' ' ) ; index += columns ; } } return ( sb . toString ( ) ) ; }
Dump raw data as hex .
182
7
144,411
public void generateWBS ( Task parent ) { String wbs ; if ( parent == null ) { if ( NumberHelper . getInt ( getUniqueID ( ) ) == 0 ) { wbs = "0" ; } else { wbs = Integer . toString ( getParentFile ( ) . getChildTasks ( ) . size ( ) + 1 ) ; } } else { wbs = parent . getWBS ( ) ; // // Apparently I added the next lines to support MPX files generated by Artemis, back in 2005 // Unfortunately I have no test data which exercises this code, and it now breaks // otherwise valid WBS values read (in this case) from XER files. So it's commented out // until someone complains about their 2005-era Artemis MPX files not working! // // int index = wbs.lastIndexOf(".0"); // if (index != -1) // { // wbs = wbs.substring(0, index); // } int childTaskCount = parent . getChildTasks ( ) . size ( ) + 1 ; if ( wbs . equals ( "0" ) ) { wbs = Integer . toString ( childTaskCount ) ; } else { wbs += ( "." + childTaskCount ) ; } } setWBS ( wbs ) ; }
This method is used to automatically generate a value for the WBS field of this task .
279
18
144,412
public void generateOutlineNumber ( Task parent ) { String outline ; if ( parent == null ) { if ( NumberHelper . getInt ( getUniqueID ( ) ) == 0 ) { outline = "0" ; } else { outline = Integer . toString ( getParentFile ( ) . getChildTasks ( ) . size ( ) + 1 ) ; } } else { outline = parent . getOutlineNumber ( ) ; int index = outline . lastIndexOf ( ".0" ) ; if ( index != - 1 ) { outline = outline . substring ( 0 , index ) ; } int childTaskCount = parent . getChildTasks ( ) . size ( ) + 1 ; if ( outline . equals ( "0" ) ) { outline = Integer . toString ( childTaskCount ) ; } else { outline += ( "." + childTaskCount ) ; } } setOutlineNumber ( outline ) ; }
This method is used to automatically generate a value for the Outline Number field of this task .
194
19
144,413
@ Override public Task addTask ( ) { ProjectFile parent = getParentFile ( ) ; Task task = new Task ( parent , this ) ; m_children . add ( task ) ; parent . getTasks ( ) . add ( task ) ; setSummary ( true ) ; return ( task ) ; }
This method allows nested tasks to be added with the WBS being completed automatically .
65
16
144,414
public void addChildTask ( Task child , int childOutlineLevel ) { int outlineLevel = NumberHelper . getInt ( getOutlineLevel ( ) ) ; if ( ( outlineLevel + 1 ) == childOutlineLevel ) { m_children . add ( child ) ; setSummary ( true ) ; } else { if ( m_children . isEmpty ( ) == false ) { ( m_children . get ( m_children . size ( ) - 1 ) ) . addChildTask ( child , childOutlineLevel ) ; } } }
This method is used to associate a child task with the current task instance . It has package access and has been designed to allow the hierarchical outline structure of tasks in an MPX file to be constructed as the file is read in .
115
46
144,415
public void addChildTask ( Task child ) { child . m_parent = this ; m_children . add ( child ) ; setSummary ( true ) ; if ( getParentFile ( ) . getProjectConfig ( ) . getAutoOutlineLevel ( ) == true ) { child . setOutlineLevel ( Integer . valueOf ( NumberHelper . getInt ( getOutlineLevel ( ) ) + 1 ) ) ; } }
This method is used to associate a child task with the current task instance . It has been designed to allow the hierarchical outline structure of tasks in an MPX file to be updated once all of the task data has been read .
90
45
144,416
public void addChildTaskBefore ( Task child , Task previousSibling ) { int index = m_children . indexOf ( previousSibling ) ; if ( index == - 1 ) { m_children . add ( child ) ; } else { m_children . add ( index , child ) ; } child . m_parent = this ; setSummary ( true ) ; if ( getParentFile ( ) . getProjectConfig ( ) . getAutoOutlineLevel ( ) == true ) { child . setOutlineLevel ( Integer . valueOf ( NumberHelper . getInt ( getOutlineLevel ( ) ) + 1 ) ) ; } }
Inserts a child task prior to a given sibling task .
134
12
144,417
public void removeChildTask ( Task child ) { if ( m_children . remove ( child ) ) { child . m_parent = null ; } setSummary ( ! m_children . isEmpty ( ) ) ; }
Removes a child task .
46
6
144,418
public ResourceAssignment addResourceAssignment ( Resource resource ) { ResourceAssignment assignment = getExistingResourceAssignment ( resource ) ; if ( assignment == null ) { assignment = new ResourceAssignment ( getParentFile ( ) , this ) ; m_assignments . add ( assignment ) ; getParentFile ( ) . getResourceAssignments ( ) . add ( assignment ) ; assignment . setTaskUniqueID ( getUniqueID ( ) ) ; assignment . setWork ( getDuration ( ) ) ; assignment . setUnits ( ResourceAssignment . DEFAULT_UNITS ) ; if ( resource != null ) { assignment . setResourceUniqueID ( resource . getUniqueID ( ) ) ; resource . addResourceAssignment ( assignment ) ; } } return ( assignment ) ; }
This method allows a resource assignment to be added to the current task .
164
14
144,419
public void addResourceAssignment ( ResourceAssignment assignment ) { if ( getExistingResourceAssignment ( assignment . getResource ( ) ) == null ) { m_assignments . add ( assignment ) ; getParentFile ( ) . getResourceAssignments ( ) . add ( assignment ) ; Resource resource = assignment . getResource ( ) ; if ( resource != null ) { resource . addResourceAssignment ( assignment ) ; } } }
Add a resource assignment which has been populated elsewhere .
93
10
144,420
private ResourceAssignment getExistingResourceAssignment ( Resource resource ) { ResourceAssignment assignment = null ; Integer resourceUniqueID = null ; if ( resource != null ) { Iterator < ResourceAssignment > iter = m_assignments . iterator ( ) ; resourceUniqueID = resource . getUniqueID ( ) ; while ( iter . hasNext ( ) == true ) { assignment = iter . next ( ) ; Integer uniqueID = assignment . getResourceUniqueID ( ) ; if ( uniqueID != null && uniqueID . equals ( resourceUniqueID ) == true ) { break ; } assignment = null ; } } return assignment ; }
Retrieves an existing resource assignment if one is present to prevent duplicate resource assignments being added .
133
19
144,421
@ SuppressWarnings ( "unchecked" ) public Relation addPredecessor ( Task targetTask , RelationType type , Duration lag ) { // // Ensure that we have a valid lag duration // if ( lag == null ) { lag = Duration . getInstance ( 0 , TimeUnit . DAYS ) ; } // // Retrieve the list of predecessors // List < Relation > predecessorList = ( List < Relation > ) getCachedValue ( TaskField . PREDECESSORS ) ; // // Ensure that there is only one predecessor relationship between // these two tasks. // Relation predecessorRelation = null ; Iterator < Relation > iter = predecessorList . iterator ( ) ; while ( iter . hasNext ( ) == true ) { predecessorRelation = iter . next ( ) ; if ( predecessorRelation . getTargetTask ( ) == targetTask ) { if ( predecessorRelation . getType ( ) != type || predecessorRelation . getLag ( ) . compareTo ( lag ) != 0 ) { predecessorRelation = null ; } break ; } predecessorRelation = null ; } // // If necessary, create a new predecessor relationship // if ( predecessorRelation == null ) { predecessorRelation = new Relation ( this , targetTask , type , lag ) ; predecessorList . add ( predecessorRelation ) ; } // // Retrieve the list of successors // List < Relation > successorList = ( List < Relation > ) targetTask . getCachedValue ( TaskField . SUCCESSORS ) ; // // Ensure that there is only one successor relationship between // these two tasks. // Relation successorRelation = null ; iter = successorList . iterator ( ) ; while ( iter . hasNext ( ) == true ) { successorRelation = iter . next ( ) ; if ( successorRelation . getTargetTask ( ) == this ) { if ( successorRelation . getType ( ) != type || successorRelation . getLag ( ) . compareTo ( lag ) != 0 ) { successorRelation = null ; } break ; } successorRelation = null ; } // // If necessary, create a new successor relationship // if ( successorRelation == null ) { successorRelation = new Relation ( targetTask , this , type , lag ) ; successorList . add ( successorRelation ) ; } return ( predecessorRelation ) ; }
This method allows a predecessor relationship to be added to this task instance .
501
14
144,422
@ Override public void setID ( Integer val ) { ProjectFile parent = getParentFile ( ) ; Integer previous = getID ( ) ; if ( previous != null ) { parent . getTasks ( ) . unmapID ( previous ) ; } parent . getTasks ( ) . mapID ( val , this ) ; set ( TaskField . ID , val ) ; }
The ID field contains the identifier number that Microsoft Project automatically assigns to each task as you add it to the project . The ID indicates the position of a task with respect to the other tasks .
80
38
144,423
public Duration getBaselineDuration ( ) { Object result = getCachedValue ( TaskField . BASELINE_DURATION ) ; if ( result == null ) { result = getCachedValue ( TaskField . BASELINE_ESTIMATED_DURATION ) ; } if ( ! ( result instanceof Duration ) ) { result = null ; } return ( Duration ) result ; }
The Baseline Duration field shows the original span of time planned to complete a task .
83
17
144,424
public String getBaselineDurationText ( ) { Object result = getCachedValue ( TaskField . BASELINE_DURATION ) ; if ( result == null ) { result = getCachedValue ( TaskField . BASELINE_ESTIMATED_DURATION ) ; } if ( ! ( result instanceof String ) ) { result = null ; } return ( String ) result ; }
Retrieves the text value for the baseline duration .
84
11
144,425
public Date getBaselineFinish ( ) { Object result = getCachedValue ( TaskField . BASELINE_FINISH ) ; if ( result == null ) { result = getCachedValue ( TaskField . BASELINE_ESTIMATED_FINISH ) ; } if ( ! ( result instanceof Date ) ) { result = null ; } return ( Date ) result ; }
The Baseline Finish field shows the planned completion date for a task at the time you saved a baseline . Information in this field becomes available when you set a baseline for a task .
81
36
144,426
public Date getBaselineStart ( ) { Object result = getCachedValue ( TaskField . BASELINE_START ) ; if ( result == null ) { result = getCachedValue ( TaskField . BASELINE_ESTIMATED_START ) ; } if ( ! ( result instanceof Date ) ) { result = null ; } return ( Date ) result ; }
The Baseline Start field shows the planned beginning date for a task at the time you saved a baseline . Information in this field becomes available when you set a baseline .
81
33
144,427
public Number getCostVariance ( ) { Number variance = ( Number ) getCachedValue ( TaskField . COST_VARIANCE ) ; if ( variance == null ) { Number cost = getCost ( ) ; Number baselineCost = getBaselineCost ( ) ; if ( cost != null && baselineCost != null ) { variance = NumberHelper . getDouble ( cost . doubleValue ( ) - baselineCost . doubleValue ( ) ) ; set ( TaskField . COST_VARIANCE , variance ) ; } } return ( variance ) ; }
The Cost Variance field shows the difference between the baseline cost and total cost for a task . The total cost is the current estimate of costs based on actual costs and remaining costs .
118
36
144,428
public boolean getCritical ( ) { Boolean critical = ( Boolean ) getCachedValue ( TaskField . CRITICAL ) ; if ( critical == null ) { Duration totalSlack = getTotalSlack ( ) ; ProjectProperties props = getParentFile ( ) . getProjectProperties ( ) ; int criticalSlackLimit = NumberHelper . getInt ( props . getCriticalSlackLimit ( ) ) ; if ( criticalSlackLimit != 0 && totalSlack . getDuration ( ) != 0 && totalSlack . getUnits ( ) != TimeUnit . DAYS ) { totalSlack = totalSlack . convertUnits ( TimeUnit . DAYS , props ) ; } critical = Boolean . valueOf ( totalSlack . getDuration ( ) <= criticalSlackLimit && NumberHelper . getInt ( getPercentageComplete ( ) ) != 100 && ( ( getTaskMode ( ) == TaskMode . AUTO_SCHEDULED ) || ( getDurationText ( ) == null && getStartText ( ) == null && getFinishText ( ) == null ) ) ) ; set ( TaskField . CRITICAL , critical ) ; } return ( BooleanHelper . getBoolean ( critical ) ) ; }
The Critical field indicates whether a task has any room in the schedule to slip or if a task is on the critical path . The Critical field contains Yes if the task is critical and No if the task is not critical .
258
44
144,429
public void setOutlineCode ( int index , String value ) { set ( selectField ( TaskFieldLists . CUSTOM_OUTLINE_CODE , index ) , value ) ; }
Set an outline code value .
41
6
144,430
public Duration getTotalSlack ( ) { Duration totalSlack = ( Duration ) getCachedValue ( TaskField . TOTAL_SLACK ) ; if ( totalSlack == null ) { Duration duration = getDuration ( ) ; if ( duration == null ) { duration = Duration . getInstance ( 0 , TimeUnit . DAYS ) ; } TimeUnit units = duration . getUnits ( ) ; Duration startSlack = getStartSlack ( ) ; if ( startSlack == null ) { startSlack = Duration . getInstance ( 0 , units ) ; } else { if ( startSlack . getUnits ( ) != units ) { startSlack = startSlack . convertUnits ( units , getParentFile ( ) . getProjectProperties ( ) ) ; } } Duration finishSlack = getFinishSlack ( ) ; if ( finishSlack == null ) { finishSlack = Duration . getInstance ( 0 , units ) ; } else { if ( finishSlack . getUnits ( ) != units ) { finishSlack = finishSlack . convertUnits ( units , getParentFile ( ) . getProjectProperties ( ) ) ; } } double startSlackDuration = startSlack . getDuration ( ) ; double finishSlackDuration = finishSlack . getDuration ( ) ; if ( startSlackDuration == 0 || finishSlackDuration == 0 ) { if ( startSlackDuration != 0 ) { totalSlack = startSlack ; } else { totalSlack = finishSlack ; } } else { if ( startSlackDuration < finishSlackDuration ) { totalSlack = startSlack ; } else { totalSlack = finishSlack ; } } set ( TaskField . TOTAL_SLACK , totalSlack ) ; } return ( totalSlack ) ; }
The Total Slack field contains the amount of time a task can be delayed without delaying the project s finish date .
388
22
144,431
public void setCalendar ( ProjectCalendar calendar ) { set ( TaskField . CALENDAR , calendar ) ; setCalendarUniqueID ( calendar == null ? null : calendar . getUniqueID ( ) ) ; }
Sets the name of the base calendar associated with this task . Note that this attribute appears in MPP9 and MSPDI files .
46
28
144,432
public Duration getStartSlack ( ) { Duration startSlack = ( Duration ) getCachedValue ( TaskField . START_SLACK ) ; if ( startSlack == null ) { Duration duration = getDuration ( ) ; if ( duration != null ) { startSlack = DateHelper . getVariance ( this , getEarlyStart ( ) , getLateStart ( ) , duration . getUnits ( ) ) ; set ( TaskField . START_SLACK , startSlack ) ; } } return ( startSlack ) ; }
Retrieve the start slack .
114
6
144,433
public Duration getFinishSlack ( ) { Duration finishSlack = ( Duration ) getCachedValue ( TaskField . FINISH_SLACK ) ; if ( finishSlack == null ) { Duration duration = getDuration ( ) ; if ( duration != null ) { finishSlack = DateHelper . getVariance ( this , getEarlyFinish ( ) , getLateFinish ( ) , duration . getUnits ( ) ) ; set ( TaskField . FINISH_SLACK , finishSlack ) ; } } return ( finishSlack ) ; }
Retrieve the finish slack .
116
6
144,434
public Object getFieldByAlias ( String alias ) { return getCachedValue ( getParentFile ( ) . getCustomFields ( ) . getFieldByAlias ( FieldTypeClass . TASK , alias ) ) ; }
Retrieve the value of a field using its alias .
48
11
144,435
public void setFieldByAlias ( String alias , Object value ) { set ( getParentFile ( ) . getCustomFields ( ) . getFieldByAlias ( FieldTypeClass . TASK , alias ) , value ) ; }
Set the value of a field using its alias .
49
10
144,436
public boolean getEnterpriseFlag ( int index ) { return ( BooleanHelper . getBoolean ( ( Boolean ) getCachedValue ( selectField ( TaskFieldLists . ENTERPRISE_FLAG , index ) ) ) ) ; }
Retrieve an enterprise field value .
49
7
144,437
public String getBaselineDurationText ( int baselineNumber ) { Object result = getCachedValue ( selectField ( TaskFieldLists . BASELINE_DURATIONS , baselineNumber ) ) ; if ( result == null ) { result = getCachedValue ( selectField ( TaskFieldLists . BASELINE_ESTIMATED_DURATIONS , baselineNumber ) ) ; } if ( ! ( result instanceof String ) ) { result = null ; } return ( String ) result ; }
Retrieves the baseline duration text value .
105
9
144,438
public void setBaselineDurationText ( int baselineNumber , String value ) { set ( selectField ( TaskFieldLists . BASELINE_DURATIONS , baselineNumber ) , value ) ; }
Sets the baseline duration text value .
42
8
144,439
public void setBaselineFinishText ( int baselineNumber , String value ) { set ( selectField ( TaskFieldLists . BASELINE_FINISHES , baselineNumber ) , value ) ; }
Sets the baseline finish text value .
42
8
144,440
public void setBaselineStartText ( int baselineNumber , String value ) { set ( selectField ( TaskFieldLists . BASELINE_STARTS , baselineNumber ) , value ) ; }
Sets the baseline start text value .
41
8
144,441
public Date getCompleteThrough ( ) { Date value = ( Date ) getCachedValue ( TaskField . COMPLETE_THROUGH ) ; if ( value == null ) { int percentComplete = NumberHelper . getInt ( getPercentageComplete ( ) ) ; switch ( percentComplete ) { case 0 : { break ; } case 100 : { value = getActualFinish ( ) ; break ; } default : { Date actualStart = getActualStart ( ) ; Duration duration = getDuration ( ) ; if ( actualStart != null && duration != null ) { double durationValue = ( duration . getDuration ( ) * percentComplete ) / 100d ; duration = Duration . getInstance ( durationValue , duration . getUnits ( ) ) ; ProjectCalendar calendar = getEffectiveCalendar ( ) ; value = calendar . getDate ( actualStart , duration , true ) ; } break ; } } set ( TaskField . COMPLETE_THROUGH , value ) ; } return value ; }
Retrieve the complete through date .
208
7
144,442
public TaskMode getTaskMode ( ) { return BooleanHelper . getBoolean ( ( Boolean ) getCachedValue ( TaskField . TASK_MODE ) ) ? TaskMode . MANUALLY_SCHEDULED : TaskMode . AUTO_SCHEDULED ; }
Retrieves the task mode .
62
7
144,443
public ProjectCalendar getEffectiveCalendar ( ) { ProjectCalendar result = getCalendar ( ) ; if ( result == null ) { result = getParentFile ( ) . getDefaultCalendar ( ) ; } return result ; }
Retrieve the effective calendar for this task . If the task does not have a specific calendar associated with it fall back to using the default calendar for the project .
49
32
144,444
public boolean removePredecessor ( Task targetTask , RelationType type , Duration lag ) { boolean matchFound = false ; // // Retrieve the list of predecessors // List < Relation > predecessorList = getPredecessors ( ) ; if ( ! predecessorList . isEmpty ( ) ) { // // Ensure that we have a valid lag duration // if ( lag == null ) { lag = Duration . getInstance ( 0 , TimeUnit . DAYS ) ; } // // Ensure that there is a predecessor relationship between // these two tasks, and remove it. // matchFound = removeRelation ( predecessorList , targetTask , type , lag ) ; // // If we have removed a predecessor, then we must remove the // corresponding successor entry from the target task list // if ( matchFound ) { // // Retrieve the list of successors // List < Relation > successorList = targetTask . getSuccessors ( ) ; if ( ! successorList . isEmpty ( ) ) { // // Ensure that there is a successor relationship between // these two tasks, and remove it. // removeRelation ( successorList , this , type , lag ) ; } } } return matchFound ; }
This method allows a predecessor relationship to be removed from this task instance . It will only delete relationships that exactly match the given targetTask type and lag time .
245
31
144,445
private boolean removeRelation ( List < Relation > relationList , Task targetTask , RelationType type , Duration lag ) { boolean matchFound = false ; for ( Relation relation : relationList ) { if ( relation . getTargetTask ( ) == targetTask ) { if ( relation . getType ( ) == type && relation . getLag ( ) . compareTo ( lag ) == 0 ) { matchFound = relationList . remove ( relation ) ; break ; } } } return matchFound ; }
Internal method used to locate an remove an item from a list Relations .
106
14
144,446
private boolean isRelated ( Task task , List < Relation > list ) { boolean result = false ; for ( Relation relation : list ) { if ( relation . getTargetTask ( ) . getUniqueID ( ) . intValue ( ) == task . getUniqueID ( ) . intValue ( ) ) { result = true ; break ; } } return result ; }
Internal method used to test for the existence of a relationship with a task .
77
15
144,447
public void writeTo ( Writer destination ) { Element eltRuleset = new Element ( "ruleset" ) ; addAttribute ( eltRuleset , "name" , name ) ; addChild ( eltRuleset , "description" , description ) ; for ( PmdRule pmdRule : rules ) { Element eltRule = new Element ( "rule" ) ; addAttribute ( eltRule , "ref" , pmdRule . getRef ( ) ) ; addAttribute ( eltRule , "class" , pmdRule . getClazz ( ) ) ; addAttribute ( eltRule , "message" , pmdRule . getMessage ( ) ) ; addAttribute ( eltRule , "name" , pmdRule . getName ( ) ) ; addAttribute ( eltRule , "language" , pmdRule . getLanguage ( ) ) ; addChild ( eltRule , "priority" , String . valueOf ( pmdRule . getPriority ( ) ) ) ; if ( pmdRule . hasProperties ( ) ) { Element ruleProperties = processRuleProperties ( pmdRule ) ; if ( ruleProperties . getContentSize ( ) > 0 ) { eltRule . addContent ( ruleProperties ) ; } } eltRuleset . addContent ( eltRule ) ; } XMLOutputter serializer = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; try { serializer . output ( new Document ( eltRuleset ) , destination ) ; } catch ( IOException e ) { throw new IllegalStateException ( "An exception occurred while serializing PmdRuleSet." , e ) ; } }
Serializes this RuleSet in an XML document .
355
10
144,448
@ Override public PmdRuleSet create ( ) { final SAXBuilder parser = new SAXBuilder ( ) ; final Document dom ; try { dom = parser . build ( source ) ; } catch ( JDOMException | IOException e ) { if ( messages != null ) { messages . addErrorText ( INVALID_INPUT + " : " + e . getMessage ( ) ) ; } LOG . error ( INVALID_INPUT , e ) ; return new PmdRuleSet ( ) ; } final Element eltResultset = dom . getRootElement ( ) ; final Namespace namespace = eltResultset . getNamespace ( ) ; final PmdRuleSet result = new PmdRuleSet ( ) ; final String name = eltResultset . getAttributeValue ( "name" ) ; final Element descriptionElement = getChild ( eltResultset , namespace ) ; result . setName ( name ) ; if ( descriptionElement != null ) { result . setDescription ( descriptionElement . getValue ( ) ) ; } for ( Element eltRule : getChildren ( eltResultset , "rule" , namespace ) ) { PmdRule pmdRule = new PmdRule ( eltRule . getAttributeValue ( "ref" ) ) ; pmdRule . setClazz ( eltRule . getAttributeValue ( "class" ) ) ; pmdRule . setName ( eltRule . getAttributeValue ( "name" ) ) ; pmdRule . setMessage ( eltRule . getAttributeValue ( "message" ) ) ; parsePmdPriority ( eltRule , pmdRule , namespace ) ; parsePmdProperties ( eltRule , pmdRule , namespace ) ; result . addRule ( pmdRule ) ; } return result ; }
Parses the given Reader for PmdRuleSets .
382
13
144,449
private static int calculateBeginLine ( RuleViolation pmdViolation ) { int minLine = Math . min ( pmdViolation . getBeginLine ( ) , pmdViolation . getEndLine ( ) ) ; return minLine > 0 ? minLine : calculateEndLine ( pmdViolation ) ; }
Calculates the beginLine of a violation report .
67
11
144,450
@ Nullable public View findViewById ( int id ) { if ( searchView != null ) { return searchView . findViewById ( id ) ; } else if ( supportView != null ) { return supportView . findViewById ( id ) ; } throw new IllegalStateException ( ERROR_NO_SEARCHVIEW ) ; }
Look for a child view with the given id . If this view has the given id return this view .
70
21
144,451
@ NonNull public Context getContext ( ) { if ( searchView != null ) { return searchView . getContext ( ) ; } else if ( supportView != null ) { return supportView . getContext ( ) ; } throw new IllegalStateException ( ERROR_NO_SEARCHVIEW ) ; }
Returns the context the view is running in through which it can access the current theme resources etc .
63
19
144,452
@ NonNull public CharSequence getQuery ( ) { if ( searchView != null ) { return searchView . getQuery ( ) ; } else if ( supportView != null ) { return supportView . getQuery ( ) ; } throw new IllegalStateException ( ERROR_NO_SEARCHVIEW ) ; }
Returns the query string currently in the text field .
65
10
144,453
public void setOnQueryTextListener ( @ NonNull final SearchView . OnQueryTextListener listener ) { if ( searchView != null ) { searchView . setOnQueryTextListener ( listener ) ; } else if ( supportView != null ) { supportView . setOnQueryTextListener ( new android . support . v7 . widget . SearchView . OnQueryTextListener ( ) { @ Override public boolean onQueryTextSubmit ( String query ) { return listener . onQueryTextSubmit ( query ) ; } @ Override public boolean onQueryTextChange ( String newText ) { return listener . onQueryTextChange ( newText ) ; } } ) ; } else { throw new IllegalStateException ( ERROR_NO_SEARCHVIEW ) ; } }
Sets a listener for user actions within the SearchView .
158
12
144,454
public void setOnCloseListener ( @ NonNull final android . support . v7 . widget . SearchView . OnCloseListener listener ) { if ( searchView != null ) { searchView . setOnCloseListener ( new SearchView . OnCloseListener ( ) { @ Override public boolean onClose ( ) { return listener . onClose ( ) ; } } ) ; } else if ( supportView != null ) { supportView . setOnCloseListener ( listener ) ; } else { throw new IllegalStateException ( ERROR_NO_SEARCHVIEW ) ; } }
Sets a listener to inform when the user closes the SearchView .
118
14
144,455
public static Searcher get ( String variant ) { final Searcher searcher = instances . get ( variant ) ; if ( searcher == null ) { throw new IllegalStateException ( Errors . SEARCHER_GET_BEFORE_CREATE ) ; } return searcher ; }
Gets the Searcher for a given variant .
58
10
144,456
@ NonNull @ SuppressWarnings ( { "WeakerAccess" , "unused" } ) // For library users public Searcher reset ( ) { lastResponsePage = 0 ; lastRequestPage = 0 ; lastResponseId = 0 ; endReached = false ; clearFacetRefinements ( ) ; cancelPendingRequests ( ) ; numericRefinements . clear ( ) ; return this ; }
Resets the helper s state .
88
7
144,457
@ SuppressWarnings ( { "WeakerAccess" , "unused" } ) // For library users public Searcher cancelPendingRequests ( ) { if ( pendingRequests . size ( ) != 0 ) { for ( int i = 0 ; i < pendingRequests . size ( ) ; i ++ ) { int reqId = pendingRequests . keyAt ( i ) ; Request r = pendingRequests . valueAt ( i ) ; if ( ! r . isFinished ( ) && ! r . isCancelled ( ) ) { cancelRequest ( r , reqId ) ; } } } return this ; }
Cancels all requests still waiting for a response .
134
11
144,458
@ SuppressWarnings ( { "WeakerAccess" , "unused" } ) // For library users public Searcher addBooleanFilter ( String attribute , Boolean value ) { booleanFilterMap . put ( attribute , value ) ; rebuildQueryFacetFilters ( ) ; return this ; }
Adds a boolean refinement for the next queries .
63
9
144,459
@ SuppressWarnings ( { "WeakerAccess" , "unused" } ) // For library users public Searcher addFacet ( String ... attributes ) { for ( String attribute : attributes ) { final Integer value = facetRequestCount . get ( attribute ) ; facetRequestCount . put ( attribute , value == null ? 1 : value + 1 ) ; if ( value == null || value == 0 ) { facets . add ( attribute ) ; } } rebuildQueryFacets ( ) ; return this ; }
Adds one or several attributes to facet on for the next queries .
107
13
144,460
@ SuppressWarnings ( { "WeakerAccess" , "unused" } ) // For library users public Searcher deleteFacet ( String ... attributes ) { for ( String attribute : attributes ) { facetRequestCount . put ( attribute , 0 ) ; facets . remove ( attribute ) ; } rebuildQueryFacets ( ) ; return this ; }
Forces removal of one or several faceted attributes for the next queries .
74
15
144,461
public static void checkOperatorIsValid ( int operatorCode ) { switch ( operatorCode ) { case OPERATOR_LT : case OPERATOR_LE : case OPERATOR_EQ : case OPERATOR_NE : case OPERATOR_GE : case OPERATOR_GT : case OPERATOR_UNKNOWN : return ; default : throw new IllegalStateException ( String . format ( Locale . US , ERROR_INVALID_CODE , operatorCode ) ) ; } }
Checks if the given operator code is a valid one .
99
12
144,462
public static String getStringFromJSONPath ( JSONObject record , String path ) { final Object object = getObjectFromJSONPath ( record , path ) ; return object == null ? null : object . toString ( ) ; }
Gets a string attribute from a json object given a path to traverse .
47
15
144,463
public static HashMap < String , String > getMapFromJSONPath ( JSONObject record , String path ) { return getObjectFromJSONPath ( record , path ) ; }
Gets a Map of attributes from a json object given a path to traverse .
36
16
144,464
@ SuppressWarnings ( { "WeakerAccess" , "unused" } ) // For library users public void enableKeyboardAutoHiding ( ) { keyboardListener = new OnScrollListener ( ) { @ Override public void onScrolled ( RecyclerView recyclerView , int dx , int dy ) { if ( dx != 0 || dy != 0 ) { imeManager . hideSoftInputFromWindow ( Hits . this . getWindowToken ( ) , InputMethodManager . HIDE_NOT_ALWAYS ) ; } super . onScrolled ( recyclerView , dx , dy ) ; } } ; addOnScrollListener ( keyboardListener ) ; }
Starts closing the keyboard when the hits are scrolled .
142
12
144,465
public void search ( String query ) { final Query newQuery = searcher . getQuery ( ) . setQuery ( query ) ; searcher . setQuery ( newQuery ) . search ( ) ; }
Triggers a new search with the given text .
42
11
144,466
@ SuppressWarnings ( { "WeakerAccess" , "unused" } ) // For library users public void registerFilters ( List < AlgoliaFilter > filters ) { for ( final AlgoliaFilter filter : filters ) { searcher . addFacet ( filter . getAttribute ( ) ) ; } }
Registers your facet filters adding them to this InstantSearch s widgets .
69
14
144,467
@ SuppressWarnings ( { "WeakerAccess" , "unused" } ) // For library users public void registerWidget ( View widget ) { prepareWidget ( widget ) ; if ( widget instanceof AlgoliaResultsListener ) { AlgoliaResultsListener listener = ( AlgoliaResultsListener ) widget ; if ( ! this . resultListeners . contains ( listener ) ) { this . resultListeners . add ( listener ) ; } searcher . registerResultListener ( listener ) ; } if ( widget instanceof AlgoliaErrorListener ) { AlgoliaErrorListener listener = ( AlgoliaErrorListener ) widget ; if ( ! this . errorListeners . contains ( listener ) ) { this . errorListeners . add ( listener ) ; } searcher . registerErrorListener ( listener ) ; } if ( widget instanceof AlgoliaSearcherListener ) { AlgoliaSearcherListener listener = ( AlgoliaSearcherListener ) widget ; listener . initWithSearcher ( searcher ) ; } }
Links the given widget to InstantSearch according to the interfaces it implements .
215
14
144,468
private List < String > processAllListeners ( View rootView ) { List < String > refinementAttributes = new ArrayList <> ( ) ; // Register any AlgoliaResultsListener (unless it has a different variant than searcher) final List < AlgoliaResultsListener > resultListeners = LayoutViews . findByClass ( ( ViewGroup ) rootView , AlgoliaResultsListener . class ) ; if ( resultListeners . isEmpty ( ) ) { throw new IllegalStateException ( Errors . LAYOUT_MISSING_RESULT_LISTENER ) ; } for ( AlgoliaResultsListener listener : resultListeners ) { if ( ! this . resultListeners . contains ( listener ) ) { final String variant = BindingHelper . getVariantForView ( ( View ) listener ) ; if ( variant == null || searcher . variant . equals ( variant ) ) { this . resultListeners . add ( listener ) ; searcher . registerResultListener ( listener ) ; prepareWidget ( listener , refinementAttributes ) ; } } } // Register any AlgoliaErrorListener (unless it has a different variant than searcher) final List < AlgoliaErrorListener > errorListeners = LayoutViews . findByClass ( ( ViewGroup ) rootView , AlgoliaErrorListener . class ) ; for ( AlgoliaErrorListener listener : errorListeners ) { if ( ! this . errorListeners . contains ( listener ) ) { final String variant = BindingHelper . getVariantForView ( ( View ) listener ) ; if ( variant == null || searcher . variant . equals ( variant ) ) { this . errorListeners . add ( listener ) ; } } searcher . registerErrorListener ( listener ) ; prepareWidget ( listener , refinementAttributes ) ; } // Register any AlgoliaSearcherListener (unless it has a different variant than searcher) final List < AlgoliaSearcherListener > searcherListeners = LayoutViews . findByClass ( ( ViewGroup ) rootView , AlgoliaSearcherListener . class ) ; for ( AlgoliaSearcherListener listener : searcherListeners ) { final String variant = BindingHelper . getVariantForView ( ( View ) listener ) ; if ( variant == null || searcher . variant . equals ( variant ) ) { listener . initWithSearcher ( searcher ) ; prepareWidget ( listener , refinementAttributes ) ; } } return refinementAttributes ; }
Finds and sets up the Listeners in the given rootView .
514
14
144,469
@ Override public SuggestAccountsRequest suggestAccounts ( ) throws RestApiException { return new SuggestAccountsRequest ( ) { @ Override public List < AccountInfo > get ( ) throws RestApiException { return AccountsRestClient . this . suggestAccounts ( this ) ; } } ; }
Added in Gerrit 2 . 11 .
64
8
144,470
public static String encode ( String component ) { if ( component != null ) { try { return URLEncoder . encode ( component , UTF_8 . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( "JVM must support UTF-8" , e ) ; } } return null ; }
Encode a path segment escaping characters not valid for a URL .
72
13
144,471
private Optional < String > getXsrfFromHtmlBody ( HttpResponse loginResponse ) throws IOException { Optional < Cookie > gerritAccountCookie = findGerritAccountCookie ( ) ; if ( gerritAccountCookie . isPresent ( ) ) { Matcher matcher = GERRIT_AUTH_PATTERN . matcher ( EntityUtils . toString ( loginResponse . getEntity ( ) , Consts . UTF_8 ) ) ; if ( matcher . find ( ) ) { return Optional . of ( matcher . group ( 1 ) ) ; } } return Optional . absent ( ) ; }
In Gerrit < 2 . 12 the XSRF token was included in the start page HTML .
134
20
144,472
private BasicCredentialsProvider getCredentialsProvider ( ) { return new BasicCredentialsProvider ( ) { private Set < AuthScope > authAlreadyTried = Sets . newHashSet ( ) ; @ Override public Credentials getCredentials ( AuthScope authscope ) { if ( authAlreadyTried . contains ( authscope ) ) { return null ; } authAlreadyTried . add ( authscope ) ; return super . getCredentials ( authscope ) ; } } ; }
With this impl it only returns the same credentials once . Otherwise it s possible that a loop will occur . When server returns status code 401 the HTTP client provides the same credentials forever . Since we create a new HTTP client for every request we can handle it this way .
106
53
144,473
public String asString ( ) throws IOException { long len = getContentLength ( ) ; ByteArrayOutputStream buf ; if ( 0 < len ) { buf = new ByteArrayOutputStream ( ( int ) len ) ; } else { buf = new ByteArrayOutputStream ( ) ; } writeTo ( buf ) ; return decode ( buf . toByteArray ( ) , getCharacterEncoding ( ) ) ; }
Return a copy of the result as a String .
86
10
144,474
private boolean isForGerritHost ( HttpRequest request ) { if ( ! ( request instanceof HttpRequestWrapper ) ) return false ; HttpRequest originalRequest = ( ( HttpRequestWrapper ) request ) . getOriginal ( ) ; if ( ! ( originalRequest instanceof HttpRequestBase ) ) return false ; URI uri = ( ( HttpRequestBase ) originalRequest ) . getURI ( ) ; URI authDataUri = URI . create ( authData . getHost ( ) ) ; if ( uri == null || uri . getHost ( ) == null ) return false ; boolean hostEquals = uri . getHost ( ) . equals ( authDataUri . getHost ( ) ) ; boolean portEquals = uri . getPort ( ) == authDataUri . getPort ( ) ; return hostEquals && portEquals ; }
Checks if request is intended for Gerrit host .
188
11
144,475
public static String getRelativePathName ( Path root , Path path ) { Path relative = root . relativize ( path ) ; return Files . isDirectory ( path ) && ! relative . toString ( ) . endsWith ( "/" ) ? String . format ( "%s/" , relative . toString ( ) ) : relative . toString ( ) ; }
Get the relative path of an application
76
7
144,476
@ PreDestroy public final void dispose ( ) { getConnectionPool ( ) . ifPresent ( PoolResources :: dispose ) ; getThreadPool ( ) . dispose ( ) ; try { ObjectName name = getByteBufAllocatorObjectName ( ) ; if ( ManagementFactory . getPlatformMBeanServer ( ) . isRegistered ( name ) ) { ManagementFactory . getPlatformMBeanServer ( ) . unregisterMBean ( name ) ; } } catch ( JMException e ) { this . logger . error ( "Unable to register ByteBufAllocator MBean" , e ) ; } }
Disposes resources created to service this connection context
131
9
144,477
public static < T , R extends Resource < T > > T getEntity ( R resource ) { return resource . getEntity ( ) ; }
Return the entity of a resource
29
6
144,478
public static < R extends Resource < ? > , U extends PaginatedResponse < R > > Flux < R > getResources ( U response ) { return Flux . fromIterable ( response . getResources ( ) ) ; }
Return a stream of resources from a response
48
8
144,479
public static Mono < Void > waitForCompletion ( CloudFoundryClient cloudFoundryClient , Duration completionTimeout , String jobId ) { return requestJobV3 ( cloudFoundryClient , jobId ) . filter ( job -> JobState . PROCESSING != job . getState ( ) ) . repeatWhenEmpty ( exponentialBackOff ( Duration . ofSeconds ( 1 ) , Duration . ofSeconds ( 15 ) , completionTimeout ) ) . filter ( job -> JobState . FAILED == job . getState ( ) ) . flatMap ( JobUtils :: getError ) ; }
Waits for a job V3 to complete
125
9
144,480
public static String asTime ( long time ) { if ( time > HOUR ) { return String . format ( "%.1f h" , ( time / HOUR ) ) ; } else if ( time > MINUTE ) { return String . format ( "%.1f m" , ( time / MINUTE ) ) ; } else if ( time > SECOND ) { return String . format ( "%.1f s" , ( time / SECOND ) ) ; } else { return String . format ( "%d ms" , time ) ; } }
Renders a time period in human readable form
116
9
144,481
private ClassMatcher buildMatcher ( String tagText ) { // check there are at least @match <type> and a parameter String [ ] strings = StringUtil . tokenize ( tagText ) ; if ( strings . length < 2 ) { System . err . println ( "Skipping uncomplete @match tag, type missing: " + tagText + " in view " + viewDoc ) ; return null ; } try { if ( strings [ 0 ] . equals ( "class" ) ) { return new PatternMatcher ( Pattern . compile ( strings [ 1 ] ) ) ; } else if ( strings [ 0 ] . equals ( "context" ) ) { return new ContextMatcher ( root , Pattern . compile ( strings [ 1 ] ) , getGlobalOptions ( ) , false ) ; } else if ( strings [ 0 ] . equals ( "outgoingContext" ) ) { return new ContextMatcher ( root , Pattern . compile ( strings [ 1 ] ) , getGlobalOptions ( ) , false ) ; } else if ( strings [ 0 ] . equals ( "interface" ) ) { return new InterfaceMatcher ( root , Pattern . compile ( strings [ 1 ] ) ) ; } else if ( strings [ 0 ] . equals ( "subclass" ) ) { return new SubclassMatcher ( root , Pattern . compile ( strings [ 1 ] ) ) ; } else { System . err . println ( "Skipping @match tag, unknown match type, in view " + viewDoc ) ; } } catch ( PatternSyntaxException pse ) { System . err . println ( "Skipping @match tag due to invalid regular expression '" + tagText + "'" + " in view " + viewDoc ) ; } catch ( Exception e ) { System . err . println ( "Skipping @match tag due to an internal error '" + tagText + "'" + " in view " + viewDoc ) ; e . printStackTrace ( ) ; } return null ; }
Factory method that builds the appropriate matcher for
420
9
144,482
private void addToGraph ( ClassDoc cd ) { // avoid adding twice the same class, but don't rely on cg.getClassInfo // since there are other ways to add a classInfor than printing the class if ( visited . contains ( cd . toString ( ) ) ) return ; visited . add ( cd . toString ( ) ) ; cg . printClass ( cd , false ) ; cg . printRelations ( cd ) ; if ( opt . inferRelationships ) cg . printInferredRelations ( cd ) ; if ( opt . inferDependencies ) cg . printInferredDependencies ( cd ) ; }
Adds the specified class to the internal class graph along with its relations and dependencies eventually inferring them according to the Options specified for this matcher
136
28
144,483
public static int optionLength ( String option ) { int result = Standard . optionLength ( option ) ; if ( result != 0 ) return result ; else return UmlGraph . optionLength ( option ) ; }
Option check forwards options to the standard doclet if that one refuses them they are sent to UmlGraph
43
21
144,484
public static boolean start ( RootDoc root ) { root . printNotice ( "UmlGraphDoc version " + Version . VERSION + ", running the standard doclet" ) ; Standard . start ( root ) ; root . printNotice ( "UmlGraphDoc version " + Version . VERSION + ", altering javadocs" ) ; try { String outputFolder = findOutputPath ( root . options ( ) ) ; Options opt = UmlGraph . buildOptions ( root ) ; opt . setOptions ( root . options ( ) ) ; // in javadoc enumerations are always printed opt . showEnumerations = true ; opt . relativeLinksForSourcePackages = true ; // enable strict matching for hide expressions opt . strictMatching = true ; // root.printNotice(opt.toString()); generatePackageDiagrams ( root , opt , outputFolder ) ; generateContextDiagrams ( root , opt , outputFolder ) ; } catch ( Throwable t ) { root . printWarning ( "Error: " + t . toString ( ) ) ; t . printStackTrace ( ) ; return false ; } return true ; }
Standard doclet entry point
242
5
144,485
private static void generateContextDiagrams ( RootDoc root , Options opt , String outputFolder ) throws IOException { Set < ClassDoc > classDocs = new TreeSet < ClassDoc > ( new Comparator < ClassDoc > ( ) { public int compare ( ClassDoc cd1 , ClassDoc cd2 ) { return cd1 . name ( ) . compareTo ( cd2 . name ( ) ) ; } } ) ; for ( ClassDoc classDoc : root . classes ( ) ) classDocs . ( classDoc ) ; ContextView view = null ; for ( ClassDoc classDoc : classDocs ) { try { if ( view == null ) view = new ContextView ( outputFolder , classDoc , root , opt ) ; else view . setContextCenter ( classDoc ) ; UmlGraph . buildGraph ( root , view , classDoc ) ; runGraphviz ( opt . dotExecutable , outputFolder , classDoc . containingPackage ( ) . name ( ) , classDoc . name ( ) , root ) ; alterHtmlDocs ( opt , outputFolder , classDoc . containingPackage ( ) . name ( ) , classDoc . name ( ) , classDoc . name ( ) + ".html" , Pattern . compile ( ".*(Class|Interface|Enum) " + classDoc . name ( ) + ".*" ) , root ) ; } catch ( Exception e ) { throw new RuntimeException ( "Error generating " + classDoc . name ( ) , e ) ; } } }
Generates the context diagram for a single class
318
9
144,486
private static void alterHtmlDocs ( Options opt , String outputFolder , String packageName , String className , String htmlFileName , Pattern insertPointPattern , RootDoc root ) throws IOException { // setup files File output = new File ( outputFolder , packageName . replace ( "." , "/" ) ) ; File htmlFile = new File ( output , htmlFileName ) ; File alteredFile = new File ( htmlFile . getAbsolutePath ( ) + ".uml" ) ; if ( ! htmlFile . exists ( ) ) { System . err . println ( "Expected file not found: " + htmlFile . getAbsolutePath ( ) ) ; return ; } // parse & rewrite BufferedWriter writer = null ; BufferedReader reader = null ; boolean matched = false ; try { writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( alteredFile ) , opt . outputEncoding ) ) ; reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( htmlFile ) , opt . outputEncoding ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { writer . write ( line ) ; writer . newLine ( ) ; if ( ! matched && insertPointPattern . matcher ( line ) . matches ( ) ) { matched = true ; String tag ; if ( opt . autoSize ) tag = String . format ( UML_AUTO_SIZED_DIV_TAG , className ) ; else tag = String . format ( UML_DIV_TAG , className ) ; if ( opt . collapsibleDiagrams ) tag = String . format ( EXPANDABLE_UML , tag , "Show UML class diagram" , "Hide UML class diagram" ) ; writer . write ( "<!-- UML diagram added by UMLGraph version " + Version . VERSION + " (http://www.spinellis.gr/umlgraph/) -->" ) ; writer . newLine ( ) ; writer . write ( tag ) ; writer . newLine ( ) ; } } } finally { if ( writer != null ) writer . close ( ) ; if ( reader != null ) reader . close ( ) ; } // if altered, delete old file and rename new one to the old file name if ( matched ) { htmlFile . delete ( ) ; alteredFile . renameTo ( htmlFile ) ; } else { root . printNotice ( "Warning, could not find a line that matches the pattern '" + insertPointPattern . pattern ( ) + "'.\n Class diagram reference not inserted" ) ; alteredFile . delete ( ) ; } }
Takes an HTML file looks for the first instance of the specified insertion point and inserts the diagram image reference and a client side map in that point .
563
30
144,487
private static String findOutputPath ( String [ ] [ ] options ) { for ( int i = 0 ; i < options . length ; i ++ ) { if ( options [ i ] [ 0 ] . equals ( "-d" ) ) return options [ i ] [ 1 ] ; } return "." ; }
Returns the output path specified on the javadoc options
64
12
144,488
public void setAll ( ) { showAttributes = true ; showEnumerations = true ; showEnumConstants = true ; showOperations = true ; showConstructors = true ; showVisibility = true ; showType = true ; }
Most complete output
51
3
144,489
public static int optionLength ( String option ) { if ( matchOption ( option , "qualify" , true ) || matchOption ( option , "qualifyGenerics" , true ) || matchOption ( option , "hideGenerics" , true ) || matchOption ( option , "horizontal" , true ) || matchOption ( option , "all" ) || matchOption ( option , "attributes" , true ) || matchOption ( option , "enumconstants" , true ) || matchOption ( option , "operations" , true ) || matchOption ( option , "enumerations" , true ) || matchOption ( option , "constructors" , true ) || matchOption ( option , "visibility" , true ) || matchOption ( option , "types" , true ) || matchOption ( option , "autosize" , true ) || matchOption ( option , "commentname" , true ) || matchOption ( option , "nodefontabstractitalic" , true ) || matchOption ( option , "postfixpackage" , true ) || matchOption ( option , "noguillemot" , true ) || matchOption ( option , "views" , true ) || matchOption ( option , "inferrel" , true ) || matchOption ( option , "useimports" , true ) || matchOption ( option , "collapsible" , true ) || matchOption ( option , "inferdep" , true ) || matchOption ( option , "inferdepinpackage" , true ) || matchOption ( option , "hideprivateinner" , true ) || matchOption ( option , "compact" , true ) ) return 1 ; else if ( matchOption ( option , "nodefillcolor" ) || matchOption ( option , "nodefontcolor" ) || matchOption ( option , "nodefontsize" ) || matchOption ( option , "nodefontname" ) || matchOption ( option , "nodefontclasssize" ) || matchOption ( option , "nodefontclassname" ) || matchOption ( option , "nodefonttagsize" ) || matchOption ( option , "nodefonttagname" ) || matchOption ( option , "nodefontpackagesize" ) || matchOption ( option , "nodefontpackagename" ) || matchOption ( option , "edgefontcolor" ) || matchOption ( option , "edgecolor" ) || matchOption ( option , "edgefontsize" ) || matchOption ( option , "edgefontname" ) || matchOption ( option , "shape" ) || matchOption ( option , "output" ) || matchOption ( option , "outputencoding" ) || matchOption ( option , "bgcolor" ) || matchOption ( option , "hide" ) || matchOption ( option , "include" ) || matchOption ( option , "apidocroot" ) || matchOption ( option , "apidocmap" ) || matchOption ( option , "d" ) || matchOption ( option , "view" ) || matchOption ( option , "inferreltype" ) || matchOption ( option , "inferdepvis" ) || matchOption ( option , "collpackages" ) || matchOption ( option , "nodesep" ) || matchOption ( option , "ranksep" ) || matchOption ( option , "dotexecutable" ) || matchOption ( option , "link" ) ) return 2 ; else if ( matchOption ( option , "contextPattern" ) || matchOption ( option , "linkoffline" ) ) return 3 ; else return 0 ; }
Return the number of arguments associated with the specified option . The return value includes the actual option . Will return 0 if the option is not supported .
785
29
144,490
private void addApiDocRoots ( String packageListUrl ) { BufferedReader br = null ; packageListUrl = fixApiDocRoot ( packageListUrl ) ; try { URL url = new URL ( packageListUrl + "/package-list" ) ; br = new BufferedReader ( new InputStreamReader ( url . openStream ( ) ) ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { line = line + "." ; Pattern pattern = Pattern . compile ( line . replace ( "." , "\\." ) + "[^\\.]*" ) ; apiDocMap . put ( pattern , packageListUrl ) ; } } catch ( IOException e ) { System . err . println ( "Errors happened while accessing the package-list file at " + packageListUrl ) ; } finally { if ( br != null ) try { br . close ( ) ; } catch ( IOException e ) { } } }
Adds api doc roots from a link . The folder reffered by the link should contain a package - list file that will be parsed in order to add api doc roots to this configuration
205
37
144,491
private String fixApiDocRoot ( String str ) { if ( str == null ) return null ; String fixed = str . trim ( ) ; if ( fixed . isEmpty ( ) ) return "" ; if ( File . separatorChar != ' ' ) fixed = fixed . replace ( File . separatorChar , ' ' ) ; if ( ! fixed . endsWith ( "/" ) ) fixed = fixed + "/" ; return fixed ; }
Trim and append a file separator to the string
92
11
144,492
public void setOptions ( Doc p ) { if ( p == null ) return ; for ( Tag tag : p . tags ( "opt" ) ) setOption ( StringUtil . tokenize ( tag . text ( ) ) ) ; } /** * Check if the supplied string matches an entity specified * with the -hide parameter. * @return true if the string matches. */ public boolean matchesHideExpression ( String s ) { for ( Pattern hidePattern : hidePatterns ) { // micro-optimization because the "all pattern" is heavily used in UmlGraphDoc if ( hidePattern == allPattern ) return true ; Matcher m = hidePattern . matcher ( s ) ; if ( strictMatching ? m . matches ( ) : m . find ( ) ) return true ; } return false ; } /** * Check if the supplied string matches an entity specified * with the -include parameter. * @return true if the string matches. */ public boolean matchesIncludeExpression ( String s ) { for ( Pattern includePattern : includePatterns ) { Matcher m = includePattern . matcher ( s ) ; if ( strictMatching ? m . matches ( ) : m . find ( ) ) return true ; } return false ; } /** * Check if the supplied string matches an entity specified * with the -collpackages parameter. * @return true if the string matches. */ public boolean matchesCollPackageExpression ( String s ) { for ( Pattern collPattern : collPackages ) { Matcher m = collPattern . matcher ( s ) ; if ( strictMatching ? m . matches ( ) : m . find ( ) ) return true ; } return false ; } // ---------------------------------------------------------------- // OptionProvider methods // ---------------------------------------------------------------- public Options getOptionsFor ( ClassDoc cd ) { Options localOpt = getGlobalOptions ( ) ; localOpt . setOptions ( cd ) ; return localOpt ; } public Options getOptionsFor ( String name ) { return getGlobalOptions ( ) ; } public Options getGlobalOptions ( ) { return ( Options ) clone ( ) ; } public void overrideForClass ( Options opt , ClassDoc cd ) { // nothing to do }
Set the options based on the tag elements of the ClassDoc parameter
447
13
144,493
public void addRelation ( RelationType relationType , RelationDirection direction ) { int idx = relationType . ordinal ( ) ; directions [ idx ] = directions [ idx ] . sum ( direction ) ; }
Adds eventually merging a direction for the specified relation type
49
10
144,494
private static String qualifiedName ( Options opt , String r ) { if ( opt . hideGenerics ) r = removeTemplate ( r ) ; // Fast path - nothing to do: if ( opt . showQualified && ( opt . showQualifiedGenerics || r . indexOf ( ' ' ) < 0 ) ) return r ; StringBuilder buf = new StringBuilder ( r . length ( ) ) ; qualifiedNameInner ( opt , r , buf , 0 , ! opt . showQualified ) ; return buf . toString ( ) ; }
Return the class s name possibly by stripping the leading path
114
11
144,495
private String visibility ( Options opt , ProgramElementDoc e ) { return opt . showVisibility ? Visibility . get ( e ) . symbol : " " ; }
Print the visibility adornment of element e prefixed by any stereotypes
34
14
144,496
private String parameter ( Options opt , Parameter p [ ] ) { StringBuilder par = new StringBuilder ( 1000 ) ; for ( int i = 0 ; i < p . length ; i ++ ) { par . append ( p [ i ] . name ( ) + typeAnnotation ( opt , p [ i ] . type ( ) ) ) ; if ( i + 1 < p . length ) par . append ( ", " ) ; } return par . toString ( ) ; }
Print the method parameter p
100
5
144,497
private String type ( Options opt , Type t , boolean generics ) { return ( ( generics ? opt . showQualifiedGenerics : opt . showQualified ) ? // t . qualifiedTypeName ( ) : t . typeName ( ) ) // + ( opt . hideGenerics ? "" : typeParameters ( opt , t . asParameterizedType ( ) ) ) ; }
Print a a basic type t
80
6
144,498
private String typeParameters ( Options opt , ParameterizedType t ) { if ( t == null ) return "" ; StringBuffer tp = new StringBuffer ( 1000 ) . append ( "&lt;" ) ; Type args [ ] = t . typeArguments ( ) ; for ( int i = 0 ; i < args . length ; i ++ ) { tp . append ( type ( opt , args [ i ] , true ) ) ; if ( i != args . length - 1 ) tp . append ( ", " ) ; } return tp . append ( "&gt;" ) . toString ( ) ; }
Print the parameters of the parameterized type t
130
9
144,499
private void attributes ( Options opt , FieldDoc fd [ ] ) { for ( FieldDoc f : fd ) { if ( hidden ( f ) ) continue ; stereotype ( opt , f , Align . LEFT ) ; String att = visibility ( opt , f ) + f . name ( ) ; if ( opt . showType ) att += typeAnnotation ( opt , f . type ( ) ) ; tableLine ( Align . LEFT , att ) ; tagvalue ( opt , f ) ; } }
Print the class s attributes fd
107
7