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 ( ) ) { return new SecretKeySpec ( bytes , alg . getJcaName ( ) ) ; } } String msg = "The specified key byte array is " + bitLength + " bits which " + "is not secure enough for any JWT HMAC-SHA algorithm. The JWT " + "JWA Specification (RFC 7518, Section 3.2) states that keys used with HMAC-SHA algorithms MUST have a " + "size >= 256 bits (the key size must be greater than or equal to the hash " + "output size). Consider using the " + Keys . class . getName ( ) + "#secretKeyFor(SignatureAlgorithm) method " + "to create a key guaranteed to be secure enough for your preferred HMAC-SHA algorithm. See " + "https://tools.ietf.org/html/rfc7518#section-3.2 for more information." ; throw new WeakKeyException ( msg ) ; } | 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< ; ?> ; 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 status code reply and starts accepting commands from the client . Otherwise an error is returned and the clients needs to try a new password . Note that for the high performance nature of Redis it is possible to try a lot of passwords in parallel in very short time so make sure to generate a strong and very long password so that this attack is infeasible . |
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_INPUT . name ( ) ) ; task . setInputData ( downloadFromExternalStorage ( ExternalPayloadStorage . PayloadType . TASK_INPUT , task . getExternalInputPayloadStoragePath ( ) ) ) ; task . setExternalInputPayloadStoragePath ( null ) ; } } | 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 , searchResultTaskSummary ) ; } | 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 ( ) != ApplicationException . Code . BACKEND_ERROR ) ) ; } return true ; } | 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 . getMessage ( t ) ) . build ( ) ) ; return Status . INTERNAL . withDescription ( t . getMessage ( ) ) . withCause ( t ) . asException ( metadata ) ; } | 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 /tasks/poll/{}?{}&{}" , task , taskType , workerId , domain ) ; } Monitors . recordTaskPollCount ( taskType , domain , 1 ) ; return task ; } | 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 ( ) . map ( Task :: getTaskId ) . collect ( Collectors . toList ( ) ) , taskType , workerId , domain ) ; Monitors . recordTaskPollCount ( taskType , domain , polledTasks . size ( ) ) ; return polledTasks ; } | 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 . getCallbackAfterSeconds ( ) ) ; return taskResult . getTaskId ( ) ; } | 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 > newBuilder ( ) . retryIfException ( Optional . ofNullable ( throwablePredicate ) . orElse ( exception -> true ) ) . retryIfResult ( Optional . ofNullable ( resultRetryPredicate ) . orElse ( result -> false ) ) . withWaitStrategy ( WaitStrategies . join ( WaitStrategies . exponentialWait ( 1000 , 90 , TimeUnit . SECONDS ) , WaitStrategies . randomWait ( 100 , TimeUnit . MILLISECONDS , 500 , TimeUnit . MILLISECONDS ) ) ) . withStopStrategy ( StopStrategies . stopAfterAttempt ( retryCount ) ) . withBlockStrategy ( BlockStrategies . threadSleepStrategy ( ) ) . withRetryListener ( new RetryListener ( ) { public < V > void onRetry ( Attempt < V > attempt ) { logger . debug ( "Attempt # {}, {} millis since first attempt. Operation: {}, description:{}" , attempt . getAttemptNumber ( ) , attempt . getDelaySinceFirstAttempt ( ) , operationName , shortDescription ) ; internalNumberOfRetries . incrementAndGet ( ) ; } } ) . build ( ) ; try { return retryer . call ( supplierCommand :: get ) ; } catch ( ExecutionException executionException ) { String errorMessage = String . format ( "Operation '%s:%s' failed for the %d time in RetryUtil" , operationName , shortDescription , internalNumberOfRetries . get ( ) ) ; logger . debug ( errorMessage ) ; throw new RuntimeException ( errorMessage , executionException . getCause ( ) ) ; } catch ( RetryException retryException ) { String errorMessage = String . format ( "Operation '%s:%s' failed after retrying %d times, retry limit %d" , operationName , shortDescription , internalNumberOfRetries . get ( ) , 3 ) ; logger . debug ( errorMessage , retryException . getLastFailedAttempt ( ) . getExceptionCause ( ) ) ; throw new RuntimeException ( errorMessage , retryException . getLastFailedAttempt ( ) . getExceptionCause ( ) ) ; } } | 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 ( "No such workflow found by name: %s, version: %d" , name , version ) ) ; } return workflowExecutor . startWorkflow ( workflowDef . getName ( ) , workflowDef . getVersion ( ) , correlationId , input , null ) ; } | 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 found." , workflowId ) ) ; } return workflow ; } | 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 , endTime ) ; } else { return workflowExecutor . getRunningWorkflowIds ( workflowName ) ; } } | 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 ( workflow ) , true } ) ; } else { indexDAO . removeWorkflow ( workflowId ) ; } try { executionDAO . removeWorkflow ( workflowId ) ; } catch ( Exception ex ) { Monitors . recordDaoError ( "executionDao" , "removeWorkflow" ) ; throw ex ; } } catch ( Exception e ) { throw new ApplicationException ( ApplicationException . Code . BACKEND_ERROR , "Error removing workflow: " + workflowId , e ) ; } } | 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 . isExecuted ( ) ) . collect ( Collectors . toList ( ) ) ; List < Task > tasksToBeScheduled = new LinkedList < > ( ) ; if ( unprocessedTasks . isEmpty ( ) ) { tasksToBeScheduled = startWorkflow ( workflow ) ; if ( tasksToBeScheduled == null ) { tasksToBeScheduled = new LinkedList < > ( ) ; } } return decide ( workflow , tasksToBeScheduled ) ; } | 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 to download payload from external storage path: {}" , path , e ) ; throw new ApplicationException ( ApplicationException . Code . INTERNAL_ERROR , e ) ; } } | 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" , index ) ; } catch ( ResponseException e ) { boolean errorCreatingIndex = true ; Response errorResponse = e . getResponse ( ) ; if ( errorResponse . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_BAD_REQUEST ) { JsonNode root = objectMapper . readTree ( EntityUtils . toString ( errorResponse . getEntity ( ) ) ) ; String errorCode = root . get ( "error" ) . get ( "type" ) . asText ( ) ; if ( "index_already_exists_exception" . equals ( errorCode ) ) { errorCreatingIndex = false ; } } if ( errorCreatingIndex ) { throw e ; } } } else { logger . info ( "Index '{}' already exists" , 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 ) ; searchSourceBuilder . from ( start ) ; searchSourceBuilder . size ( size ) ; if ( sortOptions != null && ! sortOptions . isEmpty ( ) ) { for ( String sortOption : sortOptions ) { SortOrder order = SortOrder . ASC ; String field = sortOption ; int index = sortOption . indexOf ( ":" ) ; if ( index > 0 ) { field = sortOption . substring ( 0 , index ) ; order = SortOrder . valueOf ( sortOption . substring ( index + 1 ) ) ; } searchSourceBuilder . sort ( new FieldSortBuilder ( field ) . order ( order ) ) ; } } SearchRequest searchRequest = new SearchRequest ( indexName ) ; searchRequest . types ( docType ) ; searchRequest . source ( searchSourceBuilder ) ; SearchResponse response = elasticSearchClient . search ( searchRequest ) ; List < String > result = new LinkedList < > ( ) ; response . getHits ( ) . forEach ( hit -> result . add ( hit . getId ( ) ) ) ; long count = response . getHits ( ) . getTotalHits ( ) ; return new SearchResult < > ( count , result ) ; } | 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 , operationDescription , "indexWithRetry" ) ; } catch ( Exception e ) { Monitors . error ( className , "index" ) ; logger . error ( "Failed to index {} for request type: {}" , request . id ( ) , request . type ( ) , e ) ; } } | 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 exists!" ) ; } index ( eventHandler ) ; dynoClient . hset ( nsKey ( EVENT_HANDLERS ) , eventHandler . getName ( ) , toJson ( eventHandler ) ) ; recordRedisDaoRequests ( "addEventHandler" ) ; } | Event Handler APIs |
22,654 | private void populateWorkflowOutput ( Workflow workflow ) { if ( StringUtils . isNotBlank ( workflow . getExternalOutputPayloadStoragePath ( ) ) ) { WorkflowTaskMetrics . incrementExternalPayloadUsedCount ( workflow . getWorkflowName ( ) , ExternalPayloadStorage . Operation . READ . name ( ) , ExternalPayloadStorage . PayloadType . WORKFLOW_OUTPUT . name ( ) ) ; workflow . setOutput ( downloadFromExternalStorage ( ExternalPayloadStorage . PayloadType . WORKFLOW_OUTPUT , workflow . getExternalOutputPayloadStoragePath ( ) ) ) ; } } | 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 > > ( ) { } , workflowName ) ; } | 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 . size ( ) ; return tasks . subList ( start , total ) ; } | 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 . addAll ( extractParamPathComponentsFromString ( e . getKey ( ) , value . toString ( ) , taskName , workflow ) ) ; } else if ( value instanceof Map ) { errorList . addAll ( validateInputParam ( ( Map < String , Object > ) value , taskName , workflow ) ) ; } else if ( value instanceof List ) { errorList . addAll ( extractListInputParam ( e . getKey ( ) , ( List < ? > ) value , taskName , workflow ) ) ; } else { e . setValue ( value ) ; } } return 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 ApplicationException ( ApplicationException . Code . BACKEND_ERROR , msg , e ) ; } } | 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 ) ; } else { throw ( ParserException ) e ; } } skipWhitespace ( ) ; } | 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 ( BufferedOutputStream bufferedOutputStream = new BufferedOutputStream ( connection . getOutputStream ( ) ) ) { long count = IOUtils . copy ( payload , bufferedOutputStream ) ; bufferedOutputStream . flush ( ) ; logger . debug ( "Uploaded {} bytes to uri: {}" , count , uri ) ; int responseCode = connection . getResponseCode ( ) ; logger . debug ( "Upload completed with HTTP response code: {}" , responseCode ) ; } } catch ( URISyntaxException | MalformedURLException e ) { String errorMsg = String . format ( "Invalid path specified: %s" , uri ) ; logger . error ( errorMsg , e ) ; throw new ConductorClientException ( errorMsg , e ) ; } catch ( IOException e ) { String errorMsg = String . format ( "Error uploading to path: %s" , uri ) ; logger . error ( errorMsg , e ) ; throw new ConductorClientException ( errorMsg , e ) ; } finally { if ( connection != null ) { connection . disconnect ( ) ; } try { if ( payload != null ) { payload . close ( ) ; } } catch ( IOException e ) { logger . warn ( "Unable to close inputstream when uploading to uri: {}" , uri ) ; } } } | 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 == HttpURLConnection . HTTP_OK ) { logger . debug ( "Download completed with HTTP response code: {}" , connection . getResponseCode ( ) ) ; return org . apache . commons . io . IOUtils . toBufferedInputStream ( connection . getInputStream ( ) ) ; } errorMsg = String . format ( "Unable to download. Response code: %d" , responseCode ) ; logger . error ( errorMsg ) ; throw new ConductorClientException ( errorMsg ) ; } catch ( URISyntaxException | MalformedURLException e ) { errorMsg = String . format ( "Invalid uri specified: %s" , uri ) ; logger . error ( errorMsg , e ) ; throw new ConductorClientException ( errorMsg , e ) ; } catch ( IOException e ) { errorMsg = String . format ( "Error downloading from uri: %s" , uri ) ; logger . error ( errorMsg , e ) ; throw new ConductorClientException ( errorMsg , e ) ; } finally { if ( connection != null ) { connection . disconnect ( ) ; } } } | 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 ) { addParameter ( ( Double ) v ) ; } else if ( v instanceof Boolean ) { addParameter ( ( Boolean ) v ) ; } else if ( v instanceof Date ) { addParameter ( ( Date ) v ) ; } else if ( v instanceof Timestamp ) { addParameter ( ( Timestamp ) v ) ; } else { throw new IllegalArgumentException ( "Type " + v . getClass ( ) . getName ( ) + " is not supported by automatic property assignment" ) ; } } return this ; } | 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 ; } return returnType . cast ( value ) ; } else { return getScalarFromResultSet ( rs , returnType ) ; } } catch ( SQLException ex ) { throw new ApplicationException ( Code . BACKEND_ERROR , ex ) ; } } | 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 ApplicationException ( Code . BACKEND_ERROR , ex ) ; } } | 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 ) is . read ( ) ; sb . append ( c ) ; } else { sb . append ( c ) ; } } if ( ! valid ) { throw new ParserException ( "String constant is not quoted with <" + delim + "> : " + sb . toString ( ) ) ; } return "\"" + sb . toString ( ) + "\"" ; } | 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 new ApplicationException ( INVALID_INPUT , "NULL input passed when starting workflow" ) ; } } catch ( Exception e ) { Monitors . recordWorkflowStartError ( workflowDef . getName ( ) , WorkflowContext . get ( ) . getClientApp ( ) ) ; throw e ; } } | 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 ) ; taskToBeRetried . setRetried ( false ) ; taskToBeRetried . setPollCount ( 0 ) ; taskToBeRetried . setCallbackAfterSeconds ( 0 ) ; task . setRetried ( true ) ; return taskToBeRetried ; } | 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 { return input ; } } | 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 . getStatus ( ) != 404 ) { try { String responseBody = response . getEntity ( String . class ) ; if ( responseBody != null ) { builder . append ( ", response body: " ) . append ( responseBody ) ; } } catch ( RuntimeException ignore ) { } } builder . append ( ", response headers: " ) . append ( response . getHeaders ( ) ) ; builder . append ( "]" ) ; return builder . toString ( ) ; } | 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'" ) ; InputStream stream = ElasticSearchDAOV5 . class . getResourceAsStream ( "/template_tasklog.json" ) ; byte [ ] templateSource = IOUtils . toByteArray ( stream ) ; try { elasticSearchClient . admin ( ) . indices ( ) . preparePutTemplate ( "tasklog_template" ) . setSource ( templateSource , XContentType . JSON ) . execute ( ) . actionGet ( ) ; } catch ( Exception e ) { logger . error ( "Failed to init tasklog_template" , e ) ; } } } | 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 cannot be blank" ) ; Preconditions . checkArgument ( count > 0 , "Count must be greater than 0" ) ; Iterator < TaskPb . Task > it = stub . batchPoll ( TaskServicePb . BatchPollRequest . newBuilder ( ) . setTaskType ( taskType ) . setWorkerId ( workerId ) . setCount ( count ) . setTimeout ( timeoutInMillisecond ) . build ( ) ) ; return Iterators . transform ( it , protoMapper :: fromProto ) ; } | 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 Observable < HttpClientResponse < O > > call ( Server server ) { HttpClient < I , O > rxClient = getOrCreateRxClient ( server ) ; setHostHeader ( request , server . getHost ( ) ) ; Observable < HttpClientResponse < O > > o ; if ( rxClientConfig != null ) { o = rxClient . submit ( request , rxClientConfig ) ; } else { o = rxClient . submit ( request ) ; } return o . concatMap ( new Func1 < HttpClientResponse < O > , Observable < HttpClientResponse < O > > > ( ) { public Observable < HttpClientResponse < O > > call ( HttpClientResponse < O > t1 ) { if ( t1 . getStatus ( ) . code ( ) / 100 == 4 || t1 . getStatus ( ) . code ( ) / 100 == 5 ) return responseToErrorPolicy . call ( t1 , backoffStrategy . call ( count . getAndIncrement ( ) ) ) ; else return Observable . just ( t1 ) ; } } ) ; } } ; } | 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 = getProperty ( IClientConfigKey . Keys . FollowRedirects , requestConfig , null ) ; HttpClientConfig . Builder builder = new HttpClientConfig . Builder ( ) . readTimeout ( requestReadTimeout , TimeUnit . MILLISECONDS ) ; if ( followRedirect != null ) { builder . setFollowRedirect ( followRedirect ) ; } return builder . build ( ) ; } | 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 = getRequestRetryHandler ( request , requestConfig ) ; } final IClientConfig config = requestConfig == null ? DefaultClientConfigImpl . getEmptyConfig ( ) : requestConfig ; final ExecutionContext < HttpClientRequest < I > > context = new ExecutionContext < HttpClientRequest < I > > ( request , config , this . getClientConfig ( ) , retryHandler ) ; Observable < HttpClientResponse < O > > result = submitToServerInURI ( request , config , rxClientConfig , retryHandler , context ) ; if ( result == null ) { LoadBalancerCommand < HttpClientResponse < O > > command ; if ( retryHandler != defaultRetryHandler ) { command = LoadBalancerCommand . < HttpClientResponse < O > > builder ( ) . withExecutionContext ( context ) . withLoadBalancerContext ( lbContext ) . withListeners ( listeners ) . withClientConfig ( this . getClientConfig ( ) ) . withRetryHandler ( retryHandler ) . withServer ( server ) . build ( ) ; } else { command = defaultCommandBuilder ; } result = command . submit ( requestToOperation ( request , getRxClientConfig ( config , rxClientConfig ) ) ) ; } return result ; } | 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 ( URISyntaxException e ) { return Observable . error ( e ) ; } String host = uri . getHost ( ) ; if ( host == null ) { return null ; } int port = uri . getPort ( ) ; if ( port < 0 ) { if ( Optional . ofNullable ( clientConfig . get ( IClientConfigKey . Keys . IsSecure ) ) . orElse ( false ) ) { port = 443 ; } else { port = 80 ; } } return LoadBalancerCommand . < HttpClientResponse < O > > builder ( ) . withRetryHandler ( errorHandler ) . withLoadBalancerContext ( lbContext ) . withListeners ( listeners ) . withExecutionContext ( context ) . withServer ( new Server ( host , port ) ) . build ( ) . submit ( this . requestToOperation ( request , getRxClientConfig ( requestConfig , config ) ) ) ; } | 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 ( mods ) ) { try { map . put ( flds [ i ] . get ( null ) , flds [ i ] . getName ( ) ) ; } catch ( Throwable t ) { } } } return map ; } | 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 : servers ) { if ( this . apply ( new PredicateKey ( loadBalancerKey , server ) ) ) { results . add ( server ) ; } } return results ; } } | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.