idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
23,500
public static long waitTillNextTick ( long currentTick , long tickSize ) { long nextBlock = System . currentTimeMillis ( ) / tickSize ; for ( ; nextBlock <= currentTick ; nextBlock = System . currentTimeMillis ( ) / tickSize ) { Thread . yield ( ) ; } return nextBlock ; }
Waits till clock moves to the next tick .
23,501
synchronized public long generateId48 ( ) { final long blockSize = 1000L ; long timestamp = System . currentTimeMillis ( ) / blockSize ; long sequence = 0 ; boolean done = false ; while ( ! done ) { done = true ; while ( timestamp < lastTimestampMillisec . get ( ) / blockSize ) { timestamp = waitTillNextSecond ( timest...
Generates a 48 - bit id .
23,502
synchronized public long generateId64 ( ) { long timestamp = System . currentTimeMillis ( ) ; long sequence = 0 ; boolean done = false ; while ( ! done ) { done = true ; while ( timestamp < lastTimestampMillisec . get ( ) ) { timestamp = waitTillNextMillisec ( timestamp ) ; } if ( timestamp == lastTimestampMillisec . g...
Generates a 64 - bit id .
23,503
synchronized public BigInteger generateId128 ( ) { long timestamp = System . currentTimeMillis ( ) ; long sequence = 0 ; boolean done = false ; while ( ! done ) { done = true ; while ( timestamp < lastTimestampMillisec . get ( ) ) { timestamp = waitTillNextMillisec ( timestamp ) ; } if ( timestamp == lastTimestampMilli...
Generates a 128 - bit id .
23,504
public static RSAPublicKey buildPublicKey ( String base64KeyData ) throws NoSuchAlgorithmException , InvalidKeySpecException { byte [ ] keyData = Base64 . getDecoder ( ) . decode ( base64KeyData ) ; return buildPublicKey ( keyData ) ; }
Construct the RSA public key from a key string data .
23,505
public static RSAPublicKey buildPublicKey ( byte [ ] keyData ) throws NoSuchAlgorithmException , InvalidKeySpecException { X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec ( keyData ) ; KeyFactory keyFactory = KeyFactory . getInstance ( CIPHER_ALGORITHM ) ; PublicKey generatePublic = keyFactory . generatePubli...
Construct the RSA public key from a key binary data .
23,506
public static RSAPrivateKey buildPrivateKey ( final byte [ ] keyData ) throws NoSuchAlgorithmException , InvalidKeySpecException { PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec ( keyData ) ; KeyFactory keyFactory = KeyFactory . getInstance ( CIPHER_ALGORITHM ) ; PrivateKey generatePrivate = keyFactory . ...
Construct the RSA private key from a key binary data .
23,507
public static RSAPrivateKey buildPrivateKey ( final String base64KeyData ) throws NoSuchAlgorithmException , InvalidKeySpecException { byte [ ] keyData = Base64 . getDecoder ( ) . decode ( base64KeyData ) ; return buildPrivateKey ( keyData ) ; }
Construct the RSA private key from a key string data .
23,508
public static KeyPair generateKeys ( int numBits ) throws NoSuchAlgorithmException { int numBitsPow2 = 1 ; while ( numBitsPow2 < numBits ) { numBitsPow2 <<= 1 ; } KeyPairGenerator kpg = KeyPairGenerator . getInstance ( CIPHER_ALGORITHM ) ; kpg . initialize ( numBitsPow2 , SECURE_RNG ) ; KeyPair keyPair = kpg . generate...
Generate a random RSA keypair .
23,509
public static CloseableHttpClient newHttpClient ( ) { final SocketConfig socketConfig = SocketConfig . custom ( ) . setSoKeepAlive ( Boolean . TRUE ) . setTcpNoDelay ( Boolean . TRUE ) . setSoTimeout ( SOCKET_TIMEOUT_MS ) . build ( ) ; final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionMa...
Get a new CloseableHttpClient
23,510
public SnowizardResponse executeRequest ( final String host , final int count ) throws IOException { final String uri = String . format ( "http://%s/?count=%d" , host , count ) ; final HttpGet request = new HttpGet ( uri ) ; request . addHeader ( HttpHeaders . ACCEPT , ProtocolBufferMediaType . APPLICATION_PROTOBUF ) ;...
Execute a request to the Snowizard service URL
23,511
public long getId ( ) throws SnowizardClientException { for ( final String host : hosts ) { try { final SnowizardResponse snowizard = executeRequest ( host ) ; if ( snowizard != null ) { return snowizard . getId ( 0 ) ; } } catch ( final Exception ex ) { LOGGER . warn ( "Unable to get ID from host ({})" , host ) ; } } ...
Get a new ID from Snowizard
23,512
public List < Long > getIds ( final int count ) throws SnowizardClientException { for ( final String host : hosts ) { try { final SnowizardResponse snowizard = executeRequest ( host , count ) ; if ( snowizard != null ) { return snowizard . getIdList ( ) ; } } catch ( final Exception ex ) { LOGGER . warn ( "Unable to ge...
Get multiple IDs from Snowizard
23,513
protected String resolveAvailable ( CommonTokenStream tokens , EvaluationContext context ) { boolean hasMissing = false ; List < Object > outputComponents = new ArrayList < > ( ) ; for ( int t = 0 ; t < tokens . size ( ) - 1 ; t ++ ) { Token token = tokens . get ( t ) ; Token nextToken = tokens . get ( t + 1 ) ; if ( t...
Checks the token stream for context references and if there are missing references - substitutes available references and returns a partially evaluated expression .
23,514
public static Object getSpringBean ( ApplicationContext appContext , String id ) { try { Object bean = appContext . getBean ( id ) ; return bean ; } catch ( BeansException e ) { return null ; } }
Gets a bean by its id .
23,515
public static < T > T getBean ( ApplicationContext appContext , String id , Class < T > clazz ) { try { return appContext . getBean ( id , clazz ) ; } catch ( BeansException e ) { return null ; } }
Gets a bean by its id and class .
23,516
public static < T > Map < String , T > getBeansOfType ( ApplicationContext appContext , Class < T > clazz ) { try { return appContext . getBeansOfType ( clazz ) ; } catch ( BeansException e ) { return new HashMap < String , T > ( ) ; } }
Gets all beans of a given type .
23,517
public static Map < String , Object > getBeansWithAnnotation ( ApplicationContext appContext , Class < ? extends Annotation > annotationType ) { try { return appContext . getBeansWithAnnotation ( annotationType ) ; } catch ( BeansException e ) { return new HashMap < String , Object > ( ) ; } }
Gets all beans whose Class has the supplied Annotation type .
23,518
public MetricsPlugin register ( RestExpress server ) { if ( isRegistered ) return this ; server . registerPlugin ( this ) ; this . isRegistered = true ; server . addMessageObserver ( this ) . addPreprocessor ( this ) . addFinallyProcessor ( this ) ; return this ; }
Register the MetricsPlugin with the RestExpress server .
23,519
public void process ( Request request , Response response ) { Long duration = computeDurationMillis ( START_TIMES_BY_CORRELATION_ID . get ( request . getCorrelationId ( ) ) ) ; if ( duration != null && duration . longValue ( ) > 0 ) { response . addHeader ( "X-Response-Time" , String . valueOf ( duration ) ) ; } }
Set the X - Response - Time header to the response time in milliseconds .
23,520
public static boolean isValidIp ( String ip ) { if ( ! IP_PATTERN_FULL . matcher ( ip ) . matches ( ) ) { return false ; } String [ ] ipArr = ip . split ( "\\." ) ; for ( String part : ipArr ) { int v = Integer . parseInt ( part ) ; if ( v < 0 || v > 255 ) { return false ; } } return true ; }
Check is an IP is valid .
23,521
public static String normalisedVersion ( String version , String sep , int maxWidth ) { if ( version == null ) { return null ; } String [ ] split = Pattern . compile ( sep , Pattern . LITERAL ) . split ( version ) ; StringBuilder sb = new StringBuilder ( ) ; for ( String s : split ) { sb . append ( String . format ( "%...
Normalizes a version string .
23,522
public long getEstimateNumKeys ( String cfName ) throws RocksDbException { String prop = getProperty ( cfName , "rocksdb.estimate-num-keys" ) ; return prop != null ? Long . parseLong ( prop ) : 0 ; }
Gets estimated number of keys for a column family .
23,523
public RocksIterator getIterator ( String cfName ) { synchronized ( iterators ) { RocksIterator it = iterators . get ( cfName ) ; if ( it == null ) { ColumnFamilyHandle cfh = getColumnFamilyHandle ( cfName ) ; if ( cfh == null ) { return null ; } it = rocksDb . newIterator ( cfh , readOptions ) ; iterators . put ( cfNa...
Obtains an iterator for a column family .
23,524
public void delete ( WriteOptions writeOptions , String key ) throws RocksDbException { delete ( DEFAULT_COLUMN_FAMILY , writeOptions , key ) ; }
Deletes a key from the default family specifying write options . F
23,525
public void delete ( String cfName , String key ) throws RocksDbException { delete ( cfName , writeOptions , key ) ; }
Deletes a key from a column family .
23,526
public void delete ( String cfName , WriteOptions writeOptions , String key ) throws RocksDbException { if ( cfName == null ) { cfName = DEFAULT_COLUMN_FAMILY ; } try { delete ( getColumnFamilyHandle ( cfName ) , writeOptions , key . getBytes ( StandardCharsets . UTF_8 ) ) ; } catch ( RocksDbException . ColumnFamilyNot...
Deletes a key from a column family specifying write options .
23,527
public byte [ ] get ( ReadOptions readOPtions , String key ) throws RocksDbException { return get ( DEFAULT_COLUMN_FAMILY , readOPtions , key ) ; }
Gets a value from the default column family specifying read options .
23,528
public byte [ ] get ( String cfName , String key ) throws RocksDbException { return get ( cfName , readOptions , key ) ; }
Gets a value from a column family .
23,529
public byte [ ] get ( String cfName , ReadOptions readOptions , String key ) throws RocksDbException { if ( cfName == null ) { cfName = DEFAULT_COLUMN_FAMILY ; } ColumnFamilyHandle cfh = columnFamilyHandles . get ( cfName ) ; if ( cfh == null ) { throw new RocksDbException . ColumnFamilyNotExists ( cfName ) ; } return ...
Gets a value from a column family specifying read options .
23,530
protected byte [ ] get ( ColumnFamilyHandle cfh , ReadOptions readOptions , byte [ ] key ) throws RocksDbException { try { return rocksDb . get ( cfh , readOptions != null ? readOptions : this . readOptions , key ) ; } catch ( Exception e ) { throw e instanceof RocksDbException ? ( RocksDbException ) e : new RocksDbExc...
Gets a value .
23,531
protected String createCompleteMessage ( Request request , Response response , Timer timer ) { StringBuilder sb = new StringBuilder ( request . getEffectiveHttpMethod ( ) . toString ( ) ) ; sb . append ( " " ) ; sb . append ( request . getUrl ( ) ) ; if ( timer != null ) { sb . append ( " responded with " ) ; sb . appe...
Create the message to be logged when a request is completed successfully . Sub - classes can override .
23,532
protected String createExceptionMessage ( Throwable exception , Request request , Response response ) { StringBuilder sb = new StringBuilder ( request . getEffectiveHttpMethod ( ) . toString ( ) ) ; sb . append ( ' ' ) ; sb . append ( request . getUrl ( ) ) ; sb . append ( " threw exception: " ) ; sb . append ( excepti...
Create the message to be logged when a request results in an exception . Sub - classes can override .
23,533
public static void deleteValue ( Object target , String dPath ) { if ( target instanceof JsonNode ) { deleteValue ( ( JsonNode ) target , dPath ) ; return ; } String [ ] paths = splitDpath ( dPath ) ; Object cursor = target ; for ( int i = 0 ; i < paths . length - 1 ; i ++ ) { cursor = extractValue ( cursor , paths [ i...
Delete a value from the target object specified by DPath expression .
23,534
public static String toJsonString ( Object obj , ClassLoader classLoader ) { if ( obj == null ) { return "null" ; } ClassLoader oldClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( classLoader != null ) { Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; } try { ObjectMapper...
Serialize an object to JSON string with a custom class loader .
23,535
public static < T > T fromJsonString ( String jsonString , Class < T > clazz ) { return fromJsonString ( jsonString , clazz , null ) ; }
Deserialize a JSON string .
23,536
public void addLibrary ( Class < ? > library ) { for ( Method method : library . getDeclaredMethods ( ) ) { if ( ( method . getModifiers ( ) & Modifier . PUBLIC ) == 0 ) { continue ; } String name = method . getName ( ) . toLowerCase ( ) ; if ( name . startsWith ( "_" ) ) { name = name . substring ( 1 ) ; } m_functions...
Adds functions from a library class
23,537
public Object invokeFunction ( EvaluationContext ctx , String name , List < Object > args ) { Method func = getFunction ( name ) ; if ( func == null ) { throw new EvaluationError ( "Undefined function: " + name ) ; } List < Object > parameters = new ArrayList < > ( ) ; List < Object > remainingArgs = new ArrayList < > ...
Invokes a function
23,538
public List < FunctionDescriptor > buildListing ( ) { List < FunctionDescriptor > listing = new ArrayList < > ( ) ; for ( Map . Entry < String , Method > entry : m_functions . entrySet ( ) ) { FunctionDescriptor descriptor = new FunctionDescriptor ( entry . getKey ( ) . toUpperCase ( ) ) ; listing . add ( descriptor ) ...
Builds a listing of all functions sorted A - Z . Unlike the Python port this only returns function names as Java doesn t so easily support reading of docstrings and Java 7 doesn t provide access to parameter names .
23,539
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 .
23,540
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 .
23,541
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 .
23,542
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 .
23,543
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 .
23,544
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...
Perform a GET request .
23,545
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 (...
Perform a POST request .
23,546
public RequestResponse doDelete ( String url , Map < String , Object > headers , Map < String , Object > urlParams ) { return doDelete ( url , headers , urlParams , null ) ; }
Perform a DELETE request .
23,547
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 .
23,548
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 .
23,549
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 !=...
Tells if a class is a sub - class of a super - class .
23,550
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
23,551
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 {}" , prevTim...
Get the next ID
23,552
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
23,553
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
23,554
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 Illegal...
Build query parameters
23,555
protected static Object coerceToSupportedType ( Object value ) { if ( value == null ) { return "" ; } else if ( value instanceof Map ) { Map valueAsMap = ( ( Map ) value ) ; if ( valueAsMap . containsKey ( "*" ) ) { return valueAsMap . get ( "*" ) ; } else if ( valueAsMap . containsKey ( "__default__" ) ) { return valu...
Since we let users populate the context with whatever they want this ensures the resolved value is something which the expression engine understands .
23,556
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 . ...
Serializes a thrift object to byte array .
23,557
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 = protocolFact...
Deserializes a thrift object from byte array .
23,558
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 .
23,559
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 . s...
Gets all available column family names from a RocksDb data directory .
23,560
@ 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 , c...
Convert a target object to a specified value type .
23,561
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 .
23,562
protected Temporal parse ( String text , Mode mode ) { if ( StringUtils . isBlank ( text ) ) { return null ; } if ( text . length ( ) >= 16 ) { try { return OffsetDateTime . parse ( text ) . toZonedDateTime ( ) ; } catch ( Exception e ) { } } Pattern pattern = Pattern . compile ( "([0-9]+|\\p{L}+)" ) ; Matcher matcher ...
Returns a date datetime or time depending on what information is available
23,563
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 ==...
Gets possible component sequences in the given mode
23,564
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 ( ) ...
Makes a date or datetime or time object from a map of component values
23,565
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
23,566
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 < > ( ) ; Str...
Loads month aliases from the given resource file
23,567
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 param...
Build form parameters to sign in
23,568
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 , RoundingM...
Tries conversion of any value to an integer
23,569
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 ...
Tries conversion of any value to a decimal
23,570
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 ...
Tries conversion of any value to a date
23,571
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...
Tries conversion of any value to a time
23,572
public static Pair < Object , Object > toSame ( Object value1 , Object value2 , EvaluationContext ctx ) { if ( value1 . getClass ( ) . equals ( value2 . getClass ( ) ) ) { return new ImmutablePair < > ( value1 , value2 ) ; } try { return new ImmutablePair < Object , Object > ( toDecimal ( value1 , ctx ) , toDecimal ( v...
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
23,573
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 ++ ) { par...
Returns an array of Parameter objects that represent all the parameters to the underlying method
23,574
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
23,575
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...
Slices a list Python style
23,576
public static BigDecimal decimalPow ( BigDecimal number , BigDecimal power ) { return new BigDecimal ( Math . pow ( number . doubleValue ( ) , power . doubleValue ( ) ) , MATH ) ; }
Pow for two decimals
23,577
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
23,578
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 .
23,579
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
23,580
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 ( isSymbolCha...
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 .
23,581
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
23,582
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
23,583
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
23,584
public static String _char ( EvaluationContext ctx , Object number ) { return "" + ( char ) Conversions . toInteger ( number , ctx ) ; }
Returns the character specified by a number
23,585
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
23,586
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
23,587
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 ...
Formats the given number in decimal format using a period and commas
23,588
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
23,589
public static int len ( EvaluationContext ctx , Object text ) { return Conversions . toString ( text , ctx ) . length ( ) ; }
Returns the number of characters in a text string
23,590
public static String lower ( EvaluationContext ctx , Object text ) { return Conversions . toString ( text , ctx ) . toLowerCase ( ) ; }
Converts a text string to lowercase
23,591
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 =...
Capitalizes the first letter of every word in a text string
23,592
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 )...
Repeats text a given number of times
23,593
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...
Substitutes new_text for old_text in a text string
23,594
public static String unichar ( EvaluationContext ctx , Object number ) { return "" + ( char ) Conversions . toInteger ( number , ctx ) ; }
Returns the unicode character specified by a number
23,595
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
23,596
public static String upper ( EvaluationContext ctx , Object text ) { return Conversions . toString ( text , ctx ) . toUpperCase ( ) ; }
Converts a text string to uppercase
23,597
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
23,598
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...
Calculates the number of days months or years between two dates .
23,599
public static LocalDate datevalue ( EvaluationContext ctx , Object text ) { return Conversions . toDate ( text , ctx ) ; }
Converts date stored in text to an actual date