idx
int64 0
41.2k
| question
stringlengths 74
4.04k
| target
stringlengths 7
750
|
|---|---|---|
36,300
|
protected void setNextValue ( final long pValue , final int pLength , final int pMaxSize ) { long value = pValue ; long bitMax = ( long ) Math . pow ( 2 , Math . min ( pLength , pMaxSize ) ) ; if ( pValue > bitMax ) { value = bitMax - 1 ; } int writeSize = pLength ; while ( writeSize > 0 ) { int mod = currentBitIndex % BYTE_SIZE ; byte ret = 0 ; if ( mod == 0 && writeSize <= BYTE_SIZE || pLength < BYTE_SIZE - mod ) { ret = ( byte ) ( value << BYTE_SIZE - ( writeSize + mod ) ) ; } else { long length = Long . toBinaryString ( value ) . length ( ) ; ret = ( byte ) ( value >> writeSize - length - ( BYTE_SIZE - length - mod ) ) ; } byteTab [ currentBitIndex / BYTE_SIZE ] |= ret ; long val = Math . min ( writeSize , BYTE_SIZE - mod ) ; writeSize -= val ; currentBitIndex += val ; } }
|
Add Value to the current position with the specified size
|
36,301
|
public void setNextInteger ( final int pValue , final int pLength ) { if ( pLength > Integer . SIZE ) { throw new IllegalArgumentException ( "Integer overflow with length > 32" ) ; } setNextValue ( pValue , pLength , Integer . SIZE - 1 ) ; }
|
Add Integer to the current position with the specified size
|
36,302
|
public void setNextString ( final String pValue , final int pLength , final boolean pPaddedBefore ) { setNextByte ( pValue . getBytes ( Charset . defaultCharset ( ) ) , pLength , pPaddedBefore ) ; }
|
Method to write a String
|
36,303
|
public void setResult ( R result ) { try { lock . lock ( ) ; this . result = result ; notifyHaveResult ( ) ; } finally { lock . unlock ( ) ; } }
|
Set the result value and notify about operation completion .
|
36,304
|
public void failure ( Throwable failure ) { try { lock . lock ( ) ; this . failure = failure ; notifyHaveResult ( ) ; } finally { lock . unlock ( ) ; } }
|
Notify about the failure occured during asynchronous operation execution .
|
36,305
|
void clean ( QNode pred , QNode s ) { Thread w = s . waiter ; if ( w != null ) { s . waiter = null ; if ( w != Thread . currentThread ( ) ) { LockSupport . unpark ( w ) ; } } while ( pred . next == s ) { QNode oldpred = reclean ( ) ; QNode t = getValidatedTail ( ) ; if ( s != t ) { QNode sn = s . next ; if ( sn == s || pred . casNext ( s , sn ) ) { break ; } } else if ( oldpred == pred || oldpred == null && this . cleanMe . compareAndSet ( null , pred ) ) { break ; } } }
|
Gets rid of cancelled node s with original predecessor pred .
|
36,306
|
private QNode reclean ( ) { QNode pred ; while ( ( pred = this . cleanMe . get ( ) ) != null ) { QNode t = getValidatedTail ( ) ; QNode s = pred . next ; if ( s != t ) { QNode sn ; if ( s == null || s == pred || s . get ( ) != s || ( sn = s . next ) == s || pred . casNext ( s , sn ) ) { this . cleanMe . compareAndSet ( pred , null ) ; } } else { break ; } } return pred ; }
|
Tries to unsplice the cancelled node held in cleanMe that was previously uncleanable because it was at tail .
|
36,307
|
static StorageCache initCache ( Configuration configuration ) { if ( configuration . getBoolean ( Configuration . CACHE_ENABLED ) && configuration . getLong ( Configuration . CACHE_BYTES ) > 0 ) { return new StorageCache ( configuration ) ; } else { return new DisabledCache ( ) ; } }
|
Factory to create and initialize the cache .
|
36,308
|
public synchronized void registerSerializer ( Serializer serializer ) { Class objClass = getSerializerType ( serializer ) ; if ( ! serializers . containsKey ( objClass ) ) { int index = COUNTER . getAndIncrement ( ) ; serializers . put ( objClass , new SerializerWrapper ( index , serializer ) ) ; if ( serializersArray . length <= index ) { serializersArray = Arrays . copyOf ( serializersArray , index + 1 ) ; } serializersArray [ index ] = serializer ; LOGGER . info ( String . format ( "Registered new serializer '%s' %n for '%s' at index %d" , serializer . getClass ( ) . getName ( ) , objClass . getName ( ) , index ) ) ; } }
|
Registers the serializer .
|
36,309
|
static void serialize ( DataOutput out , Serializers serializers ) throws IOException { StringBuilder msg = new StringBuilder ( String . format ( "Serialize %d serializer classes:" , serializers . serializers . values ( ) . size ( ) ) ) ; int size = serializers . serializers . values ( ) . size ( ) ; out . writeInt ( size ) ; if ( size > 0 ) { for ( SerializerWrapper sw : serializers . serializers . values ( ) ) { int index = sw . index ; String name = sw . serializer . getClass ( ) . getName ( ) ; out . writeInt ( index ) ; out . writeUTF ( name ) ; msg . append ( String . format ( "%n (%d) %s" , index , name ) ) ; } LOGGER . info ( msg . toString ( ) ) ; } }
|
Serializes this class into a data output .
|
36,310
|
private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { COUNTER = new AtomicInteger ( ) ; serializers = new HashMap < Class , SerializerWrapper > ( ) ; serializersArray = new Serializer [ 0 ] ; deserialize ( in , this ) ; }
|
Deserializes this instance from an input stream .
|
36,311
|
static void deserialize ( DataInput in , Serializers serializers ) throws IOException , ClassNotFoundException { int size = in . readInt ( ) ; if ( size > 0 ) { StringBuilder msg = new StringBuilder ( String . format ( "Deserialize %d serializer classes:" , size ) ) ; if ( serializers . serializersArray . length < size ) { serializers . serializersArray = Arrays . copyOf ( serializers . serializersArray , size ) ; } int max = 0 ; for ( int i = 0 ; i < size ; i ++ ) { int index = in . readInt ( ) ; max = Math . max ( max , index ) ; String serializerClassName = in . readUTF ( ) ; try { Class < Serializer > serializerClass = ( Class < Serializer > ) Class . forName ( serializerClassName ) ; Serializer serializerInstance = serializerClass . newInstance ( ) ; serializers . serializers . put ( getSerializerType ( serializerInstance ) , new SerializerWrapper ( index , serializerInstance ) ) ; serializers . serializersArray [ index ] = serializerInstance ; msg . append ( String . format ( "%n (%d) %s" , index , serializerClassName ) ) ; } catch ( Exception ex ) { LOGGER . log ( Level . WARNING , ( String . format ( "Can't find the serializer '%s'" , serializerClassName ) ) , ex ) ; } } serializers . COUNTER . set ( max + 1 ) ; LOGGER . info ( msg . toString ( ) ) ; } }
|
Deserializes this class from a data input .
|
36,312
|
Serializer getSerializer ( int index ) { if ( index >= serializersArray . length ) { throw new IllegalArgumentException ( String . format ( "The serializer can't be found at index %d" , index ) ) ; } return serializersArray [ index ] ; }
|
Returns the serializer given the index .
|
36,313
|
private static Class < ? > getSerializerType ( Object instance ) { Type type = instance . getClass ( ) . getGenericInterfaces ( ) [ 0 ] ; if ( type instanceof ParameterizedType ) { Class < ? > cls = null ; Type clsType = ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ 0 ] ; if ( clsType instanceof GenericArrayType ) { cls = Array . newInstance ( ( Class ) ( ( GenericArrayType ) clsType ) . getGenericComponentType ( ) , 0 ) . getClass ( ) ; } else { cls = ( Class < ? > ) clsType ; } if ( Object . class . equals ( cls ) ) { throw new RuntimeException ( "The serializer type can't be object" ) ; } return cls ; } else { throw new RuntimeException ( String . format ( "The serializer class %s is not generic or has an unknown type" , instance . getClass ( ) . getName ( ) ) ) ; } }
|
Returns the serializer s generic type .
|
36,314
|
public byte [ ] get ( byte [ ] key ) throws IOException { int keyLength = key . length ; if ( keyLength >= slots . length || keyCounts [ keyLength ] == 0 ) { return null ; } long hash = ( long ) hashUtils . hash ( key ) ; int numSlots = slots [ keyLength ] ; int slotSize = slotSizes [ keyLength ] ; int indexOffset = indexOffsets [ keyLength ] ; long dataOffset = dataOffsets [ keyLength ] ; for ( int probe = 0 ; probe < numSlots ; probe ++ ) { int slot = ( int ) ( ( hash + probe ) % numSlots ) ; indexBuffer . position ( indexOffset + slot * slotSize ) ; indexBuffer . get ( slotBuffer , 0 , slotSize ) ; long offset = LongPacker . unpackLong ( slotBuffer , keyLength ) ; if ( offset == 0 ) { return null ; } if ( isKey ( slotBuffer , key ) ) { byte [ ] value = mMapData ? getMMapBytes ( dataOffset + offset ) : getDiskBytes ( dataOffset + offset ) ; return value ; } } return null ; }
|
Get the value for the given key or null
|
36,315
|
public void close ( ) throws IOException { channel . close ( ) ; mappedFile . close ( ) ; indexBuffer = null ; dataBuffers = null ; mappedFile = null ; channel = null ; System . gc ( ) ; }
|
Close the reader channel
|
36,316
|
private byte [ ] getMMapBytes ( long offset ) throws IOException { ByteBuffer buf = getDataBuffer ( offset ) ; int maxLen = ( int ) Math . min ( 5 , dataSize - offset ) ; int size ; if ( buf . remaining ( ) >= maxLen ) { int pos = buf . position ( ) ; size = LongPacker . unpackInt ( buf ) ; offset += buf . position ( ) - pos ; } else { int len = maxLen ; int off = 0 ; sizeBuffer . reset ( ) ; while ( len > 0 ) { buf = getDataBuffer ( offset + off ) ; int count = Math . min ( len , buf . remaining ( ) ) ; buf . get ( sizeBuffer . getBuf ( ) , off , count ) ; off += count ; len -= count ; } size = LongPacker . unpackInt ( sizeBuffer ) ; offset += sizeBuffer . getPos ( ) ; buf = getDataBuffer ( offset ) ; } byte [ ] res = new byte [ size ] ; if ( buf . remaining ( ) >= size ) { buf . get ( res , 0 , size ) ; } else { int len = size ; int off = 0 ; while ( len > 0 ) { buf = getDataBuffer ( offset ) ; int count = Math . min ( len , buf . remaining ( ) ) ; buf . get ( res , off , count ) ; offset += count ; off += count ; len -= count ; } } return res ; }
|
Read the data at the given offset the data can be spread over multiple data buffers
|
36,317
|
private byte [ ] getDiskBytes ( long offset ) throws IOException { mappedFile . seek ( dataOffset + offset ) ; int size = LongPacker . unpackInt ( mappedFile ) ; byte [ ] res = new byte [ size ] ; if ( mappedFile . read ( res ) == - 1 ) { throw new EOFException ( ) ; } return res ; }
|
Get data from disk
|
36,318
|
private ByteBuffer getDataBuffer ( long index ) { ByteBuffer buf = dataBuffers [ ( int ) ( index / segmentSize ) ] ; buf . position ( ( int ) ( index % segmentSize ) ) ; return buf ; }
|
Return the data buffer for the given position
|
36,319
|
private void ensureAvail ( int n ) { if ( pos + n >= buf . length ) { int newSize = Math . max ( pos + n , buf . length * 2 ) ; buf = Arrays . copyOf ( buf , newSize ) ; } }
|
make sure there will be enought space in buffer to write N bytes
|
36,320
|
static public int unpackInt ( DataInput is ) throws IOException { for ( int offset = 0 , result = 0 ; offset < 32 ; offset += 7 ) { int b = is . readUnsignedByte ( ) ; result |= ( b & 0x7F ) << offset ; if ( ( b & 0x80 ) == 0 ) { return result ; } } throw new Error ( "Malformed integer." ) ; }
|
Unpack positive int value from the input stream .
|
36,321
|
static public int unpackInt ( ByteBuffer bb ) throws IOException { for ( int offset = 0 , result = 0 ; offset < 32 ; offset += 7 ) { int b = bb . get ( ) & 0xffff ; result |= ( b & 0x7F ) << offset ; if ( ( b & 0x80 ) == 0 ) { return result ; } } throw new Error ( "Malformed integer." ) ; }
|
Unpack positive int value from the input byte buffer .
|
36,322
|
private void mergeFiles ( List < File > inputFiles , OutputStream outputStream ) throws IOException { long startTime = System . nanoTime ( ) ; for ( File f : inputFiles ) { if ( f . exists ( ) ) { FileInputStream fileInputStream = new FileInputStream ( f ) ; BufferedInputStream bufferedInputStream = new BufferedInputStream ( fileInputStream ) ; try { LOGGER . log ( Level . INFO , "Merging {0} size={1}" , new Object [ ] { f . getName ( ) , f . length ( ) } ) ; byte [ ] buffer = new byte [ 8192 ] ; int length ; while ( ( length = bufferedInputStream . read ( buffer ) ) > 0 ) { outputStream . write ( buffer , 0 , length ) ; } } finally { bufferedInputStream . close ( ) ; fileInputStream . close ( ) ; } } else { LOGGER . log ( Level . INFO , "Skip merging file {0} because it doesn't exist" , f . getName ( ) ) ; } } LOGGER . log ( Level . INFO , "Time to merge {0} s" , ( ( System . nanoTime ( ) - startTime ) / 1000000000.0 ) ) ; }
|
Merge files to the provided fileChannel
|
36,323
|
private DataOutputStream getDataStream ( int keyLength ) throws IOException { if ( dataStreams . length <= keyLength ) { dataStreams = Arrays . copyOf ( dataStreams , keyLength + 1 ) ; dataFiles = Arrays . copyOf ( dataFiles , keyLength + 1 ) ; } DataOutputStream dos = dataStreams [ keyLength ] ; if ( dos == null ) { File file = new File ( tempFolder , "data" + keyLength + ".dat" ) ; file . deleteOnExit ( ) ; dataFiles [ keyLength ] = file ; dos = new DataOutputStream ( new BufferedOutputStream ( new FileOutputStream ( file ) ) ) ; dataStreams [ keyLength ] = dos ; dos . writeByte ( 0 ) ; } return dos ; }
|
Get the data stream for the specified keyLength create it if needed
|
36,324
|
private DataOutputStream getIndexStream ( int keyLength ) throws IOException { if ( indexStreams . length <= keyLength ) { indexStreams = Arrays . copyOf ( indexStreams , keyLength + 1 ) ; indexFiles = Arrays . copyOf ( indexFiles , keyLength + 1 ) ; keyCounts = Arrays . copyOf ( keyCounts , keyLength + 1 ) ; maxOffsetLengths = Arrays . copyOf ( maxOffsetLengths , keyLength + 1 ) ; lastValues = Arrays . copyOf ( lastValues , keyLength + 1 ) ; lastValuesLength = Arrays . copyOf ( lastValuesLength , keyLength + 1 ) ; dataLengths = Arrays . copyOf ( dataLengths , keyLength + 1 ) ; } DataOutputStream dos = indexStreams [ keyLength ] ; if ( dos == null ) { File file = new File ( tempFolder , "temp_index" + keyLength + ".dat" ) ; file . deleteOnExit ( ) ; indexFiles [ keyLength ] = file ; dos = new DataOutputStream ( new BufferedOutputStream ( new FileOutputStream ( file ) ) ) ; indexStreams [ keyLength ] = dos ; dataLengths [ keyLength ] ++ ; } return dos ; }
|
Get the index stream for the specified keyLength create it if needed
|
36,325
|
static int execute ( Arg arguments , PrintStream stream , PrintStream errorStream ) { if ( arguments == null ) { return 2 ; } if ( arguments . checkBcryptHash != null ) { BCrypt . Result result = BCrypt . verifyer ( ) . verify ( arguments . password , arguments . checkBcryptHash ) ; if ( ! result . validFormat ) { System . err . println ( "Invalid bcrypt format." ) ; return 3 ; } if ( result . verified ) { stream . println ( "Hash verified." ) ; } else { errorStream . println ( "Provided hash does not verify against given password." ) ; return 1 ; } } else { byte [ ] salt = arguments . salt == null ? Bytes . random ( 16 ) . array ( ) : arguments . salt ; byte [ ] hash = BCrypt . withDefaults ( ) . hash ( arguments . costFactor , salt , charArrayToByteArray ( arguments . password , StandardCharsets . UTF_8 ) ) ; stream . println ( new String ( hash , StandardCharsets . UTF_8 ) ) ; } return 0 ; }
|
Execute the given arguments and executes the appropriate actions
|
36,326
|
public static Hasher with ( Version version , SecureRandom secureRandom , LongPasswordStrategy longPasswordStrategy ) { return new Hasher ( version , secureRandom , longPasswordStrategy ) ; }
|
Create a new instance with custom version secureRandom and long password strategy
|
36,327
|
private static int streamToWord ( byte [ ] data , int [ ] offp ) { int i ; int word = 0 ; int off = offp [ 0 ] ; for ( i = 0 ; i < 4 ; i ++ ) { word = ( word << 8 ) | ( data [ off ] & 0xff ) ; off = ( off + 1 ) % data . length ; } offp [ 0 ] = off ; return word ; }
|
Cyclically extract a word of key material
|
36,328
|
private void encipher ( int [ ] P , int [ ] S , int [ ] lr , int off ) { int i , n , l = lr [ off ] , r = lr [ off + 1 ] ; l ^= P [ 0 ] ; for ( i = 0 ; i <= BLOWFISH_NUM_ROUNDS - 2 ; ) { n = S [ ( l >> 24 ) & 0xff ] ; n += S [ 0x100 | ( ( l >> 16 ) & 0xff ) ] ; n ^= S [ 0x200 | ( ( l >> 8 ) & 0xff ) ] ; n += S [ 0x300 | ( l & 0xff ) ] ; r ^= n ^ P [ ++ i ] ; n = S [ ( r >> 24 ) & 0xff ] ; n += S [ 0x100 | ( ( r >> 16 ) & 0xff ) ] ; n ^= S [ 0x200 | ( ( r >> 8 ) & 0xff ) ] ; n += S [ 0x300 | ( r & 0xff ) ] ; l ^= n ^ P [ ++ i ] ; } lr [ off ] = r ^ P [ BLOWFISH_NUM_ROUNDS + 1 ] ; lr [ off + 1 ] = l ; }
|
Blowfish encipher a single 64 - bit block encoded as two 32 - bit halves
|
36,329
|
protected void expand ( int min_size_needed ) { LogEntry [ ] new_entries = new LogEntry [ Math . max ( entries . length + INCR , entries . length + min_size_needed ) ] ; System . arraycopy ( entries , 0 , new_entries , 0 , entries . length ) ; entries = new_entries ; }
|
Lock must be held to call this method
|
36,330
|
public V remove ( K key ) throws Exception { return invoke ( REMOVE , key , null , true ) ; }
|
Removes a key - value pair from the state machine . The data is not removed directly from the hashmap but an update is sent via RAFT and the actual removal from the hashmap is only done when that change has been committed .
|
36,331
|
public void printMetadata ( ) throws Exception { log . info ( "-----------------" ) ; log . info ( "RAFT Log Metadata" ) ; log . info ( "-----------------" ) ; byte [ ] firstAppendedBytes = db . get ( FIRSTAPPENDED ) ; log . info ( "First Appended: %d" , fromByteArrayToInt ( firstAppendedBytes ) ) ; byte [ ] lastAppendedBytes = db . get ( LASTAPPENDED ) ; log . info ( "Last Appended: %d" , fromByteArrayToInt ( lastAppendedBytes ) ) ; byte [ ] currentTermBytes = db . get ( CURRENTTERM ) ; log . info ( "Current Term: %d" , fromByteArrayToInt ( currentTermBytes ) ) ; byte [ ] commitIndexBytes = db . get ( COMMITINDEX ) ; log . info ( "Commit Index: %d" , fromByteArrayToInt ( commitIndexBytes ) ) ; Address votedForTmp = Util . objectFromByteBuffer ( db . get ( VOTEDFOR ) ) ; log . info ( "Voted for: %s" , votedForTmp ) ; }
|
Useful in debugging
|
36,332
|
public Counter getOrCreateCounter ( String name , long initial_value ) throws Exception { Object existing_value = allow_dirty_reads ? _get ( name ) : invoke ( Command . get , name , false ) ; if ( existing_value != null ) counters . put ( name , ( Long ) existing_value ) ; else { Object retval = invoke ( Command . create , name , false , initial_value ) ; if ( retval instanceof Long ) counters . put ( name , ( Long ) retval ) ; } return new CounterImpl ( name , this ) ; }
|
Returns an existing counter or creates a new one if none exists
|
36,333
|
protected int getFirstIndexOfConflictingTerm ( int start_index , int conflicting_term ) { Log log = raft . log_impl ; int first = Math . max ( 1 , log . firstAppended ( ) ) , last = log . lastAppended ( ) ; int retval = Math . min ( start_index , last ) ; for ( int i = retval ; i >= first ; i -- ) { LogEntry entry = log . get ( i ) ; if ( entry == null || entry . term != conflicting_term ) break ; retval = i ; } return retval ; }
|
Finds the first index at which conflicting_term starts going back from start_index towards the head of the log
|
36,334
|
public static boolean isNumber ( JsonNode node , boolean isTypeLoose ) { if ( node . isNumber ( ) ) { return true ; } else if ( isTypeLoose ) { if ( TypeFactory . getValueNodeType ( node ) == JsonType . STRING ) { return isNumeric ( node . textValue ( ) ) ; } } return false ; }
|
Check if the type of the JsonNode s value is number based on the status of typeLoose flag .
|
36,335
|
private boolean isTypeLooseContainsInEnum ( JsonNode node ) { if ( TypeFactory . getValueNodeType ( node ) == JsonType . STRING ) { String nodeText = node . textValue ( ) ; for ( JsonNode n : nodes ) { String value = n . asText ( ) ; if ( value != null && value . equals ( nodeText ) ) { return true ; } } } return false ; }
|
Check whether enum contains the value of the JsonNode if the typeLoose is enabled .
|
36,336
|
public Writer sheet ( String sheetName ) { if ( StringUtil . isEmpty ( sheetName ) ) { throw new IllegalArgumentException ( "sheet cannot be empty" ) ; } this . sheetName = sheetName ; return this ; }
|
Configure the name of the sheet to be written . The default is Sheet0 .
|
36,337
|
public Writer withTemplate ( File template ) { if ( null == template || ! template . exists ( ) ) { throw new IllegalArgumentException ( "template file not exist" ) ; } this . template = template ; return this ; }
|
Specify to write an Excel table from a template file
|
36,338
|
public void to ( File file ) throws WriterException { try { this . to ( new FileOutputStream ( file ) ) ; } catch ( FileNotFoundException e ) { throw new WriterException ( e ) ; } }
|
Write an Excel document to a file
|
36,339
|
public void to ( OutputStream outputStream ) throws WriterException { if ( ! withRaw && ( null == rows || rows . isEmpty ( ) ) ) { throw new WriterException ( "write rows cannot be empty, please check it" ) ; } if ( excelType == ExcelType . XLSX ) { new WriterWith2007 ( outputStream ) . writeSheet ( this ) ; } if ( excelType == ExcelType . XLS ) { new WriterWith2003 ( outputStream ) . writeSheet ( this ) ; } if ( excelType == ExcelType . CSV ) { new WriterWithCSV ( outputStream ) . writeSheet ( this ) ; } }
|
Write an Excel document to the output stream
|
36,340
|
public Reader < T > from ( File fromFile ) { if ( null == fromFile || ! fromFile . exists ( ) ) { throw new IllegalArgumentException ( "excel file must be exist" ) ; } this . fromFile = fromFile ; return this ; }
|
Read row data from an Excel file
|
36,341
|
public Reader < T > sheet ( String sheetName ) { if ( StringUtil . isEmpty ( sheetName ) ) { throw new IllegalArgumentException ( "sheet cannot be empty" ) ; } this . sheetName = sheetName ; return this ; }
|
Set the name of the sheet to be read . If you set the name sheet will be invalid .
|
36,342
|
public Stream < T > asStream ( ) { if ( modelType == null ) { throw new IllegalArgumentException ( "modelType can be not null" ) ; } if ( fromFile == null && fromStream == null ) { throw new IllegalArgumentException ( "Excel source not is null" ) ; } if ( fromFile != null ) { return ReaderFactory . readByFile ( this ) ; } else { return ReaderFactory . readByStream ( this ) ; } }
|
Return the read result as a Stream
|
36,343
|
public List < T > asList ( ) throws ReaderException { Stream < T > stream = this . asStream ( ) ; return stream . collect ( toList ( ) ) ; }
|
Convert the read result to a List
|
36,344
|
private static void applyTypeface ( ViewGroup viewGroup , TypefaceCollection typefaceCollection ) { for ( int i = 0 ; i < viewGroup . getChildCount ( ) ; i ++ ) { View childView = viewGroup . getChildAt ( i ) ; if ( childView instanceof ViewGroup ) { applyTypeface ( ( ViewGroup ) childView , typefaceCollection ) ; } else { applyForView ( childView , typefaceCollection ) ; } } }
|
Apply typeface to all ViewGroup childs
|
36,345
|
private static void applyForView ( View view , TypefaceCollection typefaceCollection ) { if ( view instanceof TextView ) { TextView textView = ( TextView ) view ; Typeface oldTypeface = textView . getTypeface ( ) ; final int style = oldTypeface == null ? Typeface . NORMAL : oldTypeface . getStyle ( ) ; textView . setTypeface ( typefaceCollection . getTypeface ( style ) ) ; textView . setPaintFlags ( textView . getPaintFlags ( ) | Paint . SUBPIXEL_TEXT_FLAG ) ; } }
|
Apply typeface to single view
|
36,346
|
public PermissionProfile createPermissionProfile ( String accountId , PermissionProfile permissionProfile ) throws ApiException { return createPermissionProfile ( accountId , permissionProfile , null ) ; }
|
Creates a new permission profile in the specified account .
|
36,347
|
public Brand getBrand ( String accountId , String brandId ) throws ApiException { return getBrand ( accountId , brandId , null ) ; }
|
Get information for a specific brand .
|
36,348
|
public PermissionProfile getPermissionProfile ( String accountId , String permissionProfileId ) throws ApiException { return getPermissionProfile ( accountId , permissionProfileId , null ) ; }
|
Returns a permissions profile in the specified account .
|
36,349
|
public ConsumerDisclosure updateConsumerDisclosure ( String accountId , String langCode , ConsumerDisclosure consumerDisclosure ) throws ApiException { return updateConsumerDisclosure ( accountId , langCode , consumerDisclosure , null ) ; }
|
Update Consumer Disclosure .
|
36,350
|
public CustomFields updateCustomField ( String accountId , String customFieldId , CustomField customField ) throws ApiException { return updateCustomField ( accountId , customFieldId , customField , null ) ; }
|
Updates an existing account custom field .
|
36,351
|
public PermissionProfile updatePermissionProfile ( String accountId , String permissionProfileId , PermissionProfile permissionProfile ) throws ApiException { return updatePermissionProfile ( accountId , permissionProfileId , permissionProfile , null ) ; }
|
Updates a permission profile within the specified account .
|
36,352
|
public CloudStorageProviders getProvider ( String accountId , String userId , String serviceId ) throws ApiException { return getProvider ( accountId , userId , serviceId , null ) ; }
|
Gets the specified Cloud Storage Provider configuration for the User . Retrieves the list of cloud storage providers enabled for the account and the configuration information for the user .
|
36,353
|
public ExternalFolder listFolders ( String accountId , String userId , String serviceId ) throws ApiException { return listFolders ( accountId , userId , serviceId , null ) ; }
|
Retrieves a list of all the items in a specified folder from the specified cloud storage provider . Retrieves a list of all the items in a specified folder from the specified cloud storage provider .
|
36,354
|
public BulkEnvelopeStatus get ( String accountId , String batchId ) throws ApiException { return get ( accountId , batchId , null ) ; }
|
Gets the status of a specified bulk send operation . Retrieves the status information of a single bulk recipient batch . A bulk recipient batch is the set of envelopes sent from a single bulk recipient file .
|
36,355
|
public BulkRecipientsResponse getRecipients ( String accountId , String envelopeId , String recipientId ) throws ApiException { return getRecipients ( accountId , envelopeId , recipientId , null ) ; }
|
Gets the bulk recipient file from an envelope . Retrieves the bulk recipient file information from an envelope that has a bulk recipient .
|
36,356
|
public ChunkedUploadResponse getChunkedUpload ( String accountId , String chunkedUploadId ) throws ApiException { return getChunkedUpload ( accountId , chunkedUploadId , null ) ; }
|
Retrieves the current metadata of a ChunkedUpload .
|
36,357
|
public ConsumerDisclosure getConsumerDisclosureDefault ( String accountId , String envelopeId , String recipientId ) throws ApiException { return getConsumerDisclosureDefault ( accountId , envelopeId , recipientId , null ) ; }
|
Gets the Electronic Record and Signature Disclosure associated with the account . Retrieves the Electronic Record and Signature Disclosure with html formatting associated with the account . You can use an optional query string to set the language for the disclosure .
|
36,358
|
public byte [ ] getDocumentPageImage ( String accountId , String envelopeId , String documentId , String pageNumber ) throws ApiException { return getDocumentPageImage ( accountId , envelopeId , documentId , pageNumber , null ) ; }
|
Gets a page image from an envelope for display . Retrieves a page image for display from the specified envelope .
|
36,359
|
public Envelope getEnvelope ( String accountId , String envelopeId ) throws ApiException { return getEnvelope ( accountId , envelopeId , null ) ; }
|
Gets the status of a envelope . Retrieves the overall status for the specified envelope .
|
36,360
|
public Tabs listTabs ( String accountId , String envelopeId , String recipientId ) throws ApiException { return listTabs ( accountId , envelopeId , recipientId , null ) ; }
|
Gets the tabs information for a signer or sign - in - person recipient in an envelope . Retrieves information about the tabs associated with a recipient in a draft envelope .
|
36,361
|
public TemplateInformation listTemplates ( String accountId , String envelopeId ) throws ApiException { return listTemplates ( accountId , envelopeId , null ) ; }
|
Get List of Templates used in an Envelope This returns a list of the server - side templates their name and ID used in an envelope .
|
36,362
|
public TemplateInformation listTemplatesForDocument ( String accountId , String envelopeId , String documentId ) throws ApiException { return listTemplatesForDocument ( accountId , envelopeId , documentId , null ) ; }
|
Gets the templates associated with a document in an existing envelope . Retrieves the templates associated with a document in the specified envelope .
|
36,363
|
public ChunkedUploadResponse updateChunkedUpload ( String accountId , String chunkedUploadId ) throws ApiException { return updateChunkedUpload ( accountId , chunkedUploadId , null ) ; }
|
Integrity - Check and Commit a ChunkedUpload readying it for use elsewhere .
|
36,364
|
public byte [ ] getCommentsTranscript ( String accountId , String envelopeId ) throws ApiException { return getCommentsTranscript ( accountId , envelopeId , null ) ; }
|
Gets comment transcript for envelope and user
|
36,365
|
public void registerAccessTokenListener ( AccessTokenListener accessTokenListener ) { for ( Authentication auth : authentications . values ( ) ) { if ( auth instanceof OAuth ) { OAuth oauth = ( OAuth ) auth ; oauth . registerAccessTokenListener ( accessTokenListener ) ; return ; } } }
|
Configures a listener which is notified when a new access token is received .
|
36,366
|
private String getXWWWFormUrlencodedParams ( Map < String , Object > formParams ) { StringBuilder formParamBuilder = new StringBuilder ( ) ; for ( Entry < String , Object > param : formParams . entrySet ( ) ) { String valueStr = parameterToString ( param . getValue ( ) ) ; try { formParamBuilder . append ( URLEncoder . encode ( param . getKey ( ) , "utf8" ) ) . append ( "=" ) . append ( URLEncoder . encode ( valueStr , "utf8" ) ) ; formParamBuilder . append ( "&" ) ; } catch ( UnsupportedEncodingException e ) { } } String encodedFormParams = formParamBuilder . toString ( ) ; if ( encodedFormParams . endsWith ( "&" ) ) { encodedFormParams = encodedFormParams . substring ( 0 , encodedFormParams . length ( ) - 1 ) ; } return encodedFormParams ; }
|
Encode the given form parameters as request body .
|
36,367
|
private < T > String serializeToCsv ( T obj ) { if ( obj == null ) { return "" ; } for ( Method method : obj . getClass ( ) . getMethods ( ) ) { if ( "java.util.List" . equals ( method . getReturnType ( ) . getName ( ) ) ) { try { @ SuppressWarnings ( "rawtypes" ) java . util . List itemList = ( java . util . List ) method . invoke ( obj ) ; Object entry = itemList . get ( 0 ) ; List < String > stringList = new ArrayList < String > ( ) ; char delimiter = ',' ; String lineSep = "\n" ; CsvMapper mapper = new CsvMapper ( ) ; mapper . enable ( JsonGenerator . Feature . IGNORE_UNKNOWN ) ; CsvSchema schema = mapper . schemaFor ( entry . getClass ( ) ) ; for ( int i = 0 ; i < itemList . size ( ) ; i ++ ) { if ( i == 0 ) { schema = schema . withHeader ( ) ; } else { schema = schema . withoutHeader ( ) ; } String csv = mapper . writer ( schema . withColumnSeparator ( delimiter ) . withoutQuoteChar ( ) . withLineSeparator ( lineSep ) ) . writeValueAsString ( itemList . get ( i ) ) ; stringList . add ( csv ) ; } return StringUtil . join ( stringList . toArray ( new String [ 0 ] ) , "" ) ; } catch ( JsonProcessingException e ) { System . out . println ( e ) ; } catch ( IllegalAccessException e ) { System . out . println ( e ) ; } catch ( IllegalArgumentException e ) { System . out . println ( e ) ; } catch ( InvocationTargetException e ) { System . out . println ( e ) ; } } } return "" ; }
|
Encode the given request object in CSV format .
|
36,368
|
public Recipients createRecipients ( String accountId , String templateId , TemplateRecipients templateRecipients ) throws ApiException { return createRecipients ( accountId , templateId , templateRecipients , null ) ; }
|
Adds tabs for a recipient . Adds one or more recipients to a template .
|
36,369
|
public EnvelopeTemplate get ( String accountId , String templateId ) throws ApiException { return get ( accountId , templateId , null ) ; }
|
Gets a list of templates for a specified account . Retrieves the definition of the specified template .
|
36,370
|
public byte [ ] getDocumentPageImage ( String accountId , String templateId , String documentId , String pageNumber ) throws ApiException { return getDocumentPageImage ( accountId , templateId , documentId , pageNumber , null ) ; }
|
Gets a page image from a template for display . Retrieves a page image for display from the specified template .
|
36,371
|
public Recipients listRecipients ( String accountId , String templateId ) throws ApiException { return listRecipients ( accountId , templateId , null ) ; }
|
Gets recipient information from a template . Retrieves the information for all recipients in the specified template .
|
36,372
|
public Tabs listTabs ( String accountId , String templateId , String recipientId ) throws ApiException { return listTabs ( accountId , templateId , recipientId , null ) ; }
|
Gets the tabs information for a signer or sign - in - person recipient in a template . Gets the tabs information for a signer or sign - in - person recipient in a template .
|
36,373
|
public EnvelopeDocument updateDocument ( String accountId , String templateId , String documentId , EnvelopeDefinition envelopeDefinition ) throws ApiException { return updateDocument ( accountId , templateId , documentId , envelopeDefinition , null ) ; }
|
Adds a document to a template document . Adds the specified document to an existing template document .
|
36,374
|
public TemplateDocumentsResult updateDocuments ( String accountId , String templateId , EnvelopeDefinition envelopeDefinition ) throws ApiException { return updateDocuments ( accountId , templateId , envelopeDefinition , null ) ; }
|
Adds documents to a template document . Adds one or more documents to an existing template document .
|
36,375
|
public NotaryJournalList listNotaryJournals ( NotaryApi . ListNotaryJournalsOptions options ) throws ApiException { Object localVarPostBody = "{}" ; String localVarPath = "/v2/current_user/notary/journals" . replaceAll ( "\\{format\\}" , "json" ) ; java . util . List < Pair > localVarQueryParams = new java . util . ArrayList < Pair > ( ) ; java . util . Map < String , String > localVarHeaderParams = new java . util . HashMap < String , String > ( ) ; java . util . Map < String , Object > localVarFormParams = new java . util . HashMap < String , Object > ( ) ; if ( options != null ) { localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "count" , options . count ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "search_text" , options . searchText ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "start_position" , options . startPosition ) ) ; } final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { "docusignAccessCode" } ; GenericType < NotaryJournalList > localVarReturnType = new GenericType < NotaryJournalList > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "GET" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }
|
Get notary jurisdictions for a user
|
36,376
|
public static String calculatePath ( String uri ) { if ( ! uri . startsWith ( "/" ) ) { return "/" ; } int idx = uri . lastIndexOf ( '/' ) ; return uri . substring ( 0 , idx + 1 ) ; }
|
Get cookie default path from url path
|
36,377
|
public static boolean isDomainSuffix ( String domain , String domainSuffix ) { if ( domain . length ( ) < domainSuffix . length ( ) ) { return false ; } if ( domain . length ( ) == domainSuffix . length ( ) ) { return domain . equals ( domainSuffix ) ; } return domain . endsWith ( domainSuffix ) && domain . charAt ( domain . length ( ) - domainSuffix . length ( ) - 1 ) == '.' ; }
|
If domainSuffix is suffix of domain
|
36,378
|
public static boolean match ( Cookie cookie , String protocol , String host , String path ) { if ( cookie . secure ( ) && ! protocol . equalsIgnoreCase ( "https" ) ) { return false ; } if ( isIP ( host ) || cookie . hostOnly ( ) ) { if ( ! host . equals ( cookie . domain ( ) ) ) { return false ; } } else { if ( ! Cookies . isDomainSuffix ( host , cookie . domain ( ) ) ) { return false ; } } String cookiePath = cookie . path ( ) ; if ( cookiePath . length ( ) > path . length ( ) ) { return false ; } if ( cookiePath . length ( ) == path . length ( ) ) { return cookiePath . equals ( path ) ; } if ( ! path . startsWith ( cookiePath ) ) { return false ; } if ( cookiePath . charAt ( cookiePath . length ( ) - 1 ) != '/' && path . charAt ( cookiePath . length ( ) ) != '/' ) { return false ; } return true ; }
|
If cookie match the given scheme host and path .
|
36,379
|
public static Cookie parseCookie ( String cookieStr , String host , String defaultPath ) { String [ ] items = cookieStr . split ( ";" ) ; Parameter < String > param = parseCookieNameValue ( items [ 0 ] ) ; if ( param == null ) { return null ; } String domain = "" ; String path = "" ; long expiry = 0 ; boolean secure = false ; for ( String item : items ) { item = item . trim ( ) ; if ( item . isEmpty ( ) ) { continue ; } Parameter < String > attribute = parseCookieAttribute ( item ) ; switch ( attribute . name ( ) . toLowerCase ( ) ) { case "domain" : domain = normalizeDomain ( attribute . value ( ) ) ; break ; case "path" : path = normalizePath ( attribute . value ( ) ) ; break ; case "expires" : if ( expiry == 0 ) { Date date = CookieDateUtil . parseDate ( attribute . value ( ) ) ; if ( date != null ) { expiry = date . getTime ( ) ; if ( expiry == 0 ) { expiry = 1 ; } } } break ; case "max-age" : try { int seconds = Integer . parseInt ( attribute . value ( ) ) ; expiry = System . currentTimeMillis ( ) + seconds * 1000 ; if ( expiry == 0 ) { expiry = 1 ; } } catch ( NumberFormatException ignore ) { } break ; case "secure" : secure = true ; break ; case "httponly" : break ; default : } } if ( path . isEmpty ( ) ) { path = defaultPath ; } boolean hostOnly ; if ( domain . isEmpty ( ) ) { domain = host ; hostOnly = true ; } else { if ( isIP ( host ) ) { return null ; } if ( ! isDomainSuffix ( host , domain ) ) { return null ; } hostOnly = false ; } return new Cookie ( domain , path , param . name ( ) , param . value ( ) , expiry , secure , hostOnly ) ; }
|
Parse one cookie header value return the cookie .
|
36,380
|
private static String normalizeDomain ( String value ) { if ( value . startsWith ( "." ) ) { return value . substring ( 1 ) ; } return value . toLowerCase ( ) ; }
|
Parse cookie domain . In RFC 6265 the leading dot will be ignored and cookie always available in sub domains .
|
36,381
|
public static Proxy httpProxy ( String host , int port ) { return new Proxy ( Proxy . Type . HTTP , new InetSocketAddress ( Objects . requireNonNull ( host ) , port ) ) ; }
|
Create http proxy
|
36,382
|
public static Proxy socksProxy ( String host , int port ) { return new Proxy ( Proxy . Type . SOCKS , new InetSocketAddress ( Objects . requireNonNull ( host ) , port ) ) ; }
|
Create socks5 proxy
|
36,383
|
public static RequestBuilder newRequest ( String method , String url ) { return new RequestBuilder ( ) . method ( method ) . url ( url ) ; }
|
Create new request with method and url
|
36,384
|
public final RequestBuilder headers ( Map . Entry < String , ? > ... headers ) { headers ( Lists . of ( headers ) ) ; return this ; }
|
Set request headers .
|
36,385
|
public final RequestBuilder cookies ( Map . Entry < String , ? > ... cookies ) { cookies ( Lists . of ( cookies ) ) ; return this ; }
|
Set request cookies .
|
36,386
|
public final RequestBuilder params ( Map . Entry < String , ? > ... params ) { this . params = Lists . of ( params ) ; return this ; }
|
Set url query params .
|
36,387
|
public RawResponse send ( ) { Request request = build ( ) ; RequestExecutorFactory factory = RequestExecutorFactory . getInstance ( ) ; HttpExecutor executor = factory . getHttpExecutor ( ) ; return new InterceptorChain ( interceptors , executor ) . proceed ( request ) ; }
|
build http request and send out
|
36,388
|
public Part < T > contentType ( String contentType ) { requireNonNull ( contentType ) ; return new Part < > ( name , fileName , body , contentType , charset , partWriter ) ; }
|
Set content type for this part .
|
36,389
|
public Part < T > charset ( Charset charset ) { requireNonNull ( charset ) ; return new Part < > ( name , fileName , body , contentType , charset , partWriter ) ; }
|
The charset of this part s content . Each part of MultiPart body can has it s own charset set . Default not set .
|
36,390
|
public static String encodeForm ( Parameter < String > query , Charset charset ) { try { return URLEncoder . encode ( query . name ( ) , charset . name ( ) ) + "=" + URLEncoder . encode ( query . value ( ) , charset . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RequestsException ( e ) ; } }
|
Encode key - value form parameter
|
36,391
|
public static String encodeForms ( Collection < ? extends Parameter < String > > queries , Charset charset ) { StringBuilder sb = new StringBuilder ( ) ; try { for ( Parameter < String > query : queries ) { sb . append ( URLEncoder . encode ( query . name ( ) , charset . name ( ) ) ) ; sb . append ( '=' ) ; sb . append ( URLEncoder . encode ( query . value ( ) , charset . name ( ) ) ) ; sb . append ( '&' ) ; } } catch ( UnsupportedEncodingException e ) { throw new RequestsException ( e ) ; } if ( sb . length ( ) > 0 ) { sb . deleteCharAt ( sb . length ( ) - 1 ) ; } return sb . toString ( ) ; }
|
Encode multi form parameters
|
36,392
|
public static Parameter < String > decodeForm ( String s , Charset charset ) { int idx = s . indexOf ( "=" ) ; try { if ( idx < 0 ) { return Parameter . of ( "" , URLDecoder . decode ( s , charset . name ( ) ) ) ; } return Parameter . of ( URLDecoder . decode ( s . substring ( 0 , idx ) , charset . name ( ) ) , URLDecoder . decode ( s . substring ( idx + 1 ) , charset . name ( ) ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RequestsException ( e ) ; } }
|
Decode key - value query parameter
|
36,393
|
public static List < Parameter < String > > decodeForms ( String queryStr , Charset charset ) { String [ ] queries = queryStr . split ( "&" ) ; List < Parameter < String > > list = new ArrayList < > ( queries . length ) ; for ( String query : queries ) { list . add ( decodeForm ( query , charset ) ) ; } return list ; }
|
Parse query params
|
36,394
|
public Cookie getCookie ( String name ) { for ( Cookie cookie : cookies ) { if ( cookie . name ( ) . equals ( name ) ) { return cookie ; } } return null ; }
|
Get first cookie match the name returned by this response return null if not found
|
36,395
|
private static void registerAllTypeFactories ( GsonBuilder gsonBuilder ) { ServiceLoader < TypeAdapterFactory > loader = ServiceLoader . load ( TypeAdapterFactory . class ) ; for ( TypeAdapterFactory typeFactory : loader ) { if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "Add gson type factory: " + typeFactory . getClass ( ) . getName ( ) ) ; } gsonBuilder . registerTypeAdapterFactory ( typeFactory ) ; } }
|
Find and register all gson type factory using spi
|
36,396
|
public static KeyStore load ( String path , char [ ] password ) { try { return load ( new FileInputStream ( path ) , password ) ; } catch ( FileNotFoundException e ) { throw new TrustManagerLoadFailedException ( e ) ; } }
|
Load keystore from file .
|
36,397
|
public static KeyStore load ( InputStream in , char [ ] password ) { try { KeyStore myTrustStore = KeyStore . getInstance ( KeyStore . getDefaultType ( ) ) ; myTrustStore . load ( in , password ) ; return myTrustStore ; } catch ( CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException e ) { throw new TrustManagerLoadFailedException ( e ) ; } finally { Closeables . closeQuietly ( in ) ; } }
|
Load keystore from InputStream close the stream after load succeed or failed .
|
36,398
|
private RawResponse getResponse ( URL url , HttpURLConnection conn , CookieJar cookieJar , String method ) throws IOException { int status = conn . getResponseCode ( ) ; String host = url . getHost ( ) . toLowerCase ( ) ; String statusLine = null ; List < Header > headerList = new ArrayList < > ( ) ; List < Cookie > cookies = new ArrayList < > ( ) ; int index = 0 ; while ( true ) { String key = conn . getHeaderFieldKey ( index ) ; String value = conn . getHeaderField ( index ) ; if ( value == null ) { break ; } index ++ ; if ( key == null ) { statusLine = value ; continue ; } headerList . add ( new Header ( key , value ) ) ; if ( key . equalsIgnoreCase ( NAME_SET_COOKIE ) ) { Cookie c = Cookies . parseCookie ( value , host , Cookies . calculatePath ( url . getPath ( ) ) ) ; if ( c != null ) { cookies . add ( c ) ; } } } Headers headers = new Headers ( headerList ) ; InputStream input ; try { input = conn . getInputStream ( ) ; } catch ( IOException e ) { input = conn . getErrorStream ( ) ; } if ( input == null ) { input = InputStreams . empty ( ) ; } cookieJar . storeCookies ( cookies ) ; return new RawResponse ( method , url . toExternalForm ( ) , status , statusLine == null ? "" : statusLine , cookies , headers , input , conn ) ; }
|
Wrap response deal with headers and cookies
|
36,399
|
public JsonProcessor lookup ( ) { JsonProcessor registeredJsonProcessor = this . registeredJsonProcessor ; if ( registeredJsonProcessor != null ) { return registeredJsonProcessor ; } if ( ! init ) { synchronized ( this ) { if ( ! init ) { lookedJsonProcessor = lookupInClasspath ( ) ; init = true ; } } } if ( lookedJsonProcessor != null ) { return lookedJsonProcessor ; } throw new JsonProcessorNotFoundException ( "Json Provider not found" ) ; }
|
Find one json provider .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.