Example usage for com.fasterxml.jackson.databind JsonNode get

List of usage examples for com.fasterxml.jackson.databind JsonNode get

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode get.

Prototype

public JsonNode get(String paramString) 

Source Link

Usage

From source file:controllers.user.UserSettingApp.java

/**
 * ????/*  w ww .  jav a2 s  .c o m*/
 * 
 * @return
 */
public static Result sendPhoneVerificationCode() {
    JsonNode json = getJson();

    // ?
    boolean isValidParams = json.hasNonNull("phoneNum");
    if (!isValidParams) {
        return illegalParameters();
    }

    User user = User.getFromSession(session());
    ObjectNodeResult result = new ObjectNodeResult();
    String phoneNum = json.get("phoneNum").asText();

    if (HelomeUtil.trim(phoneNum).length() != 11) {
        result.error("?");
    } else {
        SendVerifyCodeResult sendResult = PhoneVerifyCodeService
                .sendVerifyCode(PhoneVerifyCodeType.BIND_MOBILE_PHONE, String.valueOf(user.id), phoneNum);

        if (SendVerifyCodeResult.TOO_MANY == sendResult) {
            result.error("?????,????");
        } else if (SendVerifyCodeResult.FAIL == sendResult) {
            result.error("????");
        }
    }

    return ok(result.getObjectNode());
}

From source file:io.fabric8.profiles.ProfilesHelpers.java

public static JsonNode merge(JsonNode target, JsonNode source) {
    if (target == null) {
        return source;
    }//from  w  ww .  j ava  2  s .c  o  m
    if (target.isArray() && source.isArray()) {
        // we append values from the source.
        ArrayNode copy = (ArrayNode) target.deepCopy();
        for (JsonNode n : source) {
            if ((n.isTextual() && DELETED.equals(n.textValue()))) {
                copy = JsonNodeFactory.instance.arrayNode();
            } else {
                copy.add(n);
            }
        }
        return copy;
    } else if (target.isObject() && source.isObject()) {
        ObjectNode copy = (ObjectNode) target.deepCopy();
        if (source.get(DELETED) != null) {
            copy = JsonNodeFactory.instance.objectNode();
        } else {
            Iterator<String> iterator = source.fieldNames();
            while (iterator.hasNext()) {
                String key = iterator.next();
                if (!DELETED.equals(key)) {
                    JsonNode value = source.get(key);
                    if ((value.isTextual() && DELETED.equals(value.textValue()))) {
                        copy.remove(key);
                    } else {
                        JsonNode original = target.get(key);
                        value = merge(original, value);
                        copy.set(key, value);
                    }
                }
            }
        }
        return copy;
    } else {
        return source;
    }

}

From source file:org.dd4t.databind.builder.json.JsonModelConverter.java

private static void fillLinkedComponentValues(final JsonNode currentField, final List<JsonNode> nodeList) {
    // Get the actual values from the values
    // if the Model's field is List, grab all embedded values
    // if it's a normal class (ComponentImpl or similar), just get the first

    final Iterator<JsonNode> nodes = currentField.get(DataBindConstants.LINKED_COMPONENT_VALUES_NODE)
            .elements();//from ww  w . j  ava2 s  .co  m
    while (nodes.hasNext()) {
        nodeList.add(nodes.next());
    }
}

From source file:de.thingweb.desc.ThingDescriptionParser.java

private static Thing parse(JsonNode td) throws Exception {
    // ProcessingReport report =
    // JsonSchemaFactory.byDefault().getValidator().validate(TD_SCHEMA, td);
    // if (!report.isSuccess()) {
    // throw new IOException("JSON data not valid");
    // }//  w w w  .  j av  a 2 s.com

    Thing thing = new Thing(td.get("name").asText());

    Iterator<String> tdIterator = td.fieldNames();
    while (tdIterator.hasNext()) {
        switch (tdIterator.next()) {
        case "@context":
            if (td.get("@context") == null || td.get("@context").getNodeType() == JsonNodeType.NULL) {
                thing.getMetadata().add("@context", factory.textNode(WOT_TD_CONTEXT));
            } else {
                thing.getMetadata().add("@context", td.get("@context"));
            }
            break;
        case "uris":
            thing.getMetadata().add("uris", td.get("uris"));
            break;
        case "@type":
            thing.getMetadata().add("@type", td.get("@type"));
            break;
        case "security":
            thing.getMetadata().add("security", td.get("security"));
            break;

        case "properties":
            for (JsonNode prop : td.get("properties")) {
                Property.Builder builder = Property.getBuilder(prop.get("name").asText());
                Iterator<String> it = prop.fieldNames();
                while (it.hasNext()) {
                    switch (it.next()) {
                    case "valueType":
                        JsonNode jn = prop.get("valueType");
                        builder.setValueType(jn);
                        break;
                    case "@type":
                        builder.setPropertyType(prop.get("@type").asText());
                        break;
                    case "writable":
                        builder.setWriteable(prop.get("writable").asBoolean());
                        break;
                    case "hrefs":
                        builder.setHrefs(stringOrArray(prop.get("hrefs")));
                        break;
                    case "security":
                        builder.setSecurity(prop.get("security"));
                        break;
                    case "stability":
                        builder.setStability(prop.get("stability").asInt());
                        break;
                    }
                }
                thing.addProperty(builder.build());
            }
            break;

        case "actions":
            for (JsonNode action : td.get("actions")) {
                Action.Builder builder = Action.getBuilder(action.get("name").asText());
                Iterator<String> it = action.fieldNames();
                while (it.hasNext()) {
                    switch (it.next()) {
                    case "inputData":
                        JsonNode jnI = action.get("inputData").get("valueType");
                        builder.setInputType(jnI);
                        break;
                    case "outputData":
                        JsonNode jnO = action.get("outputData").get("valueType");
                        builder.setOutputType(jnO);
                        break;
                    case "@type":
                        builder.setActionType(action.get("@type").asText());
                        break;
                    case "hrefs":
                        builder.setHrefs(stringOrArray(action.get("hrefs")));
                        break;
                    case "security":
                        builder.setSecurity(action.get("security"));
                        break;
                    }
                }
                thing.addAction(builder.build());
            }
            break;

        case "events":
            for (JsonNode event : td.get("events")) {
                Event.Builder builder = Event.getBuilder(event.get("name").asText());
                Iterator<String> it = event.fieldNames();
                while (it.hasNext()) {
                    switch (it.next()) {
                    case "valueType":
                        JsonNode jn = event.get("valueType");
                        builder.setValueType(jn);
                        break;
                    case "@type":
                        builder.setEventType(event.get("@type").asText());
                        break;
                    case "hrefs":
                        builder.setHrefs(stringOrArray(event.get("hrefs")));
                        break;
                    case "security":
                        builder.setSecurity(event.get("security"));
                        break;
                    }
                }
                thing.addEvent(builder.build());
            }
            break;

        case "encodings":
            thing.getMetadata().add("encodings", td.get("encodings"));
            break;
        }
    }

    return thing;
}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

public static String login(String email, String pass) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath("Login").build().toString();
    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.POST);
    addRequestHeader(conn, true);//from w w  w  .  ja va  2s . c  om

    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);

    try {
        // hash the password
        pass = Utilities.computeHash(pass);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, e.getLocalizedMessage());
    }
    // Build JSON Object
    jgen.writeStartObject();
    jgen.writeStringField(Keys.User.EMAIL, email);
    jgen.writeStringField("password", pass);
    jgen.writeEndObject();
    jgen.close();

    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    ps.close();

    // Send payload
    int responseCode = sendPostPayload(conn, payload);
    String response = getServerResponse(conn);

    /*
     * result should get valid={"userID":"##"}
     * invalid={"errorID":"3","errorMessage":"invalid username or password"}
     */
    String result = "";
    if (!response.isEmpty()) {
        JsonNode tree = MAPPER.readTree(response);
        if (!tree.has(Keys.User.ID)) {
            logError(TAG, tree);
            result = "invalid username or password";
        } else
            result = tree.get(Keys.User.ID).asText();
    }

    conn.disconnect();
    return result;

}

From source file:com.heliosapm.mws.server.net.json.JSONRequest.java

public static JSONRequest newJSONRequest(final Channel channel, final WebSocketFrame frame) {
    final ChannelBuffer cb = frame.getBinaryData();
    InputStream is = null;/*from w  w  w. ja  v a2  s. c  o  m*/
    try {
        is = new ChannelBufferInputStream(cb);
        JsonNode jsonNode = jsonMapper.readTree(is);
        return new JSONRequest(channel, jsonNode.get("t").asText(), jsonNode.get("rid").asLong(-1L), -1L,
                jsonNode.get("svc").asText(), jsonNode.get("op").asText(), jsonNode);
    } catch (Exception e) {
        throw new RuntimeException("Failed to parse JsonNode from passed frame buffer [" + frame + "]", e);
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (Exception x) {
                /* No Op */}
    }
}

From source file:controllers.user.UserSettingApp.java

/**
 * /*  w w  w.ja v  a  2 s  . c  om*/
 * 
 * @return
 */
@Transactional(readOnly = false)
public static Result changeEmail() {
    JsonNode json = getJson();

    // ?
    boolean isValidParams = json.hasNonNull("old") && json.hasNonNull("new") && json.hasNonNull("psw");
    if (!isValidParams) {
        return illegalParameters();
    }

    User user = User.getFromSession(session());

    // email
    ObjectNodeResult result = User.changeEmail(user, json.get("old").asText(), json.get("new").asText(),
            json.get("psw").asText(), session());

    return ok(result.getObjectNode());
}

From source file:com.blackberry.bdp.common.versioned.ZkVersioned.java

/**
 * Iterates over json1 which is intended to be a full representation of a complete JSON 
 * structure.  It compares nodes on json1 against nodes on json2 which should contain 
 * either the same identical structure of json1 or a subset of JSON structure contained 
 * in json1.//from   w  ww . j  a  v  a2s  . c  o  m
 * 
 * If identically named nodes on json1 and json2 vary in type (ObjectNode vs ArrayNode
 * for example) then an exception is thrown since json2 must not contain any additional 
 * structure than what is found in json1.
 * 
 * Explicit Null Node Handling Regardless of Node type:
 * 
 * This pertains to the value of a node being explicity equal to null.  See further below 
 * for handling of non-existent nodes
 * 
 * If a node is null on json1 and not null on json2 then the node on json1 is set to the 
 * value of the node on json2.
 * 
 * If a node is not null on json1 and is null on json2 then the node on json1 is made null.
 * 
 * Non-existent Node Handling:
 *
 * Since json1 is intended to be a full representation of a  complete JSON structure 
 * nodes on json2 that don't exist on json1 are completely ignored.  Only if the same
 * node exists on both json1 and json2 will the structures be merged.
 * 
 * ArrayNode Handling
 * 
 * If the node being compared is an ArrayNode then the elements on json2 are iterated
 * over.  If the index on json1 exists on json1 then the two elements are merged.  If the 
 * index doesn't exist on json1 then the element is added to the ArrayNode on json1.
 * Note: The existence of the element on json1 is determined by index and when an 
 * element is added to json1 it's index increases by one.  That shouldn't be a problem 
 * though as for there to ever be more elements in json2, the index pointer will always 
 * be one larger than the max index of json1.
 * 
 * ArrayNode Handling when json1 contains more elements than json2:
 * 
 * Elements are removed from json1 if they have higher indexes than the size of json2
 * minus 1
 *
 * @param json1
 * @param json2
 * @return
 * @throws com.blackberry.bdp.common.exception.JsonMergeException
 */
public static JsonNode merge(JsonNode json1, JsonNode json2) throws JsonMergeException {
    Iterator<String> json1Fields = json1.fieldNames();
    LOG.info("Merged called on json1 ({}), json2 ({})", json1.getNodeType(), json2.getNodeType());

    while (json1Fields.hasNext()) {
        String nodeName = json1Fields.next();
        JsonNode json1Node = json1.get(nodeName);

        // Check if json2 has the node and run explicit null checks         
        if (!json2.has(nodeName)) {
            LOG.info("Not comparing {} since it doesn't exist on json2", nodeName);
            continue;
        } else if (json1Node.isNull() && json2.hasNonNull(nodeName)) {
            ((ObjectNode) json1).replace(nodeName, json2.get(nodeName));
            LOG.info("explicit null {} on json1 replaced with non-null from json2", nodeName);
            continue;
        } else if (json1.hasNonNull(nodeName) && json2.get(nodeName).isNull()) {
            ((ObjectNode) json1).replace(nodeName, json2.get(nodeName));
            LOG.info("non-null {} on json1 replaced with explicitly null on json2", nodeName);
            continue;
        }

        JsonNode json2Node = json2.get(nodeName);

        if (json1Node.getNodeType().equals(json2Node.getNodeType()) == false) {
            throw new JsonMergeException(String.format("json1 (%s) cannot be merged with json2 (%s)",
                    json1.getNodeType(), json2.getNodeType()));
        }

        LOG.info("need to compare \"{}\" which is a {}", nodeName, json1Node.getNodeType());

        if (json1Node.isObject()) {
            LOG.info("Calling merge on object {}", nodeName);
            merge(json1Node, json2.get(nodeName));
        } else if (json1Node instanceof ObjectNode) {
            throw new JsonMergeException("{} is instance of ObjectNode and wasn't isObject()--what gives?!");
        } else if (json1Node.isArray()) {
            ArrayNode json1Array = (ArrayNode) json1Node;
            ArrayNode json2Array = (ArrayNode) json2Node;
            LOG.info("ArrayNode {} json1 has {} elements and json2 has {} elements", nodeName,
                    json1Array.size(), json2Array.size());
            int indexNo = 0;
            Iterator<JsonNode> json2Iter = json2Array.iterator();
            while (json2Iter.hasNext()) {
                JsonNode json2Element = json2Iter.next();
                if (json1Array.has(indexNo)) {
                    LOG.info("Need to merge ArrayNode {} element {}", nodeName, indexNo);
                    merge(json1Node.get(indexNo), json2Element);
                } else {
                    LOG.info("ArrayNode {} element {} not found on json1, adding", nodeName, indexNo);
                    json1Array.add(json2Element);
                }
                indexNo++;
            }
            while (json1Array.size() > json2Array.size()) {
                int indexToRemove = json1Array.size() - 1;
                json1Array.remove(indexToRemove);
                LOG.info("ArrayNode {} index {} on json1 removed since greater than size of json2 ({})",
                        nodeName, indexToRemove, json2Array.size());
            }
        } else {
            LOG.info("{} ({}) has fallen through known merge types", nodeName, json1Node.getNodeType());
            ((ObjectNode) json1).replace(nodeName, json2Node);
            LOG.info("json1 node {} replaced with json2's node", nodeName);
        }
    }
    return json1;
}

From source file:mobile.service.GroupService.java

/**
 * ??//www  .  j a  va2  s.c  o m
 *
 * @param messageId ?Id
 * @return
 */
public static ServiceResult agreeJoinGroupApply(Long messageId) {
    User me = User.getFromSession(Context.current().session());

    Message message = Message.queryById(messageId);
    if (null == message || message.msgType != MsgType.APPLY_GROUP
            || !Objects.equals(message.consumeOnly, me.id.toString())) {
        return ServiceResult.error("100005", "?messageId = " + messageId);
    }

    User senderUser = User.findById(NumberUtils.toLong(message.senderOnly, -1));
    if (null == senderUser) {
        LOGGER.error("invalid senderId. message.content = " + message.content);
        return ServiceResult.error("100001", "");
    }

    JsonNode content = Json.parse(message.content);

    long groupId = content.get("groupId").asLong(-1);
    Group group = Group.queryGroupById(groupId);
    if (null == group) {
        return ServiceResult.error("2001", "?");
    }
    List<Long> groupIdList = Arrays.asList(groupId);
    Map<Long, Boolean> checkJoinGroup = models.GroupMember.checkJoinGroup(senderUser.getId(), groupIdList);
    if (checkJoinGroup.get(groupId) == true) {
        MessageService.handlerMessage(messageId);
        return ServiceResult.error("2004", "??");
    }

    try {
        ChatService.appendMemberToGroup(groupId, senderUser.getId());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    MessageService.pushMsgApplyAgree(me, senderUser, group);
    MessageService.handlerMessage(messageId);
    return ServiceResult.success();
}

From source file:org.kitesdk.apps.streaming.StreamDescription.java

public static StreamDescription parseJson(String json) {

    ObjectMapper mapper = new ObjectMapper();

    JsonNode parent;

    try {/*from   w  w  w .j  a  v a 2 s  . co m*/
        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);
    }

    StreamDescription.Builder builder = new StreamDescription.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);
    }

    // Read the streams.
    ArrayNode streams = (ArrayNode) parent.get(STREAMS);

    for (JsonNode stream : streams) {

        String name = stream.get(NAME).asText();

        ObjectNode props = (ObjectNode) stream.get(PROPS);

        Map<String, String> properties = Maps.newHashMap();

        for (Iterator<Map.Entry<String, JsonNode>> it = props.fields(); it.hasNext();) {

            Map.Entry<String, JsonNode> property = it.next();

            properties.put(property.getKey(), property.getValue().asText());
        }

        builder.withStream(name, properties);
    }

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

    for (JsonNode view : views) {

        String name = view.get(NAME).asText();
        String uri = view.get(URI_PROP).asText();

        builder.withView(name, uri);
    }

    return builder.build();
}