idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
38,700
private int skipLineBreak ( Source source , final int offset ) { char p ; char c ; int index = offset ; p = source . charAt ( index ) ; index ++ ; if ( index < source . length ( ) ) { c = source . charAt ( index ) ; if ( ( c == '\n' || c == '\r' ) && c != p ) { index ++ ; } } return index ; }
Skip line break characters . \ r \ n for example
38,701
public Object getAttribute ( String name ) { Object value = getLocalAttribute ( name ) ; if ( value == null && parent != null ) { value = parent . getAttribute ( name ) ; } return value ; }
Get the context attribute . If attribute not exists in current context then context search the sttribute in parent context
38,702
public void setScope ( ProcScope scope ) { this . scope = scope ; scopeFalseMemo = falseMemo . get ( scope ) ; if ( scopeFalseMemo == null ) { scopeFalseMemo = new IntSet ( ) ; falseMemo . put ( scope , scopeFalseMemo ) ; } }
Set list of codes in current context
38,703
private List < String > preparePrefixes ( ) { List < String > prefixes = new ArrayList < String > ( Schema . values ( ) . length + ( local ? 3 : 0 ) ) ; for ( Schema schema : Schema . values ( ) ) { prefixes . add ( schema . getPrefix ( ) ) ; } if ( local ) { Collections . addAll ( prefixes , LOCAL_PREFIXES ) ; } return prefixes ; }
Prepare URL s prefixes .
38,704
public void setCodes ( Set < Code > codes ) { Exceptions . nullArgument ( "codes" , codes ) ; this . codes . clear ( ) ; this . codes . addAll ( codes ) ; }
Set codes .
38,705
private void cacheCodes ( ) { Set < ProcCode > set = new HashSet < ProcCode > ( ) ; if ( parent != null ) { set . addAll ( Arrays . asList ( parent . getCodes ( ) ) ) ; } if ( scopeCodes != null ) { set . addAll ( scopeCodes ) ; } cachedCodes = set . toArray ( new ProcCode [ set . size ( ) ] ) ; Arrays . sort ( cachedCodes , new Comparator < ProcCode > ( ) { public int compare ( ProcCode code1 , ProcCode code2 ) { return code2 . compareTo ( code1 ) ; } } ) ; for ( ProcCode code : cachedCodes ) { hasCrazyCode = hasCrazyCode || ! code . startsWithConstant ( ) ; hasCheck = hasCheck || code . containsCheck ( ) ; } }
Cache scope codes . Join scope codes with parent scope codes .
38,706
public BBProcessor build ( ) { this . scopes = new HashMap < Scope , ProcScope > ( ) ; this . codes = new HashMap < Code , ProcCode > ( ) ; patternElementFactory . cleanConstants ( ) ; BBProcessor processor = new BBProcessor ( ) ; processor . setScope ( createScope ( conf . getRootScope ( ) ) ) ; processor . setPrefix ( createTemplate ( conf . getPrefix ( ) ) ) ; processor . setSuffix ( createTemplate ( conf . getSuffix ( ) ) ) ; processor . setParams ( conf . getParams ( ) ) ; processor . setConstants ( patternElementFactory . getConstants ( ) ) ; processor . setNestingLimit ( conf . getNestingLimit ( ) ) ; processor . setPropagateNestingException ( conf . isPropagateNestingException ( ) ) ; for ( ProcScope scope : scopes . values ( ) ) { scope . init ( ) ; } return processor ; }
Build an processor .
38,707
ProcScope createScope ( Scope scope ) { ProcScope created = scopes . get ( scope ) ; if ( created == null ) { created = new ProcScope ( scope . getName ( ) ) ; scopes . put ( scope , created ) ; created . setStrong ( scope . isStrong ( ) ) ; created . setIgnoreText ( scope . isIgnoreText ( ) ) ; if ( scope . getParent ( ) != null ) { created . setParent ( createScope ( scope . getParent ( ) ) ) ; } Set < ProcCode > scopeCodes = new HashSet < ProcCode > ( ) ; for ( Code code : scope . getCodes ( ) ) { scopeCodes . add ( createCode ( code ) ) ; } created . setScopeCodes ( scopeCodes ) ; created . setMin ( scope . getMin ( ) ) ; created . setMax ( scope . getMax ( ) ) ; } return created ; }
Find or create the scope .
38,708
private ProcCode createCode ( Code defCode ) { if ( ! defCode . hasPatterns ( ) ) { throw new IllegalStateException ( "Field pattern can't be null." ) ; } if ( defCode . getTemplate ( ) == null ) { throw new IllegalStateException ( "Field template can't be null." ) ; } ProcCode code = codes . get ( defCode ) ; if ( code == null ) { List < Pattern > confPatterns = defCode . getPatterns ( ) ; List < ProcPattern > procPatterns = new ArrayList < ProcPattern > ( confPatterns . size ( ) ) ; for ( Pattern confPattern : confPatterns ) { procPatterns . add ( createPattern ( confPattern ) ) ; } code = new ProcCode ( procPatterns , createTemplate ( defCode . getTemplate ( ) ) , defCode . getName ( ) , defCode . getPriority ( ) , defCode . isTransparent ( ) ) ; codes . put ( defCode , code ) ; } return code ; }
Create code from this definition
38,709
private ProcTemplate createTemplate ( Template template ) { if ( ! template . isEmpty ( ) ) { return new ProcTemplate ( templateElementFactory . createTemplateList ( template . getElements ( ) ) ) ; } else { return ProcTemplate . EMPTY ; } }
Create a template from definition
38,710
private ProcPattern createPattern ( Pattern pattern ) { if ( pattern . isEmpty ( ) ) { throw new IllegalStateException ( "Pattern elements list can't be empty." ) ; } List < ProcPatternElement > elements = new ArrayList < ProcPatternElement > ( ) ; for ( PatternElement element : pattern . getElements ( ) ) { elements . add ( patternElementFactory . create ( element ) ) ; } return new ProcPattern ( elements ) ; }
Create a pattern for text parsing
38,711
public int findIn ( Source source ) { if ( regex != null ) { Matcher matcher = regex . matcher ( source . subToEnd ( ) ) ; if ( matcher . find ( ) ) { return source . getOffset ( ) + matcher . start ( ) ; } else { return - 1 ; } } else { return - 1 ; } }
Find this element
38,712
private static int binarySearch ( int [ ] array , int toIndex , int key ) { int low = 0 ; int high = toIndex - 1 ; while ( low <= high ) { int mid = ( low + high ) >>> 1 ; int midVal = array [ mid ] ; if ( midVal < key ) { low = mid + 1 ; } else if ( midVal > key ) { high = mid - 1 ; } else { return mid ; } } return - ( low + 1 ) ; }
Realisation of binary search algorithm . It is in JDK 1 . 6 . 0 but for JDK 1 . 5 . 0 compatibility I added it there .
38,713
public Configuration create ( ) { Configuration configuration ; try { InputStream stream = null ; try { stream = Utils . openResourceStream ( DEFAULT_USER_CONFIGURATION_FILE ) ; if ( stream == null ) { stream = Utils . openResourceStream ( DEFAULT_CONFIGURATION_FILE ) ; } if ( stream != null ) { configuration = create ( stream ) ; } else { throw new TextProcessorFactoryException ( "Can't find or open default configuration resource." ) ; } } finally { if ( stream != null ) { stream . close ( ) ; } } Properties properties = new Properties ( ) ; InputStream propertiesStream = null ; try { propertiesStream = Utils . openResourceStream ( DEFAULT_PROPERTIES_FILE ) ; if ( propertiesStream != null ) { properties . load ( propertiesStream ) ; } } finally { if ( propertiesStream != null ) { propertiesStream . close ( ) ; } } InputStream xmlPropertiesStream = null ; try { xmlPropertiesStream = Utils . openResourceStream ( DEFAULT_PROPERTIES_XML_FILE ) ; if ( xmlPropertiesStream != null ) { properties . loadFromXML ( xmlPropertiesStream ) ; } } finally { if ( xmlPropertiesStream != null ) { xmlPropertiesStream . close ( ) ; } } if ( ! properties . isEmpty ( ) ) { Map < String , CharSequence > params = new HashMap < String , CharSequence > ( ) ; params . putAll ( configuration . getParams ( ) ) ; for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { Object key = entry . getKey ( ) ; if ( key != null ) { params . put ( key . toString ( ) , entry . getValue ( ) . toString ( ) ) ; } } configuration . setParams ( params ) ; } } catch ( IOException e ) { throw new TextProcessorFactoryException ( e ) ; } return configuration ; }
Create the default bb - code processor .
38,714
public Configuration createFromResource ( String resourceName ) { Exceptions . nullArgument ( "resourceName" , resourceName ) ; Configuration configuration ; try { InputStream stream = null ; try { stream = Utils . openResourceStream ( resourceName ) ; if ( stream != null ) { configuration = create ( stream ) ; } else { throw new TextProcessorFactoryException ( "Can't find or open resource \"" + resourceName + "\"." ) ; } } finally { if ( stream != null ) { stream . close ( ) ; } } } catch ( IOException e ) { throw new TextProcessorFactoryException ( e ) ; } return configuration ; }
Create the bb - processor using xml - configuration resource
38,715
public Configuration create ( File file ) { try { Configuration configuration ; InputStream stream = new BufferedInputStream ( new FileInputStream ( file ) ) ; try { configuration = create ( stream ) ; } finally { stream . close ( ) ; } return configuration ; } catch ( IOException e ) { throw new TextProcessorFactoryException ( e ) ; } }
Create the bb - code processor from file with XML - configuration .
38,716
public Configuration create ( InputStream stream ) { try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setValidating ( false ) ; factory . setIgnoringElementContentWhitespace ( true ) ; factory . setNamespaceAware ( true ) ; DocumentBuilder documentBuilder = factory . newDocumentBuilder ( ) ; Document document = documentBuilder . parse ( stream ) ; return domConfigurationFactory . create ( document ) ; } catch ( ParserConfigurationException e ) { throw new TextProcessorFactoryException ( e ) ; } catch ( IOException e ) { throw new TextProcessorFactoryException ( e ) ; } catch ( SAXException e ) { throw new TextProcessorFactoryException ( e ) ; } }
Create the bb - processor from XML InputStream
38,717
public void setParams ( Map < String , CharSequence > params ) { if ( this . params == null ) { this . params = Collections . unmodifiableMap ( params ) ; } else { throw new IllegalStateException ( "Can't change parameters." ) ; } }
Set text processor parameters map .
38,718
private PatternConstant create ( Constant constant ) { if ( ! constants . containsKey ( constant ) ) { constants . put ( constant , new PatternConstant ( constant . getValue ( ) , constant . isIgnoreCase ( ) , constant . isGhost ( ) ) ) ; } return constants . get ( constant ) ; }
Create a constant element for text parsing
38,719
public Configuration create ( Document dc ) { Configuration configuration = new Configuration ( ) ; parseNesting ( configuration , dc ) ; configuration . setParams ( parseParams ( dc ) ) ; configuration . setPrefix ( parseFix ( dc , TAG_PREFIX ) ) ; configuration . setSuffix ( parseFix ( dc , TAG_SUFFIX ) ) ; NodeList scopeNodeList = dc . getDocumentElement ( ) . getElementsByTagNameNS ( SCHEMA_LOCATION , TAG_SCOPE ) ; Map < String , Scope > scopes = parseScopes ( scopeNodeList ) ; boolean fillRoot = false ; Scope root ; if ( ! scopes . containsKey ( Scope . ROOT ) ) { root = new Scope ( Scope . ROOT ) ; scopes . put ( Scope . ROOT , root ) ; fillRoot = true ; } else { root = scopes . get ( Scope . ROOT ) ; } Map < String , Code > codes = parseCodes ( dc , scopes ) ; fillScopeCodes ( scopeNodeList , scopes , codes ) ; if ( fillRoot ) { root . setCodes ( new HashSet < Code > ( codes . values ( ) ) ) ; } configuration . setRootScope ( root ) ; return configuration ; }
Create the bb - code processor from DOM Document
38,720
private void parseNesting ( Configuration configuration , Document dc ) { NodeList list = dc . getElementsByTagNameNS ( SCHEMA_LOCATION , TAG_NESTING ) ; if ( list . getLength ( ) > 0 ) { Node el = list . item ( 0 ) ; configuration . setNestingLimit ( nodeAttribute ( el , TAG_NESTING_ATTR_LIMIT , Configuration . DEFAULT_NESTING_LIMIT ) ) ; configuration . setPropagateNestingException ( nodeAttribute ( el , TAG_NESTING_ATTR_EXCEPTION , Configuration . DEFAULT_PROPAGATE_NESTING_EXCEPTION ) ) ; } }
Parse nesting element which describes nesting behavior .
38,721
private Map < String , CharSequence > parseParams ( Document dc ) { Map < String , CharSequence > params = new HashMap < String , CharSequence > ( ) ; NodeList paramsElements = dc . getElementsByTagNameNS ( SCHEMA_LOCATION , TAG_PARAMS ) ; if ( paramsElements . getLength ( ) > 0 ) { Element paramsElement = ( Element ) paramsElements . item ( 0 ) ; NodeList paramElements = paramsElement . getElementsByTagNameNS ( SCHEMA_LOCATION , TAG_PARAM ) ; for ( int i = 0 ; i < paramElements . getLength ( ) ; i ++ ) { Node paramElement = paramElements . item ( i ) ; String name = nodeAttribute ( paramElement , TAG_PARAM_ATTR_NAME , "" ) ; String value = nodeAttribute ( paramElement , TAG_PARAM_ATTR_VALUE , "" ) ; if ( name != null && name . length ( ) > 0 ) { params . put ( name , value ) ; } } } return params ; }
Parse configuration predefined parameters .
38,722
private Template parseFix ( Document dc , String tagname ) { Template fix ; NodeList prefixElementList = dc . getElementsByTagNameNS ( SCHEMA_LOCATION , tagname ) ; if ( prefixElementList . getLength ( ) > 0 ) { fix = parseTemplate ( prefixElementList . item ( 0 ) ) ; } else { fix = new Template ( ) ; } return fix ; }
Parse prefix or suffix .
38,723
private void fillScopeCodes ( NodeList scopeNodeList , Map < String , Scope > scopes , Map < String , Code > codes ) { for ( int i = 0 ; i < scopeNodeList . getLength ( ) ; i ++ ) { Element scopeElement = ( Element ) scopeNodeList . item ( i ) ; Scope scope = scopes . get ( scopeElement . getAttribute ( TAG_SCOPE_ATTR_NAME ) ) ; Set < Code > scopeCodes = new HashSet < Code > ( ) ; NodeList coderefs = scopeElement . getElementsByTagNameNS ( SCHEMA_LOCATION , TAG_CODEREF ) ; for ( int j = 0 ; j < coderefs . getLength ( ) ; j ++ ) { Element ref = ( Element ) coderefs . item ( j ) ; String codeName = ref . getAttribute ( TAG_CODEREF_ATTR_NAME ) ; Code code = codes . get ( codeName ) ; if ( code == null ) { throw new TextProcessorFactoryException ( "Can't find code \"" + codeName + "\"." ) ; } scopeCodes . add ( code ) ; } NodeList inlineCodes = scopeElement . getElementsByTagNameNS ( SCHEMA_LOCATION , TAG_CODE ) ; for ( int j = 0 ; j < inlineCodes . getLength ( ) ; j ++ ) { Element ice = ( Element ) inlineCodes . item ( j ) ; scopeCodes . add ( parseCode ( ice , scopes ) ) ; } scope . setCodes ( scopeCodes ) ; } }
Fill codes of scopes .
38,724
private Map < String , Scope > parseScopes ( NodeList scopeNodeList ) { Map < String , Scope > scopes = new HashMap < String , Scope > ( ) ; for ( int i = 0 ; i < scopeNodeList . getLength ( ) ; i ++ ) { Element scopeElement = ( Element ) scopeNodeList . item ( i ) ; String name = scopeElement . getAttribute ( TAG_SCOPE_ATTR_NAME ) ; if ( name . length ( ) == 0 ) { throw new TextProcessorFactoryException ( "Illegal scope name. Scope name can't be empty." ) ; } Scope scope = new Scope ( name , nodeAttribute ( scopeElement , TAG_SCOPE_ATTR_IGNORE_TEXT , Scope . DEFAULT_IGNORE_TEXT ) ) ; scope . setStrong ( nodeAttribute ( scopeElement , TAG_SCOPE_ATTR_STRONG , Scope . DEFAULT_STRONG ) ) ; scopes . put ( scope . getName ( ) , scope ) ; } for ( int i = 0 ; i < scopeNodeList . getLength ( ) ; i ++ ) { Element scopeElement = ( Element ) scopeNodeList . item ( i ) ; String name = scopeElement . getAttribute ( TAG_SCOPE_ATTR_NAME ) ; Scope scope = scopes . get ( name ) ; if ( scope == null ) { throw new TextProcessorFactoryException ( MessageFormat . format ( "Can't find scope \"{0}\"." , name ) ) ; } String parentName = nodeAttribute ( scopeElement , TAG_SCOPE_ATTR_PARENT ) ; if ( parentName != null ) { Scope parent = scopes . get ( parentName ) ; if ( parent == null ) { throw new TextProcessorFactoryException ( MessageFormat . format ( "Can't find parent scope \"{0}\"." , parentName ) ) ; } scope . setParent ( parent ) ; } scope . setMax ( nodeAttribute ( scopeElement , TAG_SCOPE_ATTR_MAX , Scope . DEFAULT_MAX_VALUE ) ) ; scope . setMin ( nodeAttribute ( scopeElement , TAG_SCOPE_ATTR_MIN , Scope . DEFAULT_MIN_VALUE ) ) ; } return scopes ; }
Parse scopes from XML
38,725
private Map < String , Code > parseCodes ( Document dc , Map < String , Scope > scopes ) { Map < String , Code > codes = new HashMap < String , Code > ( ) ; NodeList codeNodeList = dc . getDocumentElement ( ) . getElementsByTagNameNS ( SCHEMA_LOCATION , TAG_CODE ) ; for ( int i = 0 ; i < codeNodeList . getLength ( ) ; i ++ ) { Code code = parseCode ( ( Element ) codeNodeList . item ( i ) , scopes ) ; codes . put ( code . getName ( ) , code ) ; } return codes ; }
Parse codes from XML
38,726
private Code parseCode ( Element codeElement , Map < String , Scope > scopes ) { Code code = new Code ( nodeAttribute ( codeElement , TAG_CODE_ATTR_NAME , Utils . generateRandomName ( ) ) ) ; code . setPriority ( nodeAttribute ( codeElement , TAG_CODE_ATTR_PRIORITY , Code . DEFAULT_PRIORITY ) ) ; code . setTransparent ( nodeAttribute ( codeElement , TAG_CODE_ATTR_TRANSPARENT , true ) ) ; NodeList templateElements = codeElement . getElementsByTagNameNS ( SCHEMA_LOCATION , TAG_TEMPLATE ) ; if ( templateElements . getLength ( ) > 0 ) { code . setTemplate ( parseTemplate ( templateElements . item ( 0 ) ) ) ; } else { throw new TextProcessorFactoryException ( "Illegal configuration. Can't find template of code." ) ; } NodeList patternElements = codeElement . getElementsByTagNameNS ( SCHEMA_LOCATION , TAG_PATTERN ) ; if ( patternElements . getLength ( ) > 0 ) { for ( int i = 0 ; i < patternElements . getLength ( ) ; i ++ ) { code . addPattern ( parsePattern ( patternElements . item ( i ) , scopes ) ) ; } } else { throw new TextProcessorFactoryException ( "Illegal configuration. Can't find pattern of code." ) ; } return code ; }
Parse bb - code from DOM Node
38,727
private Pattern parsePattern ( Node node , Map < String , Scope > scopes ) { List < PatternElement > elements = new ArrayList < PatternElement > ( ) ; NodeList patternList = node . getChildNodes ( ) ; int patternLength = patternList . getLength ( ) ; if ( patternLength <= 0 ) { throw new TextProcessorFactoryException ( "Invalid pattern. Pattern is empty." ) ; } boolean ignoreCase = nodeAttribute ( node , "ignoreCase" , false ) ; for ( int k = 0 ; k < patternLength ; k ++ ) { Node el = patternList . item ( k ) ; short nodeType = el . getNodeType ( ) ; if ( nodeType == Node . TEXT_NODE ) { elements . add ( new Constant ( el . getNodeValue ( ) , ignoreCase ) ) ; } else if ( nodeType == Node . ELEMENT_NODE ) { String tagName = el . getLocalName ( ) ; if ( tagName . equals ( TAG_CONSTANT ) ) { elements . add ( parseConstant ( el , ignoreCase ) ) ; } else if ( tagName . equals ( TAG_VAR ) ) { elements . add ( parseNamedElement ( el , scopes ) ) ; } else if ( tagName . equals ( TAG_JUNK ) ) { elements . add ( new Junk ( ) ) ; } else if ( tagName . equals ( TAG_EOL ) ) { elements . add ( parseEol ( el ) ) ; } else if ( tagName . equals ( TAG_BOL ) ) { elements . add ( new Bol ( ) ) ; } else if ( tagName . equals ( TAG_BLANKLINE ) ) { elements . add ( new BlankLine ( nodeAttribute ( el , TAG_ATTR_GHOST , PatternElement . DEFAULT_GHOST_VALUE ) ) ) ; } else if ( tagName . equals ( TAG_URL ) ) { elements . add ( parseUrl ( el ) ) ; } else if ( tagName . equals ( TAG_EMAIL ) ) { elements . add ( parseEmail ( el ) ) ; } else { throw new TextProcessorFactoryException ( MessageFormat . format ( "Invalid pattern. Unknown XML element [{0}]." , tagName ) ) ; } } else { throw new TextProcessorFactoryException ( "Invalid pattern. Unsupported XML node type." ) ; } } return new Pattern ( elements ) ; }
Parse code pattern for parse text .
38,728
private Url parseUrl ( Node el ) { return new Url ( nodeAttribute ( el , TAG_VAR_ATTR_NAME , Url . DEFAULT_NAME ) , nodeAttribute ( el , TAG_ATTR_GHOST , PatternElement . DEFAULT_GHOST_VALUE ) , nodeAttribute ( el , TAG_URL_ATTR_LOCAL , Url . DEFAULT_LOCAL ) , nodeAttribute ( el , TAG_URL_ATTR_SCHEMALESS , Url . DEFAULT_SCHEMALESS ) ) ; }
Parse an URL tag .
38,729
private Email parseEmail ( Node el ) { return new Email ( nodeAttribute ( el , TAG_VAR_ATTR_NAME , Email . DEFAULT_NAME ) , nodeAttribute ( el , TAG_ATTR_GHOST , PatternElement . DEFAULT_GHOST_VALUE ) ) ; }
Parse an email tag .
38,730
private Constant parseConstant ( Node el , boolean ignoreCase ) { return new Constant ( nodeAttribute ( el , TAG_CONSTANT_ATTR_VALUE ) , nodeAttribute ( el , TAG_CONSTANT_ATTR_IGNORE_CASE , ignoreCase ) , nodeAttribute ( el , TAG_ATTR_GHOST , PatternElement . DEFAULT_GHOST_VALUE ) ) ; }
Parse constant pattern element
38,731
private PatternElement parseNamedElement ( Node el , Map < String , Scope > scopes ) { PatternElement namedElement ; if ( nodeAttribute ( el , TAG_VAR_ATTR_PARSE , DEFAULT_PARSE_VALUE ) && ! nodeHasAttribute ( el , TAG_VAR_ATTR_REGEX ) && ! nodeHasAttribute ( el , TAG_VAR_ATTR_ACTION ) ) { namedElement = parseText ( el , scopes ) ; } else { namedElement = parseVariable ( el ) ; } return namedElement ; }
Parse a pattern named element . Text or Variable .
38,732
private Text parseText ( Node el , Map < String , Scope > scopes ) { Text text ; if ( nodeAttribute ( el , TAG_VAR_ATTR_INHERIT , DEFAULT_INHERIT_VALUE ) ) { text = new Text ( nodeAttribute ( el , TAG_VAR_ATTR_NAME , Variable . DEFAULT_NAME ) , null , nodeAttribute ( el , TAG_VAR_ATTR_TRANSPARENT , false ) ) ; } else { String scopeName = nodeAttribute ( el , TAG_SCOPE , Scope . ROOT ) ; Scope scope = scopes . get ( scopeName ) ; if ( scope == null ) { throw new TextProcessorFactoryException ( MessageFormat . format ( "Scope \"{0}\" not found." , scopeName ) ) ; } text = new Text ( nodeAttribute ( el , TAG_VAR_ATTR_NAME , Variable . DEFAULT_NAME ) , scope , nodeAttribute ( el , TAG_VAR_ATTR_TRANSPARENT , false ) ) ; } return text ; }
Parse text . Text is a part of pattern .
38,733
private Variable parseVariable ( Node el ) { Variable variable ; if ( nodeHasAttribute ( el , TAG_VAR_ATTR_REGEX ) ) { variable = new Variable ( nodeAttribute ( el , TAG_VAR_ATTR_NAME , Variable . DEFAULT_NAME ) , java . util . regex . Pattern . compile ( nodeAttribute ( el , TAG_VAR_ATTR_REGEX ) ) ) ; } else { variable = new Variable ( nodeAttribute ( el , TAG_VAR_ATTR_NAME , Variable . DEFAULT_NAME ) ) ; } variable . setGhost ( nodeAttribute ( el , TAG_ATTR_GHOST , PatternElement . DEFAULT_GHOST_VALUE ) ) ; if ( nodeHasAttribute ( el , TAG_VAR_ATTR_ACTION ) ) { variable . setAction ( Action . valueOf ( nodeAttribute ( el , TAG_VAR_ATTR_ACTION ) ) ) ; } return variable ; }
Parse variable . The part of pattern .
38,734
private If parseIf ( Node node ) { return new If ( nodeAttribute ( node , TAG_VAR_ATTR_NAME , Variable . DEFAULT_NAME ) , parseTemplateElements ( node ) ) ; }
Parse an IF expression .
38,735
private boolean nodeAttribute ( Node node , String attributeName , boolean defaultValue ) { boolean value = defaultValue ; if ( node . hasAttributes ( ) ) { Node attribute = node . getAttributes ( ) . getNamedItem ( attributeName ) ; if ( attribute != null ) { value = Boolean . valueOf ( attribute . getNodeValue ( ) ) ; } } return value ; }
Return node attribute value if exists or default attribute value
38,736
private boolean nodeHasAttribute ( Node node , String attributeName ) { return node . hasAttributes ( ) && node . getAttributes ( ) . getNamedItem ( attributeName ) != null ; }
Check node attribute .
38,737
public boolean parse ( Context context ) throws NestingException { boolean flag = true ; Source source = context . getSource ( ) ; int offset = source . getOffset ( ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "[{}] Begin {}" , offset , this ) ; } int i ; for ( i = 0 ; i < patternSize && flag ; i ++ ) { ProcPatternElement current = elements . get ( i ) ; ProcPatternElement next ; if ( i < patternSize - 1 ) { next = elements . get ( i + 1 ) ; } else { next = context . getTerminator ( ) ; } flag = current . parse ( context , next ) ; } if ( ! flag ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "[{}] Rollback {} on {} element" , source . getOffset ( ) , this , i ) ; } source . setOffset ( offset ) ; } else { if ( log . isTraceEnabled ( ) ) { log . trace ( "[{}] Complete {}" , source . getOffset ( ) , this ) ; } } return flag ; }
Parse context with this pattern
38,738
public boolean process ( Context context ) throws NestingException { for ( ProcPattern pattern : patterns ) { Context codeContext = new Context ( context ) ; if ( pattern . parse ( codeContext ) ) { if ( transparent ) { codeContext . mergeWithParent ( ) ; } template . generate ( codeContext ) ; if ( logContext . isTraceEnabled ( ) ) { for ( Map . Entry < String , CharSequence > entry : context . getAttributes ( ) . entrySet ( ) ) { logContext . trace ( "Context: {} = {}" , entry . getKey ( ) , entry . getValue ( ) ) ; } } if ( logGenerate . isTraceEnabled ( ) ) { logGenerate . trace ( "Generated text: {}" , codeContext . getTarget ( ) ) ; } return true ; } } return false ; }
Parse bb - code
38,739
public boolean suspicious ( Context context ) { for ( ProcPattern pattern : patterns ) { if ( pattern . suspicious ( context ) ) { return true ; } } return false ; }
Check if next sequence can be parsed with this code . It s most called method in this project .
38,740
public static InputStream openResourceStream ( String resourceName ) { InputStream stream = null ; ClassLoader classLoader = Utils . class . getClassLoader ( ) ; if ( classLoader != null ) { stream = classLoader . getResourceAsStream ( resourceName ) ; } if ( stream == null ) { stream = ClassLoader . getSystemResourceAsStream ( resourceName ) ; } return stream ; }
Open the resource stream for named resource . Stream must be closed by user after usage .
38,741
private char [ ] getConstantChars ( ) { Set < Character > chars = new TreeSet < Character > ( ) ; chars . add ( '\n' ) ; chars . add ( '\r' ) ; for ( PatternConstant constant : constantSet ) { char c = constant . getValue ( ) . charAt ( 0 ) ; if ( constant . isIgnoreCase ( ) ) { chars . add ( Character . toLowerCase ( c ) ) ; chars . add ( Character . toUpperCase ( c ) ) ; } else { chars . add ( c ) ; } } char [ ] cs = new char [ chars . size ( ) ] ; int j = 0 ; for ( Character c : chars ) { cs [ j ] = c ; j ++ ; } Arrays . sort ( cs ) ; return cs ; }
Collect first chars of constants of configuration .
38,742
public boolean nextIs ( PatternConstant constant ) { char [ ] cs = constant . getCharArray ( ) ; int length = cs . length ; if ( length > textLength - offset ) { return false ; } if ( ! constant . isIgnoreCase ( ) ) { int i ; for ( i = 0 ; i < length && text [ offset + i ] == cs [ i ] ; i ++ ) ; return i == length ; } else { for ( int i = 0 ; i < length ; i ++ ) { char ct = text [ offset + i ] ; char cv = cs [ i ] ; if ( ct == cv || Character . toUpperCase ( ct ) == Character . toUpperCase ( cv ) || Character . toLowerCase ( ct ) == Character . toLowerCase ( cv ) ) { continue ; } return false ; } return true ; } }
Test id next sequence the constant?
38,743
public int find ( PatternConstant constant ) { char [ ] cs = constant . getCharArray ( ) ; boolean ignoreCase = constant . isIgnoreCase ( ) ; return find ( cs , ignoreCase ) ; }
Find constant in source text .
38,744
public void generate ( Context context ) { Appendable target = context . getTarget ( ) ; for ( ProcTemplateElement element : elements ) { try { target . append ( element . generate ( context ) ) ; } catch ( IOException e ) { } } }
Append to result string processed text .
38,745
public int getCurrentPosition ( ) { int curPosition = - 1 ; if ( getLayoutManager ( ) . canScrollHorizontally ( ) ) { curPosition = ViewUtils . getCenterXChildPosition ( this ) ; } else { curPosition = ViewUtils . getCenterYChildPosition ( this ) ; } if ( curPosition < 0 ) { curPosition = mSmoothScrollTargetPosition ; } return curPosition ; }
get item position in center of viewpager
38,746
public static View getCenterXChild ( RecyclerView recyclerView ) { int childCount = recyclerView . getChildCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { View child = recyclerView . getChildAt ( i ) ; if ( isChildInCenterX ( recyclerView , child ) ) { return child ; } } return null ; }
Get center child in X Axes
38,747
public static int getCenterXChildPosition ( RecyclerView recyclerView ) { int childCount = recyclerView . getChildCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { View child = recyclerView . getChildAt ( i ) ; if ( isChildInCenterX ( recyclerView , child ) ) { return recyclerView . getChildAdapterPosition ( child ) ; } } return childCount ; }
Get position of center child in X Axes
38,748
public static View getCenterYChild ( RecyclerView recyclerView ) { int childCount = recyclerView . getChildCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { View child = recyclerView . getChildAt ( i ) ; if ( isChildInCenterY ( recyclerView , child ) ) { return child ; } } return null ; }
Get center child in Y Axes
38,749
public static int getCenterYChildPosition ( RecyclerView recyclerView ) { int childCount = recyclerView . getChildCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { View child = recyclerView . getChildAt ( i ) ; if ( isChildInCenterY ( recyclerView , child ) ) { return recyclerView . getChildAdapterPosition ( child ) ; } } return childCount ; }
Get position of center child in Y Axes
38,750
public void setStatusBarColor ( View statusBar , int color ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . KITKAT ) { Window w = getWindow ( ) ; w . setFlags ( WindowManager . LayoutParams . FLAG_TRANSLUCENT_STATUS , WindowManager . LayoutParams . FLAG_TRANSLUCENT_STATUS ) ; int actionBarHeight = getActionBarHeight ( ) ; int statusBarHeight = getStatusBarHeight ( ) ; statusBar . getLayoutParams ( ) . height = statusBarHeight ; statusBar . setBackgroundColor ( color ) ; } }
only work for > = 19
38,751
private void clipViewOnTheRight ( Rect curViewBound , float curViewWidth , int right ) { curViewBound . right = ( int ) ( right - mClipPadding ) ; curViewBound . left = ( int ) ( curViewBound . right - curViewWidth ) ; }
Set bounds for the right textView including clip padding .
38,752
private void clipViewOnTheLeft ( Rect curViewBound , float curViewWidth , int left ) { curViewBound . left = ( int ) ( left + mClipPadding ) ; curViewBound . right = ( int ) ( mClipPadding + curViewWidth ) ; }
Set bounds for the left textView including clip padding .
38,753
private ArrayList < Rect > calculateAllBounds ( Paint paint ) { ArrayList < Rect > list = new ArrayList < Rect > ( ) ; final int count = mRecyclerView . getAdapter ( ) . getItemCount ( ) ; final int width = getWidth ( ) ; final int halfWidth = width / 2 ; for ( int i = 0 ; i < count ; i ++ ) { Rect bounds = calcBounds ( i , paint ) ; int w = bounds . right - bounds . left ; int h = bounds . bottom - bounds . top ; bounds . left = ( int ) ( halfWidth - ( w / 2f ) + ( ( i - mCurrentPage - mPageOffset ) * width ) ) ; bounds . right = bounds . left + w ; bounds . top = 0 ; bounds . bottom = h ; list . add ( bounds ) ; } return list ; }
Calculate views bounds and scroll them according to the current index
38,754
private Rect calcBounds ( int index , Paint paint ) { Rect bounds = new Rect ( ) ; CharSequence title = getTitle ( index ) ; bounds . right = ( int ) paint . measureText ( title , 0 , title . length ( ) ) ; bounds . bottom = ( int ) ( paint . descent ( ) - paint . ascent ( ) ) ; return bounds ; }
Calculate the bounds for a view s title
38,755
public static void initialize ( ) { if ( initialized ) return ; SniffyConfiguration . INSTANCE . addTopSqlCapacityListener ( new PropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent evt ) { ConcurrentLinkedHashMap < String , Timer > oldValues = globalSqlStats ; globalSqlStats = new ConcurrentLinkedHashMap . Builder < String , Timer > ( ) . maximumWeightedCapacity ( SniffyConfiguration . INSTANCE . getTopSqlCapacity ( ) ) . build ( ) ; globalSqlStats . putAll ( oldValues ) ; } } ) ; if ( SniffyConfiguration . INSTANCE . isMonitorSocket ( ) ) { try { SnifferSocketImplFactory . install ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } else { SniffyConfiguration . INSTANCE . addMonitorSocketListener ( new PropertyChangeListener ( ) { private boolean sniffySocketImplFactoryInstalled = false ; public synchronized void propertyChange ( PropertyChangeEvent evt ) { if ( sniffySocketImplFactoryInstalled ) return ; if ( Boolean . TRUE . equals ( evt . getNewValue ( ) ) ) { try { SnifferSocketImplFactory . install ( ) ; sniffySocketImplFactoryInstalled = true ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } ) ; } initialized = true ; }
If socket monitoring is already enabled it cannot be disabled afterwards Otherwise one webapp would enable it but another one would disable
38,756
private void grow ( int minCapacity ) { int oldCapacity = buf . length ; int newCapacity = oldCapacity << 1 ; if ( newCapacity - minCapacity < 0 ) newCapacity = minCapacity ; if ( newCapacity < 0 ) { if ( minCapacity < 0 ) throw new OutOfMemoryError ( ) ; newCapacity = Integer . MAX_VALUE ; } buf = copyOf ( buf , newCapacity ) ; }
Increases the capacity to ensure that it can hold at least the number of elements specified by the minimum capacity argument .
38,757
protected void flushIfPossible ( ) throws IOException { if ( null != bufferedServletOutputStream ) bufferedServletOutputStream . setLastChunk ( ) ; if ( null != writer ) writer . flushIfOpen ( ) ; else if ( null != outputStream ) outputStream . flushIfOpen ( ) ; else { if ( ! isCommitted ( ) ) { notifyBeforeCommit ( ) ; } notifyBeforeClose ( ) ; } }
Flush the sniffer buffer and append the information about the executed queries to the output stream
38,758
public void sendError ( int sc , String msg ) throws IOException { if ( isCommitted ( ) ) { throw new IllegalStateException ( "Cannot set error status - response is already committed" ) ; } notifyBeforeCommit ( ) ; super . sendError ( sc , msg ) ; setCommitted ( ) ; }
headers relates methods
38,759
@ SuppressWarnings ( "unchecked" ) public < T > T [ ] asArrayOf ( final Class < T > componentType ) { Class < ? > callerClass = ReflectionHelper . getDirectCallerClass ( ) ; List < T > list = evaluateMultiValues ( componentType , callerClass ) ; return list . toArray ( ( T [ ] ) java . lang . reflect . Array . newInstance ( componentType , list . size ( ) ) ) ; }
Evaluate the XPath as an array of the given type .
38,760
public static List < ? > evaluateAsList ( final XPathExpression expression , final Node node , final Method method , final InvocationContext invocationContext ) throws XPathExpressionException { final Class < ? > targetComponentType = invocationContext . getTargetComponentType ( ) ; final NodeList nodes = ( NodeList ) expression . evaluate ( node , XPathConstants . NODESET ) ; final List < Object > linkedList = new LinkedList < Object > ( ) ; final TypeConverter typeConverter = invocationContext . getProjector ( ) . config ( ) . getTypeConverter ( ) ; if ( typeConverter . isConvertable ( targetComponentType ) ) { for ( int i = 0 ; i < nodes . getLength ( ) ; ++ i ) { linkedList . add ( typeConverter . convertTo ( targetComponentType , nodes . item ( i ) . getTextContent ( ) , invocationContext . getExpressionFormatPattern ( ) ) ) ; } return linkedList ; } if ( Node . class . equals ( targetComponentType ) ) { for ( int i = 0 ; i < nodes . getLength ( ) ; ++ i ) { linkedList . add ( nodes . item ( i ) ) ; } return linkedList ; } if ( targetComponentType . isInterface ( ) ) { for ( int i = 0 ; i < nodes . getLength ( ) ; ++ i ) { Object subprojection = invocationContext . getProjector ( ) . projectDOMNode ( nodes . item ( i ) , targetComponentType ) ; linkedList . add ( subprojection ) ; } return linkedList ; } throw new IllegalArgumentException ( "Return type " + targetComponentType + " is not valid for list or array component type returning from method " + method + " using the current type converter:" + invocationContext . getProjector ( ) . config ( ) . getTypeConverter ( ) + ". Please change the return type to a sub projection or add a conversion to the type converter." ) ; }
Perform an XPath evaluation on an invocation context .
38,761
private DOMAccess checkProjectionInstance ( final Object projection ) { if ( java . lang . reflect . Proxy . isProxyClass ( projection . getClass ( ) ) ) { InvocationHandler invocationHandler = java . lang . reflect . Proxy . getInvocationHandler ( projection ) ; if ( invocationHandler instanceof ProjectionInvocationHandler ) { if ( projection instanceof DOMAccess ) { return ( DOMAccess ) projection ; } } } throw new IllegalArgumentException ( "Given object " + projection + " is not a projection." ) ; }
Ensures that the given object is a projection created by a projector .
38,762
private static int countTrue ( final boolean ... b ) { if ( b == null ) { return 0 ; } int count = 0 ; for ( boolean bb : b ) { if ( bb ) { ++ count ; } } return count ; }
Count how many parameters are true .
38,763
public < T > XBAutoMap < T > autoMapEmptyDocument ( final Class < T > valueType ) { Document document = xMLFactoriesConfig . createDocumentBuilder ( ) . newDocument ( ) ; return createAutoMapForDocument ( valueType , document ) ; }
Create an empty document and bind an XBAutoMap to it .
38,764
@ Scope ( DocScope . IO ) public < T > T read ( final Class < T > projectionInterface ) throws IOException { Document document = readDocument ( ) ; return projector . projectDOMNode ( document , projectionInterface ) ; }
Create a new projection by parsing the data provided by the input stream .
38,765
public ExpressionType getExpressionType ( ) { try { final ExpressionType expressionType = node . firstChildAccept ( new ExpressionTypeEvaluationVisitor ( ) , null ) ; return expressionType ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( "Please report this bug: Can not determine type of XPath:" + xpath , e ) ; } }
Calculates the return type of the expression .
38,766
@ SuppressWarnings ( "unchecked" ) public org . w3c . dom . Node ensureExistence ( final org . w3c . dom . Node contextNode ) { final Document document = DOMHelper . getOwnerDocumentFor ( contextNode ) ; final Map < String , String > namespaceMapping = new HashMap < String , String > ( userDefinedMapping ) ; namespaceMapping . putAll ( DOMHelper . getNamespaceMapping ( document ) ) ; return ( ( List < org . w3c . dom . Node > ) node . firstChildAccept ( new BuildDocumentVisitor ( variableResolver , namespaceMapping ) , contextNode ) ) . get ( 0 ) ; }
Creates nodes until selecting such a path would return something .
38,767
@ SuppressWarnings ( "unchecked" ) @ Scope ( DocScope . IO ) public String write ( final Object projection ) throws IOException { return IOHelper . inputStreamToString ( IOHelper . httpPost ( url , projection . toString ( ) , requestProperties ) ) ; }
Post the projected document to a HTTP URL . The response is provided as a raw string .
38,768
@ Scope ( DocScope . IO ) public UrlIO addRequestProperties ( final Map < String , String > params ) { requestProperties . putAll ( params ) ; return this ; }
Allows to add some request properties .
38,769
@ Scope ( DocScope . IO ) public UrlIO addRequestProperty ( final String name , final String value ) { requestProperties . put ( name , value ) ; return this ; }
Allows to add a single request property .
38,770
@ Scope ( DocScope . IO ) public XPathEvaluator evalXPath ( final String xpath ) { return new DefaultXPathEvaluator ( projector , new DocumentResolver ( ) { public Document resolve ( final Class < ? > ... resourceAwareClasses ) throws IOException { return IOHelper . getDocumentFromURL ( projector . config ( ) . createDocumentBuilder ( ) , url , requestProperties , resourceAwareClasses ) ; } } , xpath ) ; }
Evaluate XPath on the url document .
38,771
@ Scope ( DocScope . IO ) public < T > XBAutoMap < T > readAsMapOf ( final Class < T > valueType ) throws IOException { DefaultXPathBinder . validateEvaluationType ( valueType ) ; final Class < ? > resourceAwareClass = ReflectionHelper . getDirectCallerClass ( ) ; Document document = IOHelper . getDocumentFromURL ( projector . config ( ) . createDocumentBuilder ( ) , url , requestProperties , resourceAwareClass ) ; InvocationContext invocationContext = new InvocationContext ( null , null , null , null , null , valueType , projector ) ; return new AutoMap < T > ( document , invocationContext , valueType ) ; }
Read complete document to a Map .
38,772
private static void unwrapArgs ( final Class < ? > [ ] types , final Object [ ] args ) { if ( args == null ) { return ; } try { for ( int i = 0 ; i < args . length ; ++ i ) { args [ i ] = ReflectionHelper . unwrap ( types [ i ] , args [ i ] ) ; } } catch ( Exception e ) { throw new IllegalArgumentException ( e ) ; } }
If parameter is instance of Callable or Supplier then resolve its value .
38,773
private static Class < ? > findTargetComponentType ( final Method method ) { final Class < ? > returnType = method . getReturnType ( ) ; if ( returnType . isArray ( ) ) { return method . getReturnType ( ) . getComponentType ( ) ; } if ( ! ( List . class . equals ( returnType ) || ( Map . class . equals ( returnType ) ) || XBAutoMap . class . isAssignableFrom ( returnType ) || XBAutoList . class . equals ( returnType ) || XBAutoValue . class . equals ( returnType ) || ReflectionHelper . isStreamClass ( returnType ) ) ) { return null ; } final Type type = method . getGenericReturnType ( ) ; if ( ! ( type instanceof ParameterizedType ) || ( ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) == null ) || ( ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) . length < 1 ) ) { throw new IllegalArgumentException ( "When using List as return type for method " + method + ", please specify a generic type for the List. Otherwise I do not know which type I should fill the List with." ) ; } int index = Map . class . equals ( returnType ) ? 1 : 0 ; assert index < ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) . length ; Type componentType = ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ index ] ; if ( ! ( componentType instanceof Class ) ) { throw new IllegalArgumentException ( "I don't know how to instantiate the generic type for the return type of method " + method ) ; } return ( Class < ? > ) componentType ; }
When reading collections determine the collection component type .
38,774
public T remove ( final CharSequence xpath ) { if ( ( xpath == null ) || ( xpath . length ( ) == 0 ) ) { throw new IllegalArgumentException ( "Parameter path must not be empty or null" ) ; } domChangeTracker . refreshForReadIfNeeded ( ) ; final Document document = DOMHelper . getOwnerDocumentFor ( baseNode ) ; final DuplexExpression duplexExpression = new DuplexXPathParser ( invocationContext . getProjector ( ) . config ( ) . getUserDefinedNamespaceMapping ( ) ) . compile ( xpath ) ; try { final XPathExpression expression = invocationContext . getProjector ( ) . config ( ) . createXPath ( document ) . compile ( duplexExpression . getExpressionAsStringWithoutFormatPatterns ( ) ) ; Node prevNode = ( Node ) expression . evaluate ( boundNode , XPathConstants . NODE ) ; if ( prevNode == null ) { return null ; } final T value = DefaultXPathEvaluator . convertToComponentType ( invocationContext , prevNode , invocationContext . getTargetComponentType ( ) ) ; duplexExpression . deleteAllMatchingChildren ( prevNode . getParentNode ( ) ) ; return value ; } catch ( XPathExpressionException e ) { throw new XBPathException ( e , xpath ) ; } }
Remove element at relative location .
38,775
public static boolean hasReturnType ( final Method method ) { if ( method == null ) { return false ; } if ( method . getReturnType ( ) == null ) { return false ; } if ( Void . class . equals ( method . getReturnType ( ) ) ) { return false ; } return ! Void . TYPE . equals ( method . getReturnType ( ) ) ; }
Defensive implemented method to determine if method has a return type .
38,776
public static Method getCallableFactoryForParams ( final Class < ? > type , final Class < ? > ... params ) { for ( Method m : type . getMethods ( ) ) { if ( ( m . getModifiers ( ) & PUBLIC_STATIC_MODIFIER ) != PUBLIC_STATIC_MODIFIER ) { continue ; } if ( ! type . isAssignableFrom ( m . getReturnType ( ) ) ) { continue ; } if ( ! Arrays . equals ( m . getParameterTypes ( ) , params ) ) { continue ; } if ( ! VALID_FACTORY_METHOD_NAMES . matcher ( m . getName ( ) ) . matches ( ) ) { continue ; } return m ; } return null ; }
Search for a static factory method returning the target type .
38,777
public static Object unwrap ( final Class < ? > type , final Object object ) throws Exception { if ( object == null ) { return null ; } if ( type == null ) { return object ; } if ( Callable . class . equals ( type ) ) { assert ( object instanceof Callable ) ; return ( ( Callable < ? > ) object ) . call ( ) ; } if ( "java.util.function.Supplier" . equals ( type . getName ( ) ) ) { return findMethodByName ( type , "get" ) . invoke ( object , ( Object [ ] ) null ) ; } return object ; }
Unwrap a given object until we assume it is a value . Supports Callable and Supplier so far .
38,778
public static boolean isOptional ( final Type type ) { if ( OPTIONAL_CLASS == null ) { return false ; } if ( ! ( type instanceof ParameterizedType ) ) { return false ; } return OPTIONAL_CLASS . equals ( ( ( ParameterizedType ) type ) . getRawType ( ) ) ; }
Checks if given type is java . util . Optional with a generic type parameter .
38,779
public static boolean isRawType ( final Type type ) { if ( type instanceof Class ) { final Class < ? > clazz = ( Class < ? > ) type ; return ( clazz . getTypeParameters ( ) . length > 0 ) ; } if ( type instanceof ParameterizedType ) { final ParameterizedType ptype = ( ParameterizedType ) type ; return ( ptype . getActualTypeArguments ( ) . length == 0 ) ; } return false ; }
Checks if a given type is a raw type .
38,780
public static Object createOptional ( final Object value ) { if ( ( OPTIONAL_CLASS == null ) || ( OFNULLABLE == null ) ) { throw new IllegalStateException ( "Unreachable Code executed. You just found a bug. Please report!" ) ; } try { return OFNULLABLE . invoke ( null , value ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( e ) ; } }
Create an instance of java . util . Optional for given value .
38,781
public static void throwThrowable ( final Class < ? > throwableType , final Object [ ] args , final Throwable optionalCause ) throws Throwable { Class < ? > [ ] argsClasses = getClassesOfObjects ( args ) ; Constructor < ? > constructor = ReflectionHelper . getCallableConstructorForParams ( throwableType , argsClasses ) ; Throwable throwable = null ; if ( constructor != null ) { throwable = ( Throwable ) constructor . newInstance ( args ) ; } else { throwable = ( Throwable ) throwableType . newInstance ( ) ; } if ( optionalCause != null ) { throwable . initCause ( optionalCause ) ; } throw throwable ; }
Throws a throwable of type throwableType . The throwable will be created using an args matching constructor or the default constructor if no matching constructor can be found .
38,782
public static Map < String , String > getNamespaceMapping ( final Document document ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "xmlns" , "http://www.w3.org/2000/xmlns/" ) ; map . put ( "xml" , "http://www.w3.org/XML/1998/namespace" ) ; Element root = document . getDocumentElement ( ) ; if ( root == null ) { return map ; } fillNSMapWithPrefixesDeclaredInElement ( map , root ) ; return map ; }
Parse namespace prefixes defined anywhere in the document .
38,783
public static void setDocumentElement ( final Document document , final Element element ) { Element documentElement = document . getDocumentElement ( ) ; if ( documentElement != null ) { document . removeChild ( documentElement ) ; } if ( element != null ) { if ( element . getOwnerDocument ( ) . equals ( document ) ) { document . appendChild ( element ) ; return ; } Node node = document . adoptNode ( element ) ; document . appendChild ( node ) ; } }
Replace the current root element . If element is null the current root element will be removed .
38,784
private static boolean nodeListsAreEqual ( final NodeList a , final NodeList b ) { if ( a == b ) { return true ; } if ( ( a == null ) || ( b == null ) ) { return false ; } if ( a . getLength ( ) != b . getLength ( ) ) { return false ; } for ( int i = 0 ; i < a . getLength ( ) ; ++ i ) { if ( ! nodesAreEqual ( a . item ( i ) , b . item ( i ) ) ) { return false ; } } return true ; }
NodelLists are equal if and only if their size is equal and the containing nodes at the same indexes are equal .
38,785
public static void removeAllChildren ( final Node node ) { assert node != null ; assert node . getNodeType ( ) != Node . ATTRIBUTE_NODE ; if ( node . getNodeType ( ) == Node . DOCUMENT_TYPE_NODE ) { Element documentElement = ( ( Document ) node ) . getDocumentElement ( ) ; if ( documentElement != null ) { ( ( Document ) node ) . removeChild ( documentElement ) ; } return ; } if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { Element element = ( Element ) node ; for ( Node n = element . getFirstChild ( ) ; n != null ; n = element . getFirstChild ( ) ) { element . removeChild ( n ) ; } } }
Simply removes all child nodes .
38,786
public static void setDirectTextContent ( final Node elementToChange , final String asString ) { assert elementToChange . getNodeType ( ) != Node . DOCUMENT_NODE ; if ( Node . ATTRIBUTE_NODE == elementToChange . getNodeType ( ) ) { elementToChange . setTextContent ( asString ) ; return ; } List < Node > nodes = new LinkedList < Node > ( ) ; List < Node > nodes2 = new LinkedList < Node > ( ) ; for ( Node n : nodeListToIterator ( elementToChange . getChildNodes ( ) ) ) { if ( Node . TEXT_NODE == n . getNodeType ( ) ) { continue ; } nodes . add ( n ) ; } if ( ( asString != null ) && ( ! asString . isEmpty ( ) ) ) { elementToChange . setTextContent ( asString ) ; for ( Node n : nodeListToIterator ( elementToChange . getChildNodes ( ) ) ) { if ( Node . TEXT_NODE != n . getNodeType ( ) ) { continue ; } nodes . add ( n ) ; } } removeAllChildren ( elementToChange ) ; for ( Node n : nodes ) { elementToChange . appendChild ( n ) ; } for ( Node n : nodes2 ) { elementToChange . appendChild ( n ) ; } }
Set text content of given element without removing existing child nodes . Text nodes are added after child element nodes always .
38,787
private static void addRequestProperties ( final Map < String , String > requestProperties , final HttpURLConnection connection ) { if ( requestProperties != null ) { for ( Entry < String , String > entry : requestProperties . entrySet ( ) ) { connection . addRequestProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } }
Copies request properties to a connection .
38,788
public static Map < String , String > createBasicAuthenticationProperty ( final String username , final String password ) { Map < String , String > map = new TreeMap < String , String > ( ) ; try { String base64Binary = DatatypeConverter . printBase64Binary ( ( username + ":" + password ) . getBytes ( "US-ASCII" ) ) ; map . put ( "Authorization" , "Basic " + base64Binary ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } return map ; }
Create HTTP Basic credentials to be used in HTTP get or post methods .
38,789
public static byte [ ] dropUTF8BOM ( final byte [ ] source ) { if ( source == null ) { return null ; } if ( source . length < 3 ) { return source ; } if ( ( source [ 0 ] == ( byte ) 0xef ) && ( source [ 1 ] == ( byte ) 0xbb ) && ( source [ 2 ] == ( byte ) 0xbf ) ) { return Arrays . copyOfRange ( source , 3 , source . length ) ; } return source ; }
Silently drop UTF8 BOM
38,790
public < T > T read ( final Class < T > projectionInterface ) throws IOException { try { Document document = projector . config ( ) . createDocumentBuilder ( ) . parse ( file ) ; return projector . projectDOMNode ( document , projectionInterface ) ; } catch ( SAXException e ) { throw new XBDocumentParsingException ( e ) ; } }
Read a XML document and return a projection to it .
38,791
public FileIO setAppend ( final boolean ... append ) { this . append = ( append != null ) && ( ( append . length == 0 ) || ( ( append . length > 0 ) && append [ 0 ] ) ) ; return this ; }
Set whether output should be append to existing file . When this method is not invoked or invoked with false The file will be replaced on writing operations .
38,792
private void configureProcessName ( ) throws XPathExpressionException { if ( processName != null ) { return ; } processName = "" ; Node jvm = getXmlNode ( "/jmxetric-config/jvm" , inputSource ) ; if ( jvm != null ) { processName = jvm . getAttributes ( ) . getNamedItem ( "process" ) . getNodeValue ( ) ; } }
The XML file may specify a processName to be used which can be different from the one used in the constructor . The name in XML takes priority .
38,793
private void addMBeanAttributeToSampler ( MBeanSampler mBeanSampler , String mBeanName , MBeanAttribute mBeanAttribute ) throws Exception { if ( mBeanAttribute . getSampler ( ) == null ) { mBeanAttribute . setSampler ( mBeanSampler ) ; } mBeanSampler . addMBeanAttribute ( mBeanName , mBeanAttribute ) ; }
Adds a MBeanAttribute to an MBeanSampler . This also checks if the MBeanAttribute to be added already has a MBeanSampler set if not it will set it .
38,794
private int parseDMax ( String dMaxString ) { int dMax ; try { dMax = Integer . parseInt ( dMaxString ) ; } catch ( NumberFormatException e ) { dMax = 0 ; } return dMax ; }
Parses dMaxString which is the value of dmax read in from a configuration file .
38,795
private String buildMetricName ( String process , String mbeanName , String mbeanPublishName , String attribute , String attrPublishName ) { StringBuilder buf = new StringBuilder ( ) ; if ( process != null ) { buf . append ( process ) ; buf . append ( "_" ) ; } if ( mbeanPublishName != null ) { buf . append ( mbeanPublishName ) ; } else { buf . append ( mbeanName ) ; } buf . append ( "_" ) ; if ( ! "" . equals ( attrPublishName ) ) { buf . append ( attrPublishName ) ; } else { buf . append ( attribute ) ; } return buf . toString ( ) ; }
Builds the metric name in ganglia
38,796
public static void main ( String [ ] args ) { PrintStream out = System . out ; if ( args . length > 0 ) { try { out = new PrintStream ( new File ( args [ 0 ] ) ) ; } catch ( FileNotFoundException e ) { System . out . printf ( ERR_FILE , args [ 0 ] ) ; } } MBeanScanner mBeanScanner = new MBeanScanner ( ) ; List < Config > configs = mBeanScanner . scan ( ) ; ConfigWriter cw ; cw = new ConfigWriter ( out , configs ) ; cw . write ( ) ; }
Used mainly for testing purposed to output a test configuration file to System . out . Also shows how to use this class .
38,797
public List < Config > scan ( ) { Set < ObjectInstance > mBeanObjects = mBeanServer . queryMBeans ( null , null ) ; List < Config > configs = getConfigForAllMBeans ( mBeanObjects ) ; return configs ; }
Scans the platform MBean server for registered MBeans creating see Config objects to represent these MBeans .
38,798
private List < Config > getConfigForAllMBeans ( Set < ObjectInstance > mBeanObjects ) { List < Config > configs = new Vector < Config > ( ) ; for ( ObjectInstance objectInstance : mBeanObjects ) { Config configMB = scanOneMBeanObject ( objectInstance ) ; configs . add ( configMB ) ; } return configs ; }
Constructs a configuration for all MBeans .
38,799
private void scanMBeanAttributes ( MBeanConfig mBeanConfig , ObjectName mBeanName ) { MBeanInfo mBeanInfo ; try { mBeanInfo = mBeanServer . getMBeanInfo ( mBeanName ) ; MBeanAttributeInfo [ ] infos = mBeanInfo . getAttributes ( ) ; for ( int i = 0 ; i < infos . length ; i ++ ) { MBeanAttributeConfig cMBAttr = makeConfigMBeanAttribute ( mBeanName , infos [ i ] ) ; mBeanConfig . addChild ( cMBAttr ) ; } } catch ( IntrospectionException e ) { System . err . println ( e . getMessage ( ) ) ; } catch ( InstanceNotFoundException e ) { System . err . println ( e . getMessage ( ) ) ; } catch ( ReflectionException e ) { System . err . println ( e . getMessage ( ) ) ; } }
Stores all attributes of an MBean into its MBeanConfig object