idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
151,000
|
public static boolean isToStringMethod ( Method method ) { return ( method != null && method . getName ( ) . equals ( "readString" ) && method . getParameterTypes ( ) . length == 0 ) ; }
|
Determine whether the given method is a readString method .
| 47
| 13
|
151,001
|
public static Method [ ] getUniqueDeclaredMethods ( Class < ? > leafClass ) throws IllegalArgumentException { final List < Method > methods = new ArrayList < Method > ( 32 ) ; doWithMethods ( leafClass , new MethodCallback ( ) { @ Override public void doWith ( Method method ) { boolean knownSignature = false ; Method methodBeingOverriddenWithCovariantReturnType = null ; for ( Method existingMethod : methods ) { if ( method . getName ( ) . equals ( existingMethod . getName ( ) ) && Arrays . equals ( method . getParameterTypes ( ) , existingMethod . getParameterTypes ( ) ) ) { // Is this a covariant return type situation? if ( existingMethod . getReturnType ( ) != method . getReturnType ( ) && existingMethod . getReturnType ( ) . isAssignableFrom ( method . getReturnType ( ) ) ) { methodBeingOverriddenWithCovariantReturnType = existingMethod ; } else { knownSignature = true ; } break ; } } if ( methodBeingOverriddenWithCovariantReturnType != null ) { methods . remove ( methodBeingOverriddenWithCovariantReturnType ) ; } if ( ! knownSignature ) { methods . add ( method ) ; } } } ) ; return methods . toArray ( new Method [ methods . size ( ) ] ) ; }
|
Get the unique set of declared methods on the leaf class and all superclasses . Leaf class methods are included first and while traversing the superclass hierarchy any methods found with signatures matching a method already included are filtered out .
| 297
| 44
|
151,002
|
@ Override public V put ( K key , V value ) { if ( fast ) { synchronized ( this ) { Map < K , V > temp = cloneMap ( map ) ; V result = temp . put ( key , value ) ; map = temp ; return ( result ) ; } } else { synchronized ( map ) { return ( map . put ( key , value ) ) ; } } }
|
Associate the specified value with the specified key in this map . If the map previously contained a mapping for this key the old value is replaced and returned .
| 83
| 31
|
151,003
|
@ Override public void putAll ( Map < ? extends K , ? extends V > in ) { if ( fast ) { synchronized ( this ) { Map < K , V > temp = cloneMap ( map ) ; temp . putAll ( in ) ; map = temp ; } } else { synchronized ( map ) { map . putAll ( in ) ; } } }
|
Copy all of the mappings from the specified map to this one replacing any mappings with the same keys .
| 77
| 22
|
151,004
|
@ Override public V remove ( Object key ) { if ( fast ) { synchronized ( this ) { Map < K , V > temp = cloneMap ( map ) ; V result = temp . remove ( key ) ; map = temp ; return ( result ) ; } } else { synchronized ( map ) { return ( map . remove ( key ) ) ; } } }
|
Remove any mapping for this key and return any previously mapped value .
| 76
| 13
|
151,005
|
public static boolean isFileExist ( String filePath ) { if ( StringUtils . isEmpty ( filePath ) ) { return false ; } File file = new File ( filePath ) ; return ( file . exists ( ) && file . isFile ( ) ) ; }
|
Indicates if this file represents a file on the underlying file system .
| 58
| 14
|
151,006
|
public static boolean isFolderExist ( String directoryPath ) { if ( StringUtils . isEmpty ( directoryPath ) ) { return false ; } File dire = new File ( directoryPath ) ; return ( dire . exists ( ) && dire . isDirectory ( ) ) ; }
|
Indicates if this file represents a directory on the underlying file system .
| 58
| 14
|
151,007
|
public static void addToMediaStore ( Context context , File file ) { String [ ] path = new String [ ] { file . getPath ( ) } ; MediaScannerConnection . scanFile ( context , path , null , null ) ; }
|
another media scan way
| 51
| 4
|
151,008
|
@ Override public synchronized long skip ( final long length ) throws IOException { final long skip = super . skip ( length ) ; this . count += skip ; return skip ; }
|
Skips the stream over the specified number of bytes adding the skipped amount to the count .
| 37
| 18
|
151,009
|
public final void notifyHeaderItemRangeInserted ( int positionStart , int itemCount ) { int newHeaderItemCount = getHeaderItemCount ( ) ; if ( positionStart < 0 || itemCount < 0 || positionStart + itemCount > newHeaderItemCount ) { throw new IndexOutOfBoundsException ( "The given range [" + positionStart + " - " + ( positionStart + itemCount - 1 ) + "] is not within the position bounds for header items [0 - " + ( newHeaderItemCount - 1 ) + "]." ) ; } notifyItemRangeInserted ( positionStart , itemCount ) ; }
|
Notifies that multiple header items are inserted .
| 132
| 9
|
151,010
|
public final void notifyHeaderItemChanged ( int position ) { if ( position < 0 || position >= headerItemCount ) { throw new IndexOutOfBoundsException ( "The given position " + position + " is not within the position bounds for header items [0 - " + ( headerItemCount - 1 ) + "]." ) ; } notifyItemChanged ( position ) ; }
|
Notifies that a header item is changed .
| 78
| 9
|
151,011
|
public final void notifyHeaderItemRangeChanged ( int positionStart , int itemCount ) { if ( positionStart < 0 || itemCount < 0 || positionStart + itemCount >= headerItemCount ) { throw new IndexOutOfBoundsException ( "The given range [" + positionStart + " - " + ( positionStart + itemCount - 1 ) + "] is not within the position bounds for header items [0 - " + ( headerItemCount - 1 ) + "]." ) ; } notifyItemRangeChanged ( positionStart , itemCount ) ; }
|
Notifies that multiple header items are changed .
| 115
| 9
|
151,012
|
public void notifyHeaderItemMoved ( int fromPosition , int toPosition ) { if ( fromPosition < 0 || toPosition < 0 || fromPosition >= headerItemCount || toPosition >= headerItemCount ) { throw new IndexOutOfBoundsException ( "The given fromPosition " + fromPosition + " or toPosition " + toPosition + " is not within the position bounds for header items [0 - " + ( headerItemCount - 1 ) + "]." ) ; } notifyItemMoved ( fromPosition , toPosition ) ; }
|
Notifies that an existing header item is moved to another position .
| 113
| 13
|
151,013
|
public void notifyHeaderItemRangeRemoved ( int positionStart , int itemCount ) { if ( positionStart < 0 || itemCount < 0 || positionStart + itemCount > headerItemCount ) { throw new IndexOutOfBoundsException ( "The given range [" + positionStart + " - " + ( positionStart + itemCount - 1 ) + "] is not within the position bounds for header items [0 - " + ( headerItemCount - 1 ) + "]." ) ; } notifyItemRangeRemoved ( positionStart , itemCount ) ; }
|
Notifies that multiple header items are removed .
| 114
| 9
|
151,014
|
public final void notifyContentItemInserted ( int position ) { int newHeaderItemCount = getHeaderItemCount ( ) ; int newContentItemCount = getContentItemCount ( ) ; if ( position < 0 || position >= newContentItemCount ) { throw new IndexOutOfBoundsException ( "The given position " + position + " is not within the position bounds for content items [0 - " + ( newContentItemCount - 1 ) + "]." ) ; } notifyItemInserted ( position + newHeaderItemCount ) ; }
|
Notifies that a content item is inserted .
| 113
| 9
|
151,015
|
public final void notifyContentItemRangeInserted ( int positionStart , int itemCount ) { int newHeaderItemCount = getHeaderItemCount ( ) ; int newContentItemCount = getContentItemCount ( ) ; if ( positionStart < 0 || itemCount < 0 || positionStart + itemCount > newContentItemCount ) { throw new IndexOutOfBoundsException ( "The given range [" + positionStart + " - " + ( positionStart + itemCount - 1 ) + "] is not within the position bounds for content items [0 - " + ( newContentItemCount - 1 ) + "]." ) ; } notifyItemRangeInserted ( positionStart + newHeaderItemCount , itemCount ) ; }
|
Notifies that multiple content items are inserted .
| 150
| 9
|
151,016
|
public final void notifyContentItemChanged ( int position ) { if ( position < 0 || position >= contentItemCount ) { throw new IndexOutOfBoundsException ( "The given position " + position + " is not within the position bounds for content items [0 - " + ( contentItemCount - 1 ) + "]." ) ; } notifyItemChanged ( position + headerItemCount ) ; }
|
Notifies that a content item is changed .
| 82
| 9
|
151,017
|
public final void notifyContentItemRangeChanged ( int positionStart , int itemCount ) { if ( positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount ) { throw new IndexOutOfBoundsException ( "The given range [" + positionStart + " - " + ( positionStart + itemCount - 1 ) + "] is not within the position bounds for content items [0 - " + ( contentItemCount - 1 ) + "]." ) ; } notifyItemRangeChanged ( positionStart + headerItemCount , itemCount ) ; }
|
Notifies that multiple content items are changed .
| 119
| 9
|
151,018
|
public final void notifyContentItemMoved ( int fromPosition , int toPosition ) { if ( fromPosition < 0 || toPosition < 0 || fromPosition >= contentItemCount || toPosition >= contentItemCount ) { throw new IndexOutOfBoundsException ( "The given fromPosition " + fromPosition + " or toPosition " + toPosition + " is not within the position bounds for content items [0 - " + ( contentItemCount - 1 ) + "]." ) ; } notifyItemMoved ( fromPosition + headerItemCount , toPosition + headerItemCount ) ; }
|
Notifies that an existing content item is moved to another position .
| 122
| 13
|
151,019
|
public final void notifyContentItemRemoved ( int position ) { if ( position < 0 || position >= contentItemCount ) { throw new IndexOutOfBoundsException ( "The given position " + position + " is not within the position bounds for content items [0 - " + ( contentItemCount - 1 ) + "]." ) ; } notifyItemRemoved ( position + headerItemCount ) ; }
|
Notifies that a content item is removed .
| 82
| 9
|
151,020
|
public final void notifyContentItemRangeRemoved ( int positionStart , int itemCount ) { if ( positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount ) { throw new IndexOutOfBoundsException ( "The given range [" + positionStart + " - " + ( positionStart + itemCount - 1 ) + "] is not within the position bounds for content items [0 - " + ( contentItemCount - 1 ) + "]." ) ; } notifyItemRangeRemoved ( positionStart + headerItemCount , itemCount ) ; }
|
Notifies that multiple content items are removed .
| 119
| 9
|
151,021
|
public final void notifyFooterItemInserted ( int position ) { int newHeaderItemCount = getHeaderItemCount ( ) ; int newContentItemCount = getContentItemCount ( ) ; int newFooterItemCount = getFooterItemCount ( ) ; // if (position < 0 || position >= newFooterItemCount) { // throw new IndexOutOfBoundsException("The given position " + position // + " is not within the position bounds for footer items [0 - " // + (newFooterItemCount - 1) + "]."); // } notifyItemInserted ( position + newHeaderItemCount + newContentItemCount ) ; }
|
Notifies that a footer item is inserted .
| 140
| 10
|
151,022
|
public final void notifyFooterItemRangeInserted ( int positionStart , int itemCount ) { int newHeaderItemCount = getHeaderItemCount ( ) ; int newContentItemCount = getContentItemCount ( ) ; int newFooterItemCount = getFooterItemCount ( ) ; if ( positionStart < 0 || itemCount < 0 || positionStart + itemCount > newFooterItemCount ) { throw new IndexOutOfBoundsException ( "The given range [" + positionStart + " - " + ( positionStart + itemCount - 1 ) + "] is not within the position bounds for footer items [0 - " + ( newFooterItemCount - 1 ) + "]." ) ; } notifyItemRangeInserted ( positionStart + newHeaderItemCount + newContentItemCount , itemCount ) ; }
|
Notifies that multiple footer items are inserted .
| 174
| 10
|
151,023
|
public final void notifyFooterItemChanged ( int position ) { if ( position < 0 || position >= footerItemCount ) { throw new IndexOutOfBoundsException ( "The given position " + position + " is not within the position bounds for footer items [0 - " + ( footerItemCount - 1 ) + "]." ) ; } notifyItemChanged ( position + headerItemCount + contentItemCount ) ; }
|
Notifies that a footer item is changed .
| 90
| 10
|
151,024
|
public final void notifyFooterItemRangeChanged ( int positionStart , int itemCount ) { if ( positionStart < 0 || itemCount < 0 || positionStart + itemCount > footerItemCount ) { throw new IndexOutOfBoundsException ( "The given range [" + positionStart + " - " + ( positionStart + itemCount - 1 ) + "] is not within the position bounds for footer items [0 - " + ( footerItemCount - 1 ) + "]." ) ; } notifyItemRangeChanged ( positionStart + headerItemCount + contentItemCount , itemCount ) ; }
|
Notifies that multiple footer items are changed .
| 127
| 10
|
151,025
|
public final void notifyFooterItemMoved ( int fromPosition , int toPosition ) { if ( fromPosition < 0 || toPosition < 0 || fromPosition >= footerItemCount || toPosition >= footerItemCount ) { throw new IndexOutOfBoundsException ( "The given fromPosition " + fromPosition + " or toPosition " + toPosition + " is not within the position bounds for footer items [0 - " + ( footerItemCount - 1 ) + "]." ) ; } notifyItemMoved ( fromPosition + headerItemCount + contentItemCount , toPosition + headerItemCount + contentItemCount ) ; }
|
Notifies that an existing footer item is moved to another position .
| 135
| 14
|
151,026
|
public final void notifyFooterItemRangeRemoved ( int positionStart , int itemCount ) { if ( positionStart < 0 || itemCount < 0 || positionStart + itemCount > footerItemCount ) { throw new IndexOutOfBoundsException ( "The given range [" + positionStart + " - " + ( positionStart + itemCount - 1 ) + "] is not within the position bounds for footer items [0 - " + ( footerItemCount - 1 ) + "]." ) ; } notifyItemRangeRemoved ( positionStart + headerItemCount + contentItemCount , itemCount ) ; }
|
Notifies that multiple footer items are removed .
| 127
| 10
|
151,027
|
@ Override public View getView ( int position , View convertView , ViewGroup parent ) { if ( position == super . getCount ( ) && isEnableRefreshing ( ) ) { return ( mFooter ) ; } return ( super . getView ( position , convertView , parent ) ) ; }
|
Get a View that displays the data at the specified position in the data set . In this case if we are at the end of the list and we are still in append mode we ask for a pending view and return it plus kick off the background task to append more data to the wrapped adapter .
| 65
| 59
|
151,028
|
public static String [ ] addStringToArray ( String [ ] array , String str ) { if ( isEmpty ( array ) ) { return new String [ ] { str } ; } String [ ] newArr = new String [ array . length + 1 ] ; System . arraycopy ( array , 0 , newArr , 0 , array . length ) ; newArr [ array . length ] = str ; return newArr ; }
|
Append the given String to the given String array returning a new array consisting of the input array contents plus the given String .
| 92
| 25
|
151,029
|
public static String [ ] sortStringArray ( String [ ] array ) { if ( isEmpty ( array ) ) { return new String [ 0 ] ; } Arrays . sort ( array ) ; return array ; }
|
Turn given source String array into sorted array .
| 44
| 9
|
151,030
|
public static String [ ] removeDuplicateStrings ( String [ ] array ) { if ( isEmpty ( array ) ) { return array ; } Set < String > set = new TreeSet < String > ( ) ; Collections . addAll ( set , array ) ; return toStringArray ( set ) ; }
|
Remove duplicate Strings from the given array . Also sorts the array as it uses a TreeSet .
| 65
| 20
|
151,031
|
public static Set < String > commaDelimitedListToSet ( String str ) { Set < String > set = new TreeSet < String > ( ) ; String [ ] tokens = commaDelimitedListToStringArray ( str ) ; Collections . addAll ( set , tokens ) ; return set ; }
|
Convenience method to convert a CSV string list to a set . Note that this will suppress duplicates .
| 64
| 22
|
151,032
|
public static String toSafeFileName ( String name ) { int size = name . length ( ) ; StringBuilder builder = new StringBuilder ( size * 2 ) ; for ( int i = 0 ; i < size ; i ++ ) { char c = name . charAt ( i ) ; boolean valid = c >= ' ' && c <= ' ' ; valid = valid || ( c >= ' ' && c <= ' ' ) ; valid = valid || ( c >= ' ' && c <= ' ' ) ; valid = valid || ( c == ' ' ) || ( c == ' ' ) || ( c == ' ' ) ; if ( valid ) { builder . append ( c ) ; } else { // Encode the character using hex notation builder . append ( ' ' ) ; builder . append ( Integer . toHexString ( i ) ) ; } } return builder . toString ( ) ; }
|
Converts any string into a string that is safe to use as a file name . The result will only include ascii characters and numbers and the - _ and . characters .
| 187
| 36
|
151,033
|
@ Override @ Deprecated public List < CardWithActions > getBoardMemberActivity ( String boardId , String memberId , String actionFilter , Argument ... args ) { if ( actionFilter == null ) actionFilter = "all" ; Argument [ ] argsAndFilter = Arrays . copyOf ( args , args . length + 1 ) ; argsAndFilter [ args . length ] = new Argument ( "actions" , actionFilter ) ; return asList ( ( ) -> get ( createUrl ( GET_BOARD_MEMBER_CARDS ) . params ( argsAndFilter ) . asString ( ) , CardWithActions [ ] . class , boardId , memberId ) ) ; }
|
FIXME Remove this method
| 146
| 5
|
151,034
|
void sign ( byte [ ] data , int offset , int length , ServerMessageBlock request , ServerMessageBlock response ) { request . signSeq = signSequence ; if ( response != null ) { response . signSeq = signSequence + 1 ; response . verifyFailed = false ; } try { update ( macSigningKey , 0 , macSigningKey . length ) ; int index = offset + ServerMessageBlock . SIGNATURE_OFFSET ; for ( int i = 0 ; i < 8 ; i ++ ) data [ index + i ] = 0 ; ServerMessageBlock . writeInt4 ( signSequence , data , index ) ; update ( data , offset , length ) ; System . arraycopy ( digest ( ) , 0 , data , index , 8 ) ; if ( bypass ) { bypass = false ; System . arraycopy ( "BSRSPYL " . getBytes ( ) , 0 , data , index , 8 ) ; } } catch ( Exception ex ) { if ( log . level > 0 ) ex . printStackTrace ( log ) ; } finally { signSequence += 2 ; } }
|
Performs MAC signing of the SMB . This is done as follows . The signature field of the SMB is overwritted with the sequence number ; The MD5 digest of the MAC signing key + the entire SMB is taken ; The first 8 bytes of this are placed in the signature field .
| 236
| 61
|
151,035
|
public static Object setProperty ( String key , String value ) { return prp . setProperty ( key , value ) ; }
|
Add a property .
| 26
| 4
|
151,036
|
public static NbtAddress [ ] getAllByAddress ( NbtAddress addr ) throws UnknownHostException { try { NbtAddress [ ] addrs = CLIENT . getNodeStatus ( addr ) ; cacheAddressArray ( addrs ) ; return addrs ; } catch ( UnknownHostException uhe ) { throw new UnknownHostException ( "no name with type 0x" + Hexdump . toHexString ( addr . hostName . hexCode , 2 ) + ( ( ( addr . hostName . scope == null ) || ( addr . hostName . scope . length ( ) == 0 ) ) ? " with no scope" : " with scope " + addr . hostName . scope ) + " for host " + addr . getHostAddress ( ) ) ; } }
|
Retrieve all addresses of a host by it s address . NetBIOS hosts can have many names for a given IP address . The name and IP address make the NetBIOS address . This provides a way to retrieve the other names for a host with the same IP address .
| 161
| 56
|
151,037
|
public String getHostName ( ) { if ( addr instanceof NbtAddress ) { return ( ( NbtAddress ) addr ) . getHostName ( ) ; } return ( ( InetAddress ) addr ) . getHostName ( ) ; }
|
Return the hostname of this address such as MYCOMPUTER .
| 52
| 14
|
151,038
|
public String getHostAddress ( ) { if ( addr instanceof NbtAddress ) { return ( ( NbtAddress ) addr ) . getHostAddress ( ) ; } return ( ( InetAddress ) addr ) . getHostAddress ( ) ; }
|
Return the IP address as text such as 192 . 168 . 1 . 15 .
| 52
| 16
|
151,039
|
public String getUncPath ( ) { getUncPath0 ( ) ; if ( share == null ) { return "\\\\" + url . getHost ( ) ; } return "\\\\" + url . getHost ( ) + canon . replace ( ' ' , ' ' ) ; }
|
Retuns the Windows UNC style path with backslashs intead of forward slashes .
| 61
| 19
|
151,040
|
public void createNewFile ( ) throws SmbException { if ( getUncPath0 ( ) . length ( ) == 1 ) { throw new SmbException ( "Invalid operation for workgroups, servers, or shares" ) ; } close ( open0 ( O_RDWR | O_CREAT | O_EXCL , 0 , ATTR_NORMAL , 0 ) , 0L ) ; }
|
Create a new file but fail if it already exists . The check for existance of the file and it s creation are an atomic operation with respect to other filesystem activities .
| 86
| 34
|
151,041
|
private String getProjectName ( ) { String pName = Strings . emptyToNull ( projectName ) ; if ( pName == null ) { pName = Strings . emptyToNull ( junit4 . getProject ( ) . getName ( ) ) ; } if ( pName == null ) { pName = "(unnamed project)" ; } return pName ; }
|
Return the project name or the default project name .
| 80
| 10
|
151,042
|
@ Subscribe @ SuppressForbidden ( "legitimate printStackTrace()." ) public void onSuiteResult ( AggregatedSuiteResultEvent e ) { try { if ( jsonWriter == null ) return ; slaves . put ( e . getSlave ( ) . id , e . getSlave ( ) ) ; e . serialize ( jsonWriter , outputStreams ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; junit4 . log ( "Error serializing to JSON file: " + Throwables . getStackTraceAsString ( ex ) , Project . MSG_WARN ) ; if ( jsonWriter != null ) { try { jsonWriter . close ( ) ; } catch ( Throwable ignored ) { // Ignore. } finally { jsonWriter = null ; } } } }
|
Emit information about a single suite and all of its tests .
| 174
| 13
|
151,043
|
@ Subscribe public void onQuit ( AggregatedQuitEvent e ) { if ( jsonWriter == null ) return ; try { jsonWriter . endArray ( ) ; jsonWriter . name ( "slaves" ) ; jsonWriter . beginObject ( ) ; for ( Map . Entry < Integer , ForkedJvmInfo > entry : slaves . entrySet ( ) ) { jsonWriter . name ( Integer . toString ( entry . getKey ( ) ) ) ; entry . getValue ( ) . serialize ( jsonWriter ) ; } jsonWriter . endObject ( ) ; jsonWriter . endObject ( ) ; jsonWriter . flush ( ) ; if ( ! Strings . isNullOrEmpty ( jsonpMethod ) ) { writer . write ( ");" ) ; } jsonWriter . close ( ) ; jsonWriter = null ; writer = null ; if ( method == OutputMethod . HTML ) { copyScaffolding ( targetFile ) ; } } catch ( IOException x ) { junit4 . log ( x , Project . MSG_ERR ) ; } }
|
All tests completed .
| 225
| 4
|
151,044
|
public void setSeed ( String randomSeed ) { if ( ! Strings . isNullOrEmpty ( getProject ( ) . getUserProperty ( SYSPROP_RANDOM_SEED ( ) ) ) ) { String userProperty = getProject ( ) . getUserProperty ( SYSPROP_RANDOM_SEED ( ) ) ; if ( ! userProperty . equals ( randomSeed ) ) { log ( "Ignoring seed attribute because it is overridden by user properties." , Project . MSG_WARN ) ; } } else if ( ! Strings . isNullOrEmpty ( randomSeed ) ) { this . random = randomSeed ; } }
|
Initial random seed used for shuffling test suites and other sources of pseudo - randomness . If not set any random value is set .
| 145
| 27
|
151,045
|
public void setPrefix ( String prefix ) { if ( ! Strings . isNullOrEmpty ( getProject ( ) . getUserProperty ( SYSPROP_PREFIX ( ) ) ) ) { log ( "Ignoring prefix attribute because it is overridden by user properties." , Project . MSG_WARN ) ; } else { SysGlobals . initializeWith ( prefix ) ; } }
|
Initializes custom prefix for all junit4 properties . This must be consistent across all junit4 invocations if done from the same classpath . Use only when REALLY needed .
| 85
| 36
|
151,046
|
public void addFileSet ( FileSet fs ) { add ( fs ) ; if ( fs . getProject ( ) == null ) { fs . setProject ( getProject ( ) ) ; } }
|
Adds a set of tests based on pattern matching .
| 41
| 10
|
151,047
|
public void addAssertions ( Assertions asserts ) { if ( getCommandline ( ) . getAssertions ( ) != null ) { throw new BuildException ( "Only one assertion declaration is allowed" ) ; } getCommandline ( ) . setAssertions ( asserts ) ; }
|
Add assertions to tests execution .
| 62
| 6
|
151,048
|
private void validateArguments ( ) throws BuildException { Path tempDir = getTempDir ( ) ; if ( tempDir == null ) { throw new BuildException ( "Temporary directory cannot be null." ) ; } if ( Files . exists ( tempDir ) ) { if ( ! Files . isDirectory ( tempDir ) ) { throw new BuildException ( "Temporary directory is not a folder: " + tempDir . toAbsolutePath ( ) ) ; } } else { try { Files . createDirectories ( tempDir ) ; } catch ( IOException e ) { throw new BuildException ( "Failed to create temporary folder: " + tempDir , e ) ; } } }
|
Validate arguments .
| 144
| 4
|
151,049
|
private void validateJUnit4 ( ) throws BuildException { try { Class < ? > clazz = Class . forName ( "org.junit.runner.Description" ) ; if ( ! Serializable . class . isAssignableFrom ( clazz ) ) { throw new BuildException ( "At least JUnit version 4.10 is required on junit4's taskdef classpath." ) ; } } catch ( ClassNotFoundException e ) { throw new BuildException ( "JUnit JAR must be added to junit4 taskdef's classpath." ) ; } }
|
Validate JUnit4 presence in a concrete version .
| 123
| 11
|
151,050
|
private org . apache . tools . ant . types . Path resolveFiles ( org . apache . tools . ant . types . Path path ) { org . apache . tools . ant . types . Path cloned = new org . apache . tools . ant . types . Path ( getProject ( ) ) ; for ( String location : path . list ( ) ) { cloned . createPathElement ( ) . setLocation ( new File ( location ) ) ; } return cloned ; }
|
Resolve all files from a given path and simplify its definition .
| 103
| 13
|
151,051
|
private int determineForkedJvmCount ( TestsCollection testCollection ) { int cores = Runtime . getRuntime ( ) . availableProcessors ( ) ; int jvmCount ; if ( this . parallelism . equals ( PARALLELISM_AUTO ) ) { if ( cores >= 8 ) { // Maximum parallel jvms is 4, conserve some memory and memory bandwidth. jvmCount = 4 ; } else if ( cores >= 4 ) { // Make some space for the aggregator. jvmCount = 3 ; } else if ( cores == 3 ) { // Yes, three-core chips are a thing. jvmCount = 2 ; } else { // even for dual cores it usually makes no sense to fork more than one // JVM. jvmCount = 1 ; } } else if ( this . parallelism . equals ( PARALLELISM_MAX ) ) { jvmCount = Runtime . getRuntime ( ) . availableProcessors ( ) ; } else { try { jvmCount = Math . max ( 1 , Integer . parseInt ( parallelism ) ) ; } catch ( NumberFormatException e ) { throw new BuildException ( "parallelism must be 'auto', 'max' or a valid integer: " + parallelism ) ; } } if ( ! testCollection . hasReplicatedSuites ( ) ) { jvmCount = Math . min ( testCollection . testClasses . size ( ) , jvmCount ) ; } return jvmCount ; }
|
Determine how many forked JVMs to use .
| 313
| 13
|
151,052
|
private String escapeAndJoin ( String [ ] commandline ) { // TODO: we should try to escape special characters here, depending on the OS. StringBuilder b = new StringBuilder ( ) ; Pattern specials = Pattern . compile ( "[\\ ]" ) ; for ( String arg : commandline ) { if ( b . length ( ) > 0 ) { b . append ( " " ) ; } if ( specials . matcher ( arg ) . find ( ) ) { b . append ( ' ' ) . append ( arg ) . append ( ' ' ) ; } else { b . append ( arg ) ; } } return b . toString ( ) ; }
|
Try to provide an escaped ready - to - use shell line to repeat a given command line .
| 138
| 19
|
151,053
|
@ SuppressForbidden ( "legitimate sysstreams." ) private Execute forkProcess ( ForkedJvmInfo slaveInfo , EventBus eventBus , CommandlineJava commandline , TailInputStream eventStream , OutputStream sysout , OutputStream syserr , RandomAccessFile streamsBuffer ) { try { String tempDir = commandline . getSystemProperties ( ) . getVariablesVector ( ) . stream ( ) . filter ( v -> v . getKey ( ) . equals ( "java.io.tmpdir" ) ) . map ( v -> v . getValue ( ) ) . findAny ( ) . orElse ( null ) ; final LocalSlaveStreamHandler streamHandler = new LocalSlaveStreamHandler ( eventBus , testsClassLoader , System . err , eventStream , sysout , syserr , heartbeat , streamsBuffer ) ; // Add certain properties to allow identification of the forked JVM from within // the subprocess. This can be used for policy files etc. final Path cwd = getWorkingDirectory ( slaveInfo , tempDir ) ; Variable v = new Variable ( ) ; v . setKey ( CHILDVM_SYSPROP_CWD ) ; v . setFile ( cwd . toAbsolutePath ( ) . normalize ( ) . toFile ( ) ) ; commandline . addSysproperty ( v ) ; v = new Variable ( ) ; v . setKey ( SYSPROP_TEMPDIR ) ; v . setFile ( getTempDir ( ) . toAbsolutePath ( ) . normalize ( ) . toFile ( ) ) ; commandline . addSysproperty ( v ) ; v = new Variable ( ) ; v . setKey ( SysGlobals . CHILDVM_SYSPROP_JVM_ID ) ; v . setValue ( Integer . toString ( slaveInfo . id ) ) ; commandline . addSysproperty ( v ) ; v = new Variable ( ) ; v . setKey ( SysGlobals . CHILDVM_SYSPROP_JVM_COUNT ) ; v . setValue ( Integer . toString ( slaveInfo . slaves ) ) ; commandline . addSysproperty ( v ) ; // Emit command line before -stdin to avoid confusion. slaveInfo . slaveCommandLine = escapeAndJoin ( commandline . getCommandline ( ) ) ; log ( "Forked child JVM at '" + cwd . toAbsolutePath ( ) . normalize ( ) + "', command (may need escape sequences for your shell):\n" + slaveInfo . slaveCommandLine , Project . MSG_VERBOSE ) ; final Execute execute = new Execute ( ) ; execute . setCommandline ( commandline . getCommandline ( ) ) ; execute . setVMLauncher ( true ) ; execute . setWorkingDirectory ( cwd . toFile ( ) ) ; execute . setStreamHandler ( streamHandler ) ; execute . setNewenvironment ( newEnvironment ) ; if ( env . getVariables ( ) != null ) execute . setEnvironment ( env . getVariables ( ) ) ; log ( "Starting JVM J" + slaveInfo . id , Project . MSG_DEBUG ) ; execute . execute ( ) ; return execute ; } catch ( IOException e ) { throw new BuildException ( "Could not start the child process. Run ant with -verbose to get" + " the execution details." , e ) ; } }
|
Execute a slave process . Pump events to the given event bus .
| 735
| 14
|
151,054
|
private Path getTempDir ( ) { if ( this . tempDir == null ) { if ( this . dir != null ) { this . tempDir = dir ; } else { this . tempDir = getProject ( ) . getBaseDir ( ) . toPath ( ) ; } } return tempDir ; }
|
Resolve temporary folder .
| 65
| 5
|
151,055
|
private org . apache . tools . ant . types . Path addSlaveClasspath ( ) { org . apache . tools . ant . types . Path path = new org . apache . tools . ant . types . Path ( getProject ( ) ) ; String [ ] REQUIRED_SLAVE_CLASSES = { SlaveMain . class . getName ( ) , Strings . class . getName ( ) , MethodGlobFilter . class . getName ( ) , TeeOutputStream . class . getName ( ) } ; for ( String clazz : Arrays . asList ( REQUIRED_SLAVE_CLASSES ) ) { String resource = clazz . replace ( "." , "/" ) + ".class" ; File f = LoaderUtils . getResourceSource ( getClass ( ) . getClassLoader ( ) , resource ) ; if ( f != null ) { path . createPath ( ) . setLocation ( f ) ; } else { throw new BuildException ( "Could not locate classpath for resource: " + resource ) ; } } return path ; }
|
Adds a classpath source which contains the given resource .
| 232
| 11
|
151,056
|
private void validate ( ) { if ( Strings . emptyToNull ( random ) == null ) { random = Strings . emptyToNull ( getProject ( ) . getProperty ( SYSPROP_RANDOM_SEED ( ) ) ) ; } if ( random == null ) { throw new BuildException ( "Required attribute 'seed' must not be empty. Look at <junit4:pickseed>." ) ; } long [ ] seeds = SeedUtils . parseSeedChain ( random ) ; if ( seeds . length < 1 ) { throw new BuildException ( "Random seed is required." ) ; } if ( values . isEmpty ( ) && ! allowUndefined ) { throw new BuildException ( "No values to pick from and allowUndefined=false." ) ; } }
|
Validate arguments and state .
| 169
| 6
|
151,057
|
public void add ( ResourceCollection rc ) { if ( rc instanceof FileSet ) { FileSet fs = ( FileSet ) rc ; fs . setProject ( getProject ( ) ) ; } resources . add ( rc ) ; }
|
Adds a resource collection with execution hints .
| 48
| 8
|
151,058
|
private static void verifyJUnit4Present ( ) { try { Class < ? > clazz = Class . forName ( "org.junit.runner.Description" ) ; if ( ! Serializable . class . isAssignableFrom ( clazz ) ) { JvmExit . halt ( SlaveMain . ERR_OLD_JUNIT ) ; } } catch ( ClassNotFoundException e ) { JvmExit . halt ( SlaveMain . ERR_NO_JUNIT ) ; } }
|
Verify JUnit presence and version .
| 107
| 8
|
151,059
|
public void setShowOutput ( String mode ) { try { this . outputMode = OutputMode . valueOf ( mode . toUpperCase ( Locale . ROOT ) ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( "showOutput accepts any of: " + Arrays . toString ( OutputMode . values ( ) ) + ", value is not valid: " + mode ) ; } }
|
Display mode for output streams .
| 91
| 6
|
151,060
|
private void flushOutput ( ) throws IOException { outStream . flush ( ) ; outWriter . completeLine ( ) ; errStream . flush ( ) ; errWriter . completeLine ( ) ; }
|
Flush output streams .
| 41
| 5
|
151,061
|
private void emitSuiteStart ( Description description , long startTimestamp ) throws IOException { String suiteName = description . getDisplayName ( ) ; if ( useSimpleNames ) { if ( suiteName . lastIndexOf ( ' ' ) >= 0 ) { suiteName = suiteName . substring ( suiteName . lastIndexOf ( ' ' ) + 1 ) ; } } logShort ( shortTimestamp ( startTimestamp ) + "Suite: " + FormattingUtils . padTo ( maxClassNameColumns , suiteName , "[...]" ) ) ; }
|
Suite prologue .
| 121
| 5
|
151,062
|
private void emitSuiteEnd ( AggregatedSuiteResultEvent e , int suitesCompleted ) throws IOException { assert showSuiteSummary ; final StringBuilder b = new StringBuilder ( ) ; final int totalErrors = this . totalErrors . addAndGet ( e . isSuccessful ( ) ? 0 : 1 ) ; b . append ( String . format ( Locale . ROOT , "%sCompleted [%d/%d%s]%s in %.2fs, " , shortTimestamp ( e . getStartTimestamp ( ) + e . getExecutionTime ( ) ) , suitesCompleted , totalSuites , totalErrors == 0 ? "" : " (" + totalErrors + "!)" , e . getSlave ( ) . slaves > 1 ? " on J" + e . getSlave ( ) . id : "" , e . getExecutionTime ( ) / 1000.0d ) ) ; b . append ( e . getTests ( ) . size ( ) ) . append ( Pluralize . pluralize ( e . getTests ( ) . size ( ) , " test" ) ) ; int failures = e . getFailureCount ( ) ; if ( failures > 0 ) { b . append ( ", " ) . append ( failures ) . append ( Pluralize . pluralize ( failures , " failure" ) ) ; } int errors = e . getErrorCount ( ) ; if ( errors > 0 ) { b . append ( ", " ) . append ( errors ) . append ( Pluralize . pluralize ( errors , " error" ) ) ; } int ignored = e . getIgnoredCount ( ) ; if ( ignored > 0 ) { b . append ( ", " ) . append ( ignored ) . append ( " skipped" ) ; } if ( ! e . isSuccessful ( ) ) { b . append ( FAILURE_STRING ) ; } b . append ( "\n" ) ; logShort ( b , false ) ; }
|
Suite end .
| 425
| 4
|
151,063
|
private void emitStatusLine ( AggregatedResultEvent result , TestStatus status , long timeMillis ) throws IOException { final StringBuilder line = new StringBuilder ( ) ; line . append ( shortTimestamp ( result . getStartTimestamp ( ) ) ) ; line . append ( Strings . padEnd ( statusNames . get ( status ) , 8 , ' ' ) ) ; line . append ( formatDurationInSeconds ( timeMillis ) ) ; if ( forkedJvmCount > 1 ) { line . append ( String . format ( Locale . ROOT , jvmIdFormat , result . getSlave ( ) . id ) ) ; } line . append ( " | " ) ; line . append ( formatDescription ( result . getDescription ( ) ) ) ; if ( ! result . isSuccessful ( ) ) { line . append ( FAILURE_MARKER ) ; } line . append ( "\n" ) ; if ( showThrowable ) { // GH-82 (cause for ignored tests). if ( status == TestStatus . IGNORED && result instanceof AggregatedTestResultEvent ) { final StringWriter sw = new StringWriter ( ) ; PrefixedWriter pos = new PrefixedWriter ( indent , sw , DEFAULT_MAX_LINE_WIDTH ) ; pos . write ( "Cause: " ) ; pos . write ( ( ( AggregatedTestResultEvent ) result ) . getCauseForIgnored ( ) ) ; pos . completeLine ( ) ; line . append ( sw . toString ( ) ) ; } final List < FailureMirror > failures = result . getFailures ( ) ; if ( ! failures . isEmpty ( ) ) { final StringWriter sw = new StringWriter ( ) ; PrefixedWriter pos = new PrefixedWriter ( indent , sw , DEFAULT_MAX_LINE_WIDTH ) ; int count = 0 ; for ( FailureMirror fm : failures ) { count ++ ; if ( fm . isAssumptionViolation ( ) ) { pos . write ( String . format ( Locale . ROOT , "Assumption #%d: %s" , count , MoreObjects . firstNonNull ( fm . getMessage ( ) , "(no message)" ) ) ) ; } else { pos . write ( String . format ( Locale . ROOT , "Throwable #%d: %s" , count , showStackTraces ? filterStackTrace ( fm . getTrace ( ) ) : fm . getThrowableString ( ) ) ) ; } } pos . completeLine ( ) ; if ( sw . getBuffer ( ) . length ( ) > 0 ) { line . append ( sw . toString ( ) ) ; } } } logShort ( line ) ; }
|
Emit status line for an aggregated event .
| 588
| 10
|
151,064
|
private void logShort ( CharSequence message , boolean trim ) throws IOException { int length = message . length ( ) ; if ( trim ) { while ( length > 0 && Character . isWhitespace ( message . charAt ( length - 1 ) ) ) { length -- ; } } char [ ] chars = new char [ length + 1 ] ; for ( int i = 0 ; i < length ; i ++ ) { chars [ i ] = message . charAt ( i ) ; } chars [ length ] = ' ' ; output . write ( chars ) ; }
|
Log a message line to the output .
| 119
| 8
|
151,065
|
public int getIgnoredCount ( ) { int count = 0 ; for ( AggregatedTestResultEvent t : getTests ( ) ) { if ( t . getStatus ( ) == TestStatus . IGNORED || t . getStatus ( ) == TestStatus . IGNORED_ASSUMPTION ) { count ++ ; } } return count ; }
|
Return the number of ignored or assumption - ignored tests .
| 74
| 11
|
151,066
|
@ Subscribe public void onQuit ( AggregatedQuitEvent e ) { if ( summaryFile != null ) { try { Persister persister = new Persister ( ) ; persister . write ( new MavenFailsafeSummaryModel ( summaryListener . getResult ( ) ) , summaryFile ) ; } catch ( Exception x ) { junit4 . log ( "Could not serialize summary report." , x , Project . MSG_WARN ) ; } } }
|
Write the summary file if requested .
| 99
| 7
|
151,067
|
@ Subscribe public void onSuiteResult ( AggregatedSuiteResultEvent e ) { // Calculate summaries. summaryListener . suiteSummary ( e ) ; Description suiteDescription = e . getDescription ( ) ; String displayName = suiteDescription . getDisplayName ( ) ; if ( displayName . trim ( ) . isEmpty ( ) ) { junit4 . log ( "Could not emit XML report for suite (null description)." , Project . MSG_WARN ) ; return ; } if ( ! suiteCounts . containsKey ( displayName ) ) { suiteCounts . put ( displayName , 1 ) ; } else { int newCount = suiteCounts . get ( displayName ) + 1 ; suiteCounts . put ( displayName , newCount ) ; if ( ! ignoreDuplicateSuites && newCount == 2 ) { junit4 . log ( "Duplicate suite name used with XML reports: " + displayName + ". This may confuse tools that process XML reports. " + "Set 'ignoreDuplicateSuites' to true to skip this message." , Project . MSG_WARN ) ; } displayName = displayName + "-" + newCount ; } try { File reportFile = new File ( dir , "TEST-" + displayName + ".xml" ) ; RegistryMatcher rm = new RegistryMatcher ( ) ; rm . bind ( String . class , new XmlStringTransformer ( ) ) ; Persister persister = new Persister ( rm ) ; persister . write ( buildModel ( e ) , reportFile ) ; } catch ( Exception x ) { junit4 . log ( "Could not serialize report for suite " + displayName + ": " + x . toString ( ) , x , Project . MSG_WARN ) ; } }
|
Emit information about all of suite s tests .
| 379
| 10
|
151,068
|
private TestSuiteModel buildModel ( AggregatedSuiteResultEvent e ) throws IOException { SimpleDateFormat df = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ss" , Locale . ROOT ) ; TestSuiteModel suite = new TestSuiteModel ( ) ; suite . hostname = "nohost.nodomain" ; suite . name = e . getDescription ( ) . getDisplayName ( ) ; suite . properties = buildModel ( e . getSlave ( ) . getSystemProperties ( ) ) ; suite . time = e . getExecutionTime ( ) / 1000.0 ; suite . timestamp = df . format ( new Date ( e . getStartTimestamp ( ) ) ) ; suite . testcases = buildModel ( e . getTests ( ) ) ; suite . tests = suite . testcases . size ( ) ; if ( mavenExtensions ) { suite . skipped = 0 ; } // Suite-level failures and errors are simulated as test cases. for ( FailureMirror m : e . getFailures ( ) ) { TestCaseModel model = new TestCaseModel ( ) ; model . classname = "junit.framework.TestSuite" ; // empirical ANT output. model . name = applyFilters ( m . getDescription ( ) . getClassName ( ) ) ; model . time = 0 ; if ( m . isAssertionViolation ( ) ) { model . failures . add ( buildModel ( m ) ) ; } else { model . errors . add ( buildModel ( m ) ) ; } suite . testcases . add ( model ) ; } // Calculate test numbers that match limited view (no ignored tests, // faked suite-level errors). for ( TestCaseModel tc : suite . testcases ) { suite . errors += tc . errors . size ( ) ; suite . failures += tc . failures . size ( ) ; if ( mavenExtensions && tc . skipped != null ) { suite . skipped += 1 ; } } StringWriter sysout = new StringWriter ( ) ; StringWriter syserr = new StringWriter ( ) ; if ( outputStreams ) { e . getSlave ( ) . decodeStreams ( e . getEventStream ( ) , sysout , syserr ) ; } suite . sysout = sysout . toString ( ) ; suite . syserr = syserr . toString ( ) ; return suite ; }
|
Build data model for serialization .
| 526
| 7
|
151,069
|
private String applyFilters ( String methodName ) { if ( filters . isEmpty ( ) ) { return methodName ; } Reader in = new StringReader ( methodName ) ; for ( TokenFilter tf : filters ) { in = tf . chain ( in ) ; } try { return CharStreams . toString ( in ) ; } catch ( IOException e ) { junit4 . log ( "Could not apply filters to " + methodName + ": " + Throwables . getStackTraceAsString ( e ) , Project . MSG_WARN ) ; return methodName ; } }
|
Apply filters to a method name .
| 124
| 7
|
151,070
|
void pumpEvents ( InputStream eventStream ) { try { Deserializer deserializer = new Deserializer ( eventStream , refLoader ) ; IEvent event = null ; while ( ( event = deserializer . deserialize ( ) ) != null ) { switch ( event . getType ( ) ) { case APPEND_STDERR : case APPEND_STDOUT : // Ignore these two on activity heartbeats. GH-117 break ; default : lastActivity = System . currentTimeMillis ( ) ; break ; } try { switch ( event . getType ( ) ) { case QUIT : eventBus . post ( event ) ; return ; case IDLE : eventBus . post ( new SlaveIdle ( stdinWriter ) ) ; break ; case BOOTSTRAP : clientCharset = Charset . forName ( ( ( BootstrapEvent ) event ) . getDefaultCharsetName ( ) ) ; stdinWriter = new OutputStreamWriter ( stdin , clientCharset ) ; eventBus . post ( event ) ; break ; case APPEND_STDERR : case APPEND_STDOUT : assert streamsBuffer . getFilePointer ( ) == streamsBuffer . length ( ) ; final long bufferStart = streamsBuffer . getFilePointer ( ) ; IStreamEvent streamEvent = ( IStreamEvent ) event ; streamEvent . copyTo ( streamsBufferWrapper ) ; final long bufferEnd = streamsBuffer . getFilePointer ( ) ; event = new OnDiskStreamEvent ( event . getType ( ) , streamsBuffer , bufferStart , bufferEnd ) ; eventBus . post ( event ) ; break ; default : eventBus . post ( event ) ; } } catch ( Throwable t ) { warnStream . println ( "Event bus dispatch error: " + t . toString ( ) ) ; t . printStackTrace ( warnStream ) ; } } lastActivity = null ; } catch ( Throwable e ) { if ( ! stopping ) { warnStream . println ( "Event stream error: " + e . toString ( ) ) ; e . printStackTrace ( warnStream ) ; } } }
|
Pump events from event stream .
| 451
| 7
|
151,071
|
@ Subscribe public void onSuiteResult ( AggregatedSuiteResultEvent e ) { long millis = e . getExecutionTime ( ) ; String suiteName = e . getDescription ( ) . getDisplayName ( ) ; List < Long > values = hints . get ( suiteName ) ; if ( values == null ) { hints . put ( suiteName , values = new ArrayList <> ( ) ) ; } values . add ( millis ) ; while ( values . size ( ) > historyLength ) values . remove ( 0 ) ; }
|
Remember execution time for all executed suites .
| 116
| 8
|
151,072
|
@ Subscribe public void onEnd ( AggregatedQuitEvent e ) { try { writeHints ( hintsFile , hints ) ; } catch ( IOException exception ) { outer . log ( "Could not write back the hints file." , exception , Project . MSG_ERR ) ; } }
|
Write back to hints file .
| 62
| 6
|
151,073
|
public static Map < String , List < Long > > readHints ( File hints ) throws IOException { Map < String , List < Long > > result = new HashMap <> ( ) ; InputStream is = new FileInputStream ( hints ) ; mergeHints ( is , result ) ; return result ; }
|
Read hints from a file .
| 66
| 6
|
151,074
|
public static void mergeHints ( InputStream is , Map < String , List < Long > > hints ) throws IOException { final BufferedReader reader = new BufferedReader ( new InputStreamReader ( is , Charsets . UTF_8 ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( line . isEmpty ( ) || line . startsWith ( "#" ) ) continue ; final int equals = line . indexOf ( ' ' ) ; if ( equals <= 0 ) { throw new IOException ( "No '=' character on a non-comment line?: " + line ) ; } else { String key = line . substring ( 0 , equals ) ; List < Long > values = hints . get ( key ) ; if ( values == null ) { hints . put ( key , values = new ArrayList <> ( ) ) ; } for ( String v : line . substring ( equals + 1 ) . split ( "[\\,]" ) ) { if ( ! v . isEmpty ( ) ) values . add ( Long . parseLong ( v ) ) ; } } } }
|
Read hints from a file and merge with the given hints map .
| 248
| 13
|
151,075
|
public static void writeHints ( File file , Map < String , List < Long > > hints ) throws IOException { Closer closer = Closer . create ( ) ; try { BufferedWriter w = closer . register ( Files . newWriter ( file , Charsets . UTF_8 ) ) ; if ( ! ( hints instanceof SortedMap ) ) { hints = new TreeMap < String , List < Long > > ( hints ) ; } Joiner joiner = Joiner . on ( ' ' ) ; for ( Map . Entry < String , List < Long > > e : hints . entrySet ( ) ) { w . write ( e . getKey ( ) ) ; w . write ( "=" ) ; joiner . appendTo ( w , e . getValue ( ) ) ; w . write ( "\n" ) ; } } catch ( Throwable t ) { throw closer . rethrow ( t ) ; } finally { closer . close ( ) ; } }
|
Writes back hints file .
| 206
| 6
|
151,076
|
private static String [ ] readArgsFile ( String argsFile ) throws IOException { final ArrayList < String > lines = new ArrayList < String > ( ) ; final BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( argsFile ) , "UTF-8" ) ) ; try { String line ; while ( ( line = reader . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( ! line . isEmpty ( ) && ! line . startsWith ( "#" ) ) { lines . add ( line ) ; } } } finally { reader . close ( ) ; } return lines . toArray ( new String [ lines . size ( ) ] ) ; }
|
Read arguments from a file . Newline delimited UTF - 8 encoded . No fanciness to avoid dependencies .
| 154
| 22
|
151,077
|
@ SuppressForbidden ( "legitimate sysstreams." ) private static void redirectStreams ( final Serializer serializer , final boolean flushFrequently ) { final PrintStream origSysOut = System . out ; final PrintStream origSysErr = System . err ; // Set warnings stream to System.err. warnings = System . err ; AccessController . doPrivileged ( new PrivilegedAction < Void > ( ) { @ SuppressForbidden ( "legitimate PrintStream with default charset." ) @ Override public Void run ( ) { System . setOut ( new PrintStream ( new BufferedOutputStream ( new ChunkedStream ( ) { @ Override public void write ( byte [ ] b , int off , int len ) throws IOException { if ( multiplexStdStreams ) { origSysOut . write ( b , off , len ) ; } serializer . serialize ( new AppendStdOutEvent ( b , off , len ) ) ; if ( flushFrequently ) serializer . flush ( ) ; } } ) ) ) ; System . setErr ( new PrintStream ( new BufferedOutputStream ( new ChunkedStream ( ) { @ Override public void write ( byte [ ] b , int off , int len ) throws IOException { if ( multiplexStdStreams ) { origSysErr . write ( b , off , len ) ; } serializer . serialize ( new AppendStdErrEvent ( b , off , len ) ) ; if ( flushFrequently ) serializer . flush ( ) ; } } ) ) ) ; return null ; } } ) ; }
|
Redirect standard streams so that the output can be passed to listeners .
| 346
| 14
|
151,078
|
@ SuppressForbidden ( "legitimate sysstreams." ) public static void warn ( String message , Throwable t ) { PrintStream w = ( warnings == null ? System . err : warnings ) ; try { w . print ( "WARN: " ) ; w . print ( message ) ; if ( t != null ) { w . print ( " -> " ) ; try { t . printStackTrace ( w ) ; } catch ( OutOfMemoryError e ) { // Ignore, OOM. w . print ( t . getClass ( ) . getName ( ) ) ; w . print ( ": " ) ; w . print ( t . getMessage ( ) ) ; w . println ( " (stack unavailable; OOM)" ) ; } } else { w . println ( ) ; } w . flush ( ) ; } catch ( OutOfMemoryError t2 ) { w . println ( "ERROR: Couldn't even serialize a warning (out of memory)." ) ; } catch ( Throwable t2 ) { // Can't do anything, really. Probably an OOM? w . println ( "ERROR: Couldn't even serialize a warning." ) ; } }
|
Warning emitter . Uses whatever alternative non - event communication channel is .
| 250
| 14
|
151,079
|
private ArrayList < RunListener > instantiateRunListeners ( ) throws Exception { ArrayList < RunListener > instances = new ArrayList <> ( ) ; if ( runListeners != null ) { for ( String className : Arrays . asList ( runListeners . split ( "," ) ) ) { instances . add ( ( RunListener ) this . instantiate ( className ) . newInstance ( ) ) ; } } return instances ; }
|
Generates JUnit 4 RunListener instances for any user defined RunListeners
| 95
| 15
|
151,080
|
@ Override public List < Assignment > assign ( Collection < String > suiteNames , int slaves , long seed ) { // Read hints first. final Map < String , List < Long > > hints = ExecutionTimesReport . mergeHints ( resources , suiteNames ) ; // Preprocess and sort costs. Take the median for each suite's measurements as the // weight to avoid extreme measurements from screwing up the average. final List < SuiteHint > costs = new ArrayList <> ( ) ; for ( String suiteName : suiteNames ) { final List < Long > suiteHint = hints . get ( suiteName ) ; if ( suiteHint != null ) { // Take the median for each suite's measurements as the weight // to avoid extreme measurements from screwing up the average. Collections . sort ( suiteHint ) ; final Long median = suiteHint . get ( suiteHint . size ( ) / 2 ) ; costs . add ( new SuiteHint ( suiteName , median ) ) ; } } Collections . sort ( costs , SuiteHint . DESCENDING_BY_WEIGHT ) ; // Apply the assignment heuristic. final PriorityQueue < SlaveLoad > pq = new PriorityQueue < SlaveLoad > ( slaves , SlaveLoad . ASCENDING_BY_ESTIMATED_FINISH ) ; for ( int i = 0 ; i < slaves ; i ++ ) { pq . add ( new SlaveLoad ( i ) ) ; } final List < Assignment > assignments = new ArrayList <> ( ) ; for ( SuiteHint hint : costs ) { SlaveLoad slave = pq . remove ( ) ; slave . estimatedFinish += hint . cost ; pq . add ( slave ) ; owner . log ( "Expected execution time for " + hint . suiteName + ": " + Duration . toHumanDuration ( hint . cost ) , Project . MSG_DEBUG ) ; assignments . add ( new Assignment ( hint . suiteName , slave . id , ( int ) hint . cost ) ) ; } // Dump estimated execution times. TreeMap < Integer , SlaveLoad > ordered = new TreeMap < Integer , SlaveLoad > ( ) ; while ( ! pq . isEmpty ( ) ) { SlaveLoad slave = pq . remove ( ) ; ordered . put ( slave . id , slave ) ; } for ( Integer id : ordered . keySet ( ) ) { final SlaveLoad slave = ordered . get ( id ) ; owner . log ( String . format ( Locale . ROOT , "Expected execution time on JVM J%d: %8.2fs" , slave . id , slave . estimatedFinish / 1000.0f ) , verbose ? Project . MSG_INFO : Project . MSG_DEBUG ) ; } return assignments ; }
|
Assign based on execution time history . The algorithm is a greedy heuristic assigning the longest remaining test to the slave with the shortest - completion time so far . This is not optimal but fast and provides a decent average assignment .
| 580
| 45
|
151,081
|
static < K , V > PageMetadata < K , V > mergeTokenAndQueryParameters ( String paginationToken , final ViewQueryParameters < K , V > initialParameters ) { // Decode the base64 token into JSON String json = new String ( Base64 . decodeBase64 ( paginationToken ) , Charset . forName ( "UTF-8" ) ) ; // Get a suitable Gson, we need any adapter registered for the K key type Gson paginationTokenGson = getGsonWithKeyAdapter ( initialParameters ) ; // Deserialize the pagination token JSON, using the appropriate K, V types PaginationToken token = paginationTokenGson . fromJson ( json , PaginationToken . class ) ; // Create new query parameters using the initial ViewQueryParameters as a starting point. ViewQueryParameters < K , V > tokenPageParameters = initialParameters . copy ( ) ; // Merge the values from the token into the new query parameters tokenPageParameters . descending = token . descending ; tokenPageParameters . endkey = token . endkey ; tokenPageParameters . endkey_docid = token . endkey_docid ; tokenPageParameters . inclusive_end = token . inclusive_end ; tokenPageParameters . startkey = token . startkey ; tokenPageParameters . startkey_docid = token . startkey_docid ; return new PageMetadata < K , V > ( token . direction , token . pageNumber , tokenPageParameters ) ; }
|
Generate a PageMetadata object for the page represented by the specified pagination token .
| 314
| 18
|
151,082
|
static String tokenize ( PageMetadata < ? , ? > pageMetadata ) { try { Gson g = getGsonWithKeyAdapter ( pageMetadata . pageRequestParameters ) ; return new String ( Base64 . encodeBase64URLSafe ( g . toJson ( new PaginationToken ( pageMetadata ) ) . getBytes ( "UTF-8" ) ) , Charset . forName ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { //all JVMs should support UTF-8 throw new RuntimeException ( e ) ; } }
|
Generate an opaque pagination token from the supplied PageMetadata .
| 128
| 14
|
151,083
|
public FindByIndexOptions useIndex ( String designDocument , String indexName ) { assertNotNull ( designDocument , "designDocument" ) ; assertNotNull ( indexName , "indexName" ) ; JsonArray index = new JsonArray ( ) ; index . add ( new JsonPrimitive ( designDocument ) ) ; index . add ( new JsonPrimitive ( indexName ) ) ; this . useIndex = index ; return this ; }
|
Specify a specific index to run the query against
| 96
| 10
|
151,084
|
@ Override public String getPartialFilterSelector ( ) { return ( def . selector != null ) ? def . selector . toString ( ) : null ; }
|
Get the JSON string representation of the selector configured for this index .
| 35
| 13
|
151,085
|
public com . cloudant . client . api . model . ReplicationResult trigger ( ) { ReplicationResult couchDbReplicationResult = replication . trigger ( ) ; com . cloudant . client . api . model . ReplicationResult replicationResult = new com . cloudant . client . api . model . ReplicationResult ( couchDbReplicationResult ) ; return replicationResult ; }
|
Triggers a replication request blocks while the replication is in progress .
| 79
| 14
|
151,086
|
public Replication queryParams ( Map < String , Object > queryParams ) { this . replication = replication . queryParams ( queryParams ) ; return this ; }
|
Specify additional query parameters to be passed to the filter function .
| 37
| 13
|
151,087
|
public Replication targetOauth ( String consumerSecret , String consumerKey , String tokenSecret , String token ) { this . replication = replication . targetOauth ( consumerSecret , consumerKey , tokenSecret , token ) ; return this ; }
|
Set OAuth 1 authentication credentials for the replication target
| 49
| 10
|
151,088
|
public List < Task > getActiveTasks ( ) { InputStream response = null ; URI uri = new URIBase ( getBaseUri ( ) ) . path ( "_active_tasks" ) . build ( ) ; try { response = couchDbClient . get ( uri ) ; return getResponseList ( response , couchDbClient . getGson ( ) , DeserializationTypes . TASKS ) ; } finally { close ( response ) ; } }
|
Get the list of active tasks from the server .
| 99
| 10
|
151,089
|
public Membership getMembership ( ) { URI uri = new URIBase ( getBaseUri ( ) ) . path ( "_membership" ) . build ( ) ; Membership membership = couchDbClient . get ( uri , Membership . class ) ; return membership ; }
|
Get the list of all nodes and the list of active nodes in the cluster .
| 57
| 16
|
151,090
|
public ChangesResult getChanges ( ) { final URI uri = this . databaseHelper . changesUri ( "feed" , "normal" ) ; return client . get ( uri , ChangesResult . class ) ; }
|
Requests Change notifications of feed type normal .
| 46
| 9
|
151,091
|
public Changes parameter ( String name , String value ) { this . databaseHelper . query ( name , value ) ; return this ; }
|
Add a custom query parameter to the _changes request . Useful for specifying extra parameters to a filter function for example .
| 27
| 23
|
151,092
|
private boolean readNextRow ( ) { while ( ! stop ) { String row = getLineWrapped ( ) ; // end of stream - null indicates end of stream before we see last_seq which shouldn't // be possible but we should handle it if ( row == null || row . startsWith ( "{\"last_seq\":" ) ) { terminate ( ) ; return false ; } else if ( row . isEmpty ( ) ) { // heartbeat continue ; } setNextRow ( gson . fromJson ( row , ChangesResult . Row . class ) ) ; return true ; } // we were stopped, end of changes feed terminate ( ) ; return false ; }
|
Reads and sets the next feed in the stream .
| 139
| 11
|
151,093
|
public List < Shard > getShards ( ) { InputStream response = null ; try { response = client . couchDbClient . get ( new DatabaseURIHelper ( db . getDBUri ( ) ) . path ( "_shards" ) . build ( ) ) ; return getResponseList ( response , client . getGson ( ) , DeserializationTypes . SHARDS ) ; } finally { close ( response ) ; } }
|
Get info about the shards in the database .
| 91
| 9
|
151,094
|
public Shard getShard ( String docId ) { assertNotEmpty ( docId , "docId" ) ; return client . couchDbClient . get ( new DatabaseURIHelper ( db . getDBUri ( ) ) . path ( "_shards" ) . path ( docId ) . build ( ) , Shard . class ) ; }
|
Get info about the shard a document belongs to .
| 72
| 11
|
151,095
|
@ Deprecated public < T > List < T > findByIndex ( String selectorJson , Class < T > classOfT ) { return findByIndex ( selectorJson , classOfT , new FindByIndexOptions ( ) ) ; }
|
Find documents using an index
| 52
| 5
|
151,096
|
public < T > QueryResult < T > query ( String partitionKey , String query , final Class < T > classOfT ) { URI uri = new DatabaseURIHelper ( db . getDBUri ( ) ) . partition ( partitionKey ) . path ( "_find" ) . build ( ) ; return this . query ( uri , query , classOfT ) ; }
|
Execute a partitioned query using an index and a query selector .
| 80
| 14
|
151,097
|
public Indexes listIndexes ( ) { URI uri = new DatabaseURIHelper ( db . getDBUri ( ) ) . path ( "_index" ) . build ( ) ; return client . couchDbClient . get ( uri , Indexes . class ) ; }
|
List the indexes in the database . The returned object allows for listing indexes by type .
| 58
| 17
|
151,098
|
public void deleteIndex ( String indexName , String designDocId , String type ) { assertNotEmpty ( indexName , "indexName" ) ; assertNotEmpty ( designDocId , "designDocId" ) ; assertNotNull ( type , "type" ) ; if ( ! designDocId . startsWith ( "_design" ) ) { designDocId = "_design/" + designDocId ; } URI uri = new DatabaseURIHelper ( db . getDBUri ( ) ) . path ( "_index" ) . path ( designDocId ) . path ( type ) . path ( indexName ) . build ( ) ; InputStream response = null ; try { HttpConnection connection = Http . DELETE ( uri ) ; response = client . couchDbClient . executeToInputStream ( connection ) ; getResponse ( response , Response . class , client . getGson ( ) ) ; } finally { close ( response ) ; } }
|
Delete an index with the specified name and type in the given design document .
| 202
| 15
|
151,099
|
public < T > T find ( Class < T > classType , String id ) { return db . find ( classType , id ) ; }
|
Retrieve the document with the specified ID from the database and deserialize to an instance of the POJO of type T .
| 30
| 26
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.