idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
21,300
public static < T , E extends Exception > Supplier < T > sneaked ( SneakySupplier < T , E > supplier ) { return ( ) -> { @ SuppressWarnings ( "unchecked" ) SneakySupplier < T , RuntimeException > castedSupplier = ( SneakySupplier < T , RuntimeException > ) supplier ; return castedSupplier . get ( ) ; } ; }
Sneaky throws a Supplier lambda .
88
9
21,301
public static < T , E extends Exception > UnaryOperator < T > sneaked ( SneakyUnaryOperator < T , E > unaryOperator ) { return t -> { @ SuppressWarnings ( "unchecked" ) SneakyUnaryOperator < T , RuntimeException > castedUnaryOperator = ( SneakyUnaryOperator < T , RuntimeException > ) unaryOperator ; return castedUnaryOperator . apply ( t ) ; } ; }
Sneaky throws a UnaryOperator lambda .
106
11
21,302
public static String [ ] split ( String input , char delimiter ) { if ( input == null ) throw new NullPointerException ( "input cannot be null" ) ; final int len = input . length ( ) ; // find the number of strings to split into int nSplits = 1 ; for ( int i = 0 ; i < len ; i ++ ) { if ( input . charAt ( i ) == delimiter ) { nSplits ++ ; } } // do the actual splitting String [ ] result = new String [ nSplits ] ; int lastMark = 0 ; int lastSplit = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( input . charAt ( i ) == delimiter ) { result [ lastSplit ] = input . substring ( lastMark , i ) ; lastSplit ++ ; lastMark = i + 1 ; // 1 == delimiter length } } result [ lastSplit ] = input . substring ( lastMark , len ) ; return result ; }
Splits a string into an array using a provided delimiter . The split chunks are also trimmed .
214
20
21,303
public static void split ( String input , char delimiter , Consumer < String > callbackPerSubstring ) { if ( input == null ) throw new NullPointerException ( "input cannot be null" ) ; final int len = input . length ( ) ; int lastMark = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( input . charAt ( i ) == delimiter ) { callbackPerSubstring . accept ( input . substring ( lastMark , i ) ) ; lastMark = i + 1 ; // 1 == delimiter length } } callbackPerSubstring . accept ( input . substring ( lastMark , len ) ) ; }
Splits a string into an array using a provided delimiter . The callback will be invoked once per each found substring
142
24
21,304
public static String firstPartOfCamelCase ( String camelcased ) { // by starting to count before the isUpperCase-check, // we do not care if the strings starts with a lower- or uppercase int end = 0 ; while ( ++ end < camelcased . length ( ) ) { if ( Character . isUpperCase ( camelcased . charAt ( end ) ) ) break ; } return camelcased . substring ( 0 , end ) ; }
Extracts the first part of a camel_cased string .
103
14
21,305
public static String decapitalize ( String word ) { return Character . toLowerCase ( word . charAt ( 0 ) ) + word . substring ( 1 ) ; }
Decapitalizes a word - only the first character is converted to lower case .
36
17
21,306
private < I , D extends Descriptor > boolean satisfies ( ScannerPlugin < I , D > selectedPlugin , D descriptor ) { return ! ( selectedPlugin . getClass ( ) . isAnnotationPresent ( Requires . class ) && descriptor == null ) ; }
Verifies if the selected plugin requires a descriptor .
55
10
21,307
protected < I > boolean accepts ( ScannerPlugin < I , ? > selectedPlugin , I item , String path , Scope scope ) { boolean accepted = false ; try { accepted = selectedPlugin . accepts ( item , path , scope ) ; } catch ( IOException e ) { LOGGER . error ( "Plugin " + selectedPlugin + " failed to check whether it can accept item " + path , e ) ; } return accepted ; }
Checks whether a plugin accepts an item .
90
9
21,308
private < D extends Descriptor > void pushDesriptor ( Class < D > type , D descriptor ) { if ( descriptor != null ) { scannerContext . push ( type , descriptor ) ; scannerContext . setCurrentDescriptor ( descriptor ) ; } }
Push the given descriptor with all it s types to the context .
55
13
21,309
private < D extends Descriptor > void popDescriptor ( Class < D > type , D descriptor ) { if ( descriptor != null ) { scannerContext . setCurrentDescriptor ( null ) ; scannerContext . pop ( type ) ; } }
Pop the given descriptor from the context .
53
8
21,310
private List < ScannerPlugin < ? , ? > > getScannerPluginsForType ( final Class < ? > type ) { List < ScannerPlugin < ? , ? > > plugins = scannerPluginsPerType . get ( type ) ; if ( plugins == null ) { // The list of all scanner plugins which accept the given type final List < ScannerPlugin < ? , ? > > candidates = new LinkedList <> ( ) ; // The map of scanner plugins which produce a descriptor type final Map < Class < ? extends Descriptor > , Set < ScannerPlugin < ? , ? > > > pluginsByDescriptor = new HashMap <> ( ) ; for ( ScannerPlugin < ? , ? > scannerPlugin : scannerPlugins . values ( ) ) { Class < ? > scannerPluginType = scannerPlugin . getType ( ) ; if ( scannerPluginType . isAssignableFrom ( type ) ) { Class < ? extends Descriptor > descriptorType = scannerPlugin . getDescriptorType ( ) ; Set < ScannerPlugin < ? , ? > > pluginsForDescriptorType = pluginsByDescriptor . get ( descriptorType ) ; if ( pluginsForDescriptorType == null ) { pluginsForDescriptorType = new HashSet <> ( ) ; pluginsByDescriptor . put ( descriptorType , pluginsForDescriptorType ) ; } pluginsForDescriptorType . add ( scannerPlugin ) ; candidates . add ( scannerPlugin ) ; } } // Order plugins by the values of their optional @Requires // annotation plugins = DependencyResolver . newInstance ( candidates , new DependencyProvider < ScannerPlugin < ? , ? > > ( ) { @ Override public Set < ScannerPlugin < ? , ? > > getDependencies ( ScannerPlugin < ? , ? > dependent ) { Set < ScannerPlugin < ? , ? > > dependencies = new HashSet <> ( ) ; Requires annotation = dependent . getClass ( ) . getAnnotation ( Requires . class ) ; if ( annotation != null ) { for ( Class < ? extends Descriptor > descriptorType : annotation . value ( ) ) { Set < ScannerPlugin < ? , ? > > pluginsByDescriptorType = pluginsByDescriptor . get ( descriptorType ) ; if ( pluginsByDescriptorType != null ) { for ( ScannerPlugin < ? , ? > scannerPlugin : pluginsByDescriptorType ) { if ( ! scannerPlugin . equals ( dependent ) ) { dependencies . add ( scannerPlugin ) ; } } } } } return dependencies ; } } ) . resolve ( ) ; scannerPluginsPerType . put ( type , plugins ) ; } return plugins ; }
Determine the list of scanner plugins that handle the given type .
576
14
21,311
private < T > List < ? super T > bind ( final ResultSet results , final Class < T > klass , final List < ? super T > instances ) throws SQLException { if ( results == null ) { throw new NullPointerException ( "results is null" ) ; } if ( klass == null ) { throw new NullPointerException ( "klass is null" ) ; } if ( instances == null ) { throw new NullPointerException ( "instances is null" ) ; } while ( results . next ( ) ) { final T instance ; try { instance = klass . newInstance ( ) ; } catch ( final ReflectiveOperationException roe ) { logger . log ( SEVERE , format ( "failed to create new instance of %s" , klass ) , roe ) ; continue ; } instances . add ( bind ( results , klass , instance ) ) ; } return instances ; }
Binds all records as given type and add them to specified list .
198
14
21,312
public MetadataContext addSuppressionPaths ( @ NonNull final String suppressionPath , @ NonNull final String ... otherPaths ) { addSuppressionPath ( suppressionPath ) ; for ( final String otherPath : otherPaths ) { addSuppressionPath ( otherPath ) ; } return this ; }
Adds suppression paths and returns this instance .
64
8
21,313
public void stop ( ) { CompletableFuture . runAsync ( ( ) -> { try { bootstrap . getInjector ( ) . getInstance ( Server . class ) . stop ( ) ; } catch ( Exception ignore ) { // Ignore NPE. At this point the server REALLY should be possible to find } bootstrap . shutdown ( ) ; } ) ; }
Asynchronously shutdowns the server
77
7
21,314
public Jawn onStartup ( Runnable callback ) { Objects . requireNonNull ( callback ) ; bootstrapper . onStartup ( callback ) ; return this ; }
Run the tasks as a part of the start up process .
37
12
21,315
public Jawn onShutdown ( Runnable callback ) { Objects . requireNonNull ( callback ) ; bootstrapper . onShutdown ( callback ) ; return this ; }
Run the tasks as a part of the shut down process .
37
12
21,316
@ Override public String asText ( ) throws ParsableException { try ( BufferedReader reader = new BufferedReader ( new InputStreamReader ( request . getInputStream ( ) ) ) ) { return reader . lines ( ) . collect ( Collectors . joining ( ) ) ; } catch ( IOException e ) { throw new ParsableException ( "Reading the input failed" ) ; } }
Conveniently converts any input in the request into a string
83
12
21,317
@ Override public byte [ ] asBytes ( ) throws IOException { try ( ServletInputStream stream = request . getInputStream ( ) ) { ByteArrayOutputStream array = new ByteArrayOutputStream ( stream . available ( ) ) ; return array . toByteArray ( ) ; } }
Reads entire request data as byte array . Do not use for large data sets to avoid memory issues .
62
21
21,318
private void executeGroup ( RuleSet ruleSet , Group group , Severity parentSeverity ) throws RuleException { if ( ! executedGroups . contains ( group ) ) { ruleVisitor . beforeGroup ( group , getEffectiveSeverity ( group , parentSeverity , parentSeverity ) ) ; for ( Map . Entry < String , Severity > conceptEntry : group . getConcepts ( ) . entrySet ( ) ) { applyConcepts ( ruleSet , conceptEntry . getKey ( ) , parentSeverity , conceptEntry . getValue ( ) ) ; } for ( Map . Entry < String , Severity > groupEntry : group . getGroups ( ) . entrySet ( ) ) { executeGroups ( ruleSet , groupEntry . getKey ( ) , parentSeverity , groupEntry . getValue ( ) ) ; } Map < String , Severity > constraints = group . getConstraints ( ) ; for ( Map . Entry < String , Severity > constraintEntry : constraints . entrySet ( ) ) { validateConstraints ( ruleSet , constraintEntry . getKey ( ) , parentSeverity , constraintEntry . getValue ( ) ) ; } ruleVisitor . afterGroup ( group ) ; executedGroups . add ( group ) ; } }
Executes the given group .
276
6
21,319
private Severity getEffectiveSeverity ( SeverityRule rule , Severity parentSeverity , Severity requestedSeverity ) { Severity effectiveSeverity = requestedSeverity != null ? requestedSeverity : parentSeverity ; return effectiveSeverity != null ? effectiveSeverity : rule . getSeverity ( ) ; }
Determines the effective severity for a rule to be executed .
76
13
21,320
private void validateConstraint ( RuleSet ruleSet , Constraint constraint , Severity severity ) throws RuleException { if ( ! executedConstraints . contains ( constraint ) ) { if ( applyRequiredConcepts ( ruleSet , constraint ) ) { ruleVisitor . visitConstraint ( constraint , severity ) ; } else { ruleVisitor . skipConstraint ( constraint , severity ) ; } executedConstraints . add ( constraint ) ; } }
Validates the given constraint .
98
6
21,321
private boolean applyConcept ( RuleSet ruleSet , Concept concept , Severity severity ) throws RuleException { Boolean result = executedConcepts . get ( concept ) ; if ( result == null ) { if ( applyRequiredConcepts ( ruleSet , concept ) ) { result = ruleVisitor . visitConcept ( concept , severity ) ; } else { ruleVisitor . skipConcept ( concept , severity ) ; result = false ; } executedConcepts . put ( concept , result ) ; } return result ; }
Applies the given concept .
110
6
21,322
private boolean isSuppressedRow ( String ruleId , Map < String , Object > row , String primaryColumn ) { Object primaryValue = row . get ( primaryColumn ) ; if ( primaryValue != null && Suppress . class . isAssignableFrom ( primaryValue . getClass ( ) ) ) { Suppress suppress = ( Suppress ) primaryValue ; for ( String suppressId : suppress . getSuppressIds ( ) ) { if ( ruleId . equals ( suppressId ) ) { return true ; } } } return false ; }
Verifies if the given row shall be suppressed .
114
10
21,323
protected < T extends ExecutableRule < ? > > Status getStatus ( T executableRule , List < String > columnNames , List < Map < String , Object > > rows , AnalyzerContext context ) throws RuleException { return context . verify ( executableRule , columnNames , rows ) ; }
Evaluate the status of the result may be overridden by sub - classes .
61
17
21,324
private static < T > T getAnnotationValue ( Annotation annotation , String value , Class < T > expectedType ) { Class < ? extends Annotation > annotationType = annotation . annotationType ( ) ; Method valueMethod ; try { valueMethod = annotationType . getDeclaredMethod ( value ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( "Cannot resolve required method '" + value + "()' for '" + annotationType + "'." ) ; } Object elementValue ; try { elementValue = valueMethod . invoke ( annotation ) ; } catch ( ReflectiveOperationException e ) { throw new IllegalStateException ( "Cannot invoke method value() for " + annotationType ) ; } return elementValue != null ? expectedType . cast ( elementValue ) : null ; }
Return a value from an annotation .
171
7
21,325
private int verifyRuleResults ( Collection < ? extends Result < ? extends ExecutableRule > > results , Severity warnOnSeverity , Severity failOnSeverity , String type , String header , boolean logResult ) { int violations = 0 ; for ( Result < ? > result : results ) { if ( Result . Status . FAILURE . equals ( result . getStatus ( ) ) ) { ExecutableRule rule = result . getRule ( ) ; String severityInfo = rule . getSeverity ( ) . getInfo ( result . getSeverity ( ) ) ; List < String > resultRows = getResultRows ( result , logResult ) ; // violation severity level check boolean warn = warnOnSeverity != null && result . getSeverity ( ) . getLevel ( ) <= warnOnSeverity . getLevel ( ) ; boolean fail = failOnSeverity != null && result . getSeverity ( ) . getLevel ( ) <= failOnSeverity . getLevel ( ) ; LoggingStrategy loggingStrategy ; if ( fail ) { violations ++ ; loggingStrategy = errorLogger ; } else if ( warn ) { loggingStrategy = warnLogger ; } else { loggingStrategy = debugLogger ; } log ( loggingStrategy , rule , resultRows , severityInfo , type , header ) ; } } return violations ; }
Verifies the given results and logs messages .
296
9
21,326
private List < String > getResultRows ( Result < ? > result , boolean logResult ) { List < String > rows = new ArrayList <> ( ) ; if ( logResult ) { for ( Map < String , Object > columns : result . getRows ( ) ) { StringBuilder row = new StringBuilder ( ) ; for ( Map . Entry < String , Object > entry : columns . entrySet ( ) ) { if ( row . length ( ) > 0 ) { row . append ( ", " ) ; } row . append ( entry . getKey ( ) ) ; row . append ( ' ' ) ; String stringValue = getLabel ( entry . getValue ( ) ) ; row . append ( stringValue ) ; } rows . add ( " " + row . toString ( ) ) ; } } return rows ; }
Convert the result rows into a string representation .
175
10
21,327
private void logDescription ( LoggingStrategy loggingStrategy , Rule rule ) { String description = rule . getDescription ( ) ; StringTokenizer tokenizer = new StringTokenizer ( description , "\n" ) ; while ( tokenizer . hasMoreTokens ( ) ) { loggingStrategy . log ( tokenizer . nextToken ( ) . replaceAll ( "(\\r|\\n|\\t)" , "" ) ) ; } }
Log the description of a rule .
91
7
21,328
public static String escapeRuleId ( Rule rule ) { return rule != null ? rule . getId ( ) . replaceAll ( "\\:" , "_" ) : null ; }
Escape the id of the given rule in a way such that it can be used as file name .
37
21
21,329
public static String getLabel ( Object value ) { if ( value != null ) { if ( value instanceof CompositeObject ) { CompositeObject descriptor = ( CompositeObject ) value ; String label = getLanguageLabel ( descriptor ) ; return label != null ? label : descriptor . toString ( ) ; } else if ( value . getClass ( ) . isArray ( ) ) { Object [ ] objects = ( Object [ ] ) value ; return getLabel ( Arrays . asList ( objects ) ) ; } else if ( value instanceof Iterable ) { StringBuilder sb = new StringBuilder ( ) ; for ( Object o : ( ( Iterable ) value ) ) { if ( sb . length ( ) > 0 ) { sb . append ( "," ) ; } sb . append ( getLabel ( o ) ) ; } return "[" + sb . toString ( ) + "]" ; } else if ( value instanceof Map ) { StringBuilder sb = new StringBuilder ( ) ; for ( Map . Entry < String , Object > entry : ( ( Map < String , Object > ) value ) . entrySet ( ) ) { if ( sb . length ( ) > 0 ) { sb . append ( "," ) ; } sb . append ( entry . getKey ( ) ) ; sb . append ( ":" ) ; sb . append ( getLabel ( entry . getValue ( ) ) ) ; } return "{" + sb . toString ( ) + "}" ; } return value . toString ( ) ; } return null ; }
Converts a value to its string representation .
331
9
21,330
public final static Class < ? > getCompiledClass ( String className , boolean useCache ) throws CompilationException , ClassLoadException { try { if ( ! useCache ) { /*String compilationResult = compileClass(className); System.out.println("************ compilationResult " + compilationResult); if (compilationResult.contains("cannot read")) { throw new ClassLoadException(compilationResult); } if (compilationResult.contains("error")) { throw new CompilationException(compilationResult); }*/ DynamicClassLoader dynamicClassLoader = new DynamicClassLoader ( DynamicClassFactory . class . getClassLoader ( ) ) ; return dynamicClassLoader . loadClass ( className ) ; } else { return CACHED_CONTROLLERS . computeIfAbsent ( className , WRAP_FORNAME ) ; } } catch ( CompilationException e ) { throw e ; // so the exception doesn't get caught by the more general catch(Exception) } catch ( Exception e ) { throw new ClassLoadException ( e ) ; } }
Handles caching of classes if not active_reload
225
11
21,331
public final Result json ( Object obj ) { final Result response = ok ( ) . contentType ( MediaType . APPLICATION_JSON ) . renderable ( obj ) ; holder . setControllerResult ( response ) ; return response ; }
This method will send a JSON response to the client . It will not use any layouts . Use it to build app . services and to support AJAX .
48
31
21,332
public Result xml ( Object obj ) { Result response = ok ( ) ; holder . setControllerResult ( response ) ; response . contentType ( MediaType . APPLICATION_XML ) . renderable ( obj ) ; return response ; }
This method will send a XML response to the client . It will not use any layouts . Use it to build app . services .
49
26
21,333
private void extractRules ( RuleSource ruleSource , Collection < ? > blocks , RuleSetBuilder builder ) throws RuleException { for ( Object element : blocks ) { if ( element instanceof AbstractBlock ) { AbstractBlock block = ( AbstractBlock ) element ; if ( EXECUTABLE_RULE_TYPES . contains ( block . getRole ( ) ) ) { extractExecutableRule ( ruleSource , block , builder ) ; } else if ( GROUP . equals ( block . getRole ( ) ) ) { extractGroup ( ruleSource , block , builder ) ; } extractRules ( ruleSource , block . getBlocks ( ) , builder ) ; } else if ( element instanceof Collection < ? > ) { extractRules ( ruleSource , ( Collection < ? > ) element , builder ) ; } } }
Find all content parts representing source code listings with a role that represents a rule .
168
16
21,334
private Map < String , Boolean > getRequiresConcepts ( RuleSource ruleSource , String id , Attributes attributes ) throws RuleException { Map < String , String > requiresDeclarations = getReferences ( attributes , REQUIRES_CONCEPTS ) ; Map < String , Boolean > required = new HashMap <> ( ) ; for ( Map . Entry < String , String > requiresEntry : requiresDeclarations . entrySet ( ) ) { String conceptId = requiresEntry . getKey ( ) ; String dependencyAttribute = requiresEntry . getValue ( ) ; Boolean optional = dependencyAttribute != null ? OPTIONAL . equals ( dependencyAttribute . toLowerCase ( ) ) : null ; required . put ( conceptId , optional ) ; } return required ; }
Evaluates required concepts of a rule .
158
9
21,335
private Map < String , String > getReferences ( Attributes attributes , String attributeName ) { String attribute = attributes . getString ( attributeName ) ; Set < String > references = new HashSet <> ( ) ; if ( attribute != null && ! attribute . trim ( ) . isEmpty ( ) ) { references . addAll ( asList ( attribute . split ( "\\s*,\\s*" ) ) ) ; } Map < String , String > rules = new HashMap <> ( ) ; for ( String reference : references ) { Matcher matcher = DEPENDENCY_PATTERN . matcher ( reference ) ; if ( matcher . matches ( ) ) { String id = matcher . group ( 1 ) ; String referenceValue = matcher . group ( 3 ) ; rules . put ( id , referenceValue ) ; } } return rules ; }
Get reference declarations for an attribute from a map of attributes .
181
12
21,336
private Severity getSeverity ( Attributes attributes , Severity defaultSeverity ) throws RuleException { String severity = attributes . getString ( SEVERITY ) ; if ( severity == null ) { return defaultSeverity ; } Severity value = Severity . fromValue ( severity . toLowerCase ( ) ) ; return value != null ? value : defaultSeverity ; }
Extract the optional severity of a rule .
81
9
21,337
private String unescapeHtml ( Object content ) { return content != null ? content . toString ( ) . replace ( "&lt;" , "<" ) . replace ( "&gt;" , ">" ) : "" ; }
Unescapes the content of a rule .
48
10
21,338
private Report getReport ( AbstractBlock part ) { Object primaryReportColum = part . getAttributes ( ) . get ( PRIMARY_REPORT_COLUM ) ; Object reportType = part . getAttributes ( ) . get ( REPORT_TYPE ) ; Properties reportProperties = parseProperties ( part , REPORT_PROPERTIES ) ; Report . ReportBuilder reportBuilder = Report . builder ( ) ; if ( reportType != null ) { reportBuilder . selectedTypes ( Report . selectTypes ( reportType . toString ( ) ) ) ; } if ( primaryReportColum != null ) { reportBuilder . primaryColumn ( primaryReportColum . toString ( ) ) ; } return reportBuilder . properties ( reportProperties ) . build ( ) ; }
Create the report part of a rule .
160
8
21,339
private Properties parseProperties ( AbstractBlock part , String attributeName ) { Properties properties = new Properties ( ) ; Object attribute = part . getAttributes ( ) . get ( attributeName ) ; if ( attribute == null ) { return properties ; } Scanner propertiesScanner = new Scanner ( attribute . toString ( ) ) ; propertiesScanner . useDelimiter ( ";" ) ; while ( propertiesScanner . hasNext ( ) ) { String next = propertiesScanner . next ( ) . trim ( ) ; if ( next . length ( ) > 0 ) { Scanner propertyScanner = new Scanner ( next ) ; propertyScanner . useDelimiter ( "=" ) ; String key = propertyScanner . next ( ) . trim ( ) ; String value = propertyScanner . next ( ) . trim ( ) ; properties . setProperty ( key , value ) ; } } return properties ; }
Parse properties from an attribute .
191
7
21,340
public final static Class < ? > getCompiledClass ( String fullClassName , boolean useCache ) throws Err . Compilation , Err . UnloadableClass { try { if ( ! useCache ) { DynamicClassLoader dynamicClassLoader = new DynamicClassLoader ( fullClassName . substring ( 0 , fullClassName . lastIndexOf ( ' ' ) ) ) ; Class < ? > cl = dynamicClassLoader . loadClass ( fullClassName ) ; dynamicClassLoader = null ; return cl ; } else { return CACHED_CONTROLLERS . computeIfAbsent ( fullClassName , WRAP_FORNAME ) ; } } catch ( Exception e ) { throw new Err . UnloadableClass ( e ) ; } }
Handles caching of classes if not useCache
157
9
21,341
public String getKeyOrDefault ( String key ) { if ( StringUtils . isBlank ( key ) ) { if ( this . hasDefaultEnvironment ( ) ) { return defaultEnvironment ; } else { throw new MultiEnvSupportException ( "[environment] property is mandatory and can't be empty" ) ; } } if ( map . containsKey ( key ) ) { return key ; } if ( this . hasTemplateEnvironment ( ) ) { return this . templateEnvironment ; } LOG . error ( "Failed to find environment [{}] in {}" , key , this . keySet ( ) ) ; throw new MultiEnvSupportException ( String . format ( "Failed to find configuration for environment %s" , key ) ) ; }
Returns the key if that specified key is mapped to something
157
11
21,342
@ Override public T get ( Object key ) { String sKey = ( String ) key ; if ( StringUtils . isBlank ( sKey ) && this . hasDefaultEnvironment ( ) ) { sKey = defaultEnvironment ; } else if ( StringUtils . isBlank ( sKey ) ) { throw new MultiEnvSupportException ( "[environment] property is mandatory and can't be empty" ) ; } T value = map . get ( sKey ) ; if ( value == null ) { if ( creationFunction != null ) { value = creationFunction . apply ( sKey ) ; } else { value = resolve ( sKey , getTemplate ( ) ) ; } if ( value != null ) { map . put ( sKey , value ) ; } } return value ; }
Returns the value to which the specified key is mapped and adds it to the internal map if it wasn t previously present .
166
24
21,343
protected T resolve ( String sKey , T value ) { LOG . error ( "Fail to find environment [{}] in {}" , sKey , this . keySet ( ) ) ; throw new MultiEnvSupportException ( String . format ( "Fail to find configuration for environment %s" , sKey ) ) ; }
By default we don t try to resolve anything but others can extend this behavior if they d like to try to resolve not found values differently .
69
28
21,344
public ImageHandlerBuilder resize ( int width , int height ) { BufferedImage resize = Scalr . resize ( image , Scalr . Mode . FIT_EXACT , width , height ) ; image . flush ( ) ; image = resize ; return this ; }
Resize the image to the given width and height
55
10
21,345
public ImageHandlerBuilder resizeToHeight ( int size ) { if ( image . getHeight ( ) < size ) return this ; BufferedImage resize = Scalr . resize ( image , Scalr . Mode . FIT_TO_HEIGHT , Math . min ( size , image . getHeight ( ) ) ) ; image . flush ( ) ; image = resize ; return this ; }
Resize the image to a given height maintaining the original proportions of the image and setting the width accordingly . If the height of the image is smaller than the provided size then the image is not scaled .
80
40
21,346
public ImageHandlerBuilder resizeToWidth ( int size ) { if ( image . getWidth ( ) < size ) return this ; BufferedImage resize = Scalr . resize ( image , Scalr . Mode . FIT_TO_WIDTH , size ) ; image . flush ( ) ; image = resize ; return this ; }
Resize the image to a given width maintaining the original proportions of the image and setting the height accordingly . If the width of the image is smaller than the provided size then the image is not scaled .
69
40
21,347
public String save ( String uploadFolder ) throws ControllerException { String realPath = info . getRealPath ( uploadFolder ) ; fn . sanitise ( ) ; String imagename = uniqueImagename ( realPath , fn . fullPath ( ) ) ; try { ImageIO . write ( image , fn . extension ( ) , new File ( realPath , imagename ) ) ; image . flush ( ) ; } catch ( IOException e ) { throw new ControllerException ( e ) ; } return uploadFolder + File . separatorChar + imagename ; }
Saves the file on the server in the folder given
117
11
21,348
String uniqueImagename ( String folder , String filename ) { String buildFileName = filename ; //.replace(' ', '_'); while ( ( new File ( folder , buildFileName ) ) . exists ( ) ) buildFileName = fn . increment ( ) ; return buildFileName ; //output.getPath(); }
Calculates a unique filename located in the image upload folder .
68
13
21,349
private List < JqassistantRules > readXmlSource ( RuleSource ruleSource ) { List < JqassistantRules > rules = new ArrayList <> ( ) ; try ( InputStream inputStream = ruleSource . getInputStream ( ) ) { JqassistantRules jqassistantRules = jaxbUnmarshaller . unmarshal ( inputStream ) ; rules . add ( jqassistantRules ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( "Cannot read rules from '" + ruleSource . getId ( ) + "'." , e ) ; } return rules ; }
Read rules from XML documents .
137
6
21,350
private Report getReport ( ReportType reportType ) { String type = null ; String primaryColumn = null ; Properties properties = new Properties ( ) ; if ( reportType != null ) { type = reportType . getType ( ) ; primaryColumn = reportType . getPrimaryColumn ( ) ; for ( PropertyType propertyType : reportType . getProperty ( ) ) { properties . setProperty ( propertyType . getName ( ) , propertyType . getValue ( ) ) ; } } Report . ReportBuilder reportBuilder = Report . builder ( ) . primaryColumn ( primaryColumn ) . properties ( properties ) ; if ( type != null ) { reportBuilder . selectedTypes ( Report . selectTypes ( type ) ) ; } return reportBuilder . build ( ) ; }
Read the report definition .
157
5
21,351
private Verification getVerification ( VerificationType verificationType ) throws RuleException { if ( verificationType != null ) { RowCountVerificationType rowCountVerificationType = verificationType . getRowCount ( ) ; AggregationVerificationType aggregationVerificationType = verificationType . getAggregation ( ) ; if ( aggregationVerificationType != null ) { return AggregationVerification . builder ( ) . column ( aggregationVerificationType . getColumn ( ) ) . min ( aggregationVerificationType . getMin ( ) ) . max ( aggregationVerificationType . getMax ( ) ) . build ( ) ; } else if ( rowCountVerificationType != null ) { return RowCountVerification . builder ( ) . min ( rowCountVerificationType . getMin ( ) ) . max ( rowCountVerificationType . getMax ( ) ) . build ( ) ; } else { throw new RuleException ( "Unsupported verification " + verificationType ) ; } } return null ; }
Read the verification definition .
206
5
21,352
private Severity getSeverity ( SeverityEnumType severityType , Severity defaultSeverity ) throws RuleException { return severityType == null ? defaultSeverity : Severity . fromValue ( severityType . value ( ) ) ; }
Get the severity .
53
4
21,353
public void printScopes ( Map < String , Scope > scopes ) { logger . info ( "Scopes [" + scopes . size ( ) + "]" ) ; for ( String scopeName : scopes . keySet ( ) ) { logger . info ( "\t" + scopeName ) ; } }
Print a list of available scopes to the console .
65
11
21,354
private void shutdownGracefully ( final Iterator < EventExecutorGroup > iterator ) { if ( iterator . hasNext ( ) ) { EventExecutorGroup group = iterator . next ( ) ; if ( ! group . isShuttingDown ( ) ) { group . shutdownGracefully ( ) . addListener ( future -> { if ( ! future . isSuccess ( ) ) { //log.debug("shutdown of {} resulted in exception", group, future.cause()); } shutdownGracefully ( iterator ) ; } ) ; } } }
Shutdown executor in order .
114
7
21,355
public static void decode ( final Map < String , String > map , final String data ) { //String[] keyValues = StringUtil.split(data, '&'); StringUtil . split ( data , ' ' , keyValue -> { final int indexOfSeperator = keyValue . indexOf ( ' ' ) ; if ( indexOfSeperator > - 1 ) { if ( indexOfSeperator == keyValue . length ( ) - 1 ) { // The '=' is at the end of the string - this counts as an unsigned value map . put ( URLCodec . decode ( keyValue . substring ( 0 , indexOfSeperator ) , StandardCharsets . UTF_8 ) , "" ) ; } else { final String first = keyValue . substring ( 0 , indexOfSeperator ) , second = keyValue . substring ( indexOfSeperator + 1 ) ; map . put ( URLCodec . decode ( first , StandardCharsets . UTF_8 ) , URLCodec . decode ( second , StandardCharsets . UTF_8 ) ) ; } } } ) ; }
A faster decode than the original from Play Framework but still equivalent in output
244
14
21,356
public static < T > T selectValue ( T defaultValue , T ... overrides ) { for ( T override : overrides ) { if ( override != null ) { return override ; } } return defaultValue ; }
Determine a value from given options .
45
9
21,357
public static < T > void verifyDeprecatedOption ( String deprecatedOption , T value , String option ) { if ( value != null ) { LOGGER . warn ( "The option '" + deprecatedOption + "' is deprecated, use '" + option + "' instead." ) ; } }
Verify if a deprecated option has been used and emit a warning .
60
14
21,358
< T > Deque < T > getValues ( Class < T > key ) { Deque < T > values = ( Deque < T > ) contextValuesPerKey . get ( key ) ; if ( values == null ) { values = new LinkedList <> ( ) ; contextValuesPerKey . put ( key , values ) ; } return values ; }
Determine the stack for the given key .
77
10
21,359
public void apply ( UnaryOperator < String > function ) { this . filename = function . apply ( this . filename ) ; if ( path != null && ! path . isEmpty ( ) ) this . path = function . apply ( this . path ) ; }
Apply the function to all string
55
6
21,360
public String increment ( ) { // filename[count].jpg int count = 0 ; String newFilename , altered = filename ( ) ; if ( altered . charAt ( altered . length ( ) - 1 ) == RIGHT ) { //(last char == 'v') we assume that a suffix already has been applied int rightBracket = altered . length ( ) - 1 , leftBracket = altered . lastIndexOf ( LEFT ) ; // leftBracket = rightBracket-2;// '-2' because at least one char ought to be between LEFT & RIGHT // crawling backwards // while (leftBracket > 0 && altered.charAt(leftBracket) != LEFT) leftBracket--; try { count = Integer . parseInt ( altered . substring ( leftBracket + 1 , rightBracket ) ) ; } catch ( NumberFormatException | IndexOutOfBoundsException ignore ) { //if it fails, we can assume that it was not a correct suffix, so we add one now newFilename = altered + LEFT ; } newFilename = altered . substring ( 0 , leftBracket + 1 ) ; } else { newFilename = altered + LEFT ; } newFilename += ( count + 1 ) ; newFilename += RIGHT ; // to prevent the char being added as an int updateName ( newFilename ) ; return newFilename + EXTENSION_SEPERATOR + ext ; }
filename . jpg - &gt ; filename_1v . jpg - &gt ; filename_2v . jpg
296
26
21,361
public static < T > Supplier < T > memoizeLock ( Supplier < T > delegate ) { AtomicReference < T > value = new AtomicReference <> ( ) ; return ( ) -> { // A 2-field variant of Double Checked Locking. T val = value . get ( ) ; if ( val == null ) { synchronized ( value ) { val = value . get ( ) ; if ( val == null ) { val = Objects . requireNonNull ( delegate . get ( ) ) ; value . set ( val ) ; } } } return val ; } ; }
Stolen from Googles Guava Suppliers . java
122
13
21,362
public static String getControllerForResult ( Route route ) { if ( route == null || route . getController ( ) == null ) return Constants . ROOT_CONTROLLER_NAME ; return RouterHelper . getReverseRouteFast ( route . getController ( ) ) . substring ( 1 ) ; }
Getting the controller from the route
68
6
21,363
private < T , U > T [ ] locateAll ( final ClassLocator locator , final Class < T > clazz , final Consumer < T > bootstrapper ) { Set < Class < ? extends T > > set = locator . subtypeOf ( clazz ) ; if ( ! set . isEmpty ( ) ) { @ SuppressWarnings ( "unchecked" ) T [ ] all = ( T [ ] ) Array . newInstance ( clazz , set . size ( ) ) ; int index = 0 ; Iterator < Class < ? extends T > > iterator = set . iterator ( ) ; while ( iterator . hasNext ( ) ) { Class < ? extends T > c = iterator . next ( ) ; try { T locatedImplementation = DynamicClassFactory . createInstance ( c , clazz ) ; bootstrapper . accept ( locatedImplementation ) ; logger . debug ( "Loaded configuration from: " + c ) ; all [ index ++ ] = locatedImplementation ; } catch ( IllegalArgumentException e ) { throw e ; } catch ( Exception e ) { logger . debug ( "Error reading custom configuration. Going with built in defaults. The error was: " + getCauseMessage ( e ) ) ; } } return all ; } else { logger . debug ( "Did not find custom configuration for {}. Going with built in defaults " , clazz ) ; } return null ; }
Locates an implementation of the given type and executes the consumer if a class of the given type is found
297
21
21,364
public Optional < List < FormItem > > parseRequestMultiPartItems ( String encoding ) { DiskFileItemFactory factory = new DiskFileItemFactory ( ) ; factory . setSizeThreshold ( properties . getInt ( Constants . PROPERTY_UPLOADS_MAX_SIZE /*Constants.Params.maxUploadSize.name()*/ ) ) ; //Configuration.getMaxUploadSize()); factory . setRepository ( new File ( System . getProperty ( "java.io.tmpdir" ) ) ) ; //Configuration.getTmpDir()); //README the file for tmpdir *MIGHT* need to go into Properties ServletFileUpload upload = new ServletFileUpload ( factory ) ; if ( encoding != null ) upload . setHeaderEncoding ( encoding ) ; upload . setFileSizeMax ( properties . getInt ( Constants . PROPERTY_UPLOADS_MAX_SIZE ) ) ; try { List < FormItem > items = upload . parseRequest ( request ) . stream ( ) . map ( item -> new ApacheFileItemFormItem ( item ) ) . collect ( Collectors . toList ( ) ) ; return Optional . of ( items ) ; } catch ( FileUploadException e ) { //"Error while trying to process mulitpart file upload" //README: perhaps some logging } return Optional . empty ( ) ; }
Gets the FileItemIterator of the input .
290
10
21,365
public void printRuleSet ( RuleSet ruleSet ) throws RuleException { RuleSelection ruleSelection = RuleSelection . builder ( ) . conceptIds ( ruleSet . getConceptBucket ( ) . getIds ( ) ) . constraintIds ( ruleSet . getConstraintBucket ( ) . getIds ( ) ) . groupIds ( ruleSet . getGroupsBucket ( ) . getIds ( ) ) . build ( ) ; printRuleSet ( ruleSet , ruleSelection ) ; }
Logs the given rule set on level info .
114
10
21,366
private void printValidRules ( CollectRulesVisitor visitor ) { logger . info ( "Groups [" + visitor . getGroups ( ) . size ( ) + "]" ) ; for ( Group group : visitor . getGroups ( ) ) { logger . info ( LOG_LINE_PREFIX + group . getId ( ) + "\"" ) ; } logger . info ( "Constraints [" + visitor . getConstraints ( ) . size ( ) + "]" ) ; for ( Constraint constraint : visitor . getConstraints ( ) . keySet ( ) ) { logger . info ( LOG_LINE_PREFIX + constraint . getId ( ) + "\" - " + constraint . getDescription ( ) ) ; } logger . info ( "Concepts [" + visitor . getConcepts ( ) . size ( ) + "]" ) ; for ( Concept concept : visitor . getConcepts ( ) . keySet ( ) ) { logger . info ( LOG_LINE_PREFIX + concept . getId ( ) + "\" - " + concept . getDescription ( ) ) ; } }
Prints all valid rules .
240
6
21,367
private CollectRulesVisitor getAllRules ( RuleSet ruleSet , RuleSelection ruleSelection ) throws RuleException { CollectRulesVisitor visitor = new CollectRulesVisitor ( ) ; RuleSetExecutor executor = new RuleSetExecutor ( visitor , new RuleSetExecutorConfiguration ( ) ) ; executor . execute ( ruleSet , ruleSelection ) ; return visitor ; }
Determines all rules .
81
6
21,368
private boolean printMissingRules ( CollectRulesVisitor visitor ) { Set < String > missingConcepts = visitor . getMissingConcepts ( ) ; if ( ! missingConcepts . isEmpty ( ) ) { logger . info ( "Missing concepts [" + missingConcepts . size ( ) + "]" ) ; for ( String missingConcept : missingConcepts ) { logger . warn ( LOG_LINE_PREFIX + missingConcept ) ; } } Set < String > missingConstraints = visitor . getMissingConstraints ( ) ; if ( ! missingConstraints . isEmpty ( ) ) { logger . info ( "Missing constraints [" + missingConstraints . size ( ) + "]" ) ; for ( String missingConstraint : missingConstraints ) { logger . warn ( LOG_LINE_PREFIX + missingConstraint ) ; } } Set < String > missingGroups = visitor . getMissingGroups ( ) ; if ( ! missingGroups . isEmpty ( ) ) { logger . info ( "Missing groups [" + missingGroups . size ( ) + "]" ) ; for ( String missingGroup : missingGroups ) { logger . warn ( LOG_LINE_PREFIX + missingGroup ) ; } } return missingConcepts . isEmpty ( ) && missingConstraints . isEmpty ( ) && missingGroups . isEmpty ( ) ; }
Prints all missing rule ids .
300
8
21,369
public String getTemplateNameForResult ( Route route , Result response ) { String template = response . template ( ) ; if ( template == null ) { if ( route != null ) { String controllerPath = RouterHelper . getReverseRouteFast ( route . getController ( ) ) ; // Look for a controller named template first if ( new File ( realPath + controllerPath + templateSuffix ) . exists ( ) ) { return controllerPath ; } //TODO Route(r).reverseRoute return controllerPath + "/" + route . getActionName ( ) ; } else { return null ; } } else { if ( template . endsWith ( templateSuffix ) ) { return template . substring ( 0 , template . length ( ) - templateSuffixLengthToRemove ) ; } return template ; } }
If the template is specified by the user with a suffix corresponding to the template engine suffix then this is removed before returning the template . Suffixes such as . st or . ftl . html
173
39
21,370
public T locateLayoutTemplate ( String controller , final String layout , final boolean useCache ) throws ViewException { // first see if we have already looked for the template final String controllerLayoutCombined = controller + ' ' + layout ; if ( useCache && cachedTemplates . containsKey ( controllerLayoutCombined ) ) return engine . clone ( cachedTemplates . get ( controllerLayoutCombined ) ) ; // README: computeIfAbsent does not save the result if null - which it actually might need to do to minimise disk reads T template ; if ( ( template = lookupLayoutWithNonDefaultName ( controllerLayoutCombined ) ) != null ) return cacheTemplate ( controllerLayoutCombined , template , useCache ) ; // going for defaults if ( ( template = lookupDefaultLayoutInControllerPathChain ( controller ) ) != null ) return cacheTemplate ( controllerLayoutCombined , template , useCache ) ; if ( ( template = lookupDefaultLayout ( ) ) != null ) return cacheTemplate ( controllerLayoutCombined , template , useCache ) ; throw new ViewException ( TemplateEngine . LAYOUT_DEFAULT + engine . getSuffixOfTemplatingEngine ( ) + " is not to be found anywhere" ) ; }
If found uses the provided layout within the controller folder . If not found it looks for the default template within the controller folder then use this to override the root default template
257
33
21,371
protected void flash ( Map < String , String > values ) { for ( Object key : values . keySet ( ) ) { flash ( key . toString ( ) , values . get ( key ) ) ; } }
Convenience method takes in a map of values to flash .
45
13
21,372
protected void flash ( String name , String value ) { /*if (session().get(Context.FLASH_SESSION_KEYWORD) == null) { session().put(Context.FLASH_SESSION_KEYWORD, new HashMap<String, Object>()); } ((Map<String, Object>) session().get(Context.FLASH_SESSION_KEYWORD)).put(name, value);*/ //context.setFlash(name, value); context . getFlash ( ) . put ( name , value ) ; }
Sends value to flash . Flash survives one more request . Using flash is typical for POST - > REDIRECT - > GET pattern
115
27
21,373
protected void redirectToReferrer ( ) { String referrer = context . requestHeader ( "Referer" ) ; referrer = referrer == null ? context . contextPath ( ) /*injector.getInstance(DeploymentInfo.class).getContextPath()*/ : referrer ; redirect ( referrer ) ; }
Redirects to referrer if one exists . If a referrer does not exist it will be redirected to the root of the application .
68
28
21,374
protected String cookieValue ( String name ) { Cookie cookie = cookie ( name ) ; return cookie != null ? cookie . getValue ( ) : null ; }
Convenience method returns cookie value .
32
8
21,375
public < T > Class < T > getType ( String typeName ) { try { return ( Class < T > ) classLoader . loadClass ( typeName ) ; } catch ( ClassNotFoundException e ) { throw new IllegalArgumentException ( "Cannot find class " + typeName , e ) ; } }
Create and return an instance of the given type name .
67
11
21,376
private Map < String , ReportPlugin > selectReportPlugins ( ExecutableRule rule ) throws ReportException { Set < String > selection = rule . getReport ( ) . getSelectedTypes ( ) ; Map < String , ReportPlugin > reportPlugins = new HashMap <> ( ) ; if ( selection != null ) { for ( String type : selection ) { ReportPlugin candidate = this . selectableReportPlugins . get ( type ) ; if ( candidate == null ) { throw new ReportException ( "Unknown report selection '" + type + "' selected for '" + rule + "'" ) ; } reportPlugins . put ( type , candidate ) ; } } return reportPlugins ; }
Select the report writers for the given rule .
146
9
21,377
static Set < String > labels ( final ResultSet results ) throws SQLException { final ResultSetMetaData metadata = results . getMetaData ( ) ; final int count = metadata . getColumnCount ( ) ; final Set < String > labels = new HashSet <> ( count ) ; for ( int i = 1 ; i <= count ; i ++ ) { labels . add ( metadata . getColumnLabel ( i ) . toUpperCase ( ) ) ; } return labels ; }
Returns a set of column labels of given result set .
102
11
21,378
private void writeStatus ( Result . Status status ) throws XMLStreamException { xmlStreamWriter . writeStartElement ( "status" ) ; xmlStreamWriter . writeCharacters ( status . name ( ) . toLowerCase ( ) ) ; xmlStreamWriter . writeEndElement ( ) ; }
Write the status of the current result .
59
8
21,379
private void writeColumn ( String columnName , Object value ) throws XMLStreamException { xmlStreamWriter . writeStartElement ( "column" ) ; xmlStreamWriter . writeAttribute ( "name" , columnName ) ; String stringValue = null ; if ( value instanceof CompositeObject ) { CompositeObject descriptor = ( CompositeObject ) value ; LanguageElement elementValue = LanguageHelper . getLanguageElement ( descriptor ) ; if ( elementValue != null ) { xmlStreamWriter . writeStartElement ( "element" ) ; xmlStreamWriter . writeAttribute ( "language" , elementValue . getLanguage ( ) ) ; xmlStreamWriter . writeCharacters ( elementValue . name ( ) ) ; xmlStreamWriter . writeEndElement ( ) ; // element SourceProvider sourceProvider = elementValue . getSourceProvider ( ) ; stringValue = sourceProvider . getName ( descriptor ) ; String sourceFile = sourceProvider . getSourceFile ( descriptor ) ; Integer lineNumber = sourceProvider . getLineNumber ( descriptor ) ; if ( sourceFile != null ) { xmlStreamWriter . writeStartElement ( "source" ) ; xmlStreamWriter . writeAttribute ( "name" , sourceFile ) ; if ( lineNumber != null ) { xmlStreamWriter . writeAttribute ( "line" , lineNumber . toString ( ) ) ; } xmlStreamWriter . writeEndElement ( ) ; // sourceFile } } } else if ( value != null ) { stringValue = ReportHelper . getLabel ( value ) ; } xmlStreamWriter . writeStartElement ( "value" ) ; xmlStreamWriter . writeCharacters ( stringValue ) ; xmlStreamWriter . writeEndElement ( ) ; // value xmlStreamWriter . writeEndElement ( ) ; // column }
Determines the language and language element of a descriptor from a result column .
357
16
21,380
private void writeDuration ( long beginTime ) throws XMLStreamException { xmlStreamWriter . writeStartElement ( "duration" ) ; xmlStreamWriter . writeCharacters ( Long . toString ( System . currentTimeMillis ( ) - beginTime ) ) ; xmlStreamWriter . writeEndElement ( ) ; // duration }
Writes the duration .
66
5
21,381
private void writeSeverity ( Severity severity ) throws XMLStreamException { xmlStreamWriter . writeStartElement ( "severity" ) ; xmlStreamWriter . writeAttribute ( "level" , severity . getLevel ( ) . toString ( ) ) ; xmlStreamWriter . writeCharacters ( severity . getValue ( ) ) ; xmlStreamWriter . writeEndElement ( ) ; }
Writes the severity of the rule .
80
8
21,382
private void run ( XmlOperation operation ) throws ReportException { try { operation . run ( ) ; } catch ( XMLStreamException | IOException e ) { throw new ReportException ( "Cannot write to XML report." , e ) ; } }
Defines an operation to write XML elements .
52
9
21,383
private final CompiledST loadTemplateResource ( String prefix , String unqualifiedFileName ) { //if (resourceRoot == null) return null; //return loadTemplate(resourceRoot, prefix, unqualifiedFileName); if ( resourceRoots . isEmpty ( ) ) return null ; CompiledST template = null ; for ( URL resourceRoot : resourceRoots ) { if ( ( template = loadTemplate ( resourceRoot , prefix , unqualifiedFileName ) ) != null ) return template ; } return null ; }
Loads from a jar or similar resource if the template could not be found directly on the filesystem .
107
20
21,384
private final void renderContentTemplate ( final ST contentTemplate , final Writer writer , final Map < String , Object > values /*, final String language*/ , final ErrorBuffer error ) { injectTemplateValues ( contentTemplate , values ) ; // if (language == null) contentTemplate . write ( createSTWriter ( writer ) , error ) ; // else // contentTemplate.write(createSTWriter(writer), new Locale(language), error); }
Renders template directly to writer
92
6
21,385
private final String renderContentTemplate ( final ST contentTemplate , final Map < String , Object > values , final ErrorBuffer error , boolean inErrorState ) { if ( contentTemplate != null ) { // it has to be possible to use a layout without defining a template try ( Writer sw = new StringBuilderWriter ( ) ) { final ErrorBuffer templateErrors = new ErrorBuffer ( ) ; renderContentTemplate ( contentTemplate , sw , values /*, language*/ , templateErrors ) ; // handle potential errors if ( ! templateErrors . errors . isEmpty ( ) && ! inErrorState ) { for ( STMessage err : templateErrors . errors ) { if ( err . error == ErrorType . INTERNAL_ERROR ) { log . warn ( "Reloading GroupDir as we have found a problem during rendering of template \"{}\"\n{}" , contentTemplate . getName ( ) , templateErrors . errors . toString ( ) ) ; //README when errors occur, try to reload the specified templates and try the whole thing again // this often rectifies the problem reloadGroup ( ) ; ST reloadedContentTemplate = readTemplate ( contentTemplate . getName ( ) ) ; return renderContentTemplate ( reloadedContentTemplate , values , error , true ) ; } } } return sw . toString ( ) ; } catch ( IOException noMethodsThrowsIOE ) { } } return "" ; }
Renders template into string
298
5
21,386
public static Integer toInteger ( Object value ) throws ConversionException { if ( value == null ) { return null ; } else if ( value instanceof Number ) { return ( ( Number ) value ) . intValue ( ) ; } else { NumberFormat nf = new DecimalFormat ( ) ; try { return nf . parse ( value . toString ( ) ) . intValue ( ) ; } catch ( ParseException e ) { throw new ConversionException ( "failed to convert: '" + value + "' to Integer" , e ) ; } } }
Converts value to Integer if it can . If value is an Integer it is returned if it is a Number it is promoted to Integer and then returned in all other cases it converts the value to String then tries to parse Integer from it .
117
48
21,387
public static Boolean toBoolean ( Object value ) { if ( value == null ) { return false ; } else if ( value instanceof Boolean ) { return ( Boolean ) value ; } else if ( value instanceof BigDecimal ) { return value . equals ( BigDecimal . ONE ) ; } else if ( value instanceof Long ) { return value . equals ( 1L ) ; } else if ( value instanceof Integer ) { return value . equals ( 1 ) ; } else if ( value instanceof Character ) { return value . equals ( ' ' ) || value . equals ( ' ' ) || value . equals ( ' ' ) || value . equals ( ' ' ) ; } else return value . toString ( ) . equalsIgnoreCase ( "yes" ) || value . toString ( ) . equalsIgnoreCase ( "true" ) || value . toString ( ) . equalsIgnoreCase ( "y" ) || value . toString ( ) . equalsIgnoreCase ( "t" ) || Boolean . parseBoolean ( value . toString ( ) ) ; }
Returns true if the value is any numeric type and has a value of 1 or if string type has a value of y t true or yes . Otherwise return false .
227
33
21,388
public static Long toLong ( Object value ) throws ConversionException { if ( value == null ) { return null ; } else if ( value instanceof Number ) { return ( ( Number ) value ) . longValue ( ) ; } else { NumberFormat nf = new DecimalFormat ( ) ; try { return nf . parse ( value . toString ( ) ) . longValue ( ) ; } catch ( ParseException e ) { throw new ConversionException ( "failed to convert: '" + value + "' to Long" , e ) ; } } }
Converts value to Long if c it can . If value is a Long it is returned if it is a Number it is promoted to Long and then returned in all other cases it converts the value to String then tries to parse Long from it .
117
49
21,389
protected < T > Class < T > getType ( String typeName ) throws PluginRepositoryException { try { return ( Class < T > ) classLoader . loadClass ( typeName . trim ( ) ) ; } catch ( ClassNotFoundException | LinkageError e ) { // Catching class loader related errors for logging a message which plugin class // actually caused the problem. throw new PluginRepositoryException ( "Cannot find or load class " + typeName , e ) ; } }
Get the class for the given type name .
102
9
21,390
protected < T > T createInstance ( String typeName ) throws PluginRepositoryException { Class < T > type = getType ( typeName . trim ( ) ) ; try { return type . newInstance ( ) ; } catch ( InstantiationException e ) { throw new PluginRepositoryException ( "Cannot create instance of class " + type . getName ( ) , e ) ; } catch ( IllegalAccessException e ) { throw new PluginRepositoryException ( "Cannot access class " + typeName , e ) ; } catch ( LinkageError e ) { throw new PluginRepositoryException ( "Cannot load plugin class " + typeName , e ) ; } }
Create an instance of the given scanner plugin class .
141
10
21,391
private final Route calculateRoute ( HttpMethod httpMethod , String requestUri /*, ActionInvoker invoker*/ /*,Injector injector*/ ) throws RouteException { if ( routes == null ) throw new IllegalStateException ( "Routes have not been compiled. Call #compileRoutes() first" ) ; final Route route = matchCustom ( httpMethod , requestUri ) ; if ( route != null ) return route ; // nothing is found - try to deduce a route from controllers //if (isDev) { try { return matchStandard ( httpMethod , requestUri , invoker /*injector*/ ) ; } catch ( ClassLoadException e ) { // a route could not be deduced } //} throw new RouteException ( "Failed to map resource to URI: " + requestUri ) ; }
It is not consistent that this particular injector handles implementations from both core and server
178
16
21,392
private Route matchStandard ( HttpMethod httpMethod , String requestUri , ActionInvoker invoker ) throws ClassLoadException { // find potential routes for ( InternalRoute internalRoute : internalRoutes ) { if ( internalRoute . matches ( requestUri ) ) { Route deferred = deduceRoute ( internalRoute , httpMethod , requestUri , invoker ) ; if ( deferred != null ) return deferred ; } } throw new ClassLoadException ( "A route for request " + requestUri + " could not be deduced" ) ; }
Only to be used in DEV mode
116
8
21,393
@ SuppressWarnings ( "NullableProblems" ) @ Override public Iterator < T > iterator ( ) { return new Iterator < T > ( ) { private int index = 0 ; @ Override public boolean hasNext ( ) { return this . index < size ( ) ; } @ Override public T next ( ) { if ( this . index >= size ( ) ) { throw new NoSuchElementException ( this . index + ">=" + size ( ) ) ; } return getElementAt ( this . index ++ ) ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( "Removing is unsupported here" ) ; } } ; }
Generates an iterator to allow the array processing in loops .
145
12
21,394
private static void assertArrayLength ( final int length , final JBBPNamedFieldInfo name ) { if ( length < 0 ) { throw new JBBPParsingException ( "Detected negative calculated array length for field '" + ( name == null ? "<NO NAME>" : name . getFieldPath ( ) ) + "\' [" + JBBPUtils . int2msg ( length ) + ' ' ) ; } }
Ensure that an array length is not a negative one .
91
12
21,395
public static JBBPParser prepare ( final String script , final JBBPBitOrder bitOrder ) { return new JBBPParser ( script , bitOrder , null , 0 ) ; }
Prepare a parser for a script and a bit order .
40
12
21,396
public static JBBPParser prepare ( final String script , final JBBPBitOrder bitOrder , final JBBPCustomFieldTypeProcessor customFieldTypeProcessor , final int flags ) { return new JBBPParser ( script , bitOrder , customFieldTypeProcessor , flags ) ; }
Prepare a parser for a script with defined bit order and special flags .
63
15
21,397
public JBBPFieldStruct parse ( final InputStream in , final JBBPVarFieldProcessor varFieldProcessor , final JBBPExternalValueProvider externalValueProvider ) throws IOException { final JBBPBitInputStream bitInStream = in instanceof JBBPBitInputStream ? ( JBBPBitInputStream ) in : new JBBPBitInputStream ( in , bitOrder ) ; this . finalStreamByteCounter = bitInStream . getCounter ( ) ; final JBBPNamedNumericFieldMap fieldMap ; if ( this . compiledBlock . hasEvaluatedSizeArrays ( ) || this . compiledBlock . hasVarFields ( ) ) { fieldMap = new JBBPNamedNumericFieldMap ( externalValueProvider ) ; } else { fieldMap = null ; } if ( this . compiledBlock . hasVarFields ( ) ) { JBBPUtils . assertNotNull ( varFieldProcessor , "The Script contains VAR fields, a var field processor must be provided" ) ; } try { return new JBBPFieldStruct ( new JBBPNamedFieldInfo ( "" , "" , - 1 ) , parseStruct ( bitInStream , new JBBPIntCounter ( ) , varFieldProcessor , fieldMap , new JBBPIntCounter ( ) , new JBBPIntCounter ( ) , false ) ) ; } finally { this . finalStreamByteCounter = bitInStream . getCounter ( ) ; } }
Parse am input stream with defined external value provider .
313
11
21,398
public List < ResultSrcItem > convertToSrc ( final TargetSources target , final String name ) { JBBPUtils . assertNotNull ( name , "Name must not be null" ) ; if ( target == TargetSources . JAVA_1_6 ) { final Properties metadata = new Properties ( ) ; metadata . setProperty ( "script" , this . compiledBlock . getSource ( ) ) ; metadata . setProperty ( "name" , name ) ; metadata . setProperty ( "target" , target . name ( ) ) ; metadata . setProperty ( "converter" , JBBPToJava6Converter . class . getCanonicalName ( ) ) ; final int nameStart = name . lastIndexOf ( ' ' ) ; final String packageName ; final String className ; if ( nameStart < 0 ) { packageName = "" ; className = name ; } else { packageName = name . substring ( 0 , nameStart ) ; className = name . substring ( nameStart + 1 ) ; } final String resultSources = JBBPToJava6Converter . makeBuilder ( this ) . setMainClassPackage ( packageName ) . setMainClassName ( className ) . build ( ) . convert ( ) ; final Map < String , String > resultMap = Collections . singletonMap ( name . replace ( ' ' , ' ' ) + ".java" , resultSources ) ; return Collections . singletonList ( new ResultSrcItem ( ) { @ Override public Properties getMetadata ( ) { return metadata ; } @ Override public Map < String , String > getResult ( ) { return resultMap ; } } ) ; } throw new IllegalArgumentException ( "Unsupported target : " + target ) ; }
Convert the prepared parser into sources . It doesn t provide way to define different flag for conversion it uses default flags for converters and provided for short fast way .
378
33
21,399
@ Nonnull public static String ensureEncodingName ( @ Nullable final String charsetName ) { final Charset defaultCharset = Charset . defaultCharset ( ) ; try { return ( charsetName == null ) ? defaultCharset . name ( ) : Charset . forName ( charsetName . trim ( ) ) . name ( ) ; } catch ( IllegalCharsetNameException ex ) { throw new IllegalArgumentException ( "Can't recognize charset for name '" + charsetName + ' ' ) ; } }
Get charset name . If name is null then default charset name provided .
121
16