private String getGatewayMessage ( final List < Result > results ) throws IOException { int valueCount = 0 ; Writer writer = new StringWriter ( ) ; JsonGenerator g = jsonFactory . createGenerator ( writer ) ; g . writeStartObject ( ) ; g . writeNumberField ( "timestamp" , System . currentTimeMillis ( ) / 1000 ) ; g . writeNumberField ( "proto_version" , STACKDRIVER_PROTOCOL_VERSION ) ; g . writeArrayFieldStart ( "data" ) ; List < String > typeNames = this . getTypeNames ( ) ; for ( Result metric : results ) { if ( isNumeric ( metric . getValue ( ) ) ) { // we have a numeric value, write a value into the message StringBuilder nameBuilder = new StringBuilder ( ) ; // put the prefix if set if ( this . prefix != null ) { nameBuilder . append ( prefix ) ; nameBuilder . append ( "." ) ; } // put the class name or its alias if available if ( ! metric . getKeyAlias ( ) . isEmpty ( ) ) { nameBuilder . append ( metric . getKeyAlias ( ) ) ; } else { nameBuilder . append ( metric . getClassName ( ) ) ; } // Wildcard "typeNames" substitution String typeName = com . googlecode . jmxtrans . model . naming . StringUtils . cleanupStr ( TypeNameValuesStringBuilder . getDefaultBuilder ( ) . build ( typeNames , metric . getTypeName ( ) ) ) ; if ( typeName != null && typeName . length ( ) > 0 ) { nameBuilder . append ( "." ) ; nameBuilder . append ( typeName ) ; } // add the attribute name nameBuilder . append ( "." ) ; nameBuilder . append ( KeyUtils . getValueKey ( metric ) ) ; // check for Float/Double NaN since these will cause the message validation to fail if ( metric . getValue ( ) instanceof Float && ( ( Float ) metric . getValue ( ) ) . isNaN ( ) ) { logger . info ( "Metric value for " + nameBuilder . toString ( ) + " is NaN, skipping" ) ; continue ; } if ( metric . getValue ( ) instanceof Double && ( ( Double ) metric . getValue ( ) ) . isNaN ( ) ) { logger . info ( "Metric value for " + nameBuilder . toString ( ) + " is NaN, skipping" ) ; continue ; } valueCount ++ ; g . writeStartObject ( ) ; g . writeStringField ( "name" , nameBuilder . toString ( ) ) ; g . writeNumberField ( "value" , Double . valueOf ( metric . getValue ( ) . toString ( ) ) ) ; // if the metric is attached to an instance, include that in the message if ( instanceId != null && ! instanceId . isEmpty ( ) ) { g . writeStringField ( "instance" , instanceId ) ; } g . writeNumberField ( "collected_at" , metric . getEpoch ( ) / 1000 ) ; g . writeEndObject ( ) ; } } g . writeEndArray ( ) ; g . writeEndObject ( ) ; g . flush ( ) ; g . close ( ) ; // return the message if there are any values to report if ( valueCount > 0 ) { return writer . toString ( ) ; } else { return null ; } }
Take query results make a JSON String