Java Code Examples for org.codehaus.jackson.JsonGenerator

The following examples show how to use org.codehaus.jackson.JsonGenerator. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Bats   Source File: JsonStreamCodec.java    License: Apache License 2.0 6 votes vote down vote up
public JsonStreamCodec(Map<Class<?>, Class<? extends StringCodec<?>>> codecs) {
    JacksonObjectMapperProvider jomp = new JacksonObjectMapperProvider();
    if (codecs != null) {
        for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) {
            try {
                @SuppressWarnings("unchecked")
                final StringCodec<Object> codec = (StringCodec<Object>) entry.getValue().newInstance();
                jomp.addSerializer(new SerializerBase(entry.getKey()) {
                    @Override
                    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
                            throws IOException {
                        jgen.writeString(codec.toString(value));
                    }

                });
            } catch (Exception ex) {
                logger.error("Caught exception when instantiating codec for class {}", entry.getKey().getName(),
                        ex);
            }
        }
    }
    mapper = jomp.getContext(null);
}
 
Example 2
Source Project: jeecg   Source File: CustomObjectMapper.java    License: Apache License 2.0 6 votes vote down vote up
public CustomObjectMapper() {
	CustomSerializerFactory factory = new CustomSerializerFactory();
	factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {
		@Override
		public void serialize(Date value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateStr = sdf.format(value);
			if (dateStr.endsWith(" 00:00:00")) {
				dateStr = dateStr.substring(0, 10);
			} else if (dateStr.endsWith(":00")) {
				dateStr = dateStr.substring(0, 16);
			}
			jsonGenerator.writeString(dateStr);
		}
	});
	this.setSerializerFactory(factory);
}
 
Example 3
Source Project: FoxBPM   Source File: GroupDefinitionsCacheGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public void generate(ZipOutputStream out) {
	log.debug("开始处理GroupDefinitions.data...");
	try{
		List<GroupDefinition> groupDefinitions = FoxBpmUtil.getProcessEngine().getIdentityService().getAllGroupDefinitions();
		Map<String,Object> resultMap = new HashMap<String, Object>();
		resultMap.put("data", groupDefinitions);
		ObjectMapper objectMapper = new ObjectMapper();
		JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(out, JsonEncoding.UTF8);
		String tmpEntryName = "cache/allGroupDefinitions.data";
		ZipEntry zipEntry = new ZipEntry(tmpEntryName);
		zipEntry.setMethod(ZipEntry.DEFLATED);// 设置条目的压缩方式
		out.putNextEntry(zipEntry);
		jsonGenerator.writeObject(resultMap);
		out.closeEntry();
		log.debug("处理GroupDefinitions.data文件完毕");
	}catch(Exception ex){
		log.error("解析GroupDefinitions.data文件失败!生成zip文件失败!");
		throw new FoxBPMException("解析GroupDefinitions.data文件失败",ex);
	}
}
 
Example 4
@Override
public void writeTo(Collection<Language> detected, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String,Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {
    JsonGenerator jg = getJsonFactory().createJsonGenerator(entityStream);
    jg.writeStartArray();
    for(Language lang : detected){
        jg.writeStartObject();
        jg.writeStringField("lang", lang.getLang());
        if(lang.getProb() > 0){
            jg.writeNumberField("prob", lang.getProb());
        }
        jg.writeEndObject();
    }
    jg.writeEndArray();
    jg.close();
}
 
Example 5
Source Project: hadoop   Source File: Display.java    License: Apache License 2.0 6 votes vote down vote up
public AvroFileInputStream(FileStatus status) throws IOException {
  pos = 0;
  buffer = new byte[0];
  GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
  FileContext fc = FileContext.getFileContext(new Configuration());
  fileReader =
    DataFileReader.openReader(new AvroFSInput(fc, status.getPath()),reader);
  Schema schema = fileReader.getSchema();
  writer = new GenericDatumWriter<Object>(schema);
  output = new ByteArrayOutputStream();
  JsonGenerator generator =
    new JsonFactory().createJsonGenerator(output, JsonEncoding.UTF8);
  MinimalPrettyPrinter prettyPrinter = new MinimalPrettyPrinter();
  prettyPrinter.setRootValueSeparator(System.getProperty("line.separator"));
  generator.setPrettyPrinter(prettyPrinter);
  encoder = EncoderFactory.get().jsonEncoder(schema, generator);
}
 
Example 6
Source Project: bintray-client-java   Source File: RepositoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * PATCH repo only accepts description and label updates, name is needed for URL creation, because of the special
 * ignore and property structure of the RepositoryDetails class this method just uses a json generator to write
 * the update json.
 */
public static String getUpdateJson(RepositoryDetails repositoryDetails) throws IOException {
    StringWriter writer = new StringWriter();
    JsonGenerator jGen = ObjectMapperHelper.get().getJsonFactory().createJsonGenerator(writer);
    jGen.writeStartObject();
    jGen.writeStringField("name", repositoryDetails.getName());
    jGen.writeStringField("desc", repositoryDetails.getDescription());
    if (repositoryDetails.getLabels().size() > 0) {
        jGen.writeArrayFieldStart("labels");
        for (String label : repositoryDetails.getLabels()) {
            jGen.writeString(label);
        }
        jGen.writeEndArray();
    }
    jGen.writeEndObject();
    jGen.close();
    writer.close();
    return writer.toString();
}
 
Example 7
Source Project: big-c   Source File: StatePool.java    License: Apache License 2.0 6 votes vote down vote up
private void write(DataOutput out) throws IOException {
  // This is just a JSON experiment
  System.out.println("Dumping the StatePool's in JSON format.");
  ObjectMapper outMapper = new ObjectMapper();
  outMapper.configure(
      SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
  // define a module
  SimpleModule module = new SimpleModule("State Serializer",  
      new Version(0, 1, 1, "FINAL"));
  // add the state serializer
  //module.addSerializer(State.class, new StateSerializer());

  // register the module with the object-mapper
  outMapper.registerModule(module);

  JsonFactory outFactory = outMapper.getJsonFactory();
  JsonGenerator jGen = 
    outFactory.createJsonGenerator((DataOutputStream)out, JsonEncoding.UTF8);
  jGen.useDefaultPrettyPrinter();

  jGen.writeObject(this);
  jGen.close();
}
 
Example 8
Source Project: big-c   Source File: Anonymizer.java    License: Apache License 2.0 6 votes vote down vote up
private JsonGenerator createJsonGenerator(Configuration conf, Path path) 
throws IOException {
  FileSystem outFS = path.getFileSystem(conf);
  CompressionCodec codec =
    new CompressionCodecFactory(conf).getCodec(path);
  OutputStream output;
  Compressor compressor = null;
  if (codec != null) {
    compressor = CodecPool.getCompressor(codec);
    output = codec.createOutputStream(outFS.create(path), compressor);
  } else {
    output = outFS.create(path);
  }

  JsonGenerator outGen = outFactory.createJsonGenerator(output, 
                                                        JsonEncoding.UTF8);
  outGen.useDefaultPrettyPrinter();
  
  return outGen;
}
 
Example 9
@Override
public void serialize(AttributesSearchQueryImpl value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {

    jgen.writeStartArray();
    jgen.writeStartObject();
    jgen.writeArrayFieldStart(value.attributeName);

    @SuppressWarnings("unchecked")
    List<AttributesSearchQueryClauseImpl> clauses = value.getQueryClauses();
    for (AttributesSearchQueryClauseImpl clause : clauses) {
        if (clause.getType().equals(Attribute.Type.Boolean)) {
            jgen.writeBoolean((Boolean) clause.getClauseValue());
        } else if (clause.getType().equals(Attribute.Type.number)) {
            jgen.writeNumber(String.valueOf(clause.getClauseValue()));
        } else {  //String or Date
            jgen.writeString((String) clause.getClauseValue());
        }
    }
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.writeEndArray();
}
 
Example 10
Source Project: jenkins-build-monitor-plugin   Source File: JobViewSerialiser.java    License: MIT License 6 votes vote down vote up
@Override
public void serialize(JobView job, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    jgen.writeStartObject();
    jgen.writeObjectField("name",               job.name());
    jgen.writeObjectField("url",                job.url());
    jgen.writeObjectField("status",             job.status());
    jgen.writeObjectField("hashCode",           job.hashCode());
    jgen.writeObjectField("progress",           job.progress());
    jgen.writeObjectField("estimatedDuration",  job.estimatedDuration());

    for (Feature<?> feature : job.features()) {
        Object serialised = feature.asJson();

        if (serialised != null) {
            jgen.writeObjectField(nameOf(serialised), serialised);
        }
    }

    jgen.writeEndObject();
}
 
Example 11
Source Project: hraven   Source File: ObjectMapperProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(Configuration conf, JsonGenerator jsonGenerator,
    SerializerProvider serializerProvider) throws IOException {
  SerializationContext context = RestResource.serializationContext
      .get();
  Predicate<String> configFilter = context.getConfigurationFilter();
  Iterator<Map.Entry<String, String>> keyValueIterator = conf.iterator();

  jsonGenerator.writeStartObject();

  // here's where we can filter out keys if we want
  while (keyValueIterator.hasNext()) {
    Map.Entry<String, String> kvp = keyValueIterator.next();
    if (configFilter == null || configFilter.apply(kvp.getKey())) {
      jsonGenerator.writeFieldName(kvp.getKey());
      jsonGenerator.writeString(kvp.getValue());
    }
  }
  jsonGenerator.writeEndObject();
}
 
Example 12
Source Project: attic-apex-core   Source File: JsonStreamCodec.java    License: Apache License 2.0 6 votes vote down vote up
public JsonStreamCodec(Map<Class<?>, Class<? extends StringCodec<?>>> codecs)
{
  JacksonObjectMapperProvider jomp = new JacksonObjectMapperProvider();
  if (codecs != null) {
    for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry: codecs.entrySet()) {
      try {
        @SuppressWarnings("unchecked")
        final StringCodec<Object> codec = (StringCodec<Object>)entry.getValue().newInstance();
        jomp.addSerializer(new SerializerBase(entry.getKey())
        {
          @Override
          public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException
          {
            jgen.writeString(codec.toString(value));
          }

        });
      } catch (Exception ex) {
        logger.error("Caught exception when instantiating codec for class {}", entry.getKey().getName(), ex);
      }
    }
  }
  mapper = jomp.getContext(null);
}
 
Example 13
@Override
public void serialize(ContainerPlacementMessage value, JsonGenerator jsonGenerator, SerializerProvider provider)
    throws IOException {
  Map<String, Object> containerPlacementMessageMap = new HashMap<String, Object>();
  if (value instanceof ContainerPlacementRequestMessage) {
    containerPlacementMessageMap.put("subType", ContainerPlacementRequestMessage.class.getSimpleName());
  } else if (value instanceof ContainerPlacementResponseMessage) {
    containerPlacementMessageMap.put("subType", ContainerPlacementResponseMessage.class.getSimpleName());
    containerPlacementMessageMap.put("responseMessage",
        ((ContainerPlacementResponseMessage) value).getResponseMessage());
  }
  if (value.getRequestExpiry() != null) {
    containerPlacementMessageMap.put("requestExpiry", value.getRequestExpiry().toMillis());
  }
  containerPlacementMessageMap.put("uuid", value.getUuid().toString());
  containerPlacementMessageMap.put("deploymentId", value.getDeploymentId());
  containerPlacementMessageMap.put("processorId", value.getProcessorId());
  containerPlacementMessageMap.put("destinationHost", value.getDestinationHost());
  containerPlacementMessageMap.put("statusCode", value.getStatusCode().name());
  containerPlacementMessageMap.put("timestamp", value.getTimestamp());
  jsonGenerator.writeObject(containerPlacementMessageMap);
}
 
Example 14
Source Project: Bats   Source File: StramWebServices.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private void init()
{
  //clear content type
  httpResponse.setContentType(null);
  if (!initialized) {
    Map<Class<?>, Class<? extends StringCodec<?>>> codecs = dagManager.getApplicationAttributes().get(DAGContext.STRING_CODECS);
    StringCodecs.loadConverters(codecs);
    if (codecs != null) {
      SimpleModule sm = new SimpleModule("DTSerializationModule", new Version(1, 0, 0, null));
      for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) {
        try {
          final StringCodec<Object> codec = (StringCodec<Object>)entry.getValue().newInstance();
          sm.addSerializer(new SerializerBase(entry.getKey())
          {
            @Override
            public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException
            {
              jgen.writeString(codec.toString(value));
            }

          });
        } catch (Exception ex) {
          LOG.error("Caught exception when instantiating codec for class {}", entry.getKey().getName(), ex);
        }
      }

      objectMapper.registerModule(sm);
    }
    initialized = true;
  }
}
 
Example 15
Source Project: Bats   Source File: JacksonObjectMapperProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Constructor for JacksonObjectMapperProvider.</p>
 */
public JacksonObjectMapperProvider()
{
  this.objectMapper = new ObjectMapper();
  objectMapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
  objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
  module.addSerializer(ObjectMapperString.class, new RawSerializer<>(Object.class));
  module.addSerializer(JSONObject.class, new RawSerializer<>(Object.class));
  module.addSerializer(JSONArray.class, new RawSerializer<>(Object.class));
  objectMapper.registerModule(module);
}
 
Example 16
Source Project: incubator-gobblin   Source File: GlobalMetadata.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Serialize as a UTF8 encoded JSON string.
 */
public byte[] toJsonUtf8() {
  try {
    ByteArrayOutputStream bOs = new ByteArrayOutputStream(512);

    try (JsonGenerator generator = jsonFactory.createJsonGenerator(bOs, JsonEncoding.UTF8)
        .setCodec(objectMapper)) {
      toJsonUtf8(generator);
    }

    return bOs.toByteArray();
  } catch (IOException e) {
    throw new RuntimeException("Unexpected IOException serializing to ByteArray", e);
  }
}
 
Example 17
Source Project: nifi   Source File: WriteJsonResult.java    License: Apache License 2.0 5 votes vote down vote up
private void writeArray(final Object[] values, final String fieldName, final JsonGenerator generator, final DataType elementType) throws IOException {
    generator.writeStartArray();
    for (final Object element : values) {
        writeValue(generator, element, fieldName, elementType);
    }
    generator.writeEndArray();
}
 
Example 18
Source Project: localization_nifi   Source File: SiteToSiteReceiver.java    License: Apache License 2.0 5 votes vote down vote up
public TransactionCompletion receiveFiles() throws IOException {
    Transaction transaction = siteToSiteClient.createTransaction(TransferDirection.RECEIVE);
    JsonGenerator jsonGenerator = new JsonFactory().createJsonGenerator(output);
    jsonGenerator.writeStartArray();
    DataPacket dataPacket;
    while ((dataPacket = transaction.receive()) != null) {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeFieldName("attributes");
        jsonGenerator.writeStartObject();
        Map<String, String> attributes = dataPacket.getAttributes();
        if (attributes != null) {
            for (Map.Entry<String, String> stringStringEntry : attributes.entrySet()) {
                jsonGenerator.writeStringField(stringStringEntry.getKey(), stringStringEntry.getValue());
            }
        }
        jsonGenerator.writeEndObject();
        InputStream data = dataPacket.getData();
        if (data != null) {
            jsonGenerator.writeBinaryField("data", IOUtils.toByteArray(data));
        }
        jsonGenerator.writeEndObject();
    }
    jsonGenerator.writeEndArray();
    jsonGenerator.close();
    transaction.confirm();
    return transaction.complete();
}
 
Example 19
Source Project: WSPerfLab   Source File: ServiceResponseBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public static ByteArrayOutputStream buildTestBResponse(JsonFactory jsonFactory, BackendResponse response)
            throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(bos);

    jsonGenerator.writeStartObject();

    // delay values of each response
    jsonGenerator.writeArrayFieldStart("delay");
    writeTuple(jsonGenerator, "a", response.getDelay());
    jsonGenerator.writeEndArray();

    // itemSize values of each response
    jsonGenerator.writeArrayFieldStart("itemSize");
    writeTuple(jsonGenerator, "a", response.getItemSize());
    jsonGenerator.writeEndArray();

    // numItems values of each response
    jsonGenerator.writeArrayFieldStart("numItems");
    writeTuple(jsonGenerator, "a", response.getNumItems());
    jsonGenerator.writeEndArray();

    // all items from responses
    jsonGenerator.writeArrayFieldStart("items");
    addItemsFromResponse(jsonGenerator, response);
    jsonGenerator.writeEndArray();

    jsonGenerator.writeEndObject();
    jsonGenerator.close();

    return bos;
}
 
Example 20
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
        throws IOException, JsonProcessingException {
    String formattedDate = null;
    if (date != null) {
        formattedDate = dateFormat.format(date);
    }
    jsonGenerator.writeString(formattedDate);
}
 
Example 21
Source Project: hraven   Source File: ObjectMapperProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Flow aFlow, JsonGenerator jsonGenerator,
    SerializerProvider serializerProvider) throws IOException {

  SerializationContext context = RestResource.serializationContext.get();
  SerializationContext.DetailLevel selectedSerialization = context.getLevel();
  Predicate<String> includeFilter = context.getFlowFilter();
  writeFlowDetails(jsonGenerator, aFlow, selectedSerialization, includeFilter);
}
 
Example 22
private void writeRecord(RecordWithMetadata<?> inputRecord, JsonGenerator generator)
    throws IOException {
  if (shouldInterpretRecordAsUtf8ByteArray(inputRecord)) {
    generator.writeFieldName("r");
    byte[] bytes = (byte[]) inputRecord.getRecord();
    generator.writeUTF8String(bytes, 0, bytes.length);
  } else {
    generator.writeObjectField("r", inputRecord.getRecord());
  }
}
 
Example 23
Source Project: boubei-tss   Source File: TSSObjectMapper.java    License: Apache License 2.0 5 votes vote down vote up
public void serialize(Date value, JsonGenerator jsonGenerator, SerializerProvider provider)  
        throws IOException, JsonProcessingException {  
	
    String result = DateUtil.formatCare2Second(value);
    result = result.replaceAll(" 00:00:00", "");
	jsonGenerator.writeString( result );  
}
 
Example 24
Source Project: flink   Source File: Configuration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *  Writes out all the parameters and their properties (final and resource) to
 *  the given {@link Writer}
 *  The format of the output would be
 *  { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
 *  key2.isFinal,key2.resource}... ] }
 *  It does not output the parameters of the configuration object which is
 *  loaded from an input stream.
 * @param out the Writer to write to
 * @throws IOException
 */
public static void dumpConfiguration(Configuration config,
    Writer out) throws IOException {
  JsonFactory dumpFactory = new JsonFactory();
  JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
  dumpGenerator.writeStartObject();
  dumpGenerator.writeFieldName("properties");
  dumpGenerator.writeStartArray();
  dumpGenerator.flush();
  synchronized (config) {
    for (Entry<Object,Object> item: config.getProps().entrySet()) {
      dumpGenerator.writeStartObject();
      dumpGenerator.writeStringField("key", (String) item.getKey());
      dumpGenerator.writeStringField("value",
                                     config.get((String) item.getKey()));
      dumpGenerator.writeBooleanField("isFinal",
                                      config.finalParameters.contains(item.getKey()));
      String[] resources = config.updatingResource.get(item.getKey());
      String resource = UNKNOWN_RESOURCE;
      if(resources != null && resources.length > 0) {
        resource = resources[0];
      }
      dumpGenerator.writeStringField("resource", resource);
      dumpGenerator.writeEndObject();
    }
  }
  dumpGenerator.writeEndArray();
  dumpGenerator.writeEndObject();
  dumpGenerator.flush();
}
 
Example 25
Source Project: nifi   Source File: WriteJsonResult.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public WriteResult writeRawRecord(final Record record) throws IOException {
    // If we are not writing an active record set, then we need to ensure that we write the
    // schema information.
    if (!isActiveRecordSet()) {
        generator.flush();
        schemaAccess.writeHeader(recordSchema, getOutputStream());
    }

    writeRecord(record, recordSchema, generator, JsonGenerator::writeStartObject, JsonGenerator::writeEndObject, false);
    final Map<String, String> attributes = schemaAccess.getAttributes(recordSchema);
    return WriteResult.of(incrementRecordCount(), attributes);
}
 
Example 26
Source Project: ReactiveLab   Source File: JsonMapper.java    License: Apache License 2.0 5 votes vote down vote up
static String toJson(HystrixThreadPoolMetrics threadPoolMetrics) throws IOException {
    HystrixThreadPoolKey key = threadPoolMetrics.getThreadPoolKey();

    StringWriter jsonString = new StringWriter();
    JsonGenerator json = jsonFactory.createJsonGenerator(jsonString);
    json.writeStartObject();

    json.writeStringField("type", "HystrixThreadPool");
    json.writeStringField("name", key.name());
    json.writeNumberField("currentTime", System.currentTimeMillis());

    json.writeNumberField("currentActiveCount", threadPoolMetrics.getCurrentActiveCount().intValue());
    json.writeNumberField("currentCompletedTaskCount", threadPoolMetrics.getCurrentCompletedTaskCount().longValue());
    json.writeNumberField("currentCorePoolSize", threadPoolMetrics.getCurrentCorePoolSize().intValue());
    json.writeNumberField("currentLargestPoolSize", threadPoolMetrics.getCurrentLargestPoolSize().intValue());
    json.writeNumberField("currentMaximumPoolSize", threadPoolMetrics.getCurrentMaximumPoolSize().intValue());
    json.writeNumberField("currentPoolSize", threadPoolMetrics.getCurrentPoolSize().intValue());
    json.writeNumberField("currentQueueSize", threadPoolMetrics.getCurrentQueueSize().intValue());
    json.writeNumberField("currentTaskCount", threadPoolMetrics.getCurrentTaskCount().longValue());
    json.writeNumberField("rollingCountThreadsExecuted", threadPoolMetrics.getRollingCountThreadsExecuted());
    json.writeNumberField("rollingMaxActiveThreads", threadPoolMetrics.getRollingMaxActiveThreads());

    json.writeNumberField("propertyValue_queueSizeRejectionThreshold", threadPoolMetrics.getProperties().queueSizeRejectionThreshold().get());
    json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds", threadPoolMetrics.getProperties().metricsRollingStatisticalWindowInMilliseconds().get());

    json.writeNumberField("reportingHosts", 1); // this will get summed across all instances in a cluster

    json.writeEndObject();
    json.close();

    return jsonString.getBuffer().toString();
}
 
Example 27
Source Project: ensemble-clustering   Source File: InstanceJsonMapper.java    License: MIT License 5 votes vote down vote up
public static String toJson(Instance inst, boolean prettyPrint) 
	throws JsonMappingException, JsonGenerationException, IOException {
    
	StringWriter writer = new StringWriter();
    JsonGenerator generator = factory.createJsonGenerator(writer);
    
    if (prettyPrint) {
        generator.useDefaultPrettyPrinter();
    }
    
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    mapper.writeValue(generator, inst);
    return writer.toString();
}
 
Example 28
Source Project: hadoop   Source File: DefaultAnonymizingRumenSerializer.java    License: Apache License 2.0 5 votes vote down vote up
public void serialize(AnonymizableDataType object, JsonGenerator jGen, 
                      SerializerProvider sProvider) 
throws IOException, JsonProcessingException {
  Object val = object.getAnonymizedValue(statePool, conf);
  // output the data if its a string
  if (val instanceof String) {
    jGen.writeString(val.toString());
  } else {
    // let the mapper (JSON generator) handle this anonymized object.
    jGen.writeObject(val);
  }
}
 
Example 29
Source Project: hadoop   Source File: DefaultRumenSerializer.java    License: Apache License 2.0 5 votes vote down vote up
public void serialize(DataType object, JsonGenerator jGen, SerializerProvider sProvider) 
throws IOException, JsonProcessingException {
  Object data = object.getValue();
  if (data instanceof String) {
    jGen.writeString(data.toString());
  } else {
    jGen.writeObject(data);
  }
}
 
Example 30
Source Project: hadoop   Source File: TestHistograms.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
  final Configuration conf = new Configuration();
  final FileSystem lfs = FileSystem.getLocal(conf);

  for (String arg : args) {
    Path filePath = new Path(arg).makeQualified(lfs);
    String fileName = filePath.getName();
    if (fileName.startsWith("input")) {
      LoggedDiscreteCDF newResult = histogramFileToCDF(filePath, lfs);
      String testName = fileName.substring("input".length());
      Path goldFilePath = new Path(filePath.getParent(), "gold"+testName);

      ObjectMapper mapper = new ObjectMapper();
      JsonFactory factory = mapper.getJsonFactory();
      FSDataOutputStream ostream = lfs.create(goldFilePath, true);
      JsonGenerator gen = factory.createJsonGenerator(ostream,
          JsonEncoding.UTF8);
      gen.useDefaultPrettyPrinter();
      
      gen.writeObject(newResult);
      
      gen.close();
    } else {
      System.err.println("Input file not started with \"input\". File "+fileName+" skipped.");
    }
  }
}