idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
18,200 | protected void scanSuper ( TypeElement e ) { TypeElement superElement = ( TypeElement ) utils . typeUtils . asElement ( e . getSuperclass ( ) ) ; if ( superElement != null ) { superElement . accept ( new ContractExtensionBuilder ( ) , type ) ; } for ( TypeMirror iface : e . getInterfaces ( ) ) { TypeElement ifaceElement = ( TypeElement ) utils . typeUtils . asElement ( iface ) ; ifaceElement . accept ( new ContractExtensionBuilder ( ) , type ) ; } } | Visits the superclass and interfaces of the specified TypeElement with a ContractExtensionBuilder . |
18,201 | public static ConfigParams resolve ( ConfigParams config , boolean configAsDefault ) { ConfigParams options = config . getSection ( "options" ) ; if ( options . size ( ) == 0 && configAsDefault ) options = config ; return options ; } | Resolves an options configuration section from component configuration parameters . |
18,202 | public List < List < String > > doSelect ( final String sql ) throws SQLException { List < List < String > > results = new ArrayList < List < String > > ( ) ; LOG . info ( "Connecting to: " + this . dbString + " with " + this . usr + " and " + this . pwd ) ; LOG . info ( "Executing: " + sql ) ; Connection connection = null ; Statement st = null ; ResultSet rs = null ; try { connection = DriverManager . getConnection ( this . dbString , this . usr , this . pwd ) ; st = connection . createStatement ( ) ; rs = st . executeQuery ( sql ) ; while ( rs . next ( ) ) { ResultSetMetaData meta = rs . getMetaData ( ) ; List < String > lines = new ArrayList < String > ( ) ; for ( int col = 1 ; col < meta . getColumnCount ( ) + 1 ; col ++ ) { lines . add ( rs . getString ( col ) ) ; } results . add ( lines ) ; } } finally { if ( rs != null ) { rs . close ( ) ; } if ( st != null ) { st . close ( ) ; } if ( connection != null ) { connection . close ( ) ; } } LOG . info ( "Result returned after running " + sql + " is: " + results ) ; return results ; } | Runs a select query against the DB and get the results in a list of lists . Each item in the list will be a list of items corresponding to a row returned by the select . |
18,203 | public List < String > getValuesOfColumn ( final int columnNumber , final String sqlQuery ) throws SQLException { LOG . info ( "Connecting to: " + this . dbString + " with " + this . usr + " and " + this . pwd ) ; LOG . info ( "Executing: " + sqlQuery ) ; List < String > result = new ArrayList < String > ( ) ; List < List < String > > allResults = this . doSelect ( sqlQuery ) ; for ( List < String > list : allResults ) { result . add ( list . get ( columnNumber ) ) ; } LOG . info ( "Result returned after running " + sqlQuery + " is: " + result ) ; return result ; } | Returns all the values corresponding to a specific column returned by executing the supplied sql . |
18,204 | private String getQueryClauses ( final Map < String , Object > params , final Map < String , Object > orderParams ) { final StringBuffer queryString = new StringBuffer ( ) ; if ( ( params != null ) && ! params . isEmpty ( ) ) { queryString . append ( " where " ) ; for ( final Iterator < Map . Entry < String , Object > > it = params . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { final Map . Entry < String , Object > entry = it . next ( ) ; if ( entry . getValue ( ) instanceof Boolean ) { queryString . append ( entry . getKey ( ) ) . append ( " is " ) . append ( entry . getValue ( ) ) . append ( " " ) ; } else { if ( entry . getValue ( ) instanceof Number ) { queryString . append ( entry . getKey ( ) ) . append ( " = " ) . append ( entry . getValue ( ) ) ; } else { queryString . append ( entry . getKey ( ) ) . append ( " = '" ) . append ( entry . getValue ( ) ) . append ( "'" ) ; } } if ( it . hasNext ( ) ) { queryString . append ( " and " ) ; } } } if ( ( orderParams != null ) && ! orderParams . isEmpty ( ) ) { queryString . append ( " order by " ) ; for ( final Iterator < Map . Entry < String , Object > > it = orderParams . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { final Map . Entry < String , Object > entry = it . next ( ) ; queryString . append ( entry . getKey ( ) ) . append ( " " ) ; if ( entry . getValue ( ) != null ) { queryString . append ( entry . getValue ( ) ) ; } if ( it . hasNext ( ) ) { queryString . append ( ", " ) ; } } } return queryString . toString ( ) ; } | This method returns approapiate query clauses to be executed within a SQL statement . |
18,205 | public static Class < ? > getType ( String name , String library ) { try { if ( library != null && ! library . isEmpty ( ) ) { URL moduleUrl = new File ( library ) . toURI ( ) . toURL ( ) ; URLClassLoader child = new URLClassLoader ( new URL [ ] { moduleUrl } , ClassLoader . getSystemClassLoader ( ) ) ; return Class . forName ( name , true , child ) ; } else { return Class . forName ( name ) ; } } catch ( Exception ex ) { return null ; } } | Gets object type by its name and library where it is defined . |
18,206 | public static Class < ? > getTypeByDescriptor ( TypeDescriptor type ) { if ( type == null ) throw new NullPointerException ( "Type descriptor cannot be null" ) ; return getType ( type . getName ( ) , type . getLibrary ( ) ) ; } | Gets object type by type descriptor . |
18,207 | public static Object createInstanceByType ( Class < ? > type , Object ... args ) throws Exception { if ( args . length == 0 ) { Constructor < ? > constructor = type . getConstructor ( ) ; return constructor . newInstance ( ) ; } else { throw new UnsupportedException ( null , "NOT_SUPPORTED" , "Constructors with parameters are not supported" ) ; } } | Creates an instance of an object type . |
18,208 | public static Object createInstance ( String name , String library , Object ... args ) throws Exception { Class < ? > type = getType ( name , library ) ; if ( type == null ) throw new NotFoundException ( null , "TYPE_NOT_FOUND" , "Type " + name + "," + library + " was not found" ) . withDetails ( "type" , name ) . withDetails ( "library" , library ) ; return createInstanceByType ( type , args ) ; } | Creates an instance of an object type specified by its name and library where it is defined . |
18,209 | public static Object createInstance ( String name , Object ... args ) throws Exception { return createInstance ( name , ( String ) null , args ) ; } | Creates an instance of an object type specified by its name . |
18,210 | public static Object createInstanceByDescriptor ( TypeDescriptor type , Object ... args ) throws Exception { if ( type == null ) throw new NullPointerException ( "Type descriptor cannot be null" ) ; return createInstance ( type . getName ( ) , type . getLibrary ( ) , args ) ; } | Creates an instance of an object type specified by type descriptor . |
18,211 | public static boolean isPrimitive ( Object value ) { TypeCode typeCode = TypeConverter . toTypeCode ( value ) ; return typeCode == TypeCode . String || typeCode == TypeCode . Enum || typeCode == TypeCode . Boolean || typeCode == TypeCode . Integer || typeCode == TypeCode . Long || typeCode == TypeCode . Float || typeCode == TypeCode . Double || typeCode == TypeCode . DateTime || typeCode == TypeCode . Duration ; } | Checks if value has primitive type . |
18,212 | public String getCodeSample ( int position ) { StringBuffer buffer = new StringBuffer ( ) ; int startPosition = Math . max ( 0 , position - 10 ) ; if ( startPosition >= size ( ) ) { startPosition = 0 ; } int stopPosition = Math . min ( size ( ) - 1 , startPosition + 20 ) ; if ( startPosition > 0 ) { buffer . append ( "[...]" ) ; } for ( int i = startPosition ; i <= stopPosition ; i ++ ) { if ( i == position ) { buffer . append ( " >>> " ) ; } buffer . append ( get ( i ) . getText ( ) ) ; if ( i == position ) { buffer . append ( " <<< " ) ; } } if ( stopPosition < size ( ) - 1 ) { buffer . append ( "[...]" ) ; } return buffer . toString ( ) ; } | This method prepares a code sample out of a position defined by parameter position . This code sample marks the position and prints code around it . |
18,213 | public void doFilter ( final ServletRequest servletRequest , final ServletResponse servletResponse , final FilterChain filterChain ) throws IOException , ServletException { ServletRequest request = servletRequest ; ServletResponse response = servletResponse ; int id = 0 ; if ( LOG_REQUEST . isDebugEnabled ( ) || LOG_RESPONSE . isDebugEnabled ( ) ) { id = counter . incrementAndGet ( ) ; } if ( LOG_REQUEST . isDebugEnabled ( ) ) { request = new HttpServletRequestLoggingWrapper ( ( HttpServletRequest ) servletRequest , maxDumpSizeInKB ) ; dumpRequest ( ( HttpServletRequestLoggingWrapper ) request , id ) ; } if ( LOG_RESPONSE . isDebugEnabled ( ) ) { response = new HttpServletResponseLoggingWrapper ( ( HttpServletResponse ) servletResponse , maxDumpSizeInKB ) ; filterChain . doFilter ( request , response ) ; dumpResponse ( ( HttpServletResponseLoggingWrapper ) response , id ) ; } else { filterChain . doFilter ( request , response ) ; } } | This is where the work is done . |
18,214 | private void dumpResponse ( final HttpServletResponseLoggingWrapper response , final int id ) { final StringWriter stringWriter = new StringWriter ( ) ; final PrintWriter printWriter = new PrintWriter ( stringWriter ) ; printWriter . print ( "-- ID: " ) ; printWriter . println ( id ) ; printWriter . println ( response . getStatusCode ( ) ) ; if ( LOG_HEADERS . isDebugEnabled ( ) ) { final Map < String , List < String > > headers = response . headers ; for ( Map . Entry < String , List < String > > header : headers . entrySet ( ) ) { printWriter . print ( header . getKey ( ) ) ; printWriter . print ( ": " ) ; Iterator < String > values = header . getValue ( ) . iterator ( ) ; while ( values . hasNext ( ) ) { printWriter . print ( values . next ( ) ) ; printWriter . println ( ) ; if ( values . hasNext ( ) ) { printWriter . print ( ' ' ) ; } } } } printWriter . println ( "-- Begin response body" ) ; final String body = response . getContentAsInputString ( ) ; if ( body == null || body . length ( ) == 0 ) { printWriter . println ( "-- NO BODY WRITTEN IN RESPONSE" ) ; } else { printWriter . println ( body ) ; } printWriter . println ( ) ; printWriter . println ( "-- End response body" ) ; printWriter . flush ( ) ; LOG_RESPONSE . debug ( stringWriter . toString ( ) ) ; } | This method handles the dumping of the reponse body status code and headers if needed |
18,215 | private void dumpRequest ( final HttpServletRequestLoggingWrapper request , final int id ) { final StringWriter stringWriter = new StringWriter ( ) ; final PrintWriter printWriter = new PrintWriter ( stringWriter ) ; if ( ( request . getRemoteUser ( ) == null ) || ( request . getRemoteUser ( ) . trim ( ) . length ( ) == 0 ) ) { printWriter . print ( "Not authenticated" ) ; } else { printWriter . print ( "Authenticated as " ) ; printWriter . println ( request . getRemoteUser ( ) ) ; } printWriter . print ( "-- ID: " ) ; printWriter . println ( id ) ; printWriter . print ( request . getMethod ( ) ) ; printWriter . print ( " " ) ; printWriter . print ( request . getRequestURL ( ) ) ; printWriter . print ( " " ) ; printWriter . println ( request . getProtocol ( ) ) ; if ( LOG_HEADERS . isDebugEnabled ( ) ) { @ SuppressWarnings ( "unchecked" ) final Enumeration < String > headerNames = request . getHeaderNames ( ) ; while ( headerNames . hasMoreElements ( ) ) { final String key = headerNames . nextElement ( ) ; @ SuppressWarnings ( "unchecked" ) final Enumeration < String > headerValues = request . getHeaders ( key ) ; printWriter . print ( key ) ; printWriter . print ( ": " ) ; while ( headerValues . hasMoreElements ( ) ) { printWriter . print ( headerValues . nextElement ( ) ) ; printWriter . println ( ) ; if ( headerValues . hasMoreElements ( ) ) { printWriter . print ( ' ' ) ; } } } } printWriter . println ( "-- Begin request body" ) ; final String body = request . getBody ( ) ; if ( body == null || body . length ( ) == 0 ) { printWriter . println ( "-- NO BODY FOUND IN REQUEST" ) ; } else { printWriter . println ( body ) ; } printWriter . println ( "-- End request body" ) ; printWriter . flush ( ) ; LOG_REQUEST . debug ( stringWriter . toString ( ) ) ; } | This method handles the dumping of the request body method URL and headers if needed |
18,216 | public boolean isValidAddress ( NetworkParameters network ) { byte version = getVersion ( ) ; if ( getAllAddressBytes ( ) . length != 21 ) { return false ; } return ( ( byte ) ( network . getStandardAddressHeader ( ) & 0xFF ) ) == version || ( ( byte ) ( network . getMultisigAddressHeader ( ) & 0xFF ) ) == version ; } | Validate that an address is a valid address on the specified network |
18,217 | public static < T > List < T > filter ( Collection < T > items , Predicate < T > predicate ) { List < T > result = new ArrayList < > ( ) ; if ( ! isEmpty ( items ) ) { for ( T item : items ) { if ( predicate . apply ( item ) ) { result . add ( item ) ; } } } return result ; } | Filters a collection using the given predicate . |
18,218 | public static < T > T firstOrNull ( Collection < T > items , Predicate < T > predicate ) { if ( ! isEmpty ( items ) ) { for ( T item : items ) { if ( predicate . apply ( item ) ) { return item ; } } } return null ; } | Returns the first element from a collection that matches the given predicate or null if no matching element is found . |
18,219 | public static < T > int count ( Collection < T > items , Predicate < T > predicate ) { int count = 0 ; if ( ! isEmpty ( items ) ) { for ( T element : items ) { if ( predicate . apply ( element ) ) { count ++ ; } } } return count ; } | Returns the number of elements in a collection matching the given predicate . |
18,220 | public static < TSource , TResult > List < TResult > map ( Collection < TSource > items , Mapper < TSource , TResult > mapper ) { if ( isEmpty ( items ) ) { return new ArrayList < > ( ) ; } List < TResult > result = new ArrayList < > ( items . size ( ) ) ; for ( TSource item : items ) { TResult mappedItem = mapper . map ( item ) ; result . add ( mappedItem ) ; } return result ; } | Projects each element of a collection into a new collection . |
18,221 | public static byte [ ] decodeChecked ( String input ) { byte tmp [ ] = decode ( input ) ; if ( tmp == null || tmp . length < 4 ) { return null ; } byte [ ] bytes = copyOfRange ( tmp , 0 , tmp . length - 4 ) ; byte [ ] checksum = copyOfRange ( tmp , tmp . length - 4 , tmp . length ) ; tmp = HashUtils . doubleSha256 ( bytes ) ; byte [ ] hash = copyOfRange ( tmp , 0 , 4 ) ; if ( ! Arrays . equals ( checksum , hash ) ) { return null ; } return bytes ; } | Uses the checksum in the last 4 bytes of the decoded data to verify the rest are correct . The checksum is removed from the returned data . |
18,222 | public static String getFieldNameWithJavaCase ( final String name ) { return name == null ? null : Character . toLowerCase ( name . charAt ( 0 ) ) + name . substring ( 1 ) ; } | Make the first character lower case and leave the rest alone . |
18,223 | private void convert ( ) throws GrammarException , TreeException { convertOptions ( ) ; convertTokenDefinitions ( ) ; convertProductions ( ) ; grammar = new Grammar ( options , tokenDefinitions , productions ) ; } | This method converts the read AST from grammar file into a final grammar ready to be used . |
18,224 | private void convertOptions ( ) throws TreeException { options = new Properties ( ) ; ParseTreeNode optionList = parserTree . getChild ( "GrammarOptions" ) . getChild ( "GrammarOptionList" ) ; for ( ParseTreeNode option : optionList . getChildren ( "GrammarOption" ) ) { String name = option . getChild ( "PropertyIdentifier" ) . getText ( ) ; String value = option . getChild ( "Literal" ) . getText ( ) ; if ( value . startsWith ( "'" ) || value . startsWith ( "\"" ) ) { value = value . substring ( 1 , value . length ( ) - 1 ) ; } options . put ( name , value ) ; } } | This method converts the options part of the AST . |
18,225 | private void convertTokenDefinitions ( ) throws GrammarException , TreeException { tokenVisibility . clear ( ) ; Map < String , ParseTreeNode > helpers = getHelperTokens ( ) ; Map < String , ParseTreeNode > tokens = getTokens ( ) ; convertTokenDefinitions ( helpers , tokens ) ; } | This method converts the token definitions to the token definition set . |
18,226 | private Map < String , ParseTreeNode > getHelperTokens ( ) throws TreeException { Map < String , ParseTreeNode > helpers = new HashMap < String , ParseTreeNode > ( ) ; ParseTreeNode helperTree = parserTree . getChild ( "Helper" ) ; ParseTreeNode helperDefinitions = helperTree . getChild ( "HelperDefinitions" ) ; for ( ParseTreeNode helperDefinition : helperDefinitions . getChildren ( "HelperDefinition" ) ) { String identifier = helperDefinition . getChild ( "IDENTIFIER" ) . getText ( ) ; helpers . put ( identifier , helperDefinition ) ; } return helpers ; } | This method reads all helpers from AST and returns a map with all of them . |
18,227 | private Map < String , ParseTreeNode > getTokens ( ) throws GrammarException , TreeException { Map < String , ParseTreeNode > tokens = new HashMap < String , ParseTreeNode > ( ) ; ParseTreeNode tokensTree = parserTree . getChild ( "Tokens" ) ; ParseTreeNode tokenDefinitions = tokensTree . getChild ( "TokenDefinitions" ) ; for ( ParseTreeNode tokenDefinition : tokenDefinitions . getChildren ( "TokenDefinition" ) ) { String identifier = tokenDefinition . getChild ( "IDENTIFIER" ) . getText ( ) ; tokens . put ( identifier , tokenDefinition ) ; ParseTreeNode visibilityAST = tokenDefinition . getChild ( "Visibility" ) ; if ( visibilityAST . hasChild ( "HIDE" ) ) { tokenVisibility . put ( identifier , Visibility . HIDDEN ) ; } else if ( visibilityAST . hasChild ( "IGNORE" ) ) { tokenVisibility . put ( identifier , Visibility . IGNORED ) ; } else { tokenVisibility . put ( identifier , Visibility . VISIBLE ) ; } } return tokens ; } | This method reads all tokens from AST and returns a map with all of them . |
18,228 | private void convertTokenDefinitions ( Map < String , ParseTreeNode > helpers , Map < String , ParseTreeNode > tokens ) throws GrammarException , TreeException { tokenDefinitions = new TokenDefinitionSet ( ) ; for ( ParseTreeNode tokenDefinitionAST : parserTree . getChild ( "Tokens" ) . getChild ( "TokenDefinitions" ) . getChildren ( "TokenDefinition" ) ) { TokenDefinition convertedTokenDefinition = getTokenDefinition ( tokenDefinitionAST , helpers , tokens ) ; tokenDefinitions . addDefinition ( convertedTokenDefinition ) ; } } | This method starts and controls the process for final conversion of all tokens from the token and helper skeletons . |
18,229 | private TokenDefinition getTokenDefinition ( ParseTreeNode tokenDefinition , Map < String , ParseTreeNode > helpers , Map < String , ParseTreeNode > tokens ) throws GrammarException , TreeException { String tokenName = tokenDefinition . getChild ( "IDENTIFIER" ) . getText ( ) ; String pattern = createTokenDefinitionPattern ( tokenDefinition , helpers , tokens ) ; boolean ignoreCase = Boolean . valueOf ( ( String ) options . get ( "grammar.ignore-case" ) ) ; if ( tokenVisibility . get ( tokenName ) != null ) { return new TokenDefinition ( tokenName , pattern , tokenVisibility . get ( tokenName ) , ignoreCase ) ; } else { return new TokenDefinition ( tokenName , pattern , ignoreCase ) ; } } | This is the method which merges all tokens with their helpers . |
18,230 | private void convertProductions ( ) throws TreeException , GrammarException { productions = new ProductionSet ( ) ; ParseTreeNode productionsTree = parserTree . getChild ( "Productions" ) ; ParseTreeNode productionDefinitions = productionsTree . getChild ( "ProductionDefinitions" ) ; for ( ParseTreeNode productionDefinition : productionDefinitions . getChildren ( "ProductionDefinition" ) ) { convertProductionGroup ( productionDefinition ) ; } } | This method converts all productions from the AST into a ProductionSet . |
18,231 | private void convertSingleProductions ( String productionName , ParseTreeNode productionConstructions ) throws TreeException , GrammarException { for ( ParseTreeNode productionConstruction : productionConstructions . getChildren ( "ProductionConstruction" ) ) { convertSingleProduction ( productionName , productionConstruction ) ; } } | This method converts the list of productions from a group with a given name into a set of productions . |
18,232 | private void convertSingleProduction ( String productionName , ParseTreeNode productionConstruction ) throws TreeException , GrammarException { ParseTreeNode alternativeIdentifier = productionConstruction . getChild ( "AlternativeIdentifier" ) ; Production production ; if ( alternativeIdentifier == null ) { production = new Production ( productionName ) ; } else { ParseTreeNode alternativeIdentifierName = alternativeIdentifier . getChild ( "IDENTIFIER" ) ; if ( alternativeIdentifierName == null ) { production = new Production ( productionName ) ; } else { production = new Production ( productionName , alternativeIdentifierName . getText ( ) ) ; } } production . addAllConstructions ( getConstructions ( productionConstruction ) ) ; addOptions ( production , productionConstruction ) ; productions . add ( production ) ; } | This method converts a single production from a list of productions within a production group into a single production . Some additional productions might be created during the way due to construction grouping and quantifiers . |
18,233 | private String createNewIdentifier ( ParseTreeNode productionPart , String suffix ) throws TreeException { String identifier = "" ; if ( productionPart . hasChild ( "IDENTIFIER" ) ) { identifier = productionPart . getChild ( "IDENTIFIER" ) . getText ( ) ; } else if ( productionPart . hasChild ( "STRING_LITERAL" ) ) { identifier = productionPart . getChild ( "STRING_LITERAL" ) . getText ( ) ; } return createIdentifierName ( identifier , suffix ) ; } | This method generates a new construction identifier for an automatically generated BNF production for optionals optional lists and lists . |
18,234 | private String determineFileName ( final Matcher matcher ) { String fileName ; if ( StringUtils . isNotBlank ( matcher . group ( 3 ) ) ) { fileName = matcher . group ( 3 ) ; } else if ( StringUtils . isNotBlank ( matcher . group ( 7 ) ) ) { fileName = matcher . group ( 7 ) ; } else { fileName = matcher . group ( 1 ) ; } if ( StringUtils . isBlank ( fileName ) ) { fileName = StringUtils . substringBetween ( matcher . group ( 6 ) , "'" ) ; } if ( StringUtils . isBlank ( fileName ) ) { fileName = "unknown.file" ; } return fileName ; } | Determines the name of the file that is cause of the warning . |
18,235 | private Priority determinePriority ( final Matcher matcher ) { if ( isOfType ( matcher , "note" ) || isOfType ( matcher , "info" ) ) { return Priority . LOW ; } else if ( isOfType ( matcher , "warning" ) ) { return Priority . NORMAL ; } return Priority . HIGH ; } | Determines the priority of the warning . |
18,236 | private boolean isOfType ( final Matcher matcher , final String type ) { return StringUtils . containsIgnoreCase ( matcher . group ( 4 ) , type ) ; } | Returns whether the warning type is of the specified type . |
18,237 | public static ZonedDateTime toNullableDateTime ( Object value ) { if ( value == null ) return null ; if ( value instanceof ZonedDateTime ) return ( ZonedDateTime ) value ; if ( value instanceof Calendar ) { Calendar calendar = ( Calendar ) value ; return ZonedDateTime . ofInstant ( calendar . toInstant ( ) , calendar . getTimeZone ( ) . toZoneId ( ) ) ; } if ( value instanceof Date ) return ZonedDateTime . ofInstant ( ( ( Date ) value ) . toInstant ( ) , ZoneId . systemDefault ( ) ) ; if ( value instanceof LocalDate ) return ZonedDateTime . of ( ( LocalDate ) value , LocalTime . of ( 0 , 0 ) , ZoneId . systemDefault ( ) ) ; if ( value instanceof LocalDateTime ) return ZonedDateTime . of ( ( LocalDateTime ) value , ZoneId . systemDefault ( ) ) ; if ( value instanceof Integer ) return millisToDateTime ( ( int ) value ) ; if ( value instanceof Short ) return millisToDateTime ( ( short ) value ) ; if ( value instanceof Long ) return millisToDateTime ( ( long ) value ) ; if ( value instanceof Float ) return millisToDateTime ( ( long ) ( ( float ) value ) ) ; if ( value instanceof Double ) return millisToDateTime ( ( long ) ( ( double ) value ) ) ; if ( value instanceof Duration ) return millisToDateTime ( ( ( Duration ) value ) . toMillis ( ) ) ; if ( value instanceof String ) { try { return ZonedDateTime . parse ( ( String ) value , DateTimeFormatter . ISO_OFFSET_DATE_TIME ) ; } catch ( DateTimeParseException ex ) { } try { return ZonedDateTime . of ( LocalDateTime . parse ( ( String ) value , simpleDateTimeFormatter ) , ZoneId . systemDefault ( ) ) ; } catch ( DateTimeParseException ex ) { } try { return ZonedDateTime . of ( LocalDate . parse ( ( String ) value , simpleDateFormatter ) , LocalTime . of ( 0 , 0 ) , ZoneId . systemDefault ( ) ) ; } catch ( DateTimeParseException ex ) { } } return null ; } | Converts value into Date or returns null when conversion is not possible . |
18,238 | public static ZonedDateTime toDateTimeWithDefault ( Object value , ZonedDateTime defaultValue ) { ZonedDateTime result = toNullableDateTime ( value ) ; return result != null ? result : defaultValue ; } | Converts value into Date or returns default when conversion is not possible . |
18,239 | protected long getUpperBound ( TrieNode currentParent , AtomicLong currentChildren , TrieNode godchildNode , int godchildAdjustment ) { return Math . min ( currentParent . getCursorCount ( ) - currentChildren . get ( ) , godchildNode . getCursorCount ( ) - godchildAdjustment ) ; } | Gets upper bound . |
18,240 | public static double dot ( final List < double [ ] > a , final List < double [ ] > b ) { return com . simiacryptus . util . ArrayUtil . sum ( com . simiacryptus . util . ArrayUtil . multiply ( a , b ) ) ; } | Dot double . |
18,241 | public static double magnitude ( final double [ ] a ) { return Math . sqrt ( com . simiacryptus . util . ArrayUtil . dot ( a , a ) ) ; } | Magnitude double . |
18,242 | public static double mean ( final double [ ] op ) { return com . simiacryptus . util . ArrayUtil . sum ( op ) / op . length ; } | Mean double . |
18,243 | public static double sum ( final List < double [ ] > a ) { return a . stream ( ) . parallel ( ) . mapToDouble ( x -> Arrays . stream ( x ) . sum ( ) ) . sum ( ) ; } | Sum double . |
18,244 | public static String generateAccessKeyId ( ) { final char [ ] accessKeyId = new char [ ACCESS_KEY_ID_LENGTH ] ; for ( int i = 0 ; i < accessKeyId . length ; i ++ ) { accessKeyId [ i ] = SYMBOLS [ SECURE_RANDOM . nextInt ( SYMBOLS . length ) ] ; } return new String ( accessKeyId ) ; } | Generates a 25 length String access key id |
18,245 | public static String generateSecretAccessKey ( ) { final byte [ ] secretAccessKeyBytes = new byte [ 30 ] ; SECURE_RANDOM . nextBytes ( secretAccessKeyBytes ) ; return StringUtils . chomp ( Base64 . encodeBase64String ( secretAccessKeyBytes ) ) ; } | Generates a 40 length String secret access key |
18,246 | private String getRuleName ( RulesTextProvider textProvider ) { if ( ! quotedString ( '"' , textProvider ) ) { return "R" + ( textProvider . incrementRuleCount ( ) ) ; } return textProvider . getLastToken ( ) ; } | Method getRuleName . The rule name is normally enclosed in quotes but it might be omitted in which case we generate a unique one . |
18,247 | private AbstractRule processFormula ( RulesTextProvider textProvider ) { log . debug ( "processFormula" ) ; Formula rule = new Formula ( ) ; int start = textProvider . getPos ( ) ; LoadCommonRuleData ( rule , textProvider ) ; textProvider . addTOCElement ( null , rule . getDescription ( ) , start , textProvider . getPos ( ) , TYPE_FORMULA ) ; exactOrError ( "{" , textProvider ) ; Expression expression = processAction ( textProvider ) ; exactOrError ( "}" , textProvider ) ; rule . addAction ( expression ) ; return rule ; } | Method processFormula . Parse a formula which is just one action expression followed by a semicolon . |
18,248 | private AbstractRule processConstraint ( RulesTextProvider textProvider ) throws ParserException { log . debug ( "processConstraint" ) ; Constraint rule = new Constraint ( ) ; int start = textProvider . getPos ( ) ; LoadCommonRuleData ( rule , textProvider ) ; textProvider . addTOCElement ( null , rule . getDescription ( ) , start , textProvider . getPos ( ) , TYPE_CONSTRAINT ) ; exactOrError ( "{" , textProvider ) ; Expression condition = processAction ( textProvider ) ; if ( condition . isAssign ( ) ) { throw new ParserException ( "Found an assignment in a condition " , textProvider ) ; } exactOrError ( "}" , textProvider ) ; rule . addCondition ( condition ) ; return rule ; } | Method processConstraint . A constraint is a list of conditions and an explanation . |
18,249 | private List < ClassReference > getClassReferences ( String className ) { List < ClassReference > ret = new ArrayList < ClassReference > ( ) ; ClassReference cr = m_classReferenceMap . get ( className ) ; ret . addAll ( cr . getChildren ( ) ) ; return ret ; } | Figure out which classes extend the named class and return the current class and the extenders |
18,250 | public FieldMetadata getEmptyField ( FieldMetadata fieldMetadata ) { ValidationSession session = fieldMetadata . getValidationSession ( ) ; RuleSessionImpl ruleSession = getRuleSession ( session ) ; ProxyField proxyField = session . getProxyField ( fieldMetadata ) ; RuleProxyField ruleProxyField = ruleSession . getRuleProxyField ( proxyField ) ; while ( true ) { RuleProxyField rpf = ruleProxyField . backChain ( ) ; if ( rpf == null ) { return null ; } else { return rpf . getProxyField ( ) . getFieldMetadata ( ) ; } } } | Find an empty field ie one that is unknown and not not known If we don t find one then return null . |
18,251 | public void clearUnknowns ( ValidationObject object ) { ObjectMetadata objectMetadata = object . getMetadata ( ) ; ValidationSession session = object . getMetadata ( ) . getProxyObject ( ) . getSession ( ) ; session . setEnabled ( false ) ; Map < String , ProxyField > fieldMap = objectMetadata . getProxyObject ( ) . getFieldMap ( ) ; for ( Map . Entry < String , ProxyField > entry : fieldMap . entrySet ( ) ) { FieldMetadata fieldMetadata = entry . getValue ( ) . getFieldMetadata ( ) ; ProxyFieldImpl proxyField = ( ProxyFieldImpl ) session . getProxyField ( fieldMetadata ) ; if ( proxyField . getPropertyMetadata ( ) . isUnknown ( ) ) { proxyField . reset ( ) ; proxyField . setValue ( null ) ; proxyField . updateValue ( ) ; proxyField . setUnknown ( true ) ; logger . debug ( "Cleared {}" , proxyField . toString ( ) ) ; } } session . setEnabled ( true ) ; } | Clear all the fields that were originally flagged as unknown on this object we should assume the dynamic flag has been removed and we need to reset it . Also set the current value of each to null ie we lose any data from the unknown fields for this object . Because you only do this one object at a time there may be problems if the unknowns use rules that cross multiple objects . |
18,252 | protected Object readResolve ( ) { super . readResolve ( ) ; if ( consoleParsers == null ) { consoleParsers = Lists . newArrayList ( ) ; if ( isOlderThanRelease318 ( ) ) { upgradeFrom318 ( ) ; } for ( String parser : consoleLogParsers ) { consoleParsers . add ( new ConsoleParser ( parser ) ) ; } } return this ; } | Upgrade for release 4 . 5 or older . |
18,253 | public Schema withRule ( IValidationRule rule ) { _rules = _rules != null ? _rules : new ArrayList < IValidationRule > ( ) ; _rules . add ( rule ) ; return this ; } | Adds validation rule to this schema . |
18,254 | protected void performTypeValidation ( String path , Object type , Object value , List < ValidationResult > results ) { if ( type == null ) return ; if ( type instanceof Schema ) { Schema schema = ( Schema ) type ; schema . performValidation ( path , value , results ) ; return ; } value = ObjectReader . getValue ( value ) ; if ( value == null ) return ; String name = path != null ? path : "value" ; Class < ? > valueType = value . getClass ( ) ; if ( TypeMatcher . matchType ( type , valueType ) ) return ; results . add ( new ValidationResult ( path , ValidationResultType . Error , "TYPE_MISMATCH" , name + " type must be " + type + " but found " + valueType , type , valueType ) ) ; } | Validates a given value to match specified type . The type can be defined as a Schema type a type name or TypeCode When type is a Schema it executes validation recursively against that Schema . |
18,255 | public List < ValidationResult > validate ( Object value ) { List < ValidationResult > results = new ArrayList < ValidationResult > ( ) ; performValidation ( "" , value , results ) ; return results ; } | Validates the given value and results validation results . |
18,256 | public void validateAndThrowException ( String correlationId , Object value , boolean strict ) throws ValidationException { List < ValidationResult > results = validate ( value ) ; ValidationException . throwExceptionIfNeeded ( correlationId , results , strict ) ; } | Validates the given value and returns a ValidationException if errors were found . |
18,257 | public void validateAndThrowException ( String correlationId , Object value ) throws ValidationException { validateAndThrowException ( correlationId , value , false ) ; } | Validates the given value and throws a ValidationException if errors were found . |
18,258 | public static ErrorDescription create ( ApplicationException ex ) { ErrorDescription description = new ErrorDescription ( ) ; description . setCategory ( ex . getCategory ( ) ) ; description . setStatus ( ex . getStatus ( ) ) ; description . setCode ( ex . getCode ( ) ) ; description . setMessage ( ex . getMessage ( ) ) ; description . setDetails ( ex . getDetails ( ) ) ; description . setCorrelationId ( ex . getCorrelationId ( ) ) ; description . setCause ( ex . getCauseString ( ) ) ; description . setStackTrace ( ex . getStackTraceString ( ) ) ; return description ; } | Creates a serializable ErrorDescription from error object . |
18,259 | public static ErrorDescription create ( Throwable ex , String correlationId ) { ErrorDescription description = new ErrorDescription ( ) ; description . setType ( ex . getClass ( ) . getCanonicalName ( ) ) ; description . setCategory ( ErrorCategory . Unknown ) ; description . setStatus ( 500 ) ; description . setCode ( "Unknown" ) ; description . setMessage ( ex . getMessage ( ) ) ; Throwable t = ex . getCause ( ) ; description . setCause ( t != null ? t . toString ( ) : null ) ; StackTraceElement [ ] ste = ex . getStackTrace ( ) ; StringBuilder builder = new StringBuilder ( ) ; if ( ste != null ) { for ( int i = 0 ; i < ste . length ; i ++ ) { if ( builder . length ( ) > 0 ) builder . append ( " " ) ; builder . append ( ste [ i ] . toString ( ) ) ; } } description . setStackTrace ( builder . toString ( ) ) ; description . setCorrelationId ( correlationId ) ; return description ; } | Creates a serializable ErrorDescription from throwable object with unknown error category . |
18,260 | public void close ( ) { if ( inputStream == null ) { return ; } try { inputStream . close ( ) ; } catch ( Exception e ) { listener . exceptionThrown ( e ) ; } } | Close the input stream of xml data . |
18,261 | @ SuppressWarnings ( "nls" ) public Object readObject ( ) { if ( inputStream == null ) { return null ; } if ( saxHandler == null ) { saxHandler = new SAXHandler ( ) ; try { SAXParserFactory . newInstance ( ) . newSAXParser ( ) . parse ( inputStream , saxHandler ) ; } catch ( Exception e ) { this . listener . exceptionThrown ( e ) ; } } if ( readObjIndex >= readObjs . size ( ) ) { throw new ArrayIndexOutOfBoundsException ( Messages . getString ( "beans.70" ) ) ; } Elem elem = readObjs . get ( readObjIndex ) ; if ( ! elem . isClosed ) { throw new ArrayIndexOutOfBoundsException ( Messages . getString ( "beans.70" ) ) ; } readObjIndex ++ ; return elem . result ; } | Reads the next object . |
18,262 | public V get ( Map < ? , V > map ) { for ( Object k : keys ) { V v = map . get ( k ) ; if ( v != null ) { return v ; } } return null ; } | Get the first matching value in the map . |
18,263 | public MethodVisitor visitMethod ( int access , String name , String desc , String signature , String [ ] exceptions ) { MethodVisitor mv = cv . visitMethod ( access | Opcodes . ACC_SYNTHETIC , name , desc , signature , exceptions ) ; return new AccessMethodAdapter ( mv ) ; } | Visits the specified method fixing method calls . |
18,264 | static public TimePeriod from ( String quantityAndUnit ) { String trimed = quantityAndUnit . trim ( ) ; String allExceptLast = trimed . substring ( 0 , trimed . length ( ) - 1 ) ; if ( StringUtils . isNumericSpace ( allExceptLast ) ) { long quantity = Long . parseLong ( allExceptLast . trim ( ) ) ; TimePeriodUnit unit = TimePeriodUnit . from ( Character . toUpperCase ( trimed . charAt ( trimed . length ( ) - 1 ) ) ) ; return new TimePeriod ( quantity , unit ) ; } else { String [ ] durationAndUnit = StringUtils . split ( trimed ) ; Long duration = Long . valueOf ( durationAndUnit [ 0 ] ) ; TimePeriodUnit unit = TimePeriodUnit . from ( durationAndUnit [ 1 ] ) ; return new TimePeriod ( duration , unit ) ; } } | Parse strings like 1 hour 2 days 3 Years 12 minute into TimePeriod . Short formats like 1H 2 D 3y are also supported . |
18,265 | protected Class resolveClass ( ObjectStreamClass classDesc ) throws IOException , ClassNotFoundException { for ( ClassLoader loader : classLoaderRegistration ) { try { return resolveClass ( classDesc , loader ) ; } catch ( ClassNotFoundException e ) { } } return super . resolveClass ( classDesc ) ; } | Use the registered ClassLoaders to resolve and then use system class loader |
18,266 | protected static final boolean classEquals ( Class clz1 , Class clz2 ) { if ( clz1 == null || clz2 == null ) { throw new NullPointerException ( ) ; } return clz1 == clz2 || clz1 . getName ( ) . equals ( clz2 . getName ( ) ) ; } | Compares if two classes are equal or their class names are equal . |
18,267 | @ SuppressWarnings ( "unchecked" ) public Object [ ] toArray ( Object [ ] array ) { synchronized ( children ) { return children . keySet ( ) . toArray ( array ) ; } } | Returns an array of children of this context . |
18,268 | public com . simiacryptus . util . data . DensityTree setMinSplitFract ( double minSplitFract ) { this . minSplitFract = minSplitFract ; return this ; } | Sets min split fract . |
18,269 | public com . simiacryptus . util . data . DensityTree setSplitSizeThreshold ( int splitSizeThreshold ) { this . splitSizeThreshold = splitSizeThreshold ; return this ; } | Sets split size threshold . |
18,270 | public com . simiacryptus . util . data . DensityTree setMinFitness ( double minFitness ) { this . minFitness = minFitness ; return this ; } | Sets min fitness . |
18,271 | public com . simiacryptus . util . data . DensityTree setMaxDepth ( int maxDepth ) { this . maxDepth = maxDepth ; return this ; } | Sets max depth . |
18,272 | public WordNumberCollectorBundle addWord ( String key , String word ) { wordCollector . add ( key , word ) ; return this ; } | Add word word number collector bundle . |
18,273 | public WordNumberCollectorBundle addWordList ( String key , List < String > wordList ) { wordCollector . addAll ( key , wordList ) ; return this ; } | Add word list word number collector bundle . |
18,274 | public WordNumberCollectorBundle addNumber ( String key , Number number ) { numberCollector . add ( key , number ) ; return this ; } | Add number word number collector bundle . |
18,275 | public WordNumberCollectorBundle addNumberList ( String key , List < Number > numberList ) { numberCollector . addAll ( key , numberList ) ; return this ; } | Add number list word number collector bundle . |
18,276 | public WordNumberCollectorBundle addData ( String key , String data ) { if ( JMString . isNumber ( data ) ) addNumber ( key , Double . valueOf ( data ) ) ; else addWord ( key , data ) ; return this ; } | Add data word number collector bundle . |
18,277 | public WordNumberCollectorBundle merge ( WordNumberCollectorBundle wordNumberCollector ) { wordCollector . merge ( wordNumberCollector . wordCollector ) ; numberCollector . merge ( wordNumberCollector . numberCollector ) ; return this ; } | Merge word number collector bundle . |
18,278 | public List < E > list ( int first , int max , String sortProperty , boolean ascending ) { Criteria c = createCriteria ( ) . setMaxResults ( max ) . setFirstResult ( first ) ; final int ndx = sortProperty . lastIndexOf ( '.' ) ; if ( ndx != - 1 ) { final String associationPath = sortProperty . substring ( 0 , ndx ) ; final String propertyName = sortProperty . substring ( ndx + 1 ) ; c = c . createAlias ( associationPath , ASSOCIATION_ALIAS ) . addOrder ( ascending ? Order . asc ( ASSOCIATION_ALIAS + "." + propertyName ) : Order . desc ( ASSOCIATION_ALIAS + "." + propertyName ) ) ; } else { c = c . addOrder ( ascending ? Order . asc ( sortProperty ) : Order . desc ( sortProperty ) ) ; } return list ( c ) ; } | Returns one page of data from this repository . |
18,279 | @ SuppressWarnings ( UNCHECKED ) protected List < E > list ( Criteria criteria ) { return new ArrayList < E > ( criteria . list ( ) ) ; } | Returns a list of entities based on the provided criteria . |
18,280 | @ SuppressWarnings ( UNCHECKED ) protected List < E > list ( Query query ) { return new ArrayList < E > ( query . list ( ) ) ; } | Returns a list of entities based on the provided query . |
18,281 | @ SuppressWarnings ( UNCHECKED ) protected Set < E > set ( Criteria criteria ) { return new HashSet < E > ( criteria . list ( ) ) ; } | Returns a set of entities based on the provided criteria . |
18,282 | @ SuppressWarnings ( UNCHECKED ) protected Set < E > set ( Query query ) { return new HashSet < E > ( query . list ( ) ) ; } | Returns a set of entities based on the provided query . |
18,283 | protected final int getLineNumber ( final String lineNumber ) { if ( StringUtils . isNotBlank ( lineNumber ) ) { try { return Integer . parseInt ( lineNumber ) ; } catch ( NumberFormatException exception ) { } } return 0 ; } | Converts a string line number to an integer value . If the string is not a valid line number then 0 is returned which indicates a warning at the top of the file . |
18,284 | public ServiceInstance vote ( List < ServiceInstance > instances ) { if ( instances . isEmpty ( ) ) { return null ; } int i = index . getAndIncrement ( ) ; int pos = i % instances . size ( ) ; ServiceInstance instance = instances . get ( pos ) ; return instance ; } | Vote a ServiceInstance based on the RoundRobin LoadBalancer algorithm . |
18,285 | public long getUInt32 ( ) throws InsufficientBytesException { checkAvailable ( 4 ) ; byte [ ] intBytes = getBytes ( 4 ) ; return byteAsULong ( intBytes [ 0 ] ) | ( byteAsULong ( intBytes [ 1 ] ) << 8 ) | ( byteAsULong ( intBytes [ 2 ] ) << 16 ) | ( byteAsULong ( intBytes [ 3 ] ) << 24 ) ; } | Gets a java long type from 4 bytes of data representing 32 - bit unsigned integer |
18,286 | private Set < TokenDefinition > extractHiddenAndIgnoredTokensFromGrammar ( ) { Set < TokenDefinition > hiddenAndIgnoredTokens = new LinkedHashSet < TokenDefinition > ( ) ; for ( TokenDefinition tokenDefinition : grammar . getTokenDefinitions ( ) . getDefinitions ( ) ) { Visibility visibility = tokenDefinition . getVisibility ( ) ; if ( ( visibility == Visibility . HIDDEN ) || ( visibility == Visibility . IGNORED ) ) { hiddenAndIgnoredTokens . add ( tokenDefinition ) ; } } return hiddenAndIgnoredTokens ; } | This method extracts all token definitions which are to be ignored or hidden to process them separately and to put them into special locations into the parser tree . |
18,287 | private void initialize ( SourceCode sourceCode ) { this . sourceCode = sourceCode ; textWithSource = new StringWithLocation ( sourceCode ) ; text = textWithSource . getText ( ) ; memo . clear ( ) ; ruleInvocationStack = null ; maxPosition = 0 ; } | This method resets the whole parser and sets the new values for text and name to start the parsing process afterwards . |
18,288 | public ParseTreeNode parse ( SourceCode sourceCode , String production ) throws ParserException { try { initialize ( sourceCode ) ; MemoEntry progress = applyRule ( production , 0 , 1 ) ; if ( progress . getDeltaPosition ( ) != text . length ( ) ) { throw new ParserException ( getParserErrorMessage ( ) ) ; } Object answer = progress . getAnswer ( ) ; if ( answer instanceof Status ) { Status status = ( Status ) answer ; switch ( status ) { case FAILED : throw new ParserException ( "Parser returned status 'FAILED'." ) ; default : throw new RuntimeException ( "A status '" + status . toString ( ) + "' is not expected here." ) ; } } ParseTreeNode parserTree = ( ParseTreeNode ) answer ; normalizeParents ( parserTree ) ; return parserTree ; } catch ( TreeException e ) { throw new ParserException ( e ) ; } } | This is the actual parser start . After running the parse a check is applied to check for full parsing or partial parsing . If partial parsing is found an exception is thrown . |
18,289 | private String getParserErrorMessage ( ) { StringBuffer code = new StringBuffer ( text ) ; code = code . insert ( maxPosition , " >><< " ) ; String codeString = code . substring ( maxPosition - 100 < 0 ? 0 : maxPosition - 100 , maxPosition + 100 >= code . length ( ) ? code . length ( ) : maxPosition + 100 ) ; return "Could not parse the input string near '" + codeString + "'!" ; } | This message just generates a parser exception message to be returned containing the maximum position where the parser could not proceed . This should be in most cases the position where the error within the text is located . |
18,290 | private MemoEntry applyRule ( String rule , int position , int line ) throws TreeException , ParserException { printMessage ( "applyRule: " + rule , position , line ) ; MemoEntry m = recall ( rule , position , line ) ; if ( m == null ) { LR lr = new LR ( MemoEntry . failed ( ) , rule , null ) ; ruleInvocationStack = new RuleInvocation ( MemoEntry . failed ( ) , rule , null , ruleInvocationStack ) ; m = MemoEntry . create ( lr ) ; memo . setMemo ( rule , position , line , m ) ; final MemoEntry ans = eval ( rule , position , line ) ; ruleInvocationStack = ruleInvocationStack . getNext ( ) ; if ( ( m . getAnswer ( ) instanceof LR ) && ( ( ( LR ) m . getAnswer ( ) ) . getHead ( ) != null ) ) { lr = ( LR ) m . getAnswer ( ) ; lr . setSeed ( ans ) ; MemoEntry lrAnswer = lrAnswer ( rule , position , line , m ) ; printMessage ( "grow LR for '" + rule + "' (" + lrAnswer + ")." , position , line ) ; return lrAnswer ; } else { m . set ( ans ) ; printMessage ( "applied '" + rule + "' (" + ans . getAnswer ( ) + ")." , position , line ) ; return ans ; } } else { if ( ( m . getAnswer ( ) instanceof LR ) ) { setupLR ( rule , ( LR ) m . getAnswer ( ) ) ; MemoEntry seed = ( ( LR ) m . getAnswer ( ) ) . getSeed ( ) ; printMessage ( "Found recursion or grow in process for '" + rule + "' (" + seed + ")." , position , line ) ; return seed ; } else { printMessage ( "already processed '" + rule + "' (" + m + ")." , position , line ) ; return m ; } } } | This method tries to apply a production at a given position . The production is given as a name and not as a concrete rule to process all choices afterwards . |
18,291 | private void setupLR ( String production , final LR l ) throws ParserException { if ( l . getHead ( ) == null ) l . setHead ( new Head ( production ) ) ; RuleInvocation s = ruleInvocationStack ; while ( ! l . getHead ( ) . getProduction ( ) . equals ( s . getProduction ( ) ) ) { s . setHead ( l . getHead ( ) ) ; l . getHead ( ) . addInvolved ( s . getProduction ( ) ) ; s = s . getNext ( ) ; if ( s == null ) throw new RuntimeException ( "We should find the head again, when we search the stack.\n" + "We found a recursion and the rule should be there again." ) ; } } | After finding a recursion or a seed grow in process this method puts all information in place for seed grow . This might be the start information for the growth or the current result in the growing which means the current result . |
18,292 | private MemoEntry recall ( String production , int position , int line ) throws TreeException , ParserException { final MemoEntry m = memo . getMemo ( production , position ) ; final Head h = heads . get ( position ) ; if ( h == null ) { return m ; } if ( ( m == null ) && ( ! h . getProduction ( ) . equals ( production ) ) && ( ! h . getInvolvedSet ( ) . contains ( production ) ) ) { return MemoEntry . failed ( ) ; } if ( h . getEvalSet ( ) . contains ( production ) ) { h . getEvalSet ( ) . remove ( production ) ; final MemoEntry ans = eval ( production , position , line ) ; m . set ( ans ) ; } return m ; } | This method is an extended getMemo function which also takes into account the seed growing processes which might be underway . |
18,293 | private MemoEntry eval ( String productionName , int position , int line ) throws ParserException , TreeException { MemoEntry maxProgress = MemoEntry . failed ( ) ; for ( Production production : grammar . getProductions ( ) . get ( productionName ) ) { MemoEntry progress = parseProduction ( production , position , line ) ; if ( progress . getAnswer ( ) instanceof ParseTreeNode ) { if ( ( maxProgress . getAnswer ( ) == Status . FAILED ) || ( maxProgress . getDeltaPosition ( ) < progress . getDeltaPosition ( ) ) ) { maxProgress = progress ; } } } return maxProgress ; } | This method evaluates the production given by it s name . The different choices are tried from the first to the last . The first choice matching is returned . |
18,294 | private MemoEntry parseProduction ( Production production , int position , int line ) throws TreeException , ParserException { ParseTreeNode node = new ParseTreeNode ( production ) ; MemoEntry progress = MemoEntry . success ( 0 , 0 , node ) ; for ( Construction construction : production . getConstructions ( ) ) { processIgnoredLeadingTokens ( node , position , line , progress ) ; if ( construction . isNonTerminal ( ) ) { MemoEntry newProgress = applyRule ( construction . getName ( ) , position + progress . getDeltaPosition ( ) , line + progress . getDeltaLine ( ) ) ; if ( newProgress . getAnswer ( ) instanceof ParseTreeNode ) { ParseTreeNode child = ( ParseTreeNode ) newProgress . getAnswer ( ) ; if ( child . isNode ( ) ) { if ( child . isStackingAllowed ( ) ) { node . addChild ( child ) ; } else { if ( node . getName ( ) . equals ( child . getName ( ) ) ) { node . addChildren ( child . getChildren ( ) ) ; } else { node . addChild ( child ) ; } } } else { node . addChildren ( child . getChildren ( ) ) ; } progress . add ( newProgress ) ; } else if ( newProgress . getAnswer ( ) . equals ( Status . FAILED ) ) return MemoEntry . failed ( ) ; } else { MemoEntry newProgress = processTerminal ( node , ( Terminal ) construction , position + progress . getDeltaPosition ( ) , line + progress . getDeltaLine ( ) ) ; if ( newProgress . getAnswer ( ) instanceof ParseTreeNode ) { progress . add ( newProgress ) ; } else { return MemoEntry . failed ( ) ; } } processIgnoredTrailingTokens ( node , position , line , progress ) ; } if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Parsed: " + production ) ; } return progress ; } | This method performs the actual parsing by reading the production and applying token definitions and starting other non terminal parsings . |
18,295 | private void processIgnoredLeadingTokens ( ParseTreeNode node , int position , int line , MemoEntry progress ) throws TreeException , ParserException { if ( ignoredLeading ) { processIgnoredTokens ( node , position , line , progress ) ; } } | This method processes leading tokens which are either hidden or ignored . The processing only happens if the configuration allows it . |
18,296 | private MemoEntry processTerminal ( ParseTreeNode node , Terminal terminal , int position , int line ) throws TreeException { printMessage ( "applyTerminal: " + terminal , position , line ) ; TokenDefinitionSet tokenDefinitions = grammar . getTokenDefinitions ( ) ; TokenDefinition tokenDefinition = tokenDefinitions . getDefinition ( terminal . getName ( ) ) ; MemoEntry result = processTokenDefinition ( node , tokenDefinition , position , line ) ; if ( result == null ) { throw new RuntimeException ( "There should be a result not null!" ) ; } printMessage ( "applied Terminal '" + terminal + "' (" + result . getAnswer ( ) + ")." , position , line ) ; return result ; } | This method processes a single terminal . This method uses processTokenDefinition to do this . The information to be put into that method is extracted and prepared here . |
18,297 | private MemoEntry processTokenDefinition ( ParseTreeNode node , TokenDefinition tokenDefinition , int position , int line ) throws TreeException { Matcher matcher = tokenDefinition . getPattern ( ) . matcher ( text . substring ( position ) ) ; if ( ! matcher . find ( ) ) { return MemoEntry . failed ( ) ; } String match = matcher . group ( ) ; int lineBreakNum = StringUtils . countLineBreaks ( match ) ; SourceCodeLocation source = sourceCode . getLines ( ) . get ( line - 1 ) . getSource ( ) ; int lineNumber = textWithSource . getLineNumber ( position ) ; TokenMetaData metaData = new TokenMetaData ( source , lineNumber , lineBreakNum + 1 , textWithSource . getColumn ( position ) ) ; Token token = new Token ( tokenDefinition . getName ( ) , match , tokenDefinition . getVisibility ( ) , metaData ) ; ParseTreeNode myTree = new ParseTreeNode ( token ) ; node . addChild ( myTree ) ; if ( maxPosition < position + match . length ( ) ) { maxPosition = position + match . length ( ) ; } return MemoEntry . success ( match . length ( ) , lineBreakNum , myTree ) ; } | This method tries to process a single token definition . If this can be done true is returned a new parser tree child is added and all internal states are updated like position id and line . |
18,298 | public A messageId ( String messageId ) { this . headers . add ( Pair . of ( "X-MessageId" , messageId ) ) ; return ( A ) this ; } | Sets the message UUID . |
18,299 | public A notificationClass ( DeliveryClass delivery ) { this . headers . add ( Pair . of ( "X-NotificationClass" , String . valueOf ( deliveryValueOf ( delivery ) ) ) ) ; return ( A ) this ; } | Sets the notification batching interval indicating when the notification should be delivered to the device |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.