Example usage for com.fasterxml.jackson.databind ObjectMapper writer

List of usage examples for com.fasterxml.jackson.databind ObjectMapper writer

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper writer.

Prototype

public ObjectWriter writer(ContextAttributes attrs) 

Source Link

Document

Factory method for constructing ObjectWriter that will use specified default attributes.

Usage

From source file:com.github.shredder121.gh_event_api.handler.AbstractHandlerTest.java

public String minimize(final InputStream stream) throws IOException {
    ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().build();
    Map<String, Object> content = mapper.reader().forType(Map.class).readValue(stream);
    return mapper.writer(new MinimalPrettyPrinter(null/*minimizes*/)).writeValueAsString(content);
}

From source file:org.osiam.resources.helper.AttributesRemovalHelper.java

private ObjectWriter getObjectWriter(ObjectMapper mapper, String[] fieldsToReturn) {

    if (fieldsToReturn.length != 0) {
        mapper.addMixInAnnotations(Object.class, PropertyFilterMixIn.class);

        HashSet<String> givenFields = new HashSet<>();
        givenFields.add("schemas");
        Collections.addAll(givenFields, fieldsToReturn);
        String[] finalFieldsToReturn = givenFields.toArray(new String[givenFields.size()]);

        FilterProvider filters = new SimpleFilterProvider().addFilter("filter properties by name",
                SimpleBeanPropertyFilter.filterOutAllExcept(finalFieldsToReturn));
        return mapper.writer(filters);
    }/*from  w  w w .  ja  v  a  2  s.c o m*/
    return mapper.writer();
}

From source file:org.wrml.runtime.format.application.vnd.wrml.design.schema.SchemaDesignFormatter.java

@Override
public void writeModel(final OutputStream out, final Model model, final ModelWriteOptions writeOptions)
        throws ModelWritingException {

    if (!(model instanceof Schema)) {
        throw new ModelWritingException("The \"" + getFormatUri() + "\" format cannot write the model.", null,
                this);
    }/*from w w w.  ja v  a2s .  c o  m*/

    final Schema schema = (Schema) model;
    final ObjectNode rootNode;
    final ObjectWriter objectWriter;

    try {

        // TODO: Should this ObjectMapper be stored in a field?
        final ObjectMapper objectMapper = new ObjectMapper();
        rootNode = createSchemaDesignObjectNode(objectMapper, schema);
        objectWriter = objectMapper.writer(new DefaultPrettyPrinter());
        objectWriter.writeValue(out, rootNode);
    } catch (final Exception e) {
        throw new ModelWritingException(getClass().getSimpleName()
                + " encounter an error while attempting to write a SchemaDesign.  Message: " + e.getMessage(),
                null, this);

    }

}

From source file:org.osiam.resource_server.resources.helper.AttributesRemovalHelper.java

private ObjectWriter getObjectWriter(ObjectMapper mapper, String[] fieldsToReturn) {

    if (fieldsToReturn.length != 0) {
        mapper.addMixInAnnotations(Object.class, PropertyFilterMixIn.class);

        HashSet<String> givenFields = new HashSet<String>();
        givenFields.add("schemas");
        for (String field : fieldsToReturn) {
            givenFields.add(field);//from   w  ww .j a  v  a2  s. c  o  m
        }
        String[] finalFieldsToReturn = givenFields.toArray(new String[givenFields.size()]);

        FilterProvider filters = new SimpleFilterProvider().addFilter("filter properties by name",
                SimpleBeanPropertyFilter.filterOutAllExcept(finalFieldsToReturn));
        return mapper.writer(filters);
    }
    return mapper.writer();
}

From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java

private static void createPassJSONFile(final PKPass pass, final File tempPassDir,
        final ObjectMapper jsonObjectMapper) throws IOException, JsonGenerationException, JsonMappingException {
    File passJSONFile = new File(tempPassDir.getAbsolutePath() + File.separator + PASS_JSON_FILE_NAME);

    SimpleFilterProvider filters = new SimpleFilterProvider();

    // haven't found out, how to stack filters. Copying the validation one for now.
    filters.addFilter("validateFilter",
            SimpleBeanPropertyFilter.serializeAllExcept("valid", "validationErrors"));
    filters.addFilter("pkPassFilter", SimpleBeanPropertyFilter.serializeAllExcept("valid", "validationErrors",
            "foregroundColorAsObject", "backgroundColorAsObject", "labelColorAsObject"));
    filters.addFilter("barcodeFilter", SimpleBeanPropertyFilter.serializeAllExcept("valid", "validationErrors",
            "messageEncodingAsString"));
    filters.addFilter("charsetFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name"));
    jsonObjectMapper.setSerializationInclusion(Include.NON_NULL);
    jsonObjectMapper.addMixInAnnotations(Object.class, ValidateFilterMixIn.class);
    jsonObjectMapper.addMixInAnnotations(PKPass.class, PkPassFilterMixIn.class);
    jsonObjectMapper.addMixInAnnotations(PKBarcode.class, BarcodeFilterMixIn.class);
    jsonObjectMapper.addMixInAnnotations(Charset.class, CharsetFilterMixIn.class);

    ObjectWriter objectWriter = jsonObjectMapper.writer(filters);
    objectWriter.writeValue(passJSONFile, pass);
}

From source file:com.groupon.odo.controllers.PathController.java

@RequestMapping(value = "/api/path/test", method = RequestMethod.GET)
public @ResponseBody String testPath(@RequestParam String url, @RequestParam String profileIdentifier,
        @RequestParam Integer requestType) throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);

    List<EndpointOverride> trySelectedRequestPaths = PathOverrideService.getInstance().getSelectedPaths(
            Constants.OVERRIDE_TYPE_REQUEST, ClientService.getInstance().findClient("-1", profileId),
            ProfileService.getInstance().findProfile(profileId), url, requestType, true);

    HashMap<String, Object> jqReturn = Utils.getJQGridJSON(trySelectedRequestPaths, "paths");

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class);
    String[] ignorableFieldNames = { "possibleEndpoints", "enabledEndpoints" };
    FilterProvider filters = new SimpleFilterProvider().addFilter(
            "Filter properties from the PathController GET",
            SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

    ObjectWriter writer = objectMapper.writer(filters);

    return writer.writeValueAsString(jqReturn);
}

From source file:com.groupon.odo.controllers.PathController.java

@SuppressWarnings("deprecation")
@RequestMapping(value = "/api/path", method = RequestMethod.GET)
public @ResponseBody String getPathsForProfile(Model model, String profileIdentifier,
        @RequestParam(value = "typeFilter[]", required = false) String[] typeFilter,
        @RequestParam(value = "clientUUID", defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID)
        throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);
    List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileId, clientUUID,
            typeFilter);/*  w  ww. j  a  v  a 2  s  .c  o  m*/

    HashMap<String, Object> jqReturn = Utils.getJQGridJSON(paths, "paths");

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class);
    String[] ignorableFieldNames = { "possibleEndpoints", "enabledEndpoints" };
    FilterProvider filters = new SimpleFilterProvider().addFilter(
            "Filter properties from the PathController GET",
            SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

    ObjectWriter writer = objectMapper.writer(filters);

    return writer.writeValueAsString(jqReturn);
}

From source file:com.amazon.feeds.SampleFeedGenerator.java

/**
 * The method for generating sample feeds.
 *
 * @param format The class containing the format specifications.
 * @param items The number of items to generate.
 * @param ext File extension.//from w  w  w.  jav  a2 s  .  c o  m
 */
public void createSampleFeed(IFeedFormat format, int items, String ext) throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    mapper.getFactory().setCharacterEscapes(format.getEscapeRules());

    // create output file
    String out = format.getFeedFormat() + "-" + items + "." + ext;
    // TODO: add XML support

    File outFile = new File(SAMPLE_PATH, out);
    if (!outFile.exists()) {
        outFile.getParentFile().mkdirs();
    }

    // populate sample feed
    System.out.println("Generating " + items + (items == 1 ? " item" : " items") + " for "
            + format.getProvider() + " feed at " + outFile.getAbsolutePath());
    format.populate(items);

    // write JSON to file
    if (format.usePrettyPrint()) {

        DefaultPrettyPrinter.Indenter indenter = new DefaultIndenter("   ", DefaultIndenter.SYS_LF);
        DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
        printer.indentObjectsWith(indenter);
        printer.indentArraysWith(indenter);
        mapper.writer(printer).writeValue(outFile, format);
    } else {
        mapper.writeValue(outFile, format);
    }
}

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  w  w w.  j a  v  a  2  s.c o 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:de.brendamour.jpasskit.signing.PKAbstractSIgningUtil.java

protected ObjectWriter configureObjectMapper(final ObjectMapper jsonObjectMapper) {
    jsonObjectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    jsonObjectMapper.setDateFormat(new ISO8601DateFormat());

    SimpleFilterProvider filters = new SimpleFilterProvider();

    // haven't found out, how to stack filters. Copying the validation one for now.
    filters.addFilter("validateFilter",
            SimpleBeanPropertyFilter.serializeAllExcept("valid", "validationErrors"));
    filters.addFilter("pkPassFilter", SimpleBeanPropertyFilter.serializeAllExcept("valid", "validationErrors",
            "foregroundColorAsObject", "backgroundColorAsObject", "labelColorAsObject", "passThatWasSet"));
    filters.addFilter("barcodeFilter", SimpleBeanPropertyFilter.serializeAllExcept("valid", "validationErrors",
            "messageEncodingAsString"));
    filters.addFilter("charsetFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name"));
    jsonObjectMapper.setSerializationInclusion(Include.NON_NULL);
    jsonObjectMapper.addMixIn(Object.class, ValidateFilterMixIn.class);
    jsonObjectMapper.addMixIn(PKPass.class, PkPassFilterMixIn.class);
    jsonObjectMapper.addMixIn(PKBarcode.class, BarcodeFilterMixIn.class);
    jsonObjectMapper.addMixIn(Charset.class, CharsetFilterMixIn.class);
    return jsonObjectMapper.writer(filters);
}