Example usage for com.fasterxml.jackson.databind ObjectWriter writeValueAsBytes

List of usage examples for com.fasterxml.jackson.databind ObjectWriter writeValueAsBytes

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectWriter writeValueAsBytes.

Prototype

@SuppressWarnings("resource")
public byte[] writeValueAsBytes(Object value) throws JsonProcessingException 

Source Link

Document

Method that can be used to serialize any Java value as a byte array.

Usage

From source file:com.auth0.api.internal.JsonRequestBodyBuilder.java

public static RequestBody createBody(Object pojo, ObjectWriter writer) throws RequestBodyBuildException {
    try {/*  w ww.ja  v  a 2 s  .  c om*/
        return RequestBody.create(JSON, writer.writeValueAsBytes(pojo));
    } catch (JsonProcessingException e) {
        throw new RequestBodyBuildException("Failed to convert " + pojo.getClass().getName() + " to JSON", e);
    }
}

From source file:com.spotify.apollo.route.JsonSerializerMiddlewares.java

private static <T> ByteString serialize(ObjectWriter objectWriter, T object) {
    try {/*from   ww  w .  ja  v a  2  s.c  o m*/
        return ByteString.of(objectWriter.writeValueAsBytes(object));
    } catch (JsonProcessingException e) {
        throw Throwables.propagate(e);
    }
}

From source file:io.syndesis.rest.v1.state.ClientSideState.java

static byte[] serialize(final Object value) {
    final ObjectWriter writer = MAPPER.writerFor(value.getClass());

    try {//from  www  .j a va  2s . c o  m
        return writer.writeValueAsBytes(value);
    } catch (final JsonProcessingException e) {
        throw new IllegalArgumentException("Unable to serialize given value: " + value, e);
    }
}

From source file:com.couchbase.lite.internal.Body.java

public byte[] getPrettyJson() {
    Object properties = getObject();
    if (properties != null) {
        ObjectWriter writer = Manager.getObjectMapper().writerWithDefaultPrettyPrinter();
        try {/*from w ww . java2s  .c o m*/
            json = writer.writeValueAsBytes(properties);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return getJson();
}

From source file:ratpack.jackson.internal.DefaultJsonRenderer.java

@Override
public void render(final Context context, final JsonRender<?> object) {
    context.respond(context.getByContent().json(new Runnable() {
        @Override/*from   w ww .  j  a  v  a 2  s  .c o m*/
        public void run() {
            ObjectWriter writer = object.getObjectWriter();
            if (writer == null) {
                writer = defaultObjectWriter;
            }

            byte[] bytes;
            try {
                bytes = writer.writeValueAsBytes(object.getObject());
            } catch (JsonProcessingException e) {
                context.error(e);
                return;
            }

            context.getResponse().send(bytes);
        }
    }));
}

From source file:com.basistech.rosette.api.HttpRosetteAPI.java

private void setupMultipartRequest(final Request request, final ObjectWriter finalWriter, HttpPost post)
        throws IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMimeSubtype("mixed");
    builder.setMode(HttpMultipartMode.STRICT);

    FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("request",
            // Make sure we're not mislead by someone who puts a charset into the mime type.
            new AbstractContentBody(ContentType.parse(ContentType.APPLICATION_JSON.getMimeType())) {
                @Override//w  w  w . ja  v  a  2  s  . com
                public String getFilename() {
                    return null;
                }

                @Override
                public void writeTo(OutputStream out) throws IOException {
                    finalWriter.writeValue(out, request);
                }

                @Override
                public String getTransferEncoding() {
                    return MIME.ENC_BINARY;
                }

                @Override
                public long getContentLength() {
                    return -1;
                }
            });

    // Either one of 'name=' or 'Content-ID' would be enough.
    partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"request\"");
    partBuilder.setField("Content-ID", "request");

    builder.addPart(partBuilder.build());

    AbstractContentBody insBody;
    if (request instanceof DocumentRequest) {
        DocumentRequest docReq = (DocumentRequest) request;
        insBody = new InputStreamBody(docReq.getContentBytes(), ContentType.parse(docReq.getContentType()));
    } else if (request instanceof AdmRequest) {
        //TODO: smile?
        AdmRequest admReq = (AdmRequest) request;
        ObjectWriter writer = mapper.writer().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
        byte[] json = writer.writeValueAsBytes(admReq.getText());
        insBody = new ByteArrayBody(json, ContentType.parse(AdmRequest.ADM_CONTENT_TYPE), null);
    } else {
        throw new UnsupportedOperationException("Unsupported request type for multipart processing");
    }
    partBuilder = FormBodyPartBuilder.create("content", insBody);
    partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"content\"");
    partBuilder.setField("Content-ID", "content");
    builder.addPart(partBuilder.build());
    builder.setCharset(StandardCharsets.UTF_8);
    HttpEntity entity = builder.build();
    post.setEntity(entity);
}

From source file:org.opencb.cellbase.app.cli.VariantAnnotationCommandExecutor.java

private void indexPopulationFrequencies(RocksDB db) {
    ObjectMapper jsonObjectMapper = new ObjectMapper();
    jsonObjectMapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true);
    ObjectWriter jsonObjectWriter = jsonObjectMapper.writer();

    try {/*from w  w w  .j a v  a2  s.c  om*/
        DataReader<Variant> dataReader = new JsonVariantReader(populationFrequenciesFile.toString());
        dataReader.open();
        dataReader.pre();
        int lineCounter = 0;
        List<Variant> variant = dataReader.read();
        while (variant != null) {
            db.put(VariantAnnotationUtils.buildVariantId(variant.get(0).getChromosome(),
                    variant.get(0).getStart(), variant.get(0).getReference(), variant.get(0).getAlternate())
                    .getBytes(), jsonObjectWriter.writeValueAsBytes(variant.get(0).getImpl()));
            lineCounter++;
            if (lineCounter % 100000 == 0) {
                logger.info("{} lines indexed", lineCounter);
            }
            variant = dataReader.read();
        }
        dataReader.post();
        dataReader.close();
    } catch (IOException | RocksDBException e) {
        e.printStackTrace();
    }
}

From source file:org.opencb.cellbase.app.cli.VariantAnnotationCommandExecutor.java

private void indexCustomVcfFile(int customFileNumber, RocksDB db) {
    ObjectMapper jsonObjectMapper = new ObjectMapper();
    ObjectWriter jsonObjectWriter = jsonObjectMapper.writer();

    try {//from   w w w .ja  v a2 s .  c o  m
        VCFFileReader vcfFileReader = new VCFFileReader(customFiles.get(customFileNumber).toFile(), false);
        Iterator<VariantContext> iterator = vcfFileReader.iterator();
        VariantContextToVariantConverter converter = new VariantContextToVariantConverter("", "",
                vcfFileReader.getFileHeader().getSampleNamesInOrder());
        VariantNormalizer normalizer = new VariantNormalizer(true, false, true);
        int lineCounter = 0;
        while (iterator.hasNext()) {
            VariantContext variantContext = iterator.next();
            // Reference positions will not be indexed
            if (variantContext.getAlternateAlleles().size() > 0) {
                List<Variant> variantList = normalizer
                        .normalize(converter.apply(Collections.singletonList(variantContext)), true);
                for (Variant variant : variantList) {
                    db.put((variant.getChromosome() + "_" + variant.getStart() + "_" + variant.getReference()
                            + "_" + variant.getAlternate()).getBytes(),
                            jsonObjectWriter.writeValueAsBytes(parseInfoAttributes(variant, customFileNumber)));
                }
            }
            lineCounter++;
            if (lineCounter % 100000 == 0) {
                logger.info("{} lines indexed", lineCounter);
            }
        }
        vcfFileReader.close();
    } catch (IOException | RocksDBException | NonStandardCompliantSampleField e) {
        e.printStackTrace();
        System.exit(1);
    }
}