idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
22,600
public static SecretKey hmacShaKeyFor ( byte [ ] bytes ) throws WeakKeyException { if ( bytes == null ) { throw new InvalidKeyException ( "SecretKey byte array cannot be null." ) ; } int bitLength = bytes . length * 8 ; for ( SignatureAlgorithm alg : PREFERRED_HMAC_ALGS ) { if ( bitLength >= alg . getMinKeyLength ( ) )...
Creates a new SecretKey instance for use with HMAC - SHA algorithms based on the specified key byte array .
22,601
private void ensureFill ( ) throws JedisConnectionException { if ( count >= limit ) { try { limit = in . read ( buf ) ; count = 0 ; if ( limit == - 1 ) { throw new JedisConnectionException ( "Unexpected end of stream." ) ; } } catch ( IOException e ) { throw new JedisConnectionException ( e ) ; } } }
This methods assumes there are required bytes to be read . If we cannot read anymore bytes an exception is thrown to quickly ascertain that the stream was smaller than expected .
22,602
public void sync ( ) { if ( getPipelinedResponseLength ( ) > 0 ) { List < Object > unformatted = client . getMany ( getPipelinedResponseLength ( ) ) ; for ( Object o : unformatted ) { generateResponse ( o ) ; } } }
Synchronize pipeline by reading all responses . This operation close the pipeline . In order to get return values from pipelined commands capture the different Response&lt ; ?&gt ; of the commands you execute .
22,603
public String getKeyTag ( String key ) { if ( tagPattern != null ) { Matcher m = tagPattern . matcher ( key ) ; if ( m . find ( ) ) return m . group ( 1 ) ; } return key ; }
A key tag is a special pattern inside a key that if preset is the only part of the key hashed in order to select the server for this key .
22,604
public String quit ( ) { checkIsInMultiOrPipeline ( ) ; client . quit ( ) ; String quitReturn = client . getStatusCodeReply ( ) ; client . disconnect ( ) ; return quitReturn ; }
Ask the server to silently close the connection .
22,605
public String select ( final int index ) { checkIsInMultiOrPipeline ( ) ; client . select ( index ) ; String statusCodeReply = client . getStatusCodeReply ( ) ; client . setDb ( index ) ; return statusCodeReply ; }
Select the DB with having the specified zero - based numeric index . For default every new client connection is automatically selected to DB 0 .
22,606
public Long move ( final byte [ ] key , final int dbIndex ) { checkIsInMultiOrPipeline ( ) ; client . move ( key , dbIndex ) ; return client . getIntegerReply ( ) ; }
Move the specified key from the currently selected DB to the specified destination DB . Note that this command returns 1 only if the key was successfully moved and 0 if the target key was already there or if the source key was not found at all so it is possible to use MOVE as a locking primitive .
22,607
public Long sort ( final byte [ ] key , final SortingParams sortingParameters , final byte [ ] dstkey ) { checkIsInMultiOrPipeline ( ) ; client . sort ( key , sortingParameters , dstkey ) ; return client . getIntegerReply ( ) ; }
Sort a Set or a List accordingly to the specified parameters and store the result at dstkey .
22,608
public String auth ( final String password ) { checkIsInMultiOrPipeline ( ) ; client . auth ( password ) ; return client . getStatusCodeReply ( ) ; }
Request for authentication in a password protected Redis server . A Redis server can be instructed to require a password before to allow clients to issue commands . This is done using the requirepass directive in the Redis configuration file . If the password given by the client is correct the server replies with an OK...
22,609
public byte [ ] brpoplpush ( final byte [ ] source , final byte [ ] destination , final int timeout ) { client . brpoplpush ( source , destination , timeout ) ; client . setTimeoutInfinite ( ) ; try { return client . getBinaryBulkReply ( ) ; } finally { client . rollbackTimeout ( ) ; } }
Pop a value from a list push it to another list and return it ; or block until one is available
22,610
public Boolean setbit ( final byte [ ] key , final long offset , final boolean value ) { checkIsInMultiOrPipeline ( ) ; client . setbit ( key , offset , value ) ; return client . getIntegerReply ( ) == 1 ; }
Sets or clears the bit at offset in the string value stored at key
22,611
public Boolean getbit ( final byte [ ] key , final long offset ) { checkIsInMultiOrPipeline ( ) ; client . getbit ( key , offset ) ; return client . getIntegerReply ( ) == 1 ; }
Returns the bit value at offset in the string value stored at key
22,612
public static String getLocalhost ( ) { if ( localhost == null ) { synchronized ( HostAndPort . class ) { if ( localhost == null ) { return localhost = getLocalHostQuietly ( ) ; } } } return localhost ; }
This method resolves the localhost in a lazy manner .
22,613
public ZParams weights ( final double ... weights ) { params . add ( WEIGHTS . raw ) ; for ( final double weight : weights ) { params . add ( Protocol . toByteArray ( weight ) ) ; } return this ; }
Set weights .
22,614
public void reset ( ) { w . lock ( ) ; try { for ( JedisPool pool : nodes . values ( ) ) { try { if ( pool != null ) { pool . destroy ( ) ; } } catch ( Exception e ) { } } nodes . clear ( ) ; slots . clear ( ) ; } finally { w . unlock ( ) ; } }
Clear discovered nodes collections and gently release allocated resources
22,615
public SortingParams limit ( final int start , final int count ) { params . add ( LIMIT . raw ) ; params . add ( Protocol . toByteArray ( start ) ) ; params . add ( Protocol . toByteArray ( count ) ) ; return this ; }
Limit the Numbers of returned Elements .
22,616
private void populateTaskInput ( Task task ) { if ( StringUtils . isNotBlank ( task . getExternalInputPayloadStoragePath ( ) ) ) { WorkflowTaskMetrics . incrementExternalPayloadUsedCount ( task . getTaskDefName ( ) , ExternalPayloadStorage . Operation . READ . name ( ) , ExternalPayloadStorage . PayloadType . TASK_INPU...
Populates the task input from external payload storage if the external storage path is specified .
22,617
public List < PollData > getPollData ( String taskType ) { Preconditions . checkArgument ( StringUtils . isNotBlank ( taskType ) , "Task type cannot be blank" ) ; Object [ ] params = new Object [ ] { "taskType" , taskType } ; return getForEntity ( "tasks/queue/polldata" , params , pollDataList ) ; }
Get last poll data for a given task type
22,618
public String requeuePendingTasksByTaskType ( String taskType ) { Preconditions . checkArgument ( StringUtils . isNotBlank ( taskType ) , "Task type cannot be blank" ) ; return postForEntity ( "tasks/queue/requeue/{taskType}" , null , null , String . class , taskType ) ; }
Requeue pending tasks of a specific task type
22,619
public SearchResult < TaskSummary > search ( Integer start , Integer size , String sort , String freeText , String query ) { Object [ ] params = new Object [ ] { "start" , start , "size" , size , "sort" , sort , "freeText" , freeText , "query" , query } ; return getForEntity ( "tasks/search" , params , searchResultTask...
Paginated search for tasks based on payload
22,620
private boolean isTransientException ( Throwable throwableException ) { if ( throwableException != null ) { return ! ( ( throwableException instanceof UnsupportedOperationException ) || ( throwableException instanceof ApplicationException && ( ( ApplicationException ) throwableException ) . getCode ( ) != ApplicationEx...
Used to determine if the exception is thrown due to a transient failure and the operation is expected to succeed upon retrying .
22,621
private StatusException throwableToStatusException ( Throwable t ) { String [ ] frames = ExceptionUtils . getStackFrames ( t ) ; Metadata metadata = new Metadata ( ) ; metadata . put ( STATUS_DETAILS_KEY , DebugInfo . newBuilder ( ) . addAllStackEntries ( Arrays . asList ( frames ) ) . setDetail ( ExceptionUtils . getM...
Converts an internal exception thrown by Conductor into an StatusException that uses modern Status metadata for GRPC .
22,622
public Task poll ( String taskType , String workerId , String domain ) { LOGGER . debug ( "Task being polled: /tasks/poll/{}?{}&{}" , taskType , workerId , domain ) ; Task task = executionService . getLastPollTask ( taskType , workerId , domain ) ; if ( task != null ) { LOGGER . debug ( "The Task {} being returned for ...
Poll for a task of a certain type .
22,623
public List < Task > batchPoll ( String taskType , String workerId , String domain , Integer count , Integer timeout ) { List < Task > polledTasks = executionService . poll ( taskType , workerId , domain , count , timeout ) ; LOGGER . debug ( "The Tasks {} being returned for /tasks/poll/{}?{}&{}" , polledTasks . stream...
Batch Poll for a task of a certain type .
22,624
public List < Task > getTasks ( String taskType , String startKey , Integer count ) { return executionService . getTasks ( taskType , startKey , count ) ; }
Get in progress tasks . The results are paginated .
22,625
public Task getPendingTaskForWorkflow ( String workflowId , String taskReferenceName ) { return executionService . getPendingTaskForWorkflow ( taskReferenceName , workflowId ) ; }
Get in progress task for a given workflow id .
22,626
public String updateTask ( TaskResult taskResult ) { LOGGER . debug ( "Update Task: {} with callback time: {}" , taskResult , taskResult . getCallbackAfterSeconds ( ) ) ; executionService . updateTask ( taskResult ) ; LOGGER . debug ( "Task: {} updated successfully with callback time: {}" , taskResult , taskResult . ge...
Updates a task .
22,627
public void log ( String taskId , String log ) { executionService . log ( taskId , log ) ; }
Log Task Execution Details .
22,628
public Map < String , Integer > getTaskQueueSizes ( List < String > taskTypes ) { return executionService . getTaskQueueSizes ( taskTypes ) ; }
Get Task type queue sizes .
22,629
public String requeuePendingTask ( String taskType ) { return String . valueOf ( executionService . requeuePendingTasks ( taskType ) ) ; }
Requeue pending tasks .
22,630
@ SuppressWarnings ( "Guava" ) public T retryOnException ( Supplier < T > supplierCommand , Predicate < Throwable > throwablePredicate , Predicate < T > resultRetryPredicate , int retryCount , String shortDescription , String operationName ) throws RuntimeException { Retryer < T > retryer = RetryerBuilder . < T > newBu...
A helper method which has the ability to execute a flaky supplier function and retry in case of failures .
22,631
public String startWorkflow ( String name , Integer version , String correlationId , Map < String , Object > input ) { WorkflowDef workflowDef = metadataService . getWorkflowDef ( name , version ) ; if ( workflowDef == null ) { throw new ApplicationException ( ApplicationException . Code . NOT_FOUND , String . format (...
Start a new workflow . Returns the ID of the workflow instance that can be later used for tracking .
22,632
public Workflow getExecutionStatus ( String workflowId , boolean includeTasks ) { Workflow workflow = executionService . getExecutionStatus ( workflowId , includeTasks ) ; if ( workflow == null ) { throw new ApplicationException ( ApplicationException . Code . NOT_FOUND , String . format ( "Workflow with Id: %s not fou...
Gets the workflow by workflow Id .
22,633
public List < String > getRunningWorkflows ( String workflowName , Integer version , Long startTime , Long endTime ) { if ( Optional . ofNullable ( startTime ) . orElse ( 0l ) != 0 && Optional . ofNullable ( endTime ) . orElse ( 0l ) != 0 ) { return workflowExecutor . getWorkflows ( workflowName , version , startTime ,...
Retrieves all the running workflows .
22,634
public void skipTaskFromWorkflow ( String workflowId , String taskReferenceName , SkipTaskRequest skipTaskRequest ) { workflowExecutor . skipTaskFromWorkflow ( workflowId , taskReferenceName , skipTaskRequest ) ; }
Skips a given task from a current running workflow .
22,635
public String rerunWorkflow ( String workflowId , RerunWorkflowRequest request ) { request . setReRunFromWorkflowId ( workflowId ) ; return workflowExecutor . rerun ( request ) ; }
Reruns the workflow from a specific task .
22,636
public void terminateWorkflow ( String workflowId , String reason ) { workflowExecutor . terminateWorkflow ( workflowId , reason ) ; }
Terminate workflow execution .
22,637
public void registerWorkflowDef ( WorkflowDef workflowDef ) { Preconditions . checkNotNull ( workflowDef , "Worfklow definition cannot be null" ) ; stub . createWorkflow ( MetadataServicePb . CreateWorkflowRequest . newBuilder ( ) . setWorkflow ( protoMapper . toProto ( workflowDef ) ) . build ( ) ) ; }
Register a workflow definition with the server
22,638
public void registerTaskDefs ( List < TaskDef > taskDefs ) { Preconditions . checkNotNull ( taskDefs , "Task defs list cannot be null" ) ; stub . createTasks ( MetadataServicePb . CreateTasksRequest . newBuilder ( ) . addAllDefs ( taskDefs . stream ( ) . map ( protoMapper :: toProto ) :: iterator ) . build ( ) ) ; }
Registers a list of task types with the conductor server
22,639
public void updateTaskDef ( TaskDef taskDef ) { Preconditions . checkNotNull ( taskDef , "Task definition cannot be null" ) ; stub . updateTask ( MetadataServicePb . UpdateTaskRequest . newBuilder ( ) . setTask ( protoMapper . toProto ( taskDef ) ) . build ( ) ) ; }
Updates an existing task definition
22,640
public String createWorkflow ( Workflow workflow ) { executionDAO . createWorkflow ( workflow ) ; indexDAO . indexWorkflow ( workflow ) ; return workflow . getWorkflowId ( ) ; }
Creates a new workflow in the data store
22,641
public String updateWorkflow ( Workflow workflow ) { executionDAO . updateWorkflow ( workflow ) ; indexDAO . indexWorkflow ( workflow ) ; return workflow . getWorkflowId ( ) ; }
Updates the given workflow in the data store
22,642
public void removeWorkflow ( String workflowId , boolean archiveWorkflow ) { try { Workflow workflow = getWorkflowById ( workflowId , true ) ; if ( archiveWorkflow ) { indexDAO . updateWorkflow ( workflowId , new String [ ] { RAW_JSON_FIELD , ARCHIVED_FIELD } , new Object [ ] { objectMapper . writeValueAsString ( workf...
Removes the workflow from the data store .
22,643
public DeciderOutcome decide ( Workflow workflow ) throws TerminateWorkflowException { final List < Task > tasks = workflow . getTasks ( ) ; List < Task > unprocessedTasks = tasks . stream ( ) . filter ( t -> ! t . getStatus ( ) . equals ( SKIPPED ) && ! t . getStatus ( ) . equals ( READY_FOR_RERUN ) && ! t . isExecute...
QQ public method validation of the input params
22,644
@ SuppressWarnings ( "unchecked" ) public Map < String , Object > downloadPayload ( String path ) { try ( InputStream inputStream = externalPayloadStorage . download ( path ) ) { return objectMapper . readValue ( IOUtils . toString ( inputStream ) , Map . class ) ; } catch ( IOException e ) { logger . error ( "Unable t...
Download the payload from the given path
22,645
private void createIndexesTemplates ( ) { try { initIndexesTemplates ( ) ; updateIndexesNames ( ) ; Executors . newScheduledThreadPool ( 1 ) . scheduleAtFixedRate ( this :: updateIndexesNames , 0 , 1 , TimeUnit . HOURS ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } }
Initializes the indexes templates task_log message and event and mappings .
22,646
public void unregisterWorkflowDef ( String name , Integer version ) { Preconditions . checkArgument ( StringUtils . isNotBlank ( name ) , "Workflow name cannot be blank" ) ; Preconditions . checkNotNull ( version , "Version cannot be null" ) ; delete ( "metadata/workflow/{name}/{version}" , name , version ) ; }
Removes the workflow definition of a workflow from the conductor server . It does not remove associated workflows . Use with caution .
22,647
private void waitForHealthyCluster ( ) throws Exception { Map < String , String > params = new HashMap < > ( ) ; params . put ( "wait_for_status" , this . clusterHealthColor ) ; params . put ( "timeout" , "30s" ) ; elasticSearchAdminClient . performRequest ( "GET" , "/_cluster/health" , params ) ; }
Waits for the ES cluster to become green .
22,648
private void updateIndexName ( ) { this . logIndexName = this . logIndexPrefix + "_" + SIMPLE_DATE_FORMAT . format ( new Date ( ) ) ; try { addIndex ( logIndexName ) ; } catch ( IOException e ) { logger . error ( "Failed to update log index name: {}" , logIndexName , e ) ; } }
Roll the tasklog index daily .
22,649
private void addIndex ( final String index ) throws IOException { logger . info ( "Adding index '{}'..." , index ) ; String resourcePath = "/" + index ; if ( doesResourceNotExist ( resourcePath ) ) { try { elasticSearchAdminClient . performRequest ( HttpMethod . PUT , resourcePath ) ; logger . info ( "Added '{}' index"...
Adds an index to elasticsearch if it does not exist .
22,650
public boolean doesResourceExist ( final String resourcePath ) throws IOException { Response response = elasticSearchAdminClient . performRequest ( HttpMethod . HEAD , resourcePath ) ; return response . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ; }
Determines whether a resource exists in ES . This will call a GET method to a particular path and return true if status 200 ; false otherwise .
22,651
private SearchResult < String > searchObjectIds ( String indexName , QueryBuilder queryBuilder , int start , int size , List < String > sortOptions , String docType ) throws IOException { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder ( ) ; searchSourceBuilder . query ( queryBuilder ) ; searchSourceB...
Tries to find object ids for a given query in an index .
22,652
private void indexWithRetry ( final IndexRequest request , final String operationDescription ) { try { new RetryUtil < IndexResponse > ( ) . retryOnException ( ( ) -> { try { return elasticSearchClient . index ( request ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } , null , null , RETRY_COUNT ,...
Performs an index operation with a retry .
22,653
public void addEventHandler ( EventHandler eventHandler ) { Preconditions . checkNotNull ( eventHandler . getName ( ) , "Missing Name" ) ; if ( getEventHandler ( eventHandler . getName ( ) ) != null ) { throw new ApplicationException ( Code . CONFLICT , "EventHandler with name " + eventHandler . getName ( ) + " already...
Event Handler APIs
22,654
private void populateWorkflowOutput ( Workflow workflow ) { if ( StringUtils . isNotBlank ( workflow . getExternalOutputPayloadStoragePath ( ) ) ) { WorkflowTaskMetrics . incrementExternalPayloadUsedCount ( workflow . getWorkflowName ( ) , ExternalPayloadStorage . Operation . READ . name ( ) , ExternalPayloadStorage . ...
Populates the workflow output from external payload storage if the external storage path is specified .
22,655
public List < String > getRunningWorkflow ( String workflowName , Integer version ) { Preconditions . checkArgument ( StringUtils . isNotBlank ( workflowName ) , "Workflow name cannot be blank" ) ; return getForEntity ( "workflow/running/{name}" , new Object [ ] { "version" , version } , new GenericType < List < String...
Retrieve all running workflow instances for a given name and version
22,656
public void runDecider ( String workflowId ) { Preconditions . checkArgument ( StringUtils . isNotBlank ( workflowId ) , "workflow id cannot be blank" ) ; put ( "workflow/decide/{workflowId}" , null , null , workflowId ) ; }
Starts the decision task for the given workflow instance
22,657
@ Path ( "/resume" ) @ ApiOperation ( "Resume the list of workflows" ) public BulkResponse resumeWorkflow ( List < String > workflowIds ) { return workflowBulkService . resumeWorkflow ( workflowIds ) ; }
Resume the list of workflows .
22,658
@ Path ( "/retry" ) @ ApiOperation ( "Retry the last failed task for each workflow from the list" ) public BulkResponse retry ( List < String > workflowIds ) { return workflowBulkService . retry ( workflowIds ) ; }
Retry the last failed task for each workflow from the list .
22,659
public Map < String , Object > getAllConfig ( ) { Map < String , Object > map = config . getAll ( ) ; map . put ( "version" , version ) ; map . put ( "buildDate" , buildDate ) ; return map ; }
Get all the configuration parameters .
22,660
public List < Task > getListOfPendingTask ( String taskType , Integer start , Integer count ) { List < Task > tasks = executionService . getPendingTasksForTaskType ( taskType ) ; int total = start + count ; total = ( tasks . size ( ) > total ) ? total : tasks . size ( ) ; if ( start > tasks . size ( ) ) start = tasks ....
Get the list of pending tasks for a given task type .
22,661
public String requeueSweep ( String workflowId ) { boolean pushed = queueDAO . pushIfNotExists ( WorkflowExecutor . DECIDER_QUEUE , workflowId , config . getSweepFrequency ( ) ) ; return pushed + "." + workflowId ; }
Queue up all the running workflows for sweep .
22,662
public static List < String > validateInputParam ( Map < String , Object > input , String taskName , WorkflowDef workflow ) { ArrayList < String > errorList = new ArrayList < > ( ) ; for ( Entry < String , Object > e : input . entrySet ( ) ) { Object value = e . getValue ( ) ; if ( value instanceof String ) { errorList...
Validates inputParam and returns a list of errors if input is not valid .
22,663
public InputStream download ( String path ) { try { S3Object s3Object = s3Client . getObject ( new GetObjectRequest ( bucketName , path ) ) ; return s3Object . getObjectContent ( ) ; } catch ( SdkClientException e ) { String msg = "Error communicating with S3" ; logger . error ( msg , e ) ; throw new ApplicationExcepti...
Downloads the payload stored in the s3 object .
22,664
private void parse ( ) throws ParserException { skipWhitespace ( ) ; try { _parse ( ) ; } catch ( Exception e ) { System . out . println ( "\t" + this . getClass ( ) . getSimpleName ( ) + "->" + this . toString ( ) ) ; if ( ! ( e instanceof ParserException ) ) { throw new ParserException ( "Error parsing" , e ) ; } els...
Public stuff here
22,665
public List < EventHandler > getEventHandlersForEvent ( String event , boolean activeOnly ) { return metadataService . getEventHandlersForEvent ( event , activeOnly ) ; }
Get event handlers for a given event .
22,666
public void upload ( String uri , InputStream payload , long payloadSize ) { HttpURLConnection connection = null ; try { URL url = new URI ( uri ) . toURL ( ) ; connection = ( HttpURLConnection ) url . openConnection ( ) ; connection . setDoOutput ( true ) ; connection . setRequestMethod ( "PUT" ) ; try ( BufferedOutpu...
Uploads the payload to the uri specified .
22,667
public InputStream download ( String uri ) { HttpURLConnection connection = null ; String errorMsg ; try { URL url = new URI ( uri ) . toURL ( ) ; connection = ( HttpURLConnection ) url . openConnection ( ) ; connection . setDoOutput ( false ) ; int responseCode = connection . getResponseCode ( ) ; if ( responseCode ==...
Downloads the payload from the given uri .
22,668
public Query addParameters ( Object ... values ) { for ( Object v : values ) { if ( v instanceof String ) { addParameter ( ( String ) v ) ; } else if ( v instanceof Integer ) { addParameter ( ( Integer ) v ) ; } else if ( v instanceof Long ) { addParameter ( ( Long ) v ) ; } else if ( v instanceof Double ) { addParamet...
Add many primitive values at once .
22,669
public < V > V executeScalar ( Class < V > returnType ) { try ( ResultSet rs = executeQuery ( ) ) { if ( ! rs . next ( ) ) { Object value = null ; if ( Integer . class == returnType ) { value = 0 ; } else if ( Long . class == returnType ) { value = 0L ; } else if ( Boolean . class == returnType ) { value = false ; } re...
Execute the PreparedStatement and return a single primitive value from the ResultSet .
22,670
public < V > List < V > executeScalarList ( Class < V > returnType ) { try ( ResultSet rs = executeQuery ( ) ) { List < V > values = new ArrayList < > ( ) ; while ( rs . next ( ) ) { values . add ( getScalarFromResultSet ( rs , returnType ) ) ; } return values ; } catch ( SQLException ex ) { throw new ApplicationExcept...
Execute the PreparedStatement and return a List of primitive values from the ResultSet .
22,671
public < V > V executeAndFetchFirst ( Class < V > returnType ) { Object o = executeScalar ( ) ; if ( null == o ) { return null ; } return convert ( o , returnType ) ; }
Execute the statement and return only the first record from the result set .
22,672
public String startWorkflow ( StartWorkflowRequest startWorkflowRequest ) { Preconditions . checkNotNull ( startWorkflowRequest , "StartWorkflowRequest cannot be null" ) ; return stub . startWorkflow ( protoMapper . toProto ( startWorkflowRequest ) ) . getWorkflowId ( ) ; }
Starts a workflow
22,673
public void pauseWorkflow ( String workflowId ) { Preconditions . checkArgument ( StringUtils . isNotBlank ( workflowId ) , "workflow id cannot be blank" ) ; stub . pauseWorkflow ( WorkflowServicePb . PauseWorkflowRequest . newBuilder ( ) . setWorkflowId ( workflowId ) . build ( ) ) ; }
Pause a workflow by workflow id
22,674
public void resumeWorkflow ( String workflowId ) { Preconditions . checkArgument ( StringUtils . isNotBlank ( workflowId ) , "workflow id cannot be blank" ) ; stub . resumeWorkflow ( WorkflowServicePb . ResumeWorkflowRequest . newBuilder ( ) . setWorkflowId ( workflowId ) . build ( ) ) ; }
Resume a paused workflow by workflow id
22,675
private String readString ( InputStream is ) throws Exception { char delim = ( char ) read ( 1 ) [ 0 ] ; StringBuilder sb = new StringBuilder ( ) ; boolean valid = false ; while ( is . available ( ) > 0 ) { char c = ( char ) is . read ( ) ; if ( c == delim ) { valid = true ; break ; } else if ( c == '\\' ) { c = ( char...
Reads an escaped string
22,676
protected void execute ( Connection tx , String query , ExecuteFunction function ) { try ( Query q = new Query ( objectMapper , tx , query ) ) { function . apply ( q ) ; } catch ( SQLException ex ) { throw new ApplicationException ( ApplicationException . Code . BACKEND_ERROR , ex ) ; } }
Execute a statement with no expected return value within a given transaction .
22,677
private void validateWorkflow ( WorkflowDef workflowDef , Map < String , Object > workflowInput , String externalStoragePath ) { try { if ( workflowInput == null && StringUtils . isBlank ( externalStoragePath ) ) { LOGGER . error ( "The input for the workflow '{}' cannot be NULL" , workflowDef . getName ( ) ) ; throw n...
Performs validations for starting a workflow
22,678
private Task taskToBeRescheduled ( Task task ) { Task taskToBeRetried = task . copy ( ) ; taskToBeRetried . setTaskId ( IDGenerator . generate ( ) ) ; taskToBeRetried . setRetriedTaskId ( task . getTaskId ( ) ) ; taskToBeRetried . setStatus ( SCHEDULED ) ; taskToBeRetried . setRetryCount ( task . getRetryCount ( ) + 1 ...
Reschedule a task
22,679
public Object expand ( Object input ) { if ( input instanceof List ) { expandList ( ( List < Object > ) input ) ; return input ; } else if ( input instanceof Map ) { expandMap ( ( Map < String , Object > ) input ) ; return input ; } else if ( input instanceof String ) { return getJson ( ( String ) input ) ; } else { re...
Expands a JSON object into a java object
22,680
private Object getJson ( String jsonAsString ) { try { return objectMapper . readValue ( jsonAsString , Object . class ) ; } catch ( Exception e ) { logger . info ( "Unable to parse (json?) string: {}" , jsonAsString , e ) ; return jsonAsString ; } }
Used to obtain a JSONified object from a string
22,681
public static List < String > convertStringToList ( String inputStr ) { List < String > list = new ArrayList < String > ( ) ; if ( StringUtils . isNotBlank ( inputStr ) ) { list = Arrays . asList ( inputStr . split ( "\\|" ) ) ; } return list ; }
Split string with | as delimiter .
22,682
public static void checkArgument ( boolean condition , String errorMessage ) { if ( ! condition ) { throw new ApplicationException ( ApplicationException . Code . INVALID_INPUT , errorMessage ) ; } }
Ensures the truth of an condition involving one or more parameters to the calling method .
22,683
public static void checkNotNullOrEmpty ( Map < ? , ? > map , String errorMessage ) { if ( map == null || map . isEmpty ( ) ) { throw new ApplicationException ( ApplicationException . Code . INVALID_INPUT , errorMessage ) ; } }
This method checks if the input map is valid or not .
22,684
public static void checkNotNullOrEmpty ( String input , String errorMessage ) { try { Preconditions . checkArgument ( StringUtils . isNotBlank ( input ) , errorMessage ) ; } catch ( IllegalArgumentException exception ) { throw new ApplicationException ( ApplicationException . Code . INVALID_INPUT , errorMessage ) ; } }
This method checks it the input string is null or empty .
22,685
public static void checkNotNull ( Object object , String errorMessage ) { try { Preconditions . checkNotNull ( object , errorMessage ) ; } catch ( NullPointerException exception ) { throw new ApplicationException ( ApplicationException . Code . INVALID_INPUT , errorMessage ) ; } }
This method checks if the object is null or empty .
22,686
private String clientResponseToString ( ClientResponse response ) { if ( response == null ) { return null ; } StringBuilder builder = new StringBuilder ( ) ; builder . append ( "[status: " ) . append ( response . getStatus ( ) ) ; builder . append ( ", media type: " ) . append ( response . getType ( ) ) ; if ( response...
Converts ClientResponse object to string with detailed debug information including status code media type response headers and response body if exists .
22,687
private void initIndex ( ) throws Exception { GetIndexTemplatesResponse result = elasticSearchClient . admin ( ) . indices ( ) . prepareGetTemplates ( "tasklog_template" ) . execute ( ) . actionGet ( ) ; if ( result . getIndexTemplates ( ) . isEmpty ( ) ) { logger . info ( "Creating the index template 'tasklog_template...
Initializes the index with required templates and mappings .
22,688
private static void counter ( String className , String name , String ... additionalTags ) { getCounter ( className , name , additionalTags ) . increment ( ) ; }
Increment a counter that is used to measure the rate at which some event is occurring . Consider a simple queue counters would be used to measure things like the rate at which items are being inserted and removed .
22,689
private static void gauge ( String className , String name , long measurement , String ... additionalTags ) { getGauge ( className , name , additionalTags ) . getAndSet ( measurement ) ; }
Set a gauge is a handle to get the current value . Typical examples for gauges would be the size of a queue or number of threads in the running state . Since gauges are sampled there is no information about what might have occurred between samples .
22,690
public Iterator < Task > batchPollTasksByTaskTypeAsync ( String taskType , String workerId , int count , int timeoutInMillisecond ) { Preconditions . checkArgument ( StringUtils . isNotBlank ( taskType ) , "Task type cannot be blank" ) ; Preconditions . checkArgument ( StringUtils . isNotBlank ( workerId ) , "Worker id...
Perform a batch poll for tasks by task type . Batch size is configurable by count . Returns an iterator that streams tasks as they become available through GRPC .
22,691
public void updateTask ( TaskResult taskResult ) { Preconditions . checkNotNull ( taskResult , "Task result cannot be null" ) ; stub . updateTask ( TaskServicePb . UpdateTaskRequest . newBuilder ( ) . setResult ( protoMapper . toProto ( taskResult ) ) . build ( ) ) ; }
Updates the result of a task execution .
22,692
public Observable < HttpClientResponse < O > > submit ( Server server , final HttpClientRequest < I > request , final IClientConfig requestConfig ) { return submit ( server , request , null , requestConfig , getRxClientConfig ( requestConfig ) ) ; }
Submit a request to run on a specific server
22,693
protected ServerOperation < HttpClientResponse < O > > requestToOperation ( final HttpClientRequest < I > request , final ClientConfig rxClientConfig ) { Preconditions . checkNotNull ( request ) ; return new ServerOperation < HttpClientResponse < O > > ( ) { final AtomicInteger count = new AtomicInteger ( 0 ) ; public ...
Convert an HttpClientRequest to a ServerOperation
22,694
private RxClient . ClientConfig getRxClientConfig ( IClientConfig requestConfig ) { if ( requestConfig == null ) { return DEFAULT_RX_CONFIG ; } int requestReadTimeout = getProperty ( IClientConfigKey . Keys . ReadTimeout , requestConfig , DefaultClientConfigImpl . DEFAULT_READ_TIMEOUT ) ; Boolean followRedirect = getPr...
Construct an RxClient . ClientConfig from an IClientConfig
22,695
private Observable < HttpClientResponse < O > > submit ( final Server server , final HttpClientRequest < I > request , final RetryHandler errorHandler , final IClientConfig requestConfig , final ClientConfig rxClientConfig ) { RetryHandler retryHandler = errorHandler ; if ( retryHandler == null ) { retryHandler = getRe...
Subject an operation to run in the load balancer
22,696
private Observable < HttpClientResponse < O > > submitToServerInURI ( HttpClientRequest < I > request , IClientConfig requestConfig , ClientConfig config , RetryHandler errorHandler , ExecutionContext < HttpClientRequest < I > > context ) { URI uri ; try { uri = new URI ( request . getUri ( ) ) ; } catch ( URISyntaxExc...
Submits the request to the server indicated in the URI
22,697
static public HashMap getErrorCodes ( Class clazz ) { HashMap map = new HashMap ( 23 ) ; Field flds [ ] = clazz . getDeclaredFields ( ) ; for ( int i = 0 ; i < flds . length ; i ++ ) { int mods = flds [ i ] . getModifiers ( ) ; if ( Modifier . isFinal ( mods ) && Modifier . isStatic ( mods ) && Modifier . isPublic ( mo...
Return the codes that are defined on a subclass of our class .
22,698
public List < Server > getEligibleServers ( List < Server > servers , Object loadBalancerKey ) { if ( loadBalancerKey == null ) { return ImmutableList . copyOf ( Iterables . filter ( servers , this . getServerOnlyPredicate ( ) ) ) ; } else { List < Server > results = Lists . newArrayList ( ) ; for ( Server server : ser...
Get servers filtered by this predicate from list of servers .
22,699
public Optional < Server > chooseRandomlyAfterFiltering ( List < Server > servers ) { List < Server > eligible = getEligibleServers ( servers ) ; if ( eligible . size ( ) == 0 ) { return Optional . absent ( ) ; } return Optional . of ( eligible . get ( random . nextInt ( eligible . size ( ) ) ) ) ; }
Choose a random server after the predicate filters a list of servers . Load balancer key is presumed to be null .