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.meetingninja.csse.database.UserDatabaseAdapter.java

public static SerializableUser parseUser(JsonNode node) {
    SerializableUser u = new SerializableUser(); // start parsing a user
    // if they at least have an id, email, and name
    if (node.hasNonNull(Keys.User.EMAIL) && node.hasNonNull(Keys.User.NAME)
    // && node.hasNonNull(KEY_ID)
    ) {//from   w  w  w .ja v  a  2 s.com
        String email = node.get(Keys.User.EMAIL).asText();
        // if their email is in a reasonable format
        if (!TextUtils.isEmpty(node.get(Keys.User.NAME).asText()) && Utilities.isValidEmailAddress(email)) {
            // set the required fields
            if (node.hasNonNull(Keys.User.ID))
                u.setID(node.get(Keys.User.ID).asText());
            u.setDisplayName(node.get(Keys.User.NAME).asText());
            u.setEmail(email);

            // check and set the optional fields
            u.setLocation(JsonUtils.getJSONValue(node, Keys.User.LOCATION));
            u.setPhone(JsonUtils.getJSONValue(node, Keys.User.PHONE));
            u.setCompany(JsonUtils.getJSONValue(node, Keys.User.COMPANY));
            u.setTitle(JsonUtils.getJSONValue(node, Keys.User.TITLE));
        } else {
            // Log.w(TAG, "Parsed null user");
            return null;
        }
    } else {
        // Log.w(TAG, "Parsed null user");
        return null;
    }
    return u;
}

From source file:controllers.user.UserSettingApp.java

/**
 * ?,?/* ww w  . j  a v a2  s .c om*/
 * 
 * @return
 */
@Transactional(readOnly = false)
public static Result bindNewPhone() {
    JsonNode json = getJson();

    // ?
    if (!json.hasNonNull("code") || !json.hasNonNull("newPhoneNum") || !json.hasNonNull("key")) {
        return illegalParameters();
    }

    User user = User.getFromSession(session());
    ObjectNodeResult result = new ObjectNodeResult();

    Long userId = (Long) Cache.get(Constants.CACHE_CHANGE_PHONE_BY_EMAIL_KEY_CU + json.get("key").asText());
    if (null == userId) {
        return ok(result.error("??????")
                .getObjectNode());
    }
    if (!user.id.equals(userId)) {
        return ok(result.error(
                "?????????")
                .getObjectNode());
    }

    result = User.bindNewPhone(user, json.findPath("newPhoneNum").asText(), json.findPath("code").asText(),
            session());
    if (result.isSuccess()) {
        //user-code key
        String ucKey = Constants.CACHE_CHANGE_PHONE_BY_EMAIL_KEY_UC + user.id;

        String oldCode = (String) Cache.get(ucKey);
        if (StringUtils.isNotBlank(oldCode)) {
            String oldCUKey = Constants.CACHE_CHANGE_PHONE_BY_EMAIL_KEY_CU + oldCode;
            Cache.remove(ucKey);
            Cache.remove(oldCUKey);
        }
    }

    return ok(result.getObjectNode());
}

From source file:controllers.nwbib.Application.java

static Promise<Result> call(final String q, final String person, final String name, final String subject,
        final String id, final String publisher, final String issued, final String medium,
        final String nwbibspatial, final String nwbibsubject, final int from, final int size, String owner,
        String t, String sort, boolean showDetails, String set, String location, String word,
        String corporation, String raw) {
    final WSRequestHolder requestHolder = Lobid.request(q, person, name, subject, id, publisher, issued, medium,
            nwbibspatial, nwbibsubject, from, size, owner, t, sort, showDetails, set, location, word,
            corporation, raw);/*from  ww  w.ja  v a2  s  . c  o m*/
    return requestHolder.get().map((WSResponse response) -> {
        Long hits = 0L;
        String s = "{}";
        if (response.getStatus() == Http.Status.OK) {
            JsonNode json = response.asJson();
            hits = Lobid.getTotalResults(json);
            s = json.toString();
            if (id.isEmpty()) {
                List<JsonNode> ids = json.findValues("hbzId");
                uncache(ids.stream().map(j -> j.asText()).collect(Collectors.toList()));
                Cache.set(session("uuid") + "-lastSearch", ids.toString(), ONE_DAY);
            }
        } else {
            Logger.warn("{}: {} ({}, {})", response.getStatus(), response.getStatusText(),
                    requestHolder.getUrl(), requestHolder.getQueryParameters());
        }
        if (showDetails) {
            String json = "";
            JsonNode nodes = Json.parse(s);
            if (nodes.isArray() && nodes.size() == 2) { // first: metadata
                json = nodes.get(1).toString();
            } else {
                Logger.warn("No suitable data to show details for: {}", nodes);
            }
            return ok(details.render(CONFIG, json, id));
        }
        return ok(search.render(s, q, person, name, subject, id, publisher, issued, medium, nwbibspatial,
                nwbibsubject, from, size, hits, owner, t, sort, set, location, word, corporation, raw));
    });
}

From source file:controllers.nwbib.Lobid.java

/**
 * @param itemUri The lobid item URI//from   w w  w  . ja v  a2s.co  m
 * @return The OPAC URL for the given item, or null
 */
public static String opacUrl(String itemUri) {
    try (InputStream stream = Play.application().resourceAsStream("isil2opac_hbzid.json")) {
        JsonNode json = Json.parse(stream);
        String[] hbzId_isil_sig = itemUri.substring(itemUri.indexOf("item/") + 5).split(":");
        String hbzId = hbzId_isil_sig[0];
        String isil = hbzId_isil_sig[1];
        Logger.debug("From item URI {}, got ISIL {} and HBZ-ID {}", itemUri, isil, hbzId);
        JsonNode urlTemplate = json.get(isil);
        if (urlTemplate != null)
            return urlTemplate.asText().replace("{hbzid}", hbzId);
    } catch (IOException e) {
        Logger.error("Could not create OPAC URL", e);
    }
    return null;
}

From source file:models.daos.DatasetDao.java

public static ObjectNode getDatasetDependency(JsonNode input) throws Exception {

    ObjectNode resultJson = Json.newObject();
    String cluster = DEFAULT_CLUSTER_NAME;
    String datasetUri = null;/*from   ww  w.  java  2  s .c  o  m*/
    String dbName = null;
    String tableName = null;
    boolean isHive = false;
    boolean isDalids = false;
    if (input != null && input.isContainerNode()) {
        if (input.has(CLUSTER_NAME_KEY)) {
            cluster = input.get(CLUSTER_NAME_KEY).asText();
        }
        if (input.has(DATASET_URI_KEY)) {
            datasetUri = input.get(DATASET_URI_KEY).asText();
        }
    }

    if (StringUtils.isBlank(datasetUri)) {
        resultJson.put("return_code", 404);
        resultJson.put("message", "Wrong input format! Missing dataset uri");
        return resultJson;
    }

    Integer index = -1;
    if ((index = datasetUri.indexOf(HIVE_PREFIX_WITH_3_SLASH)) != -1) {
        isHive = true;
        String tmp = datasetUri.substring(index + HIVE_PREFIX_WITH_3_SLASH.length());
        String[] info = tmp.split("\\.|/");
        if (info != null && info.length == 2) {
            dbName = info[0];
            tableName = info[1];
        }
    } else if ((index = datasetUri.indexOf(DALIDS_PREFIX_WITH_3_SLASH)) != -1) {
        isDalids = true;
        String tmp = datasetUri.substring(index + DALIDS_PREFIX_WITH_3_SLASH.length());
        String[] info = tmp.split("\\.|/");
        if (info != null && info.length == 2) {
            dbName = info[0];
            tableName = info[1];
        }
    } else if ((index = datasetUri.indexOf(HIVE_PREFIX_WITH_2_SLASH)) != -1) {
        isHive = true;
        String tmp = datasetUri.substring(index + HIVE_PREFIX_WITH_2_SLASH.length());
        String[] info = tmp.split("\\.|/");
        if (info != null && info.length == 3) {
            cluster = info[0];
            dbName = info[1];
            tableName = info[2];
        }
    } else if ((index = datasetUri.indexOf(DALIDS_PREFIX_WITH_2_SLASH)) != -1) {
        isDalids = true;
        String tmp = datasetUri.substring(index + DALIDS_PREFIX_WITH_2_SLASH.length());
        String[] info = tmp.split("\\.|/");
        if (info != null && info.length == 3) {
            cluster = info[0];
            dbName = info[1];
            tableName = info[2];
        }
    } else if (datasetUri.indexOf('.') != -1) {
        index = datasetUri.indexOf(':');
        String tmp = datasetUri;
        if (index != -1) {
            cluster = datasetUri.substring(0, index);
            tmp = datasetUri.substring(index + 1);
        }
        String[] info = tmp.split("\\.|/");
        if (info != null && info.length == 2) {
            dbName = info[0];
            tableName = info[1];
        }
    }

    if (StringUtils.isBlank(cluster) || StringUtils.isBlank(dbName) || StringUtils.isBlank(tableName)) {
        resultJson.put("return_code", 404);
        resultJson.put("message", "Wrong input format! Missing dataset uri");
        return resultJson;
    }

    String sqlQuery = null;
    List<Map<String, Object>> rows = null;

    if (isHive) {
        rows = JdbcUtil.wherehowsJdbcTemplate.queryForList(GET_DATASET_ID_IN_MAP_TABLE_WITH_TYPE_AND_CLUSTER,
                "/" + dbName + "/" + tableName, "hive", cluster);

    } else if (isDalids) {

        rows = JdbcUtil.wherehowsJdbcTemplate.queryForList(GET_DATASET_ID_IN_MAP_TABLE_WITH_TYPE_AND_CLUSTER,
                "/" + dbName + "/" + tableName, "dalids", cluster);
    } else {
        rows = JdbcUtil.wherehowsJdbcTemplate.queryForList(GET_DATASET_ID_IN_MAP_TABLE_WITH_CLUSTER,
                "/" + dbName + "/" + tableName, cluster);

    }

    Long datasetId = 0L;
    String urn = null;
    String datasetType = null;
    String deploymentTier = null;
    String dataCenter = null;
    String serverCluster = null;
    if (rows != null && rows.size() > 0) {
        for (Map row : rows) {

            datasetId = (Long) row.get("dataset_id");
            urn = (String) row.get("urn");
            datasetType = (String) row.get("dataset_type");
            if (datasetType.equalsIgnoreCase("hive")) {
                isHive = true;
            } else if (datasetType.equalsIgnoreCase("dalids")) {
                isDalids = true;
            }
            deploymentTier = (String) row.get("deployment_tier");
            dataCenter = (String) row.get("data_center");
            serverCluster = (String) row.get("server_cluster");
            break;
        }
    } else {
        resultJson.put("return_code", 200);
        resultJson.put("message", "Dependency information is not available.");
        return resultJson;
    }

    List<DatasetDependencyRecord> depends = new ArrayList<DatasetDependencyRecord>();
    getDatasetDependencies(datasetId, "", 1, depends);
    int leafLevelDependencyCount = 0;
    if (depends.size() > 0) {
        for (DatasetDependencyRecord d : depends) {
            if (d.next_level_dependency_count == 0) {
                leafLevelDependencyCount++;
            }
        }
    }
    StringBuilder inputUri = new StringBuilder("");
    if (isHive) {
        inputUri.append("hive://");
    } else if (isDalids) {
        inputUri.append("dalids://");
    }
    inputUri.append(cluster + "/" + dbName + "/" + tableName);

    resultJson.put("return_code", 200);
    resultJson.put("deployment_tier", deploymentTier);
    resultJson.put("data_center", dataCenter);
    resultJson.put("cluster", StringUtils.isNotBlank(serverCluster) ? serverCluster : cluster);
    resultJson.put("dataset_type", datasetType);
    resultJson.put("database_name", dbName);
    resultJson.put("table_name", tableName);
    resultJson.put("urn", urn);
    resultJson.put("dataset_id", datasetId);
    resultJson.put("input_uri", inputUri.toString());
    resultJson.set("dependencies", Json.toJson(depends));
    resultJson.put("leaf_level_dependency_count", leafLevelDependencyCount);
    return resultJson;
}

From source file:controllers.Rules.java

@Security.Authenticated(Secured.class)
@BodyParser.Of(BodyParser.Json.class)
public static Promise<Result> create() {
    final JsonNode json = request().body().asJson();
    Promise<Boolean> created = Rule.nodes.create(json);
    return created.map(new Function<Boolean, Result>() {
        ObjectNode result = Json.newObject();

        public Result apply(Boolean created) {
            if (created) {
                String name = json.get("name").asText();
                result.put("id", name);
                result.put("name", name);
                result.put("description", json.get("description").asText());
                return ok(result);
            }//from   w  ww . j a  v a 2  s.  c  o  m
            return badRequest(result);
        }
    });
}

From source file:org.hawkular.alerts.api.json.JacksonDeserializer.java

public static Condition deserializeCondition(JsonNode node) throws JsonProcessingException {
    if (node == null) {
        return null;
    }/*from   w  w w  .  j a  va 2  s. co  m*/

    Condition condition = null;
    Condition.Type conditionType = null;
    if (node.get("type") == null) {
        throw new ConditionException("Condition must have a type");
    }
    try {
        conditionType = Condition.Type.valueOf(node.get("type").asText().toUpperCase());
    } catch (Exception e) {
        throw new ConditionException(e);
    }

    switch (conditionType) {
    case THRESHOLD: {
        try {
            condition = new ThresholdCondition();
            ThresholdCondition tCondition = (ThresholdCondition) condition;
            if (node.get("dataId") != null) {
                tCondition.setDataId(node.get("dataId").textValue());
            }
            if (node.get("operator") != null) {
                tCondition.setOperator(ThresholdCondition.Operator.valueOf(node.get("operator").textValue()));
            }
            if (node.get("threshold") != null) {
                tCondition.setThreshold(node.get("threshold").doubleValue());
            }
        } catch (Exception e) {
            throw new ConditionException(e);
        }
        break;
    }
    case AVAILABILITY: {
        try {
            condition = new AvailabilityCondition();
            AvailabilityCondition aCondition = (AvailabilityCondition) condition;
            if (node.get("dataId") != null) {
                aCondition.setDataId(node.get("dataId").textValue());
            }
            if (node.get("operator") != null) {
                aCondition
                        .setOperator(AvailabilityCondition.Operator.valueOf(node.get("operator").textValue()));
            }
        } catch (Exception e) {
            throw new ConditionException(e);
        }
        break;
    }
    case COMPARE: {
        try {
            condition = new CompareCondition();
            CompareCondition cCondition = (CompareCondition) condition;
            if (node.get("dataId") != null) {
                cCondition.setDataId(node.get("dataId").textValue());
            }
            if (node.get("operator") != null) {
                cCondition.setOperator(CompareCondition.Operator.valueOf(node.get("operator").textValue()));
            }
            if (node.get("data2Id") != null) {
                cCondition.setData2Id(node.get("data2Id").textValue());
            }
            if (node.get("data2Multiplier") != null) {
                cCondition.setData2Multiplier(node.get("data2Multiplier").doubleValue());
            }
        } catch (Exception e) {
            throw new ConditionException(e);
        }
        break;
    }
    case RANGE: {
        try {
            condition = new ThresholdRangeCondition();
            ThresholdRangeCondition rCondition = (ThresholdRangeCondition) condition;
            if (node.get("dataId") != null) {
                rCondition.setDataId(node.get("dataId").textValue());
            }
            if (node.get("operatorLow") != null) {
                rCondition.setOperatorLow(
                        ThresholdRangeCondition.Operator.valueOf(node.get("operatorLow").textValue()));
            }
            if (node.get("operatorHigh") != null) {
                rCondition.setOperatorHigh(
                        ThresholdRangeCondition.Operator.valueOf(node.get("operatorHigh").textValue()));
            }
            if (node.get("thresholdLow") != null) {
                rCondition.setThresholdLow(node.get("thresholdLow").doubleValue());
            }
            if (node.get("thresholdHigh") != null) {
                rCondition.setThresholdHigh(node.get("thresholdHigh").doubleValue());
            }
            if (node.get("inRange") != null) {
                rCondition.setInRange(node.get("inRange").booleanValue());
            }
        } catch (Exception e) {
            throw new ConditionException(e);
        }
        break;
    }
    case STRING: {
        try {
            condition = new StringCondition();
            StringCondition sCondition = (StringCondition) condition;
            if (node.get("dataId") != null) {
                sCondition.setDataId(node.get("dataId").textValue());
            }
            if (node.get("operator") != null) {
                sCondition.setOperator(StringCondition.Operator.valueOf(node.get("operator").textValue()));
            }
            if (node.get("pattern") != null) {
                sCondition.setPattern(node.get("pattern").textValue());
            }
            if (node.get("ignoreCase") != null) {
                sCondition.setIgnoreCase(node.get("ignoreCase").booleanValue());
            }
        } catch (Exception e) {
            throw new ConditionException(e);
        }
        break;
    }
    case EXTERNAL: {
        try {
            condition = new ExternalCondition();
            ExternalCondition eCondition = (ExternalCondition) condition;
            if (node.get("systemId") != null) {
                eCondition.setSystemId(node.get("systemId").textValue());
            }
            if (node.get("dataId") != null) {
                eCondition.setDataId(node.get("dataId").textValue());
            }
            if (node.get("expression") != null) {
                eCondition.setExpression(node.get("expression").textValue());
            }
        } catch (Exception e) {
            throw new ConditionException(e);
        }
        break;
    }
    case EVENT: {
        try {
            condition = new EventCondition();
            EventCondition evCondition = (EventCondition) condition;
            if (node.get("dataId") != null) {
                evCondition.setDataId(node.get("dataId").textValue());
            }
            if (node.get("expression") != null) {
                evCondition.setExpression(node.get("expression").textValue());
            }
        } catch (Exception e) {
            throw new ConditionException(e);
        }
        break;
    }
    case RATE: {
        try {
            condition = new RateCondition();
            RateCondition rCondition = (RateCondition) condition;
            if (node.get("dataId") != null) {
                rCondition.setDataId(node.get("dataId").textValue());
            }
            if (node.get("direction") != null) {
                rCondition.setDirection(RateCondition.Direction.valueOf(node.get("direction").textValue()));
            }
            if (node.get("period") != null) {
                rCondition.setPeriod(RateCondition.Period.valueOf(node.get("period").textValue()));
            }
            if (node.get("operator") != null) {
                rCondition.setOperator(RateCondition.Operator.valueOf(node.get("operator").textValue()));
            }
            if (node.get("threshold") != null) {
                rCondition.setThreshold(node.get("threshold").doubleValue());
            }
        } catch (Exception e) {
            throw new ConditionException(e);
        }
        break;
    }
    default:
        throw new ConditionException("Unexpected Condition Type [" + conditionType.name() + "]");
    }
    if (condition != null) {
        try {
            if (node.get("tenantId") != null) {
                condition.setTenantId(node.get("tenantId").textValue());
            }
            if (node.get("triggerId") != null) {
                condition.setTriggerId(node.get("triggerId").textValue());
            }
            if (node.get("triggerMode") != null) {
                condition.setTriggerMode(Mode.valueOf(node.get("triggerMode").textValue()));
            }
            if (node.get("conditionSetSize") != null) {
                condition.setConditionSetSize(node.get("conditionSetSize").intValue());
            }
            if (node.get("conditionSetIndex") != null) {
                condition.setConditionSetIndex(node.get("conditionSetIndex").intValue());
            }
            if (node.get("context") != null) {
                condition.setContext(deserializeMap(node.get("context")));
            }
        } catch (Exception e) {
            throw new ConditionException(e);
        }
    }
    return condition;
}

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

public static List<Note> getNotes(String userID) throws Exception {
    // Server URL setup
    String _url = getBaseUri().appendPath("Notes").appendPath(userID).build().toString();
    Log.d("GETNOTES", _url);
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);//from w  ww  . jav a 2 s  .  co  m

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    // Initialize ObjectMapper
    List<Note> noteList = new ArrayList<Note>();
    List<String> noteIds = new ArrayList<String>();
    final JsonNode noteArray = MAPPER.readTree(response).get(Keys.Note.LIST);

    if (noteArray.isArray()) {
        for (final JsonNode noteNode : noteArray) {
            Note n = NotesDatabaseAdapter.getNote(JsonUtils.getJSONValue(noteNode, Keys.Note.ID));
            n.setCreatedBy(JsonUtils.getJSONValue(noteNode, Keys.Note.CREATED_BY));
            if (n != null) {
                noteList.add(n);
            }
            noteIds.add(noteNode.get(Keys.Note.ID).asText());
        }
    } else {
        Log.e(TAG, "Error parsing user's notes list");
    }

    conn.disconnect();
    return noteList;
}

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

/**
 * Searches for the Json node to set on the model field in the Json data.
 *
 * @param entityFieldName The annotated model property. Used to search the Json node
 * @param rawJsonData     The Json data representing a node inside a child node of a component. Used for
 *                        embedded fields and component link fields
 * @param isRootComponent A flag to check whether the current Json node is the component node. If it is
 *                        the case, then a choice is made whether to fetch the metadata or the normal content
 *                        node.//w w  w. j av  a  2  s . co m
 * @param contentFields   The content node
 * @param metadataFields  The metadata node
 * @param m               The current model field that is parsing at the moment
 * @return the Json node found under the entityFieldName key or null
 */
private static JsonNode getJsonNodeToParse(final String entityFieldName, final JsonNode rawJsonData,
        final boolean isRootComponent, final boolean isEmbeddable, final JsonNode contentFields,
        final JsonNode metadataFields, final ModelFieldMapping m) {

    final JsonNode currentNode;
    if (isRootComponent) {
        if (m.getViewModelProperty().isMetadata()) {
            currentNode = metadataFields;
        } else {
            currentNode = contentFields;
        }
    } else {
        currentNode = rawJsonData;
    }

    if (currentNode != null) {
        if (isRootComponent || isEmbeddable) {
            return currentNode.get(entityFieldName);
        }
        return currentNode;
    }
    return null;
}

From source file:eu.citadel.converter.transform.CitadelJsonTransform.java

/**
 * Validate the JSON/* ww w  . j av  a  2 s  .  c o m*/
 * @param json the provided JSON to validate using the predefined schema
 * @throws TransformException if not valid, an exception will be thrown
 */
private static void validateJson(String json) throws TransformException {
    Logger logger = LoggerFactory.getLogger(CitadelJsonTransform.class.getName() + ".validateJson");
    logger.trace("validateJson(String) - start");
    try {
        URL url = CitadelJsonTransform.class.getResource("/data/datatype/citadel_general_schema.json");
        final JsonNode schemaJson = JsonLoader.fromString(Resources.toString(url, Charsets.UTF_8));
        final JsonNode generatedJson = JsonLoader.fromString(json);
        final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
        final JsonSchema schema = factory.getJsonSchema(schemaJson);

        ProcessingReport report = schema.validate(generatedJson);
        if (!report.isSuccess()) {
            String message = report.toString();
            for (Iterator<ProcessingMessage> i = report.iterator(); i.hasNext();) {
                ProcessingMessage processingMessage = i.next();
                JsonNode jsonMessage = processingMessage.asJson();
                message = processingMessage.getMessage();
                if (jsonMessage.get("instance") != null) {
                    if (jsonMessage.get("instance").get("pointer") != null) {
                        message = message + " in " + jsonMessage.get("instance").get("pointer").toString();
                    } else {
                        message = message + " in " + jsonMessage.get("instance").toString();
                    }
                }

            }
            logger.error("validateJson(String) - not valid: {}", message);
            throw new TransformException(message);
        }
        logger.debug("validateJson(String) - end");
    } catch (IOException e) {
        logger.error("validateJson(String) - IOException: {}", e);
        throw new TransformException(e.getMessage());
    } catch (ProcessingException e) {
        logger.error("validateJson(String) - ProcessingException: {}", e);
        throw new TransformException(e.getMessage());
    }
}