public static JsonGenerator createJsonGenerator(Writer w) throws JsonException { try { return jf.createJsonGenerator(w); } catch (IOException ex) { throw new JsonException(ex); } }
public static JsonGenerator createJsonGenerator(OutputStream os) throws JsonException { try { return jf.createJsonGenerator(os, JsonEncoding.UTF8); } catch (IOException ex) { throw new JsonException(ex); } }
@Test public void testSerialization() throws IOException, ClassNotFoundException { Condition cond = new Condition(); Set<UUID> ids = new HashSet<>(); ids.add(UUID.randomUUID()); ids.add(UUID.randomUUID()); cond.inPortIds = ids; cond.portGroup = UUID.randomUUID(); cond.tpSrc = new Range<>(40000, 41000); cond.tpSrcInv = false; cond.tpDst = new Range<>(42000, 43000); cond.tpDstInv = true; cond.etherType = 0x86DD; ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStream out = new BufferedOutputStream(bos); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(new OutputStreamWriter(out)); jsonGenerator.writeObject(cond); out.close(); byte[] data = bos.toByteArray(); ByteArrayInputStream bis = new ByteArrayInputStream(data); InputStream in = new BufferedInputStream(bis); JsonParser jsonParser = jsonFactory.createJsonParser(new InputStreamReader(in)); Condition c = jsonParser.readValueAs(Condition.class); in.close(); Assert.assertTrue(cond.equals(c)); }
@Override public void onEvalStart() { super.onEvalStart(); initalizeData(); try { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a")); mapper.configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true); mapper.configure(SerializationConfig.Feature.WRAP_EXCEPTIONS, true); mapper.configure(SerializationConfig.Feature.WRITE_EMPTY_JSON_ARRAYS, false); mapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, true); SimpleModule module = new SimpleModule("DataProxy", new Version(1, 0, 0, null)); module.addSerializer(DataProxy.class, new DataProxySerializer(DataProxy.class)); mapper.registerModule(module); JsonFactory jsonFactory = mapper.getJsonFactory(); writer = jsonFactory.createJsonGenerator(context.getWriter()); writer.setPrettyPrinter(new DefaultPrettyPrinter()); writer.writeStartObject(); } catch (IOException ex) { throw new OseeCoreException(ex); } }
public static void toJson(Object pojo, Writer writer, boolean prettyPrint) throws JsonMappingException, JsonGenerationException, IOException { JsonGenerator jg = jf.createJsonGenerator(writer); if (prettyPrint) { jg.useDefaultPrettyPrinter(); } m.writeValue(jg, pojo); }
private String formatJson(Object data) { try { final StringWriter result = new StringWriter(); jsonFactory.createJsonGenerator(result).writeObject(data); return result.toString(); } catch (IOException e) { throw new RuntimeException("error formatting json", e); } }
/** 将对象转换成json */ public static String toJson(Object pojo) { StringWriter sw = new StringWriter(); try { JsonGenerator jg = jf.createJsonGenerator(sw); m.writeValue(jg, pojo); } catch (Exception e) { } return sw.toString(); }
public String marshall(String definitions) throws IOException { // TODO fix this when we have the EPN ecore model StringWriter writer = new StringWriter(); JsonFactory f = new JsonFactory(); JsonGenerator generator = f.createJsonGenerator(writer); // TODO do the heavy lifting here passing in the writer and the json generator generator.close(); return writer.toString(); }
private String readBody(JsonParser jp) throws IOException { JsonNode node = mapper.readTree(jp); StringWriter out = new StringWriter(); JsonGenerator gen = jsonFactory.createJsonGenerator(out); mapper.writeTree(gen, node); gen.flush(); gen.close(); return out.toString(); }
/** * Executes a query. * * @param command Name of the command to execute * @param parameters Parameters * @param manager Reference back to business layer * @return Parsed JSON object, empty object on error. */ public JsonNode query(String command, JsonNode parameters, INotifiableManager manager) { URLConnection uc = null; try { final ObjectMapper mapper = Client.MAPPER; if (mUrlSuffix == null) { throw new NoSettingsException(); } final URL url = new URL(mUrlSuffix + XBMC_JSONRPC_BOOTSTRAP); uc = url.openConnection(); uc.setConnectTimeout(SOCKET_CONNECTION_TIMEOUT); uc.setReadTimeout(mSocketReadTimeout); if (authEncoded != null) { uc.setRequestProperty("Authorization", "Basic " + authEncoded); } uc.setRequestProperty("Content-Type", "application/json"); uc.setDoOutput(true); final ObjectNode data = Client.obj().p("jsonrpc", "2.0").p("method", command).p("id", "1"); if (parameters != null) { data.put("params", parameters); } final JsonFactory jsonFactory = new JsonFactory(); final JsonGenerator jg = jsonFactory.createJsonGenerator(uc.getOutputStream(), JsonEncoding.UTF8); jg.setCodec(mapper); // POST data jg.writeTree(data); jg.flush(); final JsonParser jp = jsonFactory.createJsonParser(uc.getInputStream()); jp.setCodec(mapper); final JsonNode ret = jp.readValueAs(JsonNode.class); return ret; } catch (MalformedURLException e) { manager.onError(e); } catch (IOException e) { int responseCode = -1; try { responseCode = ((HttpURLConnection) uc).getResponseCode(); } catch (IOException e1) { } // do nothing, getResponse code failed so treat as default i/o exception. if (uc != null && responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { manager.onError(new HttpException(Integer.toString(HttpURLConnection.HTTP_UNAUTHORIZED))); } else { manager.onError(e); } } catch (NoSettingsException e) { manager.onError(e); } return new ObjectNode(null); }
public static String toJson(Object pojo, boolean prettyPrint) throws JsonMappingException, JsonGenerationException, IOException { StringWriter sw = new StringWriter(); JsonGenerator jg = jf.createJsonGenerator(sw); if (prettyPrint) { jg.useDefaultPrettyPrinter(); } m.writeValue(jg, pojo); return sw.toString(); }
public String toJSON(T object) throws IOException { JsonFactory jsonFactory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(jsonFactory); mapper.getSerializationConfig().setAnnotationIntrospector(new JacksonAnnotationIntrospector()); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); jsonFactory.setCodec(mapper); StringWriter writer = new StringWriter(); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer); jsonGenerator.useDefaultPrettyPrinter(); jsonGenerator.writeObject(object); return writer.getBuffer().toString(); }
private JsonNode write(Map<String, Object> row) throws IOException, JsonParseException { ByteArrayOutputStream out = new ByteArrayOutputStream(); JsonGenerator json = jsonFactory.createJsonGenerator(out); json.writeStartObject(); try { new GraphExtractionWriter().write(json, row.keySet(), new MapRow(row)); } finally { json.writeEndObject(); json.flush(); } return JsonHelper.jsonNode(out.toString("UTF-8")); }
@Override public void writeTo( Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { JsonGenerator writer = null; if (type.isAssignableFrom(ArtifactReadable.class)) { ArtifactReadable artifact = (ArtifactReadable) object; try { writer = jsonFactory.createJsonGenerator(entityStream); // writer.setPrettyPrinter(new DefaultPr) writer.writeStartObject(); writer.writeNumberField("uuid", artifact.getLocalId()); if (matches(IdentityView.class, annotations)) { writer.writeStringField("Name", artifact.getName()); } else { AttributeTypes attributeTypes = getAttibuteTypes(); Collection<? extends IAttributeType> attrTypes = attributeTypes.getAll(); ResultSet<? extends AttributeReadable<Object>> attributes = artifact.getAttributes(); if (!attributes.isEmpty()) { for (IAttributeType attrType : attrTypes) { if (artifact.isAttributeTypeValid(attrType)) { List<Object> attributeValues = artifact.getAttributeValues(attrType); if (!attributeValues.isEmpty()) { if (attributeValues.size() > 1) { writer.writeArrayFieldStart(attrType.getName()); for (Object value : attributeValues) { writer.writeObject(value); } writer.writeEndArray(); } else if (attributeValues.size() == 1) { Object value = attributeValues.iterator().next(); writer.writeObjectField(attrType.getName(), value); } } } } } } writer.writeEndObject(); } finally { if (writer != null) { writer.flush(); } } } }
protected String toJson(boolean pretty) { try { StringWriter writer = new StringWriter(); JsonGenerator gen = FACTORY.createJsonGenerator(writer); if (pretty) gen.useDefaultPrettyPrinter(); toJson(gen); gen.flush(); return writer.toString(); } catch (IOException e) { throw new RuntimeException(e); } }
public void jacksonTest() throws Exception { JsonFactory factory = new JsonFactory(); StringWriter writer = new StringWriter(); JsonGenerator generator = factory.createJsonGenerator(writer); generator.writeStartObject(); generator.writeFieldName("bool"); generator.writeBoolean(true); generator.writeFieldName("firstName"); generator.writeString("john"); generator.writeFieldName("age"); generator.writeNumber(1); generator.writeFieldName("gg"); generator.writeStartObject(); generator.writeFieldName("firstName"); generator.writeString("john"); generator.writeEndObject(); generator.writeEndObject(); generator.close(); String generated = writer.toString(); System.out.print(generated); JsonParser parser = factory.createJsonParser(generated); assertTrue(parser.nextToken() == JsonToken.START_OBJECT); parser.nextToken(); assertEquals("bool", parser.getCurrentName()); assertTrue(parser.nextToken() == JsonToken.VALUE_TRUE); parser.nextToken(); assertEquals("firstName", parser.getCurrentName()); parser.nextToken(); assertEquals("john", parser.getText()); parser.nextToken(); assertEquals("age", parser.getCurrentName()); parser.nextToken(); assertTrue(1 == parser.getIntValue()); parser.nextToken(); assertEquals("gg", parser.getCurrentName()); assertTrue(parser.nextToken() == JsonToken.START_OBJECT); parser.nextToken(); assertEquals("firstName", parser.getCurrentName()); parser.nextToken(); assertEquals("john", parser.getText()); assertTrue(parser.nextToken() == JsonToken.END_OBJECT); assertTrue(parser.nextToken() == JsonToken.END_OBJECT); parser.close(); }
private String jsonify(Object object) throws SCIMWriterException { try { StringWriter stringWriter = new StringWriter(); JsonGenerator jg = jsonFactory.createJsonGenerator(stringWriter); objectMapper.writeValue(jg, object); return stringWriter.toString(); } catch (JsonGenerationException e) { throw new SCIMWriterException(e); } catch (JsonMappingException e) { throw new SCIMWriterException(e); } catch (IOException e) { throw new SCIMWriterException(e); } }
private void process(File input) throws IOException { JsonFactory jsonF = new JsonFactory(); JsonParser jp = jsonF.createJsonParser(input); TwitterEntry entry = read(jp); // let's write to a file, using UTF-8 encoding (only sensible one) StringWriter strw = new StringWriter(); JsonGenerator jg = jsonF.createJsonGenerator(strw); jg.useDefaultPrettyPrinter(); // enable indentation just to make debug/testing easier // Here we would modify it... for now, will just (re)indent it write(jg, entry); System.out.println("Result = [" + strw.toString() + "]"); }
/** * Writes the response values back to the http response. This allows the calling code to parse the * response values for display to the user. * * @param responseMap the response params to write to the http response * @param response the http response * @throws IOException */ private void writeToResponse(Map<String, String> responseMap, HttpServletResponse response) throws IOException { // Note: setting the content-type to text/html because otherwise IE prompt the user to download // the result rather than handing it off to the GWT form response handler. // See JIRA issue https://issues.jboss.org/browse/SRAMPUI-103 response.setContentType("text/html; charset=UTF8"); // $NON-NLS-1$ JsonFactory f = new JsonFactory(); JsonGenerator g = f.createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8); g.useDefaultPrettyPrinter(); g.writeStartObject(); for (java.util.Map.Entry<String, String> entry : responseMap.entrySet()) { String key = entry.getKey(); String val = entry.getValue(); g.writeStringField(key, val); } g.writeEndObject(); g.flush(); g.close(); }
private void _testBean(Class clazz, Object bean) throws Exception { Map<String, Object> props = JSONHelper.createPropertiesForJaxbContext(Collections.<String, Object>emptyMap()); Class[] classes = new Class[] {clazz}; JAXBContext ctx = JAXBContext.newInstance(classes, props); JsonFactory factory = new JsonFactory(); Writer osWriter = new OutputStreamWriter(System.out); JsonGenerator g; g = factory.createJsonGenerator(osWriter); Marshaller marshaller = ctx.createMarshaller(); marshaller.marshal(bean, new Stax2JacksonWriter(g, clazz, ctx)); g.flush(); System.out.println(""); }
void send(List<String> eventLog) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); try { JsonFactory factory = new JsonFactory(); StringWriter writer = new StringWriter(); JsonGenerator generator = factory.createJsonGenerator(writer); generator.writeStartObject(); generator.writeArrayFieldStart("events"); for (String eventJson : eventLog) { generator.writeRawValue(eventJson); } generator.writeEndArray(); generator.writeEndObject(); generator.close(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( AuthScope.ANY, new UsernamePasswordCredentials(username, password)); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); RestPostProcessorDelegate.LOG.info( "Posting " + eventLog.size() + " events to " + targetUrl); HttpPost httpPost = new HttpPost(targetUrl); httpPost.setEntity(new StringEntity(writer.toString(), ContentType.APPLICATION_JSON)); CloseableHttpResponse response = httpClient.execute(httpPost, context); int statusCode = response.getStatusLine().getStatusCode(); LOG.info("Status code was " + statusCode + " when invoking " + targetUrl); if (statusCode >= 400) { throw new RiceRuntimeException( "Failed to invoke " + targetUrl + ", response code was " + statusCode); } } finally { httpClient.close(); } }
@Override public void run() { try { // command metrics for (HystrixCommandMetrics commandMetrics : HystrixCommandMetrics.getInstances()) { HystrixCommandKey key = commandMetrics.getCommandKey(); HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(key); StringWriter jsonString = new StringWriter(); JsonGenerator json = jsonFactory.createJsonGenerator(jsonString); // Informational and Status json.writeStartObject(); json.writeStringField(type.value, HystrixCommand.value); json.writeStringField(name.value, key.name()); json.writeStringField(group.value, commandMetrics.getCommandGroup().name()); json.writeNumberField(currentTime.value, (int) (System.currentTimeMillis() / 1000)); // circuit breaker json.writeBooleanField(isCircuitBreakerOpen.value, circuitBreaker.isOpen()); HystrixCommandMetrics.HealthCounts healthCounts = commandMetrics.getHealthCounts(); json.writeNumberField(errorPercentage.value, healthCounts.getErrorPercentage()); json.writeNumberField(errorCount.value, healthCounts.getErrorCount()); json.writeNumberField(requestCount.value, healthCounts.getTotalRequests()); // rolling counters Gauge json.writeNumberField( rollingCountCollapsedRequests.value, commandMetrics.getRollingCount(HystrixRollingNumberEvent.COLLAPSED)); json.writeNumberField( rollingCountExceptionsThrown.value, commandMetrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); json.writeNumberField( rollingCountFailure.value, commandMetrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); json.writeNumberField( rollingCountFallbackFailure.value, commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); json.writeNumberField( rollingCountFallbackRejection.value, commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); json.writeNumberField( rollingCountFallbackSuccess.value, commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); json.writeNumberField( rollingCountResponsesFromCache.value, commandMetrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); json.writeNumberField( rollingCountSemaphoreRejected.value, commandMetrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); json.writeNumberField( rollingCountShortCircuited.value, commandMetrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); json.writeNumberField( rollingCountSuccess.value, commandMetrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); json.writeNumberField( rollingCountThreadPoolRejected.value, commandMetrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); json.writeNumberField( rollingCountTimeout.value, commandMetrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); json.writeNumberField( currentConcurrentExecutionCount.value, commandMetrics.getCurrentConcurrentExecutionCount()); // latency percentiles json.writeNumberField(latencyExecute_mean.value, commandMetrics.getExecutionTimeMean()); json.writeObjectFieldStart(latencyExecute.value); json.writeNumberField("0", commandMetrics.getExecutionTimePercentile(0)); json.writeNumberField("25", commandMetrics.getExecutionTimePercentile(25)); json.writeNumberField("50", commandMetrics.getExecutionTimePercentile(50)); json.writeNumberField("75", commandMetrics.getExecutionTimePercentile(75)); json.writeNumberField("90", commandMetrics.getExecutionTimePercentile(90)); json.writeNumberField("95", commandMetrics.getExecutionTimePercentile(95)); json.writeNumberField("99", commandMetrics.getExecutionTimePercentile(99)); json.writeNumberField("99.5", commandMetrics.getExecutionTimePercentile(99.5)); json.writeNumberField("100", commandMetrics.getExecutionTimePercentile(100)); json.writeEndObject(); // json.writeNumberField(latencyTotal_mean.value, commandMetrics.getTotalTimeMean()); json.writeObjectFieldStart(latencyTotal.value); json.writeNumberField("0", commandMetrics.getTotalTimePercentile(0)); json.writeNumberField("25", commandMetrics.getTotalTimePercentile(25)); json.writeNumberField("50", commandMetrics.getTotalTimePercentile(50)); json.writeNumberField("75", commandMetrics.getTotalTimePercentile(75)); json.writeNumberField("90", commandMetrics.getTotalTimePercentile(90)); json.writeNumberField("95", commandMetrics.getTotalTimePercentile(95)); json.writeNumberField("99", commandMetrics.getTotalTimePercentile(99)); json.writeNumberField("99.5", commandMetrics.getTotalTimePercentile(99.5)); json.writeNumberField("100", commandMetrics.getTotalTimePercentile(100)); json.writeEndObject(); // property values for reporting what is actually seen by the command rather than what was // set somewhere HystrixCommandProperties commandProperties = commandMetrics.getProperties(); json.writeNumberField( propertyValue_circuitBreakerRequestVolumeThreshold.value, commandProperties.circuitBreakerRequestVolumeThreshold().get()); json.writeNumberField( propertyValue_circuitBreakerSleepWindowInMilliseconds.value, commandProperties.circuitBreakerSleepWindowInMilliseconds().get()); json.writeNumberField( propertyValue_circuitBreakerErrorThresholdPercentage.value, commandProperties.circuitBreakerErrorThresholdPercentage().get()); json.writeBooleanField( propertyValue_circuitBreakerForceOpen.value, commandProperties.circuitBreakerForceOpen().get()); json.writeBooleanField( propertyValue_circuitBreakerForceClosed.value, commandProperties.circuitBreakerForceClosed().get()); json.writeBooleanField( propertyValue_circuitBreakerEnabled.value, commandProperties.circuitBreakerEnabled().get()); json.writeStringField( propertyValue_executionIsolationStrategy.value, commandProperties.executionIsolationStrategy().get().name()); json.writeNumberField( propertyValue_executionIsolationThreadTimeoutInMilliseconds.value, commandProperties.executionIsolationThreadTimeoutInMilliseconds().get()); json.writeBooleanField( propertyValue_executionIsolationThreadInterruptOnTimeout.value, commandProperties.executionIsolationThreadInterruptOnTimeout().get()); json.writeStringField( propertyValue_executionIsolationThreadPoolKeyOverride.value, commandProperties.executionIsolationThreadPoolKeyOverride().get()); json.writeNumberField( propertyValue_executionIsolationSemaphoreMaxConcurrentRequests.value, commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get()); json.writeNumberField( propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests.value, commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get()); /* * The following are commented out as these rarely change and are verbose for streaming for something people don't change. * We could perhaps allow a property or request argument to include these. */ // json.put("propertyValue_metricsRollingPercentileEnabled", // commandProperties.metricsRollingPercentileEnabled().get()); // json.put("propertyValue_metricsRollingPercentileBucketSize", // commandProperties.metricsRollingPercentileBucketSize().get()); // json.put("propertyValue_metricsRollingPercentileWindow", // commandProperties.metricsRollingPercentileWindowInMilliseconds().get()); // json.put("propertyValue_metricsRollingPercentileWindowBuckets", // commandProperties.metricsRollingPercentileWindowBuckets().get()); // json.put("propertyValue_metricsRollingStatisticalWindowBuckets", // commandProperties.metricsRollingStatisticalWindowBuckets().get()); json.writeNumberField( propertyValue_metricsRollingStatisticalWindowInMilliseconds.value, commandProperties.metricsRollingStatisticalWindowInMilliseconds().get()); json.writeBooleanField( propertyValue_requestCacheEnabled.value, commandProperties.requestCacheEnabled().get()); json.writeBooleanField( propertyValue_requestLogEnabled.value, commandProperties.requestLogEnabled().get()); json.writeNumberField(reportingHosts.value, 1); json.writeStringField(Key.ip.value, app_ip); json.writeEndObject(); json.close(); // System.out.println(ip + ":" + port + "||" + // jsonString.getBuffer().toString()); UDPClient.send( socketIp, socketPort, jsonString.getBuffer().toString().getBytes(), new byte[] {}); } // thread pool metrics for (HystrixThreadPoolMetrics threadPoolMetrics : HystrixThreadPoolMetrics.getInstances()) { HystrixThreadPoolKey key = threadPoolMetrics.getThreadPoolKey(); StringWriter jsonString = new StringWriter(); JsonGenerator json = jsonFactory.createJsonGenerator(jsonString); json.writeStartObject(); json.writeStringField(type.value, HystrixThreadPool.value); json.writeStringField(name.value, key.name()); json.writeNumberField(currentTime.value, System.currentTimeMillis()); // 101.3 80 154 json.writeNumberField( currentActiveCount.value, threadPoolMetrics.getCurrentActiveCount().intValue()); json.writeNumberField( currentCompletedTaskCount.value, threadPoolMetrics.getCurrentCompletedTaskCount().longValue()); json.writeNumberField( currentCorePoolSize.value, threadPoolMetrics.getCurrentCorePoolSize().intValue()); json.writeNumberField( currentLargestPoolSize.value, threadPoolMetrics.getCurrentLargestPoolSize().intValue()); json.writeNumberField( currentMaximumPoolSize.value, threadPoolMetrics.getCurrentMaximumPoolSize().intValue()); json.writeNumberField( currentPoolSize.value, threadPoolMetrics.getCurrentPoolSize().intValue()); json.writeNumberField( currentQueueSize.value, threadPoolMetrics.getCurrentQueueSize().intValue()); json.writeNumberField( currentTaskCount.value, threadPoolMetrics.getCurrentTaskCount().longValue()); json.writeNumberField( rollingCountThreadsExecuted.value, threadPoolMetrics.getRollingCountThreadsExecuted()); json.writeNumberField( rollingMaxActiveThreads.value, threadPoolMetrics.getRollingMaxActiveThreads()); json.writeNumberField( propertyValue_queueSizeRejectionThreshold.value, threadPoolMetrics.getProperties().queueSizeRejectionThreshold().get()); json.writeNumberField( propertyValue_metricsRollingStatisticalWindowInMilliseconds.value, threadPoolMetrics .getProperties() .metricsRollingStatisticalWindowInMilliseconds() .get()); json.writeNumberField( reportingHosts.value, 1); // this will get summed across all instances in a cluster json.writeStringField(Key.ip.value, app_ip); json.writeEndObject(); json.close(); String str = jsonString.getBuffer().toString(); byte[] ret = str.getBytes(); UDPClient.send(socketIp, socketPort, ret, new byte[] {}); } } catch (Exception e) { System.err.println("Failed to output metrics as JSON"); e.printStackTrace(); } }
private void serialize() throws GVCException { JsonGenerator jsonGenerator; StringWriter stringWriter = new StringWriter(); try { jsonGenerator = jsonFactory.createJsonGenerator(stringWriter); } catch (IOException e) { throw new GVCException(e); } jsonGenerator.useDefaultPrettyPrinter(); ObjectNode rootNode = objectMapper.createObjectNode(); // Parent if (this.parent == null) rootNode.put("parent", "null"); else rootNode.put("parent", this.parent.getHash()); // Date rootNode.put("date", df.format(this.date)); // Comment rootNode.put("comment", this.comment); // Files Added /* This is a JSON "object", it looks something like this: * { * filesAdded: { * sd5df5s2: [file1, file2], * f52s556c: [file3] * } * } */ if (this.filesAdded == null) { rootNode.put("filesAdded", "null"); } else { ObjectNode addedOb = rootNode.putObject("filesAdded"); for (String fHash : this.filesAdded.keySet()) { // this will be an array of filenames for this hash ArrayNode aNode = addedOb.putArray(fHash); for (File file : this.filesAdded.get(fHash)) { // Normalize the filesystem separator to / String fileS = file.toString().replace(File.separator, "/"); aNode.add(fileS); } } } // Files Removed if (this.filesRemoved == null) { rootNode.put("filesRemoved", "null"); } else { ObjectNode removedOb = rootNode.putObject("filesRemoved"); for (String fHash : this.filesRemoved.keySet()) { // this will be an array of filenames for this hash ArrayNode rNode = removedOb.putArray(fHash); for (File file : this.filesRemoved.get(fHash)) { // Normalize the filesystem separator to / String fileS = file.toString().replace(File.separator, "/"); rNode.add(fileS); } } } // And write it all out to a string. try { jsonGenerator.writeObject(rootNode); this.serialized = stringWriter.getBuffer().toString(); } catch (Exception e) { throw new GVCException(e); } }
private void serialize(Query query, OutputStream outputStream) throws IOException { JsonGenerator g = jsonFactory.createJsonGenerator(outputStream, JsonEncoding.UTF8); g.useDefaultPrettyPrinter(); g.writeStartObject(); g.writeStringField("name", "jmxtrans"); g.writeStringField("type", "metric"); g.writeStringField("handler", sensuhandler); StringBuffer jsonoutput = new StringBuffer(); List<String> typeNames = getTypeNames(); for (Result result : query.getResults()) { Map<String, Object> resultValues = result.getValues(); if (resultValues != null) { for (Map.Entry<String, Object> values : resultValues.entrySet()) { if (NumberUtils.isNumeric(values.getValue())) { Object value = values.getValue(); jsonoutput .append(JmxUtils.getKeyString(query, result, values, typeNames, null)) .append(" ") .append(value) .append(" ") .append(TimeUnit.SECONDS.convert(result.getEpoch(), TimeUnit.MILLISECONDS)) .append(System.getProperty("line.separator")); } } } } g.writeStringField("output", jsonoutput.toString()); g.writeEndObject(); g.flush(); g.close(); }