idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
35,100
public List < InetAddress > discoverHosts ( int udpPort , int timeoutMillis ) { List < InetAddress > hosts = new ArrayList < InetAddress > ( ) ; DatagramSocket socket = null ; try { socket = new DatagramSocket ( ) ; broadcast ( udpPort , socket ) ; socket . setSoTimeout ( timeoutMillis ) ; while ( true ) { DatagramPacket packet = discoveryHandler . onRequestNewDatagramPacket ( ) ; try { socket . receive ( packet ) ; } catch ( SocketTimeoutException ex ) { if ( INFO ) info ( "kryonet" , "Host discovery timed out." ) ; return hosts ; } if ( INFO ) info ( "kryonet" , "Discovered server: " + packet . getAddress ( ) ) ; discoveryHandler . onDiscoveredHost ( packet , getKryo ( ) ) ; hosts . add ( packet . getAddress ( ) ) ; } } catch ( IOException ex ) { if ( ERROR ) error ( "kryonet" , "Host discovery failed." , ex ) ; return hosts ; } finally { if ( socket != null ) socket . close ( ) ; discoveryHandler . onFinally ( ) ; } }
Broadcasts a UDP message on the LAN to discover any running servers .
35,101
public void sendToAllTCP ( Object object ) { Connection [ ] connections = this . connections ; for ( int i = 0 , n = connections . length ; i < n ; i ++ ) { Connection connection = connections [ i ] ; connection . sendTCP ( object ) ; } }
BOZO - Provide mechanism for sending to multiple clients without serializing multiple times .
35,102
public void internalWrite ( Server server , Query query , ImmutableList < Result > results ) throws Exception { checkFile ( query ) ; List < String > typeNames = getTypeNames ( ) ; for ( Result result : results ) { String [ ] keyString = KeyUtils . getKeyString ( server , query , result , typeNames , null ) . split ( "\\." ) ; if ( isNumeric ( result . getValue ( ) ) && filters . contains ( keyString [ 2 ] ) ) { int thresholdPos = filters . indexOf ( keyString [ 2 ] ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "[" ) ; sb . append ( result . getEpoch ( ) ) ; sb . append ( "] PROCESS_SERVICE_CHECK_RESULT;" ) ; sb . append ( nagiosHost ) ; sb . append ( ";" ) ; if ( prefix != null ) { sb . append ( prefix ) ; } sb . append ( keyString [ 2 ] ) ; if ( suffix != null ) { sb . append ( suffix ) ; } sb . append ( ";" ) ; sb . append ( nagiosCheckValue ( result . getValue ( ) . toString ( ) , thresholds . get ( thresholdPos ) ) ) ; sb . append ( ";" ) ; logger . info ( sb . toString ( ) ) ; } } }
The meat of the output . Nagios format ..
35,103
protected String nagiosCheckValue ( String value , String composeRange ) { List < String > simpleRange = Arrays . asList ( composeRange . split ( "," ) ) ; double doubleValue = Double . parseDouble ( value ) ; if ( composeRange . isEmpty ( ) ) { return "0" ; } if ( simpleRange . size ( ) == 1 ) { if ( composeRange . endsWith ( "," ) ) { if ( valueCheck ( doubleValue , simpleRange . get ( 0 ) ) ) { return "1" ; } else { return "0" ; } } else if ( valueCheck ( doubleValue , simpleRange . get ( 0 ) ) ) { return "2" ; } else { return "0" ; } } if ( valueCheck ( doubleValue , simpleRange . get ( 1 ) ) ) { return "2" ; } if ( valueCheck ( doubleValue , simpleRange . get ( 0 ) ) ) { return "1" ; } return "0" ; }
Define if a value is in a critical warning or ok state .
35,104
public void prepareSender ( ) throws LifecycleException { if ( host == null || port == null ) { throw new LifecycleException ( "Host and port for " + this . getClass ( ) . getSimpleName ( ) + " output can't be null" ) ; } try { this . dgSocket = new DatagramSocket ( ) ; this . address = new InetSocketAddress ( host , port ) ; } catch ( SocketException sockExc ) { log . error ( "Failed to create a datagram socket" , sockExc ) ; throw new LifecycleException ( sockExc ) ; } }
Setup at start of the writer .
35,105
protected void sendOutput ( String metricLine ) throws IOException { DatagramPacket packet ; byte [ ] data ; data = metricLine . getBytes ( "UTF-8" ) ; packet = new DatagramPacket ( data , 0 , data . length , this . address ) ; this . dgSocket . send ( packet ) ; }
Send a single metric to TCollector .
35,106
public static boolean isNumeric ( Object value ) { if ( value == null ) return false ; if ( value instanceof Number ) return true ; if ( value instanceof String ) { String stringValue = ( String ) value ; if ( isNullOrEmpty ( stringValue ) ) return true ; return isNumber ( stringValue ) ; } return false ; }
Useful for figuring out if an Object is a number .
35,107
public void internalWrite ( Server server , Query query , ImmutableList < Result > results ) throws Exception { this . startOutput ( ) ; for ( String formattedResult : messageFormatter . formatResults ( results , server ) ) { log . debug ( "Sending result: {}" , formattedResult ) ; this . sendOutput ( formattedResult ) ; } this . finishOutput ( ) ; }
Write the results of the query .
35,108
public static String getKeyString ( Server server , Query query , Result result , List < String > typeNames , String rootPrefix ) { StringBuilder sb = new StringBuilder ( ) ; addRootPrefix ( rootPrefix , sb ) ; addAlias ( server , sb ) ; addSeparator ( sb ) ; addMBeanIdentifier ( query , result , sb ) ; addSeparator ( sb ) ; addTypeName ( query , result , typeNames , sb ) ; addKeyString ( query , result , sb ) ; return sb . toString ( ) ; }
Gets the key string .
35,109
public static String getKeyString ( Query query , Result result , List < String > typeNames ) { StringBuilder sb = new StringBuilder ( ) ; addMBeanIdentifier ( query , result , sb ) ; addSeparator ( sb ) ; addTypeName ( query , result , typeNames , sb ) ; addKeyString ( query , result , sb ) ; return sb . toString ( ) ; }
Gets the key string without rootPrefix nor Alias
35,110
public static String getPrefixedKeyString ( Query query , Result result , List < String > typeNames ) { StringBuilder sb = new StringBuilder ( ) ; addTypeName ( query , result , typeNames , sb ) ; addKeyString ( query , result , sb ) ; return sb . toString ( ) ; }
Gets the key string without rootPrefix or Alias
35,111
private static void addMBeanIdentifier ( Query query , Result result , StringBuilder sb ) { if ( result . getKeyAlias ( ) != null ) { sb . append ( result . getKeyAlias ( ) ) ; } else if ( query . isUseObjDomainAsKey ( ) ) { sb . append ( StringUtils . cleanupStr ( result . getObjDomain ( ) , query . isAllowDottedKeys ( ) ) ) ; } else { sb . append ( StringUtils . cleanupStr ( result . getClassName ( ) ) ) ; } }
Adds a key to the StringBuilder
35,112
public void validateSetup ( Server server , Query query ) throws ValidationException { spoofedHostName = getSpoofedHostName ( server . getHost ( ) , server . getAlias ( ) ) ; log . debug ( "Validated Ganglia metric [" + HOST + ": " + host + ", " + PORT + ": " + port + ", " + ADDRESSING_MODE + ": " + addressingMode + ", " + TTL + ": " + ttl + ", " + V31 + ": " + v31 + ", " + UNITS + ": '" + units + "', " + SLOPE + ": " + slope + ", " + TMAX + ": " + tmax + ", " + DMAX + ": " + dmax + ", " + SPOOF_NAME + ": " + spoofedHostName + ", " + GROUP_NAME + ": '" + groupName + "']" ) ; }
Parse and validate settings .
35,113
public void internalWrite ( Server server , Query query , ImmutableList < Result > results ) throws Exception { for ( final Result result : results ) { final String name = KeyUtils . getKeyString ( query , result , getTypeNames ( ) ) ; Object transformedValue = valueTransformer . apply ( result . getValue ( ) ) ; GMetricType dataType = getType ( result . getValue ( ) ) ; log . debug ( "Sending Ganglia metric {}={} [type={}]" , name , transformedValue , dataType ) ; try ( GMetric metric = new GMetric ( host , port , addressingMode , ttl , v31 , null , spoofedHostName ) ) { metric . announce ( name , transformedValue . toString ( ) , dataType , units , slope , tmax , dmax , groupName ) ; } } }
Send query result values to Ganglia .
35,114
private static GMetricType getType ( final Object obj ) { if ( obj instanceof Long || obj instanceof Integer || obj instanceof Byte || obj instanceof Short ) return GMetricType . INT32 ; if ( obj instanceof Float ) return GMetricType . FLOAT ; if ( obj instanceof Double ) return GMetricType . DOUBLE ; try { Double . parseDouble ( obj . toString ( ) ) ; return GMetricType . DOUBLE ; } catch ( NumberFormatException e ) { } try { Integer . parseInt ( obj . toString ( ) ) ; return GMetricType . UINT32 ; } catch ( NumberFormatException e ) { } return GMetricType . STRING ; }
Guess the Ganglia gmetric type to use for a given object .
35,115
public static Boolean getBooleanSetting ( Map < String , Object > settings , String key , Boolean defaultVal ) { final Object value = settings . get ( key ) ; if ( value == null ) { return defaultVal ; } if ( value instanceof Boolean ) { return ( Boolean ) value ; } if ( value instanceof String ) { return Boolean . valueOf ( ( String ) value ) ; } return defaultVal ; }
Gets a Boolean value for the key returning the default value given if not specified or not a valid boolean value .
35,116
public static Integer getIntegerSetting ( Map < String , Object > settings , String key , Integer defaultVal ) { final Object value = settings . get ( key ) ; if ( value == null ) { return defaultVal ; } if ( value instanceof Number ) { return ( ( Number ) value ) . intValue ( ) ; } if ( value instanceof String ) { try { return Integer . parseInt ( ( String ) value ) ; } catch ( NumberFormatException e ) { return defaultVal ; } } return defaultVal ; }
Gets an Integer value for the key returning the default value given if not specified or not a valid numeric value .
35,117
public static String getStringSetting ( Map < String , Object > settings , String key , String defaultVal ) { final Object value = settings . get ( key ) ; return value != null ? value . toString ( ) : defaultVal ; }
Gets a String value for the setting returning the default value if not specified .
35,118
protected static int getIntSetting ( Map < String , Object > settings , String key , int defaultVal ) throws IllegalArgumentException { if ( settings . containsKey ( key ) ) { final Object objectValue = settings . get ( key ) ; if ( objectValue == null ) { throw new IllegalArgumentException ( "Setting '" + key + " null" ) ; } final String value = objectValue . toString ( ) ; try { return Integer . parseInt ( value ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Setting '" + key + "=" + value + "' is not an integer" , e ) ; } } else { return defaultVal ; } }
Gets an int value for the setting returning the default value if not specified .
35,119
protected VelocityEngine getVelocityEngine ( List < String > paths ) { VelocityEngine ve = new VelocityEngine ( ) ; ve . setProperty ( RuntimeConstants . RESOURCE_LOADER , "file" ) ; ve . setProperty ( "cp.resource.loader.class" , "org.apache.velocity.runtime.resource.loader.FileResourceLoader" ) ; ve . setProperty ( "cp.resource.loader.cache" , "true" ) ; ve . setProperty ( "cp.resource.loader.path" , StringUtils . join ( paths , "," ) ) ; ve . setProperty ( "cp.resource.loader.modificationCheckInterval " , "10" ) ; ve . setProperty ( "input.encoding" , "UTF-8" ) ; ve . setProperty ( "output.encoding" , "UTF-8" ) ; ve . setProperty ( "runtime.log" , "" ) ; return ve ; }
Sets velocity up to load resources from a list of paths .
35,120
public JmxProcess parseProcess ( File file ) throws IOException { String fileName = file . getName ( ) ; ObjectMapper mapper = fileName . endsWith ( ".yml" ) || fileName . endsWith ( ".yaml" ) ? yamlMapper : jsonMapper ; JsonNode jsonNode = mapper . readTree ( file ) ; JmxProcess jmx = mapper . treeToValue ( jsonNode , JmxProcess . class ) ; jmx . setName ( fileName ) ; return jmx ; }
Uses jackson to load json configuration from a File into a full object tree representation of that json .
35,121
void addTags ( StringBuilder resultString , Server server ) { if ( hostnameTag ) { addTag ( resultString , "host" , server . getLabel ( ) ) ; } for ( Map . Entry < String , String > tagEntry : tags . entrySet ( ) ) { addTag ( resultString , tagEntry . getKey ( ) , tagEntry . getValue ( ) ) ; } }
Add tags to the given result string including a host tag with the name of the server and all of the tags defined in the settings entry in the configuration file within the tag element .
35,122
void addTag ( StringBuilder resultString , String tagName , String tagValue ) { resultString . append ( " " ) ; resultString . append ( sanitizeString ( tagName ) ) ; resultString . append ( "=" ) ; resultString . append ( sanitizeString ( tagValue ) ) ; }
Add one tag with the provided name and value to the given result string .
35,123
private void formatResultString ( StringBuilder resultString , String metricName , long epoch , Object value ) { resultString . append ( sanitizeString ( metricName ) ) ; resultString . append ( " " ) ; resultString . append ( Long . toString ( epoch ) ) ; resultString . append ( " " ) ; resultString . append ( sanitizeString ( value . toString ( ) ) ) ; }
Format the result string given the class name and attribute name of the source value the timestamp and the value .
35,124
protected void processOneMetric ( List < String > resultStrings , Server server , Result result , Object value , String addTagName , String addTagValue ) { String metricName = this . metricNameStrategy . formatName ( result ) ; if ( isNumeric ( value ) ) { StringBuilder resultString = new StringBuilder ( ) ; formatResultString ( resultString , metricName , result . getEpoch ( ) / 1000L , value ) ; addTags ( resultString , server ) ; if ( addTagName != null ) { addTag ( resultString , addTagName , addTagValue ) ; } if ( ! typeNames . isEmpty ( ) ) { this . addTypeNamesTags ( resultString , result ) ; } resultStrings . add ( resultString . toString ( ) ) ; } else { log . debug ( "Skipping non-numeric value for metric {}; value={}" , metricName , value ) ; } }
Process a single metric from the given JMX query result with the specified value .
35,125
private String getGatewayMessage ( final List < Result > results ) throws IOException { int valueCount = 0 ; Writer writer = new StringWriter ( ) ; JsonGenerator g = jsonFactory . createGenerator ( writer ) ; g . writeStartObject ( ) ; g . writeNumberField ( "timestamp" , System . currentTimeMillis ( ) / 1000 ) ; g . writeNumberField ( "proto_version" , STACKDRIVER_PROTOCOL_VERSION ) ; g . writeArrayFieldStart ( "data" ) ; List < String > typeNames = this . getTypeNames ( ) ; for ( Result metric : results ) { if ( isNumeric ( metric . getValue ( ) ) ) { StringBuilder nameBuilder = new StringBuilder ( ) ; if ( this . prefix != null ) { nameBuilder . append ( prefix ) ; nameBuilder . append ( "." ) ; } if ( ! metric . getKeyAlias ( ) . isEmpty ( ) ) { nameBuilder . append ( metric . getKeyAlias ( ) ) ; } else { nameBuilder . append ( metric . getClassName ( ) ) ; } String typeName = com . googlecode . jmxtrans . model . naming . StringUtils . cleanupStr ( TypeNameValuesStringBuilder . getDefaultBuilder ( ) . build ( typeNames , metric . getTypeName ( ) ) ) ; if ( typeName != null && typeName . length ( ) > 0 ) { nameBuilder . append ( "." ) ; nameBuilder . append ( typeName ) ; } nameBuilder . append ( "." ) ; nameBuilder . append ( KeyUtils . getValueKey ( metric ) ) ; if ( metric . getValue ( ) instanceof Float && ( ( Float ) metric . getValue ( ) ) . isNaN ( ) ) { logger . info ( "Metric value for " + nameBuilder . toString ( ) + " is NaN, skipping" ) ; continue ; } if ( metric . getValue ( ) instanceof Double && ( ( Double ) metric . getValue ( ) ) . isNaN ( ) ) { logger . info ( "Metric value for " + nameBuilder . toString ( ) + " is NaN, skipping" ) ; continue ; } valueCount ++ ; g . writeStartObject ( ) ; g . writeStringField ( "name" , nameBuilder . toString ( ) ) ; g . writeNumberField ( "value" , Double . valueOf ( metric . getValue ( ) . toString ( ) ) ) ; if ( instanceId != null && ! instanceId . isEmpty ( ) ) { g . writeStringField ( "instance" , instanceId ) ; } g . writeNumberField ( "collected_at" , metric . getEpoch ( ) / 1000 ) ; g . writeEndObject ( ) ; } } g . writeEndArray ( ) ; g . writeEndObject ( ) ; g . flush ( ) ; g . close ( ) ; if ( valueCount > 0 ) { return writer . toString ( ) ; } else { return null ; } }
Take query results make a JSON String
35,126
private void doSend ( final String gatewayMessage ) { HttpURLConnection urlConnection = null ; try { if ( proxy == null ) { urlConnection = ( HttpURLConnection ) gatewayUrl . openConnection ( ) ; } else { urlConnection = ( HttpURLConnection ) gatewayUrl . openConnection ( proxy ) ; } urlConnection . setRequestMethod ( "POST" ) ; urlConnection . setDoInput ( true ) ; urlConnection . setDoOutput ( true ) ; urlConnection . setReadTimeout ( timeoutInMillis ) ; urlConnection . setRequestProperty ( "content-type" , "application/json; charset=utf-8" ) ; urlConnection . setRequestProperty ( "x-stackdriver-apikey" , apiKey ) ; urlConnection . getOutputStream ( ) . write ( gatewayMessage . getBytes ( ISO_8859_1 ) ) ; int responseCode = urlConnection . getResponseCode ( ) ; if ( responseCode != 200 && responseCode != 201 ) { logger . warn ( "Failed to send results to Stackdriver server: responseCode=" + responseCode + " message=" + urlConnection . getResponseMessage ( ) ) ; } } catch ( Exception e ) { logger . warn ( "Failure to send result to Stackdriver server" , e ) ; } finally { if ( urlConnection != null ) { try { InputStream in = urlConnection . getInputStream ( ) ; in . close ( ) ; InputStream err = urlConnection . getErrorStream ( ) ; if ( err != null ) { err . close ( ) ; } urlConnection . disconnect ( ) ; } catch ( IOException e ) { logger . warn ( "Error flushing http connection for one result, continuing" ) ; logger . debug ( "Stack trace for the http connection, usually a network timeout" , e ) ; } } } }
Post the formatted results to the gateway URL over HTTP
35,127
private void doMain ( ) throws Exception { this . start ( ) ; while ( true ) { try { Thread . sleep ( 5 ) ; } catch ( Exception e ) { log . info ( "shutting down" , e ) ; break ; } } this . unregisterMBeans ( ) ; }
The real main method .
35,128
private void stopWriterAndClearMasterServerList ( ) { for ( Server server : this . masterServersList ) { for ( OutputWriter writer : server . getOutputWriters ( ) ) { try { writer . close ( ) ; } catch ( LifecycleException ex ) { log . error ( "Eror stopping writer: {}" , writer ) ; } } for ( Query query : server . getQueries ( ) ) { for ( OutputWriter writer : query . getOutputWriterInstances ( ) ) { try { writer . close ( ) ; log . debug ( "Stopped writer: {} for query: {}" , writer , query ) ; } catch ( LifecycleException ex ) { log . error ( "Error stopping writer: {} for query: {}" , writer , query , ex ) ; } } } } this . masterServersList = ImmutableList . of ( ) ; }
Shut down the output writers and clear the master server list Used both during shutdown and when re - reading config files
35,129
private void startupWatchdir ( ) throws Exception { File dirToWatch ; if ( this . configuration . getProcessConfigDirOrFile ( ) . isFile ( ) ) { dirToWatch = new File ( FilenameUtils . getFullPath ( this . configuration . getProcessConfigDirOrFile ( ) . getAbsolutePath ( ) ) ) ; } else { dirToWatch = this . configuration . getProcessConfigDirOrFile ( ) ; } this . watcher = new WatchDir ( dirToWatch , this ) ; this . watcher . start ( ) ; }
Startup the watchdir service .
35,130
public void executeStandalone ( JmxProcess process ) throws Exception { this . masterServersList = process . getServers ( ) ; this . serverScheduler . start ( ) ; this . processServersIntoJobs ( ) ; Thread . sleep ( MILLISECONDS . convert ( 10 , SECONDS ) ) ; }
Handy method which runs the JmxProcess
35,131
private void processFilesIntoServers ( ) throws LifecycleException { try { this . stopWriterAndClearMasterServerList ( ) ; } catch ( Exception e ) { log . error ( "Error while clearing master server list: " + e . getMessage ( ) , e ) ; throw new LifecycleException ( e ) ; } this . masterServersList = configurationParser . parseServers ( getProcessConfigFiles ( ) , configuration . isContinueOnJsonError ( ) ) ; }
Processes all the json files and manages the dedup process
35,132
private boolean isProcessConfigFile ( File file ) { if ( this . configuration . getProcessConfigDirOrFile ( ) . isFile ( ) ) { return file . equals ( this . configuration . getProcessConfigDirOrFile ( ) ) ; } if ( file . exists ( ) && ! file . isFile ( ) ) { return false ; } final String fileName = file . getName ( ) ; return ! fileName . startsWith ( "." ) && ( fileName . endsWith ( ".json" ) || fileName . endsWith ( ".yml" ) || fileName . endsWith ( ".yaml" ) ) ; }
Are we a file and a JSON or YAML file?
35,133
public JMXConnector getServerConnection ( ) throws IOException { JMXServiceURL url = getJmxServiceURL ( ) ; return JMXConnectorFactory . connect ( url , this . getEnvironment ( ) ) ; }
Helper method for connecting to a Server . You need to close the resulting connection .
35,134
public void validateSetup ( Server server , Query query ) throws ValidationException { Logger logger ; if ( loggers . containsKey ( outputFile ) ) { logger = getLogger ( outputFile ) ; } else { try { logger = buildLogger ( outputFile ) ; loggers . put ( outputFile , logger ) ; } catch ( IOException e ) { throw new ValidationException ( "Failed to setup logback" , query , e ) ; } } logwriter = new LogWriter ( logger , delimiter ) ; }
Creates the logging
35,135
public void internalWrite ( Server server , Query query , ImmutableList < Result > results ) throws Exception { graphiteWriter . write ( logwriter , server , query , results ) ; }
The meat of the output . Reuses the GraphiteWriter2 class but writes in a logfile instead of a network socket .
35,136
private AmazonCloudWatchClient createCloudWatchClient ( ) { AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient ( new InstanceProfileCredentialsProvider ( ) ) ; cloudWatchClient . setRegion ( checkNotNull ( Regions . getCurrentRegion ( ) , "Problems getting AWS metadata" ) ) ; return cloudWatchClient ; }
Configuring the CloudWatch client .
35,137
public String formatName ( Result result ) { String formatted ; JexlContext context = new MapContext ( ) ; this . populateContext ( context , result ) ; try { formatted = ( String ) this . parsedExpr . evaluate ( context ) ; } catch ( JexlException jexlExc ) { LOG . error ( "error applying JEXL expression to query results" , jexlExc ) ; formatted = null ; } return formatted ; }
Format the name for the given result .
35,138
protected void populateContext ( JexlContext context , Result result ) { context . set ( VAR_CLASSNAME , result . getClassName ( ) ) ; context . set ( VAR_ATTRIBUTE_NAME , result . getAttributeName ( ) ) ; context . set ( VAR_CLASSNAME_ALIAS , result . getKeyAlias ( ) ) ; Map < String , String > typeNameMap = TypeNameValue . extractMap ( result . getTypeName ( ) ) ; context . set ( VAR_TYPENAME , typeNameMap ) ; String effectiveClassname = result . getKeyAlias ( ) ; if ( effectiveClassname == null ) { effectiveClassname = result . getClassName ( ) ; } context . set ( VAR_EFFECTIVE_CLASSNAME , effectiveClassname ) ; context . set ( VAR_RESULT , result ) ; }
Populate the context with values from the result .
35,139
public String getDataSourceName ( String typeName , String attributeName , List < String > valuePath ) { String result ; String entry = StringUtils . join ( valuePath , '.' ) ; if ( typeName != null ) { result = typeName + attributeName + entry ; } else { result = attributeName + entry ; } if ( attributeName . length ( ) > 15 ) { String [ ] split = StringUtils . splitByCharacterTypeCamelCase ( attributeName ) ; String join = StringUtils . join ( split , '.' ) ; attributeName = WordUtils . initials ( join , INITIALS ) ; } result = attributeName + DigestUtils . md5Hex ( result ) ; result = StringUtils . left ( result , 19 ) ; return result ; }
rrd datasources must be less than 21 characters in length so work to make it shorter . Not ideal at all but works fairly well it seems .
35,140
protected void rrdToolUpdate ( String template , String data ) throws Exception { List < String > commands = new ArrayList < > ( ) ; commands . add ( binaryPath + "/rrdtool" ) ; commands . add ( "update" ) ; commands . add ( outputFile . getCanonicalPath ( ) ) ; commands . add ( "-t" ) ; commands . add ( template ) ; commands . add ( "N:" + data ) ; ProcessBuilder pb = new ProcessBuilder ( commands ) ; Process process = pb . start ( ) ; checkErrorStream ( process ) ; }
Executes the rrdtool update command .
35,141
protected void rrdToolCreateDatabase ( RrdDef def ) throws Exception { List < String > commands = new ArrayList < > ( ) ; commands . add ( this . binaryPath + "/rrdtool" ) ; commands . add ( "create" ) ; commands . add ( this . outputFile . getCanonicalPath ( ) ) ; commands . add ( "-s" ) ; commands . add ( String . valueOf ( def . getStep ( ) ) ) ; for ( DsDef dsdef : def . getDsDefs ( ) ) { commands . add ( getDsDefStr ( dsdef ) ) ; } for ( ArcDef adef : def . getArcDefs ( ) ) { commands . add ( getRraStr ( adef ) ) ; } ProcessBuilder pb = new ProcessBuilder ( commands ) ; Process process = pb . start ( ) ; try { checkErrorStream ( process ) ; } finally { IOUtils . closeQuietly ( process . getInputStream ( ) ) ; IOUtils . closeQuietly ( process . getOutputStream ( ) ) ; IOUtils . closeQuietly ( process . getErrorStream ( ) ) ; } }
Calls out to the rrdtool binary with the create command .
35,142
private void checkErrorStream ( Process process ) throws Exception { try ( InputStream is = process . getErrorStream ( ) ; InputStreamReader isr = new InputStreamReader ( is , Charset . defaultCharset ( ) ) ; BufferedReader br = new BufferedReader ( isr ) ) { StringBuilder sb = new StringBuilder ( ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { sb . append ( line ) ; } if ( sb . length ( ) > 0 ) { throw new RuntimeException ( sb . toString ( ) ) ; } } }
Check to see if there was an error processing an rrdtool command
35,143
private String getRraStr ( ArcDef def ) { return "RRA:" + def . getConsolFun ( ) + ":" + def . getXff ( ) + ":" + def . getSteps ( ) + ":" + def . getRows ( ) ; }
Generate a RRA line for rrdtool
35,144
private List < String > getDsNames ( DsDef [ ] defs ) { List < String > names = new ArrayList < > ( ) ; for ( DsDef def : defs ) { names . add ( def . getDsName ( ) ) ; } return names ; }
Get a list of DsNames used to create the datasource .
35,145
public void add ( URL url ) { URLClassLoader sysLoader = ( URLClassLoader ) ClassLoader . getSystemClassLoader ( ) ; Class sysClass = URLClassLoader . class ; try { Method method = sysClass . getDeclaredMethod ( "addURL" , URL . class ) ; method . setAccessible ( true ) ; method . invoke ( sysLoader , new Object [ ] { url } ) ; } catch ( InvocationTargetException e ) { throw new JarLoadingException ( e ) ; } catch ( NoSuchMethodException e ) { throw new JarLoadingException ( e ) ; } catch ( IllegalAccessException e ) { throw new JarLoadingException ( e ) ; } }
Add the given URL to the system class loader .
35,146
private static void describeClassTree ( Class < ? > inputClass , Set < Class < ? > > setOfClasses ) { if ( inputClass == null ) { return ; } if ( Object . class . equals ( inputClass ) || setOfClasses . contains ( inputClass ) ) { return ; } setOfClasses . add ( inputClass ) ; describeClassTree ( inputClass . getSuperclass ( ) , setOfClasses ) ; for ( Class < ? > hasInterface : inputClass . getInterfaces ( ) ) { describeClassTree ( hasInterface , setOfClasses ) ; } }
Recursive handler for describing the set of classes while using the setOfClasses parameter as a collector
35,147
private static Set < Class < ? > > describeClassTree ( Class < ? > inputClass ) { if ( inputClass == null ) { return Collections . emptySet ( ) ; } Set < Class < ? > > classes = Sets . newLinkedHashSet ( ) ; describeClassTree ( inputClass , classes ) ; return classes ; }
Given an object return the set of classes that it extends or implements .
35,148
public void usage ( StringBuilder out , String indent ) { if ( commander . getDescriptions ( ) == null ) { commander . createDescriptions ( ) ; } boolean hasCommands = ! commander . getCommands ( ) . isEmpty ( ) ; boolean hasOptions = ! commander . getDescriptions ( ) . isEmpty ( ) ; final int descriptionIndent = 6 ; final int indentCount = indent . length ( ) + descriptionIndent ; appendMainLine ( out , hasOptions , hasCommands , indentCount , indent ) ; int longestName = 0 ; List < ParameterDescription > sortedParameters = Lists . newArrayList ( ) ; for ( ParameterDescription pd : commander . getFields ( ) . values ( ) ) { if ( ! pd . getParameter ( ) . hidden ( ) ) { sortedParameters . add ( pd ) ; int length = pd . getNames ( ) . length ( ) + 2 ; if ( length > longestName ) { longestName = length ; } } } sortedParameters . sort ( commander . getParameterDescriptionComparator ( ) ) ; appendAllParametersDetails ( out , indentCount , indent , sortedParameters ) ; if ( hasCommands ) { appendCommands ( out , indentCount , descriptionIndent , indent ) ; } }
Stores the usage in the argument string builder with the argument indentation . This works by appending each portion of the help in the following order . Their outputs can be modified by overriding them in a subclass of this class .
35,149
@ SuppressWarnings ( "deprecation" ) private ResourceBundle findResourceBundle ( Object o ) { ResourceBundle result = null ; Parameters p = o . getClass ( ) . getAnnotation ( Parameters . class ) ; if ( p != null && ! isEmpty ( p . resourceBundle ( ) ) ) { result = ResourceBundle . getBundle ( p . resourceBundle ( ) , Locale . getDefault ( ) ) ; } else { com . beust . jcommander . ResourceBundle a = o . getClass ( ) . getAnnotation ( com . beust . jcommander . ResourceBundle . class ) ; if ( a != null && ! isEmpty ( a . value ( ) ) ) { result = ResourceBundle . getBundle ( a . value ( ) , Locale . getDefault ( ) ) ; } } return result ; }
Find the resource bundle in the annotations .
35,150
public final void addObject ( Object object ) { if ( object instanceof Iterable ) { for ( Object o : ( Iterable < ? > ) object ) { objects . add ( o ) ; } } else if ( object . getClass ( ) . isArray ( ) ) { for ( Object o : ( Object [ ] ) object ) { objects . add ( o ) ; } } else { objects . add ( object ) ; } }
declared final since this is invoked from constructors
35,151
public void parse ( String ... args ) { try { parse ( true , args ) ; } catch ( ParameterException ex ) { ex . setJCommander ( this ) ; throw ex ; } }
Parse and validate the command line parameters .
35,152
private void validateOptions ( ) { if ( helpWasSpecified ) { return ; } if ( ! requiredFields . isEmpty ( ) ) { List < String > missingFields = new ArrayList < > ( ) ; for ( ParameterDescription pd : requiredFields . values ( ) ) { missingFields . add ( "[" + Strings . join ( " | " , pd . getParameter ( ) . names ( ) ) + "]" ) ; } String message = Strings . join ( ", " , missingFields ) ; throw new ParameterException ( "The following " + pluralize ( requiredFields . size ( ) , "option is required: " , "options are required: " ) + message ) ; } if ( mainParameter != null && mainParameter . description != null ) { ParameterDescription mainParameterDescription = mainParameter . description ; if ( mainParameterDescription . getParameter ( ) . required ( ) && ! mainParameterDescription . isAssigned ( ) ) { throw new ParameterException ( "Main parameters are required (\"" + mainParameterDescription . getDescription ( ) + "\")" ) ; } int arity = mainParameterDescription . getParameter ( ) . arity ( ) ; if ( arity != Parameter . DEFAULT_ARITY ) { Object value = mainParameterDescription . getParameterized ( ) . get ( mainParameter . object ) ; if ( List . class . isAssignableFrom ( value . getClass ( ) ) ) { int size = ( ( List < ? > ) value ) . size ( ) ; if ( size != arity ) { throw new ParameterException ( "There should be exactly " + arity + " main parameters but " + size + " were found" ) ; } } } } }
Make sure that all the required parameters have received a value .
35,153
private List < String > readFile ( String fileName ) { List < String > result = Lists . newArrayList ( ) ; try ( BufferedReader bufRead = Files . newBufferedReader ( Paths . get ( fileName ) , options . atFileCharset ) ) { String line ; while ( ( line = bufRead . readLine ( ) ) != null ) { if ( line . length ( ) > 0 && ! line . trim ( ) . startsWith ( "#" ) ) { result . add ( line ) ; } } } catch ( IOException e ) { throw new ParameterException ( "Could not read file " + fileName + ": " + e ) ; } return result ; }
Reads the file specified by filename and returns the file content as a string . End of lines are replaced by a space .
35,154
private static String trim ( String string ) { String result = string . trim ( ) ; if ( result . startsWith ( "\"" ) && result . endsWith ( "\"" ) && result . length ( ) > 1 ) { result = result . substring ( 1 , result . length ( ) - 1 ) ; } return result ; }
Remove spaces at both ends and handle double quotes .
35,155
private char [ ] readPassword ( String description , boolean echoInput ) { getConsole ( ) . print ( description + ": " ) ; return getConsole ( ) . readPassword ( echoInput ) ; }
Invoke Console . readPassword through reflection to avoid depending on Java 6 .
35,156
public void setProgramName ( String name , String ... aliases ) { programName = new ProgramName ( name , Arrays . asList ( aliases ) ) ; }
Set the program name
35,157
public void addConverterFactory ( final IStringConverterFactory converterFactory ) { addConverterInstanceFactory ( new IStringConverterInstanceFactory ( ) { @ SuppressWarnings ( "unchecked" ) public IStringConverter < ? > getConverterInstance ( Parameter parameter , Class < ? > forType , String optionName ) { final Class < ? extends IStringConverter < ? > > converterClass = converterFactory . getConverter ( forType ) ; try { if ( optionName == null ) { optionName = parameter . names ( ) . length > 0 ? parameter . names ( ) [ 0 ] : "[Main class]" ; } return converterClass != null ? instantiateConverter ( optionName , converterClass ) : null ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException e ) { throw new ParameterException ( e ) ; } } } ) ; }
Adds a factory to lookup string converters . The added factory is used prior to previously added factories .
35,158
public void addCommand ( String name , Object object , String ... aliases ) { JCommander jc = new JCommander ( options ) ; jc . addObject ( object ) ; jc . createDescriptions ( ) ; jc . setProgramName ( name , aliases ) ; ProgramName progName = jc . programName ; commands . put ( progName , jc ) ; aliasMap . put ( new StringKey ( name ) , progName ) ; for ( String a : aliases ) { IKey alias = new StringKey ( a ) ; if ( ! alias . equals ( name ) ) { ProgramName mappedName = aliasMap . get ( alias ) ; if ( mappedName != null && ! mappedName . equals ( progName ) ) { throw new ParameterException ( "Cannot set alias " + alias + " for " + name + " command because it has already been defined for " + mappedName . name + " command" ) ; } aliasMap . put ( alias , progName ) ; } } }
Add a command object and its aliases .
35,159
private boolean itemIsObscuredByHeader ( RecyclerView parent , View item , View header , int orientation ) { RecyclerView . LayoutParams layoutParams = ( RecyclerView . LayoutParams ) item . getLayoutParams ( ) ; mDimensionCalculator . initMargins ( mTempRect1 , header ) ; int adapterPosition = parent . getChildAdapterPosition ( item ) ; if ( adapterPosition == RecyclerView . NO_POSITION || mHeaderProvider . getHeader ( parent , adapterPosition ) != header ) { return false ; } if ( orientation == LinearLayoutManager . VERTICAL ) { int itemTop = item . getTop ( ) - layoutParams . topMargin ; int headerBottom = getListTop ( parent ) + header . getBottom ( ) + mTempRect1 . bottom + mTempRect1 . top ; if ( itemTop >= headerBottom ) { return false ; } } else { int itemLeft = item . getLeft ( ) - layoutParams . leftMargin ; int headerRight = getListLeft ( parent ) + header . getRight ( ) + mTempRect1 . right + mTempRect1 . left ; if ( itemLeft >= headerRight ) { return false ; } } return true ; }
Determines if an item is obscured by a header
35,160
public void drawHeader ( RecyclerView recyclerView , Canvas canvas , View header , Rect offset ) { canvas . save ( ) ; if ( recyclerView . getLayoutManager ( ) . getClipToPadding ( ) ) { initClipRectForHeader ( mTempRect , recyclerView , header ) ; canvas . clipRect ( mTempRect ) ; } canvas . translate ( offset . left , offset . top ) ; header . draw ( canvas ) ; canvas . restore ( ) ; }
Draws a header to a canvas offsetting by some x and y amount
35,161
public static boolean isIanaRel ( String relation ) { Assert . notNull ( relation , "Link relation must not be null!" ) ; return LINK_RELATIONS . stream ( ) . anyMatch ( it -> it . value ( ) . equalsIgnoreCase ( relation ) ) ; }
Is this relation an IANA standard? Per RFC 8288 parsing of link relations is case insensitive .
35,162
public List < MethodParameter > getParametersOfType ( Class < ? > type ) { Assert . notNull ( type , "Type must not be null!" ) ; return getParameters ( ) . stream ( ) . filter ( it -> it . getParameterType ( ) . equals ( type ) ) . collect ( Collectors . toList ( ) ) ; }
Returns all parameters of the given type .
35,163
public static boolean isTemplate ( String candidate ) { return StringUtils . hasText ( candidate ) ? VARIABLE_REGEX . matcher ( candidate ) . find ( ) : false ; }
Returns whether the given candidate is a URI template .
35,164
public List < String > getVariableNames ( ) { return variables . asList ( ) . stream ( ) . map ( TemplateVariable :: getName ) . collect ( Collectors . toList ( ) ) ; }
Returns the names of the variables discovered .
35,165
private static String join ( String typeMapping , String mapping ) { return MULTIPLE_SLASHES . matcher ( typeMapping . concat ( "/" ) . concat ( mapping ) ) . replaceAll ( "/" ) ; }
Joins the given mappings making sure exactly one slash .
35,166
public static String encodePath ( Object source ) { Assert . notNull ( source , "Path value must not be null!" ) ; try { return UriUtils . encodePath ( source . toString ( ) , ENCODING ) ; } catch ( Throwable e ) { throw new IllegalStateException ( e ) ; } }
Encodes the given path value .
35,167
public static String encodeParameter ( Object source ) { Assert . notNull ( source , "Request parameter value must not be null!" ) ; try { return UriUtils . encodeQueryParam ( source . toString ( ) , ENCODING ) ; } catch ( Throwable e ) { throw new IllegalStateException ( e ) ; } }
Encodes the given request parameter value .
35,168
protected D createModelWithId ( Object id , T entity ) { return createModelWithId ( id , entity , new Object [ 0 ] ) ; }
Creates a new resource with a self link to the given id .
35,169
private static void validate ( RepresentationModel < ? > resource , HalFormsAffordanceModel model ) { String affordanceUri = model . getURI ( ) ; String selfLinkUri = resource . getRequiredLink ( IanaLinkRelations . SELF . value ( ) ) . expand ( ) . getHref ( ) ; if ( ! affordanceUri . equals ( selfLinkUri ) ) { throw new IllegalStateException ( "Affordance's URI " + affordanceUri + " doesn't match self link " + selfLinkUri + " as expected in HAL-FORMS" ) ; } }
Verify that the resource s self link and the affordance s URI have the same relative path .
35,170
public Hop withParameter ( String name , Object value ) { Assert . hasText ( name , "Name must not be null or empty!" ) ; HashMap < String , Object > parameters = new HashMap < > ( this . parameters ) ; parameters . put ( name , value ) ; return new Hop ( this . rel , parameters , this . headers ) ; }
Add one parameter to the map of parameters .
35,171
public Hop header ( String headerName , String headerValue ) { Assert . hasText ( headerName , "headerName must not be null or empty!" ) ; if ( this . headers == HttpHeaders . EMPTY ) { HttpHeaders newHeaders = new HttpHeaders ( ) ; newHeaders . add ( headerName , headerValue ) ; return new Hop ( this . rel , this . parameters , newHeaders ) ; } this . headers . add ( headerName , headerValue ) ; return this ; }
Add one header to the HttpHeaders collection .
35,172
private static List < UberData > doExtractLinksAndContent ( Object item ) { if ( item instanceof EntityModel ) { return extractLinksAndContent ( ( EntityModel < ? > ) item ) ; } if ( item instanceof RepresentationModel ) { return extractLinksAndContent ( ( RepresentationModel < ? > ) item ) ; } return extractLinksAndContent ( new EntityModel < > ( item ) ) ; }
Extract links and content from an object of any type .
35,173
public HalFormsTemplate getTemplate ( String key ) { Assert . notNull ( key , "Template key must not be null!" ) ; return this . templates . get ( key ) ; }
Returns the template with the given name .
35,174
public HalFormsDocument < T > andEmbedded ( HalLinkRelation key , Object value ) { Assert . notNull ( key , "Embedded key must not be null!" ) ; Assert . notNull ( value , "Embedded value must not be null!" ) ; Map < HalLinkRelation , Object > embedded = new HashMap < > ( this . embedded ) ; embedded . put ( key , value ) ; return new HalFormsDocument < > ( resource , resources , embedded , pageMetadata , links , templates ) ; }
Adds the given value as embedded one .
35,175
public Object toRawData ( JavaType javaType ) { if ( this . data . isEmpty ( ) ) { return null ; } if ( PRIMITIVE_TYPES . contains ( javaType . getRawClass ( ) ) ) { return this . data . get ( 0 ) . getValue ( ) ; } return PropertyUtils . createObjectFromProperties ( javaType . getRawClass ( ) , this . data . stream ( ) . collect ( Collectors . toMap ( CollectionJsonData :: getName , CollectionJsonData :: getValue ) ) ) ; }
Generate an object used the deserialized properties and the provided type from the deserializer .
35,176
@ SuppressWarnings ( "unchecked" ) public T add ( Link link ) { Assert . notNull ( link , "Link must not be null!" ) ; this . links . add ( link ) ; return ( T ) this ; }
Adds the given link to the resource .
35,177
private static void insertJsonColumn ( CqlSession session ) { User alice = new User ( "alice" , 30 ) ; User bob = new User ( "bob" , 35 ) ; Statement stmt = insertInto ( "examples" , "json_jackson_column" ) . value ( "id" , literal ( 1 ) ) . value ( "json" , literal ( alice , session . getContext ( ) . getCodecRegistry ( ) ) ) . build ( ) ; session . execute ( stmt ) ; PreparedStatement pst = session . prepare ( insertInto ( "examples" , "json_jackson_column" ) . value ( "id" , bindMarker ( "id" ) ) . value ( "json" , bindMarker ( "json" ) ) . build ( ) ) ; session . execute ( pst . bind ( ) . setInt ( "id" , 2 ) . set ( "json" , bob , User . class ) ) ; }
Mapping a User instance to a table column
35,178
private static void selectJsonColumn ( CqlSession session ) { Statement stmt = selectFrom ( "examples" , "json_jackson_column" ) . all ( ) . whereColumn ( "id" ) . in ( literal ( 1 ) , literal ( 2 ) ) . build ( ) ; ResultSet rows = session . execute ( stmt ) ; for ( Row row : rows ) { int id = row . getInt ( "id" ) ; User user = row . get ( "json" , User . class ) ; String json = row . getString ( "json" ) ; System . out . printf ( "Retrieved row:%n id %d%n user %s%n user (raw) %s%n%n" , id , user , json ) ; } }
Retrieving User instances from a table column
35,179
public static String opcodeString ( int opcode ) { switch ( opcode ) { case ProtocolConstants . Opcode . ERROR : return "ERROR" ; case ProtocolConstants . Opcode . STARTUP : return "STARTUP" ; case ProtocolConstants . Opcode . READY : return "READY" ; case ProtocolConstants . Opcode . AUTHENTICATE : return "AUTHENTICATE" ; case ProtocolConstants . Opcode . OPTIONS : return "OPTIONS" ; case ProtocolConstants . Opcode . SUPPORTED : return "SUPPORTED" ; case ProtocolConstants . Opcode . QUERY : return "QUERY" ; case ProtocolConstants . Opcode . RESULT : return "RESULT" ; case ProtocolConstants . Opcode . PREPARE : return "PREPARE" ; case ProtocolConstants . Opcode . EXECUTE : return "EXECUTE" ; case ProtocolConstants . Opcode . REGISTER : return "REGISTER" ; case ProtocolConstants . Opcode . EVENT : return "EVENT" ; case ProtocolConstants . Opcode . BATCH : return "BATCH" ; case ProtocolConstants . Opcode . AUTH_CHALLENGE : return "AUTH_CHALLENGE" ; case ProtocolConstants . Opcode . AUTH_RESPONSE : return "AUTH_RESPONSE" ; case ProtocolConstants . Opcode . AUTH_SUCCESS : return "AUTH_SUCCESS" ; default : return "0x" + Integer . toHexString ( opcode ) ; } }
Formats a message opcode for logs and error messages .
35,180
public static String errorCodeString ( int errorCode ) { switch ( errorCode ) { case ProtocolConstants . ErrorCode . SERVER_ERROR : return "SERVER_ERROR" ; case ProtocolConstants . ErrorCode . PROTOCOL_ERROR : return "PROTOCOL_ERROR" ; case ProtocolConstants . ErrorCode . AUTH_ERROR : return "AUTH_ERROR" ; case ProtocolConstants . ErrorCode . UNAVAILABLE : return "UNAVAILABLE" ; case ProtocolConstants . ErrorCode . OVERLOADED : return "OVERLOADED" ; case ProtocolConstants . ErrorCode . IS_BOOTSTRAPPING : return "IS_BOOTSTRAPPING" ; case ProtocolConstants . ErrorCode . TRUNCATE_ERROR : return "TRUNCATE_ERROR" ; case ProtocolConstants . ErrorCode . WRITE_TIMEOUT : return "WRITE_TIMEOUT" ; case ProtocolConstants . ErrorCode . READ_TIMEOUT : return "READ_TIMEOUT" ; case ProtocolConstants . ErrorCode . READ_FAILURE : return "READ_FAILURE" ; case ProtocolConstants . ErrorCode . FUNCTION_FAILURE : return "FUNCTION_FAILURE" ; case ProtocolConstants . ErrorCode . WRITE_FAILURE : return "WRITE_FAILURE" ; case ProtocolConstants . ErrorCode . SYNTAX_ERROR : return "SYNTAX_ERROR" ; case ProtocolConstants . ErrorCode . UNAUTHORIZED : return "UNAUTHORIZED" ; case ProtocolConstants . ErrorCode . INVALID : return "INVALID" ; case ProtocolConstants . ErrorCode . CONFIG_ERROR : return "CONFIG_ERROR" ; case ProtocolConstants . ErrorCode . ALREADY_EXISTS : return "ALREADY_EXISTS" ; case ProtocolConstants . ErrorCode . UNPREPARED : return "UNPREPARED" ; default : return "0x" + Integer . toHexString ( errorCode ) ; } }
Formats an error code for logs and error messages .
35,181
public void reconnectNow ( boolean forceIfStopped ) { assert executor . inEventLoop ( ) ; if ( state == State . ATTEMPT_IN_PROGRESS || state == State . STOP_AFTER_CURRENT ) { LOG . debug ( "[{}] reconnectNow and current attempt was still running, letting it complete" , logPrefix ) ; if ( state == State . STOP_AFTER_CURRENT ) { state = State . ATTEMPT_IN_PROGRESS ; } } else if ( state == State . STOPPED && ! forceIfStopped ) { LOG . debug ( "[{}] reconnectNow(false) while stopped, nothing to do" , logPrefix ) ; } else { assert state == State . SCHEDULED || ( state == State . STOPPED && forceIfStopped ) ; LOG . debug ( "[{}] Forcing next attempt now" , logPrefix ) ; if ( nextAttempt != null ) { nextAttempt . cancel ( true ) ; } try { onNextAttemptStarted ( reconnectionTask . call ( ) ) ; } catch ( Exception e ) { Loggers . warnWithException ( LOG , "[{}] Uncaught error while starting reconnection attempt" , logPrefix , e ) ; scheduleNextAttempt ( ) ; } } }
Forces a reconnection now without waiting for the next scheduled attempt .
35,182
private void onNextAttemptStarted ( CompletionStage < Boolean > futureOutcome ) { assert executor . inEventLoop ( ) ; state = State . ATTEMPT_IN_PROGRESS ; futureOutcome . whenCompleteAsync ( this :: onNextAttemptCompleted , executor ) . exceptionally ( UncaughtExceptions :: log ) ; }
the CompletableFuture to find out if that succeeded or not .
35,183
public static < T > T getCompleted ( CompletionStage < T > stage ) { CompletableFuture < T > future = stage . toCompletableFuture ( ) ; Preconditions . checkArgument ( future . isDone ( ) && ! future . isCompletedExceptionally ( ) ) ; try { return future . get ( ) ; } catch ( InterruptedException | ExecutionException e ) { throw new AssertionError ( "Unexpected error" , e ) ; } }
Get the result now when we know for sure that the future is complete .
35,184
public static Throwable getFailed ( CompletionStage < ? > stage ) { CompletableFuture < ? > future = stage . toCompletableFuture ( ) ; Preconditions . checkArgument ( future . isCompletedExceptionally ( ) ) ; try { future . get ( ) ; throw new AssertionError ( "future should be failed" ) ; } catch ( InterruptedException e ) { throw new AssertionError ( "Unexpected error" , e ) ; } catch ( ExecutionException e ) { return e . getCause ( ) ; } }
Get the error now when we know for sure that the future is failed .
35,185
private CompletionStage < Void > prepareOnOtherNode ( Node node ) { LOG . trace ( "[{}] Repreparing on {}" , logPrefix , node ) ; DriverChannel channel = session . getChannel ( node , logPrefix ) ; if ( channel == null ) { LOG . trace ( "[{}] Could not get a channel to reprepare on {}, skipping" , logPrefix , node ) ; return CompletableFuture . completedFuture ( null ) ; } else { ThrottledAdminRequestHandler handler = new ThrottledAdminRequestHandler ( channel , message , request . getCustomPayload ( ) , timeout , throttler , session . getMetricUpdater ( ) , logPrefix , message . toString ( ) ) ; return handler . start ( ) . handle ( ( result , error ) -> { if ( error == null ) { LOG . trace ( "[{}] Successfully reprepared on {}" , logPrefix , node ) ; } else { Loggers . warnWithException ( LOG , "[{}] Error while repreparing on {}" , node , logPrefix , error ) ; } return null ; } ) ; } }
blocking the preparation will be retried later on that node . Simply warn and move on .
35,186
private static void insertJsonColumn ( CqlSession session ) { JsonObject alice = Json . createObjectBuilder ( ) . add ( "name" , "alice" ) . add ( "age" , 30 ) . build ( ) ; JsonObject bob = Json . createObjectBuilder ( ) . add ( "name" , "bob" ) . add ( "age" , 35 ) . build ( ) ; Statement stmt = insertInto ( "examples" , "json_jsr353_column" ) . value ( "id" , literal ( 1 ) ) . value ( "json" , literal ( alice , session . getContext ( ) . getCodecRegistry ( ) ) ) . build ( ) ; session . execute ( stmt ) ; PreparedStatement pst = session . prepare ( insertInto ( "examples" , "json_jsr353_column" ) . value ( "id" , bindMarker ( "id" ) ) . value ( "json" , bindMarker ( "json" ) ) . build ( ) ) ; session . execute ( pst . bind ( ) . setInt ( "id" , 2 ) . set ( "json" , bob , JsonStructure . class ) ) ; }
Mapping a JSON object to a table column
35,187
public static void warnWithException ( Logger logger , String format , Object ... arguments ) { if ( logger . isDebugEnabled ( ) ) { logger . warn ( format , arguments ) ; } else { Object last = arguments [ arguments . length - 1 ] ; if ( last instanceof Throwable ) { Throwable t = ( Throwable ) last ; arguments [ arguments . length - 1 ] = t . getClass ( ) . getSimpleName ( ) + ": " + t . getMessage ( ) ; logger . warn ( format + " ({})" , arguments ) ; } else { logger . warn ( format , arguments ) ; } } }
Emits a warning log that includes an exception . If the current level is debug the full stack trace is included otherwise only the exception s message .
35,188
private void savePort ( DriverChannel channel ) { if ( port < 0 ) { SocketAddress address = channel . getEndPoint ( ) . resolve ( ) ; if ( address instanceof InetSocketAddress ) { port = ( ( InetSocketAddress ) address ) . getPort ( ) ; } } }
We save it the first time we get a control connection channel .
35,189
public Iterator < AdminRow > iterator ( ) { return new AbstractIterator < AdminRow > ( ) { protected AdminRow computeNext ( ) { List < ByteBuffer > rowData = data . poll ( ) ; return ( rowData == null ) ? endOfData ( ) : new AdminRow ( columnSpecs , rowData , protocolVersion ) ; } } ; }
This consumes the result s data and can be called only once .
35,190
protected TypeCodec < ? > createCodec ( GenericType < ? > javaType , boolean isJavaCovariant ) { TypeToken < ? > token = javaType . __getToken ( ) ; if ( List . class . isAssignableFrom ( token . getRawType ( ) ) && token . getType ( ) instanceof ParameterizedType ) { Type [ ] typeArguments = ( ( ParameterizedType ) token . getType ( ) ) . getActualTypeArguments ( ) ; GenericType < ? > elementType = GenericType . of ( typeArguments [ 0 ] ) ; TypeCodec < ? > elementCodec = codecFor ( elementType , isJavaCovariant ) ; return TypeCodecs . listOf ( elementCodec ) ; } else if ( Set . class . isAssignableFrom ( token . getRawType ( ) ) && token . getType ( ) instanceof ParameterizedType ) { Type [ ] typeArguments = ( ( ParameterizedType ) token . getType ( ) ) . getActualTypeArguments ( ) ; GenericType < ? > elementType = GenericType . of ( typeArguments [ 0 ] ) ; TypeCodec < ? > elementCodec = codecFor ( elementType , isJavaCovariant ) ; return TypeCodecs . setOf ( elementCodec ) ; } else if ( Map . class . isAssignableFrom ( token . getRawType ( ) ) && token . getType ( ) instanceof ParameterizedType ) { Type [ ] typeArguments = ( ( ParameterizedType ) token . getType ( ) ) . getActualTypeArguments ( ) ; GenericType < ? > keyType = GenericType . of ( typeArguments [ 0 ] ) ; GenericType < ? > valueType = GenericType . of ( typeArguments [ 1 ] ) ; TypeCodec < ? > keyCodec = codecFor ( keyType , isJavaCovariant ) ; TypeCodec < ? > valueCodec = codecFor ( valueType , isJavaCovariant ) ; return TypeCodecs . mapOf ( keyCodec , valueCodec ) ; } throw new CodecNotFoundException ( null , javaType ) ; }
Variant where the CQL type is unknown . Can be covariant if we come from a lookup by Java value .
35,191
protected TypeCodec < ? > createCodec ( DataType cqlType ) { if ( cqlType instanceof ListType ) { DataType elementType = ( ( ListType ) cqlType ) . getElementType ( ) ; TypeCodec < Object > elementCodec = codecFor ( elementType ) ; return TypeCodecs . listOf ( elementCodec ) ; } else if ( cqlType instanceof SetType ) { DataType elementType = ( ( SetType ) cqlType ) . getElementType ( ) ; TypeCodec < Object > elementCodec = codecFor ( elementType ) ; return TypeCodecs . setOf ( elementCodec ) ; } else if ( cqlType instanceof MapType ) { DataType keyType = ( ( MapType ) cqlType ) . getKeyType ( ) ; DataType valueType = ( ( MapType ) cqlType ) . getValueType ( ) ; TypeCodec < Object > keyCodec = codecFor ( keyType ) ; TypeCodec < Object > valueCodec = codecFor ( valueType ) ; return TypeCodecs . mapOf ( keyCodec , valueCodec ) ; } else if ( cqlType instanceof TupleType ) { return TypeCodecs . tupleOf ( ( TupleType ) cqlType ) ; } else if ( cqlType instanceof UserDefinedType ) { return TypeCodecs . udtOf ( ( UserDefinedType ) cqlType ) ; } else if ( cqlType instanceof CustomType ) { return TypeCodecs . custom ( cqlType ) ; } throw new CodecNotFoundException ( cqlType , null ) ; }
Variant where the Java type is unknown .
35,192
private static < DeclaredT , RuntimeT > TypeCodec < DeclaredT > uncheckedCast ( TypeCodec < RuntimeT > codec ) { @ SuppressWarnings ( "unchecked" ) TypeCodec < DeclaredT > result = ( TypeCodec < DeclaredT > ) codec ; return result ; }
We call this after validating the types so we know the cast will never fail .
35,193
protected long computeNext ( long last ) { long currentTick = clock . currentTimeMicros ( ) ; if ( last >= currentTick ) { maybeLog ( currentTick , last ) ; return last + 1 ; } return currentTick ; }
Compute the next timestamp given the current clock tick and the last timestamp returned .
35,194
public static int skipSpaces ( String toParse , int idx ) { while ( isBlank ( toParse . charAt ( idx ) ) && idx < toParse . length ( ) ) ++ idx ; return idx ; }
Returns the index of the first character in toParse from idx that is not a space .
35,195
public static int skipCQLValue ( String toParse , int idx ) { if ( idx >= toParse . length ( ) ) throw new IllegalArgumentException ( ) ; if ( isBlank ( toParse . charAt ( idx ) ) ) throw new IllegalArgumentException ( ) ; int cbrackets = 0 ; int sbrackets = 0 ; int parens = 0 ; boolean inString = false ; do { char c = toParse . charAt ( idx ) ; if ( inString ) { if ( c == '\'' ) { if ( idx + 1 < toParse . length ( ) && toParse . charAt ( idx + 1 ) == '\'' ) { ++ idx ; } else { inString = false ; if ( cbrackets == 0 && sbrackets == 0 && parens == 0 ) return idx + 1 ; } } } else if ( c == '\'' ) { inString = true ; } else if ( c == '{' ) { ++ cbrackets ; } else if ( c == '[' ) { ++ sbrackets ; } else if ( c == '(' ) { ++ parens ; } else if ( c == '}' ) { if ( cbrackets == 0 ) return idx ; -- cbrackets ; if ( cbrackets == 0 && sbrackets == 0 && parens == 0 ) return idx + 1 ; } else if ( c == ']' ) { if ( sbrackets == 0 ) return idx ; -- sbrackets ; if ( cbrackets == 0 && sbrackets == 0 && parens == 0 ) return idx + 1 ; } else if ( c == ')' ) { if ( parens == 0 ) return idx ; -- parens ; if ( cbrackets == 0 && sbrackets == 0 && parens == 0 ) return idx + 1 ; } else if ( isBlank ( c ) || ! isCqlIdentifierChar ( c ) ) { if ( cbrackets == 0 && sbrackets == 0 && parens == 0 ) return idx ; } } while ( ++ idx < toParse . length ( ) ) ; if ( inString || cbrackets != 0 || sbrackets != 0 || parens != 0 ) throw new IllegalArgumentException ( ) ; return idx ; }
Assuming that idx points to the beginning of a CQL value in toParse returns the index of the first character after this value .
35,196
public static int skipCQLId ( String toParse , int idx ) { if ( idx >= toParse . length ( ) ) throw new IllegalArgumentException ( ) ; char c = toParse . charAt ( idx ) ; if ( isCqlIdentifierChar ( c ) ) { while ( idx < toParse . length ( ) && isCqlIdentifierChar ( toParse . charAt ( idx ) ) ) idx ++ ; return idx ; } if ( c != '"' ) throw new IllegalArgumentException ( ) ; while ( ++ idx < toParse . length ( ) ) { c = toParse . charAt ( idx ) ; if ( c != '"' ) continue ; if ( idx + 1 < toParse . length ( ) && toParse . charAt ( idx + 1 ) == '\"' ) ++ idx ; else return idx + 1 ; } throw new IllegalArgumentException ( ) ; }
Assuming that idx points to the beginning of a CQL identifier in toParse returns the index of the first character after this identifier .
35,197
public < EventT > Object register ( Class < EventT > eventClass , Consumer < EventT > listener ) { LOG . debug ( "[{}] Registering {} for {}" , logPrefix , listener , eventClass ) ; listeners . put ( eventClass , listener ) ; return listener ; }
Registers a listener for an event type .
35,198
public < EventT > boolean unregister ( Object key , Class < EventT > eventClass ) { LOG . debug ( "[{}] Unregistering {} for {}" , logPrefix , key , eventClass ) ; return listeners . remove ( eventClass , key ) ; }
Unregisters a listener .
35,199
public void fire ( Object event ) { LOG . debug ( "[{}] Firing an instance of {}: {}" , logPrefix , event . getClass ( ) , event ) ; Class < ? > eventClass = event . getClass ( ) ; for ( Consumer < ? > l : listeners . get ( eventClass ) ) { @ SuppressWarnings ( "unchecked" ) Consumer < Object > listener = ( Consumer < Object > ) l ; LOG . debug ( "[{}] Notifying {} of {}" , logPrefix , listener , event ) ; listener . accept ( event ) ; } }
Sends an event that will notify any registered listener for that class .