Example usage for com.fasterxml.jackson.core.type TypeReference TypeReference

List of usage examples for com.fasterxml.jackson.core.type TypeReference TypeReference

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core.type TypeReference TypeReference.

Prototype

protected TypeReference() 

Source Link

Usage

From source file:com.twitter.ambrose.model.Event.java

public static void main(String[] args) throws IOException {
    String json = JSONUtil.readFile("pig/src/main/resources/web/data/small-events.json");
    List<Event> events = JSONUtil.toObject(json, new TypeReference<List<Event>>() {
    });/*from   w  w  w  .  j  a va2  s.c  o m*/
    for (Event event : events) {
        // useful if we need to read a file, add a field, output and re-generate
    }
    JSONUtil.writeJson("pig/src/main/resources/web/data/small-events.json2", events);
}

From source file:com.act.biointerpretation.BiointerpretationDriver.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from  w ww. j av a2s  .c  om*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(ReactionDesalter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    if (cl.hasOption(OPTION_CONFIGURATION_FILE)) {
        List<BiointerpretationStep> steps;
        File configFile = new File(cl.getOptionValue(OPTION_CONFIGURATION_FILE));
        if (!configFile.exists()) {
            String msg = String.format("Cannot find configuration file at %s", configFile.getAbsolutePath());
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }
        // Read the whole config file.
        try (InputStream is = new FileInputStream(configFile)) {
            steps = OBJECT_MAPPER.readValue(is, new TypeReference<List<BiointerpretationStep>>() {
            });
        } catch (IOException e) {
            LOGGER.error("Caught IO exception when attempting to read configuration file: %s", e.getMessage());
            throw e; // Crash after logging if the config file can't be read.
        }

        // Ask for explicit confirmation before dropping databases.
        LOGGER.info("Biointerpretation plan:");
        for (BiointerpretationStep step : steps) {
            crashIfInvalidDBName(step.getReadDBName());
            crashIfInvalidDBName(step.getWriteDBName());
            LOGGER.info("%s: %s -> %s", step.getOperation(), step.getReadDBName(), step.getWriteDBName());
        }
        LOGGER.warn("WARNING: each DB to be written will be dropped before the writing step commences");
        LOGGER.info("Proceed? [y/n]");
        String readLine;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            readLine = reader.readLine();
        }
        readLine.trim();
        if ("y".equalsIgnoreCase(readLine) || "yes".equalsIgnoreCase(readLine)) {
            LOGGER.info("Biointerpretation plan confirmed, commencing");
            for (BiointerpretationStep step : steps) {
                performOperation(step, true);
            }
            LOGGER.info("Biointerpretation plan completed");
        } else {
            LOGGER.info("Biointerpretation plan not confirmed, exiting");
        }
    } else if (cl.hasOption(OPTION_SINGLE_OPERATION)) {
        if (!cl.hasOption(OPTION_SINGLE_READ_DB) || !cl.hasOption(OPTION_SINGLE_WRITE_DB)) {
            String msg = "Must specify read and write DB names when performing a single operation";
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }
        BiointerpretationOperation operation;
        try {
            operation = BiointerpretationOperation.valueOf(cl.getOptionValue(OPTION_SINGLE_OPERATION));
        } catch (IllegalArgumentException e) {
            LOGGER.error("Caught IllegalArgumentException when trying to parse operation '%s': %s",
                    cl.getOptionValue(OPTION_SINGLE_OPERATION), e.getMessage());
            throw e; // Crash if we can't interpret the operation.
        }
        String readDB = crashIfInvalidDBName(cl.getOptionValue(OPTION_SINGLE_READ_DB));
        String writeDB = crashIfInvalidDBName(cl.getOptionValue(OPTION_SINGLE_WRITE_DB));

        performOperation(new BiointerpretationStep(operation, readDB, writeDB), false);
    } else {
        String msg = "Must specify either a config file or a single operation to perform.";
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    }
}

From source file:Main.java

public static String getValueFromJson(String json, String key) {
    String value = "null";
    try {// w w w.j  av  a 2 s.  co  m
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> values = mapper.readValue(json, new TypeReference<Map<String, String>>() {
        });
        if (values.containsKey(key)) {
            value = values.get(key).toString();
        }
    } catch (IOException e) {
        System.out.println("Could not parse json: " + json);
    }
    return value;
}

From source file:io.klerch.alexa.state.utils.ConversionUtils.java

/**
 * A json-string of key-value pairs is read out as a map
 * @param json json-string of key-value pairs
 * @return a map with corresponding key-value paris
 *///from   w  w  w  .  j  a  v a2 s .c  o m
public static Map<String, Object> mapJson(final String json) {
    final ObjectMapper mapper = new ObjectMapper();
    if (json == null || json.isEmpty()) {
        return new HashMap<>();
    }
    final TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
    };
    try {
        // read jsonString into map
        return mapper.readValue(json, typeRef);
    } catch (IOException e) {
        log.error(e);
        return new HashMap<>();
    }
}

From source file:it.jugtorino.one.msvc.way.rabbit.reference.utils.JSONUtils.java

public static Map<String, Object> toMap(byte[] bytes) {
    ObjectMapper mapper = new ObjectMapper();

    TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
    };/*  w  ww .jav  a 2s  .  c  om*/

    try {
        return mapper.readValue(bytes, typeRef);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.nesscomputing.jackson.JacksonSerializerBinder.java

/**
 * Begin creating a new serialization binding
 * @param binder the Guice binder to attach to
 * @param type the type we will transform
 * @return a builder//  ww w  .  ja v  a 2 s  .c om
 */
public static <T> SerializerBinderBuilder<T> builderOf(Binder binder, final Class<T> type) {
    return new SerializerBinderBuilderImpl<T>(binder, new TypeReference<T>() {
        @Override
        public Type getType() {
            return type;
        }
    });
}

From source file:fr.pilato.elasticsearch.crawler.fs.tika.XmlDocParser.java

public static Map<String, Object> asMap(InputStream stream) {
    try {/*from  w ww . j av  a  2s  . c o  m*/
        return xmlMapper.readValue(stream, new TypeReference<Map<String, Object>>() {
        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:at.plechinger.spring.security.scribe.JsonUtil.java

public static Map<String, Object> parseMap(String input) throws IOException {
    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper(factory);
    TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
    };//from   w w  w  .  j  a va2 s .  c o  m
    return mapper.readValue(input, typeRef);
}

From source file:com.vmware.photon.controller.api.frontend.lib.UsageTagHelper.java

public static List<UsageTag> deserialize(String concatenatedUsageTags) {
    if (StringUtils.isBlank(concatenatedUsageTags)) {
        throw new IllegalArgumentException("Blank string cannot be deserialized to list of UsageTags");
    }/*from  w  w  w .j ava2  s . c  om*/

    try {
        List<UsageTag> usageTags = objectMapper.readValue(concatenatedUsageTags,
                new TypeReference<List<UsageTag>>() {
                });
        Collections.sort(usageTags);
        return usageTags;
    } catch (IOException e) {
        logger.error(String.format("Error deserializing UsageTag %s", concatenatedUsageTags), e);
        throw new IllegalArgumentException(
                String.format("Error deserializing UsageTag %s", concatenatedUsageTags), e);
    }
}

From source file:com.damnhandy.uri.template.conformance.AbstractUriTemplateConformanceTest.java

/**
 * <p>/*from  ww  w .j av  a  2  s .  c o m*/
 * Loads the test data from the JSON file and generated the parameter list.
 * </p>
 *
 * @param file
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
protected static Collection<Object[]> loadTestData(File file) throws Exception {
    InputStream in = new FileInputStream(file);
    try {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> testsuites = mapper.readValue(in, new TypeReference<Map<String, Object>>() {
        });

        List<Object[]> params = new ArrayList<Object[]>();
        for (Map.Entry<String, Object> entry : testsuites.entrySet()) {
            String name = entry.getKey();
            Map<String, Object> testsuite = (Map<String, Object>) entry.getValue();
            Map<String, Object> variables = (Map<String, Object>) testsuite.get("variables");
            List<List<Object>> testcases = (List<List<Object>>) testsuite.get("testcases");

            for (List<Object> test : testcases) {
                Object[] p = new Object[4];
                p[0] = variables;
                p[1] = test.get(0); // expression
                p[2] = test.get(1); // expected result
                p[3] = name; // test suite label
                params.add(p);
            }
        }
        return params;
    } finally {
        in.close();
    }

}