idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
18,100
protected boolean isLoggingOut ( final Request request , final Response response ) { return this . isInterceptingLogout ( ) && this . getLogoutPath ( ) . equals ( request . getResourceRef ( ) . getRemainingPart ( false , false ) ) && ( Method . GET . equals ( request . getMethod ( ) ) || Method . POST . equals ( request . getMethod ( ) ) ) ; }
Indicates if the request is an attempt to log out and should be intercepted .
18,101
protected void login ( final Request request , final Response response ) { final Form form = new Form ( request . getEntity ( ) ) ; final Parameter identifier = form . getFirst ( this . getIdentifierFormName ( ) ) ; final Parameter secret = form . getFirst ( this . getSecretFormName ( ) ) ; final ChallengeResponse cr = new ChallengeResponse ( this . getScheme ( ) , identifier != null ? identifier . getValue ( ) : null , secret != null ? secret . getValue ( ) : null ) ; request . setChallengeResponse ( cr ) ; this . log . info ( "calling attemptRedirect after login" ) ; this . attemptRedirect ( request , response , form ) ; }
Processes the login request .
18,102
protected int logout ( final Request request , final Response response ) { request . setChallengeResponse ( null ) ; final CookieSetting credentialsCookie = this . getCredentialsCookie ( request , response ) ; credentialsCookie . setMaxAge ( 0 ) ; this . log . debug ( "calling attemptRedirect after logout" ) ; this . attemptRedirect ( request , response , null ) ; return Filter . STOP ; }
Processes the logout request .
18,103
static public String getTextValue ( Node node ) { if ( node . getChildNodes ( ) . getLength ( ) == 0 ) { return null ; } return node . getFirstChild ( ) . getNodeValue ( ) ; }
Returns the text from the given node .
18,104
public Bits writeBoundedLong ( final long value , final long max ) throws IOException { final int bits = 0 >= max ? 0 : ( int ) ( Math . floor ( Math . log ( max ) / Math . log ( 2 ) ) + 1 ) ; if ( 0 < bits ) { Bits toWrite = new Bits ( value , bits ) ; this . write ( toWrite ) ; return toWrite ; } else { return Bits . NULL ; } }
Write bounded long bits .
18,105
public void writeVarLong ( final long value ) throws IOException { final int bitLength = new Bits ( value ) . bitLength ; int type = Arrays . binarySearch ( varLongDepths , bitLength ) ; if ( type < 0 ) { type = - type - 1 ; } this . write ( new Bits ( type , 2 ) ) ; this . write ( new Bits ( value , varLongDepths [ type ] ) ) ; }
Write var long .
18,106
public void writeVarShort ( final short value , int optimal ) throws IOException { if ( value < 0 ) throw new IllegalArgumentException ( ) ; int [ ] varShortDepths = { optimal , 16 } ; final int bitLength = new Bits ( value ) . bitLength ; int type = Arrays . binarySearch ( varShortDepths , bitLength ) ; if ( type < 0 ) { type = - type - 1 ; } this . write ( new Bits ( type , 1 ) ) ; this . write ( new Bits ( value , varShortDepths [ type ] ) ) ; }
Write var short .
18,107
static public boolean isServerPortFree ( int port ) { ServerSocket s ; try { s = new ServerSocket ( port ) ; s . close ( ) ; } catch ( IOException e ) { return false ; } return true ; }
Check whether the specified server socket port is free or not . Be aware that this method is not safe if there are so many programs trying to open server sockets .
18,108
static public int getFreeServerPort ( int port ) { int resultPort = 0 ; ServerSocket s ; try { s = new ServerSocket ( port ) ; resultPort = s . getLocalPort ( ) ; s . close ( ) ; } catch ( IOException e ) { resultPort = 0 ; } return resultPort ; }
Get a free server port that can be used . A preferred port number can be specified . Be aware that this method is not safe if there are so many programs trying to open server sockets .
18,109
static public int getFreeServerPort ( boolean tryOthers , int ... ports ) { for ( int port : ports ) { if ( isServerPortFree ( port ) ) { return port ; } } return tryOthers ? getFreeServerPort ( ) : 0 ; }
Get a free server port that can be used . Several preferred port numbers can be specified .
18,110
static public String getExternalIpAddress ( ) { String ip = null ; URL url = null ; BufferedReader in = null ; for ( int i = 0 ; ! isIPv4Address ( ip ) && i < CHECK_IP_ENDPOINTS . length ; i ++ , url = null , in = null ) { try { url = new URL ( CHECK_IP_ENDPOINTS [ i ] ) ; in = new BufferedReader ( new InputStreamReader ( url . openStream ( ) ) ) ; ip = in . readLine ( ) ; } catch ( Exception e ) { System . err . println ( "Unable to find out external IP address through end point '" + CHECK_IP_ENDPOINTS [ i ] + "': " + e . getMessage ( ) ) ; if ( in != null ) { try { in . close ( ) ; } catch ( Exception e2 ) { } } } } return ip ; }
Get external ip address that the machine is exposed to internet
18,111
public PipedInputStream newInputStream ( ) throws IOException { final com . simiacryptus . util . io . TeeOutputStream outTee = this ; final AtomicReference < Runnable > onClose = new AtomicReference < > ( ) ; final PipedOutputStream outPipe = new PipedOutputStream ( ) ; final PipedInputStream in = new PipedInputStream ( ) { public void close ( ) throws IOException { outPipe . close ( ) ; super . close ( ) ; } } ; outPipe . connect ( in ) ; final OutputStream outAsync = new AsyncOutputStream ( outPipe ) ; new Thread ( ( ) -> { try { if ( null != heapBuffer ) { outAsync . write ( heapBuffer . toByteArray ( ) ) ; outAsync . flush ( ) ; } outTee . branches . add ( outAsync ) ; } catch ( final IOException e ) { e . printStackTrace ( ) ; } } ) . start ( ) ; onClose . set ( ( ) -> { outTee . branches . remove ( outAsync ) ; System . err . println ( "END HTTP Session" ) ; } ) ; return in ; }
New input stream piped input stream .
18,112
private Document uploadSslCertificate ( SSLCertificateCreateOptions opts , boolean cs44hack ) throws InternalException , CloudException { final List < Param > params = new ArrayList < Param > ( ) ; try { params . add ( new Param ( "certificate" , cs44hack ? URLEncoder . encode ( opts . getCertificateBody ( ) , "UTF-8" ) : opts . getCertificateBody ( ) ) ) ; params . add ( new Param ( "privatekey" , cs44hack ? URLEncoder . encode ( opts . getPrivateKey ( ) , "UTF-8" ) : opts . getPrivateKey ( ) ) ) ; if ( opts . getCertificateChain ( ) != null ) { params . add ( new Param ( "certchain" , cs44hack ? URLEncoder . encode ( opts . getCertificateChain ( ) , "UTF-8" ) : opts . getCertificateChain ( ) ) ) ; } } catch ( UnsupportedEncodingException e ) { throw new InternalException ( e ) ; } return new CSMethod ( getProvider ( ) ) . get ( UPLOAD_SSL_CERTIFICATE , params ) ; }
Upload SSL certificate optionally using parameter double encoding to address CLOUDSTACK - 6864 found in 4 . 4
18,113
public RegistrationManager getRegistrationManager ( ) { if ( registrationManager == null ) { synchronized ( this ) { if ( registrationManager == null ) { RegistrationManagerImpl registration = new RegistrationManagerImpl ( getDirectoryServiceClientManager ( ) ) ; registration . start ( ) ; registrationManager = registration ; } } } return registrationManager ; }
Get RegistrationManager .
18,114
private String getHostname ( ) { String hostname = null ; try { hostname = InetAddress . getLocalHost ( ) . getHostName ( ) . toLowerCase ( ) ; } catch ( UnknownHostException e ) { logger . warn ( "Cannot find hostname." , e ) ; } String hostnameOverride = System . getProperty ( hostnamePropertyName ) ; if ( hostnameOverride != null && hostnameOverride . length ( ) > 0 ) { hostname = hostnameOverride ; logger . info ( "Overriden hostname '{}' defined in system property '{}' will be used to choose Spring profile" , hostname , hostnamePropertyName ) ; } else { hostnameOverride = System . getenv ( hostnamePropertyName . toUpperCase ( ) ) ; if ( hostnameOverride != null && hostnameOverride . length ( ) > 0 ) { hostname = hostnameOverride ; logger . info ( "Overriden hostname '{}' defined in environment variable '{}' will be used to choose Spring profile" , hostname , hostnamePropertyName . toUpperCase ( ) ) ; } else { logger . info ( "The hostname '{}' will be used to choose Spring profile" , hostname ) ; } } String subHostnameOverride = System . getProperty ( subHostnamePropertyName ) ; if ( subHostnameOverride != null && subHostnameOverride . length ( ) > 0 ) { hostname += "/" + subHostnameOverride ; logger . info ( "Sub-hostname defined in system property '{}' appended. The full hostname that will be used to choose Spring profile is: {}" , subHostnamePropertyName , hostname ) ; } else { subHostnameOverride = System . getenv ( subHostnamePropertyName . toUpperCase ( ) ) ; if ( subHostnameOverride != null && subHostnameOverride . length ( ) > 0 ) { hostname += "/" + subHostnameOverride ; logger . info ( "Sub-hostname defined in environment variable '{}' appended. The full hostname that will be used to choose Spring profile is: {}" , subHostnamePropertyName . toUpperCase ( ) , hostname ) ; } } return hostname ; }
Get the final host name that will be used to choose the active profiles .
18,115
private List < StringKeyValueBean > loadConfiguration ( ) { List < StringKeyValueBean > result = new LinkedList < StringKeyValueBean > ( ) ; Resource resource = null ; if ( primaryConfigFileLocation == null ) { return result ; } else { resource = new ClassPathResource ( primaryConfigFileLocation ) ; if ( ! resource . exists ( ) ) { if ( secondaryConfigFileLocation == null ) { return result ; } resource = new ClassPathResource ( secondaryConfigFileLocation ) ; } } Properties properties = null ; try { properties = PropertiesLoaderUtils . loadProperties ( resource ) ; List < StringKeyValueBean > sorted = new ArrayList < StringKeyValueBean > ( properties . size ( ) ) ; for ( Entry < Object , Object > entry : properties . entrySet ( ) ) { sorted . add ( new StringKeyValueBean ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) . toString ( ) ) ) ; } Collections . sort ( sorted , new Comparator < StringKeyValueBean > ( ) { public int compare ( StringKeyValueBean b0 , StringKeyValueBean b1 ) { if ( b0 . getKey ( ) . equals ( b1 . getKey ( ) ) ) { return 0 ; } if ( "*" . equals ( b0 . getKey ( ) ) || ".*" . equals ( b0 . getKey ( ) ) ) { return 1 ; } else if ( "*" . equals ( b1 . getKey ( ) ) || ".*" . equals ( b1 . getKey ( ) ) ) { return - 1 ; } return b1 . getKey ( ) . compareTo ( b0 . getKey ( ) ) ; } } ) ; result . addAll ( sorted ) ; } catch ( Exception e ) { logger . warn ( "Cannot load environments configuration file from class path: " + ( resource == null ? "<null>" : resource . getDescription ( ) ) , e ) ; } return result ; }
Load hostname - profiles mapping configuration
18,116
public String [ ] getActiveProfiles ( ) { String hostname = getHostname ( ) ; List < StringKeyValueBean > config = loadConfiguration ( ) ; for ( StringKeyValueBean entry : config ) { String pattern = entry . getKey ( ) ; if ( "*" . equals ( pattern ) || ! ( pattern . contains ( "\\." ) || pattern . contains ( ".+" ) || pattern . contains ( ".*" ) || StringUtils . containsAny ( pattern , '[' , '^' , '$' , '(' , '|' ) ) ) { String widecard = pattern ; pattern = widecard . replace ( "." , "\\." ) . replace ( "?" , "." ) . replace ( "*" , ".*" ) ; if ( ! pattern . contains ( "/" ) ) { pattern += "/?.*" ; } logger . debug ( "Widecard '" + widecard + "' converted to regular expression: '" + pattern + "'." ) ; } else { if ( ! pattern . contains ( "/" ) ) { pattern += "/?.*" ; } logger . debug ( "Regular expression: '" + pattern + "'." ) ; } if ( Pattern . matches ( pattern , hostname ) ) { String profiles = ( String ) entry . getValue ( ) ; logger . debug ( "Hostname '" + hostname + "' matched by '" + pattern + "'" ) ; return profiles . split ( "[ ,\t]+" ) ; } } logger . warn ( "No matching profiles can be found for '" + hostname + "', a profile derived from hostname will be activated." ) ; String firstPart = StringUtils . substringBefore ( hostname , "." ) ; String profile = firstPart . replaceAll ( "[0-9-]+$" , "" ) ; return new String [ ] { profile } ; }
Get active profiles according to all the factors .
18,117
public static Object instantiate ( ClassLoader cls , String beanName , BeanContext beanContext ) throws IOException , ClassNotFoundException { return internalInstantiate ( cls , beanName , beanContext , null ) ; }
Obtains an instance of a JavaBean specified the bean name using the specified class loader and adds the instance into the specified bean context .
18,118
public static boolean isInstanceOf ( Object bean , Class < ? > targetType ) { if ( bean == null ) { throw new NullPointerException ( Messages . getString ( "beans.1D" ) ) ; } return targetType == null ? false : targetType . isInstance ( bean ) ; }
Determine if the the specified bean object can be viewed as the specified type .
18,119
private static URL safeURL ( String urlString ) throws ClassNotFoundException { try { return new URL ( urlString ) ; } catch ( MalformedURLException exception ) { throw new ClassNotFoundException ( exception . getMessage ( ) ) ; } }
Maps malformed URL exception to ClassNotFoundException
18,120
public static < T > T deserialize ( byte [ ] input , Class < T > classType ) throws JsonParseException , JsonMappingException , IOException { return mapper . readValue ( input , classType ) ; }
Deserialize from byte array .
18,121
public static byte [ ] serialize ( Object instance ) throws JsonGenerationException , JsonMappingException , IOException { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; mapper . writeValue ( out , instance ) ; return out . toByteArray ( ) ; }
Serialize the Object to JSON String .
18,122
public static DataSource createDataSource ( String source , String jndiName ) { DataSource ds = createDataSource ( source ) ; if ( ds != null && jndiName != null ) { InitialContext ic ; try { ic = new InitialContext ( ) ; ic . bind ( jndiName , ds ) ; } catch ( NamingException e ) { log . error ( "Failed to bind data source '" + source + "' to JNDI name: " + jndiName , e ) ; } } return ds ; }
Create DataSource and bind it to JNDI
18,123
public static void destroyDataSource ( DataSource dataSource , boolean force ) { synchronized ( dataSourcesStructureLock ) { String dsName = null ; for ( Map . Entry < String , DataSource > dsEntry : dataSources . entrySet ( ) ) { DataSource ds = dsEntry . getValue ( ) ; if ( ds == dataSource ) { dsName = dsEntry . getKey ( ) ; break ; } } if ( force || dsName != null ) { for ( Map . Entry < String , DataSourceProvider > dspEntry : dataSourceProviders . entrySet ( ) ) { String dspName = dspEntry . getKey ( ) ; DataSourceProvider dsp = dspEntry . getValue ( ) ; try { if ( dsp . destroyDataSource ( dataSource ) ) { if ( dsName != null ) { dataSources . remove ( dsName ) ; } break ; } } catch ( NoClassDefFoundError e ) { } catch ( Throwable e ) { log . error ( "Error when destroying data source '" + dsName + "' using provider '" + dspName + "'" , e ) ; } } } } }
Destroy a data source got from or created by ConnectionUtility before . If any exception occurred it will be logged but never propagated .
18,124
public static void destroyDataSources ( ) { synchronized ( dataSourcesStructureLock ) { for ( Map . Entry < String , DataSource > dsEntry : dataSources . entrySet ( ) ) { String dsName = dsEntry . getKey ( ) ; DataSource ds = dsEntry . getValue ( ) ; for ( Map . Entry < String , DataSourceProvider > dspEntry : dataSourceProviders . entrySet ( ) ) { String dspName = dspEntry . getKey ( ) ; DataSourceProvider dsp = dspEntry . getValue ( ) ; try { if ( dsp . destroyDataSource ( ds ) ) { break ; } } catch ( NoClassDefFoundError e ) { } catch ( Throwable e ) { log . error ( "Error when destroying data source '" + dsName + "' using provider '" + dspName + "'" , e ) ; } } } dataSources . clear ( ) ; } }
Destroy all the data sources created before . If any exception occurred it will be logged but never propagated .
18,125
public static void closeConnection ( Connection conn ) { if ( conn != null ) { try { conn . close ( ) ; } catch ( Exception e ) { log . warn ( "Exception when closing database connection." , e ) ; } } }
Closes database Connection . No exception will be thrown even if occurred during closing instead the exception will be logged at warning level .
18,126
public static void closeStatement ( Statement st ) { if ( st != null ) { try { st . close ( ) ; } catch ( Exception e ) { log . warn ( "Exception when closing database statement." , e ) ; } } }
Closes database Statement . No exception will be thrown even if occurred during closing instead the exception will be logged at warning level .
18,127
public static void closeResultSet ( ResultSet rs ) { if ( rs != null ) { try { rs . close ( ) ; } catch ( Exception e ) { log . warn ( "Exception when closing database result set." , e ) ; } } }
Closes database ResultSet No exception will be thrown even if occurred during closing instead the exception will be logged at warning level .
18,128
public static void closeOne ( String correlationId , Object component ) throws ApplicationException { if ( component instanceof IClosable ) ( ( IClosable ) component ) . close ( correlationId ) ; }
Closes specific component .
18,129
public static void close ( String correlationId , Iterable < Object > components ) throws ApplicationException { if ( components == null ) return ; for ( Object component : components ) closeOne ( correlationId , component ) ; }
Closes multiple components .
18,130
public void addPrivateKey ( PrivateKey key , NetworkParameters network ) { _privateKeys . put ( key . getPublicKey ( ) , key ) ; addPublicKey ( key . getPublicKey ( ) , network ) ; }
Add a private key to the key ring .
18,131
public KeyExporter findKeyExporterByPublicKey ( PublicKey publicKey ) { PrivateKey key = _privateKeys . get ( publicKey ) ; if ( key instanceof KeyExporter ) { return ( KeyExporter ) key ; } return null ; }
Find a KeyExporter by public key
18,132
public synchronized void createConnection ( ) { if ( scribeClient != null ) { try { connectionRetries . incrementAndGet ( ) ; scribeClient . closeLogger ( ) ; scribeClient . openLogger ( ) ; isClosed . set ( false ) ; log . info ( "Connection to Scribe established" ) ; } catch ( TTransportException e ) { log . warn ( "Unable to connect to Scribe: {}" , e . getLocalizedMessage ( ) ) ; scribeClient . closeLogger ( ) ; } } else { log . warn ( "Scribe client has not been set up correctly." ) ; } }
Re - initialize the connection with the Scribe endpoint .
18,133
public synchronized void close ( ) { if ( scribeClient != null && ! isClosed . get ( ) ) { scribeClient . closeLogger ( ) ; isClosed . set ( true ) ; } }
Disconnect from Scribe for good .
18,134
private List < LogEntry > createScribePayload ( final File file , final CallbackHandler handler ) { try { final List < Event > events = Events . fromFile ( file ) ; final List < LogEntry > list = new ArrayList < LogEntry > ( events . size ( ) ) ; for ( final Event event : events ) { final String logEntryMessage = eventToLogEntryMessage ( event ) ; list . add ( new LogEntry ( event . getName ( ) , logEntryMessage ) ) ; } return list ; } catch ( ClassNotFoundException e ) { handler . onError ( new Throwable ( e ) , file ) ; return null ; } catch ( IOException e ) { handler . onError ( new Throwable ( e ) , file ) ; return null ; } }
Give a file of events generate LogEntry messages for Scribe
18,135
public void addInstanceChangeListener ( String serviceName , ServiceInstanceChangeListener listener ) throws ServiceException { ServiceInstanceUtils . validateManagerIsStarted ( isStarted . get ( ) ) ; ServiceInstanceUtils . validateServiceName ( serviceName ) ; if ( listener == null ) { throw new ServiceException ( ErrorCode . SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR , ErrorCode . SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR . getMessageTemplate ( ) , "ServiceInstanceChangeListener" ) ; } ModelService service = getLookupService ( ) . getModelService ( serviceName ) ; if ( service == null ) { throw new ServiceException ( ErrorCode . SERVICE_DOES_NOT_EXIST , ErrorCode . SERVICE_DOES_NOT_EXIST . getMessageTemplate ( ) , serviceName ) ; } getLookupService ( ) . addServiceInstanceChangeListener ( serviceName , listener ) ; }
Add a ServiceInstanceChangeListener to the Service .
18,136
public void removeInstanceChangeListener ( String serviceName , ServiceInstanceChangeListener listener ) throws ServiceException { ServiceInstanceUtils . validateManagerIsStarted ( isStarted . get ( ) ) ; ServiceInstanceUtils . validateServiceName ( serviceName ) ; if ( listener == null ) { throw new ServiceException ( ErrorCode . SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR , ErrorCode . SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR . getMessageTemplate ( ) , "ServiceInstanceChangeListener" ) ; } getLookupService ( ) . removeServiceInstanceChangeListener ( serviceName , listener ) ; }
Remove a ServiceInstanceChangeListener from the Service .
18,137
public static boolean compare ( Object value1 , String operation , Object value2 ) { if ( operation == null ) return false ; operation = operation . toUpperCase ( ) ; if ( operation . equals ( "=" ) || operation . equals ( "==" ) || operation . equals ( "EQ" ) ) return areEqual ( value1 , value2 ) ; if ( operation . equals ( "!=" ) || operation . equals ( "<>" ) || operation . equals ( "NE" ) ) return areNotEqual ( value1 , value2 ) ; if ( operation . equals ( "<" ) || operation . equals ( "LT" ) ) return less ( value1 , value2 ) ; if ( operation . equals ( "<=" ) || operation . equals ( "LE" ) ) return areEqual ( value1 , value2 ) || less ( value1 , value2 ) ; if ( operation . equals ( ">" ) || operation . equals ( "GT" ) ) return more ( value1 , value2 ) ; if ( operation . equals ( ">=" ) || operation . equals ( "GE" ) ) return areEqual ( value1 , value2 ) || more ( value1 , value2 ) ; if ( operation . equals ( "LIKE" ) ) return match ( value1 , value2 ) ; return true ; }
Perform comparison operation over two arguments . The operation can be performed over values of any type .
18,138
public static boolean areEqual ( Object value1 , Object value2 ) { if ( value1 == null && value2 == null ) return true ; if ( value1 == null || value2 == null ) return false ; return value1 . equals ( value2 ) ; }
Checks if two values are equal . The operation can be performed over values of any type .
18,139
public static boolean less ( Object value1 , Object value2 ) { Double number1 = DoubleConverter . toNullableDouble ( value1 ) ; Double number2 = DoubleConverter . toNullableDouble ( value2 ) ; if ( number1 == null || number2 == null ) return false ; return number1 . doubleValue ( ) < number2 . doubleValue ( ) ; }
Checks if first value is less than the second one . The operation can be performed over numbers or strings .
18,140
public static boolean match ( Object value1 , Object value2 ) { if ( value1 == null && value2 == null ) return true ; if ( value1 == null || value2 == null ) return false ; String string1 = value1 . toString ( ) ; String string2 = value2 . toString ( ) ; return string1 . matches ( string2 ) ; }
Checks if string matches a regular expression
18,141
public Future < Boolean > send ( final String eventPayload ) { if ( client == null || client . isClosed ( ) ) { client = new AsyncHttpClient ( clientConfig ) ; } try { final AsyncHttpClient . BoundRequestBuilder requestBuilder = client . prepareGet ( collectorURI + eventPayload ) ; log . debug ( "Sending event to collector: {}" , eventPayload ) ; activeRequests . incrementAndGet ( ) ; return client . executeRequest ( requestBuilder . build ( ) , new AsyncCompletionHandler < Boolean > ( ) { public Boolean onCompleted ( final Response response ) { activeRequests . decrementAndGet ( ) ; if ( response . getStatusCode ( ) == 202 ) { return true ; } else { log . warn ( "Received response from collector {}: {}" , response . getStatusCode ( ) , response . getStatusText ( ) ) ; return false ; } } public void onThrowable ( final Throwable t ) { activeRequests . decrementAndGet ( ) ; } } ) ; } catch ( IOException e ) { client . close ( ) ; return null ; } }
Send a single event to the collector
18,142
public static int [ ] removeFromIntArray ( int [ ] a , int value ) { if ( a == null ) { throw new NullPointerException ( "Array was null" ) ; } int index = - 1 ; for ( int i = 0 ; i < a . length ; i ++ ) { if ( a [ i ] == value ) { index = i ; break ; } } if ( index < 0 ) { throw new IllegalArgumentException ( String . format ( "Element %d not found in array" , value ) ) ; } int [ ] array = new int [ a . length - 1 ] ; if ( index > 0 ) { System . arraycopy ( a , 0 , array , 0 , index ) ; } if ( index < a . length ) { System . arraycopy ( a , index + 1 , array , index , array . length - index ) ; } return array ; }
removes first value found by linear search from array a
18,143
public < O extends BaseOption > ArgumentParser add ( O option ) { if ( option . getName ( ) != null ) { if ( longNameOptions . containsKey ( option . getName ( ) ) ) { throw new IllegalArgumentException ( "Option " + option . getName ( ) + " already exists" ) ; } if ( parent != null && parent . longNameOptions . containsKey ( option . getName ( ) ) ) { throw new IllegalArgumentException ( "Option " + option . getName ( ) + " already exists in parent" ) ; } longNameOptions . put ( option . getName ( ) , option ) ; } if ( option instanceof Flag ) { String negate = ( ( Flag ) option ) . getNegateName ( ) ; if ( negate != null ) { if ( longNameOptions . containsKey ( negate ) ) { throw new IllegalArgumentException ( "Flag " + negate + " already exists" ) ; } if ( parent != null && parent . longNameOptions . containsKey ( negate ) ) { throw new IllegalArgumentException ( "Flag " + negate + " already exists in parent" ) ; } longNameOptions . put ( negate , option ) ; } } if ( option . getShortNames ( ) . length ( ) > 0 ) { for ( char s : option . getShortNames ( ) . toCharArray ( ) ) { if ( shortOptions . containsKey ( s ) ) { throw new IllegalArgumentException ( "Short option -" + s + " already exists" ) ; } if ( parent != null && parent . shortOptions . containsKey ( s ) ) { throw new IllegalArgumentException ( "Short option -" + s + " already exists in parent" ) ; } shortOptions . put ( s , option ) ; } } this . options . add ( option ) ; return this ; }
Add a command line option .
18,144
public < A extends BaseArgument > ArgumentParser add ( A arg ) { if ( arg instanceof BaseOption ) { return add ( ( BaseOption ) arg ) ; } if ( arguments . size ( ) > 0 && arguments . get ( arguments . size ( ) - 1 ) instanceof SubCommandSet ) { throw new IllegalArgumentException ( "No arguments can be added after a sub-command set" ) ; } arguments . add ( arg ) ; return this ; }
Add a sub - command .
18,145
public void parse ( ArgumentList args ) { try { parseInternal ( args ) ; } catch ( ArgumentException e ) { if ( e . getParser ( ) == null ) { e . setParser ( this ) ; } throw e ; } }
Parse arguments from the main method .
18,146
public String getSingleLineUsage ( ) { StringBuilder writer = new StringBuilder ( ) ; writer . append ( program ) ; StringBuilder sh = new StringBuilder ( ) ; options . stream ( ) . filter ( opt -> opt instanceof Flag ) . filter ( opt -> opt . getShortNames ( ) . length ( ) > 0 ) . forEachOrdered ( opt -> sh . append ( opt . getShortNames ( ) . charAt ( 0 ) ) ) ; if ( sh . length ( ) > 0 ) { writer . append ( " [-" ) . append ( sh . toString ( ) ) . append ( ']' ) ; } for ( BaseOption opt : options ) { if ( opt instanceof Flag && opt . getShortNames ( ) . length ( ) > 0 ) { continue ; } String usage = opt . getSingleLineUsage ( ) ; if ( usage != null ) { writer . append ( ' ' ) . append ( usage ) ; } } for ( BaseArgument arg : arguments ) { String usage = arg . getSingleLineUsage ( ) ; if ( usage != null ) { writer . append ( ' ' ) . append ( usage ) ; } } return writer . toString ( ) ; }
Get the single line usage string for the parser . Contains essentially the line program options args .
18,147
public void addCell ( String content ) { content = content . trim ( ) ; if ( content . startsWith ( "=" ) ) { if ( null == functionOccurences ) { functionOccurences = new ArrayList ( ) ; } functionOccurences . add ( new int [ ] { indexCol , indexRow } ) ; } currentRow . add ( content ) ; indexCol ++ ; }
Add a cell to the current row of the table
18,148
public void calc ( ) { if ( null != functionOccurences ) { Iterator iterator = functionOccurences . iterator ( ) ; while ( iterator . hasNext ( ) ) { int [ ] position = ( int [ ] ) iterator . next ( ) ; String functionString = ( ( String ) getXY ( position [ 0 ] , position [ 1 ] ) ) . trim ( ) ; String name = functionString . substring ( 1 , functionString . indexOf ( "(" ) ) . trim ( ) . toLowerCase ( ) ; String range = functionString . substring ( functionString . indexOf ( "(" ) + 1 , functionString . indexOf ( ")" ) ) ; int colon = range . indexOf ( ":" ) ; String start = range . substring ( 0 , colon ) . trim ( ) ; String end = range . substring ( colon + 1 ) . trim ( ) ; int startX = start . charAt ( 0 ) - 'A' ; int startY = Integer . parseInt ( start . substring ( 1 ) ) - 1 ; int endX = end . charAt ( 0 ) - 'A' ; int endY = Integer . parseInt ( end . substring ( 1 ) ) - 1 ; if ( startX > endX ) { int tmp = startX ; startX = endX ; endX = tmp ; } if ( startY > endY ) { int tmp = startY ; startY = endY ; endY = tmp ; } if ( functions . containsKey ( name ) ) { Function function = ( Function ) functions . get ( name ) ; function . execute ( this , position [ 0 ] , position [ 1 ] , startX , startY , endX , endY ) ; } } } return ; }
Recalculate all cells . Currently does nothing .
18,149
public Writer appendTo ( Writer writer ) throws IOException { writer . write ( "<table class=\"wiki-table\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">" ) ; List [ ] outputRows = ( List [ ] ) rows . toArray ( new List [ 0 ] ) ; int rowSize = outputRows . length ; boolean odd = true ; for ( int i = 0 ; i < rowSize ; i ++ ) { writer . write ( "<tr" ) ; if ( i == 0 ) { writer . write ( ">" ) ; } else if ( odd ) { writer . write ( " class=\"table-odd\">" ) ; odd = false ; } else { writer . write ( " class=\"table-even\">" ) ; odd = true ; } String [ ] outputCols = ( String [ ] ) outputRows [ i ] . toArray ( new String [ 0 ] ) ; int colSize = outputCols . length ; for ( int j = 0 ; j < colSize ; j ++ ) { writer . write ( i == 0 ? "<th>" : "<td>" ) ; if ( outputCols [ j ] == null || outputCols [ j ] . trim ( ) . length ( ) == 0 ) { writer . write ( "&#160;" ) ; } else { writer . write ( outputCols [ j ] ) ; } writer . write ( i == 0 ? "</th>" : "</td>" ) ; } writer . write ( "</tr>" ) ; } writer . write ( "</table>" ) ; return writer ; }
Serialize table by appending it to a writer . The output format is HTML .
18,150
public static String resolve ( ConfigParams config , String defaultName ) { String name = config . getAsNullableString ( "name" ) ; name = name != null ? name : config . getAsNullableString ( "id" ) ; if ( name == null ) { String descriptorStr = config . getAsNullableString ( "descriptor" ) ; try { Descriptor descriptor = Descriptor . fromString ( descriptorStr ) ; name = descriptor != null ? descriptor . getName ( ) : null ; } catch ( Exception ex ) { } } return name != null ? name : defaultName ; }
Resolves a component name from configuration parameters . The name can be stored in id name fields or inside a component descriptor . If name cannot be determined it returns a defaultName .
18,151
public double random ( ) { long z = next ( ) ; int exponentMag = 4 ; double resolution = 1e8 ; double x = ( ( z / 2 ) % resolution ) / resolution ; double y = z % exponentMag - exponentMag / 2 ; while ( y > 1 ) { y -- ; x = 2 ; } while ( y < - 1 ) { y ++ ; x /= 2 ; } return x ; }
Random double .
18,152
public long next ( ) { long x = xorshift ( this . x ) ; this . x = y ; y = z ; z = this . x ^ x ^ y ; return z ; }
Next long .
18,153
private CloseableHttpClient buildClient ( boolean trustSelfSigned ) { try { SSLContext sslContext = ! trustSelfSigned ? SSLContexts . createSystemDefault ( ) : SSLContexts . custom ( ) . loadTrustMaterial ( null , new TrustSelfSignedStrategy ( ) ) . build ( ) ; int globalTimeout = readFromProperty ( "bdTimeout" , 100000 ) ; int connectTimeout = readFromProperty ( "bdConnectTimeout" , globalTimeout ) ; int connectionRequestTimeout = readFromProperty ( "bdConnectionRequestTimeout" , globalTimeout ) ; int socketTimeout = readFromProperty ( "bdSocketTimeout" , globalTimeout ) ; RequestConfig requestConfig = RequestConfig . copy ( RequestConfig . DEFAULT ) . setConnectTimeout ( connectTimeout ) . setSocketTimeout ( socketTimeout ) . setConnectionRequestTimeout ( connectionRequestTimeout ) . build ( ) ; CacheConfig cacheConfig = CacheConfig . copy ( CacheConfig . DEFAULT ) . setSharedCache ( false ) . setMaxCacheEntries ( 1000 ) . setMaxObjectSize ( 2 * 1024 * 1024 ) . build ( ) ; PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager ( RegistryBuilder . < ConnectionSocketFactory > create ( ) . register ( "http" , PlainConnectionSocketFactory . getSocketFactory ( ) ) . register ( "https" , new SSLConnectionSocketFactory ( sslContext ) ) . build ( ) ) ; int connectionLimit = readFromProperty ( "bdMaxConnections" , 40 ) ; connManager . setMaxTotal ( connectionLimit ) ; connManager . setDefaultMaxPerRoute ( connectionLimit ) ; return CachingHttpClientBuilder . create ( ) . setCacheConfig ( cacheConfig ) . setDefaultRequestConfig ( requestConfig ) . setConnectionManager ( connManager ) . build ( ) ; } catch ( GeneralSecurityException e ) { throw new InternalConfigurationException ( "Failed to set up SSL context" , e ) ; } }
Builds the HTTP client to connect to the server .
18,154
private BellaDatiRuntimeException buildException ( int code , byte [ ] content , boolean hasToken ) { try { HttpParameters oauthParams = OAuth . decodeForm ( new ByteArrayInputStream ( content ) ) ; if ( oauthParams . containsKey ( "oauth_problem" ) ) { String problem = oauthParams . getFirst ( "oauth_problem" ) ; if ( "missing_consumer" . equals ( problem ) || "invalid_consumer" . equals ( problem ) ) { return new AuthorizationException ( Reason . CONSUMER_KEY_UNKNOWN ) ; } else if ( "invalid_signature" . equals ( problem ) || "signature_invalid" . equals ( problem ) ) { return new AuthorizationException ( hasToken ? Reason . TOKEN_INVALID : Reason . CONSUMER_SECRET_INVALID ) ; } else if ( "domain_expired" . equals ( problem ) ) { return new AuthorizationException ( Reason . DOMAIN_EXPIRED ) ; } else if ( "missing_token" . equals ( problem ) || "invalid_token" . equals ( problem ) ) { return new AuthorizationException ( Reason . TOKEN_INVALID ) ; } else if ( "unauthorized_token" . equals ( problem ) ) { return new AuthorizationException ( Reason . TOKEN_UNAUTHORIZED ) ; } else if ( "token_expired" . equals ( problem ) ) { return new AuthorizationException ( Reason . TOKEN_EXPIRED ) ; } else if ( "x_auth_disabled" . equals ( problem ) ) { return new AuthorizationException ( Reason . X_AUTH_DISABLED ) ; } else if ( "piccolo_not_enabled" . equals ( problem ) ) { return new AuthorizationException ( Reason . BD_MOBILE_DISABLED ) ; } else if ( "missing_username" . equals ( problem ) || "missing_password" . equals ( problem ) || "invalid_credentials" . equals ( problem ) || "permission_denied" . equals ( problem ) ) { return new AuthorizationException ( Reason . USER_CREDENTIALS_INVALID ) ; } else if ( "account_locked" . equals ( problem ) || "user_not_active" . equals ( problem ) ) { return new AuthorizationException ( Reason . USER_ACCOUNT_LOCKED ) ; } else if ( "domain_restricted" . equals ( problem ) ) { return new AuthorizationException ( Reason . USER_DOMAIN_MISMATCH ) ; } else if ( "timestamp_refused" . equals ( problem ) ) { String acceptable = oauthParams . getFirst ( "oauth_acceptable_timestamps" ) ; if ( acceptable != null && acceptable . contains ( "-" ) ) { return new InvalidTimestampException ( Long . parseLong ( acceptable . split ( "-" ) [ 0 ] ) , Long . parseLong ( acceptable . split ( "-" ) [ 1 ] ) ) ; } } return new AuthorizationException ( Reason . OTHER , problem ) ; } return new UnexpectedResponseException ( code , new String ( content ) ) ; } catch ( IOException e ) { throw new UnexpectedResponseException ( code , new String ( content ) , e ) ; } }
Builds an exception based on the given content assuming that it has been returned as an error from the server .
18,155
private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { in . defaultReadObject ( ) ; try { Field client = getClass ( ) . getDeclaredField ( "client" ) ; client . setAccessible ( true ) ; client . set ( this , buildClient ( trustSelfSigned ) ) ; } catch ( NoSuchFieldException e ) { throw new InternalConfigurationException ( "Failed to set client fields" , e ) ; } catch ( IllegalAccessException e ) { throw new InternalConfigurationException ( "Failed to set client fields" , e ) ; } catch ( SecurityException e ) { throw new InternalConfigurationException ( "Failed to set client fields" , e ) ; } catch ( IllegalArgumentException e ) { throw new InternalConfigurationException ( "Failed to set client fields" , e ) ; } }
Deserialization . Sets up an HTTP client instance .
18,156
public void registerService ( ProvidedServiceInstance serviceInstance , OperationalStatus status ) { serviceInstance . setStatus ( status ) ; registerService ( serviceInstance ) ; }
Register a ProvidedServiceInstance with the OperationalStatus .
18,157
public void updateServiceUri ( String serviceName , String providerAddress , String uri ) { getServiceDirectoryClient ( ) . updateInstanceUri ( serviceName , providerAddress , uri , disableOwnerError ) ; }
Update the uri attribute of the ProvidedServiceInstance The ProvidedServiceInstance is uniquely identified by serviceName and providerAddress
18,158
public void updateServiceOperationalStatus ( String serviceName , String providerAddress , OperationalStatus status ) { getServiceDirectoryClient ( ) . updateInstanceStatus ( serviceName , providerAddress , status , disableOwnerError ) ; }
Update the OperationalStatus of the ProvidedServiceInstance The ProvidedServiceInstance is uniquely identified by serviceName and providerAddress
18,159
public void updateServiceMetadata ( String serviceName , String providerAddress , Map < String , String > metadata ) { getServiceDirectoryClient ( ) . updateInstanceMetadata ( serviceName , providerAddress , metadata , disableOwnerError ) ; }
Update the metadata attribute of the ProvidedServiceInstance The ProvidedServiceInstance is uniquely identified by serviceName and providerAddress
18,160
public void unregisterService ( String serviceName , String providerAddress ) { getServiceDirectoryClient ( ) . unregisterInstance ( serviceName , providerAddress , disableOwnerError ) ; }
Unregister a ProvidedServiceInstance The ProvidedServiceInstance is uniquely identified by serviceName and providerAddress
18,161
@ Requires ( { "files != null" , "diagnostics != null" } ) @ Ensures ( "result != null" ) public CompilationTask getTask ( List < ? extends JavaFileObject > files , DiagnosticListener < JavaFileObject > diagnostics ) { return javaCompiler . getTask ( null , fileManager , diagnostics , OPTIONS , null , files ) ; }
Returns a new compilation task .
18,162
public static Object executeOne ( String correlationId , Object component , Parameters args ) throws ApplicationException { if ( component instanceof IExecutable ) return ( ( IExecutable ) component ) . execute ( correlationId , args ) ; else return null ; }
Executes specific component .
18,163
public static List < Object > execute ( String correlationId , Iterable < Object > components , Parameters args ) throws ApplicationException { List < Object > results = new ArrayList < Object > ( ) ; if ( components == null ) return results ; for ( Object component : components ) { if ( component instanceof IExecutable ) results . add ( executeOne ( correlationId , component , args ) ) ; } return results ; }
Executes multiple components .
18,164
public TableMetadata getTableMetadata ( String tableName ) { if ( tableName == null ) return null ; try { tableMetadataStatement . setInt ( 1 , tableName . hashCode ( ) ) ; ResultSet set = tableMetadataStatement . executeQuery ( ) ; return transformToTableMetadata ( set ) ; } catch ( SQLException e ) { throw new BackendException ( "Could not get TableMetadata for table '" + tableName + "'" , e ) ; } }
Liefert die Metadaten der gegebenen Tabelle .
18,165
public void updateMetadata ( String tableName , String metadata ) { try { updateStatement . setString ( 1 , metadata ) ; updateStatement . setLong ( 2 , tableName . hashCode ( ) ) ; updateStatement . executeUpdate ( ) ; } catch ( SQLException e ) { throw new BackendException ( "Could not update metadata for table '" + tableName + "'" , e ) ; } }
Aktualisiert die Metadaten eines Eintrages .
18,166
public BufferedImage buildBufferedImageOfIconInOS ( Path path ) { path = JMOptional . getNullableAndFilteredOptional ( path , JMPath . NotExistFilter ) . flatMap ( JMPathOperation :: createTempFilePathAsOpt ) . orElse ( path ) ; Icon iconInOS = os . getIcon ( path . toFile ( ) ) ; BufferedImage bufferedImage = new BufferedImage ( iconInOS . getIconWidth ( ) , iconInOS . getIconHeight ( ) , BufferedImage . TYPE_INT_ARGB ) ; iconInOS . paintIcon ( null , bufferedImage . getGraphics ( ) , 0 , 0 ) ; return bufferedImage ; }
Build buffered image of icon in os buffered image .
18,167
public BufferedImage getCachedBufferedImageOfIconInOS ( Path path ) { return getSpecialPathAsOpt ( path ) . map ( getCachedBufferedImageFunction ( path ) ) . orElseGet ( ( ) -> buildCachedBufferedImageOfFileIconInOS ( path ) ) ; }
Gets cached buffered image of icon in os .
18,168
public void onChange ( String valueScope , Object key ) { notifyLocalRepositories ( valueScope , key ) ; notifyRemoteRepositories ( valueScope , key ) ; }
Notify both local and remote repositories about the value change
18,169
public static Config parse ( Properties properties ) { ConfigBuilder config = new SimpleConfig ( ) ; for ( Object o : new TreeSet < > ( properties . keySet ( ) ) ) { String key = o . toString ( ) ; if ( isPositional ( key ) ) { String entryKey = entryKey ( key ) ; if ( config . containsKey ( entryKey ) ) { config . getCollection ( entryKey ) . add ( properties . getProperty ( key ) ) ; } else { ArrayList < Object > sequence = new ArrayList < > ( ) ; sequence . add ( properties . getProperty ( key ) ) ; config . putCollection ( entryKey , sequence ) ; } } else { config . put ( key , properties . getProperty ( key ) ) ; } } return ImmutableConfig . copyOf ( config ) ; }
Parse the properties instance into a config .
18,170
public List < RawEntry > toRawList ( ) { if ( t == null || t . size ( ) == 0 ) { return Collections . emptyList ( ) ; } List < RawEntry > result = new ArrayList < RawEntry > ( t . size ( ) ) ; int lastDuration = 0 ; for ( int i = 0 ; i < t . size ( ) ; i ++ ) { long timestamp = t . get ( i ) ; int duration = - 1 ; if ( i < d . size ( ) ) { duration = d . get ( i ) ; } if ( duration == - 1 ) { duration = lastDuration ; } lastDuration = duration ; long timestampMillis ; long durationMillis ; if ( u == null || u . equals ( "m" ) ) { timestampMillis = 1000L * 60 * timestamp ; durationMillis = 1000L * 60 * duration ; } else if ( u . equals ( "s" ) ) { timestampMillis = 1000L * timestamp ; durationMillis = 1000L * duration ; } else if ( u . equals ( "S" ) ) { timestampMillis = timestamp ; durationMillis = duration ; } else { throw new IllegalArgumentException ( "Unit not supported: " + u ) ; } result . add ( new RawEntry ( timestampMillis , durationMillis , c == null || i >= c . size ( ) ? null : c . get ( i ) , s == null || i >= s . size ( ) ? null : s . get ( i ) , a == null || i >= a . size ( ) ? null : a . get ( i ) , m == null || i >= m . size ( ) ? null : m . get ( i ) , x == null || i >= x . size ( ) ? null : x . get ( i ) , n == null || i >= n . size ( ) ? null : n . get ( i ) , o == null || i >= o . size ( ) ? null : o . get ( i ) ) ) ; } return result ; }
Convert into raw list form .
18,171
public static void copy ( File sourceFile , File targetFile ) throws IOException { FileInputStream in = new FileInputStream ( sourceFile ) ; try { FileOutputStream out = new FileOutputStream ( targetFile ) ; try { copy ( in , out ) ; } finally { out . close ( ) ; } } finally { in . close ( ) ; } }
This method performs a simple copy of sourceFile to targetFile .
18,172
public static boolean isUpdateRequired ( File sourceFile , File targetFile ) { if ( targetFile . exists ( ) ) { if ( targetFile . lastModified ( ) > sourceFile . lastModified ( ) ) { return false ; } } return true ; }
This method checks for the requirement for an update .
18,173
public static boolean writeFile ( File directory , File fileName , String text ) { try { File destination = new File ( directory , fileName . getPath ( ) ) ; File parent = destination . getParentFile ( ) ; if ( ! parent . exists ( ) ) { if ( ! parent . mkdirs ( ) ) { return false ; } } RandomAccessFile ra = new RandomAccessFile ( destination , "rw" ) ; try { ra . setLength ( 0 ) ; ra . writeBytes ( text ) ; } finally { ra . close ( ) ; } return true ; } catch ( FileNotFoundException e ) { logger . error ( e . getMessage ( ) , e ) ; return false ; } catch ( IOException e ) { logger . error ( e . getMessage ( ) , e ) ; return false ; } }
This method writes the content of a String into a file specified by a directory and its fileName .
18,174
public static void deleteFileOrDir ( File file ) throws IOException { if ( file . isDirectory ( ) ) { File [ ] children = file . listFiles ( ) ; if ( children != null ) { for ( File child : children ) { deleteFileOrDir ( child ) ; } } } if ( ! file . delete ( ) ) { throw new IOException ( "Could not remove '" + file + "'!" ) ; } }
Utility method used to delete the profile directory when run as a stand - alone application .
18,175
public static String createHumanReadableSizeString ( long size ) { DecimalFormat format = new DecimalFormat ( "#.##" ) ; BinaryPrefix prefix = BinaryPrefix . getSuitablePrefix ( size ) ; double doubleSize = size / prefix . getBinaryFactor ( ) . doubleValue ( ) ; return format . format ( doubleSize ) + prefix . getUnit ( ) + "B" ; }
This method converts a size in bytes into a string which can be used to be put into UI .
18,176
public static String decodeLZToString ( byte [ ] data , String dictionary ) { try { return new String ( decodeLZ ( data ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Decode lz to string string .
18,177
public static Map < String , String > getSchedulerNames ( ) { Map < String , String > schedulerNames = new HashMap < String , String > ( ) ; MySchedule mySchedule = MySchedule . getInstance ( ) ; for ( String settingsName : mySchedule . getSchedulerSettingsNames ( ) ) { SchedulerSettings settings = mySchedule . getSchedulerSettings ( settingsName ) ; schedulerNames . put ( settingsName , settings . getSchedulerFullName ( ) ) ; } return schedulerNames ; }
Get the settings names and full names of all schedulers defined in myschedule .
18,178
public static Map < String , SchedulerTemplate > getSchedulers ( ) { Map < String , SchedulerTemplate > schedulers = new HashMap < String , SchedulerTemplate > ( ) ; MySchedule mySchedule = MySchedule . getInstance ( ) ; for ( String settingsName : mySchedule . getSchedulerSettingsNames ( ) ) { SchedulerTemplate schedulerTemplate = mySchedule . getScheduler ( settingsName ) ; schedulers . put ( settingsName , schedulerTemplate ) ; } return schedulers ; }
Get the settings names and corresponding schedulers of all schedulers defined in myschedule .
18,179
public static Map < String , Object > convertTextToDataMap ( String text ) throws IOException { Map < String , Object > dataMap = null ; Properties p = new Properties ( ) ; p . load ( new StringReader ( text ) ) ; dataMap = new HashMap < String , Object > ( ) ; for ( Entry < Object , Object > entry : p . entrySet ( ) ) { dataMap . put ( ( String ) entry . getKey ( ) , entry . getValue ( ) ) ; } return dataMap ; }
Convert a text in properties file format to DataMap that can be used by Quartz
18,180
public static String convertDataMapToText ( Map < String , Object > dataMap ) { StringBuilder sb = new StringBuilder ( ) ; for ( Entry < String , Object > entry : dataMap . entrySet ( ) ) { sb . append ( entry . getKey ( ) ) . append ( "=" ) . append ( entry . getValue ( ) ) ; sb . append ( '\n' ) ; } return sb . toString ( ) ; }
Convert JobDataMap into text in properties file format
18,181
public Object execute ( String correlationId , Parameters args ) throws ApplicationException { if ( _schema != null ) _schema . validateAndThrowException ( correlationId , args ) ; try { return _function . execute ( correlationId , args ) ; } catch ( Throwable ex ) { throw new InvocationException ( correlationId , "EXEC_FAILED" , "Execution " + _name + " failed: " + ex ) . withDetails ( "command" , _name ) . wrap ( ex ) ; } }
Executes the command . Before execution is validates Parameters args using the defined schema . The command execution intercepts ApplicationException raised by the called function and throws them .
18,182
public List < ValidationResult > validate ( Parameters args ) { if ( _schema != null ) return _schema . validate ( args ) ; return new ArrayList < ValidationResult > ( ) ; }
Validates the command Parameters args before execution using the defined schema .
18,183
public static List < File > find ( File directory , String pattern ) { pattern = wildcardsToRegExp ( pattern ) ; List < File > files = findFilesInDirectory ( directory , Pattern . compile ( pattern ) , true ) ; List < File > result = new ArrayList < File > ( ) ; for ( File file : files ) { String fileString = file . getPath ( ) . substring ( directory . getPath ( ) . length ( ) ) ; result . add ( new File ( fileString ) ) ; } return result ; }
This method searches a directory recursively . A pattern specifies which files are to be put into the output list .
18,184
private static List < File > findFilesInDirectory ( File directory , Pattern pattern , boolean scanRecursive ) { List < File > files = new ArrayList < File > ( ) ; String [ ] filesInDirectory = directory . list ( ) ; if ( filesInDirectory == null ) { return files ; } for ( String fileToCheck : filesInDirectory ) { File file = new File ( directory , fileToCheck ) ; if ( file . isFile ( ) ) { if ( pattern . matcher ( fileToCheck ) . matches ( ) ) { files . add ( file ) ; } } else if ( file . isDirectory ( ) ) { if ( scanRecursive ) { files . addAll ( findFilesInDirectory ( file , pattern , scanRecursive ) ) ; } } } return files ; }
This class is the recursive part of the file search .
18,185
public static String getCurrentTimestamp ( String timeFormat , String zoneId ) { return getTime ( System . currentTimeMillis ( ) , timeFormat , zoneId ) ; }
Gets current timestamp .
18,186
public static DateTimeFormatter getDateTimeFormatter ( String timeFormat ) { return JMMap . getOrPutGetNew ( dateTimeFormatterCache , timeFormat , ( ) -> DateTimeFormatter . ofPattern ( timeFormat ) ) ; }
Gets date time formatter .
18,187
public static ZoneId getZoneId ( String zoneId ) { return JMMap . getOrPutGetNew ( zoneIdCache , zoneId , ( ) -> ZoneId . of ( zoneId ) ) ; }
Gets zone id .
18,188
public static SimpleDateFormat getSimpleDateFormat ( String dateFormat , String zoneId ) { return JMMap . getOrPutGetNew ( simpleDateFormatMap , buildSimpleDateFormatKey ( dateFormat , zoneId ) , newSimpleDateFormatBuilder . apply ( dateFormat , zoneId ) ) ; }
Gets simple date format .
18,189
public static String changeTimestampToIsoInstant ( String dateFormat , String timestamp ) { return getTime ( changeTimestampToLong ( getSimpleDateFormat ( dateFormat ) , timestamp ) , ISO_INSTANT_Z , UTC_ZONE_ID ) ; }
Change timestamp to iso instant string .
18,190
public static long getTimeMillisWithNano ( int year , int month , int dayOfMonth , int hour , int minute , int second , int nanoOfSecond , String zoneId ) { return ZonedDateTime . of ( year , month , dayOfMonth , hour , minute , second , nanoOfSecond , getZoneId ( zoneId ) ) . toInstant ( ) . toEpochMilli ( ) ; }
Gets time millis with nano .
18,191
public static ZonedDateTime getZonedDataTime ( long timestamp , String zoneId ) { return Instant . ofEpochMilli ( timestamp ) . atZone ( getZoneId ( zoneId ) ) ; }
Gets zoned data time .
18,192
public static OffsetDateTime getOffsetDateTime ( long timestamp , ZoneOffset zoneOffset ) { return Instant . ofEpochMilli ( timestamp ) . atOffset ( zoneOffset ) ; }
Gets offset date time .
18,193
public static ZoneOffset getZoneOffset ( String zoneOffsetId ) { return JMMap . getOrPutGetNew ( zoneOffsetCache , zoneOffsetId , ( ) -> ZoneOffset . of ( zoneOffsetId ) ) ; }
Gets zone offset .
18,194
public static < T extends Number > ImmutableNumberStatistics < T > copyOf ( NumberStatistics < ? extends T > statistics ) { return new ImmutableNumberStatistics < T > ( statistics ) ; }
Create an immutable copy of another NumberStatistics
18,195
private String buildAuthorisationCredential ( final Query < ? , ? > query ) { String credential = null ; if ( query instanceof OAuthQuery ) { final String oauthToken = ( ( OAuthQuery ) query ) . getOauthToken ( ) ; credential = String . format ( "Bearer %s" , oauthToken ) ; } else if ( query instanceof AccessTokenQuery ) { } else { credential = String . format ( "Token %s" , clientSecret ) ; } return credential ; }
Build the credential that will be passed in the Authorization HTTP header as part of the API call . The nature of the credential will depend on the query being made .
18,196
public Response < AccessTokenDetails > redeemAuthorisationCodeForAccessToken ( final String authorisationCode ) throws FreesoundClientException { final OAuth2AccessTokenRequest tokenRequest = new OAuth2AccessTokenRequest ( clientId , clientSecret , authorisationCode ) ; return executeQuery ( tokenRequest ) ; }
Redeem an authorisation code received from freesound . org for an access token that can be used to make calls to OAuth2 protected resources .
18,197
public Response < AccessTokenDetails > refreshAccessToken ( final String refreshToken ) throws FreesoundClientException { final RefreshOAuth2AccessTokenRequest tokenRequest = new RefreshOAuth2AccessTokenRequest ( clientId , clientSecret , refreshToken ) ; return executeQuery ( tokenRequest ) ; }
Retrieve a new OAuth2 access token using a refresh token .
18,198
@ Requires ( { "sourceDependencyLoader != null" , "type != null" } ) @ Ensures ( { "importNames != null" , "rootLineNumberIterator != null" } ) @ SuppressWarnings ( "unchecked" ) protected void fetchSourceDependency ( ) throws IOException { String fileName = type . getName ( ) . getBinaryName ( ) + JavaUtils . SOURCE_DEPENDENCY_EXTENSION ; InputStream in = sourceDependencyLoader . getResourceAsStream ( fileName ) ; if ( in == null ) { throw new FileNotFoundException ( ) ; } ObjectInputStream oin = new ObjectInputStream ( in ) ; try { importNames = ( Set < String > ) oin . readObject ( ) ; rootLineNumberIterator = ( ( List < Long > ) oin . readObject ( ) ) . iterator ( ) ; } catch ( ClassNotFoundException e ) { throw new IOException ( e ) ; } oin . close ( ) ; }
Fetches source dependency information from the system class loader .
18,199
protected void addMethod ( String k , ExecutableElement e , MethodModel exec ) { ArrayList < ContractableMethod > list = methodMap . get ( k ) ; if ( list == null ) { list = new ArrayList < ContractableMethod > ( ) ; methodMap . put ( k , list ) ; } list . add ( new ContractableMethod ( e , exec ) ) ; }
Adds an association to the method map .