Example usage for com.fasterxml.jackson.core JsonParser readValueAsTree

List of usage examples for com.fasterxml.jackson.core JsonParser readValueAsTree

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonParser readValueAsTree.

Prototype

@SuppressWarnings("unchecked")
public <T extends TreeNode> T readValueAsTree() throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content into equivalent "tree model", represented by root TreeNode of resulting model.

Usage

From source file:client.json.JsonSerialization.java

/**
 * Creates an {@link ObjectNode} based on the given {@code pojo}, copying all its properties to the resulting {@link ObjectNode}.
 *
 * @param pojo a pojo which properties will be populates into the resulting a {@link ObjectNode}
 * @return a {@link ObjectNode} with all the properties from the given pojo
 * @throws IOException if the resulting a {@link ObjectNode} can not be created
 */// w  w  w.j a  va  2  s  .c o  m
public static ObjectNode createObjectNode(Object pojo) throws IOException {
    if (pojo == null) {
        throw new IllegalArgumentException("Pojo can not be null.");
    }

    ObjectNode objectNode = createObjectNode();
    JsonParser jsonParser = mapper.getJsonFactory().createJsonParser(writeValueAsBytes(pojo));
    JsonNode jsonNode = jsonParser.readValueAsTree();

    if (!jsonNode.isObject()) {
        throw new RuntimeException("JsonNode [" + jsonNode + "] is not a object.");
    }

    objectNode.putAll((ObjectNode) jsonNode);

    return objectNode;
}

From source file:info.bonjean.quinkana.Main.java

private static void run(String[] args) throws QuinkanaException {
    Properties properties = new Properties();
    InputStream inputstream = Main.class.getResourceAsStream("/config.properties");

    try {//  w w w  .  j a va 2s  .  c  o m
        properties.load(inputstream);
        inputstream.close();
    } catch (IOException e) {
        throw new QuinkanaException("cannot load internal properties", e);
    }

    String name = (String) properties.get("name");
    String description = (String) properties.get("description");
    String url = (String) properties.get("url");
    String version = (String) properties.get("version");
    String usage = (String) properties.get("help.usage");
    String defaultHost = (String) properties.get("default.host");
    int defaultPort = Integer.valueOf(properties.getProperty("default.port"));

    ArgumentParser parser = ArgumentParsers.newArgumentParser(name).description(description)
            .epilog("For more information, go to " + url).version("${prog} " + version).usage(usage);
    parser.addArgument("ACTION").type(Action.class).choices(Action.tail, Action.list).dest("action");
    parser.addArgument("-H", "--host").setDefault(defaultHost)
            .help(String.format("logstash host (default: %s)", defaultHost));
    parser.addArgument("-P", "--port").type(Integer.class).setDefault(defaultPort)
            .help(String.format("logstash TCP port (default: %d)", defaultPort));
    parser.addArgument("-f", "--fields").nargs("+").help("fields to display");
    parser.addArgument("-i", "--include").nargs("+").help("include filter (OR), example host=example.com")
            .metavar("FILTER").type(Filter.class);
    parser.addArgument("-x", "--exclude").nargs("+")
            .help("exclude filter (OR, applied after include), example: severity=debug").metavar("FILTER")
            .type(Filter.class);
    parser.addArgument("-s", "--single").action(Arguments.storeTrue()).help("display single result and exit");
    parser.addArgument("--version").action(Arguments.version()).help("output version information and exit");

    Namespace ns = parser.parseArgsOrFail(args);

    Action action = ns.get("action");
    List<String> fields = ns.getList("fields");
    List<Filter> includes = ns.getList("include");
    List<Filter> excludes = ns.getList("exclude");
    boolean single = ns.getBoolean("single");
    String host = ns.getString("host");
    int port = ns.getInt("port");

    final Socket clientSocket;
    final InputStream is;
    try {
        clientSocket = new Socket(host, port);
        is = clientSocket.getInputStream();
    } catch (IOException e) {
        throw new QuinkanaException("cannot connect to the server " + host + ":" + port, e);
    }

    // add a hook to ensure we clean the resources when leaving
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    // prepare JSON parser
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jsonFactory = mapper.getFactory();
    JsonParser jp;
    try {
        jp = jsonFactory.createParser(is);
    } catch (IOException e) {
        throw new QuinkanaException("error during JSON parser creation", e);
    }

    JsonToken token;

    // action=list
    if (action.equals(Action.list)) {
        try {
            // do this in a separate loop to not pollute the main loop
            while ((token = jp.nextToken()) != null) {
                if (token != JsonToken.START_OBJECT)
                    continue;

                // parse object
                JsonNode node = jp.readValueAsTree();

                // print fields
                Iterator<String> fieldNames = node.fieldNames();
                while (fieldNames.hasNext())
                    System.out.println(fieldNames.next());

                System.exit(0);
            }
        } catch (IOException e) {
            throw new QuinkanaException("error during JSON parsing", e);
        }
    }

    // action=tail
    try {
        while ((token = jp.nextToken()) != null) {
            if (token != JsonToken.START_OBJECT)
                continue;

            // parse object
            JsonNode node = jp.readValueAsTree();

            // filtering (includes)
            if (includes != null) {
                boolean skip = true;
                for (Filter include : includes) {
                    if (include.match(node)) {
                        skip = false;
                        break;
                    }
                }
                if (skip)
                    continue;
            }

            // filtering (excludes)
            if (excludes != null) {
                boolean skip = false;
                for (Filter exclude : excludes) {
                    if (exclude.match(node)) {
                        skip = true;
                        break;
                    }
                }
                if (skip)
                    continue;
            }

            // if no field specified, print raw output (JSON)
            if (fields == null) {
                System.out.println(node.toString());
                if (single)
                    break;
                continue;
            }

            // formatted output, build and print the string
            StringBuilder sb = new StringBuilder(128);
            for (String field : fields) {
                if (sb.length() > 0)
                    sb.append(" ");

                if (node.get(field) != null && node.get(field).textValue() != null)
                    sb.append(node.get(field).textValue());
            }
            System.out.println(sb.toString());

            if (single)
                break;
        }
    } catch (IOException e) {
        throw new QuinkanaException("error during JSON parsing", e);
    }
}

From source file:org.nuxeo.client.api.marshaller.AutomationMarshaller.java

@Override
public Object read(JsonParser jp) throws IOException {
    String json = jp.readValueAsTree().toString();
    return null;//from ww  w  .ja  v  a2s.  c o  m
}

From source file:org.hyperledger.jackson.OutpointDeserializer.java

@Override
public Outpoint deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode node = jp.readValueAsTree();
    TID h = new TID(node.get(0).asText());
    int ix = node.get(1).asInt();
    return new Outpoint(h, ix);
}

From source file:com.cloudant.mazha.json.OpenRevisionDeserializer.java

@Override
public OpenRevision deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    ObjectNode node = jp.readValueAsTree();
    if (node.has("ok")) {
        return jp.getCodec().treeToValue(node, OkOpenRevision.class);
    } else if (node.has("missing")) {
        return jp.getCodec().treeToValue(node, MissingOpenRevision.class);
    } else {/*w  w  w. j a  v  a2s  . c  o m*/
        // Should never happen
        throw new IllegalStateException("Unexpected object in open revisions response.");
    }
}

From source file:alpine.json.TrimmedStringDeserializer.java

@Override
public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
    final JsonNode node = jsonParser.readValueAsTree();
    return StringUtils.trimToNull(node.asText());
}

From source file:org.jmingo.mapping.convert.mongo.type.deserialize.ObjectIdDeserializer.java

/**
 * {@inheritDoc}/*from  w  w  w  . j  av a 2  s . c  om*/
 */
@Override
public ObjectId deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    TreeNode treeNode = jp.readValueAsTree();
    JsonNode oid = ((JsonNode) treeNode).get(MONGO_OID);
    if (oid != null)
        return getAsObjectId(oid);
    else {
        return getAsObjectId((JsonNode) treeNode);
    }
}

From source file:org.jongo.marshall.jackson.NativeDeserializer.java

@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    String asString = jp.readValueAsTree().toString();
    return JSON.parse(asString);
}

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

@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    JsonNode node = jp.readValueAsTree();
    return node.get(VALUE).textValue();
}

From source file:com.github.tomakehurst.wiremock.http.HttpHeadersJsonDeserializer.java

@Override
public HttpHeaders deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    JsonNode rootNode = parser.readValueAsTree();
    return new HttpHeaders(transform(all(rootNode.fields()), toHttpHeaders()));
}