idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
29,400 | public void setPrefixConfig ( final PrefixConfig config ) { lock . writeLock ( ) . lock ( ) ; try { if ( config == null ) { prefixes = EmptyPrefix . INSTANCE ; } else { prefixes = config ; } } finally { lock . writeLock ( ) . unlock ( ) ; } } | Sets the prefix config . |
29,401 | public void store ( final OutputStream out , final String comments , final String encoding ) throws IOException { lock . readLock ( ) . lock ( ) ; try { properties . store ( new OutputStreamWriter ( out , Charset . forName ( encoding ) ) , comments ) ; } finally { lock . readLock ( ) . unlock ( ) ; } } | Stores a properties - file by using the given comments and encoding . |
29,402 | public void storeToYAML ( final OutputStream os ) throws IOException { lock . readLock ( ) . lock ( ) ; try { final YAMLFactory f = new YAMLFactory ( ) ; final YAMLGenerator generator = f . createGenerator ( os , JsonEncoding . UTF8 ) ; generator . useDefaultPrettyPrinter ( ) ; generator . writeStartObject ( ) ; writeJsonOrYaml ( generator , getTreeMap ( ) ) ; generator . writeEndObject ( ) ; generator . flush ( ) ; } finally { lock . readLock ( ) . unlock ( ) ; } } | Store to yaml . |
29,403 | public E set ( E value , Locale locale ) { if ( defaultLocale == null ) defaultLocale = locale ; if ( value != null ) return values . put ( locale , value ) ; values . remove ( locale ) ; return null ; } | Adds or overrides a value to the internal hash . |
29,404 | public void setDefault ( E value , Locale locale ) { set ( value , locale ) ; this . defaultLocale = locale ; } | Overrides the default locale value . |
29,405 | private E getBest ( Locale ... preferredLocales ) { long bestGoodness = 0 ; Locale bestKey = null ; for ( Locale locale : preferredLocales ) { for ( Locale key : values . keySet ( ) ) { long goodness = computeGoodness ( locale , key ) ; if ( goodness > bestGoodness ) bestKey = key ; } } if ( bestKey != null ) return exactGet ( bestKey ) ; return null ; } | Goes through the list of preferred wrappers and returns the value stored the hashtable with the most good matching key or null if there are no matches . |
29,406 | public Border createComponentNodeBorder ( ) { return BorderFactory . createCompoundBorder ( BorderFactory . createLineBorder ( Color . LIGHT_GRAY ) , BorderFactory . createEmptyBorder ( 3 , 3 , 3 , 3 ) ) ; } | Creates the border which surrounds component nodes . By default this is a light gray line border . |
29,407 | public static Version copy ( Version version ) { if ( version == null ) { return null ; } Version result = new Version ( ) ; result . labels = new LinkedList < String > ( version . labels ) ; result . numbers = new LinkedList < Integer > ( version . numbers ) ; result . snapshot = version . snapshot ; return result ; } | Create a new copy of version descriptor . |
29,408 | public static Version parse ( String version ) { if ( version == null ) { throw new NullPointerException ( "version is null" ) ; } Version result = new Version ( ) ; String [ ] numbers = version . split ( "." ) ; for ( int i = 0 ; i < numbers . length ; i ++ ) { String parts [ ] = numbers [ i ] . split ( "-" ) ; int number = Integer . parseInt ( parts [ 0 ] ) ; StringBuilder label = new StringBuilder ( ) ; for ( int j = 1 ; j < parts . length ; j ++ ) { if ( ( i < numbers . length - 1 ) && ( j < parts . length - 1 ) ) { label . append ( '-' ) . append ( parts [ j ] ) ; } else { result . setSnapshot ( parts [ j ] . equalsIgnoreCase ( "SNAPSHOT" ) ) ; } } result . append ( number , label . toString ( ) ) ; } return result ; } | Creates a new version descriptor based on its string presentation . |
29,409 | public Version append ( int number , String label ) { validateNumber ( number ) ; return appendNumber ( number , label ) ; } | Adds a new version number . |
29,410 | public Version cutoff ( int index ) { if ( ! isBeyondBounds ( index ) ) { labels = labels . subList ( -- index , labels . size ( ) ) ; numbers = numbers . subList ( index , numbers . size ( ) ) ; } return this ; } | Removes version numbers starting after specified index . |
29,411 | public Version setNumber ( int index , int number , String label ) { validateNumber ( number ) ; if ( isBeyondBounds ( index ) ) { String message = String . format ( "illegal number index: %d" , index ) ; throw new IllegalArgumentException ( message ) ; } labels . set ( -- index , label ) ; numbers . set ( index , number ) ; return this ; } | Sets a new version number . |
29,412 | public String [ ] readLines ( ) throws IOException { List < String > list = new ArrayList < String > ( ) ; String line ; while ( ( line = readLine ( ) ) != null ) { list . add ( line ) ; } return list . toArray ( new String [ 0 ] ) ; } | Reads all lines and return as a String array . |
29,413 | public String readAll ( ) throws IOException { StringBuilder sb = new StringBuilder ( ) ; String line ; while ( ( line = readLine ( ) ) != null ) { sb . append ( line ) ; } return sb . toString ( ) ; } | Reads all lines and return as a String . |
29,414 | protected String buildParamsQuery ( final Map < String , String > params ) throws UnsupportedEncodingException { StringBuilder builder = new StringBuilder ( ) ; if ( params . isEmpty ( ) ) { return builder . toString ( ) ; } String sep = "" ; for ( Map . Entry < String , String > entry : params . entrySet ( ) ) { builder . append ( sep ) ; builder . append ( urlencode ( entry . getKey ( ) ) ) ; builder . append ( "=" ) ; builder . append ( urlencode ( entry . getValue ( ) ) ) ; sep = "&" ; } return builder . toString ( ) ; } | Builds a urlencoded query string from a param map . |
29,415 | protected HttpURLConnection openConnection ( final URL url , final RpcRequest request ) throws IOException { HttpURLConnection connection = ( HttpURLConnection ) url . openConnection ( ) ; if ( request . isPost ( ) ) { connection . setRequestMethod ( POST ) ; connection . setRequestProperty ( CONTENT_TYPE_HEADER , APPLICATION_X_WWW_FORM_URLENCODED ) ; connection . setDoOutput ( true ) ; } else { connection . setRequestMethod ( GET ) ; } return connection ; } | Opens a connection and sets its HTTP method . |
29,416 | protected void sendPostData ( final HttpURLConnection connection , final RpcRequest request ) throws IOException { String post = buildParamsQuery ( request . getPost ( ) ) ; byte [ ] data = post . getBytes ( UTF8 ) ; connection . setRequestProperty ( CONTENT_TYPE_HEADER , APPLICATION_X_WWW_FORM_URLENCODED ) ; connection . setRequestProperty ( CONTENT_LENGTH_HEADER , String . valueOf ( data . length ) ) ; OutputStream out = new BufferedOutputStream ( connection . getOutputStream ( ) ) ; try { out . write ( data ) ; } finally { closeLogExc ( out ) ; } } | Sets the connection content - type and content - length and sends the post data . |
29,417 | protected < T , E > T handleResponse ( final HttpURLConnection connection , final DataTypeDescriptor < T > datad , final DataTypeDescriptor < E > errord ) throws IOException { connection . connect ( ) ; int status = connection . getResponseCode ( ) ; if ( status == HttpURLConnection . HTTP_OK ) { return readResult ( connection , datad ) ; } else if ( status == APPLICATION_EXC_STATUS ) { throw ( RuntimeException ) readApplicationException ( connection , errord ) ; } else { throw readError ( connection ) ; } } | Reads a response . |
29,418 | protected IOException readError ( final HttpURLConnection connection ) throws IOException { int status = connection . getResponseCode ( ) ; InputStream input = connection . getErrorStream ( ) ; try { String message = input == null ? "No error description" : readString ( connection , input ) ; if ( message . length ( ) > MAX_RPC_EXCEPTION_MESSAGE_LEN ) { message = message . substring ( 0 , MAX_RPC_EXCEPTION_MESSAGE_LEN ) + "..." ; } message = message . replace ( "\n" , " " ) ; message = message . replace ( "\r" , " " ) ; throw new RpcException ( status , message ) ; } finally { closeLogExc ( input ) ; } } | Reads an unexpected exception throws RpcException . |
29,419 | protected String readString ( final HttpURLConnection connection , final InputStream input ) throws IOException { Charset charset = guessContentTypeCharset ( connection ) ; StringBuilder sb = new StringBuilder ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( input , charset ) ) ; try { boolean first = true ; for ( String line ; ( line = reader . readLine ( ) ) != null ; ) { if ( ! first ) { sb . append ( '\n' ) ; } sb . append ( line ) ; first = false ; } } finally { closeLogExc ( reader ) ; } return sb . toString ( ) ; } | Reads a string from an input stream gets the charset from the content - type header . |
29,420 | protected Charset guessContentTypeCharset ( final HttpURLConnection connection ) { String contentType = connection . getHeaderField ( CONTENT_TYPE_HEADER ) ; if ( contentType == null ) { return UTF8 ; } String charset = null ; for ( String param : contentType . replace ( " " , "" ) . split ( ";" ) ) { if ( param . startsWith ( "charset=" ) ) { charset = param . split ( "=" , 2 ) [ 1 ] ; break ; } } try { return Charset . forName ( charset ) ; } catch ( Exception e ) { return UTF8 ; } } | Returns a charset from the content type header or UTF8 . |
29,421 | protected void closeLogExc ( final Closeable closeable ) { if ( closeable == null ) { return ; } try { closeable . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } | Closes a closeable and logs an exception if any . |
29,422 | public void registerPlugin ( final DajlabExtension plugin ) { if ( plugin != null ) { if ( plugin instanceof DajlabControllerExtensionInterface ) { controllers . add ( ( DajlabControllerExtensionInterface < DajlabModelInterface > ) plugin ) ; } if ( plugin instanceof TabExtensionInterface ) { tabPlugins . add ( ( TabExtensionInterface ) plugin ) ; } if ( plugin instanceof MenuExtensionInterface ) { menuPlugins . add ( ( MenuExtensionInterface ) plugin ) ; } } } | Register an extension . Should be called in the constructor method of the implemented class . |
29,423 | public void start ( ) throws ConfigurationException { if ( connectionFactory == null ) { throw new ConfigurationException ( "can not start without client socket factory" ) ; } try { server = new ServerSocket ( port ) ; } catch ( IOException e ) { System . out . println ( new LogEntry ( e . getMessage ( ) , e ) ) ; throw new ConfigurationException ( "Cannot start server at port " + port , e ) ; } System . out . println ( new LogEntry ( "starting socket server at port " + port ) ) ; serverThread = new Thread ( this ) ; serverThread . start ( ) ; } | Starts the service . Instantiates a server socket and starts a thread that handles incoming client connections . |
29,424 | public void run ( ) { try { while ( true ) { Socket socket = server . accept ( ) ; System . out . println ( new LogEntry ( "client (" + socket . getInetAddress ( ) . getHostAddress ( ) + ") attempts to connect..." ) ) ; Connection c = establishConnection ( socket ) ; updateConnectedClients ( c ) ; } } catch ( IOException ioe ) { System . out . println ( new LogEntry ( "server forced to stop with message " + ioe . getClass ( ) . getName ( ) + ' ' + ioe . getMessage ( ) ) ) ; } catch ( Throwable t ) { System . out . println ( new LogEntry ( Level . CRITICAL , "server forced to stop with message " + t . getClass ( ) . getName ( ) + ' ' + t . getMessage ( ) , t ) ) ; } } | Contains the loop that waits for and handles incoming connections . |
29,425 | public void stop ( ) { if ( serverThread != null ) { try { server . close ( ) ; } catch ( IOException ioe ) { System . out . println ( new LogEntry ( Level . CRITICAL , ioe . getMessage ( ) , ioe ) ) ; } } for ( Connection client : new HashSet < Connection > ( connectedClients ) ) { if ( ! client . isClosed ( ) ) { client . close ( "server shut down..." ) ; } } } | Stops this component . Closes the server socket which stops the incoming connection exceptionHandler as well . |
29,426 | private String forceResolve ( String key ) { GetParametersRequest request ; if ( key . startsWith ( "aws." ) ) { log . warn ( "Will not try to resolve unprefixed key (" + key + ") - AWS does not allow this" ) ; if ( org . apache . commons . lang3 . StringUtils . isNotEmpty ( parameterPrefix ) ) { request = new GetParametersRequest ( ) . withNames ( parameterPrefix + key ) . withWithDecryption ( true ) ; } else { return null ; } } else { request = new GetParametersRequest ( ) . withNames ( parameterPrefix + key , key ) . withWithDecryption ( true ) ; } GetParametersResult result = ssmClient . getParameters ( request ) ; for ( Parameter parameter : result . getParameters ( ) ) { return parameter . getValue ( ) ; } return null ; } | todo - ensure prefixe parameter takes precedence |
29,427 | public static List < String > split ( String name ) { List < String > firstPassTokens = tokeniseOnSeparators ( name ) ; List < String > tokens = tokeniseOnLowercaseToUppercase ( firstPassTokens ) ; return tokens ; } | Tokenises the given name . |
29,428 | private static List < String > tokeniseOnLowercaseToUppercase ( String name ) { List < String > splits = new ArrayList < > ( ) ; ArrayList < Integer > candidateBoundaries = new ArrayList < > ( ) ; for ( Integer index = 0 ; index < name . length ( ) ; index ++ ) { if ( index == 0 ) { candidateBoundaries . add ( index ) ; } else { if ( Character . isUpperCase ( name . codePointAt ( index ) ) && Character . isLowerCase ( name . codePointAt ( index - 1 ) ) ) { candidateBoundaries . add ( index - 1 ) ; candidateBoundaries . add ( index ) ; } } if ( index == name . length ( ) - 1 ) { candidateBoundaries . add ( index ) ; } } if ( candidateBoundaries . size ( ) % 2 == 1 ) { LOGGER . warn ( "Odd number of boundaries found for: \"{}\"" , name ) ; } for ( int i = 0 ; i < candidateBoundaries . size ( ) ; i += 2 ) { splits . add ( name . substring ( candidateBoundaries . get ( i ) , candidateBoundaries . get ( i + 1 ) + 1 ) ) ; } return splits ; } | Provides a naive camel case splitter to work on character only string . |
29,429 | public void add ( CommandOption option ) { Assert . notNull ( option , "Missing command line option" ) ; CommandOption found = find ( option ) ; Assert . isNull ( found , "Given option: " + option + " overlaps with: " + found ) ; options . add ( option ) ; } | Adds new option and checks if option overlaps with existing options |
29,430 | private CommandOption find ( CommandOption option ) { Assert . notNull ( option , "Missing option!" ) ; Optional < CommandOption > found = options . stream ( ) . filter ( o -> o . is ( option ) ) . findFirst ( ) ; return found . orElse ( null ) ; } | Finds similar option by name or short name |
29,431 | public CommandOption findShort ( String argument ) { Assert . notNullOrEmptyTrimmed ( argument , "Missing short name!" ) ; Optional < CommandOption > found = options . stream ( ) . filter ( o -> o . isShort ( argument ) ) . findFirst ( ) ; return found . orElse ( null ) ; } | Find option by short name |
29,432 | public CommandOption findLong ( String argument ) { Assert . notNullOrEmptyTrimmed ( argument , "Missing long name!" ) ; Optional < CommandOption > found = options . stream ( ) . filter ( o -> o . isLong ( argument ) ) . findFirst ( ) ; return found . orElse ( null ) ; } | Finds option by long name |
29,433 | private CommandOption < ? > findBySetting ( String key ) { Assert . notNullOrEmptyTrimmed ( key , "Missing setting key!" ) ; Optional < CommandOption > found = options . stream ( ) . filter ( o -> o . getSetting ( ) . equals ( key ) ) . findFirst ( ) ; return found . orElse ( null ) ; } | Finds option by setting |
29,434 | public CommandOption findOption ( String name ) { Assert . notNullOrEmptyTrimmed ( name , "Missing name!" ) ; Optional < CommandOption > found = options . stream ( ) . filter ( o -> o . getSetting ( ) . equals ( name ) || o . isShort ( name ) || o . isLong ( name ) ) . findFirst ( ) ; return found . orElse ( null ) ; } | Finds option by short long or setting name |
29,435 | void setDefaults ( Settings defaultSettings ) { Assert . notNull ( defaultSettings , "Missing default settings!" ) ; for ( String key : defaultSettings . keySet ( ) ) { CommandOption < ? > option = findBySetting ( key ) ; if ( option == null ) { continue ; } Object value = defaultSettings . get ( key ) ; option . defaultsTo ( value ) ; } } | Sets default settings if listed in options |
29,436 | public void setHelp ( String appVersion , String usageExample ) { helpAppVersion = StringUtils . trimToNull ( appVersion ) ; helpAppExample = StringUtils . trimToNull ( usageExample ) ; } | Sets app version and example to be show in help screen |
29,437 | public List < String > getHelp ( ) { List < String > out = new ArrayList < > ( ) ; if ( helpAppVersion != null ) { out . add ( helpAppVersion ) ; } if ( helpAppExample != null ) { out . add ( helpAppExample ) ; } if ( helpAppVersion != null || helpAppExample != null ) { out . add ( "" ) ; } int max = 0 ; for ( CommandOption option : options ) { String command = option . toCommandString ( ) ; max = Math . max ( max , command . length ( ) ) ; } for ( CommandOption option : options ) { String info = option . toCommandString ( ) ; int spaces = max - info . length ( ) + 1 ; String delimiter = new String ( new char [ spaces ] ) . replace ( "\0" , " " ) ; info = info + delimiter + option . getDescription ( ) ; out . add ( info ) ; } return out ; } | Outputs command line options for System . out display |
29,438 | public List < Problem > validate ( TypeElement type ) { List < Problem > problems = new ArrayList < Problem > ( ) ; boolean declared = false ; int constructor = 0 ; List < Element > keys = new ArrayList < Element > ( ) ; for ( Element element : type . getEnclosedElements ( ) ) { ElementKind kind = element . getKind ( ) ; if ( kind == ElementKind . CONSTRUCTOR ) { constructor ++ ; if ( ( ( ExecutableElement ) element ) . getParameters ( ) . isEmpty ( ) ) { if ( element . getModifiers ( ) . contains ( Modifier . PUBLIC ) ) { declared = true ; } } } else if ( kind == ElementKind . FIELD ) { for ( AnnotationMirror mirror : element . getAnnotationMirrors ( ) ) { Name name = ( ( TypeElement ) mirror . getAnnotationType ( ) . asElement ( ) ) . getQualifiedName ( ) ; if ( name . contentEquals ( KEY ) ) { keys . add ( element ) ; break ; } } } } if ( ! declared && constructor > 0 ) { problems . add ( new Problem ( Kind . ERROR , "Entity class must have a public default constructor" , type ) ) ; return problems ; } if ( keys . isEmpty ( ) ) { problems . add ( new Problem ( Kind . ERROR , "Entity class must have one @Key property" , type ) ) ; return problems ; } else if ( keys . size ( ) > 1 ) { for ( Element key : keys ) { problems . add ( new Problem ( Kind . ERROR , "@Key cannot be annotated on multiple properties" , key ) ) ; } return problems ; } VariableElement variableElement = ( VariableElement ) keys . get ( 0 ) ; TypeMirror mirror = variableElement . asType ( ) ; Element element = ( mirror . getKind ( ) . isPrimitive ( ) ) ? types . boxedClass ( ( PrimitiveType ) mirror ) : types . asElement ( mirror ) ; Name name = ( ( TypeElement ) element ) . getQualifiedName ( ) ; if ( ! name . contentEquals ( JAVA_LANG_LONG ) && ! name . contentEquals ( JAVA_LANG_STRING ) && ! name . contentEquals ( LONG ) ) { problems . add ( new Problem ( Kind . ERROR , "@Key property must be [" + JAVA_LANG_STRING + "] or [" + JAVA_LANG_LONG + "] or [" + LONG + "]" , variableElement ) ) ; } return problems ; } | Validates the declaration of Acid House entity and returns the problems for metamodel declaration . |
29,439 | public static void transferDirect ( Pipe . Schema pipeSchema , Pipe pipe , Input input , Output output ) throws IOException { pipeSchema . transfer ( pipe , input , output ) ; } | This should not be called directly by applications . |
29,440 | public static void assertToken ( int expectedType , String expectedText , LexerResults lexerResults ) { assertToken ( expectedType , expectedText , lexerResults . getToken ( ) ) ; } | Asserts the token produced by an ANTLR tester . |
29,441 | public InputStream getAsStream ( ) throws CacheException { File file = null ; try { File directory = new File ( System . getProperty ( "java.library.path" ) ) ; file = new File ( directory , filename ) ; if ( file . exists ( ) && file . isFile ( ) ) { return new FileInputStream ( file ) ; } } catch ( IOException e ) { logger . error ( "file '{}' does not exist on classpath or is not a file" , filename ) ; throw new CacheException ( "File " + filename + " does not exist on classpath or is not a regular file" , e ) ; } return null ; } | Returns the file as a stream . |
29,442 | public List < ISubmission > filter ( List < ISubmission > submissions ) { List < ISubmission > sortedSubmissions = new ArrayList < ISubmission > ( ) ; sortedSubmissions . addAll ( submissions ) ; Collections . sort ( sortedSubmissions , new SubmissionComparator ( ) ) ; List < ISubmission > filteredSubmissions = new ArrayList < ISubmission > ( ) ; for ( ISubmission submission : sortedSubmissions ) { if ( submission . getAction ( ) != null ) { if ( submission . getAction ( ) . getVerb ( ) != null ) { if ( submission . getAction ( ) . getVerb ( ) . equals ( verb ) ) { if ( ! filteredSubmissions . contains ( submission ) ) { filteredSubmissions . add ( submission ) ; } } } } } return filteredSubmissions ; } | Given a list of submissions return only the submissions that are unique for a given set of resources and actors taking the most recent as being the definitive . |
29,443 | final boolean select ( int extension , ExplorationStep state ) throws WrongFirstParentException { if ( this . allowExploration ( extension , state ) ) { return ( this . next == null || this . next . select ( extension , state ) ) ; } else { PLCMCounters key = this . getCountersKey ( ) ; if ( key != null ) { ( ( PLCM . PLCMThread ) Thread . currentThread ( ) ) . counters [ key . ordinal ( ) ] ++ ; } return false ; } } | This one handles chained calls |
29,444 | public Retryer < R > timeout ( long duration , TimeUnit timeUnit ) { return timeout ( duration , timeUnit , null ) ; } | Timing out after the specified time limit |
29,445 | public R call ( Callable < R > callable ) throws ExecutionException , RetryException { return this . delegate ( callable ) . call ( ) ; } | Executes the given callable |
29,446 | public R quietCall ( ) { try { return call ( ) ; } catch ( ExecutionException e ) { log . error ( e . getMessage ( ) , e ) ; } catch ( RetryException e ) { log . warn ( e . getMessage ( ) ) ; } return null ; } | Executes the delegate callable quietly |
29,447 | public R call ( ) throws ExecutionException , RetryException { long elapsed = 0 ; TimeUnit unit = TimeUnit . MILLISECONDS ; Stopwatch watch = Stopwatch . createStarted ( ) ; for ( int attempt = 1 ; ; attempt ++ ) { Tried < R > target = null ; if ( ! this . rejection . apply ( target = oneCall ( ) ) ) { elapsed = watch . stop ( ) . elapsed ( unit ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Retrying %s at %s attempt. elapsed: %s ms" , target . hasResult ( ) ? "successfully" : "rejection with exception" , attempt , elapsed ) ) ; } return target . get ( ) ; } if ( this . getStopStrategy ( ) . shouldStop ( attempt , watch . elapsed ( unit ) ) ) { elapsed = watch . stop ( ) . elapsed ( unit ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Retrying stopped at %s attempt. elapsed: %s ms" , attempt , elapsed ) ) ; } throw new RetryException ( attempt , target ) ; } else { long sleepTime = this . getWaitStrategy ( ) . computeSleepTime ( attempt , watch . elapsed ( unit ) ) ; try { this . getBlockStrategy ( ) . block ( sleepTime ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Retrying blocked %s ms at %s attempt" , sleepTime , attempt ) ) ; } } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; elapsed = watch . stop ( ) . elapsed ( unit ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Retrying interrupted at %s attempt. elapsed: %s ms. %s" , attempt , elapsed , e . getMessage ( ) ) ) ; } throw new RetryException ( attempt , target ) ; } } } } | Executes the delegate callable . If the rejection predicate accepts the attempt the stop strategy is used to decide if a new attempt must be made . Then the wait strategy is used to decide how much time to sleep and a new attempt is made . |
29,448 | public Retryer < R > withStopStrategy ( StopStrategy stopStrategy ) { checkState ( this . stopStrategy == null , "A stop strategy has already been set %s" , this . stopStrategy ) ; this . stopStrategy = checkNotNull ( stopStrategy , "StopStrategy cannot be null" ) ; return this ; } | Sets the stop strategy used to decide when to stop retrying . The default strategy is never stop |
29,449 | public Retryer < R > stopAfterAttempt ( final int maxAttemptNumber ) { checkArgument ( maxAttemptNumber >= 1 , "maxAttemptNumber must be >= 1 but is %d" , maxAttemptNumber ) ; return withStopStrategy ( new StopStrategy ( ) { public boolean shouldStop ( int previousAttemptNumber , long delaySinceFirstAttemptInMillis ) { return previousAttemptNumber >= maxAttemptNumber ; } } ) ; } | Sets the stop strategy which stops after N failed attempts |
29,450 | public Retryer < R > stopAfterDelay ( final long delayInMillis ) { checkArgument ( delayInMillis >= 0L , "delayInMillis must be >= 0 but is %d" , delayInMillis ) ; return withStopStrategy ( new StopStrategy ( ) { public boolean shouldStop ( int previousAttemptNumber , long delaySinceFirstAttemptInMillis ) { return delaySinceFirstAttemptInMillis >= delayInMillis ; } } ) ; } | Sets the stop strategy which stops after a given delay milliseconds |
29,451 | public Retryer < R > withWaitStrategy ( WaitStrategy waitStrategy ) { ( this . waitStrategy = ( this . waitStrategy . isPresent ( ) ? this . waitStrategy : Optional . of ( new CompositeWaitStrategy ( ) ) ) ) . get ( ) . put ( checkNotNull ( waitStrategy , "WaitStrategy cannot be null" ) ) ; return this ; } | Sets the wait strategy used to decide how long to sleep between failed attempts . The default strategy is to retry immediately after a failed attempt |
29,452 | public Retryer < R > fixedWait ( long sleepTime , TimeUnit timeUnit ) { withWaitStrategy ( fixedWaitStrategy ( checkNotNull ( timeUnit , "TimeUnit cannot be null" ) . toMillis ( sleepTime ) ) ) ; return this ; } | Sets the wait strategy that sleeps a fixed amount of time before retrying |
29,453 | public Retryer < R > randomWait ( final long minimum , final long maximum ) { checkArgument ( minimum >= 0 , "minimum must be >= 0 but is %d" , minimum ) ; checkArgument ( maximum > minimum , "maximum must be > minimum but maximum is %d and minimum is" , maximum , minimum ) ; final Random random = new Random ( ) ; return withWaitStrategy ( new WaitStrategy ( ) { public long computeSleepTime ( int previousAttemptNumber , long delaySinceFirstAttemptInMillis ) { long t = Math . abs ( random . nextLong ( ) ) % ( maximum - minimum ) ; return t + minimum ; } } ) ; } | Sets the wait strategy that sleeps a random amount milliseconds before retrying |
29,454 | public Retryer < R > incrementingWait ( long initialSleepTime , TimeUnit initialSleepUnit , long increment , TimeUnit incrementUnit ) { return incrementingWait ( checkNotNull ( initialSleepUnit ) . toMillis ( initialSleepTime ) , checkNotNull ( incrementUnit ) . toMillis ( increment ) ) ; } | Sets the strategy that sleeps a fixed amount of time after the first failed attempt and in incrementing amounts of time after each additional failed attempt . |
29,455 | public Retryer < R > incrementingWait ( final long initialSleepTime , final long increment ) { checkArgument ( initialSleepTime >= 0L , "initialSleepTime must be >= 0 but is %d" , initialSleepTime ) ; return withWaitStrategy ( new WaitStrategy ( ) { public long computeSleepTime ( int previousAttemptNumber , long delaySinceFirstAttemptInMillis ) { long result = initialSleepTime + ( increment * ( previousAttemptNumber - 1 ) ) ; return result >= 0L ? result : 0L ; } } ) ; } | Sets the strategy that sleeps a fixed amount milliseconds after the first failed attempt and in incrementing amounts milliseconds after each additional failed attempt . |
29,456 | public Retryer < R > exponentialWait ( long multiplier , long maximumTime , TimeUnit maximumUnit ) { return exponentialWait ( multiplier , checkNotNull ( maximumUnit ) . toMillis ( maximumTime ) ) ; } | Sets the wait strategy which sleeps for an exponential amount of time after the first failed attempt |
29,457 | protected boolean included ( String url ) { for ( final Pattern urlPattern : this . includedUrls ) { final Matcher matcher = urlPattern . matcher ( url ) ; if ( matcher . matches ( ) ) { if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( "Include pattern " + urlPattern . pattern ( ) + " matches " + url ) ; } return true ; } } return false ; } | Check if the URL matches one of the configured include patterns |
29,458 | protected boolean excluded ( String url ) { for ( final Pattern urlPattern : this . excludedUrls ) { final Matcher matcher = urlPattern . matcher ( url ) ; if ( matcher . matches ( ) ) { if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( "Exclude pattern " + urlPattern . pattern ( ) + " matches " + url ) ; } return true ; } } return false ; } | Check if the URL matches one of the configured exclude patterns |
29,459 | public static void loadDocument ( String xml , String xsd , DOMHandler handler ) throws IOException , InvalidArgumentException , SAXException , ParserConfigurationException , Exception { loadDocument ( xml , xsd , handler , DEFAULT_VALIDATE_XML ) ; } | Parses an XML document and passes it on to the given handler or to a lambda expression for handling ; it does not perform validation . |
29,460 | public ImmutableSet < Entry < K , V > > entries ( ) { ImmutableSet < Entry < K , V > > result = entries ; return ( result == null ) ? ( entries = new EntrySet < K , V > ( this ) ) : result ; } | Returns an immutable collection of all key - value pairs in the multimap . Its iterator traverses the values for the first key the values for the second key and so on . |
29,461 | private < T > DeferredAction < M > deferAction ( final M metadata , final Supplier < ? extends CompletionStage < T > > action , final CompletableFuture < T > future ) { return new DeferredAction < > ( metadata , ( ) -> { final CompletionStage < ? extends T > resultFuture ; try { resultFuture = action . get ( ) ; } catch ( final Exception e ) { future . completeExceptionally ( e ) ; markProcessed ( metadata ) ; return ; } resultFuture . handleAsync ( ( result , e ) -> { if ( e != null ) { future . completeExceptionally ( e ) ; } else { future . complete ( result ) ; } markProcessed ( metadata ) ; return null ; } , executor ) ; } ) ; } | Defer the given action . |
29,462 | private void markProcessed ( final M metadata ) { synchronized ( processedLock ) { processed . add ( metadata ) ; onceProcessed . add ( metadata ) ; processedLock . notifyAll ( ) ; } } | Mark the given metadata as processed . |
29,463 | public boolean join ( ) { Message joinMessage = new Message ( MessageType . JOIN , this . channelName ) ; List < Message > response ; try { response = connection . request ( MessageFilters . message ( MessageType . RPL_NAMREPLY , null , "=" , channelName ) , MessageFilters . message ( MessageType . RPL_ENDOFNAMES , null , channelName ) , joinMessage ) ; } catch ( InterruptedException e ) { return false ; } List < String > names = new ArrayList < String > ( ) ; for ( Message message : response ) { if ( message . getType ( ) == MessageType . RPL_NAMREPLY ) { String [ ] args = message . getArgs ( ) ; for ( String name : args [ args . length - 1 ] . split ( " " ) ) { names . add ( name . replaceFirst ( "^[@+]" , "" ) ) ; } } } this . names = names ; return true ; } | Perform the join to the channel . Returns once the join operation is complete |
29,464 | private static String getRandomString ( int length , char [ ] chars ) throws IllegalArgumentException { if ( length < 1 ) throw new IllegalArgumentException ( "Invalid length: " + length ) ; if ( chars == null || chars . length == 0 ) throw new IllegalArgumentException ( "Null/Empty chars" ) ; StringBuilder sb = new StringBuilder ( ) ; Random random = new Random ( ) ; for ( int i = 0 ; i < length ; i ++ ) { char c = chars [ random . nextInt ( chars . length ) ] ; sb . append ( c ) ; } return sb . toString ( ) ; } | Generates a random String |
29,465 | protected boolean handleOption ( String arg , String nextArg , OptionArgument handler ) throws YarrgParseException { checkState ( handler != null , "No such option '" + arg + "'" ) ; if ( handler instanceof ValueOptionArgument ) { checkState ( nextArg != null , "'" + arg + "' requires a value following it" ) ; parse ( nextArg , handler ) ; return true ; } else if ( handler instanceof HelpArgument ) { throw new YarrgHelpException ( _usage , _detail ) ; } else { parse ( "true" , handler ) ; return false ; } } | Adds the value of arg and possibly nextArg to the parser for handler . |
29,466 | protected void parse ( String arg , Argument argDesc ) throws YarrgParseException { Parser < ? > parser = parsers . get ( argDesc . field ) ; if ( parser == null ) { parser = _cmd . _factory . createParser ( argDesc . field ) ; parsers . put ( argDesc . field , parser ) ; } try { parser . add ( arg ) ; } catch ( RuntimeException e ) { throw new YarrgParseException ( _usage , e . getMessage ( ) , e ) ; } } | Adds the value from arg to the parser for argDesc . |
29,467 | private Set < URL > filterURLs ( final Set < URL > urls ) { final Set < URL > results = new HashSet < URL > ( urls . size ( ) ) ; for ( final URL url : urls ) { String cleanURL = url . toString ( ) ; if ( url . getProtocol ( ) . startsWith ( "vfszip:" ) ) { cleanURL = cleanURL . replaceFirst ( "vfszip:" , "file:" ) ; } else if ( url . getProtocol ( ) . startsWith ( "vfsfile:" ) ) { cleanURL = cleanURL . replaceFirst ( "vfsfile:" , "file:" ) ; } cleanURL = cleanURL . replaceFirst ( "\\.jar/" , ".jar!/" ) ; try { results . add ( new URL ( cleanURL ) ) ; } catch ( final MalformedURLException ex ) { } } return results ; } | JBoss returns URLs with the vfszip and vfsfile protocol for resources and the org . reflections library doesn t recognize them . This is more a bug inside the reflections library but we can write a small workaround for a quick fix on our side . |
29,468 | public static int getColor ( final int alpha , final int red , final int green , final int blue ) { return ( alpha << ALPHA_SHIFT ) | ( red << RED_SHIFT ) | ( green << GREEN_SHIFT ) | blue ; } | Gets a color composed of the specified channels . All values must be between 0 and 255 both inclusive |
29,469 | public JsonXOutput clear ( boolean clearBuffer ) { if ( clearBuffer ) tail = head . clear ( ) ; lastRepeated = false ; lastNumber = 0 ; return this ; } | Resets this output for re - use . |
29,470 | public void close ( ) { if ( csvReader != null ) { try { csvReader . close ( ) ; } catch ( IOException e ) { } } if ( csvWriter != null ) { try { csvWriter . close ( ) ; } catch ( IOException e ) { } } } | Close reader and writer objects . |
29,471 | public static final < S , E > Functional < S > functionalList ( List < E > list ) { return new FunctionalList < S , E > ( list ) ; } | Returns a functional wrapper for the input list providing a way to apply a function on all its elements in a functional style . |
29,472 | public static final < S , E > Functional < S > functionalSet ( Set < E > set ) { return new FunctionalSet < S , E > ( set ) ; } | Returns a functional wrapper for the input set providing a way to apply a function on all its elements in a functional style . |
29,473 | public static final < S , K , V > Functional < S > functionalMap ( Map < K , V > map ) { return new FunctionalMap < S , K , V > ( map ) ; } | Returns a functional wrapper for the input map providing a way to apply a function on all its entries in a functional style . |
29,474 | public static final < S , E > S forEach ( List < E > list , S state , Fx < S , E > functor ) { return new FunctionalList < S , E > ( list ) . forEach ( state , functor ) ; } | Applies the given functor to all elements in the input list . |
29,475 | public static final < S , E > S forEach ( Set < E > set , S state , Fx < S , E > functor ) { return new FunctionalSet < S , E > ( set ) . forEach ( state , functor ) ; } | Applies the given functor to all elements in the input set . |
29,476 | public static final < S , K , V > S forEach ( Map < K , V > map , S state , Fx < S , Entry < K , V > > functor ) { return new FunctionalMap < S , K , V > ( map ) . forEach ( state , functor ) ; } | Applies the given functor to all entries in the input map . |
29,477 | public < E > S forEach ( Fx < S , E > functor ) { return forEach ( null , functor ) ; } | Iterates over the collection elements or entries and passing each of them to the given implementation of the functor interface ; if state needs to be propagated it can be instantiated and returned by the first invocation of the functor and it will be passed along the next elements of the collection . |
29,478 | public static < T > Comparer < T > of ( Comparable < T > delegate ) { return new Comparer < T > ( delegate ) ; } | Returns a new Comparer instance |
29,479 | public static < C > boolean expect ( C target , C ... expects ) { if ( null == expects ) { return null == target ; } for ( C expect : expects ) { if ( expect == target ) { return true ; } } return false ; } | Returns true if the given target is any one of the given expects |
29,480 | public void in ( Object key , Box < ? > value , Integer type , Converter encoder ) { Parameter parameter = new Parameter ( ) ; parameter . setInput ( value ) ; parameter . setType ( type ) ; parameter . setEncoder ( encoder ) ; merge ( key , parameter ) ; } | Registers an input parameter with specified key . |
29,481 | public Box < Object > out ( Object key , int type , String struct , Converter decoder ) { Parameter parameter = new Parameter ( ) ; parameter . setOutput ( new Box < Object > ( ) ) ; parameter . setType ( type ) ; parameter . setStruct ( struct ) ; parameter . setDecoder ( decoder ) ; return merge ( key , parameter ) . getOutput ( ) ; } | Registers an output parameter with specified key . |
29,482 | public void parseAll ( Connection connection , Statement statement ) throws SQLException { for ( Object key : mappings . keySet ( ) ) { Parameter parameter = mappings . get ( key ) ; if ( parameter . getOutput ( ) != null ) { Object output = statement . read ( key ) ; Converter decoder = parameter . getDecoder ( ) ; if ( decoder != null ) { output = decoder . perform ( connection , output ) ; } parameter . getOutput ( ) . setValue ( output ) ; } } } | Reads all registered output parameters from specified statement . |
29,483 | public void setupAll ( Connection connection , Statement statement ) throws SQLException { for ( Object key : mappings . keySet ( ) ) { Parameter parameter = mappings . get ( key ) ; if ( parameter . getInput ( ) != null ) { Object value = parameter . getInput ( ) . getValue ( ) ; Converter encoder = parameter . getEncoder ( ) ; if ( encoder != null ) { value = encoder . perform ( connection , value ) ; } statement . in ( key , value , parameter . getType ( ) ) ; } if ( parameter . getOutput ( ) != null ) { Integer sqlType = parameter . getType ( ) ; String structName = parameter . getStruct ( ) ; statement . out ( key , sqlType , structName ) ; } } } | Set up all registered parameters to specified statement . |
29,484 | public static Map < String , Object > errorToMap ( Throwable e ) { Map < String , Object > m = new HashMap < String , Object > ( ) ; m . put ( "requestId" , MDC . get ( "requestId" ) ) ; m . put ( "message" , e . getMessage ( ) ) ; m . put ( "errorClass" , e . getClass ( ) . getName ( ) ) ; return m ; } | Convert error to map |
29,485 | public synchronized AuthStorage getStorage ( ) { if ( storage == null ) { String cls = Objects . get ( config , "storageClass" , LogStorage . class . getName ( ) ) ; try { storage = ( AuthStorage ) Class . forName ( cls ) . newInstance ( ) ; } catch ( Exception e ) { throw S1SystemError . wrap ( e ) ; } } return storage ; } | Gets authentication data storage |
29,486 | public void connectionReleased ( IManagedConnectionEvent < C > event ) { IPhynixxManagedConnection < C > proxy = event . getManagedConnection ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Proxy " + proxy + " released" ) ; } } | the connection is released to the pool |
29,487 | protected Object doExec ( Element element , Object scope , String propertyPath , Object ... arguments ) throws IOException , TemplateException { if ( ! propertyPath . equals ( "." ) && ConverterRegistry . hasType ( scope . getClass ( ) ) ) { throw new TemplateException ( "Operand is property path but scope is not an object." ) ; } Element itemTemplate = element . getFirstChild ( ) ; if ( itemTemplate == null ) { throw new TemplateException ( "Invalid list element |%s|. Missing item template." , element ) ; } for ( Object item : content . getIterable ( scope , propertyPath ) ) { serializer . writeItem ( itemTemplate , item ) ; } return null ; } | Execute LIST operator . Extract content list then repeat context element first child for every list item . |
29,488 | public static FlowContext createFlowContext ( final String uuid ) { if ( null == uuid ) { throw new IllegalArgumentException ( "Flow context cannot be null" ) ; } final FlowContext flowContext = new FlowContextImpl ( uuid ) ; addFlowContext ( flowContext ) ; return flowContext ; } | Create FlowContext and put it on ThreadLocal . If there is a FlowContext in the ThreadLocal it will be overridden . |
29,489 | public static FlowContext deserializeNativeFlowContext ( final String flowContextString ) { if ( flowContextString == null ) { return null ; } final FlowContext flowContext = FlowContextImpl . deserializeNativeFlowContext ( flowContextString ) ; addFlowContext ( flowContext ) ; return flowContext ; } | De - serialize a Sting to FlowContext object and add it to ThreadLocal . If there is a FlowContext in the ThreadLocal it will be overridden . |
29,490 | public static void addFlowContext ( final FlowContext flowContext ) { if ( null == flowContext ) { clearFlowcontext ( ) ; return ; } FLOW_CONTEXT_THREAD_LOCAL . set ( flowContext ) ; MDC . put ( "flowCtxt" , flowContext . toString ( ) ) ; } | Add flowContext to ThreadLocal when coming to another component . |
29,491 | public static String serializeNativeFlowContext ( ) { final FlowContext flowCntext = FLOW_CONTEXT_THREAD_LOCAL . get ( ) ; if ( flowCntext != null ) { return ( ( FlowContextImpl ) flowCntext ) . serializeNativeFlowContext ( ) ; } return "" ; } | Serialize flowContext into a String . |
29,492 | public String getString ( String name ) { Object value = get ( name ) ; if ( value instanceof String || value instanceof Boolean || value instanceof Integer ) { return value . toString ( ) ; } if ( value instanceof String [ ] ) { String [ ] list = getStrings ( name ) ; return StringUtils . join ( list , "," ) ; } return get ( name ) . toString ( ) ; } | Get setting as String |
29,493 | public int getInt ( String name ) { Object value = super . get ( name ) ; if ( value instanceof Integer ) { return ( Integer ) value ; } if ( value == null ) { throw new IllegalArgumentException ( "Setting: '" + name + "', not found!" ) ; } try { return Integer . parseInt ( value . toString ( ) ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Setting: '" + name + "', can't be converted to integer: '" + value + "'!" ) ; } } | Get setting as integer |
29,494 | public String [ ] getStrings ( String name ) { Object value = super . get ( name ) ; if ( value instanceof String [ ] ) { return ( String [ ] ) value ; } throw new IllegalArgumentException ( "Setting: '" + name + "', can't be converted to string array: '" + value + "'!" ) ; } | Returns setting as array of Strings |
29,495 | public boolean getBool ( String name ) { Object value = super . get ( name ) ; if ( value instanceof Boolean ) { return ( Boolean ) value ; } if ( value instanceof String ) { String txt = ( String ) value ; txt = txt . trim ( ) . toLowerCase ( ) ; if ( "yes" . equals ( txt ) || "y" . equals ( txt ) || "1" . equals ( txt ) || "true" . equals ( txt ) || "t" . equals ( txt ) ) { return true ; } if ( "no" . equals ( txt ) || "n" . equals ( txt ) || "0" . equals ( txt ) || "false" . equals ( txt ) || "f" . equals ( txt ) ) { return false ; } } if ( value == null ) { throw new IllegalArgumentException ( "Setting: '" + name + "', not found!" ) ; } throw new IllegalArgumentException ( "Setting: '" + name + "', can't be converted to boolean: '" + value + "'!" ) ; } | Returns boolean flag |
29,496 | private Object get ( String name ) { Object value = find ( name ) ; if ( value == null ) { throw new IllegalArgumentException ( "Setting: '" + name + "', not found!" ) ; } return value ; } | Gets setting or throws an IllegalArgumentException if not found |
29,497 | public < T > List < T > getList ( String name , Class < T > type ) { Object value = super . get ( name ) ; if ( value instanceof List ) { ArrayList < T > output = new ArrayList < > ( ) ; List list = ( List ) value ; for ( Object item : list ) { output . add ( type . cast ( item ) ) ; } return output ; } throw new IllegalArgumentException ( "Setting: '" + name + "', can't be converted to List<" + type . getName ( ) + ">: '" + value + "'!" ) ; } | Returns setting a list of objects |
29,498 | @ SuppressWarnings ( "unchecked" ) public static < T > T get ( Object target ) { return ( T ) new RandomStructBehavior ( target ) . doDetect ( ) ; } | Returns the given object s instance that fill properties with the random value . |
29,499 | protected void callback ( Callback ... callbacks ) throws IOException , UnsupportedCallbackException , LoginException { if ( callbackHandler != null ) { callbackHandler . handle ( callbacks ) ; } else if ( requireCallbackHandler ) { throw new LoginException ( "Login module requires a callback handler" ) ; } } | Issues the specified callbacks to acquire login information . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.