idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
31,400
public EntryStream < K , V > peekValues ( Consumer < ? super V > valueAction ) { return peek ( e -> valueAction . accept ( e . getValue ( ) ) ) ; }
Returns a stream consisting of the entries of this stream additionally performing the provided action on each entry value as entries are consumed from the resulting stream .
31,401
public EntryStream < K , V > peekKeyValue ( BiConsumer < ? super K , ? super V > action ) { return peek ( toConsumer ( action ) ) ; }
Returns a stream consisting of the entries of this stream additionally performing the provided action on each entry key - value pair as entries are consumed from the resulting stream .
31,402
public EntryStream < K , V > collapseKeys ( BinaryOperator < V > merger ) { BinaryOperator < Entry < K , V > > entryMerger = ( e1 , e2 ) -> new SimpleImmutableEntry < > ( e1 . getKey ( ) , merger . apply ( e1 . getValue ( ) , e2 . getValue ( ) ) ) ; return new EntryStream < > ( new CollapseSpliterator < > ( equalKeys ( ) , Function . identity ( ) , entryMerger , entryMerger , spliterator ( ) ) , context ) ; }
Merge series of adjacent stream entries with equal keys combining the corresponding values using the provided function .
31,403
protected int loadLibraryFrom ( String soName , int loadFlags , File libDir , StrictMode . ThreadPolicy threadPolicy ) throws IOException { File soFile = new File ( libDir , soName ) ; if ( ! soFile . exists ( ) ) { Log . d ( SoLoader . TAG , soName + " not found on " + libDir . getCanonicalPath ( ) ) ; return LOAD_RESULT_NOT_FOUND ; } else { Log . d ( SoLoader . TAG , soName + " found on " + libDir . getCanonicalPath ( ) ) ; } if ( ( loadFlags & LOAD_FLAG_ALLOW_IMPLICIT_PROVISION ) != 0 && ( flags & ON_LD_LIBRARY_PATH ) != 0 ) { Log . d ( SoLoader . TAG , soName + " loaded implicitly" ) ; return LOAD_RESULT_IMPLICITLY_PROVIDED ; } if ( ( flags & RESOLVE_DEPENDENCIES ) != 0 ) { loadDependencies ( soFile , loadFlags , threadPolicy ) ; } else { Log . d ( SoLoader . TAG , "Not resolving dependencies for " + soName ) ; } try { SoLoader . sSoFileLoader . load ( soFile . getAbsolutePath ( ) , loadFlags ) ; } catch ( UnsatisfiedLinkError e ) { if ( e . getMessage ( ) . contains ( "bad ELF magic" ) ) { Log . d ( SoLoader . TAG , "Corrupted lib file detected" ) ; return LOAD_RESULT_CORRUPTED_LIB_FILE ; } else { throw e ; } } return LOAD_RESULT_LOADED ; }
Abstracted this logic in another method so subclasses can take advantage of it .
31,404
public boolean checkAndMaybeUpdate ( ) throws IOException { try { File nativeLibDir = soSource . soDirectory ; Context updatedContext = applicationContext . createPackageContext ( applicationContext . getPackageName ( ) , 0 ) ; File updatedNativeLibDir = new File ( updatedContext . getApplicationInfo ( ) . nativeLibraryDir ) ; if ( ! nativeLibDir . equals ( updatedNativeLibDir ) ) { Log . d ( SoLoader . TAG , "Native library directory updated from " + nativeLibDir + " to " + updatedNativeLibDir ) ; flags |= DirectorySoSource . RESOLVE_DEPENDENCIES ; soSource = new DirectorySoSource ( updatedNativeLibDir , flags ) ; soSource . prepare ( flags ) ; applicationContext = updatedContext ; return true ; } return false ; } catch ( PackageManager . NameNotFoundException e ) { throw new RuntimeException ( e ) ; } }
check to make sure there haven t been any changes to the nativeLibraryDir since the last check if there have been changes update the context and soSource
31,405
public static String getLibraryPath ( String libName ) throws IOException { sSoSourcesLock . readLock ( ) . lock ( ) ; String libPath = null ; try { if ( sSoSources != null ) { for ( int i = 0 ; libPath == null && i < sSoSources . length ; ++ i ) { SoSource currentSource = sSoSources [ i ] ; libPath = currentSource . getLibraryPath ( libName ) ; } } } finally { sSoSourcesLock . readLock ( ) . unlock ( ) ; } return libPath ; }
Gets the full path of a library .
31,406
public static boolean loadLibrary ( String shortName , int loadFlags ) throws UnsatisfiedLinkError { sSoSourcesLock . readLock ( ) . lock ( ) ; try { if ( sSoSources == null ) { if ( "http://www.android.com/" . equals ( System . getProperty ( "java.vendor.url" ) ) ) { assertInitialized ( ) ; } else { synchronized ( SoLoader . class ) { boolean needsLoad = ! sLoadedLibraries . contains ( shortName ) ; if ( needsLoad ) { if ( sSystemLoadLibraryWrapper != null ) { sSystemLoadLibraryWrapper . loadLibrary ( shortName ) ; } else { System . loadLibrary ( shortName ) ; } } return needsLoad ; } } } } finally { sSoSourcesLock . readLock ( ) . unlock ( ) ; } String mergedLibName = MergedSoMapping . mapLibName ( shortName ) ; String soName = mergedLibName != null ? mergedLibName : shortName ; return loadLibraryBySoName ( System . mapLibraryName ( soName ) , shortName , mergedLibName , loadFlags | SoSource . LOAD_FLAG_ALLOW_SOURCE_CHANGE , null ) ; }
Load a shared library initializing any JNI binding it contains .
31,407
public static File unpackLibraryAndDependencies ( String shortName ) throws UnsatisfiedLinkError { assertInitialized ( ) ; try { return unpackLibraryBySoName ( System . mapLibraryName ( shortName ) ) ; } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } }
Unpack library and its dependencies returning the location of the unpacked library file . All non - system dependencies of the given library will either be on LD_LIBRARY_PATH or will be in the same directory as the returned File .
31,408
public static void prependSoSource ( SoSource extraSoSource ) throws IOException { sSoSourcesLock . writeLock ( ) . lock ( ) ; try { Log . d ( TAG , "Prepending to SO sources: " + extraSoSource ) ; assertInitialized ( ) ; extraSoSource . prepare ( makePrepareFlags ( ) ) ; SoSource [ ] newSoSources = new SoSource [ sSoSources . length + 1 ] ; newSoSources [ 0 ] = extraSoSource ; System . arraycopy ( sSoSources , 0 , newSoSources , 1 , sSoSources . length ) ; sSoSources = newSoSources ; sSoSourcesVersion ++ ; Log . d ( TAG , "Prepended to SO sources: " + extraSoSource ) ; } finally { sSoSourcesLock . writeLock ( ) . unlock ( ) ; } }
Add a new source of native libraries . SoLoader consults the new source before any currently - installed source .
31,409
public static String makeLdLibraryPath ( ) { sSoSourcesLock . readLock ( ) . lock ( ) ; try { assertInitialized ( ) ; Log . d ( TAG , "makeLdLibraryPath" ) ; ArrayList < String > pathElements = new ArrayList < > ( ) ; SoSource [ ] soSources = sSoSources ; for ( int i = 0 ; i < soSources . length ; ++ i ) { soSources [ i ] . addToLdLibraryPath ( pathElements ) ; } String joinedPaths = TextUtils . join ( ":" , pathElements ) ; Log . d ( TAG , "makeLdLibraryPath final path: " + joinedPaths ) ; return joinedPaths ; } finally { sSoSourcesLock . readLock ( ) . unlock ( ) ; } }
Retrieve an LD_LIBRARY_PATH value suitable for using the native linker to resolve our shared libraries .
31,410
public static boolean areSoSourcesAbisSupported ( ) { sSoSourcesLock . readLock ( ) . lock ( ) ; try { if ( sSoSources == null ) { return false ; } String supportedAbis [ ] = SysUtil . getSupportedAbis ( ) ; for ( int i = 0 ; i < sSoSources . length ; ++ i ) { String [ ] soSourceAbis = sSoSources [ i ] . getSoSourceAbis ( ) ; for ( int j = 0 ; j < soSourceAbis . length ; ++ j ) { boolean soSourceSupported = false ; for ( int k = 0 ; k < supportedAbis . length && ! soSourceSupported ; ++ k ) { soSourceSupported = soSourceAbis [ j ] . equals ( supportedAbis [ k ] ) ; } if ( ! soSourceSupported ) { Log . e ( TAG , "abi not supported: " + soSourceAbis [ j ] ) ; return false ; } } } return true ; } finally { sSoSourcesLock . readLock ( ) . unlock ( ) ; } }
This function ensure that every SoSources Abi is supported for at least one abi in SysUtil . getSupportedAbis
31,411
public boolean loadLibraries ( ) { synchronized ( mLock ) { if ( mLoadLibraries == false ) { return mLibrariesLoaded ; } try { if ( mLibraryNames != null ) { for ( String name : mLibraryNames ) { SoLoader . loadLibrary ( name ) ; } } initialNativeCheck ( ) ; mLibrariesLoaded = true ; mLibraryNames = null ; } catch ( UnsatisfiedLinkError error ) { Log . e ( TAG , "Failed to load native lib (initial check): " , error ) ; mLinkError = error ; mLibrariesLoaded = false ; } catch ( Throwable other ) { Log . e ( TAG , "Failed to load native lib (other error): " , other ) ; mLinkError = new UnsatisfiedLinkError ( "Failed loading libraries" ) ; mLinkError . initCause ( other ) ; mLibrariesLoaded = false ; } mLoadLibraries = false ; return mLibrariesLoaded ; } }
safe loading of native libs
31,412
public static int findAbiScore ( String [ ] supportedAbis , String abi ) { for ( int i = 0 ; i < supportedAbis . length ; ++ i ) { if ( supportedAbis [ i ] != null && abi . equals ( supportedAbis [ i ] ) ) { return i ; } } return - 1 ; }
Determine how preferred a given ABI is on this system .
31,413
public static String [ ] getSupportedAbis ( ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . LOLLIPOP ) { return new String [ ] { Build . CPU_ABI , Build . CPU_ABI2 } ; } else { return LollipopSysdeps . getSupportedAbis ( ) ; } }
Return an list of ABIs we supported on this device ordered according to preference . Use a separate inner class to isolate the version - dependent call where it won t cause the whole class to fail preverification .
31,414
public static void fallocateIfSupported ( FileDescriptor fd , long length ) throws IOException { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { LollipopSysdeps . fallocateIfSupported ( fd , length ) ; } }
Pre - allocate disk space for a file if we can do that on this version of the OS .
31,415
public static void dumbDeleteRecursive ( File file ) throws IOException { if ( file . isDirectory ( ) ) { File [ ] fileList = file . listFiles ( ) ; if ( fileList == null ) { return ; } for ( File entry : fileList ) { dumbDeleteRecursive ( entry ) ; } } if ( ! file . delete ( ) && file . exists ( ) ) { throw new IOException ( "could not delete: " + file ) ; } }
Delete a directory and its contents .
31,416
static void mkdirOrThrow ( File dir ) throws IOException { if ( ! dir . mkdirs ( ) && ! dir . isDirectory ( ) ) { throw new IOException ( "cannot mkdir: " + dir ) ; } }
Like File . mkdirs but throws on error . Succeeds even if File . mkdirs fails but dir still names a directory .
31,417
static int copyBytes ( RandomAccessFile os , InputStream is , int byteLimit , byte [ ] buffer ) throws IOException { int bytesCopied = 0 ; int nrRead ; while ( bytesCopied < byteLimit && ( nrRead = is . read ( buffer , 0 , Math . min ( buffer . length , byteLimit - bytesCopied ) ) ) != - 1 ) { os . write ( buffer , 0 , nrRead ) ; bytesCopied += nrRead ; } return bytesCopied ; }
Copy up to byteLimit bytes from the input stream to the output stream .
31,418
private void deleteUnmentionedFiles ( Dso [ ] dsos ) throws IOException { String [ ] existingFiles = soDirectory . list ( ) ; if ( existingFiles == null ) { throw new IOException ( "unable to list directory " + soDirectory ) ; } for ( int i = 0 ; i < existingFiles . length ; ++ i ) { String fileName = existingFiles [ i ] ; if ( fileName . equals ( STATE_FILE_NAME ) || fileName . equals ( LOCK_FILE_NAME ) || fileName . equals ( DEPS_FILE_NAME ) || fileName . equals ( MANIFEST_FILE_NAME ) ) { continue ; } boolean found = false ; for ( int j = 0 ; ! found && j < dsos . length ; ++ j ) { if ( dsos [ j ] . name . equals ( fileName ) ) { found = true ; } } if ( ! found ) { File fileNameToDelete = new File ( soDirectory , fileName ) ; Log . v ( TAG , "deleting unaccounted-for file " + fileNameToDelete ) ; SysUtil . dumbDeleteRecursive ( fileNameToDelete ) ; } } }
Delete files not mentioned in the given DSO list .
31,419
protected void prepare ( int flags ) throws IOException { SysUtil . mkdirOrThrow ( soDirectory ) ; File lockFileName = new File ( soDirectory , LOCK_FILE_NAME ) ; FileLocker lock = FileLocker . lock ( lockFileName ) ; try { Log . v ( TAG , "locked dso store " + soDirectory ) ; if ( refreshLocked ( lock , flags , getDepsBlock ( ) ) ) { lock = null ; } else { Log . i ( TAG , "dso store is up-to-date: " + soDirectory ) ; } } finally { if ( lock != null ) { Log . v ( TAG , "releasing dso store lock for " + soDirectory ) ; lock . close ( ) ; } else { Log . v ( TAG , "not releasing dso store lock for " + soDirectory + " (syncer thread started)" ) ; } } }
Verify or refresh the state of the shared library store .
31,420
protected synchronized void prepare ( String soName ) throws IOException { Object lock = getLibraryLock ( soName ) ; synchronized ( lock ) { mCorruptedLib = soName ; prepare ( SoSource . PREPARE_FLAG_FORCE_REFRESH ) ; } }
Prepare this SoSource extracting a corrupted library .
31,421
static < K , V > void onSend ( ProducerRecord < K , V > record , Span span ) { setCommonTags ( span ) ; Tags . MESSAGE_BUS_DESTINATION . set ( span , record . topic ( ) ) ; if ( record . partition ( ) != null ) { span . setTag ( "partition" , record . partition ( ) ) ; } }
Called before record is sent by producer
31,422
static < K , V > void onResponse ( ConsumerRecord < K , V > record , Span span ) { setCommonTags ( span ) ; span . setTag ( "partition" , record . partition ( ) ) ; span . setTag ( "topic" , record . topic ( ) ) ; span . setTag ( "offset" , record . offset ( ) ) ; }
Called when record is received in consumer
31,423
static SpanContext extract ( Headers headers , Tracer tracer ) { return tracer . extract ( Format . Builtin . TEXT_MAP , new HeadersMapExtractAdapter ( headers , false ) ) ; }
Extract Span Context from record headers
31,424
public static SpanContext extractSpanContext ( Headers headers , Tracer tracer ) { return tracer . extract ( Format . Builtin . TEXT_MAP , new HeadersMapExtractAdapter ( headers , true ) ) ; }
Extract Span Context from Consumer record headers
31,425
static void inject ( SpanContext spanContext , Headers headers , Tracer tracer ) { tracer . inject ( spanContext , Format . Builtin . TEXT_MAP , new HeadersMapInjectAdapter ( headers , false ) ) ; }
Inject Span Context to record headers
31,426
static void injectSecond ( SpanContext spanContext , Headers headers , Tracer tracer ) { tracer . inject ( spanContext , Format . Builtin . TEXT_MAP , new HeadersMapInjectAdapter ( headers , true ) ) ; }
Inject second Span Context to record headers
31,427
public Rule BlockQuote ( ) { StringBuilderVar inner = new StringBuilderVar ( ) ; StringBuilderVar optional = new StringBuilderVar ( ) ; return NodeSequence ( OneOrMore ( CrossedOut ( Sequence ( '>' , Optional ( ' ' ) ) , inner ) , Line ( inner ) , ZeroOrMore ( TestNot ( '>' ) , TestNot ( BlankLine ( ) ) , Line ( inner ) ) , Optional ( Sequence ( OneOrMore ( BlankLine ( ) ) , optional . append ( match ( ) ) , Test ( '>' ) ) , inner . append ( optional . getString ( ) ) && optional . clearContents ( ) ) ) , inner . append ( "\n\n" ) , push ( new BlockQuoteNode ( withIndicesShifted ( parseInternal ( inner ) , ( Integer ) peek ( ) ) . getChildren ( ) ) ) ) ; }
otherwise don t include the blank lines they are not part of the block quote
31,428
protected boolean mayEnterEmphOrStrong ( String chars ) { if ( ! isLegalEmphOrStrongStartPos ( ) ) { return false ; } Object parent = peek ( 2 ) ; boolean isStrong = ( chars . length ( ) == 2 ) ; if ( StrongEmphSuperNode . class . equals ( parent . getClass ( ) ) ) { if ( ( ( StrongEmphSuperNode ) parent ) . isStrong ( ) == isStrong ) return false ; } return true ; }
This method checks if the parser can enter an emph or strong sequence Emph only allows Strong as direct child Strong only allows Emph as direct child .
31,429
protected boolean isLegalEmphOrStrongClosePos ( ) { Object lastItem = peek ( ) ; if ( StrongEmphSuperNode . class . equals ( lastItem . getClass ( ) ) ) { List < Node > children = ( ( StrongEmphSuperNode ) lastItem ) . getChildren ( ) ; if ( children . size ( ) < 1 ) return true ; lastItem = children . get ( children . size ( ) - 1 ) ; Class < ? > lastClass = lastItem . getClass ( ) ; if ( TextNode . class . equals ( lastClass ) ) return ! ( ( TextNode ) lastItem ) . getText ( ) . endsWith ( " " ) ; if ( SimpleNode . class . equals ( lastClass ) ) return ! ( ( SimpleNode ) lastItem ) . getType ( ) . equals ( SimpleNode . Type . Linebreak ) ; } return true ; }
This method checks if the last parsed character or sequence is a valid prefix for a closing char for an emph or strong sequence .
31,430
public Rule ImageAlt ( ) { return Sequence ( '[' , checkForParsingTimeout ( ) , push ( new SuperNode ( ) ) , ZeroOrMore ( TestNot ( ']' ) , NonAutoLinkInline ( ) , addAsChild ( ) ) , ']' ) ; }
can t treat labels the same as the image alt since the image alt should be able to empty .
31,431
public Rule TableCell ( ) { return Sequence ( NodeSequence ( push ( new TableCellNode ( ) ) , TestNot ( Sp ( ) , Optional ( ':' ) , Sp ( ) , OneOrMore ( '-' ) , Sp ( ) , Optional ( ':' ) , Sp ( ) , FirstOf ( '|' , Newline ( ) ) ) , Optional ( Sp ( ) , TestNot ( '|' ) , NotNewline ( ) ) , OneOrMore ( TestNot ( '|' ) , TestNot ( Sp ( ) , Newline ( ) ) , Inline ( ) , addAsChild ( ) , Optional ( Sp ( ) , Test ( '|' ) , Test ( Newline ( ) ) ) ) ) , ZeroOrMore ( '|' ) , ( ( TableCellNode ) peek ( ) ) . setColSpan ( Math . max ( 1 , matchLength ( ) ) ) ) ; }
that the TableCell will include only the text of the cell .
31,432
public RootNode parseInternal ( StringBuilderVar block ) { char [ ] chars = block . getChars ( ) ; int [ ] ixMap = new int [ chars . length + 1 ] ; StringBuilder clean = new StringBuilder ( ) ; for ( int i = 0 ; i < chars . length ; i ++ ) { char c = chars [ i ] ; if ( c != CROSSED_OUT ) { ixMap [ clean . length ( ) ] = i ; clean . append ( c ) ; } } ixMap [ clean . length ( ) ] = chars . length ; char [ ] cleaned = new char [ clean . length ( ) ] ; clean . getChars ( 0 , cleaned . length , cleaned , 0 ) ; RootNode rootNode = parseInternal ( cleaned ) ; fixIndices ( rootNode , ixMap ) ; return rootNode ; }
called for inner parses for list items and blockquotes
31,433
public char [ ] prepareSource ( char [ ] source ) { char [ ] src = new char [ source . length + 2 ] ; System . arraycopy ( source , 0 , src , 0 , source . length ) ; src [ source . length ] = '\n' ; src [ source . length + 1 ] = '\n' ; return src ; }
Adds two trailing newlines .
31,434
public static Builder builder ( PegDownPlugins like ) { return builder ( ) . withInlinePluginRules ( like . getInlinePluginRules ( ) ) . withBlockPluginRules ( like . getBlockPluginRules ( ) ) . withHtmlSerializer ( like . serializerPlugins . toArray ( new ToHtmlSerializerPlugin [ 0 ] ) ) ; }
Create a builder that is a copy of the existing plugins
31,435
public File getDestinationDir ( ) { File out = destinationDir ; if ( out == null ) out = new File ( getProject ( ) . getBuildDir ( ) , "jarjar" ) ; return out ; }
Returns the directory where the archive is generated into .
31,436
public String getDestinationName ( ) { String out = destinationName ; if ( out == null ) out = getName ( ) + ".jar" ; return out ; }
Returns the file name of the generated archive .
31,437
public synchronized void close ( ) throws IOException , InterruptedException { logger . info ( "shutting down cm processor" ) ; if ( closed . get ( ) ) { return ; } closed . set ( true ) ; thread . join ( ) ; logger . info ( "cm processor down" ) ; cmChannel . destroyEventChannel ( ) ; logger . info ( "cm channel down" ) ; }
Close the event loop .
31,438
public C accept ( ) throws IOException { try { synchronized ( this ) { if ( connState != CONN_STATE_READY_FOR_ACCEPT ) { throw new IOException ( "bind needs to be called before accept (1), current state =" + connState ) ; } logger . info ( "starting accept" ) ; if ( requested . peek ( ) == null ) { wait ( ) ; } } C endpoint = requested . poll ( ) ; logger . info ( "connect request received" ) ; endpoint . accept ( ) ; return endpoint ; } catch ( Exception e ) { throw new IOException ( e ) ; } }
Extract the first connection request on the queue of pending connections .
31,439
public synchronized void close ( ) throws IOException , InterruptedException { if ( isClosed ) { return ; } logger . info ( "closing client endpoint" ) ; if ( connState == CONN_STATE_CONNECTED ) { idPriv . disconnect ( ) ; this . wait ( 1000 ) ; } if ( connState >= CONN_STATE_RESOURCES_ALLOCATED ) { idPriv . destroyQP ( ) ; } idPriv . destroyId ( ) ; group . unregisterClientEp ( this ) ; isClosed = true ; logger . info ( "closing client done" ) ; }
Close this endpoint .
31,440
public SVCPostRecv postRecv ( List < IbvRecvWR > recvList ) throws IOException { return qp . postRecv ( recvList , null ) ; }
Post a receive operation on this endpoint .
31,441
public SVCPostSend postSend ( List < IbvSendWR > sendList ) throws IOException { return qp . postSend ( sendList , null ) ; }
Post a send operation on this endpoint .
31,442
public static URLConnection getConnection ( URL url , Map inCookies , boolean input , boolean output , boolean cache , boolean allowAllCerts ) throws IOException { URLConnection c = url . openConnection ( ) ; c . setRequestProperty ( "Accept-Encoding" , "gzip, deflate" ) ; c . setAllowUserInteraction ( false ) ; c . setDoOutput ( output ) ; c . setDoInput ( input ) ; c . setUseCaches ( cache ) ; c . setReadTimeout ( 220000 ) ; c . setConnectTimeout ( 45000 ) ; String ref = getReferrer ( ) ; if ( StringUtilities . hasContent ( ref ) ) { c . setRequestProperty ( "Referer" , ref ) ; } String agent = getUserAgent ( ) ; if ( StringUtilities . hasContent ( agent ) ) { c . setRequestProperty ( "User-Agent" , agent ) ; } if ( c instanceof HttpURLConnection ) { HttpURLConnection . setFollowRedirects ( true ) ; } if ( c instanceof HttpsURLConnection && allowAllCerts ) { try { setNaiveSSLSocketFactory ( ( HttpsURLConnection ) c ) ; } catch ( Exception e ) { LOG . warn ( "Could not access '" + url . toString ( ) + "'" , e ) ; } } if ( inCookies != null ) { setCookies ( c , inCookies ) ; } return c ; }
Gets a connection from a url . All getConnection calls should go through this code .
31,443
public static void safelyIgnoreException ( Throwable t ) { if ( t instanceof ThreadDeath ) { throw ( ThreadDeath ) t ; } if ( t instanceof OutOfMemoryError ) { throw ( OutOfMemoryError ) t ; } }
Safely Ignore a Throwable or rethrow if it is a Throwable that should not be ignored .
31,444
private static void compareSets ( Delta delta , Collection deltas , LinkedList stack , ID idFetcher ) { Set srcSet = ( Set ) delta . srcValue ; Set targetSet = ( Set ) delta . targetValue ; Map targetIdToValue = new HashMap ( ) ; for ( Object targetValue : targetSet ) { if ( targetValue != null && isIdObject ( targetValue , idFetcher ) ) { targetIdToValue . put ( idFetcher . getId ( targetValue ) , targetValue ) ; } } Map srcIdToValue = new HashMap ( ) ; String sysId = "(" + System . identityHashCode ( srcSet ) + ").remove(" ; for ( Object srcValue : srcSet ) { String srcPtr = sysId + System . identityHashCode ( srcValue ) + ')' ; if ( isIdObject ( srcValue , idFetcher ) ) { Object srcId = idFetcher . getId ( srcValue ) ; srcIdToValue . put ( srcId , srcValue ) ; if ( targetIdToValue . containsKey ( srcId ) ) { stack . push ( new Delta ( delta . id , delta . fieldName , srcPtr , srcValue , targetIdToValue . get ( srcId ) , null ) ) ; } else { Delta removeDelta = new Delta ( delta . id , delta . fieldName , srcPtr , srcValue , null , null ) ; removeDelta . setCmd ( SET_REMOVE ) ; deltas . add ( removeDelta ) ; } } else { if ( ! targetSet . contains ( srcValue ) ) { Delta removeDelta = new Delta ( delta . id , delta . fieldName , srcPtr , srcValue , null , null ) ; removeDelta . setCmd ( SET_REMOVE ) ; deltas . add ( removeDelta ) ; } } } sysId = "(" + System . identityHashCode ( targetSet ) + ").add(" ; for ( Object targetValue : targetSet ) { String srcPtr = sysId + System . identityHashCode ( targetValue ) + ')' ; if ( isIdObject ( targetValue , idFetcher ) ) { Object targetId = idFetcher . getId ( targetValue ) ; if ( ! srcIdToValue . containsKey ( targetId ) ) { Delta addDelta = new Delta ( delta . id , delta . fieldName , srcPtr , null , targetValue , null ) ; addDelta . setCmd ( SET_ADD ) ; deltas . add ( addDelta ) ; } } else { if ( ! srcSet . contains ( targetValue ) ) { Delta addDelta = new Delta ( delta . id , delta . fieldName , srcPtr , null , targetValue , null ) ; addDelta . setCmd ( SET_ADD ) ; deltas . add ( addDelta ) ; } } } }
Deeply compare two Sets and generate the appropriate add or remove commands to rectify their differences .
31,445
private static void compareMaps ( Delta delta , Collection deltas , LinkedList stack , ID idFetcher ) { Map < Object , Object > srcMap = ( Map < Object , Object > ) delta . srcValue ; Map < Object , Object > targetMap = ( Map < Object , Object > ) delta . targetValue ; final String sysId = "(" + System . identityHashCode ( srcMap ) + ')' ; for ( Map . Entry entry : srcMap . entrySet ( ) ) { Object srcKey = entry . getKey ( ) ; Object srcValue = entry . getValue ( ) ; String srcPtr = sysId + "['" + System . identityHashCode ( srcKey ) + "']" ; if ( targetMap . containsKey ( srcKey ) ) { Object targetValue = targetMap . get ( srcKey ) ; if ( srcValue == null || targetValue == null ) { if ( srcValue != targetValue ) { addMapPutDelta ( delta , deltas , srcPtr , targetValue , srcKey ) ; } } else if ( isIdObject ( srcValue , idFetcher ) && isIdObject ( targetValue , idFetcher ) ) { if ( idFetcher . getId ( srcValue ) . equals ( idFetcher . getId ( targetValue ) ) ) { stack . push ( new Delta ( delta . id , delta . fieldName , srcPtr , srcValue , targetValue , null ) ) ; } else { addMapPutDelta ( delta , deltas , srcPtr , targetValue , srcKey ) ; } } else if ( ! DeepEquals . deepEquals ( srcValue , targetValue ) ) { addMapPutDelta ( delta , deltas , srcPtr , targetValue , srcKey ) ; } } else { Delta removeDelta = new Delta ( delta . id , delta . fieldName , srcPtr , srcValue , null , srcKey ) ; removeDelta . setCmd ( MAP_REMOVE ) ; deltas . add ( removeDelta ) ; } } for ( Map . Entry entry : targetMap . entrySet ( ) ) { Object targetKey = entry . getKey ( ) ; String srcPtr = sysId + "['" + System . identityHashCode ( targetKey ) + "']" ; if ( ! srcMap . containsKey ( targetKey ) ) { Delta putDelta = new Delta ( delta . id , delta . fieldName , srcPtr , null , entry . getValue ( ) , targetKey ) ; putDelta . setCmd ( MAP_PUT ) ; deltas . add ( putDelta ) ; } } }
Deeply compare two Maps and generate the appropriate put or remove commands to rectify their differences .
31,446
private static void compareLists ( Delta delta , Collection deltas , LinkedList stack , ID idFetcher ) { List srcList = ( List ) delta . srcValue ; List targetList = ( List ) delta . targetValue ; int srcLen = srcList . size ( ) ; int targetLen = targetList . size ( ) ; if ( srcLen != targetLen ) { delta . setCmd ( LIST_RESIZE ) ; delta . setOptionalKey ( targetLen ) ; deltas . add ( delta ) ; } final String sysId = "(" + System . identityHashCode ( srcList ) + ')' ; for ( int i = targetLen - 1 ; i >= 0 ; i -- ) { final Object targetValue = targetList . get ( i ) ; String srcPtr = sysId + '{' + i + '}' ; if ( i < srcLen ) { final Object srcValue = srcList . get ( i ) ; if ( targetValue == null || srcValue == null ) { if ( srcValue != targetValue ) { copyListElement ( delta , deltas , srcPtr , srcValue , targetValue , i ) ; } } else if ( isIdObject ( srcValue , idFetcher ) && isIdObject ( targetValue , idFetcher ) ) { Object srcId = idFetcher . getId ( srcValue ) ; Object targetId = idFetcher . getId ( targetValue ) ; if ( targetId . equals ( srcId ) ) { stack . push ( new Delta ( delta . id , delta . fieldName , srcPtr , srcValue , targetValue , i ) ) ; } else { copyListElement ( delta , deltas , srcPtr , srcValue , targetValue , i ) ; } } else if ( ! DeepEquals . deepEquals ( srcValue , targetValue ) ) { copyListElement ( delta , deltas , srcPtr , srcValue , targetValue , i ) ; } } else { copyListElement ( delta , deltas , srcPtr , null , targetValue , i ) ; } } }
Deeply compare two Lists and generate the appropriate resize or set commands to rectify their differences .
31,447
public static Cipher createAesCipher ( Key key , int mode ) throws Exception { MessageDigest d = getMD5Digest ( ) ; d . update ( key . getEncoded ( ) ) ; byte [ ] iv = d . digest ( ) ; AlgorithmParameterSpec paramSpec = new IvParameterSpec ( iv ) ; Cipher cipher = Cipher . getInstance ( "AES/CBC/PKCS5Padding" ) ; cipher . init ( mode , key , paramSpec ) ; return cipher ; }
Creates a Cipher from the passed in key using the passed in mode .
31,448
public static String encrypt ( String key , String content ) { try { return ByteUtilities . encode ( createAesEncryptionCipher ( key ) . doFinal ( content . getBytes ( StandardCharsets . UTF_8 ) ) ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Error occurred encrypting data" , e ) ; } }
Get hex String of content String encrypted .
31,449
public static String decrypt ( String key , String hexStr ) { try { return new String ( createAesDecryptionCipher ( key ) . doFinal ( ByteUtilities . decode ( hexStr ) ) ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Error occurred decrypting data" , e ) ; } }
Get unencrypted String from encrypted hex String
31,450
public static < T > T get ( Map map , String key , T def ) { Object val = map . get ( key ) ; return val == null ? def : ( T ) val ; }
Retrieves a value from a map by key
31,451
public static byte [ ] decode ( String s ) { int len = s . length ( ) ; if ( len % 2 != 0 ) { return null ; } byte [ ] bytes = new byte [ len / 2 ] ; int pos = 0 ; for ( int i = 0 ; i < len ; i += 2 ) { byte hi = ( byte ) Character . digit ( s . charAt ( i ) , 16 ) ; byte lo = ( byte ) Character . digit ( s . charAt ( i + 1 ) , 16 ) ; bytes [ pos ++ ] = ( byte ) ( hi * 16 + lo ) ; } return bytes ; }
If string is not even length return null .
31,452
public static int damerauLevenshteinDistance ( CharSequence source , CharSequence target ) { if ( source == null || "" . equals ( source ) ) { return target == null || "" . equals ( target ) ? 0 : target . length ( ) ; } else if ( target == null || "" . equals ( target ) ) { return source . length ( ) ; } int srcLen = source . length ( ) ; int targetLen = target . length ( ) ; int [ ] [ ] distanceMatrix = new int [ srcLen + 1 ] [ targetLen + 1 ] ; for ( int srcIndex = 0 ; srcIndex <= srcLen ; srcIndex ++ ) { distanceMatrix [ srcIndex ] [ 0 ] = srcIndex ; } for ( int targetIndex = 0 ; targetIndex <= targetLen ; targetIndex ++ ) { distanceMatrix [ 0 ] [ targetIndex ] = targetIndex ; } for ( int srcIndex = 1 ; srcIndex <= srcLen ; srcIndex ++ ) { for ( int targetIndex = 1 ; targetIndex <= targetLen ; targetIndex ++ ) { int cost = source . charAt ( srcIndex - 1 ) == target . charAt ( targetIndex - 1 ) ? 0 : 1 ; distanceMatrix [ srcIndex ] [ targetIndex ] = ( int ) MathUtilities . minimum ( distanceMatrix [ srcIndex - 1 ] [ targetIndex ] + 1 , distanceMatrix [ srcIndex ] [ targetIndex - 1 ] + 1 , distanceMatrix [ srcIndex - 1 ] [ targetIndex - 1 ] + cost ) ; if ( srcIndex == 1 || targetIndex == 1 ) { continue ; } if ( source . charAt ( srcIndex - 1 ) == target . charAt ( targetIndex - 2 ) && source . charAt ( srcIndex - 2 ) == target . charAt ( targetIndex - 1 ) ) { distanceMatrix [ srcIndex ] [ targetIndex ] = ( int ) MathUtilities . minimum ( distanceMatrix [ srcIndex ] [ targetIndex ] , distanceMatrix [ srcIndex - 2 ] [ targetIndex - 2 ] + cost ) ; } } } return distanceMatrix [ srcLen ] [ targetLen ] ; }
Calculate the Damerau - Levenshtein Distance between two strings . The basic difference between this algorithm and the general Levenshtein algorithm is that damerau - Levenshtein counts a swap of two characters next to each other as 1 instead of 2 . This breaks the triangular equality which makes it unusable for Metric trees . See Wikipedia pages on both Levenshtein and Damerau - Levenshtein and then make your decision as to which algorithm is appropriate for your situation .
31,453
public static int hashCodeIgnoreCase ( String s ) { if ( s == null ) { return 0 ; } int hash = 0 ; int len = s . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = Character . toLowerCase ( s . charAt ( i ) ) ; hash = 31 * hash + c ; } return hash ; }
Get the hashCode of a String insensitive to case without any new Strings being created on the heap .
31,454
public static BigDecimal maximum ( BigDecimal ... values ) { int len = values . length ; if ( len == 1 ) { if ( values [ 0 ] == null ) { throw new IllegalArgumentException ( "Cannot passed null BigDecimal entry to maximum()" ) ; } return values [ 0 ] ; } BigDecimal current = values [ 0 ] ; for ( int i = 1 ; i < len ; i ++ ) { if ( values [ i ] == null ) { throw new IllegalArgumentException ( "Cannot passed null BigDecimal entry to maximum()" ) ; } current = values [ i ] . max ( current ) ; } return current ; }
Calculate the maximum value from an array of values .
31,455
private static boolean compareOrderedCollection ( Collection col1 , Collection col2 , Deque stack , Set visited ) { if ( col1 . size ( ) != col2 . size ( ) ) { return false ; } Iterator i1 = col1 . iterator ( ) ; Iterator i2 = col2 . iterator ( ) ; while ( i1 . hasNext ( ) ) { DualKey dk = new DualKey ( i1 . next ( ) , i2 . next ( ) ) ; if ( ! visited . contains ( dk ) ) { stack . addFirst ( dk ) ; } } return true ; }
Deeply compare two Collections that must be same length and in same order .
31,456
private static boolean compareSortedMap ( SortedMap map1 , SortedMap map2 , Deque stack , Set visited ) { if ( map1 . size ( ) != map2 . size ( ) ) { return false ; } Iterator i1 = map1 . entrySet ( ) . iterator ( ) ; Iterator i2 = map2 . entrySet ( ) . iterator ( ) ; while ( i1 . hasNext ( ) ) { Map . Entry entry1 = ( Map . Entry ) i1 . next ( ) ; Map . Entry entry2 = ( Map . Entry ) i2 . next ( ) ; DualKey dk = new DualKey ( entry1 . getKey ( ) , entry2 . getKey ( ) ) ; if ( ! visited . contains ( dk ) ) { stack . addFirst ( dk ) ; } dk = new DualKey ( entry1 . getValue ( ) , entry2 . getValue ( ) ) ; if ( ! visited . contains ( dk ) ) { stack . addFirst ( dk ) ; } } return true ; }
Deeply compare two SortedMap instances . This method walks the Maps in order taking advantage of the fact that the Maps are SortedMaps .
31,457
private static boolean compareFloatingPointNumbers ( Object a , Object b , double epsilon ) { double a1 = a instanceof Double ? ( Double ) a : ( Float ) a ; double b1 = b instanceof Double ? ( Double ) b : ( Float ) b ; return nearlyEqual ( a1 , b1 , epsilon ) ; }
Compare if two floating point numbers are within a given range
31,458
public static String getExternalVariable ( String var ) { String value = System . getProperty ( var ) ; if ( StringUtilities . isEmpty ( value ) ) { value = System . getenv ( var ) ; } return StringUtilities . isEmpty ( value ) ? null : value ; }
Fetch value from environment variable and if not set then fetch from System properties . If neither available return null .
31,459
public void walk ( Object root , Class [ ] skip , Visitor visitor ) { Deque stack = new LinkedList ( ) ; stack . add ( root ) ; while ( ! stack . isEmpty ( ) ) { Object current = stack . removeFirst ( ) ; if ( current == null || _objVisited . containsKey ( current ) ) { continue ; } final Class clazz = current . getClass ( ) ; ClassInfo classInfo = getClassInfo ( clazz , skip ) ; if ( classInfo . _skip ) { continue ; } _objVisited . put ( current , null ) ; visitor . process ( current ) ; if ( clazz . isArray ( ) ) { int len = Array . getLength ( current ) ; Class compType = clazz . getComponentType ( ) ; if ( ! compType . isPrimitive ( ) ) { ClassInfo info = getClassInfo ( compType , skip ) ; if ( ! info . _skip ) { for ( int i = 0 ; i < len ; i ++ ) { Object element = Array . get ( current , i ) ; if ( element != null ) { stack . add ( Array . get ( current , i ) ) ; } } } } } else { if ( current instanceof Collection ) { walkCollection ( stack , ( Collection ) current ) ; } else if ( current instanceof Map ) { walkMap ( stack , ( Map ) current ) ; } else { walkFields ( stack , current , skip ) ; } } } }
Traverse the object graph referenced by the passed in root .
31,460
public void destroy ( ) throws Exception { if ( this . reporters != null ) { for ( Closeable reporter : this . reporters ) { try { reporter . close ( ) ; } catch ( Exception ex ) { LOG . warn ( "Problem stopping reporter" , ex ) ; } } } }
Called when the Spring context is closed this method stops reporters .
31,461
protected < R extends Closeable > R registerReporter ( final R reporter ) { if ( this . reporters == null ) { this . reporters = new HashSet < Closeable > ( ) ; } this . reporters . add ( reporter ) ; return reporter ; }
Registers a reporter for destruction on Spring context close
31,462
public static PactDslRootValue decimalType ( ) { PactDslRootValue value = new PactDslRootValue ( ) ; value . generators . addGenerator ( Category . BODY , "" , new RandomDecimalGenerator ( 10 ) ) ; value . setValue ( 100 ) ; value . setMatcher ( new NumberTypeMatcher ( NumberTypeMatcher . NumberType . DECIMAL ) ) ; return value ; }
Value that must be a decimal value
31,463
protected Map < String , RequestResponsePact > getPacts ( String fragment ) { if ( pacts == null ) { pacts = new HashMap < > ( ) ; for ( Method m : target . getClass ( ) . getMethods ( ) ) { if ( JUnitTestSupport . conformsToSignature ( m ) && methodMatchesFragment ( m , fragment ) ) { Pact pactAnnotation = m . getAnnotation ( Pact . class ) ; if ( StringUtils . isEmpty ( pactAnnotation . provider ( ) ) || provider . equals ( pactAnnotation . provider ( ) ) ) { PactDslWithProvider dslBuilder = ConsumerPactBuilder . consumer ( pactAnnotation . consumer ( ) ) . hasPactWith ( provider ) ; updateAnyDefaultValues ( dslBuilder ) ; try { RequestResponsePact pact = ( RequestResponsePact ) m . invoke ( target , dslBuilder ) ; pacts . put ( provider , pact ) ; } catch ( Exception e ) { throw new RuntimeException ( "Failed to invoke pact method" , e ) ; } } } } } return pacts ; }
scan all methods for
31,464
public PactDslRequestWithPath matchHeader ( String header , String regex ) { return matchHeader ( header , regex , new Generex ( regex ) . random ( ) ) ; }
Match a request header . A random example header value will be generated from the provided regular expression .
31,465
public PactDslRequestWithPath matchHeader ( String header , String regex , String headerExample ) { requestMatchers . addCategory ( "header" ) . setRule ( header , new RegexMatcher ( regex ) ) ; requestHeaders . put ( header , Collections . singletonList ( headerExample ) ) ; return this ; }
Match a request header .
31,466
public PactDslRequestWithPath matchQuery ( String parameter , String regex ) { return matchQuery ( parameter , regex , new Generex ( regex ) . random ( ) ) ; }
Match a query parameter with a regex . A random query parameter value will be generated from the regex .
31,467
public PactDslRequestWithPath matchQuery ( String parameter , String regex , List < String > example ) { requestMatchers . addCategory ( "query" ) . addRule ( parameter , new RegexMatcher ( regex ) ) ; query . put ( parameter , example ) ; return this ; }
Match a repeating query parameter with a regex .
31,468
public static PactDslJsonRootValue decimalType ( BigDecimal number ) { PactDslJsonRootValue value = new PactDslJsonRootValue ( ) ; value . setValue ( number ) ; value . setMatcher ( new NumberTypeMatcher ( NumberTypeMatcher . NumberType . DECIMAL ) ) ; return value ; }
Value that must be a decimalType value
31,469
public static PactDslJsonRootValue valueFromProviderState ( String expression , Object example ) { PactDslJsonRootValue value = new PactDslJsonRootValue ( ) ; value . generators . addGenerator ( Category . BODY , "" , new ProviderStateGenerator ( expression ) ) ; value . setValue ( example ) ; return value ; }
Adds a value that will have it s value injected from the provider state
31,470
public LambdaDslJsonArray minArrayLike ( Integer size , Consumer < LambdaDslJsonBody > nestedObject ) { final PactDslJsonBody arrayLike = pactArray . minArrayLike ( size ) ; final LambdaDslJsonBody dslBody = new LambdaDslJsonBody ( arrayLike ) ; nestedObject . accept ( dslBody ) ; arrayLike . closeArray ( ) ; return this ; }
Element that is an array with a minimum size where each item must match the following example
31,471
public LambdaDslJsonArray minMaxArrayLike ( Integer minSize , Integer maxSize , Consumer < LambdaDslJsonBody > nestedObject ) { final PactDslJsonBody arrayLike = pactArray . minMaxArrayLike ( minSize , maxSize ) ; final LambdaDslJsonBody dslBody = new LambdaDslJsonBody ( arrayLike ) ; nestedObject . accept ( dslBody ) ; arrayLike . closeArray ( ) ; return this ; }
Element that is an array with a minimum and maximum size where each item must match the following example
31,472
public LambdaDslObject eachLike ( String name , Consumer < LambdaDslObject > nestedObject ) { final PactDslJsonBody arrayLike = object . eachLike ( name ) ; final LambdaDslObject dslObject = new LambdaDslObject ( arrayLike ) ; nestedObject . accept ( dslObject ) ; arrayLike . closeArray ( ) ; return this ; }
Attribute that is an array where each item must match the following example
31,473
public LambdaDslObject eachLike ( String name , PactDslJsonRootValue value , int numberExamples ) { object . eachLike ( name , value , numberExamples ) ; return this ; }
Attribute that is an array where each item is a primitive that must match the provided value
31,474
public LambdaDslObject minArrayLike ( String name , Integer size , Consumer < LambdaDslObject > nestedObject ) { final PactDslJsonBody minArrayLike = object . minArrayLike ( name , size ) ; final LambdaDslObject dslObject = new LambdaDslObject ( minArrayLike ) ; nestedObject . accept ( dslObject ) ; minArrayLike . closeArray ( ) ; return this ; }
Attribute that is an array with a minimum size where each item must match the following example
31,475
public LambdaDslObject minArrayLike ( String name , Integer size , PactDslJsonRootValue value , int numberExamples ) { object . minArrayLike ( name , size , value , numberExamples ) ; return this ; }
Attribute that is an array of values with a minimum size that are not objects where each item must match the following example
31,476
public LambdaDslObject maxArrayLike ( String name , Integer size , Consumer < LambdaDslObject > nestedObject ) { final PactDslJsonBody maxArrayLike = object . maxArrayLike ( name , size ) ; final LambdaDslObject dslObject = new LambdaDslObject ( maxArrayLike ) ; nestedObject . accept ( dslObject ) ; maxArrayLike . closeArray ( ) ; return this ; }
Attribute that is an array with a maximum size where each item must match the following example
31,477
public LambdaDslObject minMaxArrayLike ( String name , Integer minSize , Integer maxSize , int numberExamples , Consumer < LambdaDslObject > nestedObject ) { final PactDslJsonBody maxArrayLike = object . minMaxArrayLike ( name , minSize , maxSize , numberExamples ) ; final LambdaDslObject dslObject = new LambdaDslObject ( maxArrayLike ) ; nestedObject . accept ( dslObject ) ; maxArrayLike . closeArray ( ) ; return this ; }
Attribute that is an array with a minimum and maximum size where each item must match the following example
31,478
public LambdaDslObject minMaxArrayLike ( String name , Integer minSize , Integer maxSize , PactDslJsonRootValue value , int numberExamples ) { object . minMaxArrayLike ( name , minSize , maxSize , value , numberExamples ) ; return this ; }
Attribute that is an array of values with a minimum and maximum size that are not objects where each item must match the following example
31,479
public PactDslWithState given ( String stateDesc , Map < String , Object > params ) { state . add ( new ProviderState ( stateDesc , params ) ) ; return this ; }
Adds another provider state to this interaction
31,480
public PactDslRequestWithoutPath uponReceiving ( String description ) { return new PactDslWithState ( consumerPactBuilder , consumerPactBuilder . getConsumerName ( ) , providerName , defaultRequestValues , defaultResponseValues ) . uponReceiving ( description ) ; }
Description of the request that is expected to be received
31,481
public DslPart closeArray ( ) { if ( parent != null ) { parent . putArray ( this ) ; } else { getMatchers ( ) . applyMatcherRootPrefix ( "$" ) ; getGenerators ( ) . applyRootPrefix ( "$" ) ; } closed = true ; return parent ; }
Closes the current array
31,482
public PactDslJsonBody maxArrayLike ( Integer size , int numberExamples ) { if ( numberExamples > size ) { throw new IllegalArgumentException ( String . format ( "Number of example %d is more than the maximum size of %d" , numberExamples , size ) ) ; } matchers . addRule ( rootPath + appendArrayIndex ( 1 ) , matchMax ( size ) ) ; PactDslJsonArray parent = new PactDslJsonArray ( "" , "" , this , true ) ; parent . setNumberExamples ( numberExamples ) ; return new PactDslJsonBody ( "." , "" , parent ) ; }
Element that is an array with a maximum size where each item must match the following example
31,483
public PactDslJsonArray stringValue ( String value ) { if ( value == null ) { body . put ( JSONObject . NULL ) ; } else { body . put ( value ) ; } return this ; }
Element that must be the specified value
31,484
public PactDslJsonArray integerType ( Long number ) { body . put ( number ) ; matchers . addRule ( rootPath + appendArrayIndex ( 0 ) , new NumberTypeMatcher ( NumberTypeMatcher . NumberType . INTEGER ) ) ; return this ; }
Element that must be an integer
31,485
public PactDslJsonArray decimalType ( ) { generators . addGenerator ( Category . BODY , rootPath + appendArrayIndex ( 1 ) , new RandomDecimalGenerator ( 10 ) ) ; return decimalType ( new BigDecimal ( "100" ) ) ; }
Element that must be a decimal value
31,486
public PactDslJsonArray decimalType ( BigDecimal number ) { body . put ( number ) ; matchers . addRule ( rootPath + appendArrayIndex ( 0 ) , new NumberTypeMatcher ( NumberTypeMatcher . NumberType . DECIMAL ) ) ; return this ; }
Element that must be a decimalType value
31,487
public PactDslJsonArray timestamp ( ) { String pattern = DateFormatUtils . ISO_DATETIME_FORMAT . getPattern ( ) ; body . put ( DateFormatUtils . ISO_DATETIME_FORMAT . format ( new Date ( DATE_2000 ) ) ) ; generators . addGenerator ( Category . BODY , rootPath + appendArrayIndex ( 0 ) , new DateTimeGenerator ( pattern ) ) ; matchers . addRule ( rootPath + appendArrayIndex ( 0 ) , matchTimestamp ( pattern ) ) ; return this ; }
Element that must be an ISO formatted timestamp
31,488
public PactDslJsonArray date ( ) { String pattern = DateFormatUtils . ISO_DATE_FORMAT . getPattern ( ) ; body . put ( DateFormatUtils . ISO_DATE_FORMAT . format ( new Date ( DATE_2000 ) ) ) ; generators . addGenerator ( Category . BODY , rootPath + appendArrayIndex ( 0 ) , new DateGenerator ( pattern ) ) ; matchers . addRule ( rootPath + appendArrayIndex ( 0 ) , matchDate ( pattern ) ) ; return this ; }
Element that must be formatted as an ISO date
31,489
public PactDslJsonArray time ( ) { String pattern = DateFormatUtils . ISO_TIME_FORMAT . getPattern ( ) ; body . put ( DateFormatUtils . ISO_TIME_FORMAT . format ( new Date ( DATE_2000 ) ) ) ; generators . addGenerator ( Category . BODY , rootPath + appendArrayIndex ( 0 ) , new TimeGenerator ( pattern ) ) ; matchers . addRule ( rootPath + appendArrayIndex ( 0 ) , matchTime ( pattern ) ) ; return this ; }
Element that must be an ISO formatted time
31,490
public PactDslJsonArray template ( DslPart template , int occurrences ) { for ( int i = 0 ; i < occurrences ; i ++ ) { template ( template ) ; } return this ; }
Adds a number of template objects to the array
31,491
public static PactDslJsonBody arrayEachLike ( Integer numberExamples ) { PactDslJsonArray parent = new PactDslJsonArray ( "" , "" , null , true ) ; parent . setNumberExamples ( numberExamples ) ; parent . matchers . addRule ( "" , parent . matchMin ( 0 ) ) ; return new PactDslJsonBody ( "." , "" , parent ) ; }
Array where each item must match the following example
31,492
public static PactDslJsonArray arrayEachLike ( Integer numberExamples , PactDslJsonRootValue value ) { PactDslJsonArray parent = new PactDslJsonArray ( "" , "" , null , true ) ; parent . setNumberExamples ( numberExamples ) ; parent . matchers . addRule ( "" , parent . matchMin ( 0 ) ) ; parent . putObject ( value ) ; return parent ; }
Root level array where each item must match the provided matcher
31,493
public static PactDslJsonBody arrayMinLike ( int minSize , int numberExamples ) { if ( numberExamples < minSize ) { throw new IllegalArgumentException ( String . format ( "Number of example %d is less than the minimum size of %d" , numberExamples , minSize ) ) ; } PactDslJsonArray parent = new PactDslJsonArray ( "" , "" , null , true ) ; parent . setNumberExamples ( numberExamples ) ; parent . matchers . addRule ( "" , parent . matchMin ( minSize ) ) ; return new PactDslJsonBody ( "." , "" , parent ) ; }
Array with a minimum size where each item must match the following example
31,494
public static PactDslJsonArray arrayMinLike ( int minSize , int numberExamples , PactDslJsonRootValue value ) { if ( numberExamples < minSize ) { throw new IllegalArgumentException ( String . format ( "Number of example %d is less than the minimum size of %d" , numberExamples , minSize ) ) ; } PactDslJsonArray parent = new PactDslJsonArray ( "" , "" , null , true ) ; parent . setNumberExamples ( numberExamples ) ; parent . matchers . addRule ( "" , parent . matchMin ( minSize ) ) ; parent . putObject ( value ) ; return parent ; }
Root level array with minimum size where each item must match the provided matcher
31,495
public static PactDslJsonBody arrayMaxLike ( int maxSize , int numberExamples ) { if ( numberExamples > maxSize ) { throw new IllegalArgumentException ( String . format ( "Number of example %d is more than the maximum size of %d" , numberExamples , maxSize ) ) ; } PactDslJsonArray parent = new PactDslJsonArray ( "" , "" , null , true ) ; parent . setNumberExamples ( numberExamples ) ; parent . matchers . addRule ( "" , parent . matchMax ( maxSize ) ) ; return new PactDslJsonBody ( "." , "" , parent ) ; }
Array with a maximum size where each item must match the following example
31,496
public static PactDslJsonArray arrayMaxLike ( int maxSize , int numberExamples , PactDslJsonRootValue value ) { if ( numberExamples > maxSize ) { throw new IllegalArgumentException ( String . format ( "Number of example %d is more than the maximum size of %d" , numberExamples , maxSize ) ) ; } PactDslJsonArray parent = new PactDslJsonArray ( "" , "" , null , true ) ; parent . setNumberExamples ( numberExamples ) ; parent . matchers . addRule ( "" , parent . matchMax ( maxSize ) ) ; parent . putObject ( value ) ; return parent ; }
Root level array with maximum size where each item must match the provided matcher
31,497
public static PactDslJsonBody arrayMinMaxLike ( int minSize , int maxSize , int numberExamples ) { if ( numberExamples < minSize ) { throw new IllegalArgumentException ( String . format ( "Number of example %d is less than the minimum size of %d" , numberExamples , minSize ) ) ; } else if ( numberExamples > maxSize ) { throw new IllegalArgumentException ( String . format ( "Number of example %d is more than the maximum size of %d" , numberExamples , maxSize ) ) ; } PactDslJsonArray parent = new PactDslJsonArray ( "" , "" , null , true ) ; parent . setNumberExamples ( numberExamples ) ; parent . matchers . addRule ( "" , parent . matchMinMax ( minSize , maxSize ) ) ; return new PactDslJsonBody ( "." , "" , parent ) ; }
Array with a minimum and maximum size where each item must match the following example
31,498
public PactDslJsonArray eachLike ( PactDslJsonRootValue value , int numberExamples ) { if ( numberExamples == 0 ) { throw new IllegalArgumentException ( "Testing Zero examples is unsafe. Please make sure to provide at least one " + "example in the Pact provider implementation. See https://github.com/DiUS/pact-jvm/issues/546" ) ; } matchers . addRule ( rootPath + appendArrayIndex ( 1 ) , matchMin ( 0 ) ) ; PactDslJsonArray parent = new PactDslJsonArray ( rootPath , "" , this , true ) ; parent . setNumberExamples ( numberExamples ) ; parent . putObject ( value ) ; return ( PactDslJsonArray ) parent . closeArray ( ) ; }
Array of values that are not objects where each item must match the provided example
31,499
public PactDslJsonArray minArrayLike ( Integer size , PactDslJsonRootValue value ) { return minArrayLike ( size , value , size ) ; }
Array of values with a minimum size that are not objects where each item must match the provided example