idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
158,800
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
158,801
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 ...
Adds a key to the StringBuilder
158,802
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 + ",...
Parse and validate settings .
158,803
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 ( ) ) ; GMetr...
Send query result values to Ganglia .
158,804
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 . pa...
Guess the Ganglia gmetric type to use for a given object .
158,805
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 . val...
Gets a Boolean value for the key returning the default value given if not specified or not a valid boolean value .
158,806
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...
Gets an Integer value for the key returning the default value given if not specified or not a valid numeric value .
158,807
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 .
158,808
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...
Gets an int value for the setting returning the default value if not specified .
158,809
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 ( "...
Sets velocity up to load resources from a list of paths .
158,810
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 ,...
Uses jackson to load json configuration from a File into a full object tree representation of that json .
158,811
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 .
158,812
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 .
158,813
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 ( sanitiz...
Format the result string given the class name and attribute name of the source value the timestamp and the value .
158,814
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 ( ) ; formatResu...
Process a single metric from the given JMX query result with the specified value .
158,815
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 . w...
Take query results make a JSON String
158,816
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 the formatted results to the gateway URL over HTTP
158,817
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 .
158,818
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 . get...
Shut down the output writers and clear the master server list Used both during shutdown and when re - reading config files
158,819
private void startupWatchdir ( ) throws Exception { File dirToWatch ; if ( this . configuration . getProcessConfigDirOrFile ( ) . isFile ( ) ) { dirToWatch = new File ( FilenameUtils . getFullPath ( this . configuration . getProcessConfigDirOrFile ( ) . getAbsolutePath ( ) ) ) ; } else { dirToWatch = this . configurati...
Startup the watchdir service .
158,820
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
158,821
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 = configurationParse...
Processes all the json files and manages the dedup process
158,822
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 ( ) ;...
Are we a file and a JSON or YAML file?
158,823
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 .
158,824
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 Vali...
Creates the logging
158,825
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 .
158,826
private AmazonCloudWatchClient createCloudWatchClient ( ) { AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient ( new InstanceProfileCredentialsProvider ( ) ) ; cloudWatchClient . setRegion ( checkNotNull ( Regions . getCurrentRegion ( ) , "Problems getting AWS metadata" ) ) ; return cloudWatchClient ;...
Configuring the CloudWatch client .
158,827
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 resu...
Format the name for the given result .
158,828
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 = TypeNameV...
Populate the context with values from the result .
158,829
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 (...
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 .
158,830
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 ) ; c...
Executes the rrdtool update command .
158,831
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 . va...
Calls out to the rrdtool binary with the create command .
158,832
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 ; whi...
Check to see if there was an error processing an rrdtool command
158,833
private String getRraStr ( ArcDef def ) { return "RRA:" + def . getConsolFun ( ) + ":" + def . getXff ( ) + ":" + def . getSteps ( ) + ":" + def . getRows ( ) ; }
Generate a RRA line for rrdtool
158,834
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 .
158,835
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 [ ] { ...
Add the given URL to the system class loader .
158,836
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 . getSuperc...
Recursive handler for describing the set of classes while using the setOfClasses parameter as a collector
158,837
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 .
158,838
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 ; f...
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 .
158,839
@ 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 ( ) , ...
Find the resource bundle in the annotations .
158,840
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
158,841
public void parse ( String ... args ) { try { parse ( true , args ) ; } catch ( ParameterException ex ) { ex . setJCommander ( this ) ; throw ex ; } }
Parse and validate the command line parameters .
158,842
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 ( ) )...
Make sure that all the required parameters have received a value .
158,843
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 &&...
Reads the file specified by filename and returns the file content as a string . End of lines are replaced by a space .
158,844
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 .
158,845
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 .
158,846
public void setProgramName ( String name , String ... aliases ) { programName = new ProgramName ( name , Arrays . asList ( aliases ) ) ; }
Set the program name
158,847
public void addConverterFactory ( final IStringConverterFactory converterFactory ) { addConverterInstanceFactory ( new IStringConverterInstanceFactory ( ) { @ SuppressWarnings ( "unchecked" ) public IStringConverter < ? > getConverterInstance ( Parameter parameter , Class < ? > forType , String optionName ) { final Cla...
Adds a factory to lookup string converters . The added factory is used prior to previously added factories .
158,848
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 ...
Add a command object and its aliases .
158,849
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 . getChildAdapter...
Determines if an item is obscured by a header
158,850
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 ...
Draws a header to a canvas offsetting by some x and y amount
158,851
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 .
158,852
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 .
158,853
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 .
158,854
public List < String > getVariableNames ( ) { return variables . asList ( ) . stream ( ) . map ( TemplateVariable :: getName ) . collect ( Collectors . toList ( ) ) ; }
Returns the names of the variables discovered .
158,855
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 .
158,856
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 .
158,857
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 .
158,858
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 .
158,859
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 ...
Verify that the resource s self link and the affordance s URI have the same relative path .
158,860
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 .
158,861
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 . pa...
Add one header to the HttpHeaders collection .
158,862
private static List < UberData > doExtractLinksAndContent ( Object item ) { if ( item instanceof EntityModel ) { return extractLinksAndContent ( ( EntityModel < ? > ) item ) ; } if ( item instanceof RepresentationModel ) { return extractLinksAndContent ( ( RepresentationModel < ? > ) item ) ; } return extractLinksAndCo...
Extract links and content from an object of any type .
158,863
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 .
158,864
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 , valu...
Adds the given value as embedded one .
158,865
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 ( ...
Generate an object used the deserialized properties and the provided type from the deserializer .
158,866
@ 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 .
158,867
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...
Mapping a User instance to a table column
158,868
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" ) ; U...
Retrieving User instances from a table column
158,869
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 "AUTHENTICAT...
Formats a message opcode for logs and error messages .
158,870
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 Protoco...
Formats an error code for logs and error messages .
158,871
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_CUR...
Forces a reconnection now without waiting for the next scheduled attempt .
158,872
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 .
158,873
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...
Get the result now when we know for sure that the future is complete .
158,874
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 ( InterruptedExceptio...
Get the error now when we know for sure that the future is failed .
158,875
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 ) ; ...
blocking the preparation will be retried later on that node . Simply warn and move on .
158,876
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 ( "example...
Mapping a JSON object to a table column
158,877
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 [ argu...
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 .
158,878
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 .
158,879
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 .
158,880
protected TypeCodec < ? > createCodec ( GenericType < ? > javaType , boolean isJavaCovariant ) { TypeToken < ? > token = javaType . __getToken ( ) ; if ( List . class . isAssignableFrom ( token . getRawType ( ) ) && token . getType ( ) instanceof ParameterizedType ) { Type [ ] typeArguments = ( ( ParameterizedType ) to...
Variant where the CQL type is unknown . Can be covariant if we come from a lookup by Java value .
158,881
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 ) {...
Variant where the Java type is unknown .
158,882
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 .
158,883
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 .
158,884
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 .
158,885
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 =...
Assuming that idx points to the beginning of a CQL value in toParse returns the index of the first character after this value .
158,886
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 ; } i...
Assuming that idx points to the beginning of a CQL identifier in toParse returns the index of the first character after this identifier .
158,887
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 .
158,888
public < EventT > boolean unregister ( Object key , Class < EventT > eventClass ) { LOG . debug ( "[{}] Unregistering {} for {}" , logPrefix , key , eventClass ) ; return listeners . remove ( eventClass , key ) ; }
Unregisters a listener .
158,889
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 < ...
Sends an event that will notify any registered listener for that class .
158,890
public static boolean needsDoubleQuotes ( String s ) { assert s != null && ! s . isEmpty ( ) ; char c = s . charAt ( 0 ) ; if ( ! ( c >= 97 && c <= 122 ) ) return true ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) { c = s . charAt ( i ) ; if ( ! ( ( c >= 48 && c <= 57 ) || ( c == 95 ) || ( c >= 97 && c <= 122 ) ) ) {...
Whether a string needs double quotes to be a valid CQL identifier .
158,891
public static boolean isLongLiteral ( String str ) { if ( str == null || str . isEmpty ( ) ) return false ; char [ ] chars = str . toCharArray ( ) ; for ( int i = 0 ; i < chars . length ; i ++ ) { char c = chars [ i ] ; if ( ( c < '0' && ( i != 0 || c != '-' ) ) || c > '9' ) return false ; } return true ; }
Check whether the given string corresponds to a valid CQL long literal . Long literals are composed solely by digits but can have an optional leading minus sign .
158,892
public String asCql ( boolean pretty ) { if ( pretty ) { return Strings . needsDoubleQuotes ( internal ) ? Strings . doubleQuote ( internal ) : internal ; } else { return Strings . doubleQuote ( internal ) ; } }
Returns the identifier in a format appropriate for concatenation in a CQL query .
158,893
public Map < String , String > build ( ) { NullAllowingImmutableMap . Builder < String , String > builder = NullAllowingImmutableMap . builder ( 3 ) ; String compressionAlgorithm = context . getCompressor ( ) . algorithm ( ) ; if ( compressionAlgorithm != null && ! compressionAlgorithm . trim ( ) . isEmpty ( ) ) { buil...
Builds a map of options to send in a Startup message .
158,894
private void connect ( ) { session = CqlSession . builder ( ) . build ( ) ; System . out . printf ( "Connected to session: %s%n" , session . getName ( ) ) ; }
Initiates a connection to the session specified by the application . conf .
158,895
private void write ( ConsistencyLevel cl , int retryCount ) { System . out . printf ( "Writing at %s (retry count: %d)%n" , cl , retryCount ) ; BatchStatement batch = BatchStatement . newInstance ( UNLOGGED ) . add ( SimpleStatement . newInstance ( "INSERT INTO downgrading.sensor_data " + "(sensor_id, date, timestamp, ...
Inserts data retrying if necessary with a downgraded CL .
158,896
private ResultSet read ( ConsistencyLevel cl , int retryCount ) { System . out . printf ( "Reading at %s (retry count: %d)%n" , cl , retryCount ) ; Statement stmt = SimpleStatement . newInstance ( "SELECT sensor_id, date, timestamp, value " + "FROM downgrading.sensor_data " + "WHERE " + "sensor_id = 756716f7-2e54-4715-...
Queries data retrying if necessary with a downgraded CL .
158,897
private void display ( ResultSet rows ) { final int width1 = 38 ; final int width2 = 12 ; final int width3 = 30 ; final int width4 = 21 ; String format = "%-" + width1 + "s%-" + width2 + "s%-" + width3 + "s%-" + width4 + "s%n" ; System . out . printf ( format , "sensor_id" , "date" , "timestamp" , "value" ) ; drawLine ...
Displays the results on the console .
158,898
private static ConsistencyLevel downgrade ( ConsistencyLevel current , int acknowledgements , DriverException original ) { if ( acknowledgements >= 3 ) { return DefaultConsistencyLevel . THREE ; } if ( acknowledgements == 2 ) { return DefaultConsistencyLevel . TWO ; } if ( acknowledgements == 1 ) { return DefaultConsis...
Downgrades the current consistency level to the highest level that is likely to succeed given the number of acknowledgements received . Rethrows the original exception if the current consistency level cannot be downgraded any further .
158,899
private static void drawLine ( int ... widths ) { for ( int width : widths ) { for ( int i = 1 ; i < width ; i ++ ) { System . out . print ( '-' ) ; } System . out . print ( '+' ) ; } System . out . println ( ) ; }
Draws a line to isolate headings from rows .