idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
18,500
public final char charAt ( int i ) { if ( i < - len || len <= i ) { throw new IllegalArgumentException ( String . format ( "position %d of slice length %d is not valid." , i , len ) ) ; } if ( i < 0 ) { i = len + i ; } return fb [ off + i ] ; }
Get character at slice relative position .
18,501
public final long parseInteger ( ) { int pos = off , radix = 10 ; boolean neg = false ; if ( len > 2 && charAt ( 0 ) == '0' && charAt ( 1 ) == 'x' ) { pos += 2 ; radix = 16 ; } else if ( len > 1 && charAt ( 0 ) == '0' ) { pos += 1 ; radix = 8 ; } else if ( len > 1 && charAt ( 0 ) == '-' ) { neg = true ; pos += 1 ; } long res = 0 ; for ( ; pos < off + len ; ++ pos ) { res *= radix ; res += validate ( fb [ pos ] , valueOfHex ( fb [ pos ] ) , radix ) ; } return neg ? - res : res ; }
Get the whole slice as a simple integer .
18,502
public final boolean containsAny ( char ... a ) { for ( int i = 0 ; i < len ; ++ i ) { for ( char b : a ) { if ( b == fb [ off + i ] ) { return true ; } } } return false ; }
Checks if any of the provided bytes is contained in the slice .
18,503
public final boolean contains ( char [ ] a ) { final int last_pos = off + len - a . length ; outer : for ( int pos = off ; pos <= last_pos ; ++ pos ) { for ( int a_off = 0 ; a_off < a . length ; ++ a_off ) { if ( a [ a_off ] != fb [ pos + a_off ] ) { continue outer ; } } return true ; } return false ; }
Checks if the byte array is contained in the slice .
18,504
public final boolean contains ( char a ) { for ( int i = off ; i < ( off + len ) ; ++ i ) { if ( fb [ i ] == a ) { return true ; } } return false ; }
Checks if a single byte can be found in the slice .
18,505
protected Properties replacePlaceHolders ( Properties props ) { if ( replacePlaceHolders ) { Properties result = new Properties ( ) ; for ( Object keyObj : props . keySet ( ) ) { String key = ( String ) keyObj ; String value = props . getProperty ( key ) ; key = PlaceHolderReplacer . replaceWithProperties ( key ) ; value = PlaceHolderReplacer . replaceWithProperties ( value ) ; result . put ( key , value ) ; } return result ; } else { return props ; } }
Replace place holders in both keys and values with values defined in system properties .
18,506
public synchronized void accept ( final double value ) { super . accept ( value ) ; final double squareValue = value * value ; simpleSumOfSquare += squareValue ; sumOfSquareWithCompensation ( squareValue ) ; }
Low order bits of sum
18,507
public com . simiacryptus . util . data . DoubleStatistics accept ( final double [ ] value ) { Arrays . stream ( value ) . forEach ( this :: accept ) ; return this ; }
Accept double statistics .
18,508
public com . simiacryptus . util . data . DoubleStatistics combine ( final com . simiacryptus . util . data . DoubleStatistics other ) { super . combine ( other ) ; simpleSumOfSquare += other . simpleSumOfSquare ; sumOfSquareWithCompensation ( other . sumOfSquare ) ; sumOfSquareWithCompensation ( other . sumOfSquareCompensation ) ; return this ; }
Combine double statistics .
18,509
public double getSumOfSquare ( ) { final double tmp = sumOfSquare + sumOfSquareCompensation ; if ( Double . isNaN ( tmp ) && Double . isInfinite ( simpleSumOfSquare ) ) { return simpleSumOfSquare ; } return tmp ; }
Gets sum of square .
18,510
public com . authy . api . User createUser ( String email , String phone ) { return createUser ( email , phone , DEFAULT_COUNTRY_CODE ) ; }
Create a new user using his e - mail and phone . It uses USA country code by default .
18,511
public static boolean hasMethod ( Object obj , String name ) { if ( obj == null ) throw new NullPointerException ( "Object cannot be null" ) ; if ( name == null ) throw new NullPointerException ( "Method name cannot be null" ) ; Class < ? > objClass = obj . getClass ( ) ; for ( Method method : objClass . getMethods ( ) ) { if ( matchMethod ( method , name ) ) return true ; } return false ; }
Checks if object has a method with specified name ..
18,512
public static Object invokeMethod ( Object obj , String name , Object ... args ) { if ( obj == null ) throw new NullPointerException ( "Object cannot be null" ) ; if ( name == null ) throw new NullPointerException ( "Method name cannot be null" ) ; Class < ? > objClass = obj . getClass ( ) ; for ( Method method : objClass . getMethods ( ) ) { try { if ( matchMethod ( method , name ) ) return method . invoke ( obj , args ) ; } catch ( Throwable t ) { } } return null ; }
Invokes an object method by its name with specified parameters .
18,513
public static List < String > getMethodNames ( Object obj ) { List < String > methods = new ArrayList < String > ( ) ; Class < ? > objClass = obj . getClass ( ) ; for ( Method method : objClass . getMethods ( ) ) { if ( matchMethod ( method , method . getName ( ) ) ) { methods . add ( method . getName ( ) ) ; } } return methods ; }
Gets names of all methods implemented in specified object .
18,514
static void createSupportingInfrastructure ( String apiName ) { elementType = getFullClassTypeName ( ELEMENT , apiName ) ; elementTypeDesc = getFullClassTypeNameDesc ( ELEMENT , apiName ) ; elementVisitorType = getFullClassTypeName ( ELEMENT_VISITOR , apiName ) ; elementVisitorTypeDesc = getFullClassTypeNameDesc ( ELEMENT_VISITOR , apiName ) ; textGroupType = getFullClassTypeName ( TEXT_GROUP , apiName ) ; customAttributeGroupType = getFullClassTypeName ( CUSTOM_ATTRIBUTE_GROUP , apiName ) ; textType = getFullClassTypeName ( TEXT , apiName ) ; textTypeDesc = getFullClassTypeNameDesc ( TEXT , apiName ) ; createElement ( apiName ) ; createTextGroup ( apiName ) ; createCustomAttributeGroup ( apiName ) ; createText ( apiName ) ; infrastructureVars . put ( ELEMENT , elementType ) ; infrastructureVars . put ( ELEMENT_VISITOR , elementVisitorType ) ; infrastructureVars . put ( TEXT_GROUP , textGroupType ) ; }
Creates all the classes that belong to the fluent interface infrastructure and can t be defined the same way as the classes present in the infrastructure package of this solution .
18,515
public void addAllWithAlias ( List < String > aliasList , List < V > dataList ) { synchronized ( dataList ) { JMLambda . runByBoolean ( aliasList . size ( ) == dataList . size ( ) , ( ) -> JMStream . numberRangeWithCount ( 0 , 1 , dataList . size ( ) ) . forEach ( i -> addWithAlias ( aliasList . get ( i ) , dataList . get ( i ) ) ) , ( ) -> JMExceptionManager . logRuntimeException ( log , "Wrong Key List Size !!! - " + "dataList Size = " + size ( ) + " aliasList Size = " + aliasList . size ( ) , "setKeyIndexMap" , aliasList ) ) ; } }
Add all with alias .
18,516
public Integer addWithAlias ( String alias , V value ) { synchronized ( dataList ) { dataList . add ( value ) ; return aliasIndexMap . put ( alias , dataList . size ( ) - 1 ) ; } }
Add with alias integer .
18,517
synchronized public void putAlias ( String alias , int index ) { JMLambda . runByBoolean ( index < size ( ) , ( ) -> aliasIndexMap . put ( alias , index ) , ( ) -> JMExceptionManager . logRuntimeException ( log , "Wrong Index !!! - " + "dataList Size = " + dataList , "setKeyIndexMap" , index ) ) ; }
Put alias .
18,518
public ModelService getModelService ( String serviceName ) { ModelService service = null ; try { service = getDirectoryServiceClient ( ) . lookupService ( serviceName ) ; } catch ( ServiceException se ) { if ( se . getErrorCode ( ) == ErrorCode . SERVICE_DOES_NOT_EXIST ) { LOGGER . error ( se . getMessage ( ) ) ; } else { LOGGER . error ( "Error when getModelService" , se ) ; } throw se ; } return service ; }
Get the ModelService by service name .
18,519
public ModelServiceInstance getModelServiceInstanceByAddress ( String serviceName , String instanceAddress ) { ModelService service = getModelService ( serviceName ) ; if ( service != null && service . getServiceInstances ( ) != null ) { for ( ModelServiceInstance instance : service . getServiceInstances ( ) ) { if ( instance . getAddress ( ) . equals ( instanceAddress ) ) { return instance ; } } } return null ; }
Get the ModelServiceInstance by serviceName and instanceAddress .
18,520
public List < ModelServiceInstance > getUPModelInstancesByMetadataKey ( String keyName ) { List < ModelServiceInstance > list = new ArrayList < > ( ) ; for ( ModelServiceInstance instance : getModelInstancesByMetadataKey ( keyName ) ) { if ( instance . getStatus ( ) . equals ( OperationalStatus . UP ) ) { list . add ( instance ) ; } } return list ; }
Get the UP ModelServiceInstance list that contains the metadata key .
18,521
public List < ModelServiceInstance > getAllInstances ( ) { List < ModelServiceInstance > result = Collections . emptyList ( ) ; try { result = getDirectoryServiceClient ( ) . getAllInstances ( ) ; } catch ( ServiceException se ) { LOGGER . error ( "Error when getAllInstances()" , se ) ; } return result ; }
Get All ModelServiceInstance on the Directory Server .
18,522
public void setState ( S state ) { Integer id = definition . getStateId ( state ) ; currentStateId . set ( id ) ; }
Set current state of the state machine . This method is multi - thread safe .
18,523
public boolean transit ( T transition ) { S currentState = definition . getState ( currentStateId . get ( ) ) ; if ( currentState != null ) { try { Transition < S > transitionDef = definition . getTransition ( currentState , transition ) ; return currentStateId . compareAndSet ( transitionDef . fromStateId , transitionDef . toStateId ) ; } catch ( IllegalArgumentException iae ) { return false ; } catch ( NullPointerException npe ) { return false ; } } return false ; }
Transit from current state to another . The method is multi - thread safe .
18,524
public static ConsoleParser [ ] filterExisting ( final Collection < ? extends ConsoleParser > parsers ) { List < ConsoleParser > existing = Lists . newArrayList ( ) ; for ( ConsoleParser parser : parsers ) { if ( ParserRegistry . exists ( parser . getParserName ( ) ) ) { existing . add ( parser ) ; } } return existing . toArray ( new ConsoleParser [ existing . size ( ) ] ) ; }
Removes non - existing parsers from the specified list .
18,525
static void createGeneratedFilesDirectory ( String apiName ) { File folder = new File ( getDestinationDirectory ( apiName ) ) ; if ( ! folder . exists ( ) ) { folder . mkdirs ( ) ; } }
Creates the destination directory of the generated files if not exists .
18,526
static void writeClassToFile ( String className , ClassWriter classWriter , String apiName ) { classWriter . visitEnd ( ) ; byte [ ] constructedClass = classWriter . toByteArray ( ) ; try ( FileOutputStream os = new FileOutputStream ( new File ( getFinalPathPart ( className , apiName ) ) ) ) { os . write ( constructedClass ) ; } catch ( IOException e ) { throw new AsmException ( "Exception while writing generated classes to the .class files." , e ) ; } }
Writes a given class to a . class file .
18,527
static String getFullJavaType ( XsdAttribute attribute ) { List < XsdRestriction > restrictions = getAttributeRestrictions ( attribute ) ; String javaType = xsdFullTypesToJava . getOrDefault ( attribute . getType ( ) , null ) ; if ( javaType == null ) { if ( ! restrictions . isEmpty ( ) ) { return xsdFullTypesToJava . getOrDefault ( restrictions . get ( 0 ) . getBase ( ) , JAVA_OBJECT_DESC ) ; } return JAVA_OBJECT_DESC ; } return javaType ; }
Obtains the java type descriptor based on the attribute type attribute .
18,528
static List < XsdRestriction > getAttributeRestrictions ( XsdAttribute attribute ) { try { return attribute . getAllRestrictions ( ) ; } catch ( InvalidParameterException e ) { throw new AsmException ( "The provided XSD file has contradictory restrictions." , e ) ; } }
Obtains the attribute restrictions .
18,529
static void generateMethodsAndCreateAttribute ( Map < String , List < XsdAttribute > > createdAttributes , ClassWriter classWriter , XsdAttribute elementAttribute , String returnType , String className , String apiName ) { XsdAsmAttributes . generateMethodsForAttribute ( classWriter , elementAttribute , returnType , className , apiName ) ; createAttribute ( createdAttributes , elementAttribute ) ; }
Generates the required methods for adding a given attribute and creates the respective class if needed .
18,530
static String getClassSignature ( String [ ] interfaces , String className , String apiName ) { StringBuilder signature ; signature = new StringBuilder ( "<Z::" + XsdSupportingStructure . elementTypeDesc + ">" + JAVA_OBJECT_DESC ) ; if ( interfaces != null ) { for ( String anInterface : interfaces ) { signature . append ( "L" ) . append ( getFullClassTypeName ( anInterface , apiName ) ) . append ( "<L" ) . append ( getFullClassTypeName ( className , apiName ) ) . append ( "<TZ;>;TZ;>;" ) ; } } return signature . toString ( ) ; }
Obtains the signature for a class given the interface names .
18,531
static String getInterfaceSignature ( String [ ] interfaces , String apiName ) { StringBuilder signature = new StringBuilder ( "<T::L" + XsdSupportingStructure . elementType + "<TT;TZ;>;Z::" + XsdSupportingStructure . elementTypeDesc + ">" + JAVA_OBJECT_DESC ) ; if ( interfaces != null ) { for ( String anInterface : interfaces ) { signature . append ( "L" ) . append ( getFullClassTypeName ( anInterface , apiName ) ) . append ( "<TT;TZ;>;" ) ; } } return signature . toString ( ) ; }
Obtains the interface signature for a interface .
18,532
static ClassWriter generateClass ( String className , String superName , String [ ] interfaces , String signature , int classModifiers , String apiName ) { ClassWriter classWriter = new ClassWriter ( 0 ) ; if ( interfaces != null ) { for ( int i = 0 ; i < interfaces . length ; i ++ ) { interfaces [ i ] = getFullClassTypeName ( interfaces [ i ] , apiName ) ; } } classWriter . visit ( V1_8 , classModifiers , getFullClassTypeName ( className , apiName ) , signature , superName , interfaces ) ; return classWriter ; }
Generates an empty class .
18,533
private static List < String > getAllInterfaceMethodInfo ( List < InterfaceInfo > interfaceInfoList ) { List < String > names = new ArrayList < > ( ) ; if ( interfaceInfoList == null || interfaceInfoList . isEmpty ( ) ) { return names ; } interfaceInfoList . forEach ( ( InterfaceInfo interfaceInfo ) -> { if ( interfaceInfo . getMethodNames ( ) != null && ! interfaceInfo . getMethodNames ( ) . isEmpty ( ) ) { names . addAll ( interfaceInfo . getMethodNames ( ) ) ; } names . addAll ( getAllInterfaceMethodInfo ( interfaceInfo . getExtendedInterfaces ( ) ) ) ; } ) ; return names ; }
Obtain the names of all the methods in the current interface and all the extended interfaces .
18,534
public ArgumentOptions withMaxUsageWidth ( int maxWidth ) { if ( tty . isInteractive ( ) ) { this . usageWidth = Math . min ( maxWidth , tty . getTerminalSize ( ) . cols ) ; } else { this . usageWidth = maxWidth ; } return this ; }
Set the maximum usage width . The width is set as wide as possible based on the terminal column count but maximum the maxWidth .
18,535
public void addRows ( ResultSet rs ) throws SQLException { ResultSetMetaData rsmd = rs . getMetaData ( ) ; int columnCount = rsmd . getColumnCount ( ) ; while ( rs . next ( ) ) { Map < String , Object > row = new HashMap < String , Object > ( ) ; for ( int i = 1 ; i < columnCount + 1 ; i ++ ) { String colName = rsmd . getColumnName ( i ) ; Object colObj = rs . getObject ( i ) ; if ( colObj == null ) { row . put ( colName , colObj ) ; } else { if ( colObj instanceof oracle . sql . Datum ) { colObj = ( ( oracle . sql . TIMESTAMP ) colObj ) . toJdbc ( ) ; } if ( colObj instanceof java . sql . Timestamp ) { row . put ( colName , new Date ( ( ( java . sql . Timestamp ) colObj ) . getTime ( ) ) ) ; } else if ( colObj instanceof java . sql . Date ) { row . put ( colName , new Date ( ( ( java . sql . Date ) colObj ) . getTime ( ) ) ) ; } else { row . put ( colName , colObj ) ; } } } addRow ( row ) ; } }
Add rows from a JDBC ResultSet . Each row will be a HashMap mapped from a record of ResultSet .
18,536
private void setupPaths ( ) { sourcePath = processingEnv . getOptions ( ) . get ( OPT_SOURCEPATH ) ; classPath = processingEnv . getOptions ( ) . get ( OPT_CLASSPATH ) ; outputDirectory = processingEnv . getOptions ( ) . get ( OPT_CLASSOUTPUT ) ; if ( processingEnv . getClass ( ) . getName ( ) . equals ( "com.sun.tools.javac.processing.JavacProcessingEnvironment" ) ) { JavacProcessingEnvironment javacEnv = ( JavacProcessingEnvironment ) processingEnv ; Options options = Options . instance ( javacEnv . getContext ( ) ) ; if ( sourcePath == null ) { sourcePath = options . get ( OptionName . SOURCEPATH ) ; } if ( classPath == null ) { String classPath1 = options . get ( OptionName . CP ) ; String classPath2 = options . get ( OptionName . CLASSPATH ) ; if ( classPath1 != null ) { if ( classPath2 != null ) { classPath = classPath1 + File . pathSeparator + classPath2 ; } else { classPath = classPath1 ; } } else { classPath = classPath2 ; } } if ( outputDirectory == null ) { outputDirectory = options . get ( OptionName . D ) ; } } }
Sets class and output paths from command - line options .
18,537
@ Requires ( { "types != null" , "sources != null" , "types.size() == sources.size()" } ) protected void dumpSources ( List < TypeModel > types , List < SyntheticJavaFile > sources ) { Iterator < TypeModel > itType = types . iterator ( ) ; Iterator < SyntheticJavaFile > itFile = sources . iterator ( ) ; while ( itType . hasNext ( ) && itFile . hasNext ( ) ) { TypeModel type = itType . next ( ) ; SyntheticJavaFile file = itFile . next ( ) ; DebugUtils . dump ( type . getName ( ) . getBinaryName ( ) , file . getCharContent ( true ) . toString ( ) . getBytes ( ) , Kind . SOURCE ) ; } }
Dumps the computed Java source files in the dump directory of Contracts for Java .
18,538
@ Requires ( "roundEnv != null" ) @ Ensures ( "result != null" ) protected Set < TypeElement > getContractedRootElements ( RoundEnvironment roundEnv ) { Set < ? extends Element > allElements = roundEnv . getRootElements ( ) ; Set < TypeElement > contractedRootElements = new HashSet < TypeElement > ( allElements . size ( ) ) ; ContractFinder cf = new ContractFinder ( utils ) ; for ( Element e : allElements ) { if ( e . accept ( cf , null ) ) { contractedRootElements . add ( getRootElement ( e ) ) ; } } return contractedRootElements ; }
Returns the set of root elements that contain contracts . Contracts can have been directly declared as annotations or inherited through the hierarchy .
18,539
protected void writeForward ( Encoder encoder ) throws IOException { if ( encoder . node . index != encoder . fromNode . index ) { Bits bits = encoder . fromNode . bitsTo ( encoder . node ) ; short count = ( short ) ( encoder . node . getDepth ( ) - encoder . fromNode . getDepth ( ) ) ; if ( verbose != null ) { verbose . println ( String . format ( "Writing %s forward from %s to %s = %s" , count , encoder . fromNode . getDebugString ( ) , encoder . node . getDebugString ( ) , bits ) ) ; } encoder . out . writeVarShort ( count , 3 ) ; encoder . out . write ( bits ) ; } else { assert ( 0 == encoder . node . index ) ; encoder . out . writeVarShort ( ( short ) 0 , 3 ) ; } }
Write forward .
18,540
protected void readForward ( Decoder decoder ) throws IOException { short numberOfTokens = decoder . in . readVarShort ( 3 ) ; if ( 0 < numberOfTokens ) { long seek = decoder . in . peekLongCoord ( decoder . node . getCursorCount ( ) ) ; TrieNode toNode = decoder . node . traverse ( seek + decoder . node . getCursorIndex ( ) ) ; while ( toNode . getDepth ( ) > decoder . node . getDepth ( ) + numberOfTokens ) toNode = toNode . getParent ( ) ; Interval interval = decoder . node . intervalTo ( toNode ) ; String str = toNode . getString ( decoder . node ) ; Bits bits = interval . toBits ( ) ; if ( verbose != null ) { verbose . println ( String . format ( "Read %s forward from %s to %s = %s" , numberOfTokens , decoder . node . getDebugString ( ) , toNode . getDebugString ( ) , bits ) ) ; } decoder . in . expect ( bits ) ; decoder . out . append ( str ) ; decoder . node = toNode ; } else { assert ( 0 == decoder . node . index ) ; } }
Read forward .
18,541
protected Optional < TrieNode > writeBackup ( Encoder encoder , char token ) throws IOException { Optional < TrieNode > child = Optional . empty ( ) ; while ( ! child . isPresent ( ) ) { encoder . node = encoder . node . godparent ( ) ; if ( encoder . node == null ) break ; child = ( Optional < TrieNode > ) encoder . node . getChild ( token ) ; } assert ( null == encoder . node || child . isPresent ( ) ) ; if ( null != encoder . node ) { for ( int i = 0 ; i < 2 ; i ++ ) { if ( 0 != encoder . node . index ) encoder . node = encoder . node . godparent ( ) ; } child = ( Optional < TrieNode > ) encoder . node . getChild ( token ) ; while ( ! child . isPresent ( ) ) { encoder . node = encoder . node . godparent ( ) ; if ( encoder . node == null ) break ; child = ( Optional < TrieNode > ) encoder . node . getChild ( token ) ; } assert ( null == encoder . node || child . isPresent ( ) ) ; } short backupSteps = ( short ) ( encoder . fromNode . getDepth ( ) - ( null == encoder . node ? - 1 : encoder . node . getDepth ( ) ) ) ; assert ( backupSteps >= 0 ) ; if ( verbose != null ) { verbose . println ( String . format ( "Backing up %s from from %s to %s" , backupSteps , encoder . fromNode . getDebugString ( ) , null == encoder . node ? null : encoder . node . getDebugString ( ) ) ) ; } encoder . out . writeVarShort ( backupSteps , 3 ) ; return child ; }
Write backup optional .
18,542
protected boolean readBackup ( Decoder decoder ) throws IOException { short numberOfBackupSteps = decoder . in . readVarShort ( 3 ) ; TrieNode fromNode = decoder . node ; if ( 0 == numberOfBackupSteps ) return true ; for ( int i = 0 ; i < numberOfBackupSteps ; i ++ ) { decoder . node = decoder . node . godparent ( ) ; } if ( verbose != null ) { verbose . println ( String . format ( "Backing up %s from from %s to %s" , numberOfBackupSteps , fromNode . getDebugString ( ) , decoder . node . getDebugString ( ) ) ) ; } return false ; }
Read backup boolean .
18,543
protected void writeTerminal ( Encoder encoder ) throws IOException { if ( verbose != null ) { verbose . println ( String . format ( "Writing forward to end from %s to %s" , encoder . fromNode . getDebugString ( ) , encoder . node . getDebugString ( ) ) ) ; } encoder . out . writeVarShort ( ( short ) ( encoder . node . getDepth ( ) - encoder . fromNode . getDepth ( ) ) , 3 ) ; encoder . out . write ( encoder . fromNode . bitsTo ( encoder . node ) ) ; encoder . out . writeVarShort ( ( short ) 0 , 3 ) ; }
Write terminal .
18,544
private boolean checkDeadLoop ( Object value ) { int n = 0 ; Object obj = value ; while ( obj != null ) { Record rec = objRecordMap . get ( obj ) ; if ( rec != null && rec . exp != null ) { obj = rec . exp . getTarget ( ) ; } else { break ; } if ( obj != null && ( obj . getClass ( ) . isAssignableFrom ( value . getClass ( ) ) ) && obj . equals ( value ) ) { n ++ ; if ( n >= DEADLOCK_THRESHOLD ) { return true ; } } } return false ; }
Imperfect attempt to detect a dead loop . This works with specific patterns that can be found in our AWT implementation . See HARMONY - 5707 for details .
18,545
public void writeExpression ( Expression oldExp ) { if ( null == oldExp ) { throw new NullPointerException ( ) ; } boolean oldWritingObject = writingObject ; writingObject = true ; Object oldValue = expressionValue ( oldExp ) ; if ( oldValue == null || get ( oldValue ) != null && ( oldWritingObject || oldValue . getClass ( ) != String . class ) ) { return ; } if ( ! isBasicType ( oldValue ) || ( ! oldWritingObject && oldValue . getClass ( ) == String . class ) ) { recordExpression ( oldValue , oldExp ) ; } if ( checkDeadLoop ( oldValue ) ) { return ; } super . writeExpression ( oldExp ) ; writingObject = oldWritingObject ; }
Records the expression so that it can be written out later then calls super implementation .
18,546
public void writeObject ( Object o ) { synchronized ( this ) { ArrayList < Object > prePending = objPrePendingCache . get ( o ) ; if ( prePending == null ) { boolean oldWritingObject = writingObject ; writingObject = true ; try { super . writeObject ( o ) ; } finally { writingObject = oldWritingObject ; } } else { flushPrePending . clear ( ) ; flushPrePending . addAll ( prePending ) ; } if ( ! writingObject ) { boolean isNotCached = prePending == null ; if ( isNotCached && o != null ) { prePending = new ArrayList < Object > ( ) ; prePending . addAll ( flushPrePending ) ; objPrePendingCache . put ( o , prePending ) ; } flushPending . addAll ( flushPrePending ) ; flushPendingStat . addAll ( flushPrePending ) ; flushPrePending . clear ( ) ; if ( isNotCached && flushPending . contains ( o ) ) { flushPendingStat . remove ( o ) ; } else { flushPending . add ( o ) ; } if ( needOwner ) { this . flushPending . remove ( owner ) ; this . flushPending . add ( 0 , owner ) ; } } } }
Records the object so that it can be written out later then calls super implementation .
18,547
public void writeStatement ( Statement oldStat ) { if ( null == oldStat ) { System . err . println ( "java.lang.Exception: XMLEncoder: discarding statement null" ) ; System . err . println ( "Continuing..." ) ; return ; } recordStatement ( oldStat ) ; super . writeStatement ( oldStat ) ; }
Records the statement so that it can be written out later then calls super implementation .
18,548
public void offerEvent ( final Event event ) throws IOException { if ( ! acceptEvents . get ( ) ) { return ; } eventsReceived . incrementAndGet ( ) ; try { log . debug ( "Writing event: {}" , event ) ; eventWriter . write ( event ) ; } catch ( IOException e ) { log . error ( String . format ( "Failed to write event: %s" , event ) , e ) ; eventsLost . incrementAndGet ( ) ; throw e ; } }
Offer an event to the queue .
18,549
@ SuppressWarnings ( "unchecked" ) static public Map < String , Object > getParameters ( ServletRequest request ) { Map < String , Object > params = ( Map < String , Object > ) request . getAttribute ( TEMPLATE_PARAMETER_MAP ) ; if ( params == null ) { params = new HashMap < String , Object > ( ) ; request . setAttribute ( TEMPLATE_PARAMETER_MAP , params ) ; } return params ; }
Get parameters from the attribute of servlet request .
18,550
@ SuppressWarnings ( "unchecked" ) public static boolean hasProperty ( Object obj , String name ) { if ( obj == null || name == null ) { return false ; } else if ( obj instanceof Map < ? , ? > ) { Map < Object , Object > map = ( Map < Object , Object > ) obj ; for ( Object key : map . keySet ( ) ) { if ( name . equalsIgnoreCase ( key . toString ( ) ) ) return true ; } return false ; } else if ( obj instanceof List < ? > ) { Integer index = IntegerConverter . toNullableInteger ( name ) ; List < Object > list = ( List < Object > ) obj ; return index != null && index . intValue ( ) >= 0 && index . intValue ( ) < list . size ( ) ; } else if ( obj . getClass ( ) . isArray ( ) ) { Integer index = IntegerConverter . toNullableInteger ( name ) ; int length = Array . getLength ( obj ) ; return index != null && index . intValue ( ) >= 0 && index . intValue ( ) < length ; } else { return PropertyReflector . hasProperty ( obj , name ) ; } }
Checks if object has a property with specified name .
18,551
public void sendTextToNextAlert ( String text ) { Alert alert = driver . switchTo ( ) . alert ( ) ; alert . sendKeys ( text ) ; alert . accept ( ) ; }
Enters the specified text into the upcoming input alert .
18,552
public void authenticateOnNextAlert ( String username , String password ) { Credentials credentials = new UserAndPassword ( username , password ) ; Alert alert = driver . switchTo ( ) . alert ( ) ; alert . authenticateUsing ( credentials ) ; }
Authenticates the user using the given username and password . This will work only if the credentials are requested through an alert window .
18,553
public void takeScreenshot ( String filename ) throws IOException { File screenshot = ( ( TakesScreenshot ) driver ) . getScreenshotAs ( OutputType . FILE ) ; FileUtils . copyFile ( screenshot , new File ( filename ) ) ; }
Takes a screenshot of the current screen .
18,554
public boolean verifyCookiePresentByName ( final String cookieName ) { Set < Cookie > cookies = driver . manage ( ) . getCookies ( ) ; for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( cookieName ) ) { LOG . info ( "Cookie: " + cookieName + " was found with value: " + cookie . getValue ( ) ) ; return true ; } } LOG . info ( "Cookie: " + cookieName + " NOT found!" ) ; return false ; }
Checks if the given cookie name exists in the current session . This method is also logging the result . The match is CASE SENSITIVE .
18,555
public boolean verifyText ( final By by , final String text ) { WebElement element = driver . findElement ( by ) ; if ( element . getText ( ) . equals ( text ) ) { LOG . info ( "Element: " + element + " contains the given text: " + text ) ; return true ; } LOG . info ( "Element: " + element + " does NOT contain the given text: " + text ) ; return false ; }
Verifies that the given element contains the given text .
18,556
public boolean verifyChecked ( final By checkboxBy ) { WebElement element = driver . findElement ( checkboxBy ) ; if ( element . isSelected ( ) ) { LOG . info ( "Checkbox: " + element + " is checked!" ) ; return true ; } LOG . info ( "Checkbox: " + element + " is NOT checked!" ) ; return false ; }
Verifies that the given checkbox is checked .
18,557
public void assertCookiePresentByName ( final String cookieName ) { Set < Cookie > cookies = driver . manage ( ) . getCookies ( ) ; for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( cookieName ) ) { LOG . info ( "Cookie: " + cookieName + " was found with value: " + cookie . getValue ( ) ) ; Assert . assertEquals ( cookieName , cookie . getName ( ) ) ; return ; } } Assert . fail ( "The given cookie name: " + cookieName + " is not present within the current session!" ) ; }
Checks if the given cookie name exists in the current session . This method is also logging the result . The match is CASE SENSITIVE . Please not that the method will do a JUNIT Assert causing the test to fail .
18,558
public void assertCookie ( final String cookieName , final String cookieValue ) { Set < Cookie > cookies = driver . manage ( ) . getCookies ( ) ; for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( cookieName ) && cookie . getValue ( ) . equals ( cookieValue ) ) { LOG . info ( "Cookie: " + cookieName + " was found with value: " + cookie . getValue ( ) ) ; return ; } } Assert . fail ( "Cookie: " + cookieName + " with value: " + cookieValue + " NOT found!" ) ; }
Verifies that the given cookie name has the given cookie value . This method is also add logging info . Please not that the method will do a JUNIT Assert causing the test to fail .
18,559
public void assertText ( final By by , final String text ) { WebElement element = driver . findElement ( by ) ; Assert . assertEquals ( "Element: " + element + " does NOT contain the given text: " + text , text , element . getText ( ) ) ; }
Verifies that the given element contains the given text . Please not that the method will do a JUNIT Assert causing the test to fail .
18,560
public void assertChecked ( final By checkboxBy ) { WebElement element = driver . findElement ( checkboxBy ) ; Assert . assertTrue ( "Checkbox: " + element + " is NOT checked!" , element . isSelected ( ) ) ; }
Verifies that the given checkbox is checked . Please not that the method will do a JUNIT Assert causing the test to fail .
18,561
public boolean isElementPresent ( final By by ) { try { driver . findElement ( by ) ; } catch ( Exception e ) { return false ; } return true ; }
Checks if the specified element is present into the page .
18,562
public void waitForElementPresent ( final By by , final int maximumSeconds ) { WebDriverWait wait = new WebDriverWait ( driver , maximumSeconds ) ; wait . until ( ExpectedConditions . presenceOfElementLocated ( ( by ) ) ) ; }
Waits until an element will be displayed into the page .
18,563
public void waitForTextPresentWithinPage ( final String text , final int maximumSeconds ) { WebDriverWait wait = new WebDriverWait ( driver , maximumSeconds ) ; wait . until ( ExpectedConditions . textToBePresentInElement ( By . tagName ( "body" ) , text ) ) ; }
Waits until a text will be displayed within the page .
18,564
public void waitForElementToBeVisible ( final By by , final int maximumSeconds ) { WebDriverWait wait = new WebDriverWait ( driver , maximumSeconds ) ; wait . until ( ExpectedConditions . visibilityOfElementLocated ( by ) ) ; }
Waits until a WebElement will be displayed into the page .
18,565
public void waitForElementToContainText ( final By by , final int maximumSeconds ) { ( new WebDriverWait ( driver , maximumSeconds ) ) . until ( new ExpectedCondition < Boolean > ( ) { public Boolean apply ( final WebDriver error1 ) { return ! driver . findElement ( by ) . getText ( ) . isEmpty ( ) ; } } ) ; }
Waits for an element to contain some text .
18,566
public void waitForElementToContainSpecificText ( final By by , final String text , final int maximumSeconds ) { WebDriverWait wait = new WebDriverWait ( driver , maximumSeconds ) ; wait . until ( ExpectedConditions . textToBePresentInElement ( by , text ) ) ; }
Waits until an element contains a specific text .
18,567
public boolean isTextPresentInPage ( final String text ) { WebElement body = driver . findElement ( By . tagName ( "body" ) ) ; return body . getText ( ) . contains ( text ) ; }
Checks for presence of the text in a html page .
18,568
public void selectOptionFromDropdownByValue ( final By by , final String value ) { Select select = new Select ( driver . findElement ( by ) ) ; select . selectByValue ( value ) ; }
Select a value from a drop down list based on the actual value NOT DISPLAYED TEXT .
18,569
public void selectOptionFromDropdownByDisplayText ( final By by , final String displayText ) { Select select = new Select ( driver . findElement ( by ) ) ; select . selectByVisibleText ( displayText ) ; }
Select text from a drop down list based on the displayed text .
18,570
public boolean isTextSelectedInDropDown ( final By by , final String displayText ) { WebElement element = driver . findElement ( by ) ; List < WebElement > options = element . findElements ( By . xpath ( ".//option[normalize-space(.) = " + escapeQuotes ( displayText ) + "]" ) ) ; for ( WebElement opt : options ) { if ( opt . isSelected ( ) ) { return true ; } } return false ; }
Checks if a text is selected in a drop down list . This will consider the display text not the actual value .
18,571
public String getSelectedValue ( final By by ) { Select select = new Select ( driver . findElement ( by ) ) ; String defaultSelectedValue = select . getFirstSelectedOption ( ) . getText ( ) ; return defaultSelectedValue ; }
Returns the first selected value from a drop down list .
18,572
public boolean isValueSelectedInDropDown ( final By by , final String value ) { WebElement element = driver . findElement ( by ) ; StringBuilder builder = new StringBuilder ( ".//option[@value = " ) ; builder . append ( escapeQuotes ( value ) ) ; builder . append ( "]" ) ; List < WebElement > options = element . findElements ( By . xpath ( builder . toString ( ) ) ) ; for ( WebElement opt : options ) { if ( opt . isSelected ( ) ) { return true ; } } return false ; }
Checks if a value is selected in a drop down list .
18,573
public void selectRadioButtonByValue ( final String radioButtonName , final String value ) { List < WebElement > radioGroup = driver . findElements ( By . name ( radioButtonName ) ) ; for ( WebElement button : radioGroup ) { if ( button . getAttribute ( "value" ) . equalsIgnoreCase ( value ) ) { button . click ( ) ; break ; } } }
Select the supplied value from a radio button group .
18,574
public boolean isRadioButtonValueSelected ( final String radioButtonName , final String value ) { List < WebElement > radioGroup = driver . findElements ( By . name ( radioButtonName ) ) ; for ( WebElement button : radioGroup ) { if ( button . getAttribute ( "value" ) . equalsIgnoreCase ( value ) && button . isSelected ( ) ) { return true ; } } return false ; }
Checks if a radio button group has the supplied value selected .
18,575
public void selectWindowByTitle ( final String title ) { String currentWindow = driver . getWindowHandle ( ) ; Set < String > handles = driver . getWindowHandles ( ) ; if ( ! handles . isEmpty ( ) ) { for ( String windowId : handles ) { if ( ! driver . switchTo ( ) . window ( windowId ) . getTitle ( ) . equals ( title ) ) { driver . switchTo ( ) . window ( currentWindow ) ; } } } }
Used to switch to a window by title .
18,576
public static WebDriver getDriverWithProxy ( final String proxyURL , final String port , final WebDriver driver ) { org . openqa . selenium . Proxy proxy = new org . openqa . selenium . Proxy ( ) ; proxy . setHttpProxy ( proxyURL + ":" + port ) . setFtpProxy ( proxyURL + ":" + port ) . setSslProxy ( proxyURL + ":" + port ) ; DesiredCapabilities cap = new DesiredCapabilities ( ) ; cap . setCapability ( CapabilityType . PROXY , proxy ) ; try { Constructor < ? > c = driver . getClass ( ) . getConstructor ( Capabilities . class ) ; return ( WebDriver ) c . newInstance ( cap ) ; } catch ( Exception e ) { LOG . error ( "Exception while creating a driver with the specified proxy" , e ) ; } return driver ; }
Returns a WebDriver object that has the proxy server set .
18,577
public static WebDriver getFirefoxDriverWithUserAgent ( final String userAgent ) { ProfilesIni allProfiles = new ProfilesIni ( ) ; FirefoxProfile profile = allProfiles . getProfile ( "default" ) ; profile . setPreference ( "general.useragent.override" , userAgent ) ; profile . setAcceptUntrustedCertificates ( true ) ; profile . setAssumeUntrustedCertificateIssuer ( true ) ; WebDriver driver = new FirefoxDriver ( profile ) ; return driver ; }
Creates a FirefoxDriver that has the supplied user agent .
18,578
public static WebDriver getFirefoxDriverWithExistingProfile ( final String pathToProfile ) { FirefoxProfile profile = new FirefoxProfile ( new File ( pathToProfile ) ) ; return new FirefoxDriver ( profile ) ; }
Returns a new WebDriver instance and loads an existing profile from the disk . You must pass the path to the profile .
18,579
public String escapeQuotes ( final String toEscape ) { if ( toEscape . indexOf ( "\"" ) > - 1 && toEscape . indexOf ( "'" ) > - 1 ) { boolean quoteIsLast = false ; if ( toEscape . indexOf ( "\"" ) == toEscape . length ( ) - 1 ) { quoteIsLast = true ; } String [ ] substrings = toEscape . split ( "\"" ) ; StringBuilder quoted = new StringBuilder ( "concat(" ) ; for ( int i = 0 ; i < substrings . length ; i ++ ) { quoted . append ( "\"" ) . append ( substrings [ i ] ) . append ( "\"" ) ; quoted . append ( ( ( i == substrings . length - 1 ) ? ( quoteIsLast ? ", '\"')" : ")" ) : ", '\"', " ) ) ; } return quoted . toString ( ) ; } if ( toEscape . indexOf ( "\"" ) > - 1 ) { return String . format ( "'%s'" , toEscape ) ; } return String . format ( "\"%s\"" , toEscape ) ; }
Escapes the quotes for the supplied string .
18,580
public static WebDriver getFirefoxDriverWithJSSettings ( final String userAgent , final boolean javascriptEnabled ) { FirefoxProfile profile = new FirefoxProfile ( ) ; profile . setPreference ( "general.useragent.override" , userAgent ) ; profile . setPreference ( "javascript.enabled" , javascriptEnabled ) ; WebDriver driver = new FirefoxDriver ( profile ) ; return driver ; }
Gets a profile with a specific user agent with or without javascript enabled .
18,581
private static WebDriver getDriverInstance ( final DesiredCapabilities capabilities , final Builder builder ) { WebDriver driver = null ; try { Class < ? > clazz = Class . forName ( "org.openqa.selenium." + builder . browserPackage + "." + StringUtils . capitalize ( builder . browser + "Driver" ) ) ; LOG . info ( "Driver class to be returned: " + clazz ) ; Constructor < ? > c = clazz . getConstructor ( Capabilities . class ) ; LOG . info ( "Driver constructor to be called: " + c ) ; driver = ( WebDriver ) c . newInstance ( new Object [ ] { capabilities } ) ; LOG . info ( "Driver initialized: " + driver ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Browser " + builder . browser + " is not a valid name!" , e ) ; } LOG . info ( "Returned driver instance: " + driver ) ; return driver ; }
Returns a web driver instance based on capabilities .
18,582
private static void addSpecificBrowserSettings ( final DesiredCapabilities capabilities , final Builder builder ) { if ( capabilities . getBrowserName ( ) . equalsIgnoreCase ( Constants . Browsers . FIREFOX ) ) { LOG . info ( "Browser is Firefox. Getting local profile" ) ; FirefoxProfile profile = null ; if ( builder . profileLocation != null && ! "" . equalsIgnoreCase ( builder . profileLocation ) ) { profile = new FirefoxProfile ( new File ( builder . profileLocation ) ) ; LOG . info ( "Firefox profile: " + builder . profileLocation ) ; } else { LOG . info ( "Loading Firefox default sprofile" ) ; ProfilesIni allProfiles = new ProfilesIni ( ) ; allProfiles . getProfile ( "default" ) ; } capabilities . setCapability ( FirefoxDriver . PROFILE , profile ) ; if ( builder . userAgent != null ) { profile . setPreference ( "general.useragent.override" , builder . userAgent ) ; } } else if ( capabilities . getBrowserName ( ) . equalsIgnoreCase ( Constants . Browsers . CHROME ) ) { ChromeOptions options = new ChromeOptions ( ) ; if ( builder . userAgent != null ) { options . addArguments ( "user-agent=" + builder . userAgent ) ; } capabilities . setCapability ( ChromeOptions . CAPABILITY , options ) ; } else if ( capabilities . getBrowserName ( ) . equalsIgnoreCase ( Constants . Browsers . IE ) ) { capabilities . setCapability ( InternetExplorerDriver . INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS , builder . flakinessForIe ) ; } LOG . info ( "Finished adding specific browser settings" ) ; }
This method adds browser specific capabilities like FirefoxProfile and ChromeOptions .
18,583
private static WebDriver getDriver ( final Builder builder ) { DesiredCapabilities capabilities = getCapabilitiesBrowser ( builder . browser ) ; WebDriver driver = null ; LOG . info ( "Proxy seetings set" ) ; org . openqa . selenium . Proxy proxy = new org . openqa . selenium . Proxy ( ) ; if ( builder . proxyHost != null && ! builder . proxyHost . isEmpty ( ) ) { if ( ! builder . proxyHost . equals ( "direct" ) ) { proxy . setAutodetect ( false ) ; proxy . setHttpProxy ( builder . proxyHost + ":" + builder . proxyPort ) . setFtpProxy ( builder . proxyHost + ":" + builder . proxyPort ) . setSslProxy ( builder . proxyHost + ":" + builder . proxyPort ) . setNoProxy ( builder . noProxyFor ) ; } else { proxy . setProxyType ( ProxyType . DIRECT ) ; } capabilities . setCapability ( CapabilityType . PROXY , proxy ) ; } LOG . info ( "Screenshot capability set" ) ; capabilities . setCapability ( CapabilityType . TAKES_SCREENSHOT , true ) ; if ( builder . platform != null ) { capabilities . setCapability ( CapabilityType . PLATFORM , builder . platform ) ; } if ( builder . browserVersion != null ) { capabilities . setCapability ( CapabilityType . VERSION , builder . browserVersion ) ; } capabilities . setJavascriptEnabled ( builder . jsEnabled ) ; capabilities . setCapability ( CapabilityType . ACCEPT_SSL_CERTS , builder . acceptAllCertificates ) ; LOG . info ( "Adding specific browser settings" ) ; addSpecificBrowserSettings ( capabilities , builder ) ; LOG . info ( "Detecting running mode" ) ; if ( builder . runMode . equalsIgnoreCase ( Constants . RunMode . GRID ) ) { LOG . info ( "Run mode GRID. Setting GRID properties" ) ; try { driver = new RemoteWebDriver ( new URL ( builder . gridUrl ) , capabilities ) ; ( ( RemoteWebDriver ) driver ) . setLogLevel ( Level . SEVERE ) ; } catch ( Exception e ) { LOG . debug ( "Exception while initiating remote driver:" , e ) ; } } else { LOG . info ( "Normal run mode. Getting driver instance" ) ; driver = getDriverInstance ( capabilities , builder ) ; } LOG . info ( "Returning the following driver: " + driver ) ; LOG . info ( "With capabilities: " + capabilities ) ; return driver ; }
This method returns a fully configured WebDriver instance based on the parameters sent .
18,584
public void goToUrlWithCookie ( final String url , final String cookieName , final String cookieValue ) { LOG . info ( "Getting: " + url + " with cookieName: " + cookieName + " and cookieValue: " + cookieValue ) ; driver . get ( url + "/404.html" ) ; driver . manage ( ) . deleteAllCookies ( ) ; driver . manage ( ) . addCookie ( new Cookie ( cookieName , cookieValue ) ) ; driver . get ( url ) ; }
Opens the specified URL using the specified cookie .
18,585
public void goToUrlWithCookies ( final String url , final Map < String , String > cookieNamesValues ) { LOG . info ( "Getting: " + url + " with cookies: " + cookieNamesValues ) ; driver . get ( url + "/404.html" ) ; driver . manage ( ) . deleteAllCookies ( ) ; Set < Entry < String , String > > entries = cookieNamesValues . entrySet ( ) ; for ( Entry < String , String > cookieEntry : entries ) { driver . manage ( ) . addCookie ( new Cookie ( cookieEntry . getKey ( ) , cookieEntry . getValue ( ) ) ) ; } driver . get ( url ) ; }
Opens the specified URL using the specified cookies list .
18,586
public List < List < String > > getTableAsList ( final By tableBy ) { List < List < String > > all = new ArrayList < List < String > > ( ) ; WebElement table = driver . findElement ( tableBy ) ; List < WebElement > rows = table . findElements ( By . tagName ( "tr" ) ) ; for ( WebElement row : rows ) { List < String > toAdd = new ArrayList < String > ( ) ; List < WebElement > columns = row . findElements ( By . tagName ( "td" ) ) ; for ( WebElement column : columns ) { toAdd . add ( column . getText ( ) ) ; } all . add ( toAdd ) ; } return all ; }
Returns the contents of the table as a list . Each item in the list contains a table row .
18,587
public List < String > getTableColumn ( final By tableBy , final int columnNumber ) { List < String > result = new ArrayList < String > ( ) ; List < List < String > > table = this . getTableAsList ( tableBy ) ; for ( List < String > line : table ) { result . add ( line . get ( columnNumber ) ) ; } return result ; }
Returns the values for a specific column from a HTML table .
18,588
public static < T > Collector < T , LinkedList < List < T > > , Stream < List < T > > > inBatchesOf ( int itemsPerBatch ) { return Collector . of ( LinkedList :: new , ( l , i ) -> { if ( l . isEmpty ( ) || l . peekLast ( ) . size ( ) >= itemsPerBatch ) { l . add ( new ArrayList < > ( itemsPerBatch ) ) ; } l . peekLast ( ) . add ( i ) ; } , ( a , b ) -> { while ( ! b . isEmpty ( ) ) { for ( T i : b . peekFirst ( ) ) { if ( a . peekLast ( ) . size ( ) >= itemsPerBatch ) { a . add ( new ArrayList < > ( itemsPerBatch ) ) ; } a . peekLast ( ) . add ( i ) ; } b . pollFirst ( ) ; } return a ; } , Collection :: stream ) ; }
Collect into batches of max N items per batch . Creates a stream of lists as response .
18,589
public static < T > Collector < T , ArrayList < List < T > > , Stream < List < T > > > inNumBatches ( int numBatches ) { AtomicInteger nextPos = new AtomicInteger ( 0 ) ; AtomicInteger numTotal = new AtomicInteger ( 0 ) ; return Collector . of ( ( ) -> { ArrayList < List < T > > batches = new ArrayList < > ( numBatches ) ; for ( int i = 0 ; i < numBatches ; ++ i ) { batches . add ( new ArrayList < > ( ) ) ; } return batches ; } , ( batches , item ) -> { int pos = nextPos . getAndUpdate ( i -> ( ++ i ) % numBatches ) ; batches . get ( pos ) . add ( item ) ; numTotal . incrementAndGet ( ) ; } , ( a , b ) -> { for ( int i = 0 ; i < numBatches ; ++ i ) { List < T > al = a . get ( i ) ; List < T > bl = b . get ( i ) ; al . addAll ( bl ) ; } return a ; } , batches -> { if ( numTotal . get ( ) < numBatches ) { return batches . subList ( 0 , numTotal . get ( ) ) . stream ( ) ; } return batches . stream ( ) ; } ) ; }
Collect into N batches of approximate equal size . Creates a stream of lists as response .
18,590
NodeData getData ( ) { if ( null == data ) { synchronized ( this ) { if ( null == data ) { this . data = this . trie . nodes . get ( index ) ; } } } return data ; }
Gets data .
18,591
public TrieNode godparent ( ) { if ( 0 == getDepth ( ) ) return null ; TrieNode root = trie . root ( ) ; if ( 1 == getDepth ( ) ) return root ; if ( null != trie . godparentIndex && trie . godparentIndex . length > index ) { int godparentIndex = trie . godparentIndex [ this . index ] ; if ( godparentIndex >= 0 ) { return newNode ( godparentIndex ) ; } } TrieNode parent = this . getParent ( ) ; TrieNode godparent ; if ( null == parent ) { godparent = root ; } else { TrieNode greatgodparent = parent . godparent ( ) ; if ( null == greatgodparent ) { godparent = root ; } else { godparent = greatgodparent . getChild ( getChar ( ) ) . map ( x -> ( TrieNode ) x ) . orElseGet ( ( ) -> root ) ; } } if ( null != godparent && null != trie . godparentIndex && trie . godparentIndex . length > index ) { trie . godparentIndex [ this . index ] = godparent . index ; } return godparent ; }
Godparent trie node .
18,592
public String getDebugString ( TrieNode root ) { if ( this == root ) return "" ; String parentStr = null == getParent ( ) ? "" : getParent ( ) . getDebugString ( root ) ; return parentStr + getDebugToken ( ) ; }
Gets debug string .
18,593
public String getDebugToken ( ) { char asChar = getChar ( ) ; if ( asChar == NodewalkerCodec . FALLBACK ) return "<STOP>" ; if ( asChar == NodewalkerCodec . END_OF_STRING ) return "<NULL>" ; if ( asChar == NodewalkerCodec . ESCAPE ) return "<ESC>" ; if ( asChar == '\\' ) return "\\\\" ; if ( asChar == '\n' ) return "\\n" ; return new String ( new char [ ] { asChar } ) ; }
Gets debug token .
18,594
public short getDepth ( ) { if ( 0 == index ) return 0 ; if ( - 1 == depth ) { synchronized ( this ) { if ( - 1 == depth ) { TrieNode parent = getParent ( ) ; assert ( null == parent || parent . index < index ) ; depth = ( short ) ( null == parent ? 0 : ( parent . getDepth ( ) + 1 ) ) ; } } } return depth ; }
Gets depth .
18,595
public TrieNode visitFirst ( Consumer < ? super TrieNode > visitor ) { visitor . accept ( this ) ; TrieNode refresh = refresh ( ) ; refresh . getChildren ( ) . forEach ( n -> n . visitFirst ( visitor ) ) ; return refresh ; }
Visit first trie node .
18,596
public TrieNode visitLast ( Consumer < ? super TrieNode > visitor ) { getChildren ( ) . forEach ( n -> n . visitLast ( visitor ) ) ; visitor . accept ( this ) ; return refresh ( ) ; }
Visit last trie node .
18,597
public Stream < ? extends TrieNode > getChildren ( ) { if ( getData ( ) . firstChildIndex >= 0 ) { return IntStream . range ( 0 , getData ( ) . numberOfChildren ) . mapToObj ( i -> new TrieNode ( this . trie , getData ( ) . firstChildIndex + i , TrieNode . this ) ) ; } else { return Stream . empty ( ) ; } }
Gets children .
18,598
public Optional < ? extends TrieNode > getChild ( char token ) { NodeData data = getData ( ) ; int min = data . firstChildIndex ; int max = data . firstChildIndex + data . numberOfChildren - 1 ; while ( min <= max ) { int i = ( min + max ) / 2 ; TrieNode node = new TrieNode ( this . trie , i , TrieNode . this ) ; char c = node . getChar ( ) ; int compare = Character . compare ( c , token ) ; if ( c < token ) { min = i + 1 ; } else if ( c > token ) { max = i - 1 ; } else { return Optional . of ( node ) ; } } return Optional . empty ( ) ; }
Gets child .
18,599
protected void decrementCursorCount ( long count ) { this . trie . nodes . update ( index , data -> data . setCursorCount ( Math . max ( data . cursorCount - count , 0 ) ) ) ; if ( null != getParent ( ) ) { getParent ( ) . decrementCursorCount ( count ) ; } }
Decrement cursor count .