idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
140,400
protected String getFunctionDescription ( String functionName ) { String className = getClass ( ) . getSimpleName ( ) ; StringBuilder buffer = new StringBuilder ( functionName . length ( ) + className . length ( ) + 4 ) ; buffer . append ( FUNCTION_NAME_PREFIX ) ; buffer . append ( functionName ) ; buffer . append ( " [" ) ; buffer . append ( className ) ; buffer . append ( "]" ) ; return buffer . toString ( ) ; }
This method gets a description of this function .
107
9
140,401
public BooleanFormula andWith ( BooleanFormula other ) { if ( other . isTrue ( ) ) { return this ; } if ( other . isFalse ( ) || isFalse ( ) ) { if ( booleanTerms == null ) { booleanTerms = new HashSet < BooleanTerm > ( ) ; } else { booleanTerms . clear ( ) ; } isSimplified = true ; return this ; } if ( isTrue ( ) ) { booleanTerms = new HashSet < BooleanTerm > ( other . booleanTerms ) ; return this ; } BooleanFormula newTerms = new BooleanFormula ( ) ; for ( BooleanTerm otherTerm : other ) { for ( BooleanTerm term : booleanTerms ) { BooleanTerm newTerm = term . andWith ( otherTerm ) ; if ( newTerm != null ) { newTerms . add ( newTerm ) ; } } } booleanTerms = newTerms . booleanTerms ; isSimplified = newTerms . isSimplified ; return this ; }
Logically ands the provided terms with the terms in the formula replacing this formula with the result
219
19
140,402
public boolean removeTerms ( Set < BooleanTerm > toRemove ) { boolean modified = false ; if ( toRemove == null || toRemove . iterator ( ) == null ) { modified = booleanTerms == null || size ( ) != 0 ; booleanTerms = new HashSet < BooleanTerm > ( ) ; } else if ( booleanTerms != null ) { modified = removeAll ( toRemove ) ; } return modified ; }
Removes the specified terms from the formula
90
8
140,403
@ Override public boolean addAll ( Collection < ? extends BooleanTerm > terms ) { boolean modified = false ; // a null booleanTerms means that the expression is // already true, so no need to modify it if ( terms == null ) { modified = booleanTerms != null ; booleanTerms = null ; } else if ( booleanTerms != null ) { for ( BooleanTerm term : terms ) { modified |= add ( term ) ; } } return modified ; }
Adds the terms to the formula . Note that if the formula has previously been simplified and determined to evaluate to true then adding any terms will have no effect .
99
31
140,404
public static TaskMonitor build ( IntVar start , IntVar duration , IntVar end ) { return new TaskMonitor ( start , duration , end ) ; }
Make a new Monitor
32
4
140,405
@ Override public boolean containsNode ( long id ) { return nodeIdMapping . containsKey ( id ) && ! isRemoved ( nodes . get ( nodeIdMapping . get ( id ) ) ) ; }
Verify whether the node which has the given id is in the graph or not .
45
17
140,406
@ Override public boolean applyAction ( Model m ) { Mapping map = m . getMapping ( ) ; if ( ! map . contains ( id ) ) { map . addReadyVM ( id ) ; return true ; } return false ; }
Put the VM in the ready state iff it does not already belong to the mapping .
52
18
140,407
public void visitResourceNames ( String packageName , boolean includeSubPackages , ClassLoader classLoader , ResourceVisitor visitor ) { try { String path = packageName . replace ( ' ' , ' ' ) ; if ( path . isEmpty ( ) ) { LOG . debug ( "Scanning entire classpath..." ) ; } else { LOG . trace ( "Scanning for resources on classpath for {}" , path ) ; } StringBuilder qualifiedNameBuilder = new StringBuilder ( path ) ; if ( qualifiedNameBuilder . length ( ) > 0 ) { qualifiedNameBuilder . append ( ' ' ) ; } String pathWithPrefix = qualifiedNameBuilder . toString ( ) ; int qualifiedNamePrefixLength = qualifiedNameBuilder . length ( ) ; Enumeration < URL > urls = classLoader . getResources ( path ) ; Set < String > urlSet = new HashSet <> ( ) ; while ( urls . hasMoreElements ( ) ) { URL url = urls . nextElement ( ) ; visitResourceUrl ( includeSubPackages , visitor , pathWithPrefix , qualifiedNameBuilder , qualifiedNamePrefixLength , url , urlSet ) ; } if ( path . isEmpty ( ) ) { visitResourceClassloader ( includeSubPackages , classLoader , visitor , pathWithPrefix , qualifiedNameBuilder , qualifiedNamePrefixLength , urlSet ) ; visitResourceClasspath ( includeSubPackages , visitor , qualifiedNameBuilder , pathWithPrefix , qualifiedNamePrefixLength , urlSet ) ; } } catch ( IOException e ) { throw new IllegalStateException ( "Error reading resources." , e ) ; } }
This method does the actual magic to locate resources on the classpath .
348
14
140,408
public boolean setPartitions ( Collection < Collection < Node > > parts ) { if ( ! isDisjoint ( parts ) ) { return false ; } partitions = parts ; return true ; }
Set the node partitions
40
4
140,409
public int run ( String ... args ) { CliParser parser = getParserBuilder ( ) . build ( this ) ; try { CliModeObject mode = parser . parseParameters ( args ) ; if ( this . help ) { assert ( mode . getId ( ) . equals ( CliMode . ID_HELP ) ) ; printHelp ( parser ) ; return 0 ; } validate ( mode ) ; return run ( mode ) ; } catch ( Exception e ) { return handleError ( e , parser ) ; } finally { getStandardOutput ( ) . flush ( ) ; getStandardError ( ) . flush ( ) ; } }
This method should be invoked from the static main - method .
133
12
140,410
public static < T > List < T > sortedCollection ( Collection < T > coll ) { List < T > list = new LinkedList < T > ( coll ) ; Collections . sort ( list , new UComp < T > ( ) ) ; return list ; }
Returns a list containing all the objects from a collection in increasing lexicographic order of their string representations .
56
21
140,411
public static < T > String stringImg ( Collection < T > coll ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "[ " ) ; for ( T t : sortedCollection ( coll ) ) { buffer . append ( t ) ; buffer . append ( " " ) ; } buffer . append ( "]" ) ; return buffer . toString ( ) ; }
Returns a string representation of all elements from a collection in increasing lexicographic order of their string representations .
80
21
140,412
public static < T > String stringImg ( T [ ] v ) { if ( v == null ) return "null" ; StringBuffer buffer = new StringBuffer ( ) ; Arrays . sort ( v , new UComp < T > ( ) ) ; for ( int i = 0 ; i < v . length ; i ++ ) { buffer . append ( v [ i ] ) ; buffer . append ( "\n" ) ; } return buffer . toString ( ) ; }
Returns a string representation of all elements from an array in increasing lexicographic order of their string representations .
100
21
140,413
@ Override public List < Sync > buildConstraint ( BtrPlaceTree t , List < BtrpOperand > args ) { if ( ! checkConformance ( t , args ) ) { return Collections . emptyList ( ) ; } @ SuppressWarnings ( "unchecked" ) List < VM > s = ( List < VM > ) params [ 0 ] . transform ( this , t , args . get ( 0 ) ) ; if ( s == null ) { return Collections . emptyList ( ) ; } if ( s . size ( ) < 2 ) { t . ignoreError ( "Parameter '" + params [ 0 ] . getName ( ) + "' expects a list of at least 2 VMs" ) ; return Collections . emptyList ( ) ; } return Collections . singletonList ( new Sync ( s ) ) ; }
Build a sync constraint .
179
5
140,414
public static int getPrecisionFormat ( @ Nonnull final String mapcode ) throws UnknownPrecisionFormatException { // First, decode to ASCII. final String decodedMapcode = convertStringToPlainAscii ( mapcode ) . toUpperCase ( ) ; // Syntax needs to be OK. if ( ! PATTERN_MAPCODE . matcher ( decodedMapcode ) . matches ( ) ) { throw new UnknownPrecisionFormatException ( decodedMapcode + " is not a correctly formatted mapcode code; " + "the regular expression for the mapcode code syntax is: " + REGEX_MAPCODE ) ; } // Precision part should be OK. final Matcher matcherPrecision = PATTERN_PRECISION . matcher ( decodedMapcode ) ; if ( ! matcherPrecision . find ( ) ) { return 0 ; } final int length = matcherPrecision . end ( ) - matcherPrecision . start ( ) - 1 ; assert ( 1 <= length ) && ( length <= 8 ) ; return length ; }
This method return the mapcode type given a mapcode string . If the mapcode string has an invalid format an exception is thrown .
226
27
140,415
public static boolean isValidMapcodeFormat ( @ Nonnull final String mapcode ) throws IllegalArgumentException { checkNonnull ( "mapcode" , mapcode ) ; try { // Throws an exception if the format is incorrect. getPrecisionFormat ( mapcode . toUpperCase ( ) ) ; return true ; } catch ( final UnknownPrecisionFormatException ignored ) { return false ; } }
This method provides a shortcut to checking if a mapcode string is formatted properly or not at all .
85
20
140,416
public static boolean containsTerritory ( @ Nonnull final String mapcode ) throws IllegalArgumentException { checkMapcodeCode ( "mapcode" , mapcode ) ; return PATTERN_TERRITORY . matcher ( mapcode . toUpperCase ( ) . trim ( ) ) . find ( ) ; }
Returns whether the mapcode contains territory information or not .
68
11
140,417
@ Nonnull static String convertStringToPlainAscii ( @ Nonnull final String string ) { return Decoder . decodeUTF16 ( string . toUpperCase ( ) ) ; }
Convert a string which potentially contains Unicode characters to an ASCII variant .
40
14
140,418
public static RePairGrammar buildGrammar ( SAXRecords saxRecords ) { RePairGrammar grammar = NewRepair . parse ( saxRecords . getSAXString ( SPACE ) ) ; return grammar ; }
Builds a repair grammar given a set of SAX records .
53
13
140,419
public static RePairGrammar buildGrammar ( String inputString ) { RePairGrammar grammar = NewRepair . parse ( inputString ) ; return grammar ; }
Builds a grammar given a string of terminals delimeted by space .
40
15
140,420
public String getValue ( String name ) { String result = null ; for ( InitParam initParam : initParams ) { if ( initParam . getName ( ) . equals ( name ) ) { result = initParam . getValue ( ) ; break ; } } return result ; }
Returns the value of the first instance of the named init - param or null if the init - param is not found .
60
24
140,421
public Collection < String > getNames ( ) { Collection < String > names = new HashSet < String > ( ) ; for ( InitParam initParam : initParams ) { names . add ( initParam . getName ( ) ) ; } return names ; }
Returns a collection of the init - param names or an empty collection if there are no init - params
55
20
140,422
public void setRefreshDelayInSeconds ( int refreshDelayInSeconds ) { ValueOutOfRangeException . checkRange ( Integer . valueOf ( refreshDelayInSeconds ) , MIN_DELAY , Integer . valueOf ( Integer . MAX_VALUE ) , getClass ( ) . getSimpleName ( ) + ".refreshDelayInSeconds" ) ; this . refreshDelayInSeconds = refreshDelayInSeconds ; }
This method sets the refresh - delay in seconds . A reasonable value should be at least 5 seconds but better in the range of minutes .
99
27
140,423
public void register ( ModelViewConverter < ? extends ModelView > c ) { java2json . put ( c . getSupportedView ( ) , c ) ; json2java . put ( c . getJSONId ( ) , c ) ; }
Register a converter for a specific view .
53
8
140,424
public ModelView fromJSON ( Model mo , JSONObject in ) throws JSONConverterException { checkKeys ( in , ModelViewConverter . IDENTIFIER ) ; Object id = in . get ( ModelViewConverter . IDENTIFIER ) ; ModelViewConverter < ? extends ModelView > c = json2java . get ( id . toString ( ) ) ; if ( c == null ) { throw new JSONConverterException ( "No converter available for a view having id '" + id + "'" ) ; } return c . fromJSON ( mo , in ) ; }
Convert a json - encoded view .
129
8
140,425
public JSONObject toJSON ( ModelView o ) throws JSONConverterException { ModelViewConverter c = java2json . get ( o . getClass ( ) ) ; if ( c == null ) { throw new JSONConverterException ( "No converter available for a view with the '" + o . getClass ( ) + "' className" ) ; } return c . toJSON ( o ) ; }
Serialise a view .
89
5
140,426
public DistanceElement getElement ( long id ) { if ( ! vector . containsKey ( id ) ) vector . put ( id , new DistanceElement ( id ) ) ; return vector . get ( id ) ; }
Gets an element of the distance vector based on the given node id . If a DistanceElement object with the given id does not exist in the vector a new object with the id is added to it . Then the element with the given id as key is returned in the end .
44
56
140,427
public void printPathTo ( long targetId ) { System . out . println ( getPath ( targetId ) . stream ( ) . map ( String :: valueOf ) . reduce ( ( s1 , s2 ) -> s1 + " -> " + s2 ) . get ( ) ) ; }
Prints the path between a source node and a target node if it exists . If it does not exist a message indicating this is shown . Is a path does exist a sequence of nodes is printed to show the path that the nodes share .
63
48
140,428
public String evaluate ( Features features , Set < String > discovered , boolean coerceUndefinedToFalse ) { if ( feature != null && discovered != null ) { discovered . add ( feature ) ; } if ( feature == null ) { return nodeName ; } else if ( ! coerceUndefinedToFalse && ! features . contains ( feature ) ) { return null ; } else { if ( features . isFeature ( feature ) ) { return trueNode . evaluate ( features , discovered , coerceUndefinedToFalse ) ; } else { return falseNode . evaluate ( features , discovered , coerceUndefinedToFalse ) ; } } }
Evaluate the has plugin for the given set of features .
132
13
140,429
public void replaceWith ( HasNode node ) { feature = node . feature ; nodeName = node . nodeName ; trueNode = node . trueNode ; falseNode = node . falseNode ; }
Replaces the properties of the current node with the properties of the specified node .
41
16
140,430
public void replaceWith ( String nodeName ) { feature = null ; this . nodeName = nodeName ; trueNode = falseNode = null ; }
Replaces the properties of the current node with the specified node name making this node into an end point node .
31
22
140,431
protected String invoke ( CommandProvider provider , CommandInterpreterWrapper interpreter ) throws Exception { Method method = provider . getClass ( ) . getMethod ( "_aggregator" , new Class [ ] { CommandInterpreter . class } ) ; //$NON-NLS-1$ method . invoke ( provider , new Object [ ] { interpreter } ) ; return interpreter . getOutput ( ) ; }
Invokes the aggregator command processor using reflection in order avoid framework dependencies on the aggregator classes .
86
20
140,432
public static final void setWriter ( String format , TreeWriter writer ) { String key = format . toLowerCase ( ) ; writers . put ( key , writer ) ; if ( JSON . equals ( key ) ) { cachedJsonWriter = writer ; } }
Binds the given TreeWriter instance to the specified data format .
54
13
140,433
public static < T > Predicate < T > TRUE ( ) { return new Predicate < T > ( ) { public boolean check ( T obj ) { return true ; } } ; }
Returns an always - true predicate .
39
7
140,434
public static < T > Predicate < T > FALSE ( ) { return Predicate . < T > NOT ( Predicate . < T > TRUE ( ) ) ; }
Returns an always - false predicate .
35
7
140,435
public static < T > Predicate < T > NOT ( final Predicate < T > pred ) { return new Predicate < T > ( ) { public boolean check ( T obj ) { return ! pred . check ( obj ) ; } } ; }
Predicate negation .
52
5
140,436
public static < T > Predicate < T > AND ( final Predicate < T > a , final Predicate < T > b ) { return new Predicate < T > ( ) { public boolean check ( T obj ) { return a . check ( obj ) && b . check ( obj ) ; } } ; }
Short - circuited AND operation .
66
8
140,437
public static < T > Predicate < T > OR ( final Predicate < T > a , final Predicate < T > b ) { return new Predicate < T > ( ) { public boolean check ( T obj ) { return a . check ( obj ) || b . check ( obj ) ; } } ; }
Short - circuited OR operation .
66
8
140,438
public void fillVMIndex ( TIntIntHashMap index , int p ) { for ( Node n : scope ) { for ( VM v : parent . getRunningVMs ( n ) ) { index . put ( v . id ( ) , p ) ; } for ( VM v : parent . getSleepingVMs ( n ) ) { index . put ( v . id ( ) , p ) ; } } for ( VM v : ready ) { index . put ( v . id ( ) , p ) ; } }
Fill an index with the VM presents in this mapping
111
10
140,439
public Boolean getIncludeStatus ( ) { if ( formula . isTrue ( ) ) { return Boolean . TRUE ; } else if ( formula . isFalse ( ) ) { return Boolean . FALSE ; } return null ; }
Returns a Boolean value indicating the value of the formula expression or null if the formula expression contains undefined features . The formula is NOT simplified prior to returning the result for performance reasons so some expressions that may simplify to TRUE can return a null value .
46
48
140,440
public ModuleDepInfo andWith ( ModuleDepInfo other ) { if ( other == null ) { return this ; } formula . andWith ( other . formula ) ; if ( ! isPluginNameDeclared && other . isPluginNameDeclared ) { pluginName = other . pluginName ; isPluginNameDeclared = true ; } else if ( pluginName == null ) { pluginName = other . pluginName ; isPluginNameDeclared = other . isPluginNameDeclared ; } return this ; }
logically ands the provided terms with the formula belonging to this object updating this object with the result .
105
21
140,441
public boolean add ( ModuleDepInfo other ) { Boolean modified = false ; if ( formula . isTrue ( ) ) { // No terms added to a true formula will change the evaluation. return false ; } if ( other . formula . isTrue ( ) ) { // Adding true to this formula makes this formula true. modified = ! formula . isTrue ( ) ; formula = new BooleanFormula ( true ) ; if ( modified && other . comment != null && other . commentTermSize < commentTermSize ) { comment = other . comment ; commentTermSize = other . commentTermSize ; } return modified ; } // Add the terms modified = formula . addAll ( other . formula ) ; // Copy over plugin name if needed if ( ! isPluginNameDeclared && other . isPluginNameDeclared ) { pluginName = other . pluginName ; isPluginNameDeclared = true ; modified = true ; } // And comments... if ( other . comment != null && other . commentTermSize < commentTermSize ) { comment = other . comment ; commentTermSize = other . commentTermSize ; } return modified ; }
Adds the terms and comments from the specified object to this object .
233
13
140,442
public void setMinMaxLength ( int [ ] lengths ) { Arrays . sort ( lengths ) ; this . minLength = lengths [ 0 ] ; this . maxLength = lengths [ lengths . length - 1 ] ; }
Set min and max lengths .
46
6
140,443
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) protected AbstractGenericType < T > create ( Type genericType , GenericType < ? > genericDefiningType ) { return new GenericTypeImpl ( genericType , genericDefiningType ) ; }
This method creates a new instance of this class . It may be overridden to create the appropriate sub - type .
59
23
140,444
public static < T > void inOrder ( T root , BinTreeNavigator < T > binTreeNav , Action < T > action ) { for ( Iterator < T > it = inOrder ( root , binTreeNav ) ; it . hasNext ( ) ; ) { T treeVertex = it . next ( ) ; action . action ( treeVertex ) ; } }
Executes an action on all nodes from a tree in inorder . For trees with sharing the same tree node object will be visited multiple times .
80
29
140,445
private Map < Link , Boolean > getFirstPhysicalPath ( Map < Link , Boolean > currentPath , Switch sw , Node dst ) { // Iterate through the current switch's links for ( Link l : net . getConnectedLinks ( sw ) ) { // Wrong link if ( currentPath . containsKey ( l ) ) { continue ; } /* * Go through the link and track the direction for full-duplex purpose * From switch to element => false : DownLink * From element to switch => true : UpLink */ currentPath . put ( l , ! l . getSwitch ( ) . equals ( sw ) ) ; // Check what is after if ( l . getElement ( ) instanceof Node ) { // Node found, path complete if ( l . getElement ( ) . equals ( dst ) ) { return currentPath ; } } else { // Go to the next switch Map < Link , Boolean > recall = getFirstPhysicalPath ( currentPath , l . getSwitch ( ) . equals ( sw ) ? ( Switch ) l . getElement ( ) : l . getSwitch ( ) , dst ) ; // Return the complete path if found if ( ! recall . isEmpty ( ) ) { return recall ; } } // Wrong link, go back currentPath . remove ( l ) ; } // No path found through this switch return new LinkedHashMap <> ( ) ; }
Recursive method to get the first physical path found from a switch to a destination node
287
17
140,446
public Bundle getBundle ( String symbolicName ) { final String sourceMethod = "getBundle" ; //$NON-NLS-1$ boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( FrameworkWiringBundleResolver . class . getName ( ) , sourceMethod , new Object [ ] { symbolicName } ) ; } Bundle [ ] candidates = Platform . getBundles ( symbolicName , null ) ; if ( isTraceLogging ) { log . finer ( "candidate bundles = " + Arrays . toString ( candidates ) ) ; //$NON-NLS-1$ } if ( candidates == null || candidates . length == 0 ) { if ( isTraceLogging ) { log . exiting ( FrameworkWiringBundleResolver . class . getName ( ) , sourceMethod , null ) ; } return null ; } if ( candidates . length == 1 ) { // Only one choice, so return it if ( isTraceLogging ) { log . exiting ( FrameworkWiringBundleResolver . class . getName ( ) , sourceMethod , candidates [ 0 ] ) ; } return candidates [ 0 ] ; } if ( fw == null ) { if ( isTraceLogging ) { log . finer ( "Framework wiring not available. Returning bundle with latest version" ) ; //$NON-NLS-1$ log . exiting ( FrameworkWiringBundleResolver . class . getName ( ) , sourceMethod , candidates [ 0 ] ) ; } return candidates [ 0 ] ; } Bundle result = null ; // For each candidate bundle, check to see if it's wired, directly or indirectly, to the contributing bundle for ( Bundle candidate : candidates ) { Collection < Bundle > bundles = fw . getDependencyClosure ( Arrays . asList ( new Bundle [ ] { candidate } ) ) ; for ( Bundle bundle : bundles ) { if ( bundle . equals ( contributingBundle ) ) { // found wired bundle. Return the candidate. result = candidate ; break ; } } if ( result != null ) { break ; } } if ( result == null ) { if ( isTraceLogging ) { log . finer ( "No wired bundle found amoung candidates. Returning bundle with most recent version." ) ; //$NON-NLS-1$ } result = candidates [ 0 ] ; } if ( isTraceLogging ) { log . exiting ( FrameworkWiringBundleResolver . class . getName ( ) , sourceMethod , result ) ; } return result ; }
Returns the bundle with the requested symbolic name that is wired to the contributing bundle or the bundle with the latest version if unable to determine wiring .
560
28
140,447
protected String getSourcesMappingEpilogue ( ) { String root = "" ; //$NON-NLS-1$ String contextPath = request . getRequestURI ( ) ; if ( contextPath != null ) { // We may be re-building a layer for a source map request where the layer // has been flushed from the cache. If that's the case, then the context // path will already include the source map path component, so just remove it. if ( contextPath . endsWith ( ILayer . SOURCEMAP_RESOURCE_PATH ) ) { contextPath = contextPath . substring ( 0 , contextPath . length ( ) - ( ILayer . SOURCEMAP_RESOURCE_PATHCOMP . length ( ) + 1 ) ) ; } // Because we're specifying a relative URL that is relative to the request for the // layer and aggregator paths are assumed to NOT include a trailing '/', then we // need to start the relative path with the last path component of the context // path so that the relative URL will be resolved correctly by the browser. For // more details, see refer to the behavior of URI.resolve(); int idx = contextPath . lastIndexOf ( "/" ) ; //$NON-NLS-1$ root = contextPath . substring ( idx != - 1 ? idx + 1 : 0 ) ; if ( root . length ( ) > 0 && ! root . endsWith ( "/" ) ) { //$NON-NLS-1$ root += "/" ; //$NON-NLS-1$ } } StringBuffer sb = new StringBuffer ( ) ; sb . append ( "//# sourceMappingURL=" ) //$NON-NLS-1$ . append ( root ) . append ( ILayer . SOURCEMAP_RESOURCE_PATHCOMP ) ; String queryString = request . getQueryString ( ) ; if ( queryString != null ) { sb . append ( "?" ) . append ( queryString ) ; //$NON-NLS-1$ } return sb . toString ( ) ; }
Returns the source mapping epilogue for the layer that gets added to the end of the response .
452
20
140,448
protected List < ModuleBuildFuture > collectFutures ( ModuleList moduleList , HttpServletRequest request ) throws IOException { final String sourceMethod = "collectFutures" ; //$NON-NLS-1$ final boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( sourceClass , sourceMethod , new Object [ ] { moduleList , request } ) ; } IAggregator aggr = ( IAggregator ) request . getAttribute ( IAggregator . AGGREGATOR_REQATTRNAME ) ; List < ModuleBuildFuture > futures = new ArrayList < ModuleBuildFuture > ( ) ; IModuleCache moduleCache = aggr . getCacheManager ( ) . getCache ( ) . getModules ( ) ; // For each source file, add a Future<IModule.ModuleReader> to the list for ( ModuleList . ModuleListEntry moduleListEntry : moduleList ) { IModule module = moduleListEntry . getModule ( ) ; Future < ModuleBuildReader > future = null ; try { future = moduleCache . getBuild ( request , module ) ; } catch ( NotFoundException e ) { if ( log . isLoggable ( Level . FINER ) ) { log . logp ( Level . FINER , sourceClass , sourceMethod , moduleListEntry . getModule ( ) . getModuleId ( ) + " not found." ) ; //$NON-NLS-1$ } future = new NotFoundModule ( module . getModuleId ( ) , module . getURI ( ) ) . getBuild ( request ) ; if ( ! moduleListEntry . isServerExpanded ( ) ) { // Treat as error. Return error response, or if debug mode, then include // the NotFoundModule in the response. if ( options . isDevelopmentMode ( ) || options . isDebugMode ( ) ) { // Don't cache responses containing error modules. request . setAttribute ( ILayer . NOCACHE_RESPONSE_REQATTRNAME , Boolean . TRUE ) ; } else { // Rethrow the exception to return an error response throw e ; } } else { // Not an error if we're doing server-side expansion, but if debug mode // then get the error message from the completed future so that we can output // a console warning in the browser. if ( options . isDevelopmentMode ( ) || options . isDebugMode ( ) ) { try { nonErrorMessages . add ( future . get ( ) . getErrorMessage ( ) ) ; } catch ( Exception ex ) { // Sholdn't ever happen as this is a CompletedFuture throw new RuntimeException ( ex ) ; } } if ( isTraceLogging ) { log . logp ( Level . FINER , sourceClass , sourceMethod , "Ignoring exception for server expanded module " + e . getMessage ( ) , e ) ; //$NON-NLS-1$ } // Don't add the future for the error module to the response. continue ; } } catch ( UnsupportedOperationException ex ) { // Missing resource factory or module builder for this resource if ( moduleListEntry . isServerExpanded ( ) ) { // ignore the error if it's a server expanded module if ( isTraceLogging ) { log . logp ( Level . FINER , sourceClass , sourceMethod , "Ignoring exception for server expanded module " + ex . getMessage ( ) , ex ) ; //$NON-NLS-1$ } continue ; } else { // re-throw the exception throw ex ; } } futures . add ( new ModuleBuildFuture ( module , future , moduleListEntry . getSource ( ) ) ) ; } if ( isTraceLogging ) { log . exiting ( sourceClass , sourceMethod , futures ) ; } return futures ; }
Dispatch the modules specified in the request to the module builders and collect the build futures returned by the builders into the returned list .
830
25
140,449
protected String notifyLayerListeners ( ILayerListener . EventType type , HttpServletRequest request , IModule module ) throws IOException { StringBuffer sb = new StringBuffer ( ) ; // notify any listeners that the config has been updated List < IServiceReference > refs = null ; if ( aggr . getPlatformServices ( ) != null ) { try { IServiceReference [ ] ary = aggr . getPlatformServices ( ) . getServiceReferences ( ILayerListener . class . getName ( ) , "(name=" + aggr . getName ( ) + ")" ) ; //$NON-NLS-1$ //$NON-NLS-2$ if ( ary != null ) refs = Arrays . asList ( ary ) ; } catch ( PlatformServicesException e ) { if ( log . isLoggable ( Level . SEVERE ) ) { log . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } } if ( refs != null ) { if ( type == EventType . END_LAYER ) { // for END_LAYER, invoke the listeners in reverse order refs = new ArrayList < IServiceReference > ( refs ) ; Collections . reverse ( refs ) ; } for ( IServiceReference ref : refs ) { ILayerListener listener = ( ILayerListener ) aggr . getPlatformServices ( ) . getService ( ref ) ; try { Set < String > depFeatures = new HashSet < String > ( ) ; String str = listener . layerBeginEndNotifier ( type , request , type == ILayerListener . EventType . BEGIN_MODULE ? Arrays . asList ( new IModule [ ] { module } ) : umLayerListenerModuleList , depFeatures ) ; dependentFeatures . addAll ( depFeatures ) ; if ( str != null ) { sb . append ( str ) ; } } finally { aggr . getPlatformServices ( ) . ungetService ( ref ) ; } } } } return sb . toString ( ) ; }
Calls the registered layer listeners .
448
7
140,450
public static String getModuleName ( URI uri ) { String name = uri . getPath ( ) ; if ( name . endsWith ( "/" ) ) { //$NON-NLS-1$ name = name . substring ( 0 , name . length ( ) - 1 ) ; } int idx = name . lastIndexOf ( "/" ) ; //$NON-NLS-1$ if ( idx != - 1 ) { name = name . substring ( idx + 1 ) ; } if ( name . endsWith ( ".js" ) ) { //$NON-NLS-1$ name = name . substring ( 0 , name . length ( ) - 3 ) ; } return name ; }
Returns the module name for the specified URI . This is the name part of the URI with path information removed and with the . js extension removed if present .
157
31
140,451
public static String getExtension ( String path ) { int idx = path . lastIndexOf ( "/" ) ; //$NON-NLS-1$ String filename = idx == - 1 ? path : path . substring ( idx + 1 ) ; idx = filename . lastIndexOf ( "." ) ; //$NON-NLS-1$ return idx == - 1 ? "" : filename . substring ( idx + 1 ) ; //$NON-NLS-1$ }
Returns the file extension part of the specified path
111
9
140,452
private boolean tryAddModule ( IAggregator aggregator , List < String > list , String bundleRoot , IResource bundleRootRes , String locale , String resource , Collection < String > availableLocales ) throws IOException { if ( availableLocales != null && ! availableLocales . contains ( locale ) ) { return false ; } boolean result = false ; URI uri = bundleRootRes . getURI ( ) ; URI testUri = uri . resolve ( locale + "/" + resource + ".js" ) ; //$NON-NLS-1$ //$NON-NLS-2$ IResource testResource = aggregator . newResource ( testUri ) ; if ( availableLocales != null || testResource . exists ( ) ) { String mid = bundleRoot + "/" + locale + "/" + resource ; //$NON-NLS-1$ //$NON-NLS-2$ list . add ( mid ) ; result = true ; } return result ; }
Adds the source for the locale specific i18n resource if it exists .
214
15
140,453
private static < A > ForwardNavigator < RegExp < A > > unionNav ( ) { return new ForwardNavigator < RegExp < A > > ( ) { private Visitor < A , List < RegExp < A > > > unionVis = new Visitor < A , List < RegExp < A > > > ( ) { public List < RegExp < A > > visit ( Union < A > ure ) { return Arrays . < RegExp < A > > asList ( ure . left , ure . right ) ; } public List < RegExp < A > > visit ( RegExp < A > re ) { return Collections . < RegExp < A > > emptyList ( ) ; } } ; public List < RegExp < A > > next ( RegExp < A > re ) { return re . accept ( unionVis ) ; } } ; }
forward navigator through the sons of Union nodes .
185
10
140,454
private static < A > ForwardNavigator < RegExp < A > > concatNav ( ) { return new ForwardNavigator < RegExp < A > > ( ) { private Visitor < A , List < RegExp < A > > > concatVis = new Visitor < A , List < RegExp < A > > > ( ) { public List < RegExp < A > > visit ( Concat < A > ure ) { return Arrays . < RegExp < A > > asList ( ure . left , ure . right ) ; } public List < RegExp < A > > visit ( RegExp < A > re ) { return Collections . < RegExp < A > > emptyList ( ) ; } } ; public List < RegExp < A > > next ( RegExp < A > re ) { return re . accept ( concatVis ) ; } } ; }
forward navigator through the sons of Concat nodes .
189
11
140,455
private Transformer createTransformer ( boolean indent ) { try { Transformer result = this . transformerFactory . newTransformer ( ) ; if ( indent ) { result . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; } return result ; } catch ( TransformerConfigurationException e ) { throw new IllegalStateException ( "XML Transformer misconfigured!" + " Probably your JVM does not support the required JAXP version!" , e ) ; } }
This method creates a new transformer .
101
7
140,456
public Parameters parameters ( ) { Parameters ps = new DefaultParameters ( ) . setTimeLimit ( timeout ) . doRepair ( repair ) . doOptimize ( optimize ) ; if ( single ( ) ) { ps . setVerbosity ( verbosity ) ; } if ( chunk ) { ps . setEnvironmentFactory ( mo -> new EnvironmentBuilder ( ) . fromChunk ( ) . build ( ) ) ; } return ps ; }
Get the parameters from the options .
90
7
140,457
public Stream < LabelledInstance > instances ( ) throws IOException { if ( single ( ) ) { return Collections . singletonList ( instance ( new File ( instance ) ) ) . stream ( ) ; } @ SuppressWarnings ( "resource" ) Stream < String > s = Files . lines ( Paths . get ( instances ) , StandardCharsets . UTF_8 ) ; return s . map ( x -> instance ( new File ( x ) ) ) ; }
List all the instances to solve .
100
7
140,458
public File output ( ) throws IOException { File o = new File ( output ) ; if ( ! o . exists ( ) && ! o . mkdirs ( ) ) { throw new IOException ( "Unable to create output folder '" + output + "'" ) ; } return o ; }
Get the output directory .
63
5
140,459
public static LabelledInstance instance ( File f ) { String path = f . getAbsolutePath ( ) ; return new LabelledInstance ( path , JSON . readInstance ( f ) ) ; }
Make an instance .
41
4
140,460
public static < T1 , T2 , T3 > Function < T1 , T3 > comp ( final Function < T2 , T3 > func1 , final Function < T1 , T2 > func2 ) { return new Function < T1 , T3 > ( ) { public T3 f ( T1 x ) { return func1 . f ( func2 . f ( x ) ) ; } } ; }
Computes the composition of two functions .
89
8
140,461
public Collection < VM > getAssociatedVGroup ( VM u ) { for ( Collection < VM > vGrp : sets ) { if ( vGrp . contains ( u ) ) { return vGrp ; } } return Collections . emptySet ( ) ; }
Get the group of VMs that contains the given VM .
55
12
140,462
protected Properties loadProps ( Properties props ) { // try to load the properties file first from the user's home directory File file = getPropsFile ( ) ; if ( file != null ) { // Try to load the file from the user's home directory if ( file . exists ( ) ) { try { URL url = file . toURI ( ) . toURL ( ) ; loadFromUrl ( props , url ) ; } catch ( MalformedURLException ex ) { if ( log . isLoggable ( Level . WARNING ) ) { log . log ( Level . WARNING , ex . getMessage ( ) , ex ) ; } } } } return props ; }
Loads the Options properties from the aggregator properties file into the specified properties object . If the properties file does not exist then try to load from the bundle .
141
32
140,463
protected void saveProps ( Properties props ) throws IOException { if ( loadFromPropertiesFile ) { // Persist the change to the properties file. File file = getPropsFile ( ) ; if ( file != null ) { FileWriter writer = new FileWriter ( file ) ; try { props . store ( writer , null ) ; } finally { writer . close ( ) ; } } } }
Saves the specified Options properties to the properties file for the aggregator .
84
15
140,464
protected void updateNotify ( long sequence ) { IServiceReference [ ] refs = null ; try { if ( aggregator != null && aggregator . getPlatformServices ( ) != null ) { refs = aggregator . getPlatformServices ( ) . getServiceReferences ( IOptionsListener . class . getName ( ) , "(name=" + registrationName + ")" ) ; //$NON-NLS-1$ //$NON-NLS-2$ if ( refs != null ) { for ( IServiceReference ref : refs ) { IOptionsListener listener = ( IOptionsListener ) aggregator . getPlatformServices ( ) . getService ( ref ) ; if ( listener != null ) { try { listener . optionsUpdated ( this , sequence ) ; } catch ( Throwable ignore ) { } finally { aggregator . getPlatformServices ( ) . ungetService ( ref ) ; } } } } } } catch ( PlatformServicesException e ) { if ( log . isLoggable ( Level . SEVERE ) ) { log . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } } }
Notify options change listeners that Options have been updated
245
10
140,465
protected void propertiesFileUpdated ( Properties updated , long sequence ) { Properties newProps = new Properties ( getDefaultOptions ( ) ) ; Enumeration < ? > propsEnum = updated . propertyNames ( ) ; while ( propsEnum . hasMoreElements ( ) ) { String name = ( String ) propsEnum . nextElement ( ) ; newProps . setProperty ( name , updated . getProperty ( name ) ) ; } setProps ( newProps ) ; updateNotify ( sequence ) ; }
Listener method for being informed of changes to the properties file by another instance of this class . Called by other instances of this class for instances that use the same properties file when properties are saved .
110
38
140,466
protected void propsFileUpdateNotify ( Properties updatedProps , long sequence ) { if ( aggregator == null || aggregator . getPlatformServices ( ) == null // unit tests? || ! loadFromPropertiesFile ) return ; IPlatformServices platformServices = aggregator . getPlatformServices ( ) ; try { IServiceReference [ ] refs = platformServices . getServiceReferences ( OptionsImpl . class . getName ( ) , "(propsFileName=" + getPropsFile ( ) . getAbsolutePath ( ) . replace ( "\\" , "\\\\" ) + ")" ) ; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ if ( refs != null ) { for ( IServiceReference ref : refs ) { String name = ref . getProperty ( "name" ) ; //$NON-NLS-1$ if ( ! registrationName . equals ( name ) ) { OptionsImpl impl = ( OptionsImpl ) platformServices . getService ( ref ) ; if ( impl != null ) { try { impl . propertiesFileUpdated ( updatedProps , sequence ) ; } catch ( Throwable ignore ) { } finally { platformServices . ungetService ( ref ) ; } } } } } } catch ( PlatformServicesException e ) { if ( log . isLoggable ( Level . SEVERE ) ) { log . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } } }
Notify implementations of this class that are listening for properties file updates on the same properties file that the properties file has been updated .
336
26
140,467
protected Properties initDefaultOptions ( ) { Properties defaultValues = new Properties ( ) ; defaultValues . putAll ( defaults ) ; // See if there's an aggregator.properties in the class loader's root ClassLoader cl = OptionsImpl . class . getClassLoader ( ) ; URL url = cl . getResource ( getPropsFilename ( ) ) ; if ( url != null ) { loadFromUrl ( defaultValues , url ) ; } // If the bundle defines properties, then load those too if ( aggregator != null ) { url = aggregator . getPlatformServices ( ) . getResource ( getPropsFilename ( ) ) ; if ( url != null ) { loadFromUrl ( defaultValues , url ) ; } } Map < String , String > map = new HashMap < String , String > ( ) ; for ( String name : defaultValues . stringPropertyNames ( ) ) { map . put ( name , ( String ) defaultValues . getProperty ( name ) ) ; } defaultOptionsMap = Collections . unmodifiableMap ( map ) ; return defaultValues ; }
Returns the default options for this the aggregator service .
224
11
140,468
void setFromFractions ( final double latFraction , final double lonFraction , final double latFractionDelta , final double lonFractionDelta ) { assert ( lonFractionDelta >= 0.0 ) ; assert ( latFractionDelta != 0.0 ) ; lonFractionMin = lonFraction ; lonFractionMax = lonFraction + lonFractionDelta ; if ( latFractionDelta < 0 ) { latFractionMin = latFraction + 1 + latFractionDelta ; // y + yDelta can NOT be represented. latFractionMax = latFraction + 1 ; // y CAN be represented. } else { latFractionMin = latFraction ; latFractionMax = latFraction + latFractionDelta ; } }
Generate upper and lower limits based on x and y and delta s .
169
15
140,469
@ Override public boolean applyAction ( Model c ) { Mapping map = c . getMapping ( ) ; return ! map . isOffline ( node ) && map . addOfflineNode ( node ) ; }
Put the node offline on a model
44
7
140,470
public static void join ( SAXSymbol left , SAXSymbol right ) { // System.out.println(" performing the join of " + getPayload(left) + " and " // + getPayload(right)); // check for an OLD digram existence - i.e. left must have a next symbol // if .n exists then we are joining TERMINAL symbols within the string, and must clean-up the // old digram if ( left . n != null ) { // System.out.println(" " + getPayload(left) // + " use to be in the digram table, cleaning up"); left . deleteDigram ( ) ; } // re-link left and right left . n = right ; right . p = left ; }
Links left and right symbols together i . e . removes this symbol from the string also removing any old digram from the hash table .
164
27
140,471
public void substitute ( SAXRule r ) { // System.out.println("[sequitur debug] *substitute* " + this.value + " with rule " // + r.asDebugLine()); // clean up this place and the next // here we keep the original position in the input string // r . addIndex ( this . originalPosition ) ; this . cleanUp ( ) ; this . n . cleanUp ( ) ; // link the rule instead of digram SAXNonTerminal nt = new SAXNonTerminal ( r ) ; nt . originalPosition = this . originalPosition ; this . p . insertAfter ( nt ) ; // do p check // // TODO: not getting this if ( ! p . check ( ) ) { p . n . check ( ) ; } }
Replace a digram with a non - terminal .
173
11
140,472
public void match ( SAXSymbol theDigram , SAXSymbol matchingDigram ) { SAXRule rule ; SAXSymbol first , second ; // System.out.println("[sequitur debug] *match* newDigram [" + newDigram.value + "," // + newDigram.n.value + "], old matching one [" + matchingDigram.value + "," // + matchingDigram.n.value + "]"); // if previous of matching digram is a guard if ( matchingDigram . p . isGuard ( ) && matchingDigram . n . n . isGuard ( ) ) { // reuse an existing rule rule = ( ( SAXGuard ) matchingDigram . p ) . r ; theDigram . substitute ( rule ) ; } else { // well, here we create a new rule because there are two matching digrams rule = new SAXRule ( ) ; try { // tie the digram's links together within the new rule // this uses copies of objects, so they do not get cut out of S first = ( SAXSymbol ) theDigram . clone ( ) ; second = ( SAXSymbol ) theDigram . n . clone ( ) ; rule . theGuard . n = first ; first . p = rule . theGuard ; first . n = second ; second . p = first ; second . n = rule . theGuard ; rule . theGuard . p = second ; // System.out.println("[sequitur debug] *newRule...* \n" + rule.getRules()); // put this digram into the hash // this effectively erases the OLD MATCHING digram with the new DIGRAM (symbol is wrapped // into Guard) theDigrams . put ( first , first ) ; // substitute the matching (old) digram with this rule in S // System.out.println("[sequitur debug] *newRule...* substitute OLD digram first."); matchingDigram . substitute ( rule ) ; // substitute the new digram with this rule in S // System.out.println("[sequitur debug] *newRule...* substitute NEW digram last."); theDigram . substitute ( rule ) ; // rule.assignLevel(); // System.out.println(" *** Digrams now: " + makeDigramsTable()); } catch ( CloneNotSupportedException c ) { c . printStackTrace ( ) ; } } // Check for an underused rule. if ( rule . first ( ) . isNonTerminal ( ) && ( ( ( SAXNonTerminal ) rule . first ( ) ) . r . count == 1 ) ) ( ( SAXNonTerminal ) rule . first ( ) ) . expand ( ) ; rule . assignLevel ( ) ; }
Deals with a matching digram .
597
8
140,473
protected static String getPayload ( SAXSymbol symbol ) { if ( symbol . isGuard ( ) ) { return "guard of the rule " + ( ( SAXGuard ) symbol ) . r . ruleIndex ; } else if ( symbol . isNonTerminal ( ) ) { return "nonterminal " + ( ( SAXNonTerminal ) symbol ) . value ; } return "symbol " + symbol . value ; }
This routine is used for the debugging .
92
8
140,474
public List < String > getExtraModules ( ) { return extraModules == null ? Collections . < String > emptyList ( ) : Collections . unmodifiableList ( extraModules ) ; }
Returns the list of additional modules that should be included ahead of this module build in the layer
42
18
140,475
public DefaultReconfigurationProblemBuilder setNextVMsStates ( Set < VM > ready , Set < VM > running , Set < VM > sleeping , Set < VM > killed ) { runs = running ; waits = ready ; sleep = sleeping ; over = killed ; return this ; }
Set the next state of the VMs . Sets must be disjoint
59
15
140,476
public DefaultReconfigurationProblem build ( ) throws SchedulerException { if ( runs == null ) { //The others are supposed to be null too as they are set using the same method Mapping map = model . getMapping ( ) ; runs = new HashSet <> ( ) ; sleep = new HashSet <> ( ) ; for ( Node n : map . getOnlineNodes ( ) ) { runs . addAll ( map . getRunningVMs ( n ) ) ; sleep . addAll ( map . getSleepingVMs ( n ) ) ; } waits = map . getReadyVMs ( ) ; over = Collections . emptySet ( ) ; } if ( manageable == null ) { manageable = new HashSet <> ( ) ; manageable . addAll ( model . getMapping ( ) . getSleepingVMs ( ) ) ; manageable . addAll ( model . getMapping ( ) . getRunningVMs ( ) ) ; manageable . addAll ( model . getMapping ( ) . getReadyVMs ( ) ) ; } if ( ps == null ) { ps = new DefaultParameters ( ) ; } return new DefaultReconfigurationProblem ( model , ps , waits , runs , sleep , over , manageable ) ; }
Build the problem
266
3
140,477
public static String inputStreamToString ( InputStream in ) throws Exception { BufferedReader br = new BufferedReader ( new InputStreamReader ( in ) ) ; StringBuffer buffer = new StringBuffer ( ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { buffer . append ( line ) ; } return buffer . toString ( ) ; }
read a String from an InputStream object .
80
9
140,478
@ Override public int compareTo ( RepairDigramRecord o ) { if ( this . freq > o . freq ) { return 1 ; } else if ( this . freq < o . freq ) { return - 1 ; } return 0 ; }
A comparator built upon occurrence frequency only .
55
9
140,479
protected Class < ? > getNIOFileResourceClass ( ) { final String method = "getNIOFileResourceClass" ; //$NON-NLS-1$ if ( tryNIO && nioFileResourceClass == null ) { try { nioFileResourceClass = classLoader . loadClass ( "com.ibm.jaggr.core.impl.resource.NIOFileResource" ) ; //$NON-NLS-1$ } catch ( ClassNotFoundException e ) { tryNIO = false ; // Don't try this again. if ( log . isLoggable ( Level . WARNING ) ) { log . logp ( Level . WARNING , CLAZZ , method , e . getMessage ( ) ) ; log . logp ( Level . WARNING , CLAZZ , method , WARN_MESSAGE ) ; } } catch ( UnsupportedClassVersionError e ) { tryNIO = false ; // Don't try this again. if ( log . isLoggable ( Level . WARNING ) ) { log . logp ( Level . WARNING , CLAZZ , method , e . getMessage ( ) ) ; log . logp ( Level . WARNING , CLAZZ , method , WARN_MESSAGE ) ; } } } return nioFileResourceClass ; }
Utility method for acquiring a reference to the NIOFileResource class without asking the class loader every single time after we know it s not there .
280
30
140,480
protected Constructor < ? > getNIOFileResourceConstructor ( Class < ? > ... args ) { final String method = "getNIOFileResourceConstructor" ; //$NON-NLS-1$ if ( tryNIO && nioFileResourceConstructor == null ) { try { Class < ? > clazz = getNIOFileResourceClass ( ) ; if ( clazz != null ) nioFileResourceConstructor = clazz . getConstructor ( args ) ; } catch ( NoSuchMethodException e ) { tryNIO = false ; // Don't try this again. if ( log . isLoggable ( Level . SEVERE ) ) { log . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } if ( log . isLoggable ( Level . WARNING ) ) log . logp ( Level . WARNING , CLAZZ , method , WARN_MESSAGE ) ; } catch ( SecurityException e ) { tryNIO = false ; // Don't try this again. if ( log . isLoggable ( Level . SEVERE ) ) { log . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } if ( log . isLoggable ( Level . WARNING ) ) log . logp ( Level . WARNING , CLAZZ , method , WARN_MESSAGE ) ; } } return nioFileResourceConstructor ; }
Utility method for acquiring a reference to the NIOFileResource class constructor without asking the class loader every single time after we know it s not there .
309
31
140,481
protected Object getNIOInstance ( Constructor < ? > constructor , Object ... args ) throws InstantiationException , IllegalAccessException , IllegalArgumentException , InvocationTargetException { final String method = "getInstance" ; //$NON-NLS-1$ Object ret = null ; if ( tryNIO ) { if ( constructor != null ) { try { ret = ( IResource ) constructor . newInstance ( args ) ; } catch ( NoClassDefFoundError e ) { if ( log . isLoggable ( Level . WARNING ) ) { log . logp ( Level . WARNING , CLAZZ , method , e . getMessage ( ) ) ; log . logp ( Level . WARNING , CLAZZ , method , WARN_MESSAGE ) ; } tryNIO = false ; } catch ( UnsupportedClassVersionError e ) { if ( log . isLoggable ( Level . WARNING ) ) { log . logp ( Level . WARNING , CLAZZ , method , e . getMessage ( ) ) ; log . logp ( Level . WARNING , CLAZZ , method , WARN_MESSAGE ) ; } tryNIO = false ; } } } return ret ; }
Utility method to catch class loading issues and prevent repeated attempts to use reflection .
256
16
140,482
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) void complete ( ) { if ( this . range != null ) { AbstractValidatorRange validator = null ; if ( this . valueType != null ) { Class < ? > valueClass = this . valueType . getAssignmentClass ( ) ; if ( this . valueType . isCollection ( ) ) { validator = new ValidatorCollectionSize ( this . range ) ; } else if ( this . valueType . isMap ( ) ) { validator = new ValidatorMapSize ( this . range ) ; } else if ( this . valueType . getComponentType ( ) != null ) { validator = new ValidatorArrayLength ( this . range ) ; } else if ( this . mathUtil . getNumberType ( valueClass ) != null ) { validator = new ValidatorRange <> ( this . range ) ; } } if ( validator == null ) { validator = new ValidatorRangeGeneric <> ( this . range ) ; } this . validatorRegistry . add ( validator ) ; } }
Has to be called at the end to complete the processing .
237
12
140,483
protected void handleNoGetterForSetter ( PojoPropertyAccessorOneArg setter , Class < ? > targetClass , Object sourceObject , Class < ? > sourceClass ) { throw new PojoPropertyNotFoundException ( sourceClass , setter . getName ( ) ) ; }
Called if the target object of the conversion has a setter that has no corresponding getter in the source object to convert .
61
26
140,484
private void appendConsoleLogging ( Node root ) { if ( logDebug && consoleDebugOutput . size ( ) > 0 ) { // Emit code to call console.log on the client Node node = root ; if ( node . getType ( ) == Token . BLOCK ) { node = node . getFirstChild ( ) ; } if ( node . getType ( ) == Token . SCRIPT ) { if ( source == null ) { // This is non-source build. Modify the AST Node firstNode = node . getFirstChild ( ) ; for ( List < String > entry : consoleDebugOutput ) { Node call = new Node ( Token . CALL , new Node ( Token . GETPROP , Node . newString ( Token . NAME , "console" ) , //$NON-NLS-1$ Node . newString ( Token . STRING , "log" ) //$NON-NLS-1$ ) ) ; for ( String str : entry ) { call . addChildToBack ( Node . newString ( str ) ) ; } node . addChildAfter ( new Node ( Token . EXPR_RESULT , call ) , firstNode ) ; } } else { // Non-source build. Modify the AST for ( List < String > entry : consoleDebugOutput ) { StringBuffer sb = new StringBuffer ( "console.log(" ) ; //$NON-NLS-1$ int i = 0 ; for ( String str : entry ) { sb . append ( ( i ++ == 0 ? "" : "," ) + "\"" + StringUtil . escapeForJavaScript ( str ) + "\"" ) ; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } sb . append ( ");\n" ) ; //$NON-NLS-1$ source . appendln ( sb . toString ( ) ) ; } } } } }
Appends the console log output if any to the end of the module
434
14
140,485
public void close ( ) throws IOException { if ( dataStream != null ) dataStream . close ( ) ; byteStream = null ; dataStream = null ; }
Closes the file . No more reading is possible after the file has been closed .
34
17
140,486
protected Collection < String > getRequestedLocales ( HttpServletRequest request ) { final String sourceMethod = "getRequestedLocales" ; //$NON-NLS-1$ boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( sourceClass , sourceMethod , new Object [ ] { request . getQueryString ( ) } ) ; } String [ ] locales ; String sLocales = getParameter ( request , REQUESTEDLOCALES_REQPARAMS ) ; if ( sLocales != null ) { locales = sLocales . split ( "," ) ; //$NON-NLS-1$ } else { locales = new String [ 0 ] ; } Collection < String > result = Collections . unmodifiableCollection ( Arrays . asList ( locales ) ) ; if ( isTraceLogging ) { log . exiting ( sourceClass , sourceMethod , result ) ; } return result ; }
Returns the requested locales as a collection of locale strings
222
11
140,487
protected String getHasConditionsFromRequest ( HttpServletRequest request ) throws IOException { final String sourceMethod = "getHasConditionsFromRequest" ; //$NON-NLS-1$ boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( sourceClass , sourceMethod , new Object [ ] { request } ) ; } String ret = null ; if ( request . getParameter ( FEATUREMAPHASH_REQPARAM ) != null ) { // The cookie called 'has' contains the has conditions if ( isTraceLogging ) { log . finer ( "has hash = " + request . getParameter ( FEATUREMAPHASH_REQPARAM ) ) ; //$NON-NLS-1$ } Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies != null ) { for ( int i = 0 ; ret == null && i < cookies . length ; i ++ ) { Cookie cookie = cookies [ i ] ; if ( cookie . getName ( ) . equals ( FEATUREMAP_REQPARAM ) && cookie . getValue ( ) != null ) { if ( isTraceLogging ) { log . finer ( "has cookie = " + cookie . getValue ( ) ) ; //$NON-NLS-1$ } ret = URLDecoder . decode ( cookie . getValue ( ) , "US-ASCII" ) ; //$NON-NLS-1$ break ; } } } if ( ret == null ) { if ( log . isLoggable ( Level . WARNING ) ) { StringBuffer url = request . getRequestURL ( ) ; if ( url != null ) { // might be null if using mock request for unit testing url . append ( "?" ) . append ( request . getQueryString ( ) ) . toString ( ) ; //$NON-NLS-1$ log . warning ( MessageFormat . format ( Messages . AbstractHttpTransport_0 , new Object [ ] { url , request . getHeader ( "User-Agent" ) } ) ) ; //$NON-NLS-1$ } } } } else { ret = request . getParameter ( FEATUREMAP_REQPARAM ) ; if ( isTraceLogging ) { log . finer ( "reading features from has query arg" ) ; //$NON-NLS-1$ } } if ( isTraceLogging ) { log . exiting ( sourceClass , sourceMethod , ret ) ; } return ret ; }
This method checks the request for the has conditions which may either be contained in URL query arguments or in a cookie sent from the client .
556
27
140,488
protected static String getParameter ( HttpServletRequest request , String [ ] aliases ) { final String sourceMethod = "getParameter" ; //$NON-NLS-1$ boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( sourceClass , sourceMethod , new Object [ ] { request . getQueryString ( ) , Arrays . asList ( aliases ) } ) ; } Map < String , String [ ] > params = request . getParameterMap ( ) ; String result = null ; for ( Map . Entry < String , String [ ] > entry : params . entrySet ( ) ) { String name = entry . getKey ( ) ; for ( String alias : aliases ) { if ( alias . equalsIgnoreCase ( name ) ) { String [ ] values = entry . getValue ( ) ; result = values [ values . length - 1 ] ; // return last value in array } } } if ( isTraceLogging ) { log . exiting ( sourceClass , sourceMethod , result ) ; } return result ; }
Returns the value of the requested parameter from the request or null
238
12
140,489
protected OptimizationLevel getOptimizationLevelFromRequest ( HttpServletRequest request ) { final String sourceMethod = "getOptimizationLevelFromRequest" ; //$NON-NLS-1$ boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( sourceClass , sourceMethod , new Object [ ] { request . getQueryString ( ) } ) ; } // Get the optimization level specified in the request and set the ComilationLevel String optimize = getParameter ( request , OPTIMIZATIONLEVEL_REQPARAMS ) ; OptimizationLevel level = OptimizationLevel . SIMPLE ; if ( optimize != null && ! optimize . equals ( "" ) ) { //$NON-NLS-1$ if ( optimize . equalsIgnoreCase ( "whitespace" ) ) //$NON-NLS-1$ level = OptimizationLevel . WHITESPACE ; else if ( optimize . equalsIgnoreCase ( "advanced" ) ) //$NON-NLS-1$ level = OptimizationLevel . ADVANCED ; else if ( optimize . equalsIgnoreCase ( "none" ) ) //$NON-NLS-1$ level = OptimizationLevel . NONE ; } if ( isTraceLogging ) { log . exiting ( sourceClass , sourceMethod , level ) ; } return level ; }
Returns the requested optimization level from the request .
309
9
140,490
protected String getDynamicLoaderExtensionJavaScript ( HttpServletRequest request ) { final String sourceMethod = "getDynamicLoaderExtensionJavaScript" ; //$NON-NLS-1$ boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( sourceClass , sourceMethod ) ; } StringBuffer sb = new StringBuffer ( ) ; for ( String contribution : getExtensionContributions ( ) ) { sb . append ( contribution ) . append ( "\r\n" ) ; //$NON-NLS-1$ } String cacheBust = AggregatorUtil . getCacheBust ( getAggregator ( ) ) ; if ( cacheBust != null && cacheBust . length ( ) > 0 ) { sb . append ( "if (!require.combo.cacheBust){require.combo.cacheBust = '" ) //$NON-NLS-1$ . append ( cacheBust ) . append ( "';}\r\n" ) ; //$NON-NLS-1$ } contributeBootLayerDeps ( sb , request ) ; if ( moduleIdListHash != null ) { sb . append ( "require.combo.reg(null, [" ) ; //$NON-NLS-1$ for ( int i = 0 ; i < moduleIdListHash . length ; i ++ ) { sb . append ( i == 0 ? "" : ", " ) . append ( ( ( int ) moduleIdListHash [ i ] ) & 0xFF ) ; //$NON-NLS-1$ //$NON-NLS-2$ } sb . append ( "]);\r\n" ) ; //$NON-NLS-1$ } sb . append ( clientRegisterSyntheticModules ( ) ) ; if ( isTraceLogging ) { log . exiting ( sourceClass , sourceMethod , sb . toString ( ) ) ; } return sb . toString ( ) ; }
Returns the dynamic portion of the loader extension javascript for this transport . This includes all registered extension contributions .
455
20
140,491
protected FeatureListResourceFactory newFeatureListResourceFactory ( URI resourceUri ) { final String methodName = "newFeatureMapJSResourceFactory" ; //$NON-NLS-1$ boolean traceLogging = log . isLoggable ( Level . FINER ) ; if ( traceLogging ) { log . entering ( sourceClass , methodName , new Object [ ] { resourceUri } ) ; } FeatureListResourceFactory factory = new FeatureListResourceFactory ( resourceUri ) ; if ( traceLogging ) { log . exiting ( sourceClass , methodName ) ; } return factory ; }
Returns an instance of a FeatureMapJSResourceFactory .
128
11
140,492
protected String clientRegisterSyntheticModules ( ) { final String methodName = "clientRegisterSyntheticModules" ; //$NON-NLS-1$ boolean traceLogging = log . isLoggable ( Level . FINER ) ; if ( traceLogging ) { log . entering ( sourceClass , methodName ) ; } StringBuffer sb = new StringBuffer ( ) ; Map < String , Integer > map = getModuleIdMap ( ) ; if ( map != null && getModuleIdRegFunctionName ( ) != null ) { Collection < String > names = getSyntheticModuleNames ( ) ; if ( names != null && names . size ( ) > 0 ) { // register the text plugin name (combo/text) and name id with the client sb . append ( getModuleIdRegFunctionName ( ) ) . append ( "([[[" ) ; //$NON-NLS-1$ int i = 0 ; for ( String name : names ) { if ( map . get ( name ) != null ) { sb . append ( i ++ == 0 ? "" : "," ) . append ( "\"" ) . append ( name ) . append ( "\"" ) ; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } } sb . append ( "]],[[" ) ; //$NON-NLS-1$ i = 0 ; for ( String name : names ) { Integer id = map . get ( name ) ; if ( id != null ) { sb . append ( i ++ == 0 ? "" : "," ) . append ( id . intValue ( ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ } } sb . append ( "]]]);" ) ; //$NON-NLS-1$ } } if ( traceLogging ) { log . exiting ( sourceClass , methodName , sb . toString ( ) ) ; } return sb . toString ( ) ; }
Returns the JavaScript code for calling the client - side module name id registration function to register name ids for the transport synthetic modules .
459
26
140,493
public static void main ( String [ ] args ) { System . out . println ( LONG_NAME + " - Release " + RELEASE ) ; System . out . println ( ) ; System . out . println ( " " + CREDO ) ; System . out . println ( ) ; System . out . println ( "Project maintainer: " + MAINTAINER ) ; System . out . println ( "Javadoc accessible from the official website on SourceForge:\n\t" + WEBSITE ) ; System . out . println ( "Submit bug reports / feature requests on the website." ) ; }
Prints a small informative message about the current release .
128
11
140,494
private static int [ ] toBoundaries ( String str ) { int [ ] res = new int [ 9 ] ; String [ ] split = str . split ( "\\s+" ) ; for ( int i = 0 ; i < 9 ; i ++ ) { res [ i ] = Integer . valueOf ( split [ i ] ) . intValue ( ) ; } return res ; }
Converts a param string to boundaries array .
81
9
140,495
public Slice build ( ) throws SchedulerException { if ( hoster == null ) { hoster = rp . makeHostVariable ( lblPrefix , "_hoster" ) ; } if ( start == null ) { start = rp . getStart ( ) ; } if ( end == null ) { end = rp . getEnd ( ) ; } if ( duration == null ) { duration = makeDuration ( ) ; } //UB for the time variables if ( ! start . isInstantiatedTo ( 0 ) ) { //enforces start <= end, duration <= end, start + duration == end TaskMonitor . build ( start , duration , end ) ; } //start == 0 --> start <= end. duration = end enforced by TaskScheduler return new Slice ( vm , start , end , duration , hoster ) ; }
Build the slice .
177
4
140,496
private IntVar makeDuration ( ) throws SchedulerException { if ( start . isInstantiated ( ) && end . isInstantiated ( ) ) { int d = end . getValue ( ) - start . getValue ( ) ; return rp . makeDuration ( d , d , lblPrefix , "_duration" ) ; } else if ( start . isInstantiated ( ) ) { if ( start . isInstantiatedTo ( 0 ) ) { return end ; } return rp . getModel ( ) . intOffsetView ( end , - start . getValue ( ) ) ; } int inf = end . getLB ( ) - start . getUB ( ) ; if ( inf < 0 ) { inf = 0 ; } int sup = end . getUB ( ) - start . getLB ( ) ; return rp . makeDuration ( sup , inf , lblPrefix , "_duration" ) ; }
Make the duration variable depending on the others .
192
9
140,497
public String generateSourceMap ( ) throws IOException { final String sourceMethod = "generateSourceMap" ; //$NON-NLS-1$ final boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( sourceClass , sourceMethod , new Object [ ] { name } ) ; } String result = null ; lineLengths = getLineLengths ( ) ; Compiler compiler = new Compiler ( ) ; sgen = new SourceMapGeneratorV3 ( ) ; compiler . initOptions ( compiler_options ) ; currentLine = currentChar = 0 ; Node node = compiler . parse ( JSSourceFile . fromCode ( name , source ) ) ; if ( compiler . hasErrors ( ) ) { if ( log . isLoggable ( Level . WARNING ) ) { JSError [ ] errors = compiler . getErrors ( ) ; for ( JSError error : errors ) { log . logp ( Level . WARNING , sourceClass , sourceMethod , error . toString ( ) ) ; } } } if ( node != null ) { processNode ( node ) ; StringWriter writer = new StringWriter ( ) ; sgen . appendTo ( writer , name ) ; result = writer . toString ( ) ; } sgen = null ; lineLengths = null ; if ( isTraceLogging ) { log . exiting ( sourceClass , sourceMethod , result ) ; } return result ; }
Generate the identity source map and return the result .
322
11
140,498
private void processNode ( Node node ) throws IOException { for ( Node cursor = node . getFirstChild ( ) ; cursor != null ; cursor = cursor . getNext ( ) ) { int lineno = cursor . getLineno ( ) - 1 ; // adjust for rhino line numbers being 1 based int charno = cursor . getCharno ( ) ; if ( lineno > currentLine || lineno == currentLine && charno > currentChar ) { currentLine = lineno ; currentChar = charno ; } FilePosition endPosition = getEndPosition ( cursor ) ; sgen . addMapping ( name , null , new FilePosition ( currentLine , currentChar ) , new FilePosition ( currentLine , currentChar ) , endPosition ) ; if ( cursor . hasChildren ( ) ) { processNode ( cursor ) ; } } }
Recursively processes the input node adding a mapping for the node to the source map generator .
178
19
140,499
protected void dispatchEvents ( ) { while ( true ) { Object event = this . eventQueue . poll ( ) ; if ( event == null ) { return ; } Collection < Throwable > errors = new LinkedList <> ( ) ; dispatchEvent ( event , errors ) ; if ( ! errors . isEmpty ( ) ) { handleErrors ( errors , event ) ; } } }
Dispatches all events in the event queue .
81
10