idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
158,500
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
744
7
158,501
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
489
10
158,502
private void doMain ( ) throws Exception { // Start the process this . start ( ) ; while ( true ) { // look for some terminator // attempt to read off queue // process message // TODO : Make something here, maybe watch for files? try { Thread . sleep ( 5 ) ; } catch ( Exception e ) { log . info ( "shutting down" , e ) ...
The real main method .
96
5
158,503
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
188
22
158,504
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 .
126
7
158,505
public void executeStandalone ( JmxProcess process ) throws Exception { this . masterServersList = process . getServers ( ) ; this . serverScheduler . start ( ) ; this . processServersIntoJobs ( ) ; // Sleep for 10 seconds to wait for jobs to complete. // There should be a better way, but it seems that way isn't workin...
Handy method which runs the JmxProcess
106
9
158,506
private void processFilesIntoServers ( ) throws LifecycleException { // Shutdown the outputwriters and clear the current server list - this gives us a clean // start when re-reading the json config files try { this . stopWriterAndClearMasterServerList ( ) ; } catch ( Exception e ) { log . error ( "Error while clearing ...
Processes all the json files and manages the dedup process
131
12
158,507
private boolean isProcessConfigFile ( File file ) { if ( this . configuration . getProcessConfigDirOrFile ( ) . isFile ( ) ) { return file . equals ( this . configuration . getProcessConfigDirOrFile ( ) ) ; } // If the file doesn't exist anymore, treat it as a regular file (to handle file deletion events) if ( file . e...
Are we a file and a JSON or YAML file?
157
13
158,508
@ Override @ JsonIgnore 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 .
54
16
158,509
@ Override public void validateSetup ( Server server , Query query ) throws ValidationException { // Check if we've already created a logger for this file. If so, use it. Logger logger ; if ( loggers . containsKey ( outputFile ) ) { logger = getLogger ( outputFile ) ; } else { // need to create a logger try { logger = ...
Creates the logging
141
4
158,510
@ Override 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 .
42
26
158,511
private AmazonCloudWatchClient createCloudWatchClient ( ) { AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient ( new InstanceProfileCredentialsProvider ( ) ) ; cloudWatchClient . setRegion ( checkNotNull ( Regions . getCurrentRegion ( ) , "Problems getting AWS metadata" ) ) ; return cloudWatchClient ;...
Configuring the CloudWatch client .
73
7
158,512
@ Override 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...
Format the name for the given result .
99
8
158,513
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 .
190
10
158,514
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 .
171
30
158,515
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 ) ; co...
Executes the rrdtool update command .
126
9
158,516
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 . val...
Calls out to the rrdtool binary with the create command .
260
14
158,517
private void checkErrorStream ( Process process ) throws Exception { // rrdtool should use platform encoding (unless you did something // very strange with your installation of rrdtool). So let's be // explicit and use the presumed correct encoding to read errors. try ( InputStream is = process . getErrorStream ( ) ; I...
Check to see if there was an error processing an rrdtool command
174
14
158,518
private String getRraStr ( ArcDef def ) { return "RRA:" + def . getConsolFun ( ) + ":" + def . getXff ( ) + ":" + def . getSteps ( ) + ":" + def . getRows ( ) ; }
Generate a RRA line for rrdtool
61
10
158,519
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 .
61
14
158,520
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 .
145
10
158,521
private static void describeClassTree ( Class < ? > inputClass , Set < Class < ? > > setOfClasses ) { // can't map null class if ( inputClass == null ) { return ; } // don't further analyze a class that has been analyzed already if ( Object . class . equals ( inputClass ) || setOfClasses . contains ( inputClass ) ) { r...
Recursive handler for describing the set of classes while using the setOfClasses parameter as a collector
162
20
158,522
private static Set < Class < ? > > describeClassTree ( Class < ? > inputClass ) { if ( inputClass == null ) { return Collections . emptySet ( ) ; } // create result collector Set < Class < ? > > classes = Sets . newLinkedHashSet ( ) ; // describe tree describeClassTree ( inputClass , classes ) ; return classes ; }
Given an object return the set of classes that it extends or implements .
78
14
158,523
public void usage ( StringBuilder out , String indent ) { if ( commander . getDescriptions ( ) == null ) { commander . createDescriptions ( ) ; } boolean hasCommands = ! commander . getCommands ( ) . isEmpty ( ) ; boolean hasOptions = ! commander . getDescriptions ( ) . isEmpty ( ) ; // Indentation constants final int ...
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 .
340
45
158,524
@ 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 .
192
8
158,525
public final void addObject ( Object object ) { if ( object instanceof Iterable ) { // Iterable for ( Object o : ( Iterable < ? > ) object ) { objects . add ( o ) ; } } else if ( object . getClass ( ) . isArray ( ) ) { // Array for ( Object o : ( Object [ ] ) object ) { objects . add ( o ) ; } } else { // Single object...
declared final since this is invoked from constructors
100
10
158,526
public void parse ( String ... args ) { try { parse ( true /* validate */ , args ) ; } catch ( ParameterException ex ) { ex . setJCommander ( this ) ; throw ex ; } }
Parse and validate the command line parameters .
45
9
158,527
private void validateOptions ( ) { // No validation if we found a help parameter if ( helpWasSpecified ) { return ; } if ( ! requiredFields . isEmpty ( ) ) { List < String > missingFields = new ArrayList <> ( ) ; for ( ParameterDescription pd : requiredFields . values ( ) ) { missingFields . add ( "[" + Strings . join ...
Make sure that all the required parameters have received a value .
416
12
158,528
private List < String > readFile ( String fileName ) { List < String > result = Lists . newArrayList ( ) ; try ( BufferedReader bufRead = Files . newBufferedReader ( Paths . get ( fileName ) , options . atFileCharset ) ) { String line ; // Read through file one line at time. Print line # and line while ( ( line = bufRe...
Reads the file specified by filename and returns the file content as a string . End of lines are replaced by a space .
176
25
158,529
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 .
72
10
158,530
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 .
43
15
158,531
public void setProgramName ( String name , String ... aliases ) { programName = new ProgramName ( name , Arrays . asList ( aliases ) ) ; }
Set the program name
34
4
158,532
public void addConverterFactory ( final IStringConverterFactory converterFactory ) { addConverterInstanceFactory ( new IStringConverterInstanceFactory ( ) { @ SuppressWarnings ( "unchecked" ) @ Override public IStringConverter < ? > getConverterInstance ( Parameter parameter , Class < ? > forType , String optionName ) ...
Adds a factory to lookup string converters . The added factory is used prior to previously added factories .
204
20
158,533
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 ) ; /* * Register aliases...
Add a command object and its aliases .
278
8
158,534
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
317
11
158,535
public void drawHeader ( RecyclerView recyclerView , Canvas canvas , View header , Rect offset ) { canvas . save ( ) ; if ( recyclerView . getLayoutManager ( ) . getClipToPadding ( ) ) { // Clip drawing of headers to the padding of the RecyclerView. Avoids drawing in the padding initClipRectForHeader ( mTempRect , recy...
Draws a header to a canvas offsetting by some x and y amount
129
15
158,536
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 .
62
20
158,537
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 .
77
8
158,538
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 .
43
10
158,539
public List < String > getVariableNames ( ) { return variables . asList ( ) . stream ( ) // . map ( TemplateVariable :: getName ) // . collect ( Collectors . toList ( ) ) ; }
Returns the names of the variables discovered .
46
8
158,540
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 .
53
12
158,541
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 .
70
7
158,542
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 .
72
8
158,543
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 .
32
14
158,544
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 .
133
20
158,545
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 .
76
9
158,546
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 .
113
11
158,547
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 .
89
12
158,548
@ JsonIgnore 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 .
46
8
158,549
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...
Adds the given value as embedded one .
116
8
158,550
@ Nullable 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 . da...
Generate an object used the deserialized properties and the provided type from the deserializer .
128
20
158,551
@ 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 .
53
8
158,552
private static void insertJsonColumn ( CqlSession session ) { User alice = new User ( "alice" , 30 ) ; User bob = new User ( "bob" , 35 ) ; // Build and execute a simple statement Statement stmt = insertInto ( "examples" , "json_jackson_column" ) . value ( "id" , literal ( 1 ) ) // the User object will be converted int...
Mapping a User instance to a table column
278
9
158,553
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" ) ; /...
Retrieving User instances from a table column
194
8
158,554
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 .
345
12
158,555
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 .
452
11
158,556
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 .
295
14
158,557
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 .
73
14
158,558
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 .
111
15
158,559
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 .
120
15
158,560
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 .
253
18
158,561
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 ( ) ; // Build and execute a simple statemen...
Mapping a JSON object to a table column
368
9
158,562
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 .
152
29
158,563
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 .
64
13
158,564
@ NonNull @ Override public Iterator < AdminRow > iterator ( ) { return new AbstractIterator < AdminRow > ( ) { @ Override 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 .
86
13
158,565
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 .
487
24
158,566
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 .
364
9
158,567
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 .
69
17
158,568
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 .
54
16
158,569
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 .
55
20
158,570
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 .
530
28
158,571
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 .
224
28
158,572
public < EventT > Object register ( Class < EventT > eventClass , Consumer < EventT > listener ) { LOG . debug ( "[{}] Registering {} for {}" , logPrefix , listener , eventClass ) ; listeners . put ( eventClass , listener ) ; // The reason for the key mechanism is that this will often be used with method references, //...
Registers a listener for an event type .
120
9
158,573
public < EventT > boolean unregister ( Object key , Class < EventT > eventClass ) { LOG . debug ( "[{}] Unregistering {} for {}" , logPrefix , key , eventClass ) ; return listeners . remove ( eventClass , key ) ; }
Unregisters a listener .
59
6
158,574
public void fire ( Object event ) { LOG . debug ( "[{}] Firing an instance of {}: {}" , logPrefix , event . getClass ( ) , event ) ; // if the exact match thing gets too cumbersome, we can reconsider, but I'd like to avoid // scanning all the keys with instanceof checks. Class < ? > eventClass = event . getClass ( ) ; ...
Sends an event that will notify any registered listener for that class .
160
14
158,575
public static boolean needsDoubleQuotes ( String s ) { // this method should only be called for C*-provided identifiers, // so we expect it to be non-null and non-empty. assert s != null && ! s . isEmpty ( ) ; char c = s . charAt ( 0 ) ; if ( ! ( c >= 97 && c <= 122 ) ) // a-z return true ; for ( int i = 1 ; i < s . le...
Whether a string needs double quotes to be a valid CQL identifier .
173
14
158,576
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 < ' ' && ( i != 0 || c != ' ' ) ) || c > ' ' ) 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 .
100
31
158,577
@ NonNull 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 .
55
17
158,578
public Map < String , String > build ( ) { NullAllowingImmutableMap . Builder < String , String > builder = NullAllowingImmutableMap . builder ( 3 ) ; // add compression (if configured) and driver name and version String compressionAlgorithm = context . getCompressor ( ) . algorithm ( ) ; if ( compressionAlgorithm != n...
Builds a map of options to send in a Startup message .
152
13
158,579
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 .
47
15
158,580
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 .
598
13
158,581
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" ; // headings System . out . printf ( format , "sensor_id" , "date" , "timestamp" , "value" )...
Displays the results on the console .
194
8
158,582
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 .
160
41
158,583
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 .
67
11
158,584
public void querySchema ( ) { ResultSet results = session . execute ( "SELECT * FROM simplex.playlists " + "WHERE id = 2cc9ccb7-6221-4ccb-8387-f22b6a1b354d;" ) ; System . out . printf ( "%-30s\t%-20s\t%-20s%n" , "title" , "album" , "artist" ) ; System . out . println ( "-------------------------------+-----------------...
Queries and displays data .
179
6
158,585
public static Class < ? > loadClass ( ClassLoader classLoader , String className ) { try { // If input classLoader is null, use current thread's ClassLoader, if that is null, use // default (calling class') ClassLoader. ClassLoader cl = classLoader != null ? classLoader : Thread . currentThread ( ) . getContextClassLoa...
Loads a class by name .
127
7
158,586
public static < ComponentT > Optional < ComponentT > buildFromConfig ( InternalDriverContext context , DriverOption classNameOption , Class < ComponentT > expectedSuperType , String ... defaultPackages ) { return buildFromConfig ( context , null , classNameOption , expectedSuperType , defaultPackages ) ; }
Tries to create an instance of a class given an option defined in the driver configuration .
65
18
158,587
public static < ComponentT > Map < String , ComponentT > buildFromConfigProfiles ( InternalDriverContext context , DriverOption rootOption , Class < ComponentT > expectedSuperType , String ... defaultPackages ) { // Find out how many distinct configurations we have ListMultimap < Object , String > profilesByConfig = Mu...
Tries to create multiple instances of a class given options defined in the driver configuration and possibly overridden in profiles .
324
23
158,588
public Map < CqlIdentifier , UserDefinedType > parse ( Collection < AdminRow > typeRows , CqlIdentifier keyspaceId ) { if ( typeRows . isEmpty ( ) ) { return Collections . emptyMap ( ) ; } else { Map < CqlIdentifier , UserDefinedType > types = new LinkedHashMap <> ( ) ; for ( AdminRow row : topologicalSort ( typeRows ,...
Contrary to other element parsers this one processes all the types of a keyspace in one go . UDTs can depend on each other but the system table returns them in alphabetical order . In order to properly build the definitions we need to do a topological sort of the rows first so that each type is parsed after its depende...
146
69
158,589
public CompletionStage < Void > init ( boolean listenToClusterEvents , boolean reconnectOnFailure , boolean useInitialReconnectionSchedule ) { RunOrSchedule . on ( adminExecutor , ( ) -> singleThreaded . init ( listenToClusterEvents , reconnectOnFailure , useInitialReconnectionSchedule ) ) ; return singleThreaded . ini...
Initializes the control connection . If it is already initialized this is a no - op and all parameters are ignored .
82
23
158,590
public CompletionStage < Void > setKeyspace ( CqlIdentifier newKeyspaceName ) { return RunOrSchedule . on ( adminExecutor , ( ) -> singleThreaded . setKeyspace ( newKeyspaceName ) ) ; }
Changes the keyspace name on all the channels in this pool .
52
13
158,591
public List < String > getPreReleaseLabels ( ) { return preReleases == null ? null : Collections . unmodifiableList ( Arrays . asList ( preReleases ) ) ; }
The pre - release labels if relevant i . e . label1 and label2 in X . Y . Z - label1 - lable2 .
42
30
158,592
private void processNodeStateEvent ( NodeStateEvent event ) { switch ( stateRef . get ( ) ) { case BEFORE_INIT : case DURING_INIT : throw new AssertionError ( "Filter should not be marked ready until LBP init" ) ; case CLOSING : return ; // ignore case RUNNING : for ( LoadBalancingPolicy policy : policies ) { if ( even...
once it has gone through the filter
223
7
158,593
@ VisibleForTesting static String reverse ( InetAddress address ) { byte [ ] bytes = address . getAddress ( ) ; if ( bytes . length == 4 ) return reverseIpv4 ( bytes ) ; else return reverseIpv6 ( bytes ) ; }
Builds the reversed domain name in the ARPA domain to perform the reverse lookup
57
16
158,594
public int firstIndexOf ( CqlIdentifier id ) { Integer index = byId . get ( id ) ; return ( index == null ) ? - 1 : index ; }
Returns the first occurrence of a given identifier or - 1 if it s not in the list .
37
19
158,595
private static void insertWithCoreApi ( CqlSession session ) { // Bind in a simple statement: session . execute ( SimpleStatement . newInstance ( "INSERT INTO examples.querybuilder_json JSON ?" , "{ \"id\": 1, \"name\": \"Mouse\", \"specs\": { \"color\": \"silver\" } }" ) ) ; // Bind in a prepared statement: // (subseq...
Demonstrates data insertion with the core API i . e . providing the full query strings .
250
19
158,596
private static void selectWithCoreApi ( CqlSession session ) { // Reading the whole row as a JSON object: Row row = session . execute ( SimpleStatement . newInstance ( "SELECT JSON * FROM examples.querybuilder_json WHERE id = ?" , 1 ) ) . one ( ) ; assert row != null ; System . out . printf ( "Entry #1 as JSON: %s%n" ,...
Demonstrates data retrieval with the core API i . e . providing the full query strings .
208
19
158,597
public UserDefinedTypeBuilder withField ( CqlIdentifier name , DataType type ) { fieldNames . add ( name ) ; fieldTypes . add ( type ) ; return this ; }
Adds a new field . The fields in the resulting type will be in the order of the calls to this method .
40
23
158,598
public DefaultMetadata withNodes ( Map < UUID , Node > newNodes , boolean tokenMapEnabled , boolean tokensChanged , TokenFactory tokenFactory , InternalDriverContext context ) { // Force a rebuild if at least one node has different tokens, or there are new or removed nodes. boolean forceFullRebuild = tokensChanged || !...
Refreshes the current metadata with the given list of nodes .
130
13
158,599
private void sendRequest ( Node retriedNode , Queue < Node > queryPlan , int currentExecutionIndex , int retryCount , boolean scheduleNextExecution ) { if ( result . isDone ( ) ) { return ; } Node node = retriedNode ; DriverChannel channel = null ; if ( node == null || ( channel = session . getChannel ( node , logPrefi...
Sends the request to the next available node .
302
10