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

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

Introduction

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

Prototype

public TypeFactory getTypeFactory() 

Source Link

Document

Accessor for getting currently configured TypeFactory instance.

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  .j av a2 s .co  m*/
    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:xyz.monotalk.social.mixcloud.internal.JsonUtils.java

/**
 * readResultValue/*  w  ww . j  av a 2 s.  co  m*/
 *
 * @param <T>
 * @param json
 * @param clazz
 * @return
 */
public static <T> MixCloudResult<T> readResultValue(String json, Class<T> clazz) {
    MixCloudResult<T> result = null;
    ObjectMapper mapper = new ObjectMapper();
    JavaType type = mapper.getTypeFactory().constructParametrizedType(MixCloudResult.class,
            MixCloudResult.class, clazz);
    try {
        result = mapper.readValue(json, type);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return result;
}

From source file:io.ingenieux.lambada.runtime.LambadaUtils.java

public static <T> JavaType getReferenceFor(ObjectMapper mapper, Class<T> clazz) {
    final TypeFactory typeFactory = mapper.getTypeFactory();

    return typeFactory.constructParametrizedType(PassthroughRequest.class, PassthroughRequest.class, clazz);
}

From source file:org.smartdeveloperhub.vocabulary.config.ConfigurationFactory.java

static <T> T convert(final Object source, final Type type) {
    final ObjectMapper mapper = parsingMapper();
    final JavaType constructType = mapper.getTypeFactory().constructType(type);
    checkArgument(mapper.canDeserialize(constructType), "%s is not a valid configuration class",
            constructType.toCanonical());
    return mapper.convertValue(source, constructType);
}

From source file:com.couchbase.client.core.util.ClusterDependentTest.java

private static Integer minNodeVersionFromConfig(String rawConfig) throws Exception {
    ObjectMapper mapper = new ObjectMapper();

    JavaType type = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class);
    Map<String, Object> result = mapper.readValue(rawConfig, type);

    List<Object> nodes = (List<Object>) result.get("nodes");
    int min = 99;
    for (Object n : nodes) {
        Map<String, Object> node = (Map<String, Object>) n;
        String version = (String) node.get("version");
        int major = Integer.parseInt(version.substring(0, 1));
        if (major < min) {
            min = major;// w w  w.  ja v  a 2s.  com
        }
    }
    return min;
}

From source file:org.ethereum.core.genesis.GenesisLoader.java

public static Genesis loadGenesis(BigInteger initialNonce, InputStream genesisJsonIS, boolean isRsk) {
    try {//from w  ww .j a v a  2 s . c o m

        String json = new String(ByteStreams.toByteArray(genesisJsonIS));

        ObjectMapper mapper = new ObjectMapper();
        JavaType type = mapper.getTypeFactory().constructType(GenesisJson.class);

        GenesisJson genesisJson = new ObjectMapper().readValue(json, type);

        Genesis genesis = new GenesisMapper().mapFromJson(genesisJson, isRsk);

        Map<ByteArrayWrapper, InitialAddressState> premine = generatePreMine(initialNonce,
                genesisJson.getAlloc());
        genesis.setPremine(premine);

        byte[] rootHash = generateRootHash(premine);
        genesis.setStateRoot(rootHash);

        genesis.flushRLP();

        return genesis;
    } catch (Exception e) {
        System.err.println("Genesis block configuration is corrupted or not found ./resources/genesis/...");
        logger.error("Genesis block configuration is corrupted or not found ./resources/genesis/...", e);
        System.exit(-1);
        return null;
    }
}

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

/**
 * Read a list of specifications from a file.
 * @param type The specification type./*from  www .j  a v  a  2 s . co  m*/
 * @param file The file to read from.
 * @param <T> The specification type.
 * @return A deserialized specification.
 * @throws IOException if there is an error reading the file.
 */
public static <T> List<T> loadList(Class<T> type, Path file) throws IOException {
    ObjectMapper mapper = createMapper();
    JavaType listType = mapper.getTypeFactory().constructCollectionType(List.class, type);
    ObjectReader reader = createMapper().reader(listType);
    return reader.readValue(file.toFile());
}

From source file:com.bna.ezrxlookup.util.JsonMapperUtil.java

/**
 * Parse JSON string and return a list of object type.
 * @param jsonString - input JSON string
 * @param rootName - root node name/* w  ww. j ava 2  s .  com*/
 * @param type - object class type
 * @return list of object class
 */
public static <T> List<T> readJsonToList(String jsonString, String rootName, Class<T> clazz) throws Exception {
    List<T> objList = null;
    ObjectMapper objectMapper = new ObjectMapper();

    try {
        // get json content with root name
        JsonNode root = objectMapper.readTree(jsonString).get(rootName);
        TypeFactory tf = objectMapper.getTypeFactory();
        JavaType listOfObjs = tf.constructCollectionType(ArrayList.class, clazz);
        objList = objectMapper.readValue(root.traverse(), listOfObjs);
    } catch (Exception e) {
        throw e;
    }

    return objList;
}

From source file:com.dell.asm.asmcore.asmmanager.util.deployment.HostnameUtilTest.java

static Deployment loadEsxiDeployment() throws IOException {
    // Set up some mock component data
    // Get some deployment data
    URL uri = HostnameUtilTest.class.getClassLoader().getResource("esxi_deployment.json");
    assertNotNull("Failed to load esxi_deployment.json", uri);
    String json = IOUtils.toString(uri, Charsets.UTF_8);

    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector ai = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    mapper.setAnnotationIntrospector(ai);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper.readValue(json, Deployment.class);
}

From source file:com.tectonica.thirdparty.Jackson2.java

public static <T, P> T fromJson(String jsonStr, Class<T> clz, Class<P> paramClz, ObjectMapper mapper) {
    try {//from  w  ww . j a v a2 s  .  c om
        JavaType jt = mapper.getTypeFactory().constructParametrizedType(clz, clz, paramClz);
        return mapper.readValue(jsonStr, jt);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}