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 ( timestamp ) ; } if ( timestamp == lastTimestampMillisec . get ( ) / blockSize ) { sequence = sequenceMillisec . incrementAndGet ( ) ; if ( sequence > MAX_SEQUENCE_48 ) { sequenceMillisec . set ( sequence = 0 ) ; timestamp = waitTillNextSecond ( timestamp ) ; done = false ; } } } sequenceMillisec . set ( sequence ) ; lastTimestampMillisec . set ( timestamp * blockSize ) ; timestamp = ( ( timestamp * blockSize - TIMESTAMP_EPOCH ) / blockSize ) & MASK_TIMESTAMP_48 ; return timestamp << SHIFT_TIMESTAMP_48 | template48 | ( sequence & MASK_SEQUENCE_48 ) ; } | 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 . get ( ) ) { sequence = sequenceMillisec . incrementAndGet ( ) ; if ( sequence > MAX_SEQUENCE_64 ) { sequenceMillisec . set ( sequence = 0 ) ; timestamp = waitTillNextMillisec ( timestamp ) ; done = false ; } } } sequenceMillisec . set ( sequence ) ; lastTimestampMillisec . set ( timestamp ) ; timestamp = ( timestamp - TIMESTAMP_EPOCH ) & MASK_TIMESTAMP_64 ; return timestamp << SHIFT_TIMESTAMP_64 | template64 | ( sequence & MASK_SEQUENCE_64 ) ; } | 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 == lastTimestampMillisec . get ( ) ) { sequence = sequenceMillisec . incrementAndGet ( ) ; if ( sequence > MAX_SEQUENCE_128 ) { sequenceMillisec . set ( sequence = 0 ) ; timestamp = waitTillNextMillisec ( timestamp ) ; done = false ; } } } sequenceMillisec . set ( sequence ) ; lastTimestampMillisec . set ( timestamp ) ; BigInteger biSequence = BigInteger . valueOf ( sequence & MASK_SEQUENCE_128 ) ; BigInteger biResult = BigInteger . valueOf ( timestamp ) ; biResult = biResult . shiftLeft ( ( int ) SHIFT_TIMESTAMP_128 ) ; biResult = biResult . or ( template128 ) . or ( biSequence ) ; return biResult ; } | 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 . generatePublic ( publicKeySpec ) ; return ( RSAPublicKey ) generatePublic ; } | 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 . generatePrivate ( privateKeySpec ) ; return ( RSAPrivateKey ) generatePrivate ; } | 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 . generateKeyPair ( ) ; return keyPair ; } | 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 PoolingHttpClientConnectionManager ( ) ; manager . setDefaultMaxPerRoute ( MAX_HOSTS ) ; manager . setMaxTotal ( MAX_HOSTS ) ; manager . setDefaultSocketConfig ( socketConfig ) ; final RequestConfig requestConfig = RequestConfig . custom ( ) . setConnectTimeout ( CONNECTION_TIMEOUT_MS ) . setCookieSpec ( CookieSpecs . IGNORE_COOKIES ) . setStaleConnectionCheckEnabled ( Boolean . FALSE ) . setSocketTimeout ( SOCKET_TIMEOUT_MS ) . build ( ) ; final CloseableHttpClient client = HttpClients . custom ( ) . disableRedirectHandling ( ) . setConnectionManager ( manager ) . setDefaultRequestConfig ( requestConfig ) . setConnectionReuseStrategy ( new DefaultConnectionReuseStrategy ( ) ) . setConnectionBackoffStrategy ( new DefaultBackoffStrategy ( ) ) . setRetryHandler ( new DefaultHttpRequestRetryHandler ( MAX_RETRIES , false ) ) . setKeepAliveStrategy ( new DefaultConnectionKeepAliveStrategy ( ) ) . build ( ) ; return client ; } | 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 ) ; request . addHeader ( HttpHeaders . USER_AGENT , getUserAgent ( ) ) ; SnowizardResponse snowizard = null ; try { final BasicHttpContext context = new BasicHttpContext ( ) ; final HttpResponse response = client . execute ( request , context ) ; final int code = response . getStatusLine ( ) . getStatusCode ( ) ; if ( code == HttpStatus . SC_OK ) { final HttpEntity entity = response . getEntity ( ) ; if ( entity != null ) { snowizard = SnowizardResponse . parseFrom ( entity . getContent ( ) ) ; } EntityUtils . consumeQuietly ( entity ) ; } } finally { request . releaseConnection ( ) ; } return snowizard ; } | 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 ) ; } } throw new SnowizardClientException ( "Unable to generate ID from Snowizard" ) ; } | 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 get ID from host ({})" , host ) ; } } throw new SnowizardClientException ( "Unable to generate batch of IDs from Snowizard" ) ; } | 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 ( token . getType ( ) == ExcellentParser . NAME && nextToken . getType ( ) != ExcellentParser . LPAREN ) { try { outputComponents . add ( context . resolveVariable ( token . getText ( ) ) ) ; } catch ( EvaluationError ex ) { hasMissing = true ; outputComponents . add ( token ) ; } } else { outputComponents . add ( token ) ; } } if ( ! hasMissing ) { return null ; } StringBuilder output = new StringBuilder ( String . valueOf ( m_expressionPrefix ) ) ; for ( Object outputComponent : outputComponents ) { String compVal ; if ( outputComponent instanceof Token ) { compVal = ( ( Token ) outputComponent ) . getText ( ) ; } else { compVal = Conversions . toRepr ( outputComponent , context ) ; } output . append ( compVal ) ; } return output . toString ( ) ; } | 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 ( "%" + maxWidth + 's' , s ) ) ; } return sb . toString ( ) ; } | 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 ( cfName , it ) ; } return it ; } } | 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 . ColumnFamilyNotExists e ) { throw new RocksDbException . ColumnFamilyNotExists ( cfName ) ; } } | 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 get ( cfh , readOptions , key . getBytes ( StandardCharsets . UTF_8 ) ) ; } | 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 RocksDbException ( e ) ; } } | 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 . append ( response . getResponseStatus ( ) . toString ( ) ) ; sb . append ( " in " ) ; sb . append ( timer . toString ( ) ) ; } else { sb . append ( " responded with " ) ; sb . append ( response . getResponseStatus ( ) . toString ( ) ) ; sb . append ( " (no timer found)" ) ; } return sb . toString ( ) ; } | 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 ( exception . getClass ( ) . getSimpleName ( ) ) ; return sb . toString ( ) ; } | 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 ] ) ; } if ( cursor == null ) { return ; } String index = paths [ paths . length - 1 ] ; Matcher m = PATTERN_INDEX . matcher ( index ) ; if ( m . matches ( ) ) { try { int i = Integer . parseInt ( m . group ( 1 ) ) ; deleteFieldValue ( dPath , cursor , i ) ; } catch ( IndexOutOfBoundsException e ) { throw e ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Error: Invalid index. Path [" + dPath + "], target [" + cursor . getClass ( ) + "]." , e ) ; } } else { deleteFieldValue ( dPath , cursor , index ) ; } } | 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 mapper = poolMapper . borrowObject ( ) ; if ( mapper != null ) { try { return mapper . writeValueAsString ( obj ) ; } finally { poolMapper . returnObject ( mapper ) ; } } throw new SerializationException ( "No ObjectMapper instance avaialble!" ) ; } catch ( Exception e ) { throw e instanceof SerializationException ? ( SerializationException ) e : new SerializationException ( e ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; } } | 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 . put ( name , method ) ; } } | 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 < > ( args ) ; for ( Parameter param : Parameter . fromMethod ( func ) ) { BooleanDefault defaultBool = param . getAnnotation ( BooleanDefault . class ) ; IntegerDefault defaultInt = param . getAnnotation ( IntegerDefault . class ) ; StringDefault defaultStr = param . getAnnotation ( StringDefault . class ) ; if ( param . getType ( ) . equals ( EvaluationContext . class ) ) { parameters . add ( ctx ) ; } else if ( param . getType ( ) . isArray ( ) ) { parameters . add ( remainingArgs . toArray ( new Object [ remainingArgs . size ( ) ] ) ) ; remainingArgs . clear ( ) ; break ; } else if ( remainingArgs . size ( ) > 0 ) { Object arg = remainingArgs . remove ( 0 ) ; parameters . add ( arg ) ; } else if ( defaultBool != null ) { parameters . add ( defaultBool . value ( ) ) ; } else if ( defaultInt != null ) { parameters . add ( defaultInt . value ( ) ) ; } else if ( defaultStr != null ) { parameters . add ( defaultStr . value ( ) ) ; } else { throw new EvaluationError ( "Too few arguments provided for function " + name ) ; } } if ( ! remainingArgs . isEmpty ( ) ) { throw new EvaluationError ( "Too many arguments provided for function " + name ) ; } try { return func . invoke ( null , parameters . toArray ( new Object [ parameters . size ( ) ] ) ) ; } catch ( Exception e ) { List < String > prettyArgs = new ArrayList < > ( ) ; for ( Object arg : args ) { String pretty ; if ( arg instanceof String ) { pretty = "\"" + arg + "\"" ; } else { try { pretty = Conversions . toString ( arg , ctx ) ; } catch ( EvaluationError ex ) { pretty = arg . toString ( ) ; } } prettyArgs . add ( pretty ) ; } throw new EvaluationError ( "Error calling function " + name + " with arguments " + StringUtils . join ( prettyArgs , ", " ) , e ) ; } } | 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 ) ; } Collections . sort ( listing , new Comparator < FunctionDescriptor > ( ) { public int compare ( FunctionDescriptor f1 , FunctionDescriptor f2 ) { return f1 . m_name . compareTo ( f2 . m_name ) ; } } ) ; return listing ; } | 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 ( client , requestBuilder . build ( ) , requestResponse ) ; } | 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 ( buildRequestBody ( rr ) ) ; return doCall ( client , requestBuilder . build ( ) , rr ) ; } | 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 != null ) { if ( parent == superClazz ) { return true ; } parent = parent . getSuperclass ( ) ; } return false ; } | 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 {}" , 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 |
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 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 |
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 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 . |
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 . write ( oProtocol ) ; return baos . toByteArray ( ) ; } | 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 = protocolFactory . getProtocol ( transport ) ; T record = clazz . newInstance ( ) ; record . read ( iProtocol ) ; return record ; } catch ( InstantiationException | IllegalAccessException e ) { throw new TException ( e ) ; } } | 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 . 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 . |
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 , 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 . |
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 = pattern . matcher ( text ) ; List < String > tokens = new ArrayList < > ( ) ; while ( matcher . find ( ) ) { tokens . add ( matcher . group ( 0 ) ) ; } 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 ) ; } } 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 ; } } 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 |
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 == 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 |
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 ( ) ) , 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 ; } } 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 ; } } 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 |
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 < > ( ) ; 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 |
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 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 |
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 , 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 |
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 ( 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 |
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 ) 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 |
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 ZonedDateTime ) { return ( ( ZonedDateTime ) value ) . toOffsetDateTime ( ) . toOffsetTime ( ) ; } throw new EvaluationError ( "Can't convert '" + value + "' to a time" ) ; } | 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 ( value2 , ctx ) ) ; } catch ( EvaluationError ex ) { } try { 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 ) { } 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 |
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 ++ ) { 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 |
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 || 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 |
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 ( 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 . |
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 ) ; 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 |
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 = 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 |
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 ) , _numberTimes ) ; } | 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 , 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 |
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 . 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 . |
23,599 | public static LocalDate datevalue ( EvaluationContext ctx , Object text ) { return Conversions . toDate ( text , ctx ) ; } | Converts date stored in text to an actual date |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.