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

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
    public <T> T convertValue(Object fromValue, JavaType toValueType) throws IllegalArgumentException 

Source Link

Usage

From source file:test.jackson.JacksonNsgiRegister.java

public static void main(String[] args) throws IOException {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    String ngsiRcr = new String(Files.readAllBytes(Paths.get(NGSI_FILE)));

    RegisterContextRequest rcr = objectMapper.readValue(ngsiRcr, RegisterContextRequest.class);

    System.out.println(objectMapper.writeValueAsString(rcr));

    LinkedHashMap association = (LinkedHashMap) rcr.getContextRegistration().get(0).getContextMetadata().get(0)
            .getValue();/*from   w ww.  ja  v  a 2  s  .  co  m*/
    Association assocObject = objectMapper.convertValue(association, Association.class);
    System.out.println(assocObject.getAttributeAssociation().get(0).getSourceAttribute());

    rcr.getContextRegistration().get(0).getContextRegistrationAttribute().get(1).getContextMetadata().get(0);

    //        System.out.println(rcr.getContextRegistration().get(0).getContextMetadata().get(0).getValue().getClass().getCanonicalName());

    //        String assocJson = objectMapper.writeValueAsString(association);
    //        Value assocObject =  objectMapper.readValue(objectMapper.writeValueAsString(association), Value.class);
    //        System.out.println(association.values().toString());
    //        System.out.println(assocJson);

}

From source file:test.jackson.JacksonNsgiDiscover.java

public static void main(String[] args) throws IOException {

    ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

    String ngsiRcr = new String(Files.readAllBytes(Paths.get(NGSI_FILE)));

    DiscoveryContextAvailabilityRequest dcar = objectMapper.readValue(ngsiRcr,
            DiscoveryContextAvailabilityRequest.class);

    //        System.out.println(objectMapper.writeValueAsString(dcar));
    System.out.println(dcar.getRestriction().getOperationScope().get(1).getScopeValue());

    LinkedHashMap shapeHMap = (LinkedHashMap) dcar.getRestriction().getOperationScope().get(1).getScopeValue();
    //        Association assocObject =  objectMapper.convertValue(shapeHMap, Association.class);
    //        System.out.println(assocObject.getAttributeAssociation().get(0).getSourceAttribute());

    Shape shape = objectMapper.convertValue(shapeHMap, Shape.class);
    System.out.println("Deserialized Class: " + shape.getClass().getSimpleName());
    System.out.println("VALUE: " + shape.getPolygon().getVertices().get(2).getLatitude());
    System.out.println("VALUE: " + shape.getCircle());
    if (!(shape.getCircle() == null))
        System.out.println("This is null");

    Polygon polygon = shape.getPolygon();
    int vertexSize = polygon.getVertices().size();
    Coordinate[] coords = new Coordinate[vertexSize];

    final ArrayList<Coordinate> points = new ArrayList<>();
    for (int i = 0; i < vertexSize; i++) {
        Vertex vertex = polygon.getVertices().get(i);
        points.add(new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude())));
        coords[i] = new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude()));
    }//  w w w  .ja v  a 2  s  .c  o m
    points.add(new Coordinate(Double.valueOf(polygon.getVertices().get(0).getLatitude()),
            Double.valueOf(polygon.getVertices().get(0).getLongitude())));

    final GeometryFactory gf = new GeometryFactory();

    final Coordinate target = new Coordinate(49, -0.6);
    final Point point = gf.createPoint(target);

    Geometry shapeGm = gf.createPolygon(
            new LinearRing(new CoordinateArraySequence(points.toArray(new Coordinate[points.size()])), gf),
            null);
    //    Geometry shapeGm = gf.createPolygon(coords);    
    System.out.println(point.within(shapeGm));

    //        System.out.println(rcr.getContextRegistration().get(0).getContextMetadata().get(0).getValue().getClass().getCanonicalName());

    //        String assocJson = objectMapper.writeValueAsString(association);
    //        Value assocObject =  objectMapper.readValue(objectMapper.writeValueAsString(association), Value.class);
    //        System.out.println(association.values().toString());
    //        System.out.println(assocJson);

}

From source file:be.dnsbelgium.rdap.client.RDAPCLI.java

public static void main(String[] args) {

    LOGGER.debug("Create the command line parser");
    CommandLineParser parser = new GnuParser();

    LOGGER.debug("Create the options");
    Options options = new RDAPOptions(Locale.ENGLISH);

    try {//from w ww  . j  a v a 2 s. co m
        LOGGER.debug("Parse the command line arguments");
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            printHelp(options);
            return;
        }

        if (line.getArgs().length == 0) {
            throw new IllegalArgumentException("You must provide a query");
        }
        String query = line.getArgs()[0];

        Type type = (line.getArgs().length == 2) ? Type.valueOf(line.getArgs()[1].toUpperCase())
                : guessQueryType(query);

        LOGGER.debug("Query: {}, Type: {}", query, type);

        try {
            SSLContextBuilder sslContextBuilder = SSLContexts.custom();
            if (line.hasOption(RDAPOptions.TRUSTSTORE)) {
                sslContextBuilder.loadTrustMaterial(
                        RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.TRUSTSTORE)),
                                line.getOptionValue(RDAPOptions.TRUSTSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE),
                                line.getOptionValue(RDAPOptions.TRUSTSTORE_PASS, RDAPOptions.DEFAULT_PASS)));
            }
            if (line.hasOption(RDAPOptions.KEYSTORE)) {
                sslContextBuilder.loadKeyMaterial(
                        RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.KEYSTORE)),
                                line.getOptionValue(RDAPOptions.KEYSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE),
                                line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS)),
                        line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS).toCharArray());
            }
            SSLContext sslContext = sslContextBuilder.build();

            final String url = line.getOptionValue(RDAPOptions.URL);
            final HttpHost host = Utils.httpHost(url);

            HashSet<Header> headers = new HashSet<Header>();
            headers.add(new BasicHeader("Accept-Language",
                    line.getOptionValue(RDAPOptions.LANG, Locale.getDefault().toString())));
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(headers)
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext,
                            (line.hasOption(RDAPOptions.INSECURE) ? new AllowAllHostnameVerifier()
                                    : new BrowserCompatHostnameVerifier())));

            if (line.hasOption(RDAPOptions.USERNAME) && line.hasOption(RDAPOptions.PASSWORD)) {
                BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()),
                        new UsernamePasswordCredentials(line.getOptionValue(RDAPOptions.USERNAME),
                                line.getOptionValue(RDAPOptions.PASSWORD)));
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }

            RDAPClient rdapClient = new RDAPClient(httpClientBuilder.build(), url);
            ObjectMapper mapper = new ObjectMapper();

            JsonNode json = null;
            switch (type) {
            case DOMAIN:
                json = rdapClient.getDomainAsJson(query);
                break;
            case ENTITY:
                json = rdapClient.getEntityAsJson(query);
                break;
            case AUTNUM:
                json = rdapClient.getAutNum(query);
                break;
            case IP:
                json = rdapClient.getIp(query);
                break;
            case NAMESERVER:
                json = rdapClient.getNameserver(query);
                break;
            }
            PrintWriter out = new PrintWriter(System.out, true);
            if (line.hasOption(RDAPOptions.RAW)) {
                mapper.writer().writeValue(out, json);
            } else if (line.hasOption(RDAPOptions.PRETTY)) {
                mapper.writer(new DefaultPrettyPrinter()).writeValue(out, json);
            } else if (line.hasOption(RDAPOptions.YAML)) {
                DumperOptions dumperOptions = new DumperOptions();
                dumperOptions.setPrettyFlow(true);
                dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
                dumperOptions.setSplitLines(true);
                Yaml yaml = new Yaml(dumperOptions);
                Map data = mapper.convertValue(json, Map.class);
                yaml.dump(data, out);
            } else {
                mapper.writer(new MinimalPrettyPrinter()).writeValue(out, json);
            }
            out.flush();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            System.exit(-1);
        }
    } catch (org.apache.commons.cli.ParseException e) {
        printHelp(options);
        System.exit(-1);
    }
}

From source file:xyz.monotalk.social.mixcloud.internal.JsonUtils.java

/**
 * toMap//  www .  jav a 2s .c om
 *
 * @param obj
 * @return
 */
public static Map<String, Object> toMap(Object obj) {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> objectAsMap = mapper.convertValue(obj, Map.class);
    return objectAsMap;
}

From source file:org.netbeans.jcode.parser.ejs.EJSParser.java

public static Map<String, Object> introspect(Object obj) {
    ObjectMapper m = new ObjectMapper();
    Map<String, Object> mappedObject = m.convertValue(obj, Map.class);
    return mappedObject;
}

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

public static <T> PassthroughRequest<T> getRequest(ObjectMapper mapper, Class<T> clazz, Reader node)
        throws IOException {
    final JavaType typeReference = getReferenceFor(mapper, clazz);

    return mapper.convertValue(node, typeReference);
}

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

public static <T> PassthroughRequest<T> getRequest(ObjectMapper mapper, Class<T> clazz, JsonNode node)
        throws IOException {
    final JavaType typeReference = getReferenceFor(mapper, clazz);

    return mapper.convertValue(node, typeReference);
}

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

public static <T> PassthroughRequest<T> getRequest(ObjectMapper mapper, Class<T> clazz, String nodeJsonContent)
        throws IOException {
    final JavaType typeReference = getReferenceFor(mapper, clazz);

    return mapper.convertValue(nodeJsonContent, typeReference);
}

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

/**
 * Make a copy of a spec. Rather than implementing the complicated {@link Cloneable} infrastructure, we just
 * round-trip the spec through JSON and copy all specs easily.
 *
 * @param spec The spec to copy./* w  ww  .  j a va  2  s.co  m*/
 * @param <T> The spec type.
 * @return The copied spec.
 */
@SuppressWarnings("unchecked")
public static <T extends AbstractSpec> T copySpec(T spec) {
    if (spec == null) {
        return null;
    }

    ObjectMapper mapper = createMapper();
    JsonNode node = mapper.convertValue(spec, JsonNode.class);
    return (T) mapper.convertValue(node, spec.getClass());
}

From source file:com.sugaronrest.restapicalls.methodcalls.InsertEntry.java

/**
 * Formats and return selected fields.//from  www.  j a  v  a2s. co  m
 *
 * @param entity Java object to update.
 * @param selectFields Selected fields.
 * @return Formatted selected fields.
 */
private static Map<String, Object> EntityToNameValueList(Object entity, List<String> selectFields) {
    if (entity == null) {
        return null;
    }

    ObjectMapper mapper = JsonObjectMapper.getMapper();
    Map<String, Object> tempEntity = mapper.convertValue(entity, Map.class);

    if (tempEntity == null) {
        return null;
    }

    boolean useSelectedFields = (selectFields != null) && (selectFields.size() > 0);
    Map<String, Object> mappedEntity = new HashMap<String, Object>();
    for (Map.Entry<String, Object> mapEntry : tempEntity.entrySet()) {

        String key = mapEntry.getKey();
        if (useSelectedFields) {
            if (!selectFields.contains(key)) {
                continue;
            }
        }

        if (key.equalsIgnoreCase("id")) {
            continue;
        }

        Map<String, Object> namevalueDic = new HashMap<String, Object>();
        namevalueDic.put("name", key);
        namevalueDic.put("value", mapEntry.getValue());

        mappedEntity.put(key, namevalueDic);
    }

    return mappedEntity;
}