idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
15,700 | @ SuppressWarnings ( "deprecation" ) public static boolean hasNewNetworkConfig ( final Configuration config ) { return config . contains ( TaskManagerOptions . NETWORK_BUFFERS_MEMORY_FRACTION ) || config . contains ( TaskManagerOptions . NETWORK_BUFFERS_MEMORY_MIN ) || config . contains ( TaskManagerOptions . NETWORK_B... | Returns whether the new network buffer memory configuration is present in the configuration object i . e . at least one new parameter is given or the old one is not present . |
15,701 | @ SuppressWarnings ( "deprecation" ) private static int calculateNumberOfNetworkBuffers ( Configuration configuration , long maxJvmHeapMemory ) { final int numberOfNetworkBuffers ; if ( ! hasNewNetworkConfig ( configuration ) ) { numberOfNetworkBuffers = configuration . getInteger ( TaskManagerOptions . NETWORK_NUM_BUF... | Calculates the number of network buffers based on configuration and jvm heap size . |
15,702 | public static int getPageSize ( Configuration configuration ) { final int pageSize = checkedDownCast ( MemorySize . parse ( configuration . getString ( TaskManagerOptions . MEMORY_SEGMENT_SIZE ) ) . getBytes ( ) ) ; ConfigurationParserUtils . checkConfigParameter ( pageSize >= MemoryManager . MIN_PAGE_SIZE , pageSize ,... | Parses the configuration to get the page size and validates the value . |
15,703 | public SplitDataProperties < T > splitsOrderedBy ( int [ ] orderFields , Order [ ] orders ) { if ( orderFields == null || orders == null ) { throw new InvalidProgramException ( "OrderFields or Orders may not be null." ) ; } else if ( orderFields . length == 0 ) { throw new InvalidProgramException ( "OrderFields may not... | Defines that the data within an input split is sorted on the fields defined by the field positions in the specified orders . All records of an input split must be emitted by the input format in the defined order . |
15,704 | public SplitDataProperties < T > splitsOrderedBy ( String orderFields , Order [ ] orders ) { if ( orderFields == null || orders == null ) { throw new InvalidProgramException ( "OrderFields or Orders may not be null." ) ; } String [ ] orderKeysA = orderFields . split ( ";" ) ; if ( orderKeysA . length == 0 ) { throw new... | Defines that the data within an input split is sorted on the fields defined by the field expressions in the specified orders . Multiple field expressions must be separated by the semicolon ; character . All records of an input split must be emitted by the input format in the defined order . |
15,705 | public static < T > T copy ( T from , Kryo kryo , TypeSerializer < T > serializer ) { try { return kryo . copy ( from ) ; } catch ( KryoException ke ) { try { byte [ ] byteArray = InstantiationUtil . serializeToByteArray ( serializer , from ) ; return InstantiationUtil . deserializeFromByteArray ( serializer , byteArra... | Tries to copy the given record from using the provided Kryo instance . If this fails then the record from is copied by serializing it into a byte buffer and deserializing it from there . |
15,706 | public void open ( InputSplit ignored ) throws IOException { this . session = cluster . connect ( ) ; this . resultSet = session . execute ( query ) ; } | Opens a Session and executes the query . |
15,707 | private void redistributeBuffers ( ) throws IOException { assert Thread . holdsLock ( factoryLock ) ; final int numAvailableMemorySegment = totalNumberOfMemorySegments - numTotalRequiredBuffers ; if ( numAvailableMemorySegment == 0 ) { for ( LocalBufferPool bufferPool : allBufferPools ) { bufferPool . setNumBuffers ( b... | Must be called from synchronized block |
15,708 | public void close ( ) throws IOException { Throwable ex = null ; synchronized ( this ) { if ( closed ) { return ; } closed = true ; if ( recordsOutFile != null ) { try { recordsOutFile . close ( ) ; recordsOutFile = null ; } catch ( Throwable t ) { LOG . error ( "Cannot close the large records spill file." , t ) ; ex =... | Closes all structures and deletes all temporary files . Even in the presence of failures this method will try and continue closing files and deleting temporary files . |
15,709 | private AggregateOperator < T > aggregate ( Aggregations agg , int field , String callLocationName ) { return new AggregateOperator < T > ( this , agg , field , callLocationName ) ; } | private helper that allows to set a different call location name |
15,710 | public ArrayList < MemorySegment > resetOverflowBuckets ( ) { this . numOverflowSegments = 0 ; this . nextOverflowBucket = 0 ; ArrayList < MemorySegment > result = new ArrayList < MemorySegment > ( this . overflowSegments . length ) ; for ( int i = 0 ; i < this . overflowSegments . length ; i ++ ) { if ( this . overflo... | resets overflow bucket counters and returns freed memory and should only be used for resizing |
15,711 | public final long appendRecord ( T record ) throws IOException { long pointer = this . writeView . getCurrentPointer ( ) ; try { this . serializer . serialize ( record , this . writeView ) ; this . recordCounter ++ ; return pointer ; } catch ( EOFException e ) { this . writeView . resetTo ( pointer ) ; throw e ; } } | Inserts the given object into the current buffer . This method returns a pointer that can be used to address the written record in this partition . |
15,712 | public void overwriteRecordAt ( long pointer , T record ) throws IOException { long tmpPointer = this . writeView . getCurrentPointer ( ) ; this . writeView . resetTo ( pointer ) ; this . serializer . serialize ( record , this . writeView ) ; this . writeView . resetTo ( tmpPointer ) ; } | UNSAFE!! overwrites record causes inconsistency or data loss for overwriting everything but records of the exact same size |
15,713 | public void allocateSegments ( int numberOfSegments ) { while ( getBlockCount ( ) < numberOfSegments ) { MemorySegment next = this . availableMemory . nextSegment ( ) ; if ( next != null ) { this . partitionPages . add ( next ) ; } else { return ; } } } | attempts to allocate specified number of segments and should only be used by compaction partition fails silently if not enough segments are available since next compaction could still succeed |
15,714 | public static BinaryInMemorySortBuffer createBuffer ( NormalizedKeyComputer normalizedKeyComputer , AbstractRowSerializer < BaseRow > inputSerializer , BinaryRowSerializer serializer , RecordComparator comparator , List < MemorySegment > memory ) throws IOException { checkArgument ( memory . size ( ) >= MIN_REQUIRED_BU... | Create a memory sorter in insert way . |
15,715 | public void serializeRecord ( T record ) throws IOException { if ( CHECKED ) { if ( dataBuffer . hasRemaining ( ) ) { throw new IllegalStateException ( "Pending serialization of previous record." ) ; } } serializationBuffer . clear ( ) ; lengthBuffer . clear ( ) ; record . write ( serializationBuffer ) ; int len = seri... | Serializes the complete record to an intermediate data serialization buffer . |
15,716 | public SerializationResult copyToBufferBuilder ( BufferBuilder targetBuffer ) { targetBuffer . append ( lengthBuffer ) ; targetBuffer . append ( dataBuffer ) ; targetBuffer . commit ( ) ; return getSerializationResult ( targetBuffer ) ; } | Copies an intermediate data serialization buffer into the target BufferBuilder . |
15,717 | private void enqueueAvailableReader ( final NetworkSequenceViewReader reader ) throws Exception { if ( reader . isRegisteredAsAvailable ( ) || ! reader . isAvailable ( ) ) { return ; } boolean triggerWrite = availableReaders . isEmpty ( ) ; registerAvailableReader ( reader ) ; if ( triggerWrite ) { writeAndFlushNextMes... | Try to enqueue the reader once receiving credit notification from the consumer or receiving non - empty reader notification from the producer . |
15,718 | public void invoke ( IN value ) { try { byte [ ] msg = schema . serialize ( value ) ; if ( publishOptions == null ) { channel . basicPublish ( "" , queueName , null , msg ) ; } else { boolean mandatory = publishOptions . computeMandatory ( value ) ; boolean immediate = publishOptions . computeImmediate ( value ) ; Prec... | Called when new data arrives to the sink and forwards it to RMQ . |
15,719 | public void setInputType ( TypeInformation < ? > type , ExecutionConfig executionConfig ) { if ( ! type . isTupleType ( ) ) { throw new InvalidProgramException ( "The " + ScalaCsvOutputFormat . class . getSimpleName ( ) + " can only be used to write tuple data sets." ) ; } } | The purpose of this method is solely to check whether the data type to be processed is in fact a tuple type . |
15,720 | public static < X > Pattern < X , X > begin ( final String name ) { return new Pattern < > ( name , null , ConsumingStrategy . STRICT , AfterMatchSkipStrategy . noSkip ( ) ) ; } | Starts a new pattern sequence . The provided name is the one of the initial pattern of the new sequence . Furthermore the base type of the event sequence is set . |
15,721 | public < S extends F > Pattern < T , S > subtype ( final Class < S > subtypeClass ) { Preconditions . checkNotNull ( subtypeClass , "The class cannot be null." ) ; if ( condition == null ) { this . condition = new SubtypeCondition < F > ( subtypeClass ) ; } else { this . condition = new RichAndCondition < > ( condition... | Applies a subtype constraint on the current pattern . This means that an event has to be of the given subtype in order to be matched . |
15,722 | public Pattern < T , F > until ( IterativeCondition < F > untilCondition ) { Preconditions . checkNotNull ( untilCondition , "The condition cannot be null" ) ; if ( this . untilCondition != null ) { throw new MalformedPatternException ( "Only one until condition can be applied." ) ; } if ( ! quantifier . hasProperty ( ... | Applies a stop condition for a looping state . It allows cleaning the underlying state . |
15,723 | public Pattern < T , F > within ( Time windowTime ) { if ( windowTime != null ) { this . windowTime = windowTime ; } return this ; } | Defines the maximum time interval in which a matching pattern has to be completed in order to be considered valid . This interval corresponds to the maximum time gap between first and the last event . |
15,724 | public Pattern < T , T > next ( final String name ) { return new Pattern < > ( name , this , ConsumingStrategy . STRICT , afterMatchSkipStrategy ) ; } | Appends a new pattern to the existing one . The new pattern enforces strict temporal contiguity . This means that the whole pattern sequence matches only if an event which matches this pattern directly follows the preceding matching event . Thus there cannot be any events in between two matching events . |
15,725 | public Pattern < T , T > notNext ( final String name ) { if ( quantifier . hasProperty ( Quantifier . QuantifierProperty . OPTIONAL ) ) { throw new UnsupportedOperationException ( "Specifying a pattern with an optional path to NOT condition is not supported yet. " + "You can simulate such pattern with two independent p... | Appends a new pattern to the existing one . The new pattern enforces that there is no event matching this pattern right after the preceding matched event . |
15,726 | public Pattern < T , T > notFollowedBy ( final String name ) { if ( quantifier . hasProperty ( Quantifier . QuantifierProperty . OPTIONAL ) ) { throw new UnsupportedOperationException ( "Specifying a pattern with an optional path to NOT condition is not supported yet. " + "You can simulate such pattern with two indepen... | Appends a new pattern to the existing one . The new pattern enforces that there is no event matching this pattern between the preceding pattern and succeeding this one . |
15,727 | public Pattern < T , F > times ( int times ) { checkIfNoNotPattern ( ) ; checkIfQuantifierApplied ( ) ; Preconditions . checkArgument ( times > 0 , "You should give a positive number greater than 0." ) ; this . quantifier = Quantifier . times ( quantifier . getConsumingStrategy ( ) ) ; this . times = Times . of ( times... | Specifies exact number of times that this pattern should be matched . |
15,728 | public Pattern < T , F > times ( int from , int to ) { checkIfNoNotPattern ( ) ; checkIfQuantifierApplied ( ) ; this . quantifier = Quantifier . times ( quantifier . getConsumingStrategy ( ) ) ; if ( from == 0 ) { this . quantifier . optional ( ) ; from = 1 ; } this . times = Times . of ( from , to ) ; return this ; } | Specifies that the pattern can occur between from and to times . |
15,729 | public Pattern < T , F > timesOrMore ( int times ) { checkIfNoNotPattern ( ) ; checkIfQuantifierApplied ( ) ; this . quantifier = Quantifier . looping ( quantifier . getConsumingStrategy ( ) ) ; this . times = Times . of ( times ) ; return this ; } | Specifies that this pattern can occur the specified times at least . This means at least the specified times and at most infinite number of events can be matched to this pattern . |
15,730 | public static < T , F extends T > GroupPattern < T , F > begin ( final Pattern < T , F > group , final AfterMatchSkipStrategy afterMatchSkipStrategy ) { return new GroupPattern < > ( null , group , ConsumingStrategy . STRICT , afterMatchSkipStrategy ) ; } | Starts a new pattern sequence . The provided pattern is the initial pattern of the new sequence . |
15,731 | public GroupPattern < T , F > next ( Pattern < T , F > group ) { return new GroupPattern < > ( this , group , ConsumingStrategy . STRICT , afterMatchSkipStrategy ) ; } | Appends a new group pattern to the existing one . The new pattern enforces strict temporal contiguity . This means that the whole pattern sequence matches only if an event which matches this pattern directly follows the preceding matching event . Thus there cannot be any events in between two matching events . |
15,732 | public void replace ( String pathInZooKeeper , int expectedVersion , T state ) throws Exception { checkNotNull ( pathInZooKeeper , "Path in ZooKeeper" ) ; checkNotNull ( state , "State" ) ; final String path = normalizePath ( pathInZooKeeper ) ; RetrievableStateHandle < T > oldStateHandle = get ( path , false ) ; Retri... | Replaces a state handle in ZooKeeper and discards the old state handle . |
15,733 | public Collection < String > getAllPaths ( ) throws Exception { final String path = "/" ; while ( true ) { Stat stat = client . checkExists ( ) . forPath ( path ) ; if ( stat == null ) { return Collections . emptyList ( ) ; } else { try { return client . getChildren ( ) . forPath ( path ) ; } catch ( KeeperException . ... | Return a list of all valid paths for state handles . |
15,734 | @ SuppressWarnings ( "unchecked" ) public List < Tuple2 < RetrievableStateHandle < T > , String > > getAllAndLock ( ) throws Exception { final List < Tuple2 < RetrievableStateHandle < T > , String > > stateHandles = new ArrayList < > ( ) ; boolean success = false ; retry : while ( ! success ) { stateHandles . clear ( )... | Gets all available state handles from ZooKeeper and locks the respective state nodes . |
15,735 | public void releaseAndTryRemoveAll ( ) throws Exception { Collection < String > children = getAllPaths ( ) ; Exception exception = null ; for ( String child : children ) { try { releaseAndTryRemove ( '/' + child ) ; } catch ( Exception e ) { exception = ExceptionUtils . firstOrSuppressed ( e , exception ) ; } } if ( ex... | Releases all lock nodes of this ZooKeeperStateHandleStores and tries to remove all state nodes which are not locked anymore . |
15,736 | public void release ( String pathInZooKeeper ) throws Exception { final String path = normalizePath ( pathInZooKeeper ) ; try { client . delete ( ) . forPath ( getLockPath ( path ) ) ; } catch ( KeeperException . NoNodeException ignored ) { } catch ( Exception e ) { throw new Exception ( "Could not release the lock: " ... | Releases the lock from the node under the given ZooKeeper path . If no lock exists then nothing happens . |
15,737 | public void releaseAll ( ) throws Exception { Collection < String > children = getAllPaths ( ) ; Exception exception = null ; for ( String child : children ) { try { release ( child ) ; } catch ( Exception e ) { exception = ExceptionUtils . firstOrSuppressed ( e , exception ) ; } } if ( exception != null ) { throw new ... | Releases all lock nodes of this ZooKeeperStateHandleStore . |
15,738 | public void deleteChildren ( ) throws Exception { final String path = "/" + client . getNamespace ( ) ; LOG . info ( "Removing {} from ZooKeeper" , path ) ; ZKPaths . deleteChildren ( client . getZookeeperClient ( ) . getZooKeeper ( ) , path , true ) ; } | Recursively deletes all children . |
15,739 | @ SuppressWarnings ( "unchecked" ) private RetrievableStateHandle < T > get ( String pathInZooKeeper , boolean lock ) throws Exception { checkNotNull ( pathInZooKeeper , "Path in ZooKeeper" ) ; final String path = normalizePath ( pathInZooKeeper ) ; if ( lock ) { try { client . create ( ) . withMode ( CreateMode . EPHE... | Gets a state handle from ZooKeeper and optionally locks it . |
15,740 | public void set ( int index ) { Preconditions . checkArgument ( index < bitLength && index >= 0 ) ; int byteIndex = ( index & BYTE_POSITION_MASK ) >>> 3 ; byte current = memorySegment . get ( offset + byteIndex ) ; current |= ( 1 << ( index & BYTE_INDEX_MASK ) ) ; memorySegment . put ( offset + byteIndex , current ) ; ... | Sets the bit at specified index . |
15,741 | public final void coGroup ( Iterable < IN1 > first , Iterable < IN2 > second , Collector < OUT > out ) throws Exception { streamer . streamBufferWithGroups ( first . iterator ( ) , second . iterator ( ) , out ) ; } | Calls the external python function . |
15,742 | void registerColumnFamily ( String columnFamilyName , ColumnFamilyHandle handle ) { MetricGroup group = metricGroup . addGroup ( columnFamilyName ) ; for ( String property : options . getProperties ( ) ) { RocksDBNativeMetricView gauge = new RocksDBNativeMetricView ( handle , property ) ; group . gauge ( property , gau... | Register gauges to pull native metrics for the column family . |
15,743 | private void setProperty ( ColumnFamilyHandle handle , String property , RocksDBNativeMetricView metricView ) { if ( metricView . isClosed ( ) ) { return ; } try { synchronized ( lock ) { if ( rocksDB != null ) { long value = rocksDB . getLongProperty ( handle , property ) ; metricView . setValue ( value ) ; } } } catc... | Updates the value of metricView if the reference is still valid . |
15,744 | public String getMessage ( ) { String ret = super . getMessage ( ) ; if ( fileName != null ) { ret += ( " in " + fileName ) ; if ( lineNumber != - 1 ) { ret += " at line number " + lineNumber ; } if ( columnNumber != - 1 ) { ret += " at column number " + columnNumber ; } } return ret ; } | Returns a message containing the String passed to a constructor as well as line and column numbers and filename if any of these are known . |
15,745 | public static int bernstein ( String key ) { int hash = 0 ; int i ; for ( i = 0 ; i < key . length ( ) ; ++ i ) { hash = 33 * hash + key . charAt ( i ) ; } return hash ; } | Bernstein s hash |
15,746 | public String nextTo ( String delimiters ) throws JSONException { char c ; StringBuilder sb = new StringBuilder ( ) ; for ( ; ; ) { c = this . next ( ) ; if ( delimiters . indexOf ( c ) >= 0 || c == 0 || c == '\n' || c == '\r' ) { if ( c != 0 ) { this . back ( ) ; } return sb . toString ( ) . trim ( ) ; } sb . append (... | Get the text up but not including one of the specified delimiter characters or the end of line whichever comes first . |
15,747 | private static String transThree ( String s ) { String value = "" ; if ( s . startsWith ( "0" ) ) { value = transTwo ( s . substring ( 1 ) ) ; } else if ( s . substring ( 1 ) . equals ( "00" ) ) { value = parseFirst ( s . substring ( 0 , 1 ) ) + " HUNDRED" ; } else { value = parseFirst ( s . substring ( 0 , 1 ) ) + " H... | s . length = 3 |
15,748 | private static void appendDigits ( final Appendable buffer , final int value ) throws IOException { buffer . append ( ( char ) ( value / 10 + '0' ) ) ; buffer . append ( ( char ) ( value % 10 + '0' ) ) ; } | Appends two digits to the given buffer . |
15,749 | private static void appendFullDigits ( final Appendable buffer , int value , int minFieldWidth ) throws IOException { if ( value < 10000 ) { int nDigits = 4 ; if ( value < 1000 ) { -- nDigits ; if ( value < 100 ) { -- nDigits ; if ( value < 10 ) { -- nDigits ; } } } for ( int i = minFieldWidth - nDigits ; i > 0 ; -- i ... | Appends all digits to the given buffer . |
15,750 | private void readObject ( final ObjectInputStream in ) throws IOException , ClassNotFoundException { in . defaultReadObject ( ) ; final Calendar definingCalendar = Calendar . getInstance ( timeZone , locale ) ; init ( definingCalendar ) ; } | Create the object after serialization . This implementation reinitializes the transient properties . |
15,751 | private static Map < String , Integer > appendDisplayNames ( final Calendar cal , final Locale locale , final int field , final StringBuilder regex ) { final Map < String , Integer > values = new HashMap < > ( ) ; final Map < String , Integer > displayNames = cal . getDisplayNames ( field , Calendar . ALL_STYLES , loca... | Get the short and long values displayed for a field |
15,752 | private Strategy getStrategy ( final char f , final int width , final Calendar definingCalendar ) { switch ( f ) { default : throw new IllegalArgumentException ( "Format '" + f + "' not supported" ) ; case 'D' : return DAY_OF_YEAR_STRATEGY ; case 'E' : return getLocaleSpecificStrategy ( Calendar . DAY_OF_WEEK , definin... | Obtain a Strategy given a field from a SimpleDateFormat pattern |
15,753 | private static ConcurrentMap < Locale , Strategy > getCache ( final int field ) { synchronized ( caches ) { if ( caches [ field ] == null ) { caches [ field ] = new ConcurrentHashMap < > ( 3 ) ; } return caches [ field ] ; } } | Get a cache of Strategies for a particular field |
15,754 | private Strategy getLocaleSpecificStrategy ( final int field , final Calendar definingCalendar ) { final ConcurrentMap < Locale , Strategy > cache = getCache ( field ) ; Strategy strategy = cache . get ( locale ) ; if ( strategy == null ) { strategy = field == Calendar . ZONE_OFFSET ? new TimeZoneStrategy ( locale ) : ... | Construct a Strategy that parses a Text field |
15,755 | private F getDateTimeInstance ( final Integer dateStyle , final Integer timeStyle , final TimeZone timeZone , Locale locale ) { if ( locale == null ) { locale = Locale . getDefault ( ) ; } final String pattern = getPatternForStyle ( dateStyle , timeStyle , locale ) ; return getInstance ( pattern , timeZone , locale ) ;... | This must remain private see LANG - 884 |
15,756 | public Object nextMeta ( ) throws JSONException { char c ; char q ; do { c = next ( ) ; } while ( Character . isWhitespace ( c ) ) ; switch ( c ) { case 0 : throw syntaxError ( "Misshaped meta tag" ) ; case '<' : return XML . LT ; case '>' : return XML . GT ; case '/' : return XML . SLASH ; case '=' : return XML . EQ ;... | Returns the next XML meta token . This is used for skipping over < ; ! ... > ; and < ; ? ... ?> ; structures . |
15,757 | public boolean skipPast ( String to ) throws JSONException { boolean b ; char c ; int i ; int j ; int offset = 0 ; int length = to . length ( ) ; char [ ] circle = new char [ length ] ; for ( i = 0 ; i < length ; i += 1 ) { c = next ( ) ; if ( c == 0 ) { return false ; } circle [ i ] = c ; } for ( ; ; ) { j = offset ; ... | Skip characters until past the requested string . If it is not found we are left at the end of the source with a result of false . |
15,758 | public String filter ( final String input ) { reset ( ) ; String s = input ; debug ( "************************************************" ) ; debug ( " INPUT: " + input ) ; s = escapeComments ( s ) ; debug ( " escapeComments: " + s ) ; s = balanceHTML ( s ) ; debug ( " balanceHTML: " + s ) ; s = c... | given a user submitted input String filter out any invalid or restricted html . |
15,759 | public void dumpRequest ( Map < String , Object > result ) { exchange . getQueryParameters ( ) . forEach ( ( k , v ) -> { if ( config . getRequestFilteredQueryParameters ( ) . contains ( k ) ) { String queryParameterValue = config . isMaskEnabled ( ) ? Mask . maskRegex ( v . getFirst ( ) , "queryParameter" , k ) : v . ... | impl of dumping request query parameter to result |
15,760 | protected void putDumpInfoTo ( Map < String , Object > result ) { if ( this . queryParametersMap . size ( ) > 0 ) { result . put ( DumpConstants . QUERY_PARAMETERS , queryParametersMap ) ; } } | put queryParametersMap to result . |
15,761 | public void sendMail ( String to , String subject , String content ) throws MessagingException { Properties props = new Properties ( ) ; props . put ( "mail.smtp.user" , emailConfg . getUser ( ) ) ; props . put ( "mail.smtp.host" , emailConfg . getHost ( ) ) ; props . put ( "mail.smtp.port" , emailConfg . getPort ( ) )... | Send email with a string content . |
15,762 | public void sendMailWithAttachment ( String to , String subject , String content , String filename ) throws MessagingException { Properties props = new Properties ( ) ; props . put ( "mail.smtp.user" , emailConfg . getUser ( ) ) ; props . put ( "mail.smtp.host" , emailConfg . getHost ( ) ) ; props . put ( "mail.smtp.po... | Send email with a string content and attachment |
15,763 | private static void handleSingletonClass ( String key , String value ) throws Exception { Object object = handleValue ( value ) ; if ( key . contains ( "," ) ) { String [ ] interfaces = key . split ( "," ) ; for ( String anInterface : interfaces ) { serviceMap . put ( anInterface , object ) ; } } else { serviceMap . pu... | For each singleton definition create object with the initializer class and method and push it into the service map with the key of the class name . |
15,764 | private static void handleSingletonList ( String key , List < Object > value ) throws Exception { List < String > interfaceClasses = new ArrayList ( ) ; if ( key . contains ( "," ) ) { String [ ] interfaces = key . split ( "," ) ; interfaceClasses . addAll ( Arrays . asList ( interfaces ) ) ; } else { interfaceClasses ... | For each singleton definition create object for the interface with the implementation class and push it into the service map with key and implemented object . |
15,765 | public static < T > T getBean ( Class < T > interfaceClass , Class typeClass ) { Object object = serviceMap . get ( interfaceClass . getName ( ) + "<" + typeClass . getName ( ) + ">" ) ; if ( object == null ) return null ; if ( object instanceof Object [ ] ) { return ( T ) Array . get ( object , 0 ) ; } else { return (... | Get a cached singleton object from service map by interface class and generic type class . The serviceMap is constructed from service . yml which defines interface and generic type to implementation mapping . |
15,766 | public static < T > T [ ] getBeans ( Class < T > interfaceClass ) { Object object = serviceMap . get ( interfaceClass . getName ( ) ) ; if ( object == null ) return null ; if ( object instanceof Object [ ] ) { return ( T [ ] ) object ; } else { Object array = Array . newInstance ( interfaceClass , 1 ) ; Array . set ( a... | Get a list of cached singleton objects from service map by interface class . If there is only one object in the serviceMap then construct the list with this only object . |
15,767 | public byte [ ] toByteArray ( ) { final byte [ ] b = new byte [ this . len ] ; if ( this . len > 0 ) { System . arraycopy ( this . array , 0 , b , 0 , this . len ) ; } return b ; } | Converts the content of this buffer to an array of bytes . |
15,768 | public String getLastPathSegment ( ) { if ( StringUtils . isBlank ( path ) ) { return StringUtils . EMPTY ; } String segment = path ; segment = StringUtils . substringAfterLast ( segment , "/" ) ; return segment ; } | Gets the last URL path segment without the query string . If there are segment to return an empty string will be returned instead . |
15,769 | public boolean isPortDefault ( ) { return ( PROTOCOL_HTTPS . equalsIgnoreCase ( protocol ) && port == DEFAULT_HTTPS_PORT ) || ( PROTOCOL_HTTP . equalsIgnoreCase ( protocol ) && port == DEFAULT_HTTP_PORT ) ; } | Whether this URL uses the default port for the protocol . The default port is 80 for http protocol and 443 for https . Other protocols are not supported and this method will always return false for them . |
15,770 | public static String toAbsolute ( String baseURL , String relativeURL ) { String relURL = relativeURL ; if ( relURL . startsWith ( "//" ) ) { return StringUtils . substringBefore ( baseURL , "//" ) + "//" + StringUtils . substringAfter ( relURL , "//" ) ; } if ( relURL . startsWith ( "/" ) ) { return getRoot ( baseURL ... | Converts a relative URL to an absolute one based on the supplied base URL . The base URL is assumed to be a valid URL . Behavior is unexpected when base URL is invalid . |
15,771 | public static String generateRandomCodeVerifier ( SecureRandom entropySource , int entropyBytes ) { byte [ ] randomBytes = new byte [ entropyBytes ] ; entropySource . nextBytes ( randomBytes ) ; return Base64 . getUrlEncoder ( ) . withoutPadding ( ) . encodeToString ( randomBytes ) ; } | Generates a random code verifier string using the provided entropy source and the specified number of bytes of entropy . |
15,772 | public static void addProvidersToPathHandler ( PathResourceProvider [ ] pathResourceProviders , PathHandler pathHandler ) { if ( pathResourceProviders != null && pathResourceProviders . length > 0 ) { for ( PathResourceProvider pathResourceProvider : pathResourceProviders ) { if ( pathResourceProvider . isPrefixPath ( ... | Helper to add given PathResourceProviders to a PathHandler . |
15,773 | public static List < PredicatedHandler > getPredicatedHandlers ( PredicatedHandlersProvider [ ] predicatedHandlersProviders ) { List < PredicatedHandler > predicatedHandlers = new ArrayList < > ( ) ; if ( predicatedHandlersProviders != null && predicatedHandlersProviders . length > 0 ) { for ( PredicatedHandlersProvide... | Helper for retrieving all PredicatedHandlers from the given list of PredicatedHandlersProviders . |
15,774 | public static boolean isResourcePath ( String requestPath , PathResourceProvider [ ] pathResourceProviders ) { boolean isResourcePath = false ; if ( pathResourceProviders != null && pathResourceProviders . length > 0 ) { for ( PathResourceProvider pathResourceProvider : pathResourceProviders ) { if ( ( pathResourceProv... | Helper to check if a given requestPath could resolve to a PathResourceProvider . |
15,775 | public static Result < TokenResponse > getTokenResult ( TokenRequest tokenRequest , String envTag ) { final AtomicReference < Result < TokenResponse > > reference = new AtomicReference < > ( ) ; final Http2Client client = Http2Client . getInstance ( ) ; final CountDownLatch latch = new CountDownLatch ( 1 ) ; final Clie... | Get an access token from the token service . A Result of TokenResponse will be returned if the invocation is successfully . Otherwise a Result of Status will be returned . |
15,776 | public static String getKey ( KeyRequest keyRequest , String envTag ) throws ClientException { final Http2Client client = Http2Client . getInstance ( ) ; final CountDownLatch latch = new CountDownLatch ( 1 ) ; final ClientConnection connection ; try { if ( keyRequest . getServerUrl ( ) != null ) { connection = client .... | Get the certificate from key distribution service of OAuth 2 . 0 provider with the kid . |
15,777 | private static Result < Jwt > renewCCTokenSync ( final Jwt jwt ) { logger . trace ( "In renew window and token is already expired." ) ; if ( ! jwt . isRenewing ( ) || System . currentTimeMillis ( ) > jwt . getExpiredRetryTimeout ( ) ) { jwt . setRenewing ( true ) ; jwt . setEarlyRetryTimeout ( System . currentTimeMilli... | renew Client Credential token synchronously . When success will renew the Jwt jwt passed in . When fail will return Status code so that can be handled by caller . |
15,778 | private static void renewCCTokenAsync ( final Jwt jwt ) { logger . trace ( "In renew window but token is not expired yet." ) ; if ( ! jwt . isRenewing ( ) || System . currentTimeMillis ( ) > jwt . getEarlyRetryTimeout ( ) ) { jwt . setRenewing ( true ) ; jwt . setEarlyRetryTimeout ( System . currentTimeMillis ( ) + jwt... | renew the given Jwt jwt asynchronously . When fail it will swallow the exception so no need return type to be handled by caller . |
15,779 | private static Result < Jwt > getCCTokenRemotely ( final Jwt jwt ) { TokenRequest tokenRequest = new ClientCredentialsRequest ( ) ; setScope ( tokenRequest , jwt ) ; Result < TokenResponse > result = OauthHelper . getTokenResult ( tokenRequest ) ; if ( result . isSuccess ( ) ) { TokenResponse tokenResponse = result . g... | get Client Credential token from auth server |
15,780 | private static String escapeXml ( String nonEscapedXmlStr ) { StringBuilder escapedXML = new StringBuilder ( ) ; for ( int i = 0 ; i < nonEscapedXmlStr . length ( ) ; i ++ ) { char c = nonEscapedXmlStr . charAt ( i ) ; switch ( c ) { case '<' : escapedXML . append ( "<" ) ; break ; case '>' : escapedXML . append ( "... | Instead of including a large library just for escaping xml using this util . it should be used in very rare cases because the server should not return xml format message |
15,781 | public static void adjustNoChunkedEncoding ( ClientRequest request , String requestBody ) { String fixedLengthString = request . getRequestHeaders ( ) . getFirst ( Headers . CONTENT_LENGTH ) ; String transferEncodingString = request . getRequestHeaders ( ) . getLast ( Headers . TRANSFER_ENCODING ) ; if ( transferEncodi... | this method is to support sending a server which doesn t support chunked transfer encoding . |
15,782 | private void attachFormDataBody ( final HttpServerExchange exchange ) throws IOException { Object data ; FormParserFactory formParserFactory = FormParserFactory . builder ( ) . build ( ) ; FormDataParser parser = formParserFactory . createParser ( exchange ) ; if ( parser != null ) { FormData formData = parser . parseB... | Method used to parse the body into FormData and attach it into exchange |
15,783 | private void attachJsonBody ( final HttpServerExchange exchange , String string ) throws IOException { Object body ; if ( string != null ) { string = string . trim ( ) ; if ( string . startsWith ( "{" ) ) { body = Config . getInstance ( ) . getMapper ( ) . readValue ( string , new TypeReference < Map < String , Object ... | Method used to parse the body into a Map or a List and attach it into exchange |
15,784 | public static String maskString ( String input , String key ) { String output = input ; Map < String , Object > stringConfig = ( Map < String , Object > ) config . get ( MASK_TYPE_STRING ) ; if ( stringConfig != null ) { Map < String , Object > keyConfig = ( Map < String , Object > ) stringConfig . get ( key ) ; if ( k... | Mask the input string with a list of patterns indexed by key in string section in mask . json This is usually used to mask header values query parameters and uri parameters |
15,785 | public static String maskJson ( String input , String key ) { DocumentContext ctx = JsonPath . parse ( input ) ; return maskJson ( ctx , key ) ; } | Replace values in JSON using json path |
15,786 | public void skipWhiteSpace ( final CharSequence buf , final ParserCursor cursor ) { Args . notNull ( buf , "Char sequence" ) ; Args . notNull ( cursor , "Parser cursor" ) ; int pos = cursor . getPos ( ) ; final int indexFrom = cursor . getPos ( ) ; final int indexTo = cursor . getUpperBound ( ) ; for ( int i = indexFro... | Skips semantically insignificant whitespace characters and moves the cursor to the closest non - whitespace character . |
15,787 | public void copyContent ( final CharSequence buf , final ParserCursor cursor , final BitSet delimiters , final StringBuilder dst ) { Args . notNull ( buf , "Char sequence" ) ; Args . notNull ( cursor , "Parser cursor" ) ; Args . notNull ( dst , "String builder" ) ; int pos = cursor . getPos ( ) ; final int indexFrom = ... | Transfers content into the destination buffer until a whitespace character or any of the given delimiters is encountered . |
15,788 | public void copyQuotedContent ( final CharSequence buf , final ParserCursor cursor , final StringBuilder dst ) { Args . notNull ( buf , "Char sequence" ) ; Args . notNull ( cursor , "Parser cursor" ) ; Args . notNull ( dst , "String builder" ) ; if ( cursor . atEnd ( ) ) { return ; } int pos = cursor . getPos ( ) ; int... | Transfers content enclosed with quote marks into the destination buffer . |
15,789 | static void logResult ( Map < String , Object > result , DumpConfig config ) { Consumer < String > loggerFunc = getLoggerFuncBasedOnLevel ( config . getLogLevel ( ) ) ; if ( config . isUseJson ( ) ) { logResultUsingJson ( result , loggerFunc ) ; } else { int startLevel = - 1 ; StringBuilder sb = new StringBuilder ( "Ht... | A help method to log result pojo |
15,790 | private static < T > void _logResult ( T result , int level , int indentSize , StringBuilder info ) { if ( result instanceof Map ) { level += 1 ; int finalLevel = level ; ( ( Map ) result ) . forEach ( ( k , v ) -> { info . append ( "\n" ) ; info . append ( getTabBasedOnLevel ( finalLevel , indentSize ) ) . append ( k ... | this method actually append result to result string |
15,791 | private static String getTabBasedOnLevel ( int level , int indentSize ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < level ; i ++ ) { for ( int j = 0 ; j < indentSize ; j ++ ) { sb . append ( " " ) ; } } return sb . toString ( ) ; } | calculate indent for formatting |
15,792 | private URL removeUnnecessaryParmas ( URL url ) { url . getParameters ( ) . remove ( URLParamType . codec . getName ( ) ) ; return url ; } | client doesn t need to know codec . |
15,793 | public void dumpResponse ( Map < String , Object > result ) { this . statusCodeResult = String . valueOf ( exchange . getStatusCode ( ) ) ; this . putDumpInfoTo ( result ) ; } | impl of dumping response status code to result |
15,794 | protected void putDumpInfoTo ( Map < String , Object > result ) { if ( StringUtils . isNotBlank ( this . statusCodeResult ) ) { result . put ( DumpConstants . STATUS_CODE , this . statusCodeResult ) ; } } | put this . statusCodeResult to result |
15,795 | public static String getUUID ( ) { UUID id = UUID . randomUUID ( ) ; ByteBuffer bb = ByteBuffer . wrap ( new byte [ 16 ] ) ; bb . putLong ( id . getMostSignificantBits ( ) ) ; bb . putLong ( id . getLeastSignificantBits ( ) ) ; return Base64 . encodeBase64URLSafeString ( bb . array ( ) ) ; } | Generate UUID across the entire app and it is used for correlationId . |
15,796 | public static String quote ( final String value ) { if ( value == null ) { return null ; } String result = value ; if ( ! result . startsWith ( "\"" ) ) { result = "\"" + result ; } if ( ! result . endsWith ( "\"" ) ) { result = result + "\"" ; } return result ; } | Quote the given string if needed |
15,797 | public String serviceToUrl ( String protocol , String serviceId , String tag , String requestKey ) { URL url = loadBalance . select ( discovery ( protocol , serviceId , tag ) , requestKey ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( "final url after load balance = " + url ) ; return protocol + "://" + url . ... | Implement serviceToUrl with client side service discovery . |
15,798 | private String getServerTlsFingerPrint ( ) { String fingerPrint = null ; Map < String , Object > serverConfig = Config . getInstance ( ) . getJsonMapConfigNoCache ( "server" ) ; Map < String , Object > secretConfig = Config . getInstance ( ) . getJsonMapConfigNoCache ( "secret" ) ; String keystoreName = ( String ) serv... | We can get it from server module but we don t want mutual dependency . So get it from config and keystore directly |
15,799 | private void doCustomServerIdentityCheck ( X509Certificate cert ) throws CertificateException { if ( EndpointIdentificationAlgorithm . APIS == identityAlg ) { APINameChecker . verifyAndThrow ( trustedNameSet , cert ) ; } } | check server identify as per tls . trustedNames in client . yml . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.