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

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

Introduction

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

Prototype

public ObjectReader reader(ContextAttributes attrs) 

Source Link

Document

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

Usage

From source file:org.agorava.linkedin.jackson.LinkedInNetworkUpdateListDeserializer.java

@Override
public LinkedInNetworkUpdate deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    ObjectMapper mapper = BeanResolver.getInstance().resolve(ObjectMapper.class);
    jp.setCodec(mapper);/*from  w w  w .  j  av a  2s . com*/

    JsonNode dataNode = jp.readValueAs(JsonNode.class);
    if (dataNode != null) {
        LinkedInNetworkUpdate linkedInNetworkUpdate = (LinkedInNetworkUpdate) mapper
                .reader(new TypeReference<LinkedInNetworkUpdate>() {
                }).readValue(dataNode);

        UpdateContent updatedContent = null;
        UpdateType type = linkedInNetworkUpdate.getUpdateType();
        JsonNode updatedNode = dataNode.get("updateContent");
        JsonNode person = updatedNode.get("person");
        if (type == UpdateType.MSFC) {
            // Totally different.  Looks like a bad API to be honest.
            person = updatedNode.get("companyPersonUpdate").get("person");
        }

        switch (type) {
        case CONN:
            updatedContent = mapper.reader(new TypeReference<UpdateContentConnection>() {
            }).readValue(person);
            break;
        case STAT:
            updatedContent = mapper.reader(new TypeReference<UpdateContentStatus>() {
            }).readValue(person);
            break;
        case JGRP:
            updatedContent = mapper.reader(new TypeReference<UpdateContentGroup>() {
            }).readValue(person);
            break;
        case PREC:
        case SVPR:
            updatedContent = mapper.reader(new TypeReference<UpdateContentRecommendation>() {
            }).readValue(person);
            break;
        case APPM:
            updatedContent = mapper.reader(new TypeReference<UpdateContentPersonActivity>() {
            }).readValue(person);
            break;
        case MSFC:
            updatedContent = mapper.reader(new TypeReference<UpdateContentFollow>() {
            }).readValue(person);
            break;
        case VIRL:
            updatedContent = mapper.reader(new TypeReference<UpdateContentViral>() {
            }).readValue(person);
            break;
        case SHAR:
            updatedContent = mapper.reader(new TypeReference<UpdateContentShare>() {
            }).readValue(person);
            break;
        case CMPY:
            updatedContent = mapper.reader(new TypeReference<UpdateContentCompany>() {
            }).readValue(updatedNode);
            break;
        default:
            try {
                updatedContent = mapper.reader(new TypeReference<UpdateContent>() {
                }).readValue(person);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        // Need to use reflection to set private updateContent field
        try {
            Field f = LinkedInNetworkUpdate.class.getDeclaredField("updateContent");
            f.setAccessible(true);
            f.set(linkedInNetworkUpdate, updatedContent);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (type == UpdateType.MSFC) {
            // Set the action via reflection as it's private
            String action = updatedNode.get("companyPersonUpdate").get("action").get("code").asText();
            try {
                Field f = UpdateContentFollow.class.getDeclaredField("action");
                f.setAccessible(true);
                f.set(updatedContent, action);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // Set following via reflection as it's private
            Company company = mapper.reader(new TypeReference<Company>() {
            }).readValue(updatedNode.get("company"));
            try {
                Field f = UpdateContentFollow.class.getDeclaredField("following");
                f.setAccessible(true);
                f.set(updatedContent, company);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (type == UpdateType.VIRL) {
            JsonNode originalUpdate = updatedNode.path("updateAction").path("originalUpdate");
            UpdateAction updateAction = mapper.reader(new TypeReference<UpdateAction>() {
            }).readValue(originalUpdate);
            String code = updatedNode.path("updateAction").path("action").path("code").textValue();

            // Set private immutable field action on updateAction
            try {
                Field f = UpdateAction.class.getDeclaredField("action");
                f.setAccessible(true);
                f.set(updateAction, code);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // Set private immutable field  updateAction on updatedContent
            try {
                Field f = UpdateContentViral.class.getDeclaredField("updateAction");
                f.setAccessible(true);
                f.set(updatedContent, updateAction);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return linkedInNetworkUpdate;
    }

    return null;
}

From source file:org.springframework.social.linkedin.api.impl.json.LinkedInNetworkUpdateListDeserializer.java

@Override
public LinkedInNetworkUpdate deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new LinkedInModule());
    jp.setCodec(mapper);// w  w w  .j  ava  2s .  co  m

    JsonNode dataNode = jp.readValueAs(JsonNode.class);
    if (dataNode != null) {
        LinkedInNetworkUpdate linkedInNetworkUpdate = (LinkedInNetworkUpdate) mapper
                .reader(new TypeReference<LinkedInNetworkUpdate>() {
                }).readValue(dataNode);

        UpdateContent updatedContent = null;
        UpdateType type = linkedInNetworkUpdate.getUpdateType();
        JsonNode updatedNode = dataNode.get("updateContent");
        JsonNode person = updatedNode.get("person");
        if (type == UpdateType.MSFC) {
            // Totally different.  Looks like a bad API to be honest.
            person = updatedNode.get("companyPersonUpdate").get("person");
        }

        switch (type) {
        case CONN:
            updatedContent = mapper.reader(new TypeReference<UpdateContentConnection>() {
            }).readValue(person);
            break;
        case STAT:
            updatedContent = mapper.reader(new TypeReference<UpdateContentStatus>() {
            }).readValue(person);
            break;
        case JGRP:
            updatedContent = mapper.reader(new TypeReference<UpdateContentGroup>() {
            }).readValue(person);
            break;
        case PREC:
        case SVPR:
            updatedContent = mapper.reader(new TypeReference<UpdateContentRecommendation>() {
            }).readValue(person);
            break;
        case APPM:
            updatedContent = mapper.reader(new TypeReference<UpdateContentPersonActivity>() {
            }).readValue(person);
            break;
        case MSFC:
            updatedContent = mapper.reader(new TypeReference<UpdateContentFollow>() {
            }).readValue(person);
            break;
        case VIRL:
            updatedContent = mapper.reader(new TypeReference<UpdateContentViral>() {
            }).readValue(person);
            break;
        case SHAR:
            updatedContent = mapper.reader(new TypeReference<UpdateContentShare>() {
            }).readValue(person);
            break;
        case CMPY:
            updatedContent = mapper.reader(new TypeReference<UpdateContentCompany>() {
            }).readValue(updatedNode);
            break;
        default:
            try {
                updatedContent = mapper.reader(new TypeReference<UpdateContent>() {
                }).readValue(person);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        // Need to use reflection to set private updateContent field
        try {
            Field f = LinkedInNetworkUpdate.class.getDeclaredField("updateContent");
            f.setAccessible(true);
            f.set(linkedInNetworkUpdate, updatedContent);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (type == UpdateType.MSFC) {
            // Set the action via reflection as it's private
            String action = updatedNode.get("companyPersonUpdate").get("action").get("code").asText();
            try {
                Field f = UpdateContentFollow.class.getDeclaredField("action");
                f.setAccessible(true);
                f.set(updatedContent, action);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // Set following via reflection as it's private
            Company company = mapper.reader(new TypeReference<Company>() {
            }).readValue(updatedNode.get("company"));
            try {
                Field f = UpdateContentFollow.class.getDeclaredField("following");
                f.setAccessible(true);
                f.set(updatedContent, company);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (type == UpdateType.VIRL) {
            JsonNode originalUpdate = updatedNode.path("updateAction").path("originalUpdate");
            UpdateAction updateAction = mapper.reader(new TypeReference<UpdateAction>() {
            }).readValue(originalUpdate);
            String code = updatedNode.path("updateAction").path("action").path("code").textValue();

            // Set private immutable field action on updateAction
            try {
                Field f = UpdateAction.class.getDeclaredField("action");
                f.setAccessible(true);
                f.set(updateAction, code);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // Set private immutable field  updateAction on updatedContent
            try {
                Field f = UpdateContentViral.class.getDeclaredField("updateAction");
                f.setAccessible(true);
                f.set(updatedContent, updateAction);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return linkedInNetworkUpdate;
    }

    return null;
}

From source file:com.spotify.docgenerator.DocgeneratorMojo.java

private List<ResourceMethod> readResourceMethods(ObjectMapper mapper, FileInputStream ist)
        throws JsonProcessingException, IOException {
    final ObjectReader reader = mapper.reader(new TypeReference<List<ResourceMethod>>() {
    });//from   w  w w. ja va  2s. co  m
    return reader.readValue(ist);
}

From source file:com.spotify.docgenerator.DocgeneratorMojo.java

private Map<String, TransferClass> readTransferClasses(final ObjectMapper mapper, FileInputStream ist)
        throws IOException, JsonProcessingException {
    final ObjectReader reader = mapper.reader(new TypeReference<Map<String, TransferClass>>() {
    });// w  w w.j av  a 2s.c  om
    return reader.readValue(ist);
}

From source file:de.undercouch.bson4jackson.BsonParserTest.java

/**
 * Tests if a simple BSON file can be read successfully
 * @throws Exception if something went wrong
 *//*w w  w  .j a  va2 s.co  m*/
@Test
public void readBSONFile() throws Exception {
    InputStream is = getClass().getResourceAsStream("test.bson");
    try {
        ObjectMapper mapper = new ObjectMapper(new BsonFactory());
        MappingIterator<BSONObject> iterator = mapper.reader(BasicBSONObject.class).readValues(is);

        BSONObject o = null;
        while (iterator.hasNext()) {
            assertNull(o);
            BSONObject object = iterator.next();
            assertNotNull(object);
            o = object;
        }

        assertEquals("Hello world", o.get("message"));
        assertEquals(10.0, o.get("size"));
        assertTrue(o.keySet().contains("_id"));
        assertEquals(3, o.keySet().size());
    } finally {
        is.close();
    }
}

From source file:net.opentsdb.tools.ConfigArgP.java

/**
 * Checks the <b><source>opentsdb.conf.json</source></b> document to see if it has a <b><source>bindings</source></b> segment
 * which contains JS statements to evaluate which will prime variables used by the configuration. 
 * @param jsonMapper The JSON mapper//  w ww.  j a va2s . c  o m
 * @param root The root <b><source>opentsdb.conf.json</source></b> document 
 */
protected void processBindings(ObjectMapper jsonMapper, JsonNode root) {
    try {
        if (root.has("bindings")) {
            JsonNode bindingsNode = root.get("bindings");
            if (bindingsNode.isArray()) {
                String[] jsLines = jsonMapper.reader(String[].class).readValue(bindingsNode);
                StringBuilder b = new StringBuilder();
                for (String s : jsLines) {
                    b.append(s).append("\n");
                }
                scriptEngine.eval(b.toString());
                LOG.info("Successfully evaluated [{}] lines of JS in bindings", jsLines.length);
            }
        }
    } catch (Exception ex) {
        throw new IllegalArgumentException("Failed to evaluate opentsdb.conf.json bindings", ex);
    }
}

From source file:io.fabric8.mq.controller.coordination.KubernetesControl.java

private String getOrCreateBrokerReplicationControllerId() {
    if (replicationControllerId == null) {
        try {//w ww .j av a  2 s.  c om
            ObjectMapper mapper = KubernetesFactory.createObjectMapper();

            File file = new File(getBrokerTemplateLocation());
            URL url;
            if (file.exists()) {
                url = Paths.get(file.getAbsolutePath()).toUri().toURL();
            } else {
                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                url = classLoader.getResource(getBrokerTemplateLocation());
            }

            if (url != null) {
                ReplicationController replicationController = mapper.reader(ReplicationController.class)
                        .readValue(url);
                replicationControllerId = replicationController.getId();
                ReplicationController running = kubernetes.getReplicationController(replicationControllerId);
                if (running == null) {
                    kubernetes.createReplicationController(replicationController);
                    LOG.info("Created ReplicationController " + replicationControllerId);
                } else {
                    LOG.info("Found ReplicationController " + running.getId());
                    replicationControllerId = running.getId();
                }

            } else {
                LOG.error("Could not find location of Broker Template from " + getBrokerTemplateLocation());
            }

        } catch (Throwable e) {
            LOG.error("Failed to create a Broker", e);
        }
    }
    return replicationControllerId;
}

From source file:org.apereo.portal.events.aggr.JpaStatisticalSummaryTest.java

public void testStorelessUnivariateStatistic(StorelessUnivariateStatistic sus, double expected)
        throws Exception {

    assertEquals(expected, sus.getResult(), 0.1);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();/*  w w w  .  j  a  v  a 2s.  c o m*/

    //Configure Jackson to just use fields
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.SETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE);

    mapper.addMixInAnnotations(Object.class, IgnoreTypeMixIn.class);

    final FilterProvider filters = new SimpleFilterProvider().addFilter("storedDataFilter",
            SimpleBeanPropertyFilter.serializeAllExcept("storedData"));

    final ObjectWriter ssWriter = mapper.writer(filters);
    final ObjectReader ssReader = mapper.reader(sus.getClass());

    final String susString = ssWriter.writeValueAsString(sus);
    System.out.println(susString);
    final StorelessUnivariateStatistic newSus = ssReader.readValue(susString);

    assertEquals(expected, newSus.getResult(), 0.1);
}

From source file:io.fabric8.mq.coordination.KubernetesControl.java

private String getOrCreaBteBrokerReplicationControllerId() {
    if (replicationControllerId == null) {
        try {/*w  w  w.j a v a 2s.  co m*/
            ReplicationController running = kubernetes.getReplicationController(
                    getOrCreaBteBrokerReplicationControllerId(), kubernetes.getNamespace());
            if (running == null) {
                ObjectMapper mapper = KubernetesFactory.createObjectMapper();

                //ToDo chould change this to look for ReplicationController for AMQ_Broker from Maven
                File file = new File(getBrokerTemplateLocation());
                URL url;
                if (file.exists()) {
                    url = Paths.get(file.getAbsolutePath()).toUri().toURL();
                } else {
                    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                    url = classLoader.getResource(getBrokerTemplateLocation());
                }

                if (url != null) {
                    ReplicationController replicationController = mapper.reader(ReplicationController.class)
                            .readValue(url);
                    replicationControllerId = getName(replicationController);
                    running = kubernetes.getReplicationController(replicationControllerId);
                    if (running == null) {
                        kubernetes.createReplicationController(replicationController);
                        LOG.info("Created ReplicationController " + replicationControllerId);
                    } else {
                        replicationControllerId = getName(running);
                        LOG.info("Found ReplicationController " + replicationControllerId);
                    }

                } else {
                    LOG.error("Could not find location of Broker Template from " + getBrokerTemplateLocation());
                }
            }

        } catch (Throwable e) {
            LOG.error("Failed to create a Broker", e);
        }
    }
    return replicationControllerId;
}

From source file:io.fabric8.core.jmx.FabricManager.java

@Override
public void requirementsJson(String json) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    Object value = mapper.reader(FabricRequirements.class).readValue(json);
    if (value instanceof FabricRequirements) {
        requirements((FabricRequirements) value);
    } else {//from  ww  w  .  ja  v a  2  s . c o m
        throw new IOException("Failed to parse FabricRequirements from JSON. Got " + value + ". JSON: " + json);
    }
}