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

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

Introduction

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

Prototype

public void writeValue(Writer w, Object value)
        throws IOException, JsonGenerationException, JsonMappingException 

Source Link

Document

Method that can be used to serialize any Java value as JSON output, using Writer provided.

Usage

From source file:org.usd.edu.btl.cli.ConvertBld.java

public void toBets(String inputS, String output) {
    ObjectMapper bldMapper = new ObjectMapper(); //create new Jackson Mapper
    File input = new File(inputS);

    BLDV1 bldTool; //create new seqTool
    ObjectWriter oW = bldMapper.writer().withDefaultPrettyPrinter();
    try {/*from w  w  w.j a v a2s .  c  o m*/
        //map input json files to iplant class
        bldTool = bldMapper.readValue(input, BLDV1.class);
        //            String seqInputJson = oW.writeValueAsString(bldTool); //write Json as String
        //            System.out.println("=====BLD INPUT FILE =====");
        //            System.out.println(seqInputJson);

        BETSV1 betsOutput = BLDConverter.toBETS(bldTool);
        String betsOutputJson = oW.writeValueAsString(betsOutput); //write Json as String
        if (output == null) {
            /*===============PRINT JSON TO CONSOLE AND FILES =================== */
            System.err.println("************************************************\n"
                    + "*********PRINTING OUT FIRST CONVERSION************\n"
                    + "--------------Seq --> BETS--------------\n"
                    + "************************************************\n");
            //print objects as Json using jackson

            System.err.println("=== BLD TO BETS JSON - OUTPUT === \n");
            System.out.println(betsOutputJson);
        } else {
            System.err.println("Writing to file...");
            //write to files
            oW.writeValue(new File(output), betsOutput);
            System.err.println(output + " has been created successfully");
            System.exit(1);
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

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

private void setupPlainRequest(final Object request, final ObjectWriter finalWriter, HttpPost post) {
    // just posting json.
    post.addHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
    post.setEntity(new AbstractHttpEntity() {
        @Override//from www .j  a v  a2s .  c  o m
        public boolean isRepeatable() {
            return false;
        }

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

        @Override
        public InputStream getContent() throws IOException, UnsupportedOperationException {
            throw new UnsupportedOperationException();
        }

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

        @Override
        public boolean isStreaming() {
            return false;
        }
    });
}

From source file:com.github.jknack.handlebars.Jackson2Helper.java

@Override
public CharSequence apply(final Object context, final Options options) throws IOException {
    if (context == null) {
        return options.hash("default", "");
    }//from   w w  w  .  j a  va2  s  . com
    String viewName = options.hash("view", "");
    JsonGenerator generator = null;
    try {
        final ObjectWriter writer;
        // do we need to use a view?
        if (!isEmpty(viewName)) {
            Class<?> viewClass = alias.get(viewName);
            if (viewClass == null) {
                viewClass = getClass().getClassLoader().loadClass(viewName);
            }
            writer = mapper.writerWithView(viewClass);
        } else {
            writer = mapper.writer();
        }
        JsonFactory jsonFactory = mapper.getFactory();

        SegmentedStringWriter output = new SegmentedStringWriter(jsonFactory._getBufferRecycler());

        // creates a json generator.
        generator = jsonFactory.createJsonGenerator(output);

        Boolean escapeHtml = options.hash("escapeHTML", Boolean.FALSE);
        // do we need to escape html?
        if (escapeHtml) {
            generator.setCharacterEscapes(new HtmlEscapes());
        }

        Boolean pretty = options.hash("pretty", Boolean.FALSE);

        // write the JSON output.
        if (pretty) {
            writer.withDefaultPrettyPrinter().writeValue(generator, context);
        } else {
            writer.writeValue(generator, context);
        }

        generator.close();

        return new Handlebars.SafeString(output.getAndClear());
    } catch (ClassNotFoundException ex) {
        throw new IllegalArgumentException(viewName, ex);
    } finally {
        if (generator != null && !generator.isClosed()) {
            generator.close();
        }
    }
}

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//from  w ww.j a  v a  2  s . c o m
                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:com.basistech.rosette.api.RosetteAPI.java

private void setupMultipartRequest(final DocumentRequest request, final ObjectWriter finalWriter,
        HttpPost post) {//  w  w w .j  a v  a 2s . com

    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
                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());

    partBuilder = FormBodyPartBuilder.create("content",
            new InputStreamBody(request.getContentBytes(), ContentType.parse(request.getContentType())));
    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:com.rcv.ResultsWriter.java

private void generateSummaryJson(Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct,
        String outputPath) throws IOException {

    // mapper converts java objects to json
    ObjectMapper mapper = new ObjectMapper();
    // set mapper to order keys alphabetically for more legible output
    mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
    // create a module to contain a serializer for BigDecimal serialization
    SimpleModule module = new SimpleModule();
    module.addSerializer(BigDecimal.class, new ToStringSerializer());
    // attach serializer to mapper
    mapper.registerModule(module);//from www .j  a v a 2  s .  co  m

    // jsonWriter writes those object to disk
    ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter());
    // jsonPath for output json summary
    String jsonPath = outputPath + ".json";
    // log output location
    Logger.log(Level.INFO, "Generating summary JSON file: %s...", jsonPath);
    // outFile is the target file
    File outFile = new File(jsonPath);

    // root outputJson dict will have two entries:
    // results - vote totals, transfers, and candidates elected / eliminated
    // config - global config into
    HashMap<String, Object> outputJson = new HashMap<>();
    // config will contain contest configuration info
    HashMap<String, Object> configData = new HashMap<>();
    // add config header info
    configData.put("contest", config.getContestName());
    configData.put("jurisdiction", config.getContestJurisdiction());
    configData.put("office", config.getContestOffice());
    configData.put("date", config.getContestDate());
    configData.put("threshold", winningThreshold);
    if (precinct != null && !precinct.isEmpty()) {
        configData.put("precinct", precinct);
    }
    // results will be a list of round data objects
    ArrayList<Object> results = new ArrayList<>();
    // for each round create objects for json serialization
    for (int round = 1; round <= numRounds; round++) {
        // container for all json data this round:
        HashMap<String, Object> roundData = new HashMap<>();
        // add round number (this is implied by the ordering but for debugging we are explicit)
        roundData.put("round", round);
        // add actions if this is not a precinct summary
        if (precinct == null || precinct.isEmpty()) {
            // actions is a list of one or more action objects
            ArrayList<Object> actions = new ArrayList<>();
            addActionObjects("elected", roundToWinningCandidates.get(round), round, actions);
            // add any elimination actions
            addActionObjects("eliminated", roundToEliminatedCandidates.get(round), round, actions);
            // add action objects
            roundData.put("tallyResults", actions);
        }
        // add tally object
        roundData.put("tally", updateCandidateNamesInTally(roundTallies.get(round)));
        // add roundData to results list
        results.add(roundData);
    }
    // add config data to root object
    outputJson.put("config", configData);
    // add results to root object
    outputJson.put("results", results);
    // write results to disk
    try {
        jsonWriter.writeValue(outFile, outputJson);
    } catch (IOException exception) {
        Logger.log(Level.SEVERE, "Error writing to JSON file: %s\n%s", jsonPath, exception.toString());
        throw exception;
    }
}

From source file:nl.knaw.huygens.timbuctoo.rest.providers.EntityListHTMLProvider.java

@Override
public void writeTo(List<? extends Entity> docs, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream out) throws IOException {
    helper.writeHeader(out, getTitle(docs));

    JsonGenerator jgen = helper.getGenerator(out);
    ObjectWriter writer = helper.getObjectWriter(annotations);
    for (Entity doc : docs) {
        helper.write(out, "<h2>");
        helper.write(out, getDocTitle(doc));
        helper.write(out, "</h2>");
        writer.writeValue(jgen, doc);
    }// w w w .  ja v a  2 s  .  co  m

    helper.writeFooter(out);
}

From source file:org.craftercms.commons.jackson.mvc.CrafterJackson2MessageConverter.java

@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator = this.getObjectMapper().getFactory().createGenerator(outputMessage.getBody(),
            encoding);/*from w w w .j  a v  a 2  s.  c o m*/
    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.getObjectMapper().isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    try {
        if (this.jsonPrefix != null) {
            jsonGenerator.writeRaw(this.jsonPrefix);
        }

        runAnnotations(object);

        ObjectWriter writer = this.getObjectMapper().writer(filter);
        writer.writeValue(jsonGenerator, object);
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}

From source file:org.lenskit.specs.SpecUtils.java

/**
 * Write a specification to a file.//from  w w  w.j  a va 2 s.  c  om
 * @param spec The specification.
 * @param file The file to write to.
 * @throws IOException if there is an error writing the specification.
 */
public static void write(Object spec, Path file) throws IOException {
    ObjectWriter writer = createMapper().writer().with(SerializationFeature.INDENT_OUTPUT);
    writer.writeValue(file.toFile(), spec);
}

From source file:uk.gov.gchq.gaffer.jsonserialisation.JSONSerialiser.java

/**
 * Serialises an object using the provided json generator.
 *
 * @param object          the object to be serialised and written to file
 * @param jsonGenerator   the {@link com.fasterxml.jackson.core.JsonGenerator} to use to write the object to
 * @param prettyPrint     true if the object should be serialised with pretty printing
 * @param fieldsToExclude optional property names to exclude from the json
 * @throws SerialisationException if the object fails to serialise
 *///from ww w .  jav  a  2s. com
public void serialise(final Object object, final JsonGenerator jsonGenerator, final boolean prettyPrint,
        final String... fieldsToExclude) throws SerialisationException {
    if (prettyPrint) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    final ObjectWriter writer = mapper.writer(getFilterProvider(fieldsToExclude));
    try {
        writer.writeValue(jsonGenerator, object);
    } catch (final IOException e) {
        throw new SerialisationException("Failed to serialise object to json: " + e.getMessage(), e);
    }
}