idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
1,500
public static Expression power ( Expression expression1 , Expression expression2 ) { return x ( "POWER(" + expression1 . toString ( ) + ", " + expression2 . toString ( ) + ")" ) ; }
Returned expression results in expression1 to the power of expression2 .
1,501
public static Expression power ( Number value1 , Number value2 ) { return power ( x ( value1 ) , x ( value2 ) ) ; }
Returned expression results in value1 to the power of value2 .
1,502
static String formatTimeout ( final CouchbaseRequest request , final long timeout ) { Map < String , Object > fieldMap = new HashMap < String , Object > ( ) ; fieldMap . put ( "t" , timeout ) ; if ( request != null ) { fieldMap . put ( "s" , formatServiceType ( request ) ) ; putIfNotNull ( fieldMap , "i" , request . operationId ( ) ) ; putIfNotNull ( fieldMap , "b" , request . bucket ( ) ) ; putIfNotNull ( fieldMap , "c" , request . lastLocalId ( ) ) ; putIfNotNull ( fieldMap , "l" , request . lastLocalSocket ( ) ) ; putIfNotNull ( fieldMap , "r" , request . lastRemoteSocket ( ) ) ; } try { return DefaultObjectMapper . writeValueAsString ( fieldMap ) ; } catch ( JsonProcessingException e ) { LOGGER . warn ( "Could not format timeout information for request " + request , e ) ; return null ; } }
This method take the given request and produces the correct additional timeout information according to the RFC .
1,503
private static String formatServiceType ( final CouchbaseRequest request ) { if ( request instanceof BinaryRequest ) { return ThresholdLogReporter . SERVICE_KV ; } else if ( request instanceof QueryRequest ) { return ThresholdLogReporter . SERVICE_N1QL ; } else if ( request instanceof ViewRequest ) { return ThresholdLogReporter . SERVICE_VIEW ; } else if ( request instanceof AnalyticsRequest ) { return ThresholdLogReporter . SERVICE_ANALYTICS ; } else if ( request instanceof SearchRequest ) { return ThresholdLogReporter . SERVICE_FTS ; } else if ( request instanceof ConfigRequest ) { return "config" ; } else { return "unknown" ; } }
Helper method to turn the request into the proper string service type .
1,504
private Observable < BucketSettings > ensureBucketIsHealthy ( final Observable < BucketSettings > input ) { return input . flatMap ( new Func1 < BucketSettings , Observable < BucketSettings > > ( ) { public Observable < BucketSettings > call ( final BucketSettings bucketSettings ) { return info ( ) . delay ( 100 , TimeUnit . MILLISECONDS ) . filter ( new Func1 < ClusterInfo , Boolean > ( ) { public Boolean call ( ClusterInfo clusterInfo ) { boolean allHealthy = true ; for ( Object n : clusterInfo . raw ( ) . getArray ( "nodes" ) ) { JsonObject node = ( JsonObject ) n ; if ( ! node . getString ( "status" ) . equals ( "healthy" ) ) { allHealthy = false ; break ; } } return allHealthy ; } } ) . repeat ( ) . take ( 1 ) . flatMap ( new Func1 < ClusterInfo , Observable < BucketSettings > > ( ) { public Observable < BucketSettings > call ( ClusterInfo clusterInfo ) { return Observable . just ( bucketSettings ) ; } } ) ; } } ) ; }
Helper method to ensure that the state of a bucket on all nodes is healthy .
1,505
public MutateInBuilder withDurability ( PersistTo persistTo , ReplicateTo replicateTo ) { asyncBuilder . withDurability ( persistTo , replicateTo ) ; return this ; }
Set both a persistence and replication durability constraints for the whole mutation .
1,506
public static Func1 < DocumentFragment < Mutation > , Boolean > getMapResultFnForSubdocMutationToBoolean ( ) { return new Func1 < DocumentFragment < Mutation > , Boolean > ( ) { public Boolean call ( DocumentFragment < Mutation > documentFragment ) { ResponseStatus status = documentFragment . status ( 0 ) ; if ( status == ResponseStatus . SUCCESS ) { return true ; } else { throw new CouchbaseException ( status . toString ( ) ) ; } } } ; }
Creates anonymous function for mapping document fragment result to boolean
1,507
public static Func1 < JsonDocument , DocumentFragment < Mutation > > getMapFullDocResultToSubDocFn ( final Mutation mutation ) { return new Func1 < JsonDocument , DocumentFragment < Mutation > > ( ) { public DocumentFragment < Mutation > call ( JsonDocument document ) { return new DocumentFragment < Mutation > ( document . id ( ) , document . cas ( ) , document . mutationToken ( ) , Collections . singletonList ( SubdocOperationResult . createResult ( null , mutation , ResponseStatus . SUCCESS , null ) ) ) ; } } ; }
Creates anonymous function for mapping full JsonDocument insert result to document fragment result
1,508
public static < E > DocumentFragment < Mutation > convertToSubDocumentResult ( ResponseStatus status , Mutation mutation , E element ) { return new DocumentFragment < Mutation > ( null , 0 , null , Collections . singletonList ( SubdocOperationResult . createResult ( null , mutation , status , element ) ) ) ; }
Useful for mapping exceptions of Multimutation or to be silent by mapping success to a valid subdocument result
1,509
public N1qlParams consistency ( ScanConsistency consistency ) { this . consistency = consistency ; if ( consistency == ScanConsistency . NOT_BOUNDED ) { this . scanWait = null ; } return this ; }
Sets scan consistency .
1,510
public N1qlParams rawParam ( String name , Object value ) { if ( this . rawParams == null ) { this . rawParams = new HashMap < String , Object > ( ) ; } if ( ! JsonValue . checkType ( value ) ) { throw new IllegalArgumentException ( "Only JSON types are supported." ) ; } rawParams . put ( name , value ) ; return this ; }
Allows to specify an arbitrary raw N1QL param .
1,511
private static Observable < ViewQueryResponse > passThroughOrThrow ( final ViewQueryResponse response ) { final int responseCode = response . responseCode ( ) ; if ( responseCode == 200 ) { return Observable . just ( response ) ; } return response . error ( ) . map ( new Func1 < String , ViewQueryResponse > ( ) { public ViewQueryResponse call ( String error ) { if ( shouldRetry ( responseCode , error ) ) { throw SHOULD_RETRY ; } return response ; } } ) . singleOrDefault ( response ) ; }
Helper method which decides if the response is good to pass through or needs to be retried .
1,512
private static boolean shouldRetry ( final int status , final String content ) { switch ( status ) { case 200 : return false ; case 404 : return analyse404Response ( content ) ; case 500 : return analyse500Response ( content ) ; case 300 : case 301 : case 302 : case 303 : case 307 : case 401 : case 408 : case 409 : case 412 : case 416 : case 417 : case 501 : case 502 : case 503 : case 504 : return true ; default : LOGGER . info ( "Received a View HTTP response code ({}) I did not expect, not retrying." , status ) ; return false ; } }
Analyses status codes and checks if a retry needs to happen .
1,513
private static boolean analyse404Response ( final String content ) { if ( content . contains ( "\"reason\":\"missing\"" ) ) { return true ; } LOGGER . debug ( "Design document not found, error is {}" , content ) ; return false ; }
Analyses the content of a 404 response to see if it is legible for retry .
1,514
private static boolean analyse500Response ( final String content ) { if ( content . contains ( "error" ) && content . contains ( "{not_found, missing_named_view}" ) ) { LOGGER . debug ( "Design document not found, error is {}" , content ) ; return false ; } if ( content . contains ( "error" ) && content . contains ( "\"badarg\"" ) ) { LOGGER . debug ( "Malformed view query" ) ; return false ; } return true ; }
Analyses the content of a 500 response to see if it is legible for retry .
1,515
private Bucket getCachedBucket ( final String name ) { Bucket cachedBucket = bucketCache . get ( name ) ; if ( cachedBucket != null ) { if ( cachedBucket . isClosed ( ) ) { LOGGER . debug ( "Not returning cached bucket \"{}\", because it is closed." , name ) ; bucketCache . remove ( name ) ; } else { LOGGER . debug ( "Returning still open, cached bucket \"{}\"" , name ) ; return cachedBucket ; } } return null ; }
Helper method to get a bucket instead of opening it if it is cached already .
1,516
protected void writeToSerializedStream ( ObjectOutputStream stream ) throws IOException { stream . writeLong ( cas ) ; stream . writeInt ( expiry ) ; stream . writeUTF ( id ) ; stream . writeObject ( content ) ; stream . writeObject ( mutationToken ) ; }
Helper method to write the current document state to the output stream for serialization purposes .
1,517
@ SuppressWarnings ( "unchecked" ) protected void readFromSerializedStream ( final ObjectInputStream stream ) throws IOException , ClassNotFoundException { cas = stream . readLong ( ) ; expiry = stream . readInt ( ) ; id = stream . readUTF ( ) ; content = ( T ) stream . readObject ( ) ; mutationToken = ( MutationToken ) stream . readObject ( ) ; }
Helper method to create the document from an object input stream used for serialization purposes .
1,518
public static View create ( String name , String map , String reduce ) { return new DefaultView ( name , map , reduce ) ; }
Create a new representation of a regular non - spatial view .
1,519
public static View create ( String name , String map ) { return new DefaultView ( name , map , null ) ; }
Create a new representation of a regular non - spatial view without reduce function .
1,520
public SearchQuery highlight ( HighlightStyle style , String ... fields ) { this . highlightStyle = style ; if ( fields != null && fields . length > 0 ) { highlightFields = fields ; } return this ; }
Configures the highlighting of matches in the response .
1,521
public SearchQuery consistentWith ( Document ... docs ) { this . consistency = null ; this . mutationState = MutationState . from ( docs ) ; return this ; }
Sets the consistency to consider for this FTS query to AT_PLUS and uses the mutation information from the given documents to parameterize the consistency . This replaces any consistency tuning previously set .
1,522
public SearchQuery consistentWith ( DocumentFragment ... fragments ) { this . consistency = null ; this . mutationState = MutationState . from ( fragments ) ; return this ; }
Sets the consistency to consider for this FTS query to AT_PLUS and uses the mutation information from the given document fragments to parameterize the consistency . This replaces any consistency tuning previously set .
1,523
public static SatisfiesBuilder anyIn ( String variable , Expression expression ) { return new SatisfiesBuilder ( x ( "ANY" ) , variable , expression , true ) ; }
Create an ANY comprehension with a first IN range .
1,524
public static SatisfiesBuilder anyAndEveryIn ( String variable , Expression expression ) { return new SatisfiesBuilder ( x ( "ANY AND EVERY" ) , variable , expression , true ) ; }
Create an ANY AND EVERY comprehension with a first IN range .
1,525
public static SatisfiesBuilder anyWithin ( String variable , Expression expression ) { return new SatisfiesBuilder ( x ( "ANY" ) , variable , expression , false ) ; }
Create an ANY comprehension with a first WITHIN range .
1,526
public static SatisfiesBuilder everyIn ( String variable , Expression expression ) { return new SatisfiesBuilder ( x ( "EVERY" ) , variable , expression , true ) ; }
Create an EVERY comprehension with a first IN range .
1,527
public static SatisfiesBuilder everyWithin ( String variable , Expression expression ) { return new SatisfiesBuilder ( x ( "EVERY" ) , variable , expression , false ) ; }
Create an EVERY comprehension with a first WITHIN range .
1,528
public static WhenBuilder arrayIn ( Expression arrayExpression , String variable , Expression expression ) { return new WhenBuilder ( x ( "ARRAY " + arrayExpression . toString ( ) + " FOR" ) , variable , expression , true ) ; }
Create an ARRAY comprehension with a first IN range .
1,529
public static WhenBuilder arrayWithin ( Expression arrayExpression , String variable , Expression expression ) { return new WhenBuilder ( x ( "ARRAY " + arrayExpression . toString ( ) + " FOR" ) , variable , expression , false ) ; }
Create an ARRAY comprehension with a first WITHIN range .
1,530
public D newDocument ( String id , int expiry , T content , long cas , MutationToken mutationToken ) { LOGGER . warn ( "This transcoder ({}) does not support mutation tokens - this method is a " + "stub and needs to be implemented on custom transcoders." , this . getClass ( ) . getSimpleName ( ) ) ; return newDocument ( id , expiry , content , cas ) ; }
Default implementation for backwards compatibility .
1,531
public static Serializable deserialize ( final ByteBuf content ) throws Exception { byte [ ] serialized = new byte [ content . readableBytes ( ) ] ; content . getBytes ( 0 , serialized ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( serialized ) ; ObjectInputStream is = new ObjectInputStream ( bis ) ; Serializable deserialized = ( Serializable ) is . readObject ( ) ; is . close ( ) ; bis . close ( ) ; return deserialized ; }
Takes the input content and deserializes it .
1,532
public static ByteBuf serialize ( final Serializable serializable ) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; ; ObjectOutputStream os = new ObjectOutputStream ( bos ) ; os . writeObject ( serializable ) ; byte [ ] serialized = bos . toByteArray ( ) ; os . close ( ) ; bos . close ( ) ; return Unpooled . buffer ( ) . writeBytes ( serialized ) ; }
Serializes the input into a ByteBuf .
1,533
public static ByteBuf encodeStringAsUtf8 ( String source ) { ByteBuf target = Unpooled . buffer ( source . length ( ) ) ; ByteBufUtil . writeUtf8 ( target , source ) ; return target ; }
Helper method to encode a String into UTF8 via fast - path methods .
1,534
public AsyncMutateInBuilder withDurability ( PersistTo persistTo , ReplicateTo replicateTo ) { this . persistTo = persistTo ; this . replicateTo = replicateTo ; return this ; }
Set both a persistence and a replication durability constraints for the whole mutation .
1,535
public AsyncMutateInBuilder insertDocument ( boolean insertDocument ) { if ( this . upsertDocument && insertDocument ) { throw new IllegalArgumentException ( "Cannot set both upsertDocument and insertDocument to true" ) ; } this . insertDocument = insertDocument ; return this ; }
Set insertDocument to true if the document has to be created only if it does not exist
1,536
public < T > AsyncMutateInBuilder insert ( String path , T fragment , SubdocOptionsBuilder optionsBuilder ) { if ( StringUtil . isNullOrEmpty ( path ) ) { throw new IllegalArgumentException ( "Path must not be empty for insert" ) ; } this . mutationSpecs . add ( new MutationSpec ( Mutation . DICT_ADD , path , fragment , optionsBuilder ) ) ; return this ; }
Insert a fragment provided the last element of the path doesn t exist .
1,537
public AsyncMutateInBuilder upsert ( JsonObject content ) { this . mutationSpecs . add ( new MutationSpec ( Mutation . UPSERTDOC , "" , content ) ) ; return this ; }
Upsert a full JSON document .
1,538
protected Observable < DocumentFragment < Mutation > > doSingleMutate ( MutationSpec spec , long timeout , TimeUnit timeUnit ) { Observable < DocumentFragment < Mutation > > mutation ; switch ( spec . type ( ) ) { case DICT_UPSERT : mutation = doSingleMutate ( spec , DICT_UPSERT_FACTORY , DICT_UPSERT_EVALUATOR , timeout , timeUnit ) ; break ; case DICT_ADD : mutation = doSingleMutate ( spec , DICT_ADD_FACTORY , DICT_ADD_EVALUATOR , timeout , timeUnit ) ; break ; case REPLACE : mutation = doSingleMutate ( spec , REPLACE_FACTORY , REPLACE_EVALUATOR , timeout , timeUnit ) ; break ; case ARRAY_PUSH_FIRST : case ARRAY_PUSH_LAST : mutation = doSingleMutate ( spec , ARRAY_EXTEND_FACTORY , ARRAY_EXTEND_EVALUATOR , timeout , timeUnit ) ; break ; case ARRAY_INSERT : mutation = doSingleMutate ( spec , ARRAY_INSERT_FACTORY , ARRAY_INSERT_EVALUATOR , timeout , timeUnit ) ; break ; case ARRAY_ADD_UNIQUE : mutation = doSingleMutate ( spec , ARRAY_ADDUNIQUE_FACTORY , ARRAY_ADDUNIQUE_EVALUATOR , timeout , timeUnit ) ; break ; case COUNTER : mutation = counterIn ( spec , timeout , timeUnit ) ; break ; case DELETE : mutation = removeIn ( spec , timeout , timeUnit ) ; break ; default : mutation = Observable . error ( new UnsupportedOperationException ( ) ) ; break ; } return subdocObserveMutation ( mutation , timeout , timeUnit ) ; }
Single operation implementations
1,539
private < T > Observable < DocumentFragment < T > > subdocObserveMutation ( Observable < DocumentFragment < T > > mutation , final long timeout , final TimeUnit timeUnit ) { if ( persistTo == PersistTo . NONE && replicateTo == ReplicateTo . NONE ) { return mutation ; } return mutation . flatMap ( new Func1 < DocumentFragment < T > , Observable < DocumentFragment < T > > > ( ) { public Observable < DocumentFragment < T > > call ( final DocumentFragment < T > frag ) { Observable < DocumentFragment < T > > result = Observe . call ( core , bucketName , frag . id ( ) , frag . cas ( ) , false , frag . mutationToken ( ) , persistTo . value ( ) , replicateTo . value ( ) , environment . observeIntervalDelay ( ) , environment . retryStrategy ( ) ) . map ( new Func1 < Boolean , DocumentFragment < T > > ( ) { public DocumentFragment < T > call ( Boolean aBoolean ) { return frag ; } } ) . onErrorResumeNext ( new Func1 < Throwable , Observable < DocumentFragment < T > > > ( ) { public Observable < DocumentFragment < T > > call ( Throwable throwable ) { return Observable . error ( new DurabilityException ( "Durability requirement failed: " + throwable . getMessage ( ) , throwable ) ) ; } } ) ; if ( timeout > 0 ) { result = result . timeout ( timeout , timeUnit , environment . scheduler ( ) ) ; } return result ; } } ) ; }
utility methods for mutations
1,540
private Span startTracing ( String spanName ) { if ( ! environment . operationTracingEnabled ( ) ) { return null ; } Scope scope = environment . tracer ( ) . buildSpan ( spanName ) . startActive ( false ) ; Span parent = scope . span ( ) ; scope . close ( ) ; return parent ; }
Helper method to start tracing and return the span .
1,541
private Action0 stopTracing ( final Span parent ) { return new Action0 ( ) { public void call ( ) { if ( parent != null ) { environment . tracer ( ) . scopeManager ( ) . activate ( parent , true ) . close ( ) ; } } } ; }
Helper method to stop tracing for the parent span given .
1,542
private static Observable < List < String > > createMarkerDocuments ( final ClusterFacade core , final String bucket ) { return Observable . from ( FLUSH_MARKERS ) . flatMap ( new Func1 < String , Observable < UpsertResponse > > ( ) { public Observable < UpsertResponse > call ( final String id ) { return deferAndWatch ( new Func1 < Subscriber , Observable < ? extends UpsertResponse > > ( ) { public Observable < ? extends UpsertResponse > call ( final Subscriber subscriber ) { UpsertRequest request = new UpsertRequest ( id , Unpooled . copiedBuffer ( id , CharsetUtil . UTF_8 ) , bucket ) ; request . subscriber ( subscriber ) ; return core . send ( request ) ; } } ) ; } } ) . doOnNext ( new Action1 < UpsertResponse > ( ) { public void call ( UpsertResponse response ) { if ( response . content ( ) != null && response . content ( ) . refCnt ( ) > 0 ) { response . content ( ) . release ( ) ; } } } ) . last ( ) . map ( new Func1 < UpsertResponse , List < String > > ( ) { public List < String > call ( UpsertResponse response ) { return FLUSH_MARKERS ; } } ) ; }
Helper method to create marker documents for each partition .
1,543
private static Observable < Boolean > initiateFlush ( final ClusterFacade core , final String bucket , final String username , final String password ) { return deferAndWatch ( new Func1 < Subscriber , Observable < FlushResponse > > ( ) { public Observable < FlushResponse > call ( Subscriber subscriber ) { FlushRequest request = new FlushRequest ( bucket , username , password ) ; request . subscriber ( subscriber ) ; return core . send ( request ) ; } } ) . retryWhen ( any ( ) . delay ( Delay . fixed ( 100 , TimeUnit . MILLISECONDS ) ) . max ( Integer . MAX_VALUE ) . build ( ) ) . map ( new Func1 < FlushResponse , Boolean > ( ) { public Boolean call ( FlushResponse flushResponse ) { if ( ! flushResponse . status ( ) . isSuccess ( ) ) { if ( flushResponse . content ( ) . contains ( "disabled" ) ) { throw new FlushDisabledException ( "Flush is disabled for this bucket." ) ; } else { throw new CouchbaseException ( "Flush failed because of: " + flushResponse . content ( ) ) ; } } return flushResponse . isDone ( ) ; } } ) ; }
Initiates a flush request against the server .
1,544
private static Observable < Boolean > pollMarkerDocuments ( final ClusterFacade core , final String bucket ) { return Observable . from ( FLUSH_MARKERS ) . flatMap ( new Func1 < String , Observable < GetResponse > > ( ) { public Observable < GetResponse > call ( final String id ) { return deferAndWatch ( new Func1 < Subscriber , Observable < ? extends GetResponse > > ( ) { public Observable < ? extends GetResponse > call ( Subscriber subscriber ) { GetRequest request = new GetRequest ( id , bucket ) ; request . subscriber ( subscriber ) ; return core . send ( request ) ; } } ) ; } } ) . reduce ( 0 , new Func2 < Integer , GetResponse , Integer > ( ) { public Integer call ( Integer foundDocs , GetResponse response ) { if ( response . content ( ) != null && response . content ( ) . refCnt ( ) > 0 ) { response . content ( ) . release ( ) ; } if ( response . status ( ) == ResponseStatus . SUCCESS ) { foundDocs ++ ; } return foundDocs ; } } ) . filter ( new Func1 < Integer , Boolean > ( ) { public Boolean call ( Integer foundDocs ) { return foundDocs == 0 ; } } ) . repeatWhen ( new Func1 < Observable < ? extends Void > , Observable < ? > > ( ) { public Observable < ? > call ( Observable < ? extends Void > observable ) { return observable . flatMap ( new Func1 < Void , Observable < ? > > ( ) { public Observable < ? > call ( Void aVoid ) { return Observable . timer ( 500 , TimeUnit . MILLISECONDS ) ; } } ) ; } } ) . take ( 1 ) . map ( new Func1 < Integer , Boolean > ( ) { public Boolean call ( Integer integer ) { return true ; } } ) ; }
Helper method to poll the list of marker documents until all of them are gone .
1,545
private Observable < DocumentFragment < Lookup > > existsIn ( final String id , final LookupSpec spec , final long timeout , final TimeUnit timeUnit ) { return Observable . defer ( new Func0 < Observable < DocumentFragment < Lookup > > > ( ) { public Observable < DocumentFragment < Lookup > > call ( ) { final SubExistRequest request = new SubExistRequest ( id , spec . path ( ) , bucketName ) ; request . xattr ( spec . xattr ( ) ) ; request . accessDeleted ( accessDeleted ) ; addRequestSpan ( environment , request , "subdoc_exists" ) ; return applyTimeout ( deferAndWatch ( new Func1 < Subscriber , Observable < SimpleSubdocResponse > > ( ) { public Observable < SimpleSubdocResponse > call ( Subscriber s ) { request . subscriber ( s ) ; return core . send ( request ) ; } } ) . map ( new Func1 < SimpleSubdocResponse , DocumentFragment < Lookup > > ( ) { public DocumentFragment < Lookup > call ( SimpleSubdocResponse response ) { try { if ( response . content ( ) != null && response . content ( ) . refCnt ( ) > 0 ) { response . content ( ) . release ( ) ; } if ( response . status ( ) . isSuccess ( ) ) { SubdocOperationResult < Lookup > result = SubdocOperationResult . createResult ( spec . path ( ) , Lookup . EXIST , response . status ( ) , true ) ; return new DocumentFragment < Lookup > ( docId , response . cas ( ) , response . mutationToken ( ) , Collections . singletonList ( result ) ) ; } else if ( response . status ( ) == ResponseStatus . SUBDOC_PATH_NOT_FOUND ) { SubdocOperationResult < Lookup > result = SubdocOperationResult . createResult ( spec . path ( ) , Lookup . EXIST , response . status ( ) , false ) ; return new DocumentFragment < Lookup > ( docId , response . cas ( ) , response . mutationToken ( ) , Collections . singletonList ( result ) ) ; } throw SubdocHelper . commonSubdocErrors ( response . status ( ) , id , spec . path ( ) ) ; } finally { if ( environment . operationTracingEnabled ( ) ) { environment . tracer ( ) . scopeManager ( ) . activate ( response . request ( ) . span ( ) , true ) . close ( ) ; } } } } ) , request , environment , timeout , timeUnit ) ; } } ) ; }
Helper method to actually perform the subdoc exists operation .
1,546
private Observable < DocumentFragment < Lookup > > getCountIn ( final String id , final LookupSpec spec , final long timeout , final TimeUnit timeUnit ) { return Observable . defer ( new Func0 < Observable < DocumentFragment < Lookup > > > ( ) { public Observable < DocumentFragment < Lookup > > call ( ) { final SubGetCountRequest request = new SubGetCountRequest ( id , spec . path ( ) , bucketName ) ; request . xattr ( spec . xattr ( ) ) ; request . accessDeleted ( accessDeleted ) ; addRequestSpan ( environment , request , "subdoc_count" ) ; return applyTimeout ( deferAndWatch ( new Func1 < Subscriber , Observable < SimpleSubdocResponse > > ( ) { public Observable < SimpleSubdocResponse > call ( Subscriber s ) { request . subscriber ( s ) ; return core . send ( request ) ; } } ) . map ( new Func1 < SimpleSubdocResponse , DocumentFragment < Lookup > > ( ) { public DocumentFragment < Lookup > call ( SimpleSubdocResponse response ) { try { if ( response . status ( ) . isSuccess ( ) ) { try { long count = subdocumentTranscoder . decode ( response . content ( ) , Long . class ) ; SubdocOperationResult < Lookup > single = SubdocOperationResult . createResult ( spec . path ( ) , Lookup . GET_COUNT , response . status ( ) , count ) ; return new DocumentFragment < Lookup > ( id , response . cas ( ) , response . mutationToken ( ) , Collections . singletonList ( single ) ) ; } finally { if ( response . content ( ) != null ) { response . content ( ) . release ( ) ; } } } else { if ( response . content ( ) != null && response . content ( ) . refCnt ( ) > 0 ) { response . content ( ) . release ( ) ; } if ( response . status ( ) == ResponseStatus . SUBDOC_PATH_NOT_FOUND ) { SubdocOperationResult < Lookup > single = SubdocOperationResult . createResult ( spec . path ( ) , Lookup . GET_COUNT , response . status ( ) , null ) ; return new DocumentFragment < Lookup > ( id , response . cas ( ) , response . mutationToken ( ) , Collections . singletonList ( single ) ) ; } else { throw SubdocHelper . commonSubdocErrors ( response . status ( ) , id , spec . path ( ) ) ; } } } finally { if ( environment . operationTracingEnabled ( ) ) { environment . tracer ( ) . scopeManager ( ) . activate ( response . request ( ) . span ( ) , true ) . close ( ) ; } } } } ) , request , environment , timeout , timeUnit ) ; } } ) ; }
Helper method to actually perform the subdoc get count operation .
1,547
public static boolean checkType ( Object item ) { return item == null || item instanceof String || item instanceof Integer || item instanceof Long || item instanceof Double || item instanceof Boolean || item instanceof BigInteger || item instanceof BigDecimal || item instanceof JsonObject || item instanceof JsonArray ; }
Helper method to check if the given item is a supported JSON item .
1,548
private static List < Field > getAllDeclaredFields ( final Class < ? > sourceEntity ) { List < Field > fields = new ArrayList < Field > ( ) ; Class < ? > clazz = sourceEntity ; while ( clazz != null ) { Field [ ] f = clazz . getDeclaredFields ( ) ; fields . addAll ( Arrays . asList ( f ) ) ; clazz = clazz . getSuperclass ( ) ; } return fields ; }
Helper method to grab all the declared fields from the given class but also from its inherited parents!
1,549
protected void enforcePrimitive ( Object t ) throws ClassCastException { if ( ! JsonValue . checkType ( t ) || t instanceof JsonValue ) { throw new ClassCastException ( "Only primitive types are supported in CouchbaseArraySet, got a " + t . getClass ( ) . getName ( ) ) ; } }
Verify that the type of object t is compatible with CouchbaseArraySet storage .
1,550
private static Expression infix ( String infix , String left , String right ) { return new Expression ( left + " " + infix + " " + right ) ; }
Helper method to infix a string .
1,551
private static String wrapWith ( char wrapper , String ... input ) { StringBuilder escaped = new StringBuilder ( ) ; for ( String i : input ) { escaped . append ( ", " ) ; escaped . append ( wrapper ) . append ( i ) . append ( wrapper ) ; } if ( escaped . length ( ) > 2 ) { escaped . delete ( 0 , 2 ) ; } return escaped . toString ( ) ; }
Helper method to wrap varargs with the given character .
1,552
private static List < String > assembleSeedNodes ( ConnectionString connectionString , CouchbaseEnvironment environment ) { List < String > seedNodes = new ArrayList < String > ( ) ; if ( environment . dnsSrvEnabled ( ) ) { seedNodesViaDnsSrv ( connectionString , environment , seedNodes ) ; } else { for ( InetSocketAddress node : connectionString . hosts ( ) ) { seedNodes . add ( ALLOW_HOSTNAMES_AS_SEED_NODES ? node . getHostName ( ) : node . getAddress ( ) . getHostAddress ( ) ) ; } } if ( seedNodes . isEmpty ( ) ) { seedNodes . add ( DEFAULT_HOST ) ; } return seedNodes ; }
Helper method to assemble list of seed nodes depending on the given input .
1,553
private static void seedNodesViaDnsSrv ( ConnectionString connectionString , CouchbaseEnvironment environment , List < String > seedNodes ) { if ( connectionString . allHosts ( ) . size ( ) == 1 ) { InetSocketAddress lookupNode = connectionString . allHosts ( ) . get ( 0 ) ; LOGGER . debug ( "Attempting to load DNS SRV records from {}." , connectionString . allHosts ( ) . get ( 0 ) ) ; try { List < String > foundNodes = Bootstrap . fromDnsSrv ( lookupNode . getHostName ( ) , false , environment . sslEnabled ( ) ) ; if ( foundNodes . isEmpty ( ) ) { throw new IllegalStateException ( "DNS SRV list is empty." ) ; } seedNodes . addAll ( foundNodes ) ; LOGGER . info ( "Loaded seed nodes from DNS SRV {}." , system ( foundNodes ) ) ; } catch ( Exception ex ) { LOGGER . warn ( "DNS SRV lookup failed, proceeding with normal bootstrap." , ex ) ; seedNodes . add ( ALLOW_HOSTNAMES_AS_SEED_NODES ? lookupNode . getHostName ( ) : lookupNode . getAddress ( ) . getHostAddress ( ) ) ; } } else { LOGGER . info ( "DNS SRV enabled, but less or more than one seed node given. " + "Proceeding with normal bootstrap." ) ; for ( InetSocketAddress node : connectionString . hosts ( ) ) { seedNodes . add ( ALLOW_HOSTNAMES_AS_SEED_NODES ? node . getHostName ( ) : node . getAddress ( ) . getHostAddress ( ) ) ; } } }
Helper method to assemble the list of seed nodes via DNS SRV .
1,554
public Observable < RestApiResponse > execute ( ) { return deferAndWatch ( new Func1 < Subscriber , Observable < ? extends RestApiResponse > > ( ) { public Observable < ? extends RestApiResponse > call ( Subscriber subscriber ) { RestApiRequest apiRequest = asRequest ( ) ; LOGGER . debug ( "Executing Cluster API request {} on {}" , apiRequest . method ( ) , apiRequest . pathWithParameters ( ) ) ; apiRequest . subscriber ( subscriber ) ; return core . send ( apiRequest ) ; } } ) ; }
Executes the API request in an asynchronous fashion .
1,555
private EntityMetadata metadata ( final Class < ? > source ) { EntityMetadata metadata = metadataCache . get ( source ) ; if ( metadata == null ) { EntityMetadata generated = new ReflectionBasedEntityMetadata ( source ) ; metadataCache . put ( source , generated ) ; return generated ; } else { return metadata ; } }
Helper method to return and cache the entity metadata .
1,556
private static void verifyId ( final EntityMetadata entityMetadata ) { if ( ! entityMetadata . hasIdProperty ( ) ) { throw new RepositoryMappingException ( "No field annotated with @Id present." ) ; } if ( entityMetadata . idProperty ( ) . type ( ) != String . class ) { throw new RepositoryMappingException ( "The @Id Field needs to be of type String." ) ; } }
Helper method to check that the ID field is present and is of the desired types .
1,557
public static Expression regexpReplace ( Expression expression , String pattern , String repl ) { return x ( "REGEXP_REPLACE(" + expression . toString ( ) + ", \"" + pattern + "\", \"" + repl + "\")" ) ; }
Returned expression results in a new string with all occurrences of pattern replaced with repl .
1,558
public static Expression decodeJson ( JsonObject json ) { char [ ] encoded = JsonStringEncoder . getInstance ( ) . quoteAsString ( json . toString ( ) ) ; return x ( "DECODE_JSON(\"" + new String ( encoded ) + "\")" ) ; }
The returned Expression unmarshals the JSON constant into a N1QL value . The empty string results in MISSING .
1,559
public static Expression decodeJson ( String jsonString ) { try { JsonObject jsonObject = CouchbaseAsyncBucket . JSON_OBJECT_TRANSCODER . stringToJsonObject ( jsonString ) ; return decodeJson ( jsonObject ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "String is not representing JSON object: " + jsonString ) ; } }
The returned Expression unmarshals the JSON - encoded string into a N1QL value . The empty string results in MISSING .
1,560
public Object getAndDecrypt ( final String name , String providerName ) throws Exception { return decrypt ( ( JsonObject ) content . get ( ENCRYPTION_PREFIX + name ) , providerName ) ; }
Retrieve and decrypt content and not casting its type
1,561
public JsonObject putNullAndEncrypt ( String name , String providerName ) { addValueEncryptionInfo ( name , providerName , true ) ; content . put ( name , null ) ; return this ; }
Store a null value as encrypted identified by the field s name .
1,562
private void addValueEncryptionInfo ( String path , String providerName , boolean escape ) { if ( escape ) { path = path . replaceAll ( "~" , "~0" ) . replaceAll ( "/" , "~1" ) ; } if ( this . encryptionPathInfo == null ) { this . encryptionPathInfo = new HashMap < String , String > ( ) ; } this . encryptionPathInfo . put ( path , providerName ) ; }
Adds to the encryption info with optional escape for json pointer syntax
1,563
protected static Observable < Tuple2 < Integer , Throwable > > errorsWithAttempts ( Observable < ? extends Throwable > errors , final int expectedAttempts ) { return errors . zipWith ( Observable . range ( 1 , expectedAttempts ) , new Func2 < Throwable , Integer , Tuple2 < Integer , Throwable > > ( ) { public Tuple2 < Integer , Throwable > call ( Throwable error , Integer attempt ) { return Tuple . create ( attempt , error ) ; } } ) ; }
Internal utility method to combine errors in an observable with their attempt number .
1,564
public static Date parseDate ( String strdate ) { if ( strdate == null || strdate . length ( ) == 0 ) return null ; Date result = null ; strdate = strdate . trim ( ) ; if ( strdate . length ( ) > 10 ) { if ( ( strdate . substring ( strdate . length ( ) - 5 ) . indexOf ( "+" ) == 0 || strdate . substring ( strdate . length ( ) - 5 ) . indexOf ( "-" ) == 0 ) && strdate . substring ( strdate . length ( ) - 5 ) . indexOf ( ":" ) == 2 ) { String sign = strdate . substring ( strdate . length ( ) - 5 , strdate . length ( ) - 4 ) ; strdate = strdate . substring ( 0 , strdate . length ( ) - 5 ) + sign + "0" + strdate . substring ( strdate . length ( ) - 4 ) ; } String dateEnd = strdate . substring ( strdate . length ( ) - 6 ) ; if ( ( dateEnd . indexOf ( "-" ) == 0 || dateEnd . indexOf ( "+" ) == 0 ) && dateEnd . indexOf ( ":" ) == 3 ) { if ( ! "GMT" . equals ( strdate . substring ( strdate . length ( ) - 9 , strdate . length ( ) - 6 ) ) ) { String oldDate = strdate ; String newEnd = dateEnd . substring ( 0 , 3 ) + dateEnd . substring ( 4 ) ; strdate = oldDate . substring ( 0 , oldDate . length ( ) - 6 ) + newEnd ; } } } int i = 0 ; while ( i < CUSTOM_DATE_FORMATS . length ) { try { synchronized ( CUSTOM_DATE_FORMATS [ i ] ) { return CUSTOM_DATE_FORMATS [ i ] . parse ( strdate ) ; } } catch ( ParseException e ) { i ++ ; } catch ( NumberFormatException e ) { i ++ ; } } return result ; }
Tries different date formats to parse against the given string representation to retrieve a valid Date object .
1,565
private static byte [ ] base64ToByteArray ( String s , boolean alternate ) { byte [ ] alphaToInt = ( alternate ? altBase64ToInt : base64ToInt ) ; int sLen = s . length ( ) ; int numGroups = sLen / 4 ; if ( 4 * numGroups != sLen ) { throw new IllegalArgumentException ( "String length must be a multiple of four." ) ; } int missingBytesInLastGroup = 0 ; int numFullGroups = numGroups ; if ( sLen != 0 ) { if ( s . charAt ( sLen - 1 ) == '=' ) { missingBytesInLastGroup ++ ; numFullGroups -- ; } if ( s . charAt ( sLen - 2 ) == '=' ) { missingBytesInLastGroup ++ ; } } byte [ ] result = new byte [ 3 * numGroups - missingBytesInLastGroup ] ; int inCursor = 0 , outCursor = 0 ; for ( int i = 0 ; i < numFullGroups ; i ++ ) { int ch0 = base64toInt ( s . charAt ( inCursor ++ ) , alphaToInt ) ; int ch1 = base64toInt ( s . charAt ( inCursor ++ ) , alphaToInt ) ; int ch2 = base64toInt ( s . charAt ( inCursor ++ ) , alphaToInt ) ; int ch3 = base64toInt ( s . charAt ( inCursor ++ ) , alphaToInt ) ; result [ outCursor ++ ] = ( byte ) ( ( ch0 << 2 ) | ( ch1 >> 4 ) ) ; result [ outCursor ++ ] = ( byte ) ( ( ch1 << 4 ) | ( ch2 >> 2 ) ) ; result [ outCursor ++ ] = ( byte ) ( ( ch2 << 6 ) | ch3 ) ; } if ( missingBytesInLastGroup != 0 ) { int ch0 = base64toInt ( s . charAt ( inCursor ++ ) , alphaToInt ) ; int ch1 = base64toInt ( s . charAt ( inCursor ++ ) , alphaToInt ) ; result [ outCursor ++ ] = ( byte ) ( ( ch0 << 2 ) | ( ch1 >> 4 ) ) ; if ( missingBytesInLastGroup == 1 ) { int ch2 = base64toInt ( s . charAt ( inCursor ++ ) , alphaToInt ) ; result [ outCursor ++ ] = ( byte ) ( ( ch1 << 4 ) | ( ch2 >> 2 ) ) ; } } return result ; }
Translates the specified alternate representation Base64 string into a byte array .
1,566
private static int base64toInt ( char c , byte [ ] alphaToInt ) { int result = alphaToInt [ c ] ; if ( result < 0 ) { throw new IllegalArgumentException ( "Illegal character " + c ) ; } return result ; }
Translates the specified character which is assumed to be in the Base 64 Alphabet into its equivalent 6 - bit positive integer .
1,567
public static < T > T ensureNonNull ( final T value , final T defaultValue ) { return value == null ? Assertions . assertNotNull ( defaultValue ) : value ; }
Get value and ensure that the value is not null
1,568
public static < T > T ensureNonNull ( final T value ) { return Assertions . assertNotNull ( value ) ; }
Get value if it is not null .
1,569
public static < T > T findFirstNonNull ( final T ... objects ) { for ( final T obj : ensureNonNull ( objects ) ) { if ( obj != null ) { return obj ; } } throw Assertions . fail ( "Can't find non-null item in array" ) ; }
Find the first non - null value in an array and return that .
1,570
public static String ensureNonNullAndNonEmpty ( final String value , @ Constraint ( "notEmpty(X)" ) final String dflt ) { String result = value ; if ( result == null || result . isEmpty ( ) ) { assertFalse ( "Default value must not be empty" , assertNotNull ( "Default value must not be null" , dflt ) . isEmpty ( ) ) ; result = dflt ; } return result ; }
Get non - null non - empty string .
1,571
@ Weight ( Weight . Unit . VARIABLE ) public static byte [ ] packData ( final byte [ ] data ) { final Deflater compressor = new Deflater ( Deflater . BEST_COMPRESSION ) ; compressor . setInput ( Assertions . assertNotNull ( data ) ) ; compressor . finish ( ) ; final ByteArrayOutputStream resultData = new ByteArrayOutputStream ( data . length + 100 ) ; final byte [ ] buffer = new byte [ 1024 ] ; while ( ! compressor . finished ( ) ) { resultData . write ( buffer , 0 , compressor . deflate ( buffer ) ) ; } return resultData . toByteArray ( ) ; }
Pack some binary data .
1,572
@ Weight ( Weight . Unit . VARIABLE ) public static byte [ ] unpackData ( final byte [ ] data ) { final Inflater decompressor = new Inflater ( ) ; decompressor . setInput ( Assertions . assertNotNull ( data ) ) ; final ByteArrayOutputStream outStream = new ByteArrayOutputStream ( data . length * 2 ) ; final byte [ ] buffer = new byte [ 1024 ] ; try { while ( ! decompressor . finished ( ) ) { outStream . write ( buffer , 0 , decompressor . inflate ( buffer ) ) ; } return outStream . toByteArray ( ) ; } catch ( DataFormatException ex ) { MetaErrorListeners . fireError ( "Can't unpack data for wrong format" , ex ) ; throw new IllegalArgumentException ( "Wrong formatted data" , ex ) ; } }
Unpack binary data packed by the packData method .
1,573
@ Weight ( Weight . Unit . VARIABLE ) public static boolean silentSleep ( final long milliseconds ) { boolean result = true ; try { Thread . sleep ( milliseconds ) ; } catch ( InterruptedException ex ) { result = false ; Thread . currentThread ( ) . interrupt ( ) ; } return result ; }
Just suspend the current thread for defined interval in milliseconds .
1,574
@ Weight ( Weight . Unit . VARIABLE ) public static StackTraceElement stackElement ( ) { final StackTraceElement [ ] allElements = Thread . currentThread ( ) . getStackTrace ( ) ; return allElements [ 2 ] ; }
Get the stack element of the method caller .
1,575
@ Weight ( Weight . Unit . VARIABLE ) public static void fireError ( final String text , final Throwable error ) { for ( final MetaErrorListener p : ERROR_LISTENERS ) { p . onDetectedError ( text , error ) ; } }
Send notifications to all listeners .
1,576
public ExpressionTreeElement addSubTree ( final ExpressionTree tree ) { assertNotEmptySlot ( ) ; final ExpressionTreeElement root = tree . getRoot ( ) ; if ( ! root . isEmptySlot ( ) ) { root . makeMaxPriority ( ) ; addElementToNextFreeSlot ( root ) ; } return this ; }
Add a tree as new child and make the maximum priority for it
1,577
public boolean replaceElement ( final ExpressionTreeElement oldOne , final ExpressionTreeElement newOne ) { assertNotEmptySlot ( ) ; if ( oldOne == null ) { throw new PreprocessorException ( "[Expression]The old element is null" , this . sourceString , this . includeStack , null ) ; } if ( newOne == null ) { throw new PreprocessorException ( "[Expression]The new element is null" , this . sourceString , this . includeStack , null ) ; } boolean result = false ; final ExpressionTreeElement [ ] children = childElements ; final int len = children . length ; for ( int i = 0 ; i < len ; i ++ ) { if ( children [ i ] == oldOne ) { children [ i ] = newOne ; newOne . parentTreeElement = this ; result = true ; break ; } } return result ; }
It replaces a child element
1,578
public ExpressionTreeElement addTreeElement ( final ExpressionTreeElement element ) { assertNotEmptySlot ( ) ; assertNotNull ( "The element is null" , element ) ; final int newElementPriority = element . getPriority ( ) ; ExpressionTreeElement result = this ; final ExpressionTreeElement parentTreeElement = this . parentTreeElement ; final int currentPriority = getPriority ( ) ; if ( newElementPriority < currentPriority ) { if ( parentTreeElement == null ) { element . addTreeElement ( this ) ; result = element ; } else { result = parentTreeElement . addTreeElement ( element ) ; } } else if ( newElementPriority == currentPriority ) { if ( parentTreeElement != null ) { parentTreeElement . replaceElement ( this , element ) ; } if ( element . nextChildSlot >= element . childElements . length ) { throw new PreprocessorException ( "[Expression]Can't process expression item, may be wrong number of arguments" , this . sourceString , this . includeStack , null ) ; } element . childElements [ element . nextChildSlot ] = this ; element . nextChildSlot ++ ; this . parentTreeElement = element ; result = element ; } else if ( isFull ( ) ) { final int lastElementIndex = getArity ( ) - 1 ; final ExpressionTreeElement lastElement = childElements [ lastElementIndex ] ; if ( lastElement . getPriority ( ) > newElementPriority ) { element . addElementToNextFreeSlot ( lastElement ) ; childElements [ lastElementIndex ] = element ; element . parentTreeElement = this ; result = element ; } } else { addElementToNextFreeSlot ( element ) ; result = element ; } return result ; }
Add tree element with sorting operation depends on priority of the elements
1,579
public void fillArguments ( final List < ExpressionTree > arguments ) { assertNotEmptySlot ( ) ; if ( arguments == null ) { throw new PreprocessorException ( "[Expression]Argument list is null" , this . sourceString , this . includeStack , null ) ; } if ( childElements . length != arguments . size ( ) ) { throw new PreprocessorException ( "Wrong argument list size" , this . sourceString , this . includeStack , null ) ; } int i = 0 ; for ( ExpressionTree arg : arguments ) { if ( arg == null ) { throw new PreprocessorException ( "[Expression]Argument [" + ( i + 1 ) + "] is null" , this . sourceString , this . includeStack , null ) ; } if ( ! childElements [ i ] . isEmptySlot ( ) ) { throw new PreprocessorException ( "[Expression]Non-empty slot detected, it is possible that there is a program error, contact a developer please" , this . sourceString , this . includeStack , null ) ; } final ExpressionTreeElement root = arg . getRoot ( ) ; if ( root . isEmptySlot ( ) ) { throw new PreprocessorException ( "[Expression]Empty argument [" + ( i + 1 ) + "] detected" , this . sourceString , this . includeStack , null ) ; } childElements [ i ] = root ; root . parentTreeElement = this ; i ++ ; } }
It fills children slots from a list containing expression trees
1,580
private void addElementToNextFreeSlot ( final ExpressionTreeElement element ) { if ( element == null ) { throw new PreprocessorException ( "[Expression]Element is null" , this . sourceString , this . includeStack , null ) ; } if ( childElements . length == 0 ) { throw new PreprocessorException ( "[Expression]Unexpected element, may be unknown function [" + savedItem . toString ( ) + ']' , this . sourceString , this . includeStack , null ) ; } else if ( isFull ( ) ) { throw new PreprocessorException ( "[Expression]There is not any possibility to add new argument [" + savedItem . toString ( ) + ']' , this . sourceString , this . includeStack , null ) ; } else { childElements [ nextChildSlot ++ ] = element ; } element . parentTreeElement = this ; }
Add an expression element into the next free child slot
1,581
public void postProcess ( ) { if ( ! this . isEmptySlot ( ) ) { switch ( savedItem . getExpressionItemType ( ) ) { case OPERATOR : { if ( savedItem == OPERATOR_SUB ) { if ( ! childElements [ 0 ] . isEmptySlot ( ) && childElements [ 1 ] . isEmptySlot ( ) ) { final ExpressionTreeElement left = childElements [ 0 ] ; final ExpressionItem item = left . getItem ( ) ; if ( item . getExpressionItemType ( ) == ExpressionItemType . VALUE ) { final Value val = ( Value ) item ; switch ( val . getType ( ) ) { case INT : { childElements = EMPTY ; savedItem = Value . valueOf ( 0 - val . asLong ( ) ) ; makeMaxPriority ( ) ; } break ; case FLOAT : { childElements = EMPTY ; savedItem = Value . valueOf ( 0.0f - val . asFloat ( ) ) ; makeMaxPriority ( ) ; } break ; default : { if ( ! left . isEmptySlot ( ) ) { left . postProcess ( ) ; } } break ; } } } else { for ( final ExpressionTreeElement element : childElements ) { if ( ! element . isEmptySlot ( ) ) { element . postProcess ( ) ; } } } } else { for ( final ExpressionTreeElement element : childElements ) { if ( ! element . isEmptySlot ( ) ) { element . postProcess ( ) ; } } } } break ; case FUNCTION : { for ( final ExpressionTreeElement element : childElements ) { if ( ! element . isEmptySlot ( ) ) { element . postProcess ( ) ; } } } break ; } } }
Post - processing after the tree is formed the unary minus operation will be optimized
1,582
public static < E extends AbstractFunction > E findForClass ( final Class < E > functionClass ) { E result = null ; for ( final AbstractFunction function : getAllFunctions ( ) ) { if ( function . getClass ( ) == functionClass ) { result = functionClass . cast ( function ) ; break ; } } return result ; }
Allows to find a function handler instance for its class
1,583
public void registerSpecialVariableProcessor ( final SpecialVariableProcessor processor ) { assertNotNull ( "Processor is null" , processor ) ; for ( final String varName : processor . getVariableNames ( ) ) { assertNotNull ( "A Special Var name is null" , varName ) ; if ( mapVariableNameToSpecialVarProcessor . containsKey ( varName ) ) { throw new IllegalStateException ( "There is already defined processor for " + varName ) ; } mapVariableNameToSpecialVarProcessor . put ( varName , processor ) ; } }
It allows to register a special variable processor which can process some special global variables
1,584
public void logInfo ( final String text ) { if ( text != null && this . preprocessorLogger != null ) { this . preprocessorLogger . info ( text ) ; } }
Print an information into the current log
1,585
public void logError ( final String text ) { if ( text != null && this . preprocessorLogger != null ) { this . preprocessorLogger . error ( text ) ; } }
Print an information about an error into the current log
1,586
public void logDebug ( final String text ) { if ( text != null && this . preprocessorLogger != null ) { this . preprocessorLogger . debug ( text ) ; } }
Print some debug info into the current log
1,587
public void logWarning ( final String text ) { if ( text != null || this . preprocessorLogger != null ) { this . preprocessorLogger . warning ( text ) ; } }
Print an information about a warning situation into the current log
1,588
public void setSharedResource ( final String name , final Object obj ) { assertNotNull ( "Name is null" , name ) ; assertNotNull ( "Object is null" , obj ) ; sharedResources . put ( name , obj ) ; }
Set a shared source it is an object saved into the inside map for a name
1,589
public Object getSharedResource ( final String name ) { assertNotNull ( "Name is null" , name ) ; return sharedResources . get ( name ) ; }
Get a shared source from inside map
1,590
public Object removeSharedResource ( final String name ) { assertNotNull ( "Name is null" , name ) ; return sharedResources . remove ( name ) ; }
Remove a shared object from the inside map for its name
1,591
public PreprocessorContext setSources ( final List < String > folderPaths ) { this . sources . clear ( ) ; this . sources . addAll ( assertDoesntContainNull ( folderPaths ) . stream ( ) . map ( x -> new SourceFolder ( this . baseDir , x ) ) . collect ( Collectors . toList ( ) ) ) ; return this ; }
Set source directories
1,592
public PreprocessorContext setExtensions ( final List < String > extensions ) { this . extensions = new HashSet < > ( assertDoesntContainNull ( extensions ) ) ; return this ; }
Set file extensions of files to be preprocessed it is a comma separated list
1,593
public final boolean isFileAllowedForPreprocessing ( final File file ) { boolean result = false ; if ( file != null && file . isFile ( ) && file . length ( ) != 0L ) { result = this . extensions . contains ( PreprocessorUtils . getFileExtension ( file ) ) ; } return result ; }
Check that a file is allowed to be preprocessed fo its extension
1,594
public final boolean isFileExcludedByExtension ( final File file ) { return file == null || ! file . isFile ( ) || this . excludeExtensions . contains ( PreprocessorUtils . getFileExtension ( file ) ) ; }
Check that a file is excluded from preprocessing and coping actions
1,595
public PreprocessorContext setExcludeExtensions ( final List < String > extensions ) { this . excludeExtensions = new HashSet < > ( assertDoesntContainNull ( extensions ) ) ; return this ; }
Set comma separated list of file extensions to be excluded from preprocessing
1,596
public PreprocessorContext setLocalVariable ( final String name , final Value value ) { assertNotNull ( "Variable name is null" , name ) ; assertNotNull ( "Value is null" , value ) ; final String normalized = assertNotNull ( PreprocessorUtils . normalizeVariableName ( name ) ) ; if ( normalized . isEmpty ( ) ) { throw makeException ( "Not defined variable name" , null ) ; } if ( mapVariableNameToSpecialVarProcessor . containsKey ( normalized ) || globalVarTable . containsKey ( normalized ) ) { throw makeException ( "Attempting to set either a global variable or a special variable as a local one [" + normalized + ']' , null ) ; } localVarTable . put ( normalized , value ) ; return this ; }
Set a local variable value
1,597
public PreprocessorContext removeLocalVariable ( final String name ) { assertNotNull ( "Variable name is null" , name ) ; final String normalized = assertNotNull ( PreprocessorUtils . normalizeVariableName ( name ) ) ; if ( normalized . isEmpty ( ) ) { throw makeException ( "Empty variable name" , null ) ; } if ( mapVariableNameToSpecialVarProcessor . containsKey ( normalized ) || globalVarTable . containsKey ( normalized ) ) { throw makeException ( "Attempting to remove either a global variable or a special variable as a local one [" + normalized + ']' , null ) ; } if ( isVerbose ( ) ) { logForVerbose ( "Removing local variable '" + normalized + "\'" ) ; } localVarTable . remove ( normalized ) ; return this ; }
Remove a local variable value from the context .
1,598
public Value getLocalVariable ( final String name ) { if ( name == null ) { return null ; } final String normalized = assertNotNull ( PreprocessorUtils . normalizeVariableName ( name ) ) ; if ( normalized . isEmpty ( ) ) { return null ; } return localVarTable . get ( normalized ) ; }
Get a local variable value
1,599
public boolean containsLocalVariable ( final String name ) { if ( name == null ) { return false ; } final String normalized = assertNotNull ( PreprocessorUtils . normalizeVariableName ( name ) ) ; if ( normalized . isEmpty ( ) ) { return false ; } return localVarTable . containsKey ( normalized ) ; }
Check that a local variable for a name is presented