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 ) { DatagramPack... | 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 ( "... | 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 . en... | 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 , p... | 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 )... | 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 ( ... | 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 ... | 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 + ",... | 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 ( ) ) ; GMetr... | 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 . pa... | 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 . val... | 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... | 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... | 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 ( "... | 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 ,... | 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 ( sanitiz... | 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 ( ) ; formatResu... | 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 . w... | 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 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 . get... | 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 . configurati... | 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 = configurationParse... | 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 ( ) ;... | 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 Vali... | 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 resu... | 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 = TypeNameV... | 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 (... | 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 ) ; c... | 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 . va... | 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 ; whi... | 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 [ ] { ... | 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 . getSuperc... | 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 ; 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 . |
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 ( ) , ... | 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 ( ) )... | 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 &&... | 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 Cla... | 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 ... | 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 . getChildAdapter... | 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 ... | 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 ... | 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 . pa... | 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 extractLinksAndCo... | 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 , valu... | 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 ( ... | 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... | 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" ) ; U... | 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 "AUTHENTICAT... | 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 Protoco... | 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_CUR... | 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... | 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 ( InterruptedExceptio... | 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 ) ; ... | 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 ( "example... | 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 [ 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 . |
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 ) to... | 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 ) {... | 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 =... | 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 ; } i... | 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 < ... | Sends an event that will notify any registered listener for that class . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.