idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
137,800
public static boolean isXMLNameStart ( int codepoint ) { if ( codepoint >= Character . codePointAt ( "A" , 0 ) && codepoint <= Character . codePointAt ( "Z" , 0 ) ) { return true ; } else if ( codepoint == Character . codePointAt ( "_" , 0 ) ) { return true ; } else if ( codepoint >= Character . codePointAt ( "a" , 0 ) && codepoint <= Character . codePointAt ( "z" , 0 ) ) { return true ; } else if ( codepoint >= 0xC0 && codepoint <= 0xD6 ) { return true ; } else if ( codepoint >= 0xD8 && codepoint <= 0xF6 ) { return true ; } else if ( codepoint >= 0xF8 && codepoint <= 0x2FF ) { return true ; } else if ( codepoint >= 0x370 && codepoint <= 0x37D ) { return true ; } else if ( codepoint >= 0x37F && codepoint <= 0x1FFF ) { return true ; } else if ( codepoint >= 0x200C && codepoint <= 0x200D ) { return true ; } else if ( codepoint >= 0x2070 && codepoint <= 0x218F ) { return true ; } else if ( codepoint >= 0x2C00 && codepoint <= 0x2FEF ) { return true ; } else if ( codepoint >= 0x3001 && codepoint <= 0xD7FF ) { return true ; } else if ( codepoint >= 0xF900 && codepoint <= 0xFDCF ) { return true ; } else if ( codepoint >= 0xFDF0 && codepoint <= 0xFFFD ) { return true ; } else if ( codepoint >= 0x10000 && codepoint <= 0xEFFFF ) { return true ; } else { return false ; } }
Determine if the given character is a legal starting character for an XML name . Note that although a colon is a legal value its use is strongly discouraged and this method will return false for a colon .
445
41
137,801
public static boolean isXMLNamePart ( int codepoint ) { if ( isXMLNameStart ( codepoint ) ) { return true ; } else if ( codepoint >= Character . codePointAt ( "0" , 0 ) && codepoint <= Character . codePointAt ( "9" , 0 ) ) { return true ; } else if ( codepoint == Character . codePointAt ( "-" , 0 ) ) { return true ; } else if ( codepoint == Character . codePointAt ( "." , 0 ) ) { return true ; } else if ( codepoint == 0xB7 ) { return true ; } else if ( codepoint >= 0x0300 && codepoint <= 0x036F ) { return true ; } else if ( codepoint >= 0x203F && codepoint <= 0x2040 ) { return true ; } else { return false ; } }
Determine if the given character is a legal non - starting character for an XML name . Note that although a colon is a legal value its use is strongly discouraged and this method will return false for a colon .
199
43
137,802
public static boolean isValidXMLCharacter ( int codepoint ) { // Most of the time the character will be valid. Order the tests such // that most valid characters will be found in the minimum number of // tests. if ( codepoint >= 0x20 && codepoint <= 0xD7FF ) { return true ; } else if ( codepoint == 0x9 || codepoint == 0xA || codepoint == 0xD ) { return true ; } else if ( codepoint >= 0xE000 && codepoint <= 0xFFFD ) { return true ; } else if ( codepoint >= 0x10000 && codepoint <= 0x10FFFF ) { return true ; } else { return false ; } }
Determine if a given UNICODE character can appear in a valid XML file . The allowed characters are 0x9 0xA 0xD 0x20 - 0xD7FF 0xE000 - 0xFFFD and 0x100000 - 0x10FFFF ; all other characters may not appear in an XML file .
161
71
137,803
public static boolean isValidXMLName ( String s ) { // Catch the empty string or null. if ( s == null || "" . equals ( s ) ) { return false ; } // Since the string isn't empty, check that the first character is a // valid starting character. if ( ! isXMLNameStart ( s . codePointAt ( 0 ) ) ) { return false ; } // Loop through the string by UNICODE codepoints. This is NOT equivalent // to looping through the characters because some UNICODE codepoints can // occupy more than one character. int length = s . length ( ) ; int index = 1 ; while ( index < length ) { int codePoint = s . codePointAt ( index ) ; if ( ! isXMLNamePart ( codePoint ) ) { return false ; } index += Character . charCount ( codePoint ) ; } // Names that begin with "xml" with letters in any case are reserved by // the XML specification. if ( s . toLowerCase ( ) . startsWith ( "xml" ) ) { return false ; } // If we get here then all of the characters have been checked and are // valid. Unfortunately the usual case takes the longest to verify. return true ; }
Determine if the given string is a valid XML name .
265
13
137,804
public static boolean isValidXMLString ( String s ) { int length = s . length ( ) ; // Loop through the string by UNICODE codepoints. This is NOT equivalent // to looping through the characters because some UNICODE codepoints can // occupy more than one character. int index = 0 ; while ( index < length ) { int codePoint = s . codePointAt ( index ) ; if ( ! isValidXMLCharacter ( codePoint ) ) { return false ; } index += Character . charCount ( codePoint ) ; } // If we get here then all of the characters have been checked and are // valid. Unfortunately the usual case takes the longest to verify. return true ; }
Determine if the given string can be written to an XML file without encoding . This will be the case so long as the string does not contain illegal XML characters .
151
34
137,805
public static String encodeAsXMLName ( String s ) { StringBuilder sb = new StringBuilder ( "_" ) ; for ( byte b : s . getBytes ( Charset . forName ( "UTF-8" ) ) ) { sb . append ( Integer . toHexString ( ( b >>> 4 ) & 0xF ) ) ; sb . append ( Integer . toHexString ( b & 0xF ) ) ; } return sb . toString ( ) ; }
This will encode the given string as a valid XML name . The format will be an initial underscore followed by the hexadecimal representation of the string .
107
31
137,806
public String formatErrors ( ) { if ( errors . size ( ) > 0 ) { StringBuilder results = new StringBuilder ( ) ; for ( Throwable t : errors ) { results . append ( t . getMessage ( ) ) ; results . append ( "\n" ) ; if ( t instanceof NullPointerException || t instanceof CompilerError ) { results . append ( formatStackTrace ( t ) ) ; } else if ( t instanceof SystemException ) { results . append ( formatStackTrace ( t ) ) ; Throwable cause = t . getCause ( ) ; if ( cause != null ) { results . append ( "\nCause:\n" ) ; results . append ( cause . getMessage ( ) ) ; results . append ( "\n" ) ; } results . append ( formatStackTrace ( t ) ) ; } } return results . toString ( ) ; } else { return null ; } }
Format the exceptions thrown during the compilation process . A null value will be returned if no exceptions were thrown .
197
21
137,807
private void init ( ) { this . setOrientation ( LinearLayout . VERTICAL ) ; mLayoutParams = new LayoutParams ( ViewGroup . LayoutParams . MATCH_PARENT , ViewGroup . LayoutParams . WRAP_CONTENT ) ; }
Initialize the view .
59
5
137,808
public static void createParentDirectories ( File file ) { File parent = file . getParentFile ( ) ; if ( ! parent . isDirectory ( ) ) { // Test the creation separately as there appears to be a race // condition that causes unit tests to sometimes fail. boolean created = parent . mkdirs ( ) ; if ( ! created && ! parent . isDirectory ( ) ) { throw new SystemException ( MessageUtils . format ( MSG_CANNOT_CREATE_OUTPUT_DIRECTORY , parent . getAbsolutePath ( ) ) , parent ) ; } } }
Creates parent directories of the given file . The file must be absolute .
124
15
137,809
protected static void checkStaticIndexes ( SourceRange sourceRange , Operation ... operations ) throws SyntaxException { for ( int i = 0 ; i < operations . length ; i ++ ) { if ( operations [ i ] instanceof Element ) { try { TermFactory . create ( ( Element ) operations [ i ] ) ; } catch ( EvaluationException ee ) { throw SyntaxException . create ( sourceRange , MSG_INVALID_TERM , i ) ; } } } }
Ensure that any constant indexes in the operation list are valid terms .
101
14
137,810
protected void validName ( String name ) throws SyntaxException { for ( String varName : automaticVariables ) { if ( varName . equals ( name ) ) { throw SyntaxException . create ( getSourceRange ( ) , MSG_AUTO_VAR_CANNOT_BE_SET , varName ) ; } } }
A utility method to determine if the variable name collides with one of the reserved automatic variables .
70
19
137,811
private String getVersion ( boolean verbose ) { try { InputStream stream = getClass ( ) . getResourceAsStream ( "/version.properties" ) ; Properties props = new Properties ( ) ; props . load ( stream ) ; if ( verbose ) { return String . format ( "Version=%s, build date=%s" , props . getProperty ( "version" ) , props . getProperty ( "buildDate" ) ) ; } else { return props . getProperty ( "version" ) ; } } catch ( IOException e ) { log . error ( "Unable to retrieve version" , e ) ; return "unknown" ; } }
Retrieve the current version .
139
6
137,812
private void setDefaults ( ) { if ( xsdInput == null ) { setXsdInput ( DEFAULT_INPUT_FOLDER_PATH ) ; } if ( output == null ) { setOutput ( DEFAULT_OUTPUT_FOLDER_PATH ) ; } if ( avroNamespacePrefix == null ) { setAvroNamespacePrefix ( DEFAULT_AVRO_NAMESPACE_PREFIX ) ; } }
Make sure mandatory parameters have default values .
99
8
137,813
private void applyMax ( Dimension dim ) { if ( getMaxHeight ( ) > 0 ) { dim . height = Math . min ( dim . height , getMaxHeight ( ) ) ; } if ( getMaxWidth ( ) > 0 ) { dim . width = Math . min ( dim . width , getMaxWidth ( ) ) ; } }
Applies the maximum height and width to the dimension .
72
11
137,814
protected void analyzeElVars ( final T descriptor , final DescriptorContext context ) { descriptor . el = ElAnalyzer . analyzeQuery ( context . generics , descriptor . command ) ; }
Analyze query string for el variables and creates el descriptor .
41
12
137,815
protected void analyzeParameters ( final T descriptor , final DescriptorContext context ) { final CommandParamsContext paramsContext = new CommandParamsContext ( context ) ; spiService . process ( descriptor , paramsContext ) ; }
Analyze method parameters search for extensions and prepare parameters context .
47
12
137,816
private void wrapText ( ) { if ( getFont ( ) == null || text == null ) { return ; } FontMetrics fm = getFontMetrics ( getFont ( ) ) ; StringBuilder tempText = new StringBuilder ( ) ; StringBuilder finalText = new StringBuilder ( "<html>" ) ; finalText . append ( "<STYLE type='text/css'>BODY { text-align: " ) ; finalText . append ( align . name ( ) . toLowerCase ( ) ) ; finalText . append ( "}</STYLE><BODY>" ) ; ArrayList < String > words = new ArrayList < String > ( ) ; text = text . replaceAll ( "\n" , "<BR>" ) ; String split [ ] = text . split ( "<BR>" ) ; for ( int i = 0 ; i < split . length ; i ++ ) { if ( split [ i ] . length ( ) > 0 ) { String split2 [ ] = split [ i ] . split ( "[ \\t\\x0B\\f\\r]+" ) ; for ( int j = 0 ; j < split2 . length ; j ++ ) { if ( split2 [ j ] . length ( ) > 0 ) { words . add ( split2 [ j ] ) ; } } } if ( i < split . length - 1 ) { words . add ( "<BR>" ) ; } } for ( String word : words ) { if ( word . equals ( "<BR>" ) ) { finalText . append ( "<BR>" ) ; tempText . setLength ( 0 ) ; } else { tempText . append ( " " ) ; tempText . append ( word ) ; int tempWidth = SwingUtilities . computeStringWidth ( fm , tempText . toString ( ) . trim ( ) ) ; if ( ( wrapWidth > 0 && tempWidth > wrapWidth ) ) { int wordSize = SwingUtilities . computeStringWidth ( fm , word ) ; if ( wordSize >= wrapWidth ) { finalText . append ( "..." ) ; break ; } finalText . append ( "<BR>" ) ; tempText . setLength ( 0 ) ; tempText . append ( word ) ; } if ( tempText . length ( ) > 0 ) { finalText . append ( " " ) ; } finalText . append ( word ) ; } } finalText . append ( "</BODY></html>" ) ; super . setText ( finalText . toString ( ) ) ; }
The plain text is converted to HTML code . The wrap locations are calculated with the defined wrap width and component width .
531
23
137,817
public void checkFieldsCompatible ( final String ... fields ) { final Set < String > indexFields = Sets . newHashSet ( index . getDefinition ( ) . getFields ( ) ) ; final Joiner joiner = Joiner . on ( "," ) ; check ( indexFields . equals ( Sets . newHashSet ( fields ) ) , "Existing index '%s' (class '%s') fields '%s' are different from '%s'." , index . getName ( ) , index . getDefinition ( ) . getClassName ( ) , joiner . join ( indexFields ) , joiner . join ( fields ) ) ; }
Checks if existing index consists of exactly the same fields . If not error thrown to indicate probable programmer error .
143
22
137,818
public void dropIndex ( final ODatabaseObject db ) { final String name = index . getName ( ) ; logger . info ( "Dropping existing index '{}' (class '{}'), because of definition mismatch" , name , index . getDefinition ( ) . getClassName ( ) ) ; SchemeUtils . dropIndex ( db , name ) ; }
Drops index .
77
4
137,819
@ SuppressWarnings ( "PMD.LinguisticNaming" ) public IndexMatchVerifier isIndexSigns ( final Object ... signs ) { final List < Object > idxsigns = Lists . newArrayList ( ) ; idxsigns . add ( index . getType ( ) ) ; idxsigns . addAll ( Arrays . asList ( signs ) ) ; return new IndexMatchVerifier ( idxsigns ) ; }
Compares current index configuration with new signature . Used to decide if index should be dropped and re - created or its completely equal to new signature .
99
29
137,820
public static Class < ? extends CobolContext > getInputKeyCobolContext ( Configuration conf ) { return conf . getClass ( CONF_INPUT_KEY_COBOL_CONTEXT , null , CobolContext . class ) ; }
Gets the job input key mainframe COBOL parameters .
53
13
137,821
public static void setInputKeyRecordType ( Job job , Class < ? extends CobolComplexType > cobolType ) { job . getConfiguration ( ) . setClass ( CONF_INPUT_KEY_RECORD_TYPE , cobolType , CobolComplexType . class ) ; }
Sets the job input key mainframe record type .
64
11
137,822
public static Class < ? extends CobolComplexType > getInputKeyRecordType ( Configuration conf ) { return conf . getClass ( CONF_INPUT_KEY_RECORD_TYPE , null , CobolComplexType . class ) ; }
Gets the job input key mainframe record type .
53
11
137,823
public static void setInputRecordMatcher ( Job job , Class < ? extends CobolTypeFinder > matcherClass ) { job . getConfiguration ( ) . setClass ( CONF_INPUT_RECORD_MATCHER_CLASS , matcherClass , CobolTypeFinder . class ) ; }
Sets the job input record matcher class .
66
10
137,824
public static Class < ? extends CobolTypeFinder > getInputRecordMatcher ( Configuration conf ) { return conf . getClass ( CONF_INPUT_RECORD_MATCHER_CLASS , null , CobolTypeFinder . class ) ; }
Gets the job input record matcher class .
55
10
137,825
public static void setInputChoiceStrategy ( Job job , Class < ? extends FromCobolChoiceStrategy > choiceStrategyClass ) { job . getConfiguration ( ) . setClass ( CONF_INPUT_RECORD_CHOICE_STRATEGY_CLASS , choiceStrategyClass , FromCobolChoiceStrategy . class ) ; }
Sets the job input record choice strategy class .
75
10
137,826
public static Class < ? extends FromCobolChoiceStrategy > getInputChoiceStrategy ( Configuration conf ) { return conf . getClass ( CONF_INPUT_RECORD_CHOICE_STRATEGY_CLASS , null , FromCobolChoiceStrategy . class ) ; }
Gets the job input record choice strategy class .
62
10
137,827
public int readFully ( byte b [ ] , int off , int len ) throws IOException { IOUtils . readFully ( inStream , b , off , len ) ; return len ; }
Read a number of bytes from the input stream blocking until all requested bytes are read or end of file is reached .
44
23
137,828
public int read ( byte b [ ] , int off , int len ) throws IOException { return IOUtils . read ( inStream , b , off , len ) ; }
Same as above but does not throw an exception at end of file just returns the actual data read .
38
20
137,829
public void addNamedParam ( final String name , final ParamInfo paramInfo ) { check ( ! named . containsKey ( name ) , "Duplicate parameter %s declaration at position %s" , name , paramInfo . position ) ; named . put ( name , paramInfo ) ; }
Register parameter as named .
62
5
137,830
public void addStaticElVarValue ( final String name , final String value ) { check ( ! staticElValues . containsKey ( name ) , "Duplicate el variable %s value declaration: %s (original: %s)" , name , value , staticElValues . get ( name ) ) ; check ( ! dynamicElValues . contains ( name ) , "El variable %s can't be registered as static, because dynamic declaration already defined" , name ) ; staticElValues . put ( name , value ) ; }
Register static query el variable value .
110
7
137,831
public void addDynamicElVarValue ( final String name ) { check ( ! dynamicElValues . contains ( name ) , "Duplicate dynamic el variable %s declaration" , name ) ; check ( ! staticElValues . containsKey ( name ) , "El variable %s can't be registered as dynamic, because static declaration already defined" , name ) ; dynamicElValues . add ( name ) ; }
Register dynamic query el variable value . Variable will be completely handled by extension . Registration is required to validated not handled variables .
85
24
137,832
private String generateXmlSchema ( Reader cobolReader , String targetNamespace , String targetXmlSchemaName , final String xsltFileName ) { log . debug ( "XML schema {} generation started" , targetXmlSchemaName + XSD_FILE_EXTENSION ) ; String xmlSchemaSource = cob2xsd . translate ( cobolReader , NamespaceUtils . toNamespace ( targetNamespace ) , xsltFileName ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Generated Cobol-annotated XML Schema: " ) ; log . debug ( xmlSchemaSource ) ; } log . debug ( "XML schema {} generation ended" , targetXmlSchemaName + XSD_FILE_EXTENSION ) ; return xmlSchemaSource ; }
Translate the COBOL copybook to XML Schema .
181
13
137,833
private Map < String , String > generateConverterClasses ( String xmlSchemaSource , String targetPackageName ) { log . debug ( "Converter support classes generation started" ) ; Map < String , String > codeMap = xsd2CobolTypes . generate ( new StringReader ( xmlSchemaSource ) , targetPackageName ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Generated converter support classes: " ) ; for ( String code : codeMap . values ( ) ) { log . debug ( code ) ; log . debug ( "\n" ) ; } } log . debug ( "Converter support classes generation ended" ) ; return codeMap ; }
Produce the LegStar converter support classes .
151
9
137,834
private String generateAvroSchema ( String xmlSchemaSource , String targetPackageName , String targetAvroSchemaName ) throws IOException { log . debug ( "Avro schema {} generation started" , targetAvroSchemaName + AVSC_FILE_EXTENSION ) ; String avroSchemaSource = cob2AvroTranslator . translate ( new StringReader ( xmlSchemaSource ) , targetPackageName , targetAvroSchemaName ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Generated Avro Schema: " ) ; log . debug ( avroSchemaSource ) ; } log . debug ( "Avro schema {} generation ended" , targetAvroSchemaName + AVSC_FILE_EXTENSION ) ; return avroSchemaSource ; }
Produce the avro schema .
175
7
137,835
private void avroCompile ( String avroSchemaSource , File avroSchemaFile , File javaTargetFolder ) throws IOException { log . debug ( "Avro compiler started for: {}" , avroSchemaFile ) ; Schema . Parser parser = new Schema . Parser ( ) ; Schema schema = parser . parse ( avroSchemaSource ) ; SpecificCompiler compiler = new CustomSpecificCompiler ( schema ) ; compiler . setStringType ( StringType . CharSequence ) ; compiler . compileToDestination ( avroSchemaFile , javaTargetFolder ) ; log . debug ( "Avro compiler ended for: {}" , avroSchemaFile ) ; }
Given an Avro schema produce java specific classes .
150
10
137,836
public static TxConfig buildConfig ( final Class < ? > type , final Method method , final boolean useDefaults ) { final Transactional transactional = findAnnotation ( type , method , Transactional . class , useDefaults ) ; TxConfig res = null ; if ( transactional != null ) { final TxType txType = findAnnotation ( type , method , TxType . class , true ) ; res = new TxConfig ( wrapExceptions ( transactional . rollbackOn ( ) ) , wrapExceptions ( transactional . ignore ( ) ) , txType . value ( ) ) ; } return res ; }
Build transaction config for type .
137
6
137,837
private static List < Class < ? extends Exception > > wrapExceptions ( final Class < ? extends Exception > ... list ) { return list . length == 0 ? null : Arrays . asList ( list ) ; }
Avoid creation of empty list .
45
6
137,838
public void setTitleGaps ( int gapBetweenIconAndTitle , int gapBetweenTitleAndComponents , int gapBetweenComponents ) { gapBetweenIconAndTitle = Math . max ( gapBetweenIconAndTitle , 0 ) ; gapBetweenTitleAndComponents = Math . max ( gapBetweenTitleAndComponents , 0 ) ; gapBetweenComponents = Math . max ( gapBetweenComponents , 0 ) ; rebuild ( ) ; }
Defines the title gaps
91
5
137,839
public static void checkExec ( final boolean condition , final String message , final Object ... args ) { if ( ! condition ) { throw new MethodExecutionException ( String . format ( message , args ) ) ; } }
Shortcut to check and throw execution exception .
45
9
137,840
public static List < String > findVars ( final String str ) { final List < String > vars = new ArrayList < String > ( ) ; final char [ ] strArray = str . toCharArray ( ) ; int i = 0 ; while ( i < strArray . length - 1 ) { if ( strArray [ i ] == VAR_START && strArray [ i + 1 ] == VAR_LEFT_BOUND ) { i = i + 2 ; final int begin = i ; while ( strArray [ i ] != VAR_RIGHT_BOUND ) { ++ i ; } final String var = str . substring ( begin , i ++ ) ; if ( ! vars . contains ( var ) ) { vars . add ( var ) ; } } else { ++ i ; } } return vars ; }
Analyze string for variables .
179
6
137,841
public static String replace ( final String str , final Map < String , String > params ) { final StringBuilder sb = new StringBuilder ( str . length ( ) ) ; final char [ ] strArray = str . toCharArray ( ) ; int i = 0 ; while ( i < strArray . length - 1 ) { if ( strArray [ i ] == VAR_START && strArray [ i + 1 ] == VAR_LEFT_BOUND ) { i = i + 2 ; final int begin = i ; while ( strArray [ i ] != VAR_RIGHT_BOUND ) { ++ i ; } final String var = str . substring ( begin , i ++ ) ; Preconditions . checkState ( params . containsKey ( var ) , "No value provided for variable '%s' " + "in string '%s'" , var , str ) ; final String value = params . get ( var ) . trim ( ) ; sb . append ( value ) ; } else { sb . append ( strArray [ i ] ) ; ++ i ; } } if ( i < strArray . length ) { sb . append ( strArray [ i ] ) ; } return sb . toString ( ) ; }
Replace placeholders in string .
265
7
137,842
public static void validate ( final String string , final List < String > params ) { final List < String > vars = findVars ( string ) ; for ( String param : params ) { Preconditions . checkState ( vars . contains ( param ) , "Variable '%s' not found in target string '%s'" , param , string ) ; } vars . removeAll ( params ) ; Preconditions . checkState ( vars . isEmpty ( ) , "No parameter binding defined for variables '%s' from string '%s'" , Joiner . on ( ' ' ) . join ( vars ) , string ) ; }
Validate string variables and declared values for correctness .
138
10
137,843
private void expand ( boolean immediately ) { if ( locked == false && inAction == false && collapsed ) { inAction = true ; CollapsiblePanelListener [ ] array = listeners . getListeners ( CollapsiblePanelListener . class ) ; for ( CollapsiblePanelListener cpl : array ) { cpl . panelWillExpand ( new CollapsiblePanelEvent ( this ) ) ; } pixels = incremental ; if ( isAnimationEnabled ( ) && immediately == false ) { calculatedHeight = getSize ( ) . height ; if ( isFillMode ( ) ) { setEndHeights ( ) ; } else { endHeight = getPreferredSize ( false ) . height ; } getExpandTimer ( ) . start ( ) ; } else { changeStatus ( ) ; } } }
Expand the panel .
166
5
137,844
public void setReverseLayout ( boolean reverseLayout ) { if ( mPendingSavedState != null && mPendingSavedState . mReverseLayout != reverseLayout ) { // override pending state mPendingSavedState . mReverseLayout = reverseLayout ; } if ( reverseLayout == mReverseLayout ) { return ; } mReverseLayout = reverseLayout ; requestLayout ( ) ; }
Used to reverse item traversal and layout order . This behaves similar to the layout change for RTL views . When set to true first item is rendered at the end of the UI second item is render before it etc .
92
44
137,845
public static void command ( final ODatabaseObject db , final String command , final Object ... args ) { db . command ( new OCommandSQL ( String . format ( command , args ) ) ) . execute ( ) ; }
Calls schema change sql command .
46
7
137,846
@ SuppressFBWarnings ( "RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT" ) public static void dropIndex ( final ODatabaseObject db , final String indexName ) { // Separated to overcome findbugs false positive "RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT" for dropIndex method. db . getMetadata ( ) . getIndexManager ( ) . dropIndex ( indexName ) ; }
Drops named index . Safe to call even if index not exist .
104
14
137,847
private void configureCustomTypes ( ) { // empty binding is required in any case final Multibinder < OObjectSerializer > typesBinder = Multibinder . newSetBinder ( binder ( ) , OObjectSerializer . class ) ; if ( ! customTypes . isEmpty ( ) ) { for ( Class < ? extends OObjectSerializer > type : customTypes ) { bind ( type ) . in ( Singleton . class ) ; typesBinder . addBinding ( ) . to ( type ) ; } } }
Binds registered custom types as guice singletons and register them with multibinder .
112
19
137,848
protected void loadOptionalPool ( final String poolBinder ) { try { final Method bindPool = OrientModule . class . getDeclaredMethod ( "bindPool" , Class . class , Class . class ) ; bindPool . setAccessible ( true ) ; try { Class . forName ( poolBinder ) . getConstructor ( OrientModule . class , Method . class , Binder . class ) . newInstance ( this , bindPool , binder ( ) ) ; } finally { bindPool . setAccessible ( false ) ; } } catch ( Exception ignored ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Failed to process pool loader " + poolBinder , ignored ) ; } } }
Allows to load pool only if required jars are in classpath . For example no need for graph dependencies if only object db is used .
155
27
137,849
@ SuppressWarnings ( "unchecked" ) private static boolean isParametersCompatible ( final List < Class < ? > > params , final List < ParamInfo > ordinalParamInfos ) { boolean resolution = params . size ( ) == ordinalParamInfos . size ( ) ; if ( resolution && ! params . isEmpty ( ) ) { final Iterator < Class < ? > > paramsIt = params . iterator ( ) ; final Iterator < ParamInfo > targetIt = ordinalParamInfos . iterator ( ) ; while ( paramsIt . hasNext ( ) ) { final Class < ? > type = paramsIt . next ( ) ; final ParamInfo paramInfo = targetIt . next ( ) ; if ( ! paramInfo . type . isAssignableFrom ( type ) ) { resolution = false ; break ; } } } return resolution ; }
Checking method parameters compatibility .
182
6
137,850
public static ElDescriptor analyzeQuery ( final GenericsContext genericsContext , final String query ) { final List < String > vars = ElUtils . findVars ( query ) ; ElDescriptor descriptor = null ; if ( ! vars . isEmpty ( ) ) { descriptor = new ElDescriptor ( vars ) ; checkGenericVars ( descriptor , genericsContext ) ; } return descriptor ; }
Analyze query string for variables .
90
7
137,851
public static void check ( final boolean condition , final String message , final Object ... args ) { if ( ! condition ) { throw new MethodDefinitionException ( String . format ( message , args ) ) ; } }
Shortcut to check and throw definition exception .
43
9
137,852
private static Object jdk8 ( final Class < ? > type , final Object object ) { try { // a bit faster than resolving it each time if ( jdk8OptionalFactory == null ) { lookupOptionalFactoryMethod ( type ) ; } return jdk8OptionalFactory . invoke ( null , object ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Failed to instantiate jdk Optional" , e ) ; } }
Only this will cause optional class loading and fail for earlier jdk .
93
14
137,853
public void setEngineConfigMap ( Map < String , Object > engineConfigMap ) { if ( engineConfigMap != null ) { this . engineConfig . putAll ( engineConfigMap ) ; } }
Set Rythm properties as Map to allow for non - String values like ds . resource . loader . instance .
42
23
137,854
public RythmEngine createRythmEngine ( ) throws IOException , RythmException { Map < String , Object > p = new HashMap < String , Object > ( ) ; p . put ( RythmConfigurationKey . ENGINE_PLUGIN_VERSION . getKey ( ) , Version . VALUE ) ; // Load config file if set. if ( this . configLocation != null ) { logger . info ( "Loading Rythm config from [%s]" , this . configLocation ) ; CollectionUtils . mergePropertiesIntoMap ( PropertiesLoaderUtils . loadProperties ( this . configLocation ) , p ) ; } // Merge local properties if set. if ( ! this . engineConfig . isEmpty ( ) ) { p . putAll ( this . engineConfig ) ; } // Set dev mode if ( null == devMode ) { // check if devMode is set in engineConfig String k = RythmConfigurationKey . ENGINE_MODE . getKey ( ) ; if ( p . containsKey ( k ) ) { String s = p . get ( k ) . toString ( ) ; devMode = Rythm . Mode . dev . name ( ) . equalsIgnoreCase ( s ) ; } else { devMode = getDevModeFromDevModeSensor ( ) ; } } Rythm . Mode mode = devMode ? Rythm . Mode . dev : Rythm . Mode . prod ; p . put ( RythmConfigurationKey . ENGINE_MODE . getKey ( ) , mode ) ; // Cache p . put ( RythmConfigurationKey . CACHE_ENABLED . getKey ( ) , enableCache ) ; // Set a resource loader path, if required. List < ITemplateResourceLoader > loaders = null ; if ( this . resourceLoaderPath != null ) { loaders = new ArrayList < ITemplateResourceLoader > ( ) ; String [ ] paths = StringUtils . commaDelimitedListToStringArray ( resourceLoaderPath ) ; for ( String path : paths ) { loaders . add ( new SpringResourceLoader ( path , resourceLoader ) ) ; } p . put ( RythmConfigurationKey . RESOURCE_LOADER_IMPLS . getKey ( ) , loaders ) ; p . put ( RythmConfigurationKey . RESOURCE_DEF_LOADER_ENABLED . getKey ( ) , false ) ; } // the i18 message resolver ApplicationContext ctx = getApplicationContext ( ) ; if ( null != ctx ) { SpringI18nMessageResolver i18n = new SpringI18nMessageResolver ( ) ; i18n . setApplicationContext ( getApplicationContext ( ) ) ; p . put ( RythmConfigurationKey . I18N_MESSAGE_RESOLVER . getKey ( ) , i18n ) ; } configRythm ( p ) ; // Apply properties to RythmEngine. RythmEngine engine = newRythmEngine ( p ) ; if ( null != loaders ) { for ( ITemplateResourceLoader loader : loaders ) { loader . setEngine ( engine ) ; } } postProcessRythmEngine ( engine ) ; return engine ; }
Prepare the RythmEngine instance and return it .
671
11
137,855
private static int getRecordLen ( byte [ ] hostData , int start , int length ) { int len = getRawRdw ( hostData , start , length ) ; if ( len < RDW_LEN || len > hostData . length ) { throw new IllegalArgumentException ( "Record does not start with a Record Descriptor Word" ) ; } /* Beware that raw rdw accounts for the rdw length (4 bytes) */ return len - RDW_LEN ; }
RDW is a 4 bytes numeric stored in Big Endian as a binary 2 s complement .
107
19
137,856
public String translate ( XmlSchema xmlSchema , String avroNamespace , String avroSchemaName ) throws Xsd2AvroTranslatorException { log . debug ( "XML Schema to Avro Schema translator started" ) ; final Map < QName , XmlSchemaElement > items = xmlSchema . getElements ( ) ; ObjectNode rootAvroSchema = null ; final ArrayNode avroFields = MAPPER . createArrayNode ( ) ; if ( items . size ( ) > 1 ) { // More then one root, create an aggregate record for ( Entry < QName , XmlSchemaElement > entry : items . entrySet ( ) ) { visit ( xmlSchema , entry . getValue ( ) , 1 , avroFields ) ; } rootAvroSchema = buildAvroRecordType ( avroSchemaName , avroFields ) ; } else if ( items . size ( ) == 1 ) { XmlSchemaElement xsdElement = ( XmlSchemaElement ) items . values ( ) . iterator ( ) . next ( ) ; if ( xsdElement . getSchemaType ( ) instanceof XmlSchemaComplexType ) { XmlSchemaComplexType xsdType = ( XmlSchemaComplexType ) xsdElement . getSchemaType ( ) ; visit ( xmlSchema , xsdType , 1 , avroFields ) ; rootAvroSchema = buildAvroRecordType ( getAvroTypeName ( xsdType ) , avroFields ) ; } else { throw new Xsd2AvroTranslatorException ( "XML schema does contain a root element but it is not a complex type" ) ; } } else { throw new Xsd2AvroTranslatorException ( "XML schema does not contain a root element" ) ; } rootAvroSchema . put ( "namespace" , avroNamespace == null ? "" : avroNamespace ) ; log . debug ( "XML Schema to Avro Schema translator ended" ) ; return rootAvroSchema . toString ( ) ; }
Translate the input XML Schema .
461
8
137,857
private void visit ( XmlSchema xmlSchema , final XmlSchemaElement xsdElement , final int level , final ArrayNode avroFields ) throws Xsd2AvroTranslatorException { /* * If this element is referencing another, it might not be useful to * process it. */ if ( xsdElement . getRef ( ) . getTarget ( ) != null ) { return ; } log . debug ( "process started for element = " + xsdElement . getName ( ) ) ; if ( xsdElement . getSchemaType ( ) instanceof XmlSchemaComplexType ) { XmlSchemaComplexType xsdType = ( XmlSchemaComplexType ) xsdElement . getSchemaType ( ) ; int nextLevel = level + 1 ; final ArrayNode avroChildrenFields = MAPPER . createArrayNode ( ) ; visit ( xmlSchema , xsdType , nextLevel , avroChildrenFields ) ; ContainerNode avroRecordType = buildAvroCompositeType ( getAvroTypeName ( xsdType ) , avroChildrenFields , xsdElement . getMaxOccurs ( ) > 1 , xsdElement . getMinOccurs ( ) == 0 && xsdElement . getMaxOccurs ( ) == 1 ) ; ObjectNode avroRecordElement = MAPPER . createObjectNode ( ) ; avroRecordElement . put ( "type" , avroRecordType ) ; avroRecordElement . put ( "name" , getAvroFieldName ( xsdElement ) ) ; avroFields . add ( avroRecordElement ) ; } else if ( xsdElement . getSchemaType ( ) instanceof XmlSchemaSimpleType ) { visit ( ( XmlSchemaSimpleType ) xsdElement . getSchemaType ( ) , level , getAvroFieldName ( xsdElement ) , xsdElement . getMinOccurs ( ) , xsdElement . getMaxOccurs ( ) , avroFields ) ; } log . debug ( "process ended for element = " + xsdElement . getName ( ) ) ; }
Process a regular XML schema element .
459
7
137,858
private void visit ( XmlSchema xmlSchema , XmlSchemaComplexType xsdType , final int level , final ArrayNode avroFields ) { visit ( xmlSchema , xsdType . getParticle ( ) , level , avroFields ) ; }
Create an avro complex type field using an XML schema type .
61
13
137,859
private void visit ( XmlSchemaSimpleType xsdType , final int level , final String avroFieldName , long minOccurs , long maxOccurs , ArrayNode avroFields ) throws Xsd2AvroTranslatorException { Object avroType = getAvroPrimitiveType ( avroFieldName , xsdType , maxOccurs > 1 , minOccurs == 0 && maxOccurs == 1 ) ; ObjectNode avroField = MAPPER . createObjectNode ( ) ; avroField . put ( "name" , avroFieldName ) ; if ( avroType != null ) { if ( avroType instanceof String ) { avroField . put ( "type" , ( String ) avroType ) ; } else if ( avroType instanceof JsonNode ) { avroField . put ( "type" , ( JsonNode ) avroType ) ; } } avroFields . add ( avroField ) ; }
Create an avro primitive type field using an XML schema type .
209
13
137,860
public static boolean isBigDecimal ( Schema schema ) { if ( Type . BYTES == schema . getType ( ) ) { JsonNode logicalTypeNode = schema . getJsonProp ( "logicalType" ) ; if ( logicalTypeNode != null && "decimal" . equals ( logicalTypeNode . asText ( ) ) ) { return true ; } } return false ; }
Tests whether a field is to be externalized as a BigDecimal
85
15
137,861
protected void configureAop ( ) { final RepositoryMethodInterceptor proxy = new RepositoryMethodInterceptor ( ) ; requestInjection ( proxy ) ; // repository specific method annotations (query, function, delegate, etc.) bindInterceptor ( Matchers . any ( ) , new AbstractMatcher < Method > ( ) { @ Override public boolean matches ( final Method method ) { // this will throw error if two or more annotations specified (fail fast) try { return ExtUtils . findMethodAnnotation ( method ) != null ; } catch ( Exception ex ) { throw new MethodDefinitionException ( String . format ( "Error declaration on method %s" , RepositoryUtils . methodToString ( method ) ) , ex ) ; } } } , proxy ) ; }
Configures repository annotations interceptor .
161
7
137,862
protected void bindExecutor ( final Class < ? extends RepositoryExecutor > executor ) { bind ( executor ) . in ( Singleton . class ) ; executorsMultibinder . addBinding ( ) . to ( executor ) ; }
Register executor for specific connection type .
53
8
137,863
protected void loadOptionalExecutor ( final String executorBinder ) { try { final Method bindExecutor = RepositoryModule . class . getDeclaredMethod ( "bindExecutor" , Class . class ) ; bindExecutor . setAccessible ( true ) ; try { Class . forName ( executorBinder ) . getConstructor ( RepositoryModule . class , Method . class ) . newInstance ( this , bindExecutor ) ; } finally { bindExecutor . setAccessible ( false ) ; } } catch ( Exception ignore ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Failed to process executor loader " + executorBinder , ignore ) ; } } }
Allows to load executor only if required jars are in classpath . For example no need for graph dependencies if only object db is used .
153
28
137,864
public void setAdapter ( Adapter adapter ) { if ( mAdapter != null ) { mAdapter . unregisterAdapterDataObserver ( mObserver ) ; } // end all running animations if ( mItemAnimator != null ) { mItemAnimator . endAnimations ( ) ; } // Since animations are ended, mLayout.children should be equal to recyclerView.children. // This may not be true if item animator's end does not work as expected. (e.g. not release // children instantly). It is safer to use mLayout's child count. if ( mLayout != null ) { mLayout . removeAndRecycleAllViews ( mRecycler ) ; mLayout . removeAndRecycleScrapInt ( mRecycler , true ) ; } final Adapter oldAdapter = mAdapter ; mAdapter = adapter ; if ( adapter != null ) { adapter . registerAdapterDataObserver ( mObserver ) ; } if ( mLayout != null ) { mLayout . onAdapterChanged ( oldAdapter , mAdapter ) ; } mRecycler . onAdapterChanged ( oldAdapter , mAdapter ) ; mState . mStructureChanged = true ; markKnownViewsInvalid ( ) ; requestLayout ( ) ; }
Set a new adapter to provide child views on demand .
262
11
137,865
private void addAnimatingView ( View view ) { boolean alreadyAdded = false ; if ( mNumAnimatingViews > 0 ) { for ( int i = mAnimatingViewIndex ; i < getChildCount ( ) ; ++ i ) { if ( getChildAt ( i ) == view ) { alreadyAdded = true ; break ; } } } if ( ! alreadyAdded ) { if ( mNumAnimatingViews == 0 ) { mAnimatingViewIndex = getChildCount ( ) ; } ++ mNumAnimatingViews ; addView ( view ) ; } mRecycler . unscrapView ( getChildViewHolder ( view ) ) ; }
Adds a view to the animatingViews list . mAnimatingViews holds the child views that are currently being kept around purely for the purpose of being animated out of view . They are drawn as a regular part of the child list of the RecyclerView but they are invisible to the LayoutManager as they are managed separately from the regular child views .
141
73
137,866
private void removeAnimatingView ( View view ) { if ( mNumAnimatingViews > 0 ) { for ( int i = mAnimatingViewIndex ; i < getChildCount ( ) ; ++ i ) { if ( getChildAt ( i ) == view ) { removeViewAt ( i ) ; -- mNumAnimatingViews ; if ( mNumAnimatingViews == 0 ) { mAnimatingViewIndex = - 1 ; } mRecycler . recycleView ( view ) ; return ; } } } }
Removes a view from the animatingViews list .
112
12
137,867
void scrollByInternal ( int x , int y ) { int overscrollX = 0 , overscrollY = 0 ; consumePendingUpdateOperations ( ) ; if ( mAdapter != null ) { eatRequestLayout ( ) ; if ( x != 0 ) { final int hresult = mLayout . scrollHorizontallyBy ( x , mRecycler , mState ) ; overscrollX = x - hresult ; } if ( y != 0 ) { final int vresult = mLayout . scrollVerticallyBy ( y , mRecycler , mState ) ; overscrollY = y - vresult ; } resumeRequestLayout ( false ) ; } if ( ! mItemDecorations . isEmpty ( ) ) { invalidate ( ) ; } if ( ViewCompat . getOverScrollMode ( this ) != ViewCompat . OVER_SCROLL_NEVER ) { pullGlows ( overscrollX , overscrollY ) ; } if ( mScrollListener != null && ( x != 0 || y != 0 ) ) { mScrollListener . onScrolled ( x , y ) ; } if ( ! awakenScrollBars ( ) ) { invalidate ( ) ; } }
Does not perform bounds checking . Used by internal methods that have already validated input .
251
16
137,868
public boolean fling ( int velocityX , int velocityY ) { if ( Math . abs ( velocityX ) < mMinFlingVelocity ) { velocityX = 0 ; } if ( Math . abs ( velocityY ) < mMinFlingVelocity ) { velocityY = 0 ; } velocityX = Math . max ( - mMaxFlingVelocity , Math . min ( velocityX , mMaxFlingVelocity ) ) ; velocityY = Math . max ( - mMaxFlingVelocity , Math . min ( velocityY , mMaxFlingVelocity ) ) ; if ( velocityX != 0 || velocityY != 0 ) { mViewFlinger . fling ( velocityX , velocityY ) ; return true ; } return false ; }
Begin a standard fling with an initial velocity along each axis in pixels per second . If the velocity given is below the system - defined minimum this method will return false and no fling will occur .
160
40
137,869
private void pullGlows ( int overscrollX , int overscrollY ) { if ( overscrollX < 0 ) { if ( mLeftGlow == null ) { mLeftGlow = new EdgeEffectCompat ( getContext ( ) ) ; mLeftGlow . setSize ( getMeasuredHeight ( ) - getPaddingTop ( ) - getPaddingBottom ( ) , getMeasuredWidth ( ) - getPaddingLeft ( ) - getPaddingRight ( ) ) ; } mLeftGlow . onPull ( - overscrollX / ( float ) getWidth ( ) ) ; } else if ( overscrollX > 0 ) { if ( mRightGlow == null ) { mRightGlow = new EdgeEffectCompat ( getContext ( ) ) ; mRightGlow . setSize ( getMeasuredHeight ( ) - getPaddingTop ( ) - getPaddingBottom ( ) , getMeasuredWidth ( ) - getPaddingLeft ( ) - getPaddingRight ( ) ) ; } mRightGlow . onPull ( overscrollX / ( float ) getWidth ( ) ) ; } if ( overscrollY < 0 ) { if ( mTopGlow == null ) { mTopGlow = new EdgeEffectCompat ( getContext ( ) ) ; mTopGlow . setSize ( getMeasuredWidth ( ) - getPaddingLeft ( ) - getPaddingRight ( ) , getMeasuredHeight ( ) - getPaddingTop ( ) - getPaddingBottom ( ) ) ; } mTopGlow . onPull ( - overscrollY / ( float ) getHeight ( ) ) ; } else if ( overscrollY > 0 ) { if ( mBottomGlow == null ) { mBottomGlow = new EdgeEffectCompat ( getContext ( ) ) ; mBottomGlow . setSize ( getMeasuredWidth ( ) - getPaddingLeft ( ) - getPaddingRight ( ) , getMeasuredHeight ( ) - getPaddingTop ( ) - getPaddingBottom ( ) ) ; } mBottomGlow . onPull ( overscrollY / ( float ) getHeight ( ) ) ; } if ( overscrollX != 0 || overscrollY != 0 ) { ViewCompat . postInvalidateOnAnimation ( this ) ; } }
Apply a pull to relevant overscroll glow effects
486
9
137,870
void viewRangeUpdate ( int positionStart , int itemCount ) { final int childCount = getChildCount ( ) ; final int positionEnd = positionStart + itemCount ; for ( int i = 0 ; i < childCount ; i ++ ) { final ViewHolder holder = getChildViewHolderInt ( getChildAt ( i ) ) ; if ( holder == null ) { continue ; } final int position = holder . getPosition ( ) ; if ( position >= positionStart && position < positionEnd ) { holder . addFlags ( ViewHolder . FLAG_UPDATE ) ; // Binding an attached view will request a layout if needed. mAdapter . bindViewHolder ( holder , holder . getPosition ( ) ) ; } } mRecycler . viewRangeUpdate ( positionStart , itemCount ) ; }
Rebind existing views for the given range or create as needed .
171
13
137,871
void markKnownViewsInvalid ( ) { final int childCount = getChildCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { final ViewHolder holder = getChildViewHolderInt ( getChildAt ( i ) ) ; if ( holder != null ) { holder . addFlags ( ViewHolder . FLAG_UPDATE | ViewHolder . FLAG_INVALID ) ; } } mRecycler . markKnownViewsInvalid ( ) ; }
Mark all known views as invalid . Used in response to a the whole world might have changed data change event .
106
22
137,872
void postAdapterUpdate ( UpdateOp op ) { mPendingUpdates . add ( op ) ; if ( mPendingUpdates . size ( ) == 1 ) { if ( mPostUpdatesOnAnimation && mHasFixedSize && mIsAttached ) { ViewCompat . postOnAnimation ( this , mUpdateChildViewsRunnable ) ; } else { mAdapterUpdateDuringMeasure = true ; requestLayout ( ) ; } } }
Schedule an update of data from the adapter to occur on the next frame . On newer platform versions this happens via the postOnAnimation mechanism and RecyclerView attempts to avoid relayouts if possible . On older platform versions the RecyclerView requests a layout the same way ListView does .
94
60
137,873
public int getChildPosition ( View child ) { final ViewHolder holder = getChildViewHolderInt ( child ) ; return holder != null ? holder . getPosition ( ) : NO_POSITION ; }
Return the adapter position that the given child view corresponds to .
44
12
137,874
public long getChildItemId ( View child ) { if ( mAdapter == null || ! mAdapter . hasStableIds ( ) ) { return NO_ID ; } final ViewHolder holder = getChildViewHolderInt ( child ) ; return holder != null ? holder . getItemId ( ) : NO_ID ; }
Return the stable item id that the given child view corresponds to .
71
13
137,875
public View findChildViewUnder ( float x , float y ) { final int count = getChildCount ( ) ; for ( int i = count - 1 ; i >= 0 ; i -- ) { final View child = getChildAt ( i ) ; final float translationX = ViewCompat . getTranslationX ( child ) ; final float translationY = ViewCompat . getTranslationY ( child ) ; if ( x >= child . getLeft ( ) + translationX && x <= child . getRight ( ) + translationX && y >= child . getTop ( ) + translationY && y <= child . getBottom ( ) + translationY ) { return child ; } } return null ; }
Find the topmost view under the given point .
142
10
137,876
protected int getHorizontalSnapPreference ( ) { return mTargetVector == null || mTargetVector . x == 0 ? SNAP_TO_ANY : mTargetVector . x > 0 ? SNAP_TO_END : SNAP_TO_START ; }
When scrolling towards a child view this method defines whether we should align the left or the right edge of the child with the parent RecyclerView .
54
30
137,877
protected int getVerticalSnapPreference ( ) { return mTargetVector == null || mTargetVector . y == 0 ? SNAP_TO_ANY : mTargetVector . y > 0 ? SNAP_TO_END : SNAP_TO_START ; }
When scrolling towards a child view this method defines whether we should align the top or the bottom edge of the child with the parent RecyclerView .
54
30
137,878
protected void updateActionForInterimTarget ( Action action ) { // find an interim target position PointF scrollVector = computeScrollVectorForPosition ( getTargetPosition ( ) ) ; if ( scrollVector == null || ( scrollVector . x == 0 && scrollVector . y == 0 ) ) { Log . e ( TAG , "To support smooth scrolling, you should override \n" + "LayoutManager#computeScrollVectorForPosition.\n" + "Falling back to instant scroll" ) ; final int target = getTargetPosition ( ) ; stop ( ) ; instantScrollToPosition ( target ) ; return ; } normalize ( scrollVector ) ; mTargetVector = scrollVector ; mInterimTargetDx = ( int ) ( TARGET_SEEK_SCROLL_DISTANCE_PX * scrollVector . x ) ; mInterimTargetDy = ( int ) ( TARGET_SEEK_SCROLL_DISTANCE_PX * scrollVector . y ) ; final int time = calculateTimeForScrolling ( TARGET_SEEK_SCROLL_DISTANCE_PX ) ; // To avoid UI hiccups, trigger a smooth scroll to a distance little further than the // interim target. Since we track the distance travelled in onSeekTargetStep callback, it // won't actually scroll more than what we need. action . update ( ( int ) ( mInterimTargetDx * TARGET_SEEK_EXTRA_SCROLL_RATIO ) , ( int ) ( mInterimTargetDy * TARGET_SEEK_EXTRA_SCROLL_RATIO ) , ( int ) ( time * TARGET_SEEK_EXTRA_SCROLL_RATIO ) , mLinearInterpolator ) ; }
When the target scroll position is not a child of the RecyclerView this method calculates a direction vector towards that child and triggers a smooth scroll .
384
30
137,879
public int calculateDyToMakeVisible ( View view , int snapPreference ) { final RecyclerView . LayoutManager layoutManager = getLayoutManager ( ) ; if ( ! layoutManager . canScrollVertically ( ) ) { return 0 ; } final RecyclerView . LayoutParams params = ( RecyclerView . LayoutParams ) view . getLayoutParams ( ) ; final int top = layoutManager . getDecoratedTop ( view ) - params . topMargin ; final int bottom = layoutManager . getDecoratedBottom ( view ) + params . bottomMargin ; final int start = layoutManager . getPaddingTop ( ) ; final int end = layoutManager . getHeight ( ) - layoutManager . getPaddingBottom ( ) ; return calculateDtToFit ( top , bottom , start , end , snapPreference ) ; }
Calculates the vertical scroll amount necessary to make the given view fully visible inside the RecyclerView .
185
22
137,880
public int calculateDxToMakeVisible ( View view , int snapPreference ) { final RecyclerView . LayoutManager layoutManager = getLayoutManager ( ) ; if ( ! layoutManager . canScrollHorizontally ( ) ) { return 0 ; } final RecyclerView . LayoutParams params = ( RecyclerView . LayoutParams ) view . getLayoutParams ( ) ; final int left = layoutManager . getDecoratedLeft ( view ) - params . leftMargin ; final int right = layoutManager . getDecoratedRight ( view ) + params . rightMargin ; final int start = layoutManager . getPaddingLeft ( ) ; final int end = layoutManager . getWidth ( ) - layoutManager . getPaddingRight ( ) ; return calculateDtToFit ( left , right , start , end , snapPreference ) ; }
Calculates the horizontal scroll amount necessary to make the given view fully visible inside the RecyclerView .
186
22
137,881
private Class < ? > resolveTargetType ( final Class < ? > listenerType , final Class < ? > declaredTargetType ) { Class < ? > target = null ; if ( RequiresRecordConversion . class . isAssignableFrom ( listenerType ) ) { target = GenericsResolver . resolve ( listenerType ) . type ( RequiresRecordConversion . class ) . generic ( "T" ) ; // if generic could not be resolved from listener instance, use method parameter declaration (last resort) if ( Object . class . equals ( target ) ) { target = declaredTargetType ; } } return target ; }
Resolve target conversion type either from listener instance or if its not possible from listener parameter declaration .
128
19
137,882
public static String methodToString ( final Class < ? > type , final Method method ) { final StringBuilder res = new StringBuilder ( ) ; res . append ( type . getSimpleName ( ) ) . append ( ' ' ) . append ( method . getName ( ) ) . append ( ' ' ) ; int i = 0 ; for ( Class < ? > param : method . getParameterTypes ( ) ) { if ( i > 0 ) { res . append ( ", " ) ; } final Type generic = method . getGenericParameterTypes ( ) [ i ] ; if ( generic instanceof TypeVariable ) { // using generic name, because its simpler to search visually in code res . append ( ' ' ) . append ( ( ( TypeVariable ) generic ) . getName ( ) ) . append ( ' ' ) ; } else { res . append ( param . getSimpleName ( ) ) ; } i ++ ; } res . append ( ' ' ) ; return res . toString ( ) ; }
Converts method signature to human readable string .
209
9
137,883
public static void checkParamExtensionCompatibility ( final Class < ? extends RepositoryMethodDescriptor > descriptorType , final Class < ? extends MethodParamExtension > paramExtType ) { check ( isCompatible ( paramExtType , MethodParamExtension . class , descriptorType ) , "Param extension %s is incompatible with descriptor %s" , paramExtType . getSimpleName ( ) , descriptorType . getSimpleName ( ) ) ; }
Checks that parameter extension is compatible with descriptor and throws error if extension incompatible .
95
16
137,884
public static void checkAmendExtensionsCompatibility ( final Class < ? extends RepositoryMethodDescriptor > descriptorType , final List < Annotation > extensions ) { final List < Class < ? extends AmendMethodExtension > > exts = Lists . transform ( extensions , new Function < Annotation , Class < ? extends AmendMethodExtension > > ( ) { @ Nonnull @ Override public Class < ? extends AmendMethodExtension > apply ( @ Nonnull final Annotation input ) { return input . annotationType ( ) . getAnnotation ( AmendMethod . class ) . value ( ) ; } } ) ; for ( Class < ? extends AmendMethodExtension > ext : exts ) { check ( isCompatible ( ext , AmendMethodExtension . class , descriptorType ) , "Amend extension %s is incompatible with descriptor %s" , ext . getSimpleName ( ) , descriptorType . getSimpleName ( ) ) ; } }
Checks that amend extensions strictly compatible with descriptor object . Used for amend annotations defined on method .
199
19
137,885
public static List < AmendExecutionExtension > filterCompatibleExtensions ( final List < AmendExecutionExtension > extensions , final Class < ? extends RepositoryMethodDescriptor > descriptorType ) { @ SuppressWarnings ( "unchecked" ) final Class < ? extends AmendExecutionExtension > supportedExtension = ( Class < ? extends AmendExecutionExtension > ) GenericsResolver . resolve ( descriptorType ) . type ( RepositoryMethodDescriptor . class ) . generic ( "E" ) ; return Lists . newArrayList ( Iterables . filter ( extensions , new Predicate < AmendExecutionExtension > ( ) { @ Override public boolean apply ( @ Nonnull final AmendExecutionExtension ext ) { final Class < ? > rawExtType = RepositoryUtils . resolveRepositoryClass ( ext ) ; final boolean compatible = supportedExtension . isAssignableFrom ( rawExtType ) ; if ( ! compatible ) { LOGGER . debug ( "Extension {} ignored, because it doesn't implement required extension " + "interface {}" , rawExtType . getSimpleName ( ) , supportedExtension . getSimpleName ( ) ) ; } return compatible ; } } ) ) ; }
Checks resolved amend extensions compatibility with method specific extension type . Extension may be universal and support some methods and doesn t support other .
261
26
137,886
public void disposeTooltip ( ) { if ( popup != null ) { timer . stop ( ) ; popup . setVisible ( false ) ; popup = null ; } }
Dispose the tooltip
36
4
137,887
private void showTooltip ( ) { Wrap tooltipLabel = new Wrap ( toolTipWrapWidth ) ; tooltipLabel . setForeground ( getForeground ( ) ) ; tooltipLabel . setFont ( ToolTipButton . this . getFont ( ) ) ; tooltipLabel . setText ( text ) ; JPanel panel = new JPanel ( ) ; panel . setBackground ( toolTipBackground ) ; panel . setLayout ( new BorderLayout ( ) ) ; panel . add ( tooltipLabel , BorderLayout . CENTER ) ; if ( extraComponent != null && extraComponentAnchor != null ) { if ( extraComponentAnchor . equals ( ToolTipButtonAnchor . SOUTH ) ) { panel . add ( extraComponent , BorderLayout . SOUTH ) ; } else if ( extraComponentAnchor . equals ( ToolTipButtonAnchor . NORTH ) ) { panel . add ( extraComponent , BorderLayout . NORTH ) ; } else if ( extraComponentAnchor . equals ( ToolTipButtonAnchor . EAST ) ) { panel . add ( extraComponent , BorderLayout . EAST ) ; } else if ( extraComponentAnchor . equals ( ToolTipButtonAnchor . WEST ) ) { panel . add ( extraComponent , BorderLayout . WEST ) ; } } Border out = BorderFactory . createLineBorder ( borderColor , borderThickness ) ; Border in = BorderFactory . createEmptyBorder ( margin . top , margin . left , margin . bottom , margin . right ) ; Border border = BorderFactory . createCompoundBorder ( out , in ) ; panel . setBorder ( border ) ; popup = new JPopupMenu ( ) ; popup . setBorder ( BorderFactory . createEmptyBorder ( ) ) ; popup . add ( panel ) ; popup . addMouseListener ( new MouseAdapter ( ) { @ Override public void mouseExited ( MouseEvent e ) { tryDisposeTooltip ( ) ; } } ) ; popup . pack ( ) ; popup . show ( ToolTipButton . this , 0 , getHeight ( ) ) ; Point point = popup . getLocationOnScreen ( ) ; Dimension dim = popup . getSize ( ) ; popupBounds = new Rectangle2D . Double ( point . getX ( ) , point . getY ( ) , dim . getWidth ( ) , dim . getHeight ( ) ) ; }
Show the tooltip .
505
4
137,888
public static Collection < MatchedMethod > filterByClosestParams ( final Collection < MatchedMethod > possibilities , final int paramsCount ) { Collection < MatchedMethod > res = null ; for ( int i = 0 ; i < paramsCount ; i ++ ) { final Collection < MatchedMethod > filtered = filterByParam ( possibilities , i ) ; if ( res != null ) { if ( filtered . size ( ) < res . size ( ) ) { res = filtered ; } } else { res = filtered ; } } return res ; }
Looks for most specific type for each parameter .
115
9
137,889
private ODatabaseDocument checkAndAcquireConnection ( ) { final ODatabaseDocument res ; if ( userManager . isSpecificUser ( ) ) { // non pool-managed connection for different user res = orientDB . get ( ) . open ( database , userManager . getUser ( ) , userManager . getPassword ( ) ) ; } else { res = pool . acquire ( ) ; } if ( res . isClosed ( ) ) { final String message = String . format ( "Pool %s return closed connection something is terribly wrong" , getType ( ) ) ; logger . error ( message ) ; throw new IllegalStateException ( message ) ; } return res ; }
Its definitely not normal that pool returns closed connections but possible if used improperly .
140
15
137,890
public static void trackIdChange ( final ODocument document , final Object pojo ) { if ( document . getIdentity ( ) . isNew ( ) ) { ORecordInternal . addIdentityChangeListener ( document , new OIdentityChangeListener ( ) { @ Override public void onBeforeIdentityChange ( final ORecord record ) { // not needed } @ Override public void onAfterIdentityChange ( final ORecord record ) { OObjectSerializerHelper . setObjectID ( record . getIdentity ( ) , pojo ) ; OObjectSerializerHelper . setObjectVersion ( record . getVersion ( ) , pojo ) ; } } ) ; } }
When just created object is detached to pure pojo it gets temporary id . Real id is assigned only after transaction commit . This method tracks original document intercepts its id change and sets correct id and version into pojo . So it become safe to use such pojo id outside of transaction .
145
58
137,891
private static Field findIdField ( final Object value ) { Field res = null ; final Class < ? > type = value . getClass ( ) ; if ( ODatabaseRecordThreadLocal . instance ( ) . isDefined ( ) ) { res = OObjectEntitySerializer . getIdField ( type ) ; } else { final String idField = OObjectSerializerHelper . getObjectIDFieldName ( value ) ; if ( idField != null ) { try { res = type . getDeclaredField ( idField ) ; } catch ( NoSuchFieldException e ) { LOGGER . warn ( String . format ( "Id field '%s' not found in class '%s'." , idField , type . getSimpleName ( ) ) , e ) ; } } } return res ; }
Core orient field resolve method relies on bound connection but it may be required to resolve id outside of transaction . So we use orient method under transaction and do manual scan outside of transaction .
168
36
137,892
private static Component getCurrentModal_ ( RootPaneContainer rootPane ) { synchronized ( modals ) { Modal modal = modals . get ( rootPane ) ; if ( modal != null ) { if ( modal . getSize ( ) > 0 ) { return modal . components . get ( modal . components . size ( ) - 1 ) ; } } return null ; } }
Get the current modal component of a specific RootPaneContainer .
87
14
137,893
private static void closeCurrentModal_ ( RootPaneContainer rootPane ) { synchronized ( modals ) { Modal modal = modals . get ( rootPane ) ; if ( modal != null ) { modal . closeCurrent ( ) ; if ( modal . getSize ( ) == 0 ) { modals . remove ( rootPane ) ; } } } }
Close the current modal component of a specific RootPaneContainer .
82
14
137,894
public static void closeModal ( Component component ) { synchronized ( modals ) { RootPaneContainer frame = null ; Modal modal = null ; Iterator < Entry < RootPaneContainer , Modal > > it = modals . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Entry < RootPaneContainer , Modal > entry = it . next ( ) ; modal = entry . getValue ( ) ; frame = entry . getKey ( ) ; if ( frame != null && modal != null && modal . components . contains ( component ) ) { break ; } else { frame = null ; modal = null ; } } if ( frame != null && modal != null ) { modal . close ( component ) ; if ( modal . getSize ( ) == 0 ) { modals . remove ( frame ) ; } } } }
Close a specific modal component .
190
7
137,895
private static void closeAllModals_ ( RootPaneContainer rootPane ) { synchronized ( modals ) { Modal modal = modals . get ( rootPane ) ; if ( modal != null ) { modal . closeAll ( ) ; modals . remove ( rootPane ) ; } } }
Close all modals of a specific RootPaneContainer .
68
12
137,896
private static boolean hasModal_ ( RootPaneContainer rootPane ) { synchronized ( modals ) { Modal modal = modals . get ( rootPane ) ; if ( modal != null && modal . getSize ( ) > 0 ) { return true ; } return false ; } }
Indicates whether the RootPaneContainer has a modal .
65
13
137,897
private static Modal getModal ( RootPaneContainer rootPane ) { synchronized ( modals ) { Modal modal = modals . get ( rootPane ) ; if ( modal == null ) { modal = new Modal ( rootPane ) ; modals . put ( rootPane , modal ) ; } return modal ; } }
Get the modal of a specific frame
78
8
137,898
public static boolean isModal ( Component component ) { synchronized ( modals ) { Iterator < Entry < RootPaneContainer , Modal > > it = modals . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Entry < RootPaneContainer , Modal > entry = it . next ( ) ; if ( entry . getValue ( ) . components . contains ( component ) ) { return true ; } } return false ; } }
Indicates whether the component is a modal component .
100
11
137,899
public static void addModal ( JInternalFrame frame , Component component , ModalListener listener ) { addModal_ ( frame , component , listener , defaultModalDepth ) ; }
Add a modal component in the internal frame .
39
10