Example usage for com.fasterxml.jackson.core JsonGenerator writeObject

List of usage examples for com.fasterxml.jackson.core JsonGenerator writeObject

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonGenerator writeObject.

Prototype

public abstract void writeObject(Object pojo) throws IOException, JsonProcessingException;

Source Link

Document

Method for writing given Java object (POJO) as Json.

Usage

From source file:org.killbill.billing.plugin.meter.api.user.DebugJsonSamplesOutputer.java

@Override
protected void writeJsonForChunks(final JsonGenerator generator,
        final Collection<? extends TimelineChunk> chunksForSourceAndMetric) throws IOException {
    for (final TimelineChunk chunk : chunksForSourceAndMetric) {
        if (withBinaryData) {
            writer.writeValue(generator, new TimelineChunkDecoded(chunk, sampleCoder));
        } else {//from  ww w  .ja v a 2s  .  c o m
            final String source = timelineDao.getSource(chunk.getSourceId(), context);
            final CategoryRecordIdAndMetric categoryIdAndMetric = timelineDao
                    .getCategoryIdAndMetric(chunk.getMetricId(), context);
            final String category = timelineDao.getEventCategory(categoryIdAndMetric.getEventCategoryId(),
                    context);
            final String metric = categoryIdAndMetric.getMetric();
            final String samples = CSVConsumer.getSamplesAsCSV(sampleCoder, chunk);

            // Don't write out empty samples
            if (!Strings.isNullOrEmpty(samples)) {
                generator.writeObject(new SamplesForMetricAndSource(source, category, metric, samples));
            }
        }
    }
}

From source file:org.killbill.billing.plugin.meter.api.user.DecimatingJsonSamplesOutputer.java

@Override
protected void writeJsonForChunks(final JsonGenerator generator,
        final Collection<? extends TimelineChunk> chunksForSourceAndMetric) throws IOException {
    for (final TimelineChunk chunk : chunksForSourceAndMetric) {
        final String source = timelineDao.getSource(chunk.getSourceId(), context);
        final CategoryRecordIdAndMetric categoryIdAndMetric = timelineDao
                .getCategoryIdAndMetric(chunk.getMetricId(), context);
        final String eventCategory = timelineDao.getEventCategory(categoryIdAndMetric.getEventCategoryId(),
                context);//www.  j av a2  s. c  o  m
        final String metric = categoryIdAndMetric.getMetric();
        final TimeRangeSampleProcessor filter = filters.get(chunk.getSourceId()).get(chunk.getMetricId());

        final String samples = filter == null ? CSVConsumer.getSamplesAsCSV(sampleCoder, chunk)
                : CSVConsumer.getSamplesAsCSV(sampleCoder, chunk, filter);

        // Don't write out empty samples
        if (!Strings.isNullOrEmpty(samples)) {
            generator.writeObject(new SamplesForMetricAndSource(source, eventCategory, metric, samples));
        }
    }
}

From source file:org.pentaho.metaverse.impl.model.kettle.json.JobMetaJsonSerializer.java

@Override
protected void serializeSteps(JobMeta meta, JsonGenerator json) throws IOException {
    json.writeArrayFieldStart(JSON_PROPERTY_STEPS);
    int numberOfEntries = meta.nrJobEntries();
    for (int i = 0; i < numberOfEntries; i++) {
        JobEntryCopy jobEntry = meta.getJobEntry(i);
        LineageRepository repo = getLineageRepository();
        ObjectId jobId = meta.getObjectId() == null ? new StringObjectId(meta.getName()) : meta.getObjectId();
        ObjectId entryId = jobEntry.getObjectId() == null ? new StringObjectId(jobEntry.getName())
                : jobEntry.getObjectId();

        JobEntryInterface jobEntryInterface = jobEntry.getEntry();
        JobEntryBase jobEntryBase = getJobEntryBase(jobEntryInterface);
        Job job = new Job(null, meta);
        jobEntryBase.setParentJob(job);/*from  w w w .java  2  s. c  o  m*/
        jobEntryInterface.setObjectId(entryId);
        try {
            jobEntryInterface.saveRep(repo, null, jobId);
        } catch (KettleException e) {
            LOGGER.warn(Messages.getString("INFO.Serialization.Trans.Step", jobEntry.getName()), e);
        }
        json.writeObject(jobEntryBase);
    }
    json.writeEndArray();
}

From source file:io.gravitee.definition.jackson.datatype.api.ser.ApiSerializer.java

@Override
public void serialize(Api api, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    jgen.writeStartObject();/*w  w  w . ja  v a  2s. c  o m*/
    jgen.writeStringField("id", api.getId());
    jgen.writeStringField("name", api.getName());
    jgen.writeObjectField("version", api.getVersion());

    if (api.getProxy() != null) {
        jgen.writeObjectField("proxy", api.getProxy());
    }

    if (api.getPaths() != null) {
        jgen.writeObjectFieldStart("paths");
        api.getPaths().forEach((s, path) -> {
            try {
                jgen.writeObjectField(s, path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        jgen.writeEndObject();
    }

    if (api.getServices() != null && !api.getServices().isEmpty()) {
        jgen.writeObjectField("services", api.getServices());
    }

    if (api.getResources() != null && !api.getResources().isEmpty()) {
        jgen.writeArrayFieldStart("resources");
        for (Resource resource : api.getResources()) {
            jgen.writeObject(resource);
        }
        jgen.writeEndArray();
    }

    if (api.getProperties() != null) {
        jgen.writeObjectFieldStart("properties");
        api.getProperties().forEach((s, property) -> {
            try {
                jgen.writeObjectField(s, property);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        jgen.writeEndObject();
    }

    if (api.getTags() != null && !api.getTags().isEmpty()) {
        jgen.writeArrayFieldStart("tags");
        api.getTags().forEach(tag -> {
            try {
                jgen.writeObject(tag);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        jgen.writeEndArray();
    }

    jgen.writeEndObject();
}

From source file:org.pentaho.metaverse.impl.model.kettle.json.AbstractStepMetaJsonSerializer.java

protected void writeExternalResources(T meta, JsonGenerator json, SerializerProvider serializerProvider)
        throws IOException, JsonGenerationException {
    Set<Class<?>> metaClassSet = new HashSet<Class<?>>(1);
    metaClassSet.add(meta.getClass());/*  w w w  . j a va2 s. c  o  m*/
    IStepExternalResourceConsumerProvider stepExternalResourceConsumerProvider = getStepExternalResourceConsumerProvider();

    List<IStepExternalResourceConsumer> resourceConsumers = null;
    if (stepExternalResourceConsumerProvider != null) {
        resourceConsumers = stepExternalResourceConsumerProvider.getExternalResourceConsumers(metaClassSet);
    }

    json.writeArrayFieldStart(JSON_PROPERTY_EXTERNAL_RESOURCES);
    if (resourceConsumers != null) {
        for (IStepExternalResourceConsumer resourceConsumer : resourceConsumers) {

            Collection<IExternalResourceInfo> infos = resourceConsumer.getResourcesFromMeta(meta);
            for (IExternalResourceInfo info : infos) {
                json.writeObject(info);
            }
        }
    }
    json.writeEndArray();
}

From source file:com.basho.riak.client.api.commands.mapreduce.MapReduce.java

/**
 * Creates the JSON string of the M/R job for submitting to the client
 * <p/>//from ww  w.j a va 2  s . co  m
 * Uses Jackson to write out the JSON string. I'm not very happy with this method, it is a candidate for change.
 * <p/>
 * TODO re-evaluate this method, look for something smaller and more elegant.
 *
 * @return a String of JSON
 * @throws RiakException if, for some reason, we can't create a JSON string.
 */
String writeSpec() throws RiakException {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        JsonGenerator jg = new JsonFactory().createGenerator(out, JsonEncoding.UTF8);

        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule specModule = new SimpleModule("SpecModule", Version.unknownVersion());
        specModule.addSerializer(LinkPhase.class, new LinkPhaseSerializer());
        specModule.addSerializer(FunctionPhase.class, new FunctionPhaseSerializer());
        specModule.addSerializer(BucketInput.class, new BucketInputSerializer());
        specModule.addSerializer(SearchInput.class, new SearchInputSerializer());
        specModule.addSerializer(BucketKeyInput.class, new BucketKeyInputSerializer());
        specModule.addSerializer(IndexInput.class, new IndexInputSerializer());
        objectMapper.registerModule(specModule);

        jg.setCodec(objectMapper);

        List<MapReducePhase> phases = spec.getPhases();
        phases.get(phases.size() - 1).setKeep(true);
        jg.writeObject(spec);

        jg.flush();

        return out.toString("UTF8");

    } catch (IOException e) {
        throw new RiakException(e);
    }
}

From source file:org.gvnix.web.json.BindingResultSerializer.java

/**
 * {@inheritDoc}/*from w w w. ja v  a2 s.c om*/
 */
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {

    try {
        // Cast to BindingResult
        BindingResult result = (BindingResult) value;

        // Create the result map
        Map<String, Object> allErrorsMessages = new HashMap<String, Object>();

        // Get field errors
        List<FieldError> fieldErrors = result.getFieldErrors();
        if (fieldErrors.isEmpty()) {
            // Nothing to do
            jgen.writeNull();
            return;
        }

        // Check if target type is an array or a bean
        @SuppressWarnings("rawtypes")
        Class targetClass = result.getTarget().getClass();
        if (targetClass.isArray() || Collection.class.isAssignableFrom(targetClass)) {
            loadListErrors(result.getFieldErrors(), allErrorsMessages);
        } else {
            loadObjectErrors(result.getFieldErrors(), allErrorsMessages);
        }

        jgen.writeObject(allErrorsMessages);
    } catch (JsonProcessingException e) {
        LOGGER.warn(ERROR_WRITTING_BINDING, e);
        throw e;
    } catch (IOException e) {
        LOGGER.warn(ERROR_WRITTING_BINDING, e);
        throw e;
    } catch (Exception e) {
        LOGGER.warn(ERROR_WRITTING_BINDING, e);
        throw new IOException(ERROR_WRITTING_BINDING, e);
    }

}

From source file:com.zenesis.qx.remote.ProxyMethod.java

@Override
public void serialize(JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
    jgen.writeStartObject();/*w ww  . ja va 2s  .c o m*/

    // Write the return type
    Class clazz = arrayType != null ? arrayType : method.getReturnType();
    if (Proxied.class.isAssignableFrom(clazz)) {
        ProxyType type = ProxyTypeManager.INSTANCE.getProxyType(clazz);
        jgen.writeObjectField("returnType", type);
    } else if (isMap) {
        jgen.writeBooleanField("map", true);
    }
    if (cacheResult)
        jgen.writeBooleanField("cacheResult", true);
    if (staticMethod)
        jgen.writeBooleanField("staticMethod", true);

    // Whether to wrap the return
    if (array != null)
        jgen.writeObjectField("returnArray", array.toString().toLowerCase());

    // The parameters - if any are Proxied objects, we need to write their class
    Class[] parameters = method.getParameterTypes();
    if (parameters.length > 0) {
        jgen.writeArrayFieldStart("parameters");
        for (int i = 0; i < parameters.length; i++) {
            if (Proxied.class.isAssignableFrom(parameters[i]))
                jgen.writeObject(ProxyTypeManager.INSTANCE.getProxyType(parameters[i]));
            else
                jgen.writeNull();
        }
        jgen.writeEndArray();
    }

    jgen.writeEndObject();
}