idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
23,500
public static JsonNode buildResponse ( int status , String message , Object data ) { return SerializationUtils . toJson ( MapUtils . removeNulls ( MapUtils . createMap ( FIELD_STATUS , status , FIELD_MESSAGE , message , FIELD_DATA , data ) ) ) ; }
Build Json - RPC s response in JSON format .
72
11
23,501
public static RequestResponse callHttpPost ( HttpJsonRpcClient client , String url , Map < String , Object > headers , Map < String , Object > urlParams , Object requestData ) { return client . doPost ( url , headers , urlParams , requestData ) ; }
Perform a HTTP POST request .
62
7
23,502
public static RequestResponse callHttpPut ( HttpJsonRpcClient client , String url , Map < String , Object > headers , Map < String , Object > urlParams , Object requestData ) { return client . doPut ( url , headers , urlParams , requestData ) ; }
Perform a HTTP PUT request .
62
8
23,503
public static RequestResponse callHttpPatch ( HttpJsonRpcClient client , String url , Map < String , Object > headers , Map < String , Object > urlParams , Object requestData ) { return client . doPatch ( url , headers , urlParams , requestData ) ; }
Perform a HTTP PATCH request .
62
8
23,504
public static RequestResponse callHttpDelete ( HttpJsonRpcClient client , String url , Map < String , Object > headers , Map < String , Object > urlParams ) { return client . doDelete ( url , headers , urlParams ) ; }
Perform a HTTP DELETE request .
55
9
23,505
public RequestResponse doGet ( String url , Map < String , Object > headers , Map < String , Object > urlParams ) { RequestResponse requestResponse = initRequestResponse ( "GET" , url , headers , urlParams , null ) ; Request . Builder requestBuilder = buildRequest ( url , headers , urlParams ) . get ( ) ; return doCall ( client , requestBuilder . build ( ) , requestResponse ) ; }
Perform a GET request .
92
6
23,506
public RequestResponse doPost ( String url , Map < String , Object > headers , Map < String , Object > urlParams , Object requestData ) { RequestResponse rr = initRequestResponse ( "POST" , url , headers , urlParams , requestData ) ; Request . Builder requestBuilder = buildRequest ( url , headers , urlParams ) . post ( buildRequestBody ( rr ) ) ; return doCall ( client , requestBuilder . build ( ) , rr ) ; }
Perform a POST request .
104
6
23,507
public RequestResponse doDelete ( String url , Map < String , Object > headers , Map < String , Object > urlParams ) { return doDelete ( url , headers , urlParams , null ) ; }
Perform a DELETE request .
44
8
23,508
public static < T > T getValue ( Map < String , Object > map , String key , Class < T > clazz ) { return map != null ? ValueUtils . convertValue ( map . get ( key ) , clazz ) : null ; }
Extract a value from a map .
54
8
23,509
public static < K , V > Map < K , V > removeNulls ( Map < K , V > map ) { Map < K , V > result = new LinkedHashMap <> ( ) ; map . forEach ( ( k , v ) -> { if ( v != null ) { result . put ( k , v ) ; } } ) ; return result ; }
Remove null values from map .
80
6
23,510
public static boolean hasSuperClass ( Class < ? > clazz , Class < ? > superClazz ) { if ( clazz == null || superClazz == null || clazz == superClazz ) { return false ; } if ( clazz . isInterface ( ) ) { return superClazz . isAssignableFrom ( clazz ) ; } Class < ? > parent = clazz . getSuperclass ( ) ; while ( parent != null ) { if ( parent == superClazz ) { return true ; } parent = parent . getSuperclass ( ) ; } return false ; }
Tells if a class is a sub - class of a super - class .
125
16
23,511
public long getId ( final String agent ) throws InvalidUserAgentError , InvalidSystemClock { if ( ! isValidUserAgent ( agent ) ) { exceptionsCounter . inc ( ) ; throw new InvalidUserAgentError ( ) ; } final long id = nextId ( ) ; genCounter ( agent ) ; return id ; }
Get the next ID for a given user - agent
67
10
23,512
public synchronized long nextId ( ) throws InvalidSystemClock { long timestamp = timeGen ( ) ; long curSequence = 0L ; final long prevTimestamp = lastTimestamp . get ( ) ; if ( timestamp < prevTimestamp ) { exceptionsCounter . inc ( ) ; LOGGER . error ( "clock is moving backwards. Rejecting requests until {}" , prevTimestamp ) ; throw new InvalidSystemClock ( String . format ( "Clock moved backwards. Refusing to generate id for %d milliseconds" , ( prevTimestamp - timestamp ) ) ) ; } if ( prevTimestamp == timestamp ) { curSequence = sequence . incrementAndGet ( ) & SEQUENCE_MASK ; if ( curSequence == 0 ) { timestamp = tilNextMillis ( prevTimestamp ) ; } } else { curSequence = 0L ; sequence . set ( 0L ) ; } lastTimestamp . set ( timestamp ) ; final long id = ( ( timestamp - TWEPOCH ) << TIMESTAMP_LEFT_SHIFT ) | ( datacenterId << DATACENTER_ID_SHIFT ) | ( workerId << WORKER_ID_SHIFT ) | curSequence ; LOGGER . trace ( "prevTimestamp = {}, timestamp = {}, sequence = {}, id = {}" , prevTimestamp , timestamp , sequence , id ) ; return id ; }
Get the next ID
297
4
23,513
public boolean isValidUserAgent ( final String agent ) { if ( ! validateUserAgent ) { return true ; } final Matcher matcher = AGENT_PATTERN . matcher ( agent ) ; return matcher . matches ( ) ; }
Check whether the user agent is valid
52
7
23,514
protected void genCounter ( final String agent ) { idsCounter . inc ( ) ; if ( ! agentCounters . containsKey ( agent ) ) { agentCounters . put ( agent , registry . counter ( MetricRegistry . name ( IdWorker . class , "ids_generated_" + agent ) ) ) ; } agentCounters . get ( agent ) . inc ( ) ; }
Update the counters for a given user agent
84
8
23,515
public static Map < String , String > createQueryParamsList ( String clientId , String redirectUri , String responseType , String hideTenant , String scope ) { if ( clientId == null ) { throw new IllegalArgumentException ( "Missing the required parameter 'client_id'" ) ; } if ( redirectUri == null ) { throw new IllegalArgumentException ( "Missing the required parameter 'redirect_uri'" ) ; } if ( responseType == null ) { throw new IllegalArgumentException ( "Missing the required parameter 'response_type'" ) ; } Map < String , String > queryParams = new HashMap <> ( ) ; queryParams . put ( "client_id" , clientId ) ; queryParams . put ( "redirect_uri" , redirectUri ) ; queryParams . put ( "response_type" , responseType ) ; if ( hideTenant != null ) queryParams . put ( "hideTenant" , hideTenant ) ; if ( scope != null ) queryParams . put ( "scope" , scope ) ; return queryParams ; }
Build query parameters
240
3
23,516
protected static Object coerceToSupportedType ( Object value ) { if ( value == null ) { return "" ; // # empty string rather than null } else if ( value instanceof Map ) { Map valueAsMap = ( ( Map ) value ) ; if ( valueAsMap . containsKey ( "*" ) ) { return valueAsMap . get ( "*" ) ; } else if ( valueAsMap . containsKey ( "__default__" ) ) { return valueAsMap . get ( "__default__" ) ; } else { return s_gson . toJson ( valueAsMap ) ; } } else if ( value instanceof Float ) { return new BigDecimal ( ( float ) value ) ; } else if ( value instanceof Double ) { return new BigDecimal ( ( double ) value ) ; } else if ( value instanceof Long ) { return new BigDecimal ( ( long ) value ) ; } else { return value ; } }
Since we let users populate the context with whatever they want this ensures the resolved value is something which the expression engine understands .
205
24
23,517
public static byte [ ] toBytes ( TBase < ? , ? > record ) throws TException { if ( record == null ) { return null ; } ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; TTransport transport = new TIOStreamTransport ( null , baos ) ; TProtocol oProtocol = protocolFactory . getProtocol ( transport ) ; record . write ( oProtocol ) ; // baos.close(); return baos . toByteArray ( ) ; }
Serializes a thrift object to byte array .
108
10
23,518
public static < T extends TBase < ? , ? > > T fromBytes ( byte [ ] data , Class < T > clazz ) throws TException { if ( data == null ) { return null ; } ByteArrayInputStream bais = new ByteArrayInputStream ( data ) ; try { TTransport transport = new TIOStreamTransport ( bais , null ) ; TProtocol iProtocol = protocolFactory . getProtocol ( transport ) ; T record = clazz . newInstance ( ) ; record . read ( iProtocol ) ; // bais.close(); return record ; } catch ( InstantiationException | IllegalAccessException e ) { throw new TException ( e ) ; } }
Deserializes a thrift object from byte array .
149
11
23,519
public static void closeRocksObjects ( RocksObject ... rocksObjList ) { if ( rocksObjList != null ) { for ( RocksObject obj : rocksObjList ) { try { if ( obj != null ) { obj . close ( ) ; } } catch ( Exception e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; } } } }
Silently close RocksDb objects .
79
7
23,520
public static String [ ] getColumnFamilyList ( String path ) throws RocksDBException { List < byte [ ] > cfList = RocksDB . listColumnFamilies ( new Options ( ) , path ) ; if ( cfList == null || cfList . size ( ) == 0 ) { return ArrayUtils . EMPTY_STRING_ARRAY ; } List < String > result = new ArrayList <> ( cfList . size ( ) ) ; for ( byte [ ] cf : cfList ) { result . add ( new String ( cf , StandardCharsets . UTF_8 ) ) ; } return result . toArray ( ArrayUtils . EMPTY_STRING_ARRAY ) ; }
Gets all available column family names from a RocksDb data directory .
149
14
23,521
@ SuppressWarnings ( "unchecked" ) public static < T > T convertValue ( Object target , Class < T > clazz ) { if ( clazz == null ) { throw new NullPointerException ( "Class parameter is null!" ) ; } if ( target == null ) { return null ; } if ( target instanceof JsonNode ) { return convertValue ( ( JsonNode ) target , clazz ) ; } if ( Number . class . isAssignableFrom ( clazz ) || byte . class == clazz || short . class == clazz || int . class == clazz || long . class == clazz || float . class == clazz || double . class == clazz ) { return convertNumber ( target , clazz ) ; } if ( clazz == Boolean . class || clazz == boolean . class ) { return ( T ) convertBoolean ( target ) ; } if ( clazz == Character . class || clazz == char . class ) { return ( T ) convertChar ( target ) ; } if ( Date . class . isAssignableFrom ( clazz ) ) { return ( T ) convertDate ( target ) ; } if ( Object [ ] . class . isAssignableFrom ( clazz ) || List . class . isAssignableFrom ( clazz ) ) { return ( T ) convertArrayOrList ( target ) ; } if ( clazz . isAssignableFrom ( target . getClass ( ) ) ) { return ( T ) target ; } if ( clazz == String . class ) { return ( T ) target . toString ( ) ; } throw new IllegalArgumentException ( "Cannot convert an object of type [" + target . getClass ( ) + "] to [" + clazz + "]!" ) ; }
Convert a target object to a specified value type .
381
11
23,522
public static Config loadConfig ( File configFile , boolean useSystemEnvironment ) { return loadConfig ( ConfigParseOptions . defaults ( ) , ConfigResolveOptions . defaults ( ) . setUseSystemEnvironment ( useSystemEnvironment ) , configFile ) ; }
Load Parse & Resolve configurations from a file with default parse & resolve options .
53
17
23,523
protected Temporal parse ( String text , Mode mode ) { if ( StringUtils . isBlank ( text ) ) { return null ; } // try to parse the date as an ISO8601 date if ( text . length ( ) >= 16 ) { try { return OffsetDateTime . parse ( text ) . toZonedDateTime ( ) ; } catch ( Exception e ) { } } // split the text into numerical and text tokens Pattern pattern = Pattern . compile ( "([0-9]+|\\p{L}+)" ) ; Matcher matcher = pattern . matcher ( text ) ; List < String > tokens = new ArrayList <> ( ) ; while ( matcher . find ( ) ) { tokens . add ( matcher . group ( 0 ) ) ; } // get the possibilities for each token List < Map < Component , Integer > > tokenPossibilities = new ArrayList <> ( ) ; for ( String token : tokens ) { Map < Component , Integer > possibilities = getTokenPossibilities ( token , mode ) ; if ( possibilities . size ( ) > 0 ) { tokenPossibilities . add ( possibilities ) ; } } // see what valid sequences we can make List < Component [ ] > sequences = getPossibleSequences ( mode , tokenPossibilities . size ( ) , m_dateStyle ) ; outer : for ( Component [ ] sequence : sequences ) { Map < Component , Integer > match = new LinkedHashMap <> ( ) ; for ( int c = 0 ; c < sequence . length ; c ++ ) { Component component = sequence [ c ] ; Integer value = tokenPossibilities . get ( c ) . get ( component ) ; match . put ( component , value ) ; if ( value == null ) { continue outer ; } } // try to make a valid result from this and return if successful Temporal obj = makeResult ( match , m_now , m_timezone ) ; if ( obj != null ) { return obj ; } } return null ; }
Returns a date datetime or time depending on what information is available
426
13
23,524
protected static List < Component [ ] > getPossibleSequences ( Mode mode , int length , DateStyle dateStyle ) { List < Component [ ] > sequences = new ArrayList <> ( ) ; Component [ ] [ ] dateSequences = dateStyle . equals ( DateStyle . DAY_FIRST ) ? DATE_SEQUENCES_DAY_FIRST : DATE_SEQUENCES_MONTH_FIRST ; if ( mode == Mode . DATE || mode == Mode . AUTO ) { for ( Component [ ] seq : dateSequences ) { if ( seq . length == length ) { sequences . add ( seq ) ; } } } else if ( mode == Mode . TIME ) { for ( Component [ ] seq : TIME_SEQUENCES ) { if ( seq . length == length ) { sequences . add ( seq ) ; } } } if ( mode == Mode . DATETIME || mode == Mode . AUTO ) { for ( Component [ ] dateSeq : dateSequences ) { for ( Component [ ] timeSeq : TIME_SEQUENCES ) { if ( dateSeq . length + timeSeq . length == length ) { sequences . add ( ArrayUtils . addAll ( dateSeq , timeSeq ) ) ; } } } } return sequences ; }
Gets possible component sequences in the given mode
280
9
23,525
protected static Temporal makeResult ( Map < Component , Integer > values , LocalDate now , ZoneId timezone ) { LocalDate date = null ; LocalTime time = null ; if ( values . containsKey ( Component . MONTH ) ) { int year = yearFrom2Digits ( ExpressionUtils . getOrDefault ( values , Component . YEAR , now . getYear ( ) ) , now . getYear ( ) ) ; int month = values . get ( Component . MONTH ) ; int day = ExpressionUtils . getOrDefault ( values , Component . DAY , 1 ) ; try { date = LocalDate . of ( year , month , day ) ; } catch ( DateTimeException ex ) { return null ; // not a valid date } } if ( ( values . containsKey ( Component . HOUR ) && values . containsKey ( Component . MINUTE ) ) || values . containsKey ( Component . HOUR_AND_MINUTE ) ) { int hour , minute , second , nano ; if ( values . containsKey ( Component . HOUR_AND_MINUTE ) ) { int combined = values . get ( Component . HOUR_AND_MINUTE ) ; hour = combined / 100 ; minute = combined - ( hour * 100 ) ; second = 0 ; nano = 0 ; } else { hour = values . get ( Component . HOUR ) ; minute = values . get ( Component . MINUTE ) ; second = ExpressionUtils . getOrDefault ( values , Component . SECOND , 0 ) ; nano = ExpressionUtils . getOrDefault ( values , Component . NANO , 0 ) ; if ( hour < 12 && ExpressionUtils . getOrDefault ( values , Component . AM_PM , AM ) == PM ) { hour += 12 ; } else if ( hour == 12 && ExpressionUtils . getOrDefault ( values , Component . AM_PM , PM ) == AM ) { hour -= 12 ; } } try { time = LocalTime . of ( hour , minute , second , nano ) ; } catch ( DateTimeException ex ) { return null ; // not a valid time } } if ( values . containsKey ( Component . OFFSET ) ) { timezone = ZoneOffset . ofTotalSeconds ( values . get ( Component . OFFSET ) ) ; } if ( date != null && time != null ) { return ZonedDateTime . of ( date , time , timezone ) ; } else if ( date != null ) { return date ; } else if ( time != null ) { return ZonedDateTime . of ( now , time , timezone ) . toOffsetDateTime ( ) . toOffsetTime ( ) ; } else { return null ; } }
Makes a date or datetime or time object from a map of component values
568
16
23,526
protected static int yearFrom2Digits ( int shortYear , int currentYear ) { if ( shortYear < 100 ) { shortYear += currentYear - ( currentYear % 100 ) ; if ( Math . abs ( shortYear - currentYear ) >= 50 ) { if ( shortYear < currentYear ) { return shortYear + 100 ; } else { return shortYear - 100 ; } } } return shortYear ; }
Converts a relative 2 - digit year to an absolute 4 - digit year
87
15
23,527
protected static Map < String , Integer > loadMonthAliases ( String file ) throws IOException { InputStream in = DateParser . class . getClassLoader ( ) . getResourceAsStream ( file ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) ) ; Map < String , Integer > map = new HashMap <> ( ) ; String line ; int month = 1 ; while ( ( line = reader . readLine ( ) ) != null ) { for ( String alias : line . split ( "," ) ) { map . put ( alias , month ) ; } month ++ ; } reader . close ( ) ; return map ; }
Loads month aliases from the given resource file
140
9
23,528
public static Map < String , Object > createFormParamSignIn ( String username , String password , Boolean isSaml ) { if ( username == null ) { throw new IllegalArgumentException ( "Missing the required parameter 'username'" ) ; } if ( password == null ) { throw new IllegalArgumentException ( "Missing the required parameter 'password'" ) ; } Map < String , Object > formParams = new HashMap <> ( ) ; formParams . put ( "username" , username ) ; formParams . put ( "password" , password ) ; if ( isSaml != null ) { formParams . put ( "saml" , isSaml ) ; } return formParams ; }
Build form parameters to sign in
152
6
23,529
public static int toInteger ( Object value , EvaluationContext ctx ) { if ( value instanceof Boolean ) { return ( ( Boolean ) value ) ? 1 : 0 ; } else if ( value instanceof Integer ) { return ( Integer ) value ; } else if ( value instanceof BigDecimal ) { try { return ( ( BigDecimal ) value ) . setScale ( 0 , RoundingMode . HALF_UP ) . intValueExact ( ) ; } catch ( ArithmeticException ex ) { } } else if ( value instanceof String ) { try { return Integer . parseInt ( ( String ) value ) ; } catch ( NumberFormatException e ) { } } throw new EvaluationError ( "Can't convert '" + value + "' to an integer" ) ; }
Tries conversion of any value to an integer
164
9
23,530
public static BigDecimal toDecimal ( Object value , EvaluationContext ctx ) { if ( value instanceof Boolean ) { return ( ( Boolean ) value ) ? BigDecimal . ONE : BigDecimal . ZERO ; } else if ( value instanceof Integer ) { return new BigDecimal ( ( Integer ) value ) ; } else if ( value instanceof BigDecimal ) { return ( BigDecimal ) value ; } else if ( value instanceof String ) { try { return new BigDecimal ( ( String ) value ) ; } catch ( NumberFormatException e ) { } } throw new EvaluationError ( "Can't convert '" + value + "' to a decimal" ) ; }
Tries conversion of any value to a decimal
146
9
23,531
public static ZonedDateTime toDateTime ( Object value , EvaluationContext ctx ) { if ( value instanceof String ) { Temporal temporal = ctx . getDateParser ( ) . auto ( ( String ) value ) ; if ( temporal != null ) { return toDateTime ( temporal , ctx ) ; } } else if ( value instanceof LocalDate ) { return ( ( LocalDate ) value ) . atStartOfDay ( ctx . getTimezone ( ) ) ; } else if ( value instanceof ZonedDateTime ) { return ( ( ZonedDateTime ) value ) . withZoneSameInstant ( ctx . getTimezone ( ) ) ; } throw new EvaluationError ( "Can't convert '" + value + "' to a datetime" ) ; }
Tries conversion of any value to a date
165
9
23,532
public static OffsetTime toTime ( Object value , EvaluationContext ctx ) { if ( value instanceof String ) { OffsetTime time = ctx . getDateParser ( ) . time ( ( String ) value ) ; if ( time != null ) { return time ; } } else if ( value instanceof OffsetTime ) { return ( OffsetTime ) value ; } else if ( value instanceof ZonedDateTime ) { return ( ( ZonedDateTime ) value ) . toOffsetDateTime ( ) . toOffsetTime ( ) ; } throw new EvaluationError ( "Can't convert '" + value + "' to a time" ) ; }
Tries conversion of any value to a time
138
9
23,533
public static Pair < Object , Object > toSame ( Object value1 , Object value2 , EvaluationContext ctx ) { if ( value1 . getClass ( ) . equals ( value2 . getClass ( ) ) ) { return new ImmutablePair <> ( value1 , value2 ) ; } try { // try converting to two decimals return new ImmutablePair < Object , Object > ( toDecimal ( value1 , ctx ) , toDecimal ( value2 , ctx ) ) ; } catch ( EvaluationError ex ) { } try { // try converting to two dates Temporal d1 = toDateOrDateTime ( value1 , ctx ) ; Temporal d2 = toDateOrDateTime ( value2 , ctx ) ; if ( ! value1 . getClass ( ) . equals ( value2 . getClass ( ) ) ) { d1 = toDateTime ( d1 , ctx ) ; d2 = toDateTime ( d2 , ctx ) ; } return new ImmutablePair < Object , Object > ( d1 , d2 ) ; } catch ( EvaluationError ex ) { } // try converting to two strings return new ImmutablePair < Object , Object > ( toString ( value1 , ctx ) , toString ( value2 , ctx ) ) ; }
Converts a pair of arguments to their most - likely types . This deviates from Excel which doesn t auto convert values but is necessary for us to intuitively handle contact fields which don t use the correct value type
282
43
23,534
public static Parameter [ ] fromMethod ( Method method ) { Class < ? > [ ] types = method . getParameterTypes ( ) ; Annotation [ ] [ ] annotations = method . getParameterAnnotations ( ) ; int numParams = types . length ; Parameter [ ] params = new Parameter [ numParams ] ; for ( int p = 0 ; p < numParams ; p ++ ) { params [ p ] = new Parameter ( types [ p ] , annotations [ p ] ) ; } return params ; }
Returns an array of Parameter objects that represent all the parameters to the underlying method
112
16
23,535
public < T > T getAnnotation ( Class < T > annotationClass ) { for ( Annotation annotation : m_annotations ) { if ( annotation . annotationType ( ) . equals ( annotationClass ) ) { return ( T ) annotation ; } } return null ; }
Returns this element s annotation for the specified type if such an annotation is present else null
57
17
23,536
public static < T > List < T > slice ( List < T > list , Integer start , Integer stop ) { int size = list . size ( ) ; if ( start == null ) { start = 0 ; } else if ( start < 0 ) { start = size + start ; } if ( stop == null ) { stop = size ; } else if ( stop < 0 ) { stop = size + stop ; } if ( start >= size || stop <= 0 || start >= stop ) { return Collections . emptyList ( ) ; } start = Math . max ( 0 , start ) ; stop = Math . min ( size , stop ) ; return list . subList ( start , stop ) ; }
Slices a list Python style
145
7
23,537
public static BigDecimal decimalPow ( BigDecimal number , BigDecimal power ) { return new BigDecimal ( Math . pow ( number . doubleValue ( ) , power . doubleValue ( ) ) , MATH ) ; }
Pow for two decimals
50
7
23,538
public static BigDecimal decimalRound ( BigDecimal number , int numDigits , RoundingMode rounding ) { BigDecimal rounded = number . setScale ( numDigits , rounding ) ; if ( numDigits < 0 ) { rounded = rounded . setScale ( 0 , BigDecimal . ROUND_UNNECESSARY ) ; } return rounded ; }
Rounding for decimals with support for negative digits
78
11
23,539
public static String urlquote ( String text ) { try { return URLEncoder . encode ( text , "UTF-8" ) . replace ( "+" , "%20" ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( ex ) ; } }
Encodes text for inclusion in a URL query string . Should be equivalent to Django s urlquote function .
60
21
23,540
public static DateTimeFormatter getDateFormatter ( DateStyle dateStyle , boolean incTime ) { String format = dateStyle . equals ( DateStyle . DAY_FIRST ) ? "dd-MM-yyyy" : "MM-dd-yyyy" ; return DateTimeFormatter . ofPattern ( incTime ? format + " HH:mm" : format ) ; }
Gets a formatter for dates or datetimes
80
10
23,541
public static String [ ] tokenize ( String text ) { final int len = text . length ( ) ; if ( len == 0 ) { return ArrayUtils . EMPTY_STRING_ARRAY ; } final List < String > list = new ArrayList <> ( ) ; int i = 0 ; while ( i < len ) { char ch = text . charAt ( i ) ; int ch32 = text . codePointAt ( i ) ; if ( isSymbolChar ( ch32 ) ) { list . add ( new String ( Character . toChars ( ch32 ) ) ) ; i += Character . isHighSurrogate ( ch ) ? 2 : 1 ; continue ; } if ( isWordChar ( ch ) ) { int wordStart = i ; while ( i < len && isWordChar ( text . codePointAt ( i ) ) ) { i ++ ; } list . add ( text . substring ( wordStart , i ) ) ; continue ; } i ++ ; } return list . toArray ( new String [ list . size ( ) ] ) ; }
Tokenizes a string by splitting on non - word characters . This should be equivalent to splitting on \ W + in Python . The meaning of \ W is different in Android Java 7 Java 8 hence the non - use of regular expressions .
228
47
23,542
public static Instant parseJsonDate ( String value ) { if ( value == null ) { return null ; } return LocalDateTime . parse ( value , JSON_DATETIME_FORMAT ) . atOffset ( ZoneOffset . UTC ) . toInstant ( ) ; }
Parses an ISO8601 formatted time instant from a string value
58
14
23,543
public static < T > Map < String , T > toLowerCaseKeys ( Map < String , T > map ) { Map < String , T > res = new HashMap <> ( ) ; for ( Map . Entry < String , T > entry : map . entrySet ( ) ) { res . put ( entry . getKey ( ) . toLowerCase ( ) , entry . getValue ( ) ) ; } return res ; }
Returns a copy of the given map with lowercase keys
91
11
23,544
static boolean isSymbolChar ( int ch ) { int t = Character . getType ( ch ) ; return t == Character . MATH_SYMBOL || t == Character . CURRENCY_SYMBOL || t == Character . MODIFIER_SYMBOL || t == Character . OTHER_SYMBOL ; }
Returns whether the given character is a Unicode symbol
69
9
23,545
public static String _char ( EvaluationContext ctx , Object number ) { return "" + ( char ) Conversions . toInteger ( number , ctx ) ; }
Returns the character specified by a number
34
7
23,546
public static String clean ( EvaluationContext ctx , Object text ) { return Conversions . toString ( text , ctx ) . replaceAll ( "\\p{C}" , "" ) ; }
Removes all non - printable characters from a text string
41
12
23,547
public static String concatenate ( EvaluationContext ctx , Object ... args ) { StringBuilder sb = new StringBuilder ( ) ; for ( Object arg : args ) { sb . append ( Conversions . toString ( arg , ctx ) ) ; } return sb . toString ( ) ; }
Joins text strings into one text string
65
8
23,548
public static String fixed ( EvaluationContext ctx , Object number , @ IntegerDefault ( 2 ) Object decimals , @ BooleanDefault ( false ) Object noCommas ) { BigDecimal _number = Conversions . toDecimal ( number , ctx ) ; _number = _number . setScale ( Conversions . toInteger ( decimals , ctx ) , RoundingMode . HALF_UP ) ; DecimalFormat format = new DecimalFormat ( ) ; format . setMaximumFractionDigits ( 9 ) ; format . setGroupingUsed ( ! Conversions . toBoolean ( noCommas , ctx ) ) ; return format . format ( _number ) ; }
Formats the given number in decimal format using a period and commas
146
14
23,549
public static String left ( EvaluationContext ctx , Object text , Object numChars ) { int _numChars = Conversions . toInteger ( numChars , ctx ) ; if ( _numChars < 0 ) { throw new RuntimeException ( "Number of chars can't be negative" ) ; } return StringUtils . left ( Conversions . toString ( text , ctx ) , _numChars ) ; }
Returns the first characters in a text string
92
8
23,550
public static int len ( EvaluationContext ctx , Object text ) { return Conversions . toString ( text , ctx ) . length ( ) ; }
Returns the number of characters in a text string
32
9
23,551
public static String lower ( EvaluationContext ctx , Object text ) { return Conversions . toString ( text , ctx ) . toLowerCase ( ) ; }
Converts a text string to lowercase
34
8
23,552
public static String proper ( EvaluationContext ctx , Object text ) { String _text = Conversions . toString ( text , ctx ) . toLowerCase ( ) ; if ( ! StringUtils . isEmpty ( _text ) ) { char [ ] buffer = _text . toCharArray ( ) ; boolean capitalizeNext = true ; for ( int i = 0 ; i < buffer . length ; ++ i ) { char ch = buffer [ i ] ; if ( ! Character . isAlphabetic ( ch ) ) { capitalizeNext = true ; } else if ( capitalizeNext ) { buffer [ i ] = Character . toTitleCase ( ch ) ; capitalizeNext = false ; } } return new String ( buffer ) ; } else { return _text ; } }
Capitalizes the first letter of every word in a text string
160
12
23,553
public static String rept ( EvaluationContext ctx , Object text , Object numberTimes ) { int _numberTimes = Conversions . toInteger ( numberTimes , ctx ) ; if ( _numberTimes < 0 ) { throw new RuntimeException ( "Number of times can't be negative" ) ; } return StringUtils . repeat ( Conversions . toString ( text , ctx ) , _numberTimes ) ; }
Repeats text a given number of times
87
8
23,554
public static String substitute ( EvaluationContext ctx , Object text , Object oldText , Object newText , @ IntegerDefault ( - 1 ) Object instanceNum ) { String _text = Conversions . toString ( text , ctx ) ; String _oldText = Conversions . toString ( oldText , ctx ) ; String _newText = Conversions . toString ( newText , ctx ) ; int _instanceNum = Conversions . toInteger ( instanceNum , ctx ) ; if ( _instanceNum < 0 ) { return _text . replace ( _oldText , _newText ) ; } else { String [ ] splits = _text . split ( _oldText ) ; StringBuilder output = new StringBuilder ( splits [ 0 ] ) ; for ( int s = 1 ; s < splits . length ; s ++ ) { String sep = s == _instanceNum ? _newText : _oldText ; output . append ( sep ) ; output . append ( splits [ s ] ) ; } return output . toString ( ) ; } }
Substitutes new_text for old_text in a text string
221
14
23,555
public static String unichar ( EvaluationContext ctx , Object number ) { return "" + ( char ) Conversions . toInteger ( number , ctx ) ; }
Returns the unicode character specified by a number
35
9
23,556
public static int unicode ( EvaluationContext ctx , Object text ) { String _text = Conversions . toString ( text , ctx ) ; if ( _text . length ( ) == 0 ) { throw new RuntimeException ( "Text can't be empty" ) ; } return ( int ) _text . charAt ( 0 ) ; }
Returns a numeric code for the first character in a text string
72
12
23,557
public static String upper ( EvaluationContext ctx , Object text ) { return Conversions . toString ( text , ctx ) . toUpperCase ( ) ; }
Converts a text string to uppercase
35
9
23,558
public static LocalDate date ( EvaluationContext ctx , Object year , Object month , Object day ) { return LocalDate . of ( Conversions . toInteger ( year , ctx ) , Conversions . toInteger ( month , ctx ) , Conversions . toInteger ( day , ctx ) ) ; }
Defines a date value
65
5
23,559
public static int datedif ( EvaluationContext ctx , Object startDate , Object endDate , Object unit ) { LocalDate _startDate = Conversions . toDate ( startDate , ctx ) ; LocalDate _endDate = Conversions . toDate ( endDate , ctx ) ; String _unit = Conversions . toString ( unit , ctx ) . toLowerCase ( ) ; if ( _startDate . isAfter ( _endDate ) ) { throw new RuntimeException ( "Start date cannot be after end date" ) ; } switch ( _unit ) { case "y" : return ( int ) ChronoUnit . YEARS . between ( _startDate , _endDate ) ; case "m" : return ( int ) ChronoUnit . MONTHS . between ( _startDate , _endDate ) ; case "d" : return ( int ) ChronoUnit . DAYS . between ( _startDate , _endDate ) ; case "md" : return Period . between ( _startDate , _endDate ) . getDays ( ) ; case "ym" : return Period . between ( _startDate , _endDate ) . getMonths ( ) ; case "yd" : return ( int ) ChronoUnit . DAYS . between ( _startDate . withYear ( _endDate . getYear ( ) ) , _endDate ) ; } throw new RuntimeException ( "Invalid unit value: " + _unit ) ; }
Calculates the number of days months or years between two dates .
310
14
23,560
public static LocalDate datevalue ( EvaluationContext ctx , Object text ) { return Conversions . toDate ( text , ctx ) ; }
Converts date stored in text to an actual date
30
10
23,561
public static int days ( EvaluationContext ctx , Object endDate , Object startDate ) { return datedif ( ctx , startDate , endDate , "d" ) ; }
Returns the number of days between two dates .
38
9
23,562
public static Temporal edate ( EvaluationContext ctx , Object date , Object months ) { Temporal dateOrDateTime = Conversions . toDateOrDateTime ( date , ctx ) ; int _months = Conversions . toInteger ( months , ctx ) ; return dateOrDateTime . plus ( _months , ChronoUnit . MONTHS ) ; }
Moves a date by the given number of months
78
10
23,563
public static OffsetTime time ( EvaluationContext ctx , Object hours , Object minutes , Object seconds ) { int _hours = Conversions . toInteger ( hours , ctx ) ; int _minutes = Conversions . toInteger ( minutes , ctx ) ; int _seconds = Conversions . toInteger ( seconds , ctx ) ; LocalTime localTime = LocalTime . of ( _hours , _minutes , _seconds ) ; return ZonedDateTime . of ( LocalDate . now ( ctx . getTimezone ( ) ) , localTime , ctx . getTimezone ( ) ) . toOffsetDateTime ( ) . toOffsetTime ( ) ; }
Defines a time value
142
5
23,564
public static OffsetTime timevalue ( EvaluationContext ctx , Object text ) { return Conversions . toTime ( text , ctx ) ; }
Converts time stored in text to an actual time
31
10
23,565
public static LocalDate today ( EvaluationContext ctx ) { return ctx . getNow ( ) . atZone ( ctx . getTimezone ( ) ) . toLocalDate ( ) ; }
Returns the current date
41
4
23,566
public static int year ( EvaluationContext ctx , Object date ) { return Conversions . toDateOrDateTime ( date , ctx ) . get ( ChronoField . YEAR ) ; }
Returns only the year of a date
40
7
23,567
public static BigDecimal abs ( EvaluationContext ctx , Object number ) { return Conversions . toDecimal ( number , ctx ) . abs ( ) ; }
Returns the absolute value of a number
35
7
23,568
public static BigDecimal exp ( EvaluationContext ctx , Object number ) { BigDecimal _number = Conversions . toDecimal ( number , ctx ) ; return ExpressionUtils . decimalPow ( E , _number ) ; }
Returns e raised to the power of number
51
8
23,569
public static int _int ( EvaluationContext ctx , Object number ) { return Conversions . toDecimal ( number , ctx ) . setScale ( 0 , RoundingMode . FLOOR ) . intValue ( ) ; }
Rounds a number down to the nearest integer
49
9
23,570
public static BigDecimal min ( EvaluationContext ctx , Object ... args ) { if ( args . length == 0 ) { throw new RuntimeException ( "Wrong number of arguments" ) ; } BigDecimal result = null ; for ( Object arg : args ) { BigDecimal _arg = Conversions . toDecimal ( arg , ctx ) ; result = result != null ? _arg . min ( result ) : _arg ; } return result ; }
Returns the minimum of all arguments
97
6
23,571
public static BigDecimal mod ( EvaluationContext ctx , Object number , Object divisor ) { BigDecimal _number = Conversions . toDecimal ( number , ctx ) ; BigDecimal _divisor = Conversions . toDecimal ( divisor , ctx ) ; return _number . subtract ( _divisor . multiply ( new BigDecimal ( _int ( ctx , _number . divide ( _divisor , 10 , RoundingMode . HALF_UP ) ) ) ) ) ; }
Returns the remainder after number is divided by divisor
114
11
23,572
public static BigDecimal power ( EvaluationContext ctx , Object number , Object power ) { BigDecimal _number = Conversions . toDecimal ( number , ctx ) ; BigDecimal _power = Conversions . toDecimal ( power , ctx ) ; return ExpressionUtils . decimalPow ( _number , _power ) ; }
Returns the result of a number raised to a power
74
10
23,573
public static int randbetween ( EvaluationContext ctx , Object bottom , Object top ) { int _bottom = Conversions . toInteger ( bottom , ctx ) ; int _top = Conversions . toInteger ( top , ctx ) ; return ( int ) ( Math . random ( ) * ( _top + 1 - _bottom ) ) + _bottom ; }
Returns a random integer number between the numbers you specify
76
10
23,574
public static BigDecimal round ( EvaluationContext ctx , Object number , Object numDigits ) { BigDecimal _number = Conversions . toDecimal ( number , ctx ) ; int _numDigits = Conversions . toInteger ( numDigits , ctx ) ; return ExpressionUtils . decimalRound ( _number , _numDigits , RoundingMode . HALF_UP ) ; }
Rounds a number to a specified number of digits
87
10
23,575
public static BigDecimal rounddown ( EvaluationContext ctx , Object number , Object numDigits ) { BigDecimal _number = Conversions . toDecimal ( number , ctx ) ; int _numDigits = Conversions . toInteger ( numDigits , ctx ) ; return ExpressionUtils . decimalRound ( _number , _numDigits , RoundingMode . DOWN ) ; }
Rounds a number down toward zero
85
7
23,576
public static BigDecimal roundup ( EvaluationContext ctx , Object number , Object numDigits ) { BigDecimal _number = Conversions . toDecimal ( number , ctx ) ; int _numDigits = Conversions . toInteger ( numDigits , ctx ) ; return ExpressionUtils . decimalRound ( _number , _numDigits , RoundingMode . UP ) ; }
Rounds a number up away from zero
84
8
23,577
public static BigDecimal sum ( EvaluationContext ctx , Object ... args ) { if ( args . length == 0 ) { throw new RuntimeException ( "Wrong number of arguments" ) ; } BigDecimal result = BigDecimal . ZERO ; for ( Object arg : args ) { result = result . add ( Conversions . toDecimal ( arg , ctx ) ) ; } return result ; }
Returns the sum of all arguments
86
6
23,578
public static int trunc ( EvaluationContext ctx , Object number ) { return Conversions . toDecimal ( number , ctx ) . setScale ( 0 , RoundingMode . DOWN ) . intValue ( ) ; }
Truncates a number to an integer by removing the fractional part of the number
46
17
23,579
public static boolean and ( EvaluationContext ctx , Object ... args ) { for ( Object arg : args ) { if ( ! Conversions . toBoolean ( arg , ctx ) ) { return false ; } } return true ; }
Returns TRUE if and only if all its arguments evaluate to TRUE
49
12
23,580
public static Object _if ( EvaluationContext ctx , Object logicalTest , @ IntegerDefault ( 0 ) Object valueIfTrue , @ BooleanDefault ( false ) Object valueIfFalse ) { return Conversions . toBoolean ( logicalTest , ctx ) ? valueIfTrue : valueIfFalse ; }
Returns one value if the condition evaluates to TRUE and another value if it evaluates to FALSE
62
17
23,581
public ApiResponse < ModelApiResponse > pingWithHttpInfo ( ) throws ApiException { com . squareup . okhttp . Call call = pingValidateBeforeCall ( null , null ) ; Type localVarReturnType = new TypeToken < ModelApiResponse > ( ) { } . getType ( ) ; return apiClient . execute ( call , localVarReturnType ) ; }
Check connection Return 200 if user is authenticated otherwise 403
83
10
23,582
public ApiResponse < Object > retrievePCTokenUsingPOSTWithHttpInfo ( ) throws ApiException { com . squareup . okhttp . Call call = retrievePCTokenUsingPOSTValidateBeforeCall ( null , null ) ; Type localVarReturnType = new TypeToken < Object > ( ) { } . getType ( ) ; return apiClient . execute ( call , localVarReturnType ) ; }
Retrieve PC token Returns PC token
87
7
23,583
public static String field ( EvaluationContext ctx , Object text , Object index , @ StringDefault ( " " ) Object delimiter ) { String _text = Conversions . toString ( text , ctx ) ; int _index = Conversions . toInteger ( index , ctx ) ; String _delimiter = Conversions . toString ( delimiter , ctx ) ; String [ ] splits = StringUtils . splitByWholeSeparator ( _text , _delimiter ) ; if ( _index < 1 ) { throw new RuntimeException ( "Field index cannot be less than 1" ) ; } if ( _index <= splits . length ) { return splits [ _index - 1 ] ; } else { return "" ; } }
Reference a field in string separated by a delimiter
157
10
23,584
public static String first_word ( EvaluationContext ctx , Object text ) { // In Excel this would be IF(ISERR(FIND(" ",A2)),"",LEFT(A2,FIND(" ",A2)-1)) return word ( ctx , text , 1 , false ) ; }
Returns the first word in the given text string
66
9
23,585
public static String percent ( EvaluationContext ctx , Object number ) { BigDecimal percent = Conversions . toDecimal ( number , ctx ) . multiply ( new BigDecimal ( 100 ) ) ; return Conversions . toInteger ( percent , ctx ) + "%" ; }
Formats a number as a percentage
60
7
23,586
public static BigDecimal epoch ( EvaluationContext ctx , Object datetime ) { Instant instant = Conversions . toDateTime ( datetime , ctx ) . toInstant ( ) ; BigDecimal nanos = new BigDecimal ( instant . getEpochSecond ( ) * 1000000000 + instant . getNano ( ) ) ; return nanos . divide ( new BigDecimal ( 1000000000 ) ) ; }
Converts the given date to the number of nanoseconds since January 1st 1970 UTC
88
19
23,587
public static String read_digits ( EvaluationContext ctx , Object text ) { String _text = Conversions . toString ( text , ctx ) . trim ( ) ; if ( StringUtils . isEmpty ( _text ) ) { return "" ; } // trim off the plus for phone numbers if ( _text . startsWith ( "+" ) ) { _text = _text . substring ( 1 ) ; } if ( _text . length ( ) == 9 ) { // SSN return StringUtils . join ( _text . substring ( 0 , 3 ) . toCharArray ( ) , ' ' ) + " , " + StringUtils . join ( _text . substring ( 3 , 5 ) . toCharArray ( ) , ' ' ) + " , " + StringUtils . join ( _text . substring ( 5 ) . toCharArray ( ) , ' ' ) ; } else if ( _text . length ( ) % 3 == 0 && _text . length ( ) > 3 ) { // triplets, most international phone numbers List < String > chunks = chunk ( _text , 3 ) ; return StringUtils . join ( StringUtils . join ( chunks , ' ' ) . toCharArray ( ) , ' ' ) ; } else if ( _text . length ( ) % 4 == 0 ) { // quads, credit cards List < String > chunks = chunk ( _text , 4 ) ; return StringUtils . join ( StringUtils . join ( chunks , ' ' ) . toCharArray ( ) , ' ' ) ; } else { // otherwise, just put a comma between each number return StringUtils . join ( _text . toCharArray ( ) , ' ' ) ; } }
Formats digits in text for reading in TTS
368
10
23,588
public static String remove_first_word ( EvaluationContext ctx , Object text ) { String _text = StringUtils . stripStart ( Conversions . toString ( text , ctx ) , null ) ; String firstWord = first_word ( ctx , _text ) ; if ( StringUtils . isNotEmpty ( firstWord ) ) { return StringUtils . stripStart ( _text . substring ( firstWord . length ( ) ) , null ) ; } else { return "" ; } }
Removes the first word from the given text string
107
10
23,589
public static String word ( EvaluationContext ctx , Object text , Object number , @ BooleanDefault ( false ) Object bySpaces ) { return word_slice ( ctx , text , number , Conversions . toInteger ( number , ctx ) + 1 , bySpaces ) ; }
Extracts the nth word from the given text string
60
12
23,590
public static int word_count ( EvaluationContext ctx , Object text , @ BooleanDefault ( false ) Object bySpaces ) { String _text = Conversions . toString ( text , ctx ) ; boolean _bySpaces = Conversions . toBoolean ( bySpaces , ctx ) ; return getWords ( _text , _bySpaces ) . size ( ) ; }
Returns the number of words in the given text string
82
10
23,591
public static String word_slice ( EvaluationContext ctx , Object text , Object start , @ IntegerDefault ( 0 ) Object stop , @ BooleanDefault ( false ) Object bySpaces ) { String _text = Conversions . toString ( text , ctx ) ; int _start = Conversions . toInteger ( start , ctx ) ; Integer _stop = Conversions . toInteger ( stop , ctx ) ; boolean _bySpaces = Conversions . toBoolean ( bySpaces , ctx ) ; if ( _start == 0 ) { throw new RuntimeException ( "Start word cannot be zero" ) ; } else if ( _start > 0 ) { _start -= 1 ; // convert to a zero-based offset } if ( _stop == 0 ) { // zero is treated as no end _stop = null ; } else if ( _stop > 0 ) { _stop -= 1 ; // convert to a zero-based offset } List < String > words = getWords ( _text , _bySpaces ) ; List < String > selection = ExpressionUtils . slice ( words , _start , _stop ) ; // re-combine selected words with a single space return StringUtils . join ( selection , ' ' ) ; }
Extracts a substring spanning from start up to but not - including stop
262
16
23,592
public static String format_date ( EvaluationContext ctx , Object text ) { ZonedDateTime _dt = Conversions . toDateTime ( text , ctx ) . withZoneSameInstant ( ctx . getTimezone ( ) ) ; return ctx . getDateFormatter ( true ) . format ( _dt ) ; }
Formats a date according to the default org format
70
10
23,593
public static String regex_group ( EvaluationContext ctx , Object text , Object pattern , Object groupNum ) { String _text = Conversions . toString ( text , ctx ) ; String _pattern = Conversions . toString ( pattern , ctx ) ; int _groupNum = Conversions . toInteger ( groupNum , ctx ) ; try { // check whether we match int flags = Pattern . CASE_INSENSITIVE | Pattern . MULTILINE ; Pattern regex = Pattern . compile ( _pattern , flags ) ; Matcher matcher = regex . matcher ( _text ) ; if ( matcher . find ( ) ) { if ( _groupNum < 0 || _groupNum > matcher . groupCount ( ) ) { throw new RuntimeException ( "No such matching group " + _groupNum ) ; } return matcher . group ( _groupNum ) ; } } catch ( PatternSyntaxException ignored ) { } return "" ; }
Tries to match the text with the given pattern and returns the value of matching group
202
17
23,594
private static List < String > getWords ( String text , boolean bySpaces ) { if ( bySpaces ) { List < String > words = new ArrayList <> ( ) ; for ( String split : text . split ( "\\s+" ) ) { if ( StringUtils . isNotEmpty ( split ) ) { words . add ( split ) ; } } return words ; } else { return Arrays . asList ( ExpressionUtils . tokenize ( text ) ) ; } }
Helper function which splits the given text string into words . If by_spaces is false then text like 01 - 02 - 2014 will be split into 3 separate words . For backwards compatibility this is the default for all expression functions .
105
46
23,595
private static List < String > chunk ( String text , int size ) { List < String > chunks = new ArrayList <> ( ) ; for ( int i = 0 ; i < text . length ( ) ; i += size ) { chunks . add ( StringUtils . substring ( text , i , i + size ) ) ; } return chunks ; }
Splits a string into equally sized chunks
75
8
23,596
public CorsHeaderPlugin flag ( String flagValue ) { if ( isRegistered ( ) ) throw new UnsupportedOperationException ( "CorsHeaderPlugin.flag(String) must be called before register()" ) ; if ( ! flags . contains ( flagValue ) ) { flags . add ( flagValue ) ; } return this ; }
Set a flag on the automatically generated OPTIONS route for pre - flight CORS requests .
69
18
23,597
private void addPreflightOptionsRequestSupport ( RestExpress server , CorsOptionsController corsOptionsController ) { RouteBuilder rb ; for ( String pattern : methodsByPattern . keySet ( ) ) { rb = server . uri ( pattern , corsOptionsController ) . action ( "options" , HttpMethod . OPTIONS ) . noSerialization ( ) // Disable both authentication and authorization which are usually use header such as X-Authorization. // When browser does CORS preflight with OPTIONS request, such headers are not included. . flag ( Flags . Auth . PUBLIC_ROUTE ) . flag ( Flags . Auth . NO_AUTHORIZATION ) ; for ( String flag : flags ) { rb . flag ( flag ) ; } for ( Entry < String , Object > entry : parameters . entrySet ( ) ) { rb . parameter ( entry . getKey ( ) , entry . getValue ( ) ) ; } routeBuilders . add ( rb ) ; } }
Add an OPTIONS method supported on all routes for the pre - flight CORS request .
211
18
23,598
@ Override public void process ( Request request ) { String correlationId = request . getHeader ( CORRELATION_ID ) ; // Generation on empty causes problems, since the request already has a value for Correlation-Id in this case. // The method call request.addHeader() only adds ANOTHER header to the request and doesn't fix the problem. // Currently then, the plugin only adds the header if it doesn't exist, assuming that if a client sets the // header to ANYTHING, that's the correlation ID they desired. if ( correlationId == null ) // || correlationId.trim().isEmpty()) { correlationId = UUID . randomUUID ( ) . toString ( ) ; } RequestContext . put ( CORRELATION_ID , correlationId ) ; request . addHeader ( CORRELATION_ID , correlationId ) ; }
Preprocessor method to pull the Correlation - Id header or assign one as well as placing it in the RequestContext .
179
24
23,599
@ Override public void process ( Request request , Response response ) { if ( ! response . hasHeader ( CORRELATION_ID ) ) { response . addHeader ( CORRELATION_ID , request . getHeader ( CORRELATION_ID ) ) ; } }
Postprocessor method that assigns the Correlation - Id from the request to a header on the Response .
56
20