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

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
    public <T> T readValue(byte[] src, JavaType valueType)
            throws IOException, JsonParseException, JsonMappingException 

Source Link

Usage

From source file:com.ikanow.aleph2.data_model.utils.BeanTemplateUtils.java

/** Converts a JsonNode to a bean template of the specified type
 * (note: not very high performance, should only be used for management-type operations)
 * @param bean - the JSON string to convert to a bean 
 * @return - the bean template//from   www  .  j a  v a  2  s  .  c  o m
 */
static public <T> BeanTemplate<T> from(final String string_json, final Class<T> clazz) {
    try {
        ObjectMapper object_mapper = BeanTemplateUtils.configureMapper(Optional.empty());
        return BeanTemplate.of(object_mapper.readValue(string_json, clazz));
    } catch (Exception e) { // on fail returns an unchecked error
        throw new RuntimeException(e); // (this can only happen due to "static" code type issues, so unchecked exception is fine
    }
}

From source file:com.meltmedia.dropwizard.etcd.json.WatchService.java

static <T> T readValue(ObjectMapper mapper, EtcdNode value, TypeReference<T> type) {
    try {//from www . j  a v a2  s  .co m
        return value == null || value.value == null || value.dir ? null : mapper.readValue(value.value, type);
    } catch (Exception e) {
        logger.warn(format("could not read value at %s as type %s", value.key, type), e);
        return null;
    }
}

From source file:com.nextdoor.bender.config.BenderConfig.java

public static BenderConfig load(String filename, String data, ObjectMapper mapper, boolean validate) {
    String swappedData = swapEnvironmentVariables(data);

    if (validate) {
        BenderConfig.validate(swappedData, mapper);
    }/*from  w  w  w  .  j  a v  a 2 s. c  om*/

    BenderConfig config = null;
    try {
        config = mapper.readValue(swappedData, BenderConfig.class);
    } catch (IOException e) {
        throw new ConfigurationException("invalid config file", e);
    }

    return config;
}

From source file:io.coala.json.JsonUtil.java

/**
 * @param om the {@link ObjectMapper} used to parse/deserialize/unmarshal
 * @param json the JSON formatted {@link String} value
 * @param typeReference the result type {@link TypeReference}
 * @param imports the {@link Properties} instances for default values, etc.
 * @return the parsed/deserialized/unmarshalled {@link Object}
 *///from   w  w w  .j av a  2  s  . co  m
@SuppressWarnings("unchecked")
public static <T> T valueOf(final ObjectMapper om, final String json, final TypeReference<T> typeReference,
        final Properties... imports) {
    if (json == null)
        return null;
    try {
        final Class<?> rawType = om.getTypeFactory().constructType(typeReference).getRawClass();
        checkRegistered(om, rawType, imports);
        return (T) om.readValue(json, typeReference);
    } catch (final Exception e) {
        Thrower.rethrowUnchecked(e);
        return null;
    }
}

From source file:com.auditbucket.client.Importer.java

private static long processJsonTags(String fileName, AbRestClient abExporter, int skipCount,
        boolean simulateOnly) {
    Collection<TagInputBean> tags;
    ObjectMapper mapper = new ObjectMapper();
    try {//from w ww. j a  v  a 2  s .  co  m
        File file = new File(fileName);
        if (!file.exists()) {
            logger.error("{} does not exist", fileName);
            return 0;
        }
        TypeFactory typeFactory = mapper.getTypeFactory();
        CollectionType collType = typeFactory.constructCollectionType(ArrayList.class, TagInputBean.class);

        tags = mapper.readValue(file, collType);
        for (TagInputBean tag : tags) {
            abExporter.writeTag(tag, "JSON Tag Importer");
        }
    } catch (IOException e) {
        logger.error("Error writing exceptions with {} [{}]", fileName, e);
        throw new RuntimeException("IO Exception ", e);
    } finally {
        abExporter.flush("Finishing processing of TagInputBeans " + fileName);

    }
    return tags.size(); //To change body of created methods use File | Settings | File Templates.
}

From source file:org.eclipse.winery.topologymodeler.addons.topologycompleter.helper.JAXBHelper.java

/**
 * This method adds a selection of {@link TNodeTemplate}- and {@link TRelationshipTemplate}-XML-Strings to a {@link TTopologyTemplate}-XML-String using JAXB.
 * After the templates have been added, the {@link TTopologyTemplate} object is re-marshalled to an XML-String.
 *
 * This method is called by the selectionHandler.jsp after several Node or RelationshipTemplates have been chosen in a dialog.
 *
 * @param topology//w w w .ja  v  a  2s  .  c om
 *            the topology as XML string
 * @param allTemplateChoicesAsXML
 *            all possible template choices as TOSCA-XML strings containing the complete templates
 * @param selectedNodeTemplatesAsJSON
 *            the names of the selected NodeTemplates as JSONArray
 * @param selectedRelationshipTemplatesAsJSON
 *            the names of the selected RelationshipTemplates as JSONArray
 *
 * @return the complete topology XML string
 */
public static String addTemplatesToTopology(String topology, String allTemplateChoicesAsXML,
        String selectedNodeTemplatesAsJSON, String selectedRelationshipTemplatesAsJSON) {
    try {

        // initialization code for the jackson types used to convert JSON string arrays to a java.util.List
        ObjectMapper mapper = new ObjectMapper();
        TypeFactory factory = mapper.getTypeFactory();

        // convert the JSON array containing the names of the selected RelationshipTemplates to a java.util.List
        List<String> selectedRelationshipTemplates = mapper.readValue(selectedRelationshipTemplatesAsJSON,
                factory.constructCollectionType(List.class, String.class));

        // convert the topology and the choices to objects using JAXB
        TTopologyTemplate topologyTemplate = getTopologyAsJaxBObject(topology);
        List<TEntityTemplate> allTemplateChoices = getEntityTemplatesAsJaxBObject(allTemplateChoicesAsXML);

        // this distinction of cases is necessary because it is possible that only RelationshipTemplates have been selected
        if (selectedNodeTemplatesAsJSON != null) {

            // convert the JSON string array containing the names of the selected NodeTemplates to a java.util.List
            List<String> selectedNodeTemplates = mapper.readValue(selectedNodeTemplatesAsJSON,
                    factory.constructCollectionType(List.class, String.class));

            // search the selected NodeTemplate in the List of all choices by its name to receive its object which will ne added to the topology
            for (String nodeTemplateName : selectedNodeTemplates) {
                for (TEntityTemplate choice : allTemplateChoices) {
                    if (choice instanceof TNodeTemplate) {
                        TNodeTemplate nodeTemplate = (TNodeTemplate) choice;
                        // matching a name is usually unsafe because the uniqueness cannot be assured,
                        // however similar names are not possible at this location due to the implementation of the selection dialogs
                        if (nodeTemplateName.equals(nodeTemplate.getName())) {
                            // add the selected NodeTemplate to the topology
                            topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(nodeTemplate);

                            // due to the mapping of IDs in the selection dialog, the corresponding Relationship Template of the inserted Node Template misses its SourceElement.
                            // Re-add it to avoid errors.
                            for (TEntityTemplate entity : topologyTemplate
                                    .getNodeTemplateOrRelationshipTemplate()) {
                                if (entity instanceof TRelationshipTemplate) {
                                    TRelationshipTemplate relationshipTemplate = (TRelationshipTemplate) entity;
                                    if (relationshipTemplate.getSourceElement().getRef() == null) {
                                        // connect to the added NodeTemplate
                                        SourceElement sourceElement = new SourceElement();
                                        sourceElement.setRef(nodeTemplate);
                                        relationshipTemplate.setSourceElement(sourceElement);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // now search and add the selected RelationshipTemplate object connecting to the inserted NodeTemplate
            for (String relationshipTemplateName : selectedRelationshipTemplates) {
                for (TEntityTemplate toBeAdded : allTemplateChoices) {
                    if (toBeAdded instanceof TRelationshipTemplate) {
                        TRelationshipTemplate relationshipTemplate = (TRelationshipTemplate) toBeAdded;
                        if (relationshipTemplateName.equals(relationshipTemplate.getName())) {
                            topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(relationshipTemplate);
                        }
                    }
                }
            }

        } else {
            // in this case only Relationship Templates have been selected
            List<TRelationshipTemplate> allRelationshipTemplateChoices = JAXBHelper
                    .getRelationshipTemplatesAsJaxBObject(allTemplateChoicesAsXML);

            // add the target Node Template to the topology which is unique due to the implementation of the selection dialog
            topologyTemplate.getNodeTemplateOrRelationshipTemplate()
                    .add((TNodeTemplate) ((TRelationshipTemplate) allRelationshipTemplateChoices.get(0))
                            .getTargetElement().getRef());

            // search the JAXB object of the selected RelationshipTemplate and add it to the topology
            for (String relationshipTemplateName : selectedRelationshipTemplates) {
                for (TRelationshipTemplate choice : allRelationshipTemplateChoices) {
                    if (relationshipTemplateName.equals(choice.getName())) {
                        topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(choice);
                    }
                }
            }

            for (TEntityTemplate entityTemplate : topologyTemplate.getNodeTemplateOrRelationshipTemplate()) {
                if (entityTemplate instanceof TRelationshipTemplate) {
                    TRelationshipTemplate relationship = (TRelationshipTemplate) entityTemplate;

                    // due to the mapping of IDs in the selection dialog, the corresponding Relationship Template of the inserted Node Template misses its SourceElement.
                    // Re-add it to avoid errors.
                    if (relationship.getSourceElement().getRef() == null) {
                        relationship.getSourceElement().setRef(
                                (TNodeTemplate) ((TRelationshipTemplate) allRelationshipTemplateChoices.get(0))
                                        .getTargetElement().getRef());
                    }
                }
            }
        }

        // re-convert the topology from a JAXB object to an XML string and return it
        Definitions definitions = new Definitions();
        TServiceTemplate st = new TServiceTemplate();
        st.setTopologyTemplate(topologyTemplate);
        definitions.getServiceTemplateOrNodeTypeOrNodeTypeImplementation().add(st);
        JAXBContext context = JAXBContext.newInstance(Definitions.class);
        Marshaller m = context.createMarshaller();
        StringWriter stringWriter = new StringWriter();

        m.marshal(definitions, stringWriter);

        return stringWriter.toString();

    } catch (JAXBException | IOException e) {
        logger.error(e.getLocalizedMessage());
    }

    return null;
}

From source file:org.kitesdk.apps.scheduled.Schedule.java

/**
 * Parse the JSON representation of the schedule.
 */// ww  w  . j  a v  a  2  s.c o  m
public static Schedule parseJson(String json) {

    ObjectMapper mapper = new ObjectMapper();

    JsonNode parent;

    try {
        parent = mapper.readValue(json, JsonNode.class);
    } catch (JsonParseException e) {
        throw new ValidationException("Invalid JSON", e);
    } catch (JsonMappingException e) {
        throw new ValidationException("Invalid JSON", e);
    } catch (IOException e) {
        throw new AppException(e);
    }

    Schedule.Builder builder = new Schedule.Builder();

    String jobName = parent.get(NAME).asText();
    builder.jobName(jobName);

    String className = parent.get(JOBCLASS).asText();

    try {
        Class jobClass = Thread.currentThread().getContextClassLoader().loadClass(className);

        builder.jobClass(jobClass);

    } catch (ClassNotFoundException e) {
        throw new AppException(e);
    }

    String startTime = parent.get(START_TIME).asText();
    builder.startAt(new Instant(formatter.parseMillis(startTime)));

    String jobFrequency = parent.get(FREQUENCY).asText();
    builder.frequency(jobFrequency);

    // Read the views.
    ArrayNode views = (ArrayNode) parent.get(VIEWS);

    for (JsonNode view : views) {

        String name = view.get(NAME).asText();
        String uri = view.get(URI).asText();
        String frequency = view.get(FREQUENCY).asText();
        String type = view.get(TYPE).asText();
        boolean isInput = view.get(IS_INPUT).asBoolean();

        Class viewType;

        try {
            viewType = Thread.currentThread().getContextClassLoader().loadClass(type);
        } catch (ClassNotFoundException e) {
            throw new AppException(e);
        }

        if (isInput) {
            builder.withInput(name, uri, frequency, viewType);
        } else {
            builder.withOutput(name, uri, viewType);
        }
    }

    return builder.build();
}

From source file:com.groupdocs.sdk.common.ApiInvoker.java

@SuppressWarnings("unchecked")
public static Object deserialize(String json, String containerType, @SuppressWarnings("rawtypes") Class cls)
        throws ApiException {
    try {//from w  ww. j ava  2 s.co m
        ObjectMapper mapper = JsonUtil.getJsonMapper();
        SimpleModule m = new SimpleModule(PACKAGE_NAME, Version.unknownVersion());
        m.addDeserializer(Date.class, new CustomDateDeserializer(new DateDeserializer()));
        mapper.registerModule(m);

        if ("List".equals(containerType)) {
            JavaType typeInfo = mapper.getTypeFactory().constructCollectionType(List.class, cls);
            List<?> response = (List<?>) mapper.readValue(json, typeInfo);
            return response;
        } else if (String.class.equals(cls)) {
            return json;
        } else {
            return mapper.readValue(json, cls);
        }
    } catch (IOException e) {
        throw new ApiException(500, e.getMessage());
    }
}

From source file:com.sitewhere.hbase.device.HBaseDeviceEvent.java

/**
 * Converts matching rows to {@link SearchResults} for web service response.
 * //  ww w .j  a v a  2  s.  c om
 * @param matches
 * @param jsonType
 * @return
 */
@SuppressWarnings("unchecked")
protected static <I extends IDeviceEvent, D extends DeviceEvent> SearchResults<I> convertMatches(
        Pager<byte[]> matches, Class<D> jsonType) {
    ObjectMapper mapper = new ObjectMapper();
    List<I> results = new ArrayList<I>();
    for (byte[] jsonBytes : matches.getResults()) {
        try {
            D event = mapper.readValue(jsonBytes, jsonType);
            results.add((I) event);
        } catch (Throwable e) {
            LOGGER.error("Unable to read JSON value into event object.", e);
        }
    }
    return new SearchResults<I>(results, matches.getTotal());
}

From source file:de.fau.cs.inf2.tree.evaluation.Main.java

/**
 * Parses path/time and prints the total number of
 * time measurements.//from   w  w  w.j  ava  2 s. c  om
 */
private static void readTimeAndPrint(File path) {
    File repositories = new File(path, "/time/");
    ObjectMapper mapper = TreeEvalIO.createJSONMapper();
    int sum = 0;
    for (final File repository : repositories.listFiles((f) -> f.isDirectory())) {
        for (final File commitOld : repository.listFiles((f) -> f.isDirectory())) {
            for (final File commitNew : commitOld.listFiles((f) -> f.isDirectory())) {
                for (final File changedFile : commitNew.listFiles((f) -> f.isDirectory())) {
                    for (final File measurementFile : changedFile
                            .listFiles((f) -> f.getName().endsWith(".json"))) {
                        try {
                            TimeSummary result = mapper.readValue(measurementFile, TimeSummary.class);
                            if (result != null) {
                                sum++;
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    System.out.println("Time measurements found: " + sum);
}