org.codehaus.jackson.JsonGenerator Java Examples

The following examples show how to use org.codehaus.jackson.JsonGenerator. 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 File: JobViewSerialiser.java    From jenkins-build-monitor-plugin with 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 #2
Source File: JsonStreamCodec.java    From attic-apex-core with 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 #3
Source File: JsonStreamCodec.java    From Bats with 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 #4
Source File: ContainerPlacementMessageObjectMapper.java    From samza with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: ObjectMapperProvider.java    From hraven with 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 #6
Source File: CustomObjectMapper.java    From jeecg with 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 #7
Source File: AttributesSearchQueryImpl.java    From bintray-client-java with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: Anonymizer.java    From big-c with 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
Source File: GroupDefinitionsCacheGenerator.java    From FoxBPM with 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 #10
Source File: DetectedLanguageWriter.java    From stanbol-freeling with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #11
Source File: StatePool.java    From big-c with 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 #12
Source File: RepositoryImpl.java    From bintray-client-java with 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 #13
Source File: Display.java    From hadoop with 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 #14
Source File: SamzaObjectMapper.java    From samza with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(SystemStreamPartition systemStreamPartition, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
  Map<String, Object> systemStreamPartitionMap = new HashMap<String, Object>();
  systemStreamPartitionMap.put("system", systemStreamPartition.getSystem());
  systemStreamPartitionMap.put("stream", systemStreamPartition.getStream());
  systemStreamPartitionMap.put("partition", systemStreamPartition.getPartition());
  jsonGenerator.writeObject(systemStreamPartitionMap);
}
 
Example #15
Source File: ResponseBuilder.java    From ReactiveLab with Apache License 2.0 5 votes vote down vote up
public static void writeTestResponse(Writer writer, BackendResponse responseA, BackendResponse responseB,
        BackendResponse responseC, BackendResponse responseD, BackendResponse responseE, Action0 onComplete) {
    try {
        JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer);
        generateResponse(responseA, responseB, responseC, responseD, responseE, jsonGenerator);
        if (onComplete != null) {
            onComplete.call();
        }
        jsonGenerator.close();
    } catch (Exception e) {
        throw new RuntimeException("failed to generated response", e);
    }

}
 
Example #16
Source File: Log4Json.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Build a JSON entry from the parameters. This is public for testing.
 *
 * @param writer destination
 * @param loggerName logger name
 * @param timeStamp time_t value
 * @param level level string
 * @param threadName name of the thread
 * @param message rendered message
 * @param ti nullable thrown information
 * @return the writer
 * @throws IOException on any problem
 */
public Writer toJson(final Writer writer,
                     final String loggerName,
                     final long timeStamp,
                     final String level,
                     final String threadName,
                     final String message,
                     final ThrowableInformation ti) throws IOException {
  JsonGenerator json = factory.createJsonGenerator(writer);
  json.writeStartObject();
  json.writeStringField(NAME, loggerName);
  json.writeNumberField(TIME, timeStamp);
  Date date = new Date(timeStamp);
  json.writeStringField(DATE, dateFormat.format(date));
  json.writeStringField(LEVEL, level);
  json.writeStringField(THREAD, threadName);
  json.writeStringField(MESSAGE, message);
  if (ti != null) {
    //there is some throwable info, but if the log event has been sent over the wire,
    //there may not be a throwable inside it, just a summary.
    Throwable thrown = ti.getThrowable();
    String eclass = (thrown != null) ?
        thrown.getClass().getName()
        : "";
    json.writeStringField(EXCEPTION_CLASS, eclass);
    String[] stackTrace = ti.getThrowableStrRep();
    json.writeArrayFieldStart(STACK);
    for (String row : stackTrace) {
      json.writeString(row);
    }
    json.writeEndArray();
  }
  json.writeEndObject();
  json.flush();
  json.close();
  return writer;
}
 
Example #17
Source File: JsonFileWriter.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private JsonGenerator getJsonGenerator() throws IOException {
    if (jsonGenerator == null) {
        jsonGenerator = JSON_FACTORY.createJsonGenerator(getOutputStream());
        jsonGenerator.setCodec(MAPPER);
        jsonGenerator.writeStartArray();
    }

    return jsonGenerator;
}
 
Example #18
Source File: GlobalMetadata.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Write this object out to an existing JSON stream
 */
protected void bodyToJsonUtf8(JsonGenerator generator)
    throws IOException {

  generator.writeObjectField("dataset", datasetLevel);
  generator.writeObjectFieldStart("file");
  for (Map.Entry<String, Map<String, Object>> entry : fileLevel.entrySet()) {
    generator.writeObjectField(entry.getKey(), entry.getValue());
  }
  generator.writeEndObject();

}
 
Example #19
Source File: StramWebServices.java    From attic-apex-core with 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 #20
Source File: ObjectMapperProvider.java    From hraven with Apache License 2.0 5 votes vote down vote up
/**
 * checks if the member is to be filtered out or no if filter itself is
 * null, writes out that member
 *
 * @param member
 * @param includeFilter
 * @param taskObject
 * @param jsonGenerator
 * @throws JsonGenerationException
 * @throws IOException
 */
public static void filteredWrite(String member, Predicate<String> includeFilter,
    Object taskObject, JsonGenerator jsonGenerator)
    throws JsonGenerationException, IOException {
  if (includeFilter != null) {
    if (includeFilter.apply(member)) {
      jsonGenerator.writeFieldName(member);
      jsonGenerator.writeObject(taskObject);
    }
  } else {
    jsonGenerator.writeFieldName(member);
    jsonGenerator.writeObject(taskObject);
  }
}
 
Example #21
Source File: OptionalSerializer.java    From incubator-myriad with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Optional<T> value, JsonGenerator jgen, SerializerProvider provider)
    throws IOException, JsonProcessingException {
  if (value.isPresent()) {
    objMapper.writeValue(jgen, value.get());
  } else {
    objMapper.writeValue(jgen, "value is absent");
  }
}
 
Example #22
Source File: Anonymizer.java    From big-c with Apache License 2.0 5 votes vote down vote up
private void anonymizeTrace() throws Exception {
  if (anonymizeTrace) {
    System.out.println("Anonymizing trace file: " + inputTracePath);
    JobTraceReader reader = null;
    JsonGenerator outGen = null;
    Configuration conf = getConf();
    
    try {
      // create a generator
      outGen = createJsonGenerator(conf, outputTracePath);

      // define the input trace reader
      reader = new JobTraceReader(inputTracePath, conf);
      
      // read the plain unanonymized logged job
      LoggedJob job = reader.getNext();
      
      while (job != null) {
        // write it via an anonymizing channel
        outGen.writeObject(job);
        // read the next job
        job = reader.getNext();
      }
      
      System.out.println("Anonymized trace file: " + outputTracePath);
    } finally {
      if (outGen != null) {
        outGen.close();
      }
      if (reader != null) {
        reader.close();
      }
    }
  }
}
 
Example #23
Source File: LinkSerializer.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Link link, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    
    if (link == null) {
        jgen.writeNull();
        return;
    }
    
    String linkString = "{\"rel\":\"" + link.getLinkName() + "\",\"href\":\"" + link.getResourceURL().toString()
            + "\"}";
    jgen.writeRaw(linkString);
}
 
Example #24
Source File: StramWebServices.java    From Bats with 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 #25
Source File: QueueManager.java    From big-c with Apache License 2.0 5 votes vote down vote up
/***
 * Dumps the configuration of hierarchy of queues with 
 * the xml file path given. It is to be used directly ONLY FOR TESTING.
 * @param out the writer object to which dump is written to.
 * @param configFile the filename of xml file
 * @throws IOException
 */
static void dumpConfiguration(Writer out, String configFile,
    Configuration conf) throws IOException {
  if (conf != null && conf.get(DeprecatedQueueConfigurationParser.
      MAPRED_QUEUE_NAMES_KEY) != null) {
    return;
  }
  
  JsonFactory dumpFactory = new JsonFactory();
  JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
  QueueConfigurationParser parser;
  boolean aclsEnabled = false;
  if (conf != null) {
    aclsEnabled = conf.getBoolean(MRConfig.MR_ACLS_ENABLED, false);
  }
  if (configFile != null && !"".equals(configFile)) {
    parser = new QueueConfigurationParser(configFile, aclsEnabled);
  }
  else {
    parser = getQueueConfigurationParser(null, false, aclsEnabled);
  }
  dumpGenerator.writeStartObject();
  dumpGenerator.writeFieldName("queues");
  dumpGenerator.writeStartArray();
  dumpConfiguration(dumpGenerator,parser.getRoot().getChildren());
  dumpGenerator.writeEndArray();
  dumpGenerator.writeEndObject();
  dumpGenerator.flush();
}
 
Example #26
Source File: JSONUtil.java    From jstorm with Apache License 2.0 5 votes vote down vote up
/**
 * 将map转化为json
 * 
 * @param map
 * @return
 */
public String formatMap2JSON(Map<String, Object> map) {
	StringWriter stringWriter = new StringWriter();
	String json = "";
	try {
		JsonGenerator gen = new JsonFactory()
				.createJsonGenerator(stringWriter);
		MAPPER.writeValue(gen, map);
		gen.close();
		json = stringWriter.toString();
	} catch (Exception e) {
		LOGGER.error("", e);
	}
	return json;
}
 
Example #27
Source File: Configuration.java    From hadoop with 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 (Map.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 #28
Source File: Log4Json.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Build a JSON entry from the parameters. This is public for testing.
 *
 * @param writer destination
 * @param loggerName logger name
 * @param timeStamp time_t value
 * @param level level string
 * @param threadName name of the thread
 * @param message rendered message
 * @param ti nullable thrown information
 * @return the writer
 * @throws IOException on any problem
 */
public Writer toJson(final Writer writer,
                     final String loggerName,
                     final long timeStamp,
                     final String level,
                     final String threadName,
                     final String message,
                     final ThrowableInformation ti) throws IOException {
  JsonGenerator json = factory.createJsonGenerator(writer);
  json.writeStartObject();
  json.writeStringField(NAME, loggerName);
  json.writeNumberField(TIME, timeStamp);
  Date date = new Date(timeStamp);
  json.writeStringField(DATE, dateFormat.format(date));
  json.writeStringField(LEVEL, level);
  json.writeStringField(THREAD, threadName);
  json.writeStringField(MESSAGE, message);
  if (ti != null) {
    //there is some throwable info, but if the log event has been sent over the wire,
    //there may not be a throwable inside it, just a summary.
    Throwable thrown = ti.getThrowable();
    String eclass = (thrown != null) ?
        thrown.getClass().getName()
        : "";
    json.writeStringField(EXCEPTION_CLASS, eclass);
    String[] stackTrace = ti.getThrowableStrRep();
    json.writeArrayFieldStart(STACK);
    for (String row : stackTrace) {
      json.writeString(row);
    }
    json.writeEndArray();
  }
  json.writeEndObject();
  json.flush();
  json.close();
  return writer;
}
 
Example #29
Source File: JsonDateSerializer.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Date date, JsonGenerator gen,
		SerializerProvider provider) throws IOException,
		JsonProcessingException {

	String formattedDate = new SimpleDateFormat(DATE_FORMAT).format(date);
	gen.writeString(formattedDate);
}
 
Example #30
Source File: TaggedLogAPIEntity.java    From Eagle with Apache License 2.0 5 votes vote down vote up
@Override
public void serializeAsField(Object bean, JsonGenerator jgen, SerializerProvider provider, BeanPropertyWriter writer) throws Exception {
	if(bean instanceof TaggedLogAPIEntity){
		TaggedLogAPIEntity entity = (TaggedLogAPIEntity) bean;
		Set<String> modified = entity.modifiedQualifiers();
		Set<String> basePropertyNames = getPropertyNames();
		String writerName = writer.getName();
		if(modified.contains(writerName) || basePropertyNames.contains(writerName)){
			if((!entity.isSerializeVerbose() && verboseFields.contains(writerName))||							// skip verbose fields
					(timestamp.equals(writerName) && !EntityDefinitionManager.isTimeSeries(entity.getClass()))	// skip timestamp for non-timeseries entity
			){
				// log skip
				if(LOG.isDebugEnabled()) LOG.debug("skip field");
			}else{
				// if serializeAlias is not null and exp is not null
				if (exp.equals(writerName) && entity.getSerializeAlias()!=null && entity.getExp()!=null) {
					Map<String, Object> _exp = new HashMap<String, Object>();
					for (Map.Entry<String, Object> entry : entity.getExp().entrySet()) {
						String alias = entity.getSerializeAlias().get(entry.getKey());
						if (alias != null) {
							_exp.put(alias, entry.getValue());
						} else {
							_exp.put(entry.getKey(), entry.getValue());
						}
					}
					entity.setExp(_exp);
				}
				// write included field into serialized json output
				writer.serializeAsField(bean, jgen, provider);
			}
		}
	}else{
		writer.serializeAsField(bean, jgen, provider);
	}
}