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

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

Introduction

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

Prototype

public ObjectWriter writerWithView(Class<?> serializationView) 

Source Link

Document

Factory method for constructing ObjectWriter that will serialize objects using specified JSON View (filter).

Usage

From source file:com.twentyn.patentScorer.ScoreMerger.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();/*w w  w  .  java  2  s . com*/
    Options opts = new Options();
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());

    opts.addOption(Option.builder("r").longOpt("results").required().hasArg()
            .desc("A directory of search results to read").build());
    opts.addOption(Option.builder("s").longOpt("scores").required().hasArg()
            .desc("A directory of patent classification scores to read").build());
    opts.addOption(Option.builder("o").longOpt("output").required().hasArg()
            .desc("The output file where results will be written.").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }
    File scoresDirectory = new File(cmdLine.getOptionValue("scores"));
    if (cmdLine.getOptionValue("scores") == null || !scoresDirectory.isDirectory()) {
        LOGGER.error("Not a directory of score files: " + cmdLine.getOptionValue("scores"));
    }

    File resultsDirectory = new File(cmdLine.getOptionValue("results"));
    if (cmdLine.getOptionValue("results") == null || !resultsDirectory.isDirectory()) {
        LOGGER.error("Not a directory of results files: " + cmdLine.getOptionValue("results"));
    }

    FileWriter outputWriter = new FileWriter(cmdLine.getOptionValue("output"));

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

    FilenameFilter jsonFilter = new FilenameFilter() {
        public final Pattern JSON_PATTERN = Pattern.compile("\\.json$");

        public boolean accept(File dir, String name) {
            return JSON_PATTERN.matcher(name).find();
        }
    };

    Map<String, PatentScorer.ClassificationResult> scores = new HashMap<>();
    LOGGER.info("Reading scores from directory at " + scoresDirectory.getAbsolutePath());
    for (File scoreFile : scoresDirectory.listFiles(jsonFilter)) {
        BufferedReader reader = new BufferedReader(new FileReader(scoreFile));
        int count = 0;
        String line;
        while ((line = reader.readLine()) != null) {
            PatentScorer.ClassificationResult res = objectMapper.readValue(line,
                    PatentScorer.ClassificationResult.class);
            scores.put(res.docId, res);
            count++;
        }
        LOGGER.info("Read " + count + " scores from " + scoreFile.getAbsolutePath());
    }

    Map<String, List<DocumentSearch.SearchResult>> synonymsToResults = new HashMap<>();
    Map<String, List<DocumentSearch.SearchResult>> inchisToResults = new HashMap<>();
    LOGGER.info("Reading results from directory at " + resultsDirectory);
    // With help from http://stackoverflow.com/questions/6846244/jackson-and-generic-type-reference.
    JavaType resultsType = objectMapper.getTypeFactory().constructCollectionType(List.class,
            DocumentSearch.SearchResult.class);

    List<File> resultsFiles = Arrays.asList(resultsDirectory.listFiles(jsonFilter));
    Collections.sort(resultsFiles, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    for (File resultsFile : resultsFiles) {
        BufferedReader reader = new BufferedReader(new FileReader(resultsFile));
        CharBuffer buffer = CharBuffer.allocate(Long.valueOf(resultsFile.length()).intValue());
        int bytesRead = reader.read(buffer);
        LOGGER.info("Read " + bytesRead + " bytes from " + resultsFile.getName() + " (length is "
                + resultsFile.length() + ")");
        List<DocumentSearch.SearchResult> results = objectMapper.readValue(new CharArrayReader(buffer.array()),
                resultsType);

        LOGGER.info("Read " + results.size() + " results from " + resultsFile.getAbsolutePath());

        int count = 0;
        for (DocumentSearch.SearchResult sres : results) {
            for (DocumentSearch.ResultDocument resDoc : sres.getResults()) {
                String docId = resDoc.getDocId();
                PatentScorer.ClassificationResult classificationResult = scores.get(docId);
                if (classificationResult == null) {
                    LOGGER.warn("No classification result found for " + docId);
                } else {
                    resDoc.setClassifierScore(classificationResult.getScore());
                }
            }
            if (!synonymsToResults.containsKey(sres.getSynonym())) {
                synonymsToResults.put(sres.getSynonym(), new ArrayList<DocumentSearch.SearchResult>());
            }
            synonymsToResults.get(sres.getSynonym()).add(sres);
            count++;
            if (count % 1000 == 0) {
                LOGGER.info("Processed " + count + " search result documents");
            }
        }
    }

    Comparator<DocumentSearch.ResultDocument> resultDocumentComparator = new Comparator<DocumentSearch.ResultDocument>() {
        @Override
        public int compare(DocumentSearch.ResultDocument o1, DocumentSearch.ResultDocument o2) {
            int cmp = o2.getClassifierScore().compareTo(o1.getClassifierScore());
            if (cmp != 0) {
                return cmp;
            }
            cmp = o2.getScore().compareTo(o1.getScore());
            return cmp;
        }
    };

    for (Map.Entry<String, List<DocumentSearch.SearchResult>> entry : synonymsToResults.entrySet()) {
        DocumentSearch.SearchResult newSearchRes = null;
        // Merge all result documents into a single search result.
        for (DocumentSearch.SearchResult sr : entry.getValue()) {
            if (newSearchRes == null) {
                newSearchRes = sr;
            } else {
                newSearchRes.getResults().addAll(sr.getResults());
            }
        }
        if (newSearchRes == null || newSearchRes.getResults() == null) {
            LOGGER.error("Search results for " + entry.getKey() + " are null.");
            continue;
        }
        Collections.sort(newSearchRes.getResults(), resultDocumentComparator);
        if (!inchisToResults.containsKey(newSearchRes.getInchi())) {
            inchisToResults.put(newSearchRes.getInchi(), new ArrayList<DocumentSearch.SearchResult>());
        }
        inchisToResults.get(newSearchRes.getInchi()).add(newSearchRes);
    }

    List<String> sortedKeys = new ArrayList<String>(inchisToResults.keySet());
    Collections.sort(sortedKeys);
    List<GroupedInchiResults> orderedResults = new ArrayList<>(sortedKeys.size());
    Comparator<DocumentSearch.SearchResult> synonymSorter = new Comparator<DocumentSearch.SearchResult>() {
        @Override
        public int compare(DocumentSearch.SearchResult o1, DocumentSearch.SearchResult o2) {
            return o1.getSynonym().compareTo(o2.getSynonym());
        }
    };
    for (String inchi : sortedKeys) {
        List<DocumentSearch.SearchResult> res = inchisToResults.get(inchi);
        Collections.sort(res, synonymSorter);
        orderedResults.add(new GroupedInchiResults(inchi, res));
    }

    objectMapper.writerWithView(Object.class).writeValue(outputWriter, orderedResults);
    outputWriter.close();
}

From source file:com.infinities.skyport.util.JsonUtil.java

public static String toJson(Object object, Class<? extends Views.Short> view) {
    ObjectMapper mapper = getObjectMapper();
    ObjectWriter writer = mapper.writerWithView(view).withDefaultPrettyPrinter();
    try {//from   w  w w. j a v a  2 s  .  c  o m
        if (object == null || "".equals(object)) {
            object = mapper.createObjectNode();
        }
        return writer.writeValueAsString(object);
    } catch (Exception e) {
        logger.error("json parsing failed", e);
        throw new RuntimeException(e);
    }
}

From source file:com.infinities.skyport.util.JsonUtil.java

public static String toJson(boolean insertResponseCode, String msg, Object object,
        Class<? extends Views.Short> view) {
    ObjectMapper mapper = getObjectMapper();
    ObjectWriter writer = mapper.writerWithView(view).withDefaultPrettyPrinter();
    JsonNode rootNode = mapper.createObjectNode();

    try {//  w  ww. j av  a 2  s . c om
        if (object == null || "".equals(object)) {
            object = mapper.createObjectNode();
        }

        String temp = writer.writeValueAsString(object);
        rootNode = mapper.readTree(temp);
    } catch (Exception e) {
        logger.error("json parsing failed", e);

    }

    ObjectNode root = getObjectMapper().createObjectNode();
    root.put(JsonConstants.STATUS, insertResponseCode ? 1 : 0).put(JsonConstants.MSG, msg)
            .put(JsonConstants._DATA, rootNode);

    try {
        return getObjectMapper().configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, false)
                .writeValueAsString(root);
    } catch (Exception e) {
        logger.error("json parsing failed", e);
        throw new RuntimeException(e);
    }
}

From source file:org.jongo.marshall.jackson.configuration.ViewWriterCallback.java

public ObjectWriter getWriter(ObjectMapper mapper, Object pojo) {
    return mapper.writerWithView(viewClass);
}

From source file:com.infinities.skyport.compute.entity.serializer.ShortSelfRecursiveSerializer.java

@Override
public void serialize(Serializable value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {

    ObjectMapper mapper = JsonUtil.getObjectMapper();

    ObjectWriter writer = mapper.writerWithView(Views.Short.class);
    StringWriter sw = new StringWriter();
    writer.writeValue(sw, value);/*from  www.  j av  a2s . co m*/

    JsonNode rootNode = mapper.readTree(sw.toString());

    jgen.writeObject(rootNode);

}

From source file:com.infinities.skyport.compute.entity.serializer.BasicSelfRecursiveSerializer.java

@Override
public void serialize(Collection<?> value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {

    ObjectMapper mapper = JsonUtil.getObjectMapper();

    ObjectWriter writer = mapper.writerWithView(Views.Basic.class);
    StringWriter sw = new StringWriter();
    writer.writeValue(sw, value);//w ww.  j  av  a  2 s .c  o  m

    JsonNode rootNode = mapper.readTree(sw.toString());

    jgen.writeObject(rootNode);

}

From source file:fr.esiea.esieaddress.controllers.crud.CrudContactCtrl.java

@Secured("ROLE_USER")
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
@ResponseBody/*  ww w.j a  v a2 s  .  c  om*/
public void getAll(HttpServletResponse servletResponse) throws ServiceException, DaoException, IOException {

    LOGGER.info("[Controller] Querying Contact list");
    /*
     * Make the list with only id, firstname, lastname, actif
     */
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.writerWithView(ContactView.LightView.class).writeValue(servletResponse.getOutputStream(),
            crudService.getAll());
}

From source file:com.blockwithme.lessobjects.schema.StructSchema.java

/** Instantiates a new struct envelope from Struct object. */
@SuppressWarnings("null")
public StructSchema(final Struct theStruct) {
    checkNotNull(theStruct);// ww  w.jav  a2 s. co  m
    final StructInfo structInfo = theStruct.structInfo();
    if (structInfo != null) {
        createdBy = structInfo.createdBy();
        createdOn = structInfo.createdOn();
        schemaVersion = structInfo.schemaVersion();
    } else {
        createdBy = DEFAULT_CREATED_BY;
        createdOn = new Date();
        schemaVersion = DEFAULT_SCHEMA_VERSION;
    }
    jsonVersion = JSON_VERSION;
    struct = theStruct;
    binding = new StructBinding(struct);
    try {
        final ObjectMapper mapper = mapper();
        final ObjectWriter writer = mapper.writerWithView(JSONViews.SignatureView.class);
        final String signatureStr = writer.writeValueAsString(binding);
        final ObjectWriter writer2 = mapper.writerWithView(JSONViews.CompleteView.class);
        final String fullString = writer2.writeValueAsString(binding);
        signature = MurmurHash.hash64(signatureStr);
        fullHash = MurmurHash.hash64(fullString);
    } catch (final JsonProcessingException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:ch.ralscha.extdirectspring.controller.RouterController.java

private void handleMethodCallOne(ExtDirectRequest directRequest, HttpServletRequest request,
        HttpServletResponse response, Locale locale) throws IOException {

    ExtDirectResponse directResponse = handleMethodCall(directRequest, request, response, locale);
    boolean streamResponse = this.configurationService.getConfiguration().isStreamResponse()
            || directResponse.isStreamResponse();
    Class<?> jsonView = directResponse.getJsonView();

    Object responseObject;//from   w w  w. ja v  a2  s.  c  om
    if (jsonView == null) {
        responseObject = Collections.singleton(directResponse);
    } else {
        ObjectMapper objectMapper = this.configurationService.getJsonHandler().getMapper();
        String jsonResult = objectMapper.writerWithView(jsonView)
                .writeValueAsString(directResponse.getResult());
        responseObject = Collections.singleton(new ExtDirectResponseRaw(directResponse, jsonResult));
    }

    writeJsonResponse(response, responseObject, null, streamResponse);
}

From source file:com.adobe.cq.wcm.core.components.extension.contentfragment.internal.models.v1.ContentFragmentImplTest.java

@Test
public void testJSONExport() throws IOException {
    ContentFragmentImpl fragment = (ContentFragmentImpl) getTestContentFragment(CF_TEXT_ONLY);
    Writer writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.writerWithView(ContentFragmentImpl.class).writeValue(writer, fragment);
    JsonReader jsonReaderOutput = Json.createReader(IOUtils.toInputStream(writer.toString()));
    JsonReader jsonReaderExpected = Json.createReader(Thread.currentThread().getContextClassLoader().getClass()
            .getResourceAsStream("/contentfragment/test-expected-content-export.json"));
    assertEquals(jsonReaderExpected.read(), jsonReaderOutput.read());
}