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:com.squarespace.template.plugins.platform.CommerceUtils.java

public static JsonNode getFromPriceMoneyNode(JsonNode item) {
    ProductType type = getProductType(item);
    JsonNode structuredContent = item.path("structuredContent");
    switch (type) {

    case PHYSICAL:
    case SERVICE:
    case GIFT_CARD:
        JsonNode variants = structuredContent.path("variants");
        if (variants.size() == 0) {
            return DEFAULT_MONEY_NODE;
        }//w w  w .  j a  v  a 2  s. c o  m

        JsonNode first = variants.get(0);
        JsonNode moneyNode = isTruthy(first.path("onSale")) ? first.path("salePriceMoney")
                : first.path("priceMoney");
        BigDecimal price = getAmountFromMoneyNode(moneyNode);
        for (int i = 1; i < variants.size(); i++) {
            JsonNode var = variants.get(i);
            JsonNode currentMoneyNode = isTruthy(var.path("onSale")) ? var.path("salePriceMoney")
                    : var.path("priceMoney");

            BigDecimal current = getAmountFromMoneyNode(currentMoneyNode);
            if (current.compareTo(price) < 0) {
                price = current;
                moneyNode = currentMoneyNode;
            }
        }
        return moneyNode;

    case DIGITAL:
        JsonNode digitalMoneyNode = structuredContent.path("priceMoney");
        return digitalMoneyNode.isMissingNode() ? DEFAULT_MONEY_NODE : digitalMoneyNode;

    default:
        return DEFAULT_MONEY_NODE;
    }
}

From source file:com.cyphermessenger.client.SyncRequest.java

private static ArrayList<ECKey> handleKeyNode(JsonNode node, byte[] localPassword) {
    ArrayList<ECKey> array = new ArrayList<>();
    JsonNode arrayNode = node.get("keys");
    if (arrayNode.isArray()) {
        for (JsonNode selectedNode : arrayNode) {
            try {
                ECKey newECKey = Utils.decodeKey(selectedNode.get("publicKey").asText(),
                        selectedNode.get("privateKey").asText(), localPassword);
                newECKey.setTime(selectedNode.get("timestamp").asLong());
                array.add(newECKey);/*from w ww .ja v a 2  s.  co  m*/
            } catch (InvalidCipherTextException ex) {
                Log.e("PULL", "Key decryption failed", ex);
                /** TODO
                 * handle key decryption error
                 */
            }
        }
    }
    return array;
}

From source file:com.github.fge.jsonschema.core.keyword.syntax.checkers.SyntaxCheckersTest.java

private static String buildMessage(final String key, final JsonNode params, final JsonNode data) {
    final ProcessingMessage message = new ProcessingMessage().setMessage(BUNDLE.getMessage(key));
    if (params != null) {
        String name;/*from  w  ww .  j a  v  a 2s .co m*/
        JsonNode value;
        for (final JsonNode node : params) {
            name = node.textValue();
            value = data.get(name);
            message.putArgument(name, valueToArgument(value));
        }
    }
    return message.getMessage();
}

From source file:com.spoiledmilk.cykelsuperstier.break_rote.LocalTrainData.java

private static void getTimesForWeekend(int hour, int minute, ArrayList<ITransportationInfo> times,
        JsonNode timeTableNode, int index1, int index2, int numOfStations, JsonNode dataNodeArray) {
    ArrayList<TimeData> allTimes = new ArrayList<TimeData>();
    for (int i = 0; i < timeTableNode.size(); i++) {
        JsonNode intervalNode = timeTableNode.get(i);
        try {/*  w  ww .  j a  v a  2  s.c om*/
            double currentTime = ((double) hour) + ((double) minute) / 100d;
            double startInterval = intervalNode.get("start-time").asDouble();
            double endInterval = intervalNode.get("end-time").asDouble();
            if (endInterval < 1.0)
                endInterval += 24.0;
            if (currentTime >= startInterval && currentTime <= endInterval) {
                JsonNode dataNode = dataNodeArray.get(i);
                int[] minutesArray = new int[dataNode.size()];
                for (int j = 0; j < minutesArray.length; j++) {
                    minutesArray[j] = dataNode.get(j).asInt();
                }
                int currentHour = hour;
                int currentIndex = 0;
                int count = 0;
                while (currentHour <= endInterval && count < 3 && currentIndex < minutesArray.length) {
                    double time1 = minutesArray[currentIndex + index1];
                    double time2 = minutesArray[currentIndex + index2];
                    if (time1 < 0 || time2 < 0)
                        continue;
                    time1 /= 100d;
                    time1 += currentHour;
                    time2 /= 100d;
                    time2 += currentHour;
                    if (time2 < time1)
                        time2 += 1.0;
                    allTimes.add(new TimeData(time1, time2));
                    currentHour++;
                    count++;
                    currentIndex += numOfStations;
                }
            }
        } catch (Exception e) {
            LOG.e(e.getLocalizedMessage());
        }
    }

    // sort the list
    for (int i = 0; i < allTimes.size() - 1; i++) {
        for (int j = i + 1; j < allTimes.size(); j++) {
            TimeData td1 = allTimes.get(i);
            TimeData td2 = allTimes.get(j);
            if (td1.stationAtime > td2.stationAtime) {
                allTimes.set(i, td2);
                allTimes.set(j, td1);
            }
        }
    }

    LOG.d("sorted times = " + allTimes.toString());

    // return the 3 results
    for (int i = 0; i < 3 && i < allTimes.size(); i++) {
        TimeData temp = allTimes.get(i);
        int time = 0;
        int minutes1 = (int) ((temp.stationAtime - (double) ((int) temp.stationAtime)) * 100);
        int minutes2 = (int) ((temp.stationBtime - (double) ((int) temp.stationBtime)) * 100);
        time = (((int) temp.stationBtime) - ((int) temp.stationAtime)) * 60;
        if (minutes2 >= minutes1)
            time = minutes2 - minutes1;
        else {
            time += 60 - minutes1 + minutes2;
            time -= 60;
        }
        String formattedTime1 = (((int) temp.stationAtime) < 10 ? "0" + ((int) temp.stationAtime)
                : "" + ((int) temp.stationAtime)) + ":" + (minutes1 < 10 ? "0" + minutes1 : "" + minutes1);
        String formattedTime2 = (((int) temp.stationBtime) < 10 ? "0" + ((int) temp.stationBtime)
                : "" + ((int) temp.stationBtime)) + ":" + (minutes2 < 10 ? "0" + minutes2 : "" + minutes2);
        times.add(new LocalTrainData(formattedTime1, formattedTime2, time));
    }

}

From source file:com.servioticy.api.commons.data.CouchBase.java

/**
 * @param userId    // TODO [David] params????
 * @param data_id//from  w  ww .j a  v a2s  .  c o  m
 * @return
 */
public static Data getData(SO so, String streamId) {

    JsonNode stream = so.getStream(streamId);
    if (stream == null)
        return null;

    if (stream.path("data").isMissingNode())
        return null;
    String dataId = stream.get("data").asText();
    //    String storedData = getJsonNode(dataId).toString();
    JsonNode storedJsonData = getJsonNode(dataId);
    String storedData = (storedJsonData != null) ? storedJsonData.toString() : null;

    if (storedData != null) {
        return new Data(dataId, storedData);
    }
    return null;
}

From source file:ext.sns.auth.AccessTokenResponse.java

/**
 * ?AccessTokenResponse??responseStringnull
 * //from w  w  w .  jav a 2 s.c  o  m
 * @param responseString 
 * @param responseType 
 * @return AccessTokenResponsenull - ??responseString
 */
public static AccessTokenResponse create(String responseString) {
    if (StringUtils.isBlank(responseString)) {
        return null;
    }

    AccessTokenResponse response = new AccessTokenResponse();
    response.setResultTypeByResponseStr(responseString);

    if (response.resultType == 1) {
        Map<String, String> responseMap = null;
        try {
            responseMap = parseResponseParam(responseString);
        } catch (RuntimeException e) {
            LOGGER.error("AccessTokenResponse?", e);
        }

        response.raw = responseString;
        response.accessToken = responseMap.get("access_token");

        String expiresInString = responseMap.get("expires_in");
        response.expiresIn = StringUtils.isNumeric(expiresInString) ? Long.valueOf(expiresInString) : null;

        response.refreshToken = responseMap.get("refresh_token");
        response.scope = responseMap.get("scope");
        response.tokenType = responseMap.get("token_type");

        response.resultObject = responseMap;
    } else if (response.resultType == 2) {
        JsonNode responseJSON = null;
        try {
            responseJSON = Json.parse(responseString);
        } catch (RuntimeException e) {
            LOGGER.error("AccessTokenResponse?", e);
        }

        response.raw = responseString;
        response.accessToken = responseJSON.has("access_token") ? responseJSON.get("access_token").asText()
                : null;

        String expiresInString = responseJSON.has("expires_in") ? responseJSON.get("expires_in").asText()
                : null;
        response.expiresIn = StringUtils.isNumeric(expiresInString) ? Long.valueOf(expiresInString) : null;

        response.refreshToken = responseJSON.has("refresh_token") ? responseJSON.get("refresh_token").asText()
                : null;
        response.scope = responseJSON.has("scope") ? responseJSON.get("scope").asText() : null;
        response.tokenType = responseJSON.has("token_type") ? responseJSON.get("token_type").asText() : null;

        response.resultObject = responseJSON;
    } else {
        return null;
    }

    return response;
}

From source file:com.attribyte.essem.util.Util.java

/**
 * Gets the first node of an array or the node itself if it is not an array or null.
 * @param fieldsObj The object containing fields.
 * @param key The key.//www  . j ava2  s. co m
 * @return The node or <code>null</code>.
 */
public static JsonNode getFieldNode(final JsonNode fieldsObj, final String key) {
    JsonNode fieldNode = fieldsObj.get(key);
    if (fieldNode != null) {
        if (fieldNode.isArray() && fieldNode.size() > 0) {
            return fieldNode.get(0);
        } else if (!fieldNode.isArray()) {
            return fieldNode;
        } else {
            return null;
        }
    } else {
        return null;
    }
}

From source file:com.cyphermessenger.client.SyncRequest.java

private static ArrayList<CypherMessage> handleMessageNode(JsonNode node, ECKey key1, ECKey key2) {
    ArrayList<CypherMessage> array = new ArrayList<>();
    JsonNode arrayNode = node.get("messages");
    if (arrayNode.isArray()) {
        for (JsonNode selectedNode : arrayNode) {
            boolean isSender = selectedNode.get("isSender").asBoolean();
            long receivedContactID = selectedNode.get("contactID").asLong();
            long timestamp = selectedNode.get("timestamp").asLong();
            int messageID = selectedNode.get("messageID").asInt();
            byte[] payload = Utils.BASE64_URL.decode(selectedNode.get("payload").asText());
            String plainText = null;

            boolean handleDecryption = false;
            // try to decrypt message
            if (key2 != null)
                try {
                    byte[] sharedSecret = key1.getSharedSecret(key2);
                    plainText = new String(Decrypt.process(sharedSecret, payload, Utils.longToBytes(messageID),
                            Utils.longToBytes(timestamp)));
                    handleDecryption = true;
                } catch (InvalidCipherTextException ex) {
                    Log.e("PULL", "Message decryption failed", ex);
                }/*from   w  ww . j  a va  2 s. c o  m*/
            CypherMessage message;
            if (handleDecryption) {
                message = new CypherMessage(messageID, plainText, timestamp, isSender, receivedContactID);
            } else {
                message = new CypherMessage(messageID, payload, timestamp, isSender, receivedContactID);
            }
            array.add(message);
        }
    }
    return array;
}

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

@Deprecated
private static Thing parseOld(JsonNode td) throws IOException {
    try {// w w  w  . j a v a 2s.c  o  m
        Thing thing = new Thing(td.get("metadata").get("name").asText());

        Iterator<String> tdIterator = td.fieldNames();
        while (tdIterator.hasNext()) {
            switch (tdIterator.next()) {
            case "metadata":
                Iterator<String> metaIterator = td.get("metadata").fieldNames();
                while (metaIterator.hasNext()) {
                    switch (metaIterator.next()) {
                    case "encodings":
                        for (JsonNode encoding : td.get("metadata").get("encodings")) {
                            thing.getMetadata().add("encodings", encoding);
                        }
                        break;

                    case "protocols":
                        TreeMap<Long, String> orderedURIs = new TreeMap<>();
                        for (JsonNode protocol : td.get("metadata").get("protocols")) {
                            orderedURIs.put(protocol.get("priority").asLong(), protocol.get("uri").asText());
                        }
                        if (orderedURIs.size() == 1) {
                            thing.getMetadata().add("uris", factory.textNode(orderedURIs.get(0)));
                        } else {
                            ArrayNode an = factory.arrayNode();
                            for (String uri : orderedURIs.values()) {
                                // values returned in ascending order
                                an.add(uri);
                            }
                            thing.getMetadata().add("uris", an);
                        }

                        break;
                    }
                }
                break;

            case "interactions":
                for (JsonNode inter : td.get("interactions")) {
                    if (inter.get("@type").asText().equals("Property")) {
                        Property.Builder builder = Property.getBuilder(inter.get("name").asText());
                        Iterator<String> propIterator = inter.fieldNames();
                        while (propIterator.hasNext()) {
                            switch (propIterator.next()) {
                            case "outputData":
                                builder.setValueType(inter.get("outputData"));
                                break;
                            case "writable":
                                builder.setWriteable(inter.get("writable").asBoolean());
                                break;
                            }
                        }
                        thing.addProperty(builder.build());
                    } else if (inter.get("@type").asText().equals("Action")) {
                        Action.Builder builder = Action.getBuilder(inter.get("name").asText());
                        Iterator<String> actionIterator = inter.fieldNames();
                        while (actionIterator.hasNext()) {
                            switch (actionIterator.next()) {
                            case "inputData":
                                builder.setInputType(inter.get("inputData").asText());
                                break;
                            case "outputData":
                                builder.setOutputType(inter.get("outputData").asText());
                                break;
                            }
                        }
                        thing.addAction(builder.build());
                    } else if (inter.get("@type").asText().equals("Event")) {
                        Event.Builder builder = Event.getBuilder(inter.get("name").asText());
                        Iterator<String> actionIterator = inter.fieldNames();
                        while (actionIterator.hasNext()) {
                            switch (actionIterator.next()) {
                            case "outputData":
                                builder.setValueType(inter.get("outputData"));
                                break;
                            }
                        }
                        thing.addEvent(builder.build());
                    }
                }
                break;
            }
        }

        return thing;
    } catch (Exception e) { // anything could happen here
        throw new IOException("unable to parse Thing Description");
    }
}

From source file:com.attribyte.essem.util.Util.java

/**
 * Gets an int value from a node.//w w w .ja v  a  2 s. c  o  m
 * @param node The parent node.
 * @param key The key.
 * @param defaultValue The default value.
 * @return The value or default value.
 */
public static int getIntField(final JsonNode node, final String key, final int defaultValue) {
    JsonNode field = node.get(key);
    if (field != null && field.canConvertToInt()) {
        return field.intValue();
    } else {
        return defaultValue;
    }
}