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

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

Introduction

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

Prototype

public abstract String toString();

Source Link

Usage

From source file:controllers.AnyplaceMapping.java

/**
 * Update the building information. Building to update is specified by buid
 *
 * @return//from www  .j a  v  a2 s  .  com
 */
public static Result buildingUpdate() {
    OAuth2Request anyReq = new OAuth2Request(request(), response());
    if (!anyReq.assertJsonBody()) {
        return AnyResponseHelper.bad_request(AnyResponseHelper.CANNOT_PARSE_BODY_AS_JSON);
    }
    JsonNode json = anyReq.getJsonBody();
    LPLogger.info("AnyplaceMapping::buildingUpdate(): " + json.toString());

    List<String> requiredMissing = JsonUtils.requirePropertiesInJson(json, "buid", "access_token");
    if (!requiredMissing.isEmpty()) {
        return AnyResponseHelper.requiredFieldsMissing(requiredMissing);
    }
    // get access token from url and check it against google's service
    if (json.findValue("access_token") == null) {
        return AnyResponseHelper.forbidden("Unauthorized");
    }
    String owner_id = verifyOwnerId(json.findValue("access_token").textValue());
    if (owner_id == null) {
        return AnyResponseHelper.forbidden("Unauthorized");
    }
    owner_id = appendToOwnerId(owner_id);
    ((ObjectNode) json).put("owner_id", owner_id);

    String buid = json.path("buid").textValue();

    try {
        ObjectNode stored_building = (ObjectNode) ProxyDataSource.getIDatasource().getFromKeyAsJson(buid);
        if (stored_building == null) {
            return AnyResponseHelper.bad_request("Building does not exist or could not be retrieved!");
        }

        if (!isBuildingOwner(stored_building, owner_id)) {
            return AnyResponseHelper.unauthorized("Unauthorized");
        }

        // check for values to update
        if (json.findValue("is_published") != null) {
            String is_published = json.path("is_published").textValue();
            if (is_published.equals("true") || is_published.equals("false"))
                stored_building.put("is_published", json.path("is_published").textValue());
        }
        if (json.findValue("name") != null) {
            stored_building.put("name", json.path("name").textValue());
        }
        if (json.findValue("bucode") != null) {
            stored_building.put("bucode", json.path("bucode").textValue());
        }
        if (json.findValue("description") != null) {
            stored_building.put("description", json.path("description").textValue());
        }
        if (json.findValue("url") != null) {
            stored_building.put("url", json.path("url").textValue());
        }
        if (json.findValue("address") != null) {
            stored_building.put("address", json.path("address").textValue());
        }
        if (json.findValue("coordinates_lat") != null) {
            stored_building.put("coordinates_lat", json.path("coordinates_lat").textValue());
        }
        if (json.findValue("coordinates_lon") != null) {
            stored_building.put("coordinates_lon", json.path("coordinates_lon").textValue());
        }

        AbstractModel building = new Building(stored_building);
        if (!ProxyDataSource.getIDatasource().replaceJsonDocument(building.getId(), 0,
                building.toCouchGeoJSON())) {
            return AnyResponseHelper.bad_request("Building could not be updated!");
        }

        return AnyResponseHelper.ok("Successfully updated building!");
    } catch (DatasourceException e) {
        return AnyResponseHelper.internal_server_error("Server Internal Error [" + e.getMessage() + "]");
    }
}

From source file:controllers.AnyplaceMapping.java

/**
 * Adds a new connection between two valid Points of Interest - denoted by the pois_a and pois_b -
 *
 * @return/*from   w  w w .  jav  a 2 s.c  o m*/
 */
public static Result connectionAdd() {
    OAuth2Request anyReq = new OAuth2Request(request(), response());
    if (!anyReq.assertJsonBody()) {
        return AnyResponseHelper.bad_request(AnyResponseHelper.CANNOT_PARSE_BODY_AS_JSON);
    }
    JsonNode json = anyReq.getJsonBody();
    LPLogger.info("AnyplaceMapping::connectionAdd(): " + json.toString());

    List<String> requiredMissing = JsonUtils.requirePropertiesInJson(json, "is_published", "pois_a", "floor_a",
            "buid_a", "pois_b", "floor_b", "buid_b", "buid", "edge_type", "access_token");
    if (!requiredMissing.isEmpty()) {
        return AnyResponseHelper.requiredFieldsMissing(requiredMissing);
    }
    // get access token from url and check it against google's service
    if (json.findValue("access_token") == null) {
        return AnyResponseHelper.forbidden("Unauthorized");
    }
    String owner_id = verifyOwnerId(json.findValue("access_token").textValue());
    if (owner_id == null) {
        return AnyResponseHelper.forbidden("Unauthorized");
    }
    owner_id = appendToOwnerId(owner_id);
    ((ObjectNode) json).put("owner_id", owner_id);

    String buid1 = json.path("buid_a").textValue();
    String buid2 = json.path("buid_b").textValue();

    try {
        ObjectNode stored_building = (ObjectNode) ProxyDataSource.getIDatasource().getFromKeyAsJson(buid1);
        if (stored_building == null) {
            return AnyResponseHelper.bad_request("Building does not exist or could not be retrieved!");
        }

        if (!isBuildingOwner(stored_building, owner_id) && !isBuildingCoOwner(stored_building, owner_id)) {
            return AnyResponseHelper.unauthorized("Unauthorized");
        }

        stored_building = (ObjectNode) ProxyDataSource.getIDatasource().getFromKeyAsJson(buid2);
        if (stored_building == null) {
            return AnyResponseHelper.bad_request("Building does not exist or could not be retrieved!");
        }

        if (!isBuildingOwner(stored_building, owner_id) && !isBuildingCoOwner(stored_building, owner_id)) {
            return AnyResponseHelper.unauthorized("Unauthorized");
        }

    } catch (DatasourceException e) {
        return AnyResponseHelper.internal_server_error("Server Internal Error [" + e.getMessage() + "]");
    }

    String edge_type = json.path("edge_type").textValue();
    if (!edge_type.equals(Connection.EDGE_TYPE_ELEVATOR) && !edge_type.equals(Connection.EDGE_TYPE_HALLWAY)
            && !edge_type.equals(Connection.EDGE_TYPE_ROOM) && !edge_type.equals(Connection.EDGE_TYPE_OUTDOOR)
            && !edge_type.equals(Connection.EDGE_TYPE_STAIR)) {
        return AnyResponseHelper.bad_request("Invalid edge type specified.");
    }

    String pois_a = json.path("pois_a").textValue();
    String pois_b = json.path("pois_b").textValue();

    try {
        // Calculate the weight of the connection
        double weight = calculateWeightOfConnection(pois_a, pois_b);
        ((ObjectNode) json).put("weight", Double.toString(weight));
        if (edge_type.equals(Connection.EDGE_TYPE_ELEVATOR) || edge_type.equals(Connection.EDGE_TYPE_STAIR)) {
            // TODO - maybe we must put weight zero
            // TODO - or we must calculate the paths in each floor separately
        }

        Connection conn = new Connection(json);

        if (!ProxyDataSource.getIDatasource().addJsonDocument(conn.getId(), 0, conn.toValidCouchJson())) {
            return AnyResponseHelper.bad_request("Connection already exists or could not be added!");
        }
        ObjectNode res = JsonUtils.createObjectNode();
        res.put("cuid", conn.getId());
        return AnyResponseHelper.ok(res, "Successfully added new connection!");
    } catch (DatasourceException e) {
        return AnyResponseHelper.internal_server_error("Server Internal Error [" + e.getMessage() + "]");
    }
}

From source file:controllers.AnyplaceMapping.java

/**
 * Updates the edge_type of the connection between two Points of Interest - specified by pois_a and pois_b -
 *
 * @return/*from w  w w  .j  a v  a 2  s  .c om*/
 */
public static Result connectionUpdate() {
    OAuth2Request anyReq = new OAuth2Request(request(), response());
    if (!anyReq.assertJsonBody()) {
        return AnyResponseHelper.bad_request(AnyResponseHelper.CANNOT_PARSE_BODY_AS_JSON);
    }
    JsonNode json = anyReq.getJsonBody();
    LPLogger.info("AnyplaceMapping::connectionUpdate(): " + json.toString());

    List<String> requiredMissing = JsonUtils.requirePropertiesInJson(json, "pois_a", "pois_b", "buid_a",
            "buid_b", "access_token");
    if (!requiredMissing.isEmpty()) {
        return AnyResponseHelper.requiredFieldsMissing(requiredMissing);
    }
    // get access token from url and check it against google's service
    if (json.findValue("access_token") == null) {
        return AnyResponseHelper.forbidden("Unauthorized");
    }
    String owner_id = verifyOwnerId(json.findValue("access_token").textValue());
    if (owner_id == null) {
        return AnyResponseHelper.forbidden("Unauthorized");
    }
    owner_id = appendToOwnerId(owner_id);
    ((ObjectNode) json).put("owner_id", owner_id);

    String buid1 = json.path("buid_a").textValue();
    String buid2 = json.path("buid_b").textValue();

    try {
        ObjectNode stored_building = (ObjectNode) ProxyDataSource.getIDatasource().getFromKeyAsJson(buid1);
        if (stored_building == null) {
            return AnyResponseHelper.bad_request("Building does not exist or could not be retrieved!");
        }

        if (!isBuildingOwner(stored_building, owner_id) && !isBuildingCoOwner(stored_building, owner_id)) {
            return AnyResponseHelper.unauthorized("Unauthorized");
        }

        stored_building = (ObjectNode) ProxyDataSource.getIDatasource().getFromKeyAsJson(buid2);
        if (stored_building == null) {
            return AnyResponseHelper.bad_request("Building does not exist or could not be retrieved!");
        }

        if (!isBuildingOwner(stored_building, owner_id) && !isBuildingCoOwner(stored_building, owner_id)) {
            return AnyResponseHelper.unauthorized("Unauthorized");
        }

    } catch (DatasourceException e) {
        return AnyResponseHelper.internal_server_error("Server Internal Error [" + e.getMessage() + "]");
    }

    try {
        String pois_a = json.path("pois_a").textValue();
        String pois_b = json.path("pois_b").textValue();

        String cuid = Connection.getId(pois_a, pois_b);
        ObjectNode stored_conn = (ObjectNode) ProxyDataSource.getIDatasource().getFromKeyAsJson(cuid);
        if (stored_conn == null) {
            return AnyResponseHelper.bad_request("Connection does not exist or could not be retrieved!");
        }

        // check for values to update
        if (json.findValue("is_published") != null) {
            String is_published = json.path("is_published").textValue();
            if (is_published.equals("true") || is_published.equals("false"))
                stored_conn.put("is_published", json.path("is_published").textValue());
        }
        if (json.findValue("edge_type") != null) {
            String edge_type = json.path("edge_type").textValue();
            if (!edge_type.equals(Connection.EDGE_TYPE_ELEVATOR)
                    && !edge_type.equals(Connection.EDGE_TYPE_HALLWAY)
                    && !edge_type.equals(Connection.EDGE_TYPE_ROOM)
                    && !edge_type.equals(Connection.EDGE_TYPE_OUTDOOR)
                    && !edge_type.equals(Connection.EDGE_TYPE_STAIR)) {
                return AnyResponseHelper.bad_request("Invalid edge type specified.");
            }
            stored_conn.put("edge_type", edge_type);
        }

        Connection conn = new Connection(stored_conn);
        if (!ProxyDataSource.getIDatasource().replaceJsonDocument(conn.getId(), 0, conn.toValidCouchJson())) {
            return AnyResponseHelper.bad_request("Connection could not be updated!");
        }

        return AnyResponseHelper.ok("Successfully updated connection!");
    } catch (DatasourceException e) {
        return AnyResponseHelper.internal_server_error("Server Internal Error [" + e.getMessage() + "]");
    }
}

From source file:controllers.AnyplaceMapping.java

/**
 * Update the Point of Interest - specified by PUID - information
 *
 * @return/*from  www .ja  v  a 2s .  c om*/
 */
public static Result poisUpdate() {
    OAuth2Request anyReq = new OAuth2Request(request(), response());
    if (!anyReq.assertJsonBody()) {
        return AnyResponseHelper.bad_request(AnyResponseHelper.CANNOT_PARSE_BODY_AS_JSON);
    }
    JsonNode json = anyReq.getJsonBody();
    LPLogger.info("AnyplaceMapping::poisUpdate(): " + json.toString());

    List<String> requiredMissing = JsonUtils.requirePropertiesInJson(json, "puid", "buid", "access_token");
    if (!requiredMissing.isEmpty()) {
        return AnyResponseHelper.requiredFieldsMissing(requiredMissing);
    }
    // get access token from url and check it against google's service
    if (json.findValue("access_token") == null) {
        return AnyResponseHelper.forbidden("Unauthorized");
    }
    String owner_id = verifyOwnerId(json.findValue("access_token").textValue());
    if (owner_id == null) {
        return AnyResponseHelper.forbidden("Unauthorized");
    }
    owner_id = appendToOwnerId(owner_id);
    ((ObjectNode) json).put("owner_id", owner_id);

    String puid = json.path("puid").textValue();
    String buid = json.path("buid").textValue();

    try {
        ObjectNode stored_building = (ObjectNode) ProxyDataSource.getIDatasource().getFromKeyAsJson(buid);
        if (stored_building == null) {
            return AnyResponseHelper.bad_request("Building does not exist or could not be retrieved!");
        }

        if (!isBuildingOwner(stored_building, owner_id) && !isBuildingCoOwner(stored_building, owner_id)) {
            return AnyResponseHelper.unauthorized("Unauthorized");
        }

    } catch (DatasourceException e) {
        return AnyResponseHelper.internal_server_error("Server Internal Error [" + e.getMessage() + "]");
    }

    try {
        ObjectNode stored_poi = (ObjectNode) ProxyDataSource.getIDatasource().getFromKeyAsJson(puid);
        if (stored_poi == null) {
            return AnyResponseHelper.bad_request("Building does not exist or could not be retrieved!");
        }

        // check for values to update
        if (json.findValue("is_published") != null) {
            String is_published = json.path("is_published").textValue();
            if (is_published.equals("true") || is_published.equals("false"))
                stored_poi.put("is_published", json.path("is_published").textValue());
        }
        if (json.findValue("name") != null) {
            stored_poi.put("name", json.path("name").textValue());
        }
        if (json.findValue("description") != null) {
            stored_poi.put("description", json.path("description").textValue());
        }
        if (json.findValue("url") != null) {
            stored_poi.put("url", json.path("url").textValue());
        }
        if (json.findValue("pois_type") != null) {
            stored_poi.put("pois_type", json.path("pois_type").textValue());
        }
        if (json.findValue("is_door") != null) {
            String is_door = json.path("is_door").textValue();
            if (is_door.equals("true") || is_door.equals("false"))
                stored_poi.put("is_door", json.path("is_door").textValue());
        }
        if (json.findValue("is_building_entrance") != null) {
            String is_building_entrance = json.path("is_building_entrance").textValue();
            if (is_building_entrance.equals("true") || is_building_entrance.equals("false"))
                stored_poi.put("is_building_entrance", json.path("is_building_entrance").textValue());
        }
        if (json.findValue("image") != null) {
            stored_poi.put("image", json.path("image").textValue());
        }

        if (json.findValue("coordinates_lat") != null) {
            stored_poi.put("coordinates_lat", json.path("coordinates_lat").textValue());
        }

        if (json.findValue("coordinates_lon") != null) {
            stored_poi.put("coordinates_lon", json.path("coordinates_lon").textValue());
        }

        AbstractModel poi = new Poi(stored_poi);
        if (!ProxyDataSource.getIDatasource().replaceJsonDocument(poi.getId(), 0, poi.toCouchGeoJSON())) {
            return AnyResponseHelper.bad_request("Poi could not be updated!");
        }

        return AnyResponseHelper.ok("Successfully updated poi!");
    } catch (DatasourceException e) {
        return AnyResponseHelper.internal_server_error("Server Internal Error [" + e.getMessage() + "]");
    }
}

From source file:io.gravitee.definition.jackson.datatype.api.deser.RuleDeserializer.java

@Override
public Rule deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode node = jp.getCodec().readTree(jp);

    Rule rule = new Rule();

    node.fieldNames().forEachRemaining(field -> {
        JsonNode subNode = node.findValue(field);

        switch (field) {
        case "methods":
            if (subNode != null && subNode.isArray()) {
                HttpMethod[] methods = new HttpMethod[subNode.size()];

                final int[] idx = { 0 };
                subNode.elements().forEachRemaining(jsonNode -> {
                    methods[idx[0]++] = HttpMethod.valueOf(jsonNode.asText().toUpperCase());
                });//  www .ja v  a  2s .  com

                rule.getMethods().addAll(Arrays.asList(methods));
            }
            break;
        case "description":
            if (subNode != null) {
                rule.setDescription(subNode.asText());
            }
            break;
        case "enabled":
            if (subNode != null) {
                rule.setEnabled(subNode.asBoolean(true));
            }
            break;
        default:
            // We are in the case of a policy
            Policy policy = new Policy();

            policy.setName(field);
            policy.setConfiguration(subNode.toString());

            rule.setPolicy(policy);

            break;
        }
    });

    if (rule.getMethods().isEmpty()) {
        rule.getMethods()
                .addAll(Arrays.asList(HttpMethod.CONNECT, HttpMethod.DELETE, HttpMethod.GET, HttpMethod.HEAD,
                        HttpMethod.OPTIONS, HttpMethod.PATCH, HttpMethod.POST, HttpMethod.PUT,
                        HttpMethod.TRACE));
    }

    return rule;
}

From source file:com.delphix.delphix.DelphixEngine.java

/**
 * Send POST to Delphix Engine and return the result
 *///from  w ww . j  a v  a2  s  .c  o  m
private JsonNode enginePOST(final String path, final String content)
        throws IOException, DelphixEngineException {
    // Log requests
    if (!content.contains("LoginRequest")) {
        LOGGER.log(Level.WARNING, path + ":" + content);
    }

    // Build and send request
    HttpPost request = new HttpPost(PROTOCOL + engineAddress + path);
    try {
        request.setEntity(new ByteArrayEntity(content.getBytes(ENCODING)));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
    request.setHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE);
    HttpResponse response = client.execute(request);

    // Get result of request
    String result = EntityUtils.toString(response.getEntity());
    JsonNode jsonResult = MAPPER.readTree(result);
    EntityUtils.consume(response.getEntity());
    if (!jsonResult.get(FIELD_STATUS).asText().equals(OK_STATUS)) {
        throw new DelphixEngineException(jsonResult.get("error").get("details").toString());
    }

    // Log result
    if (!content.contains("LoginRequest")) {
        LOGGER.log(Level.WARNING, jsonResult.toString());
    }
    return jsonResult;
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Creates a mapping for the bucket - search service elements .. up to but not including the mapping + type
 *  NOTE: creates an embedded object that is {{, ie must be closed twice subsequently in order to be a well formed JSON object
 * @param bucket// w  ww.ja v  a 2 s . c  om
 * @return
 * @throws IOException 
 */
public static XContentBuilder getSearchServiceMapping(final DataBucketBean bucket,
        final Optional<String> secondary_buffer, final boolean is_primary,
        final ElasticsearchIndexServiceConfigBean schema_config, final Optional<XContentBuilder> to_embed,
        final ObjectMapper mapper) {
    try {
        final XContentBuilder start = to_embed.orElse(XContentFactory.jsonBuilder().startObject());

        // (Nullable)
        final ElasticsearchIndexServiceConfigBean.SearchIndexSchemaDefaultBean search_schema = schema_config
                .search_technology_override();

        //(very briefly Nullable)
        final JsonNode settings = Optional.ofNullable(search_schema).map(s -> s.settings())
                .map(o -> mapper.convertValue(o, JsonNode.class)).orElse(null);

        //(very briefly Nullable)
        final ObjectNode aliases = (ObjectNode) Optional.ofNullable(search_schema).map(s -> s.aliases())
                .map(o -> mapper.convertValue(o, JsonNode.class)).orElse(mapper.createObjectNode());

        if (is_primary) { // add the "read only" prefix alias
            aliases.set(
                    ElasticsearchContext.READ_PREFIX
                            + ElasticsearchIndexUtils.getBaseIndexName(bucket, Optional.empty()),
                    mapper.createObjectNode());
        }

        // Settings

        final String type_key = getTypeKey(bucket, mapper);

        return Lambdas.wrap_u(__ -> {
            if (null == settings) { // nothing to do
                return start;
            } else {
                return start.rawField("settings", settings.toString().getBytes());
            }
        })
                // Aliases
                .andThen(Lambdas.wrap_u(json -> {
                    if (!aliases.elements().hasNext()) { // nothing to do
                        return json;
                    } else {
                        return start.rawField("aliases", aliases.toString().getBytes());
                    }
                }))
                // Mappings and overrides
                .andThen(Lambdas.wrap_u(json -> json.startObject("mappings").startObject(type_key)))
                // Add the secondary buffer name to the metadata:
                .andThen(Lambdas.wrap_u(json -> {
                    return json.rawField(CUSTOM_META,
                            createMergedMeta(Either.right(mapper), bucket, is_primary, secondary_buffer)
                                    .toString().getBytes());
                }))
                // More mapping overrides
                .andThen(Lambdas.wrap_u(json -> {

                    return Optional.ofNullable(search_schema).map(ss -> ss.mapping_overrides())
                            .map(m -> m.getOrDefault(type_key, m.get("*"))).orElse(Collections.emptyMap())
                            .entrySet().stream().reduce(json, Lambdas.wrap_u((acc, kv) -> {
                                if (CUSTOM_META.equals(kv.getKey())) { // meta is a special case, merge my results in regardless
                                    return acc.rawField(kv.getKey(),
                                            createMergedMeta(
                                                    Either.left(
                                                            mapper.convertValue(kv.getValue(), JsonNode.class)),
                                                    bucket, is_primary, secondary_buffer).toString()
                                                            .getBytes());
                                } else {
                                    return acc.rawField(kv.getKey(), mapper
                                            .convertValue(kv.getValue(), JsonNode.class).toString().getBytes());
                                }
                            }), (acc1, acc2) -> acc1 // (can't actually ever happen)
                    );
                })).apply(null);
    } catch (IOException e) {
        //Handle fake "IOException"
        return null;
    }
}

From source file:com.redhat.lightblue.mongo.config.MongoConfiguration.java

@Override
public void initializeFromJson(JsonNode node) {
    if (node != null) {
        JsonNode x = node.get("connectionsPerHost");
        if (x != null) {
            connectionsPerHost = x.asInt();
        }/*from w  w  w. j  a  v  a2 s  .  c  o m*/
        x = node.get("ssl");
        if (x != null) {
            ssl = x.asBoolean();
        }
        x = node.get("noCertValidation");
        if (x != null) {
            noCertValidation = x.asBoolean();
        }
        credentials = credentialsFromJson(node.get("credentials"));
        x = node.get("metadataDataStoreParser");
        try {
            if (x != null) {
                metadataDataStoreParser = Class.forName(x.asText());
            }
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException(node.toString() + ":" + e);
        }
        x = node.get("database");
        if (x != null) {
            database = x.asText();
        }
        JsonNode jsonNodeServers = node.get("servers");
        if (jsonNodeServers != null && jsonNodeServers.isArray()) {
            Iterator<JsonNode> elements = jsonNodeServers.elements();
            while (elements.hasNext()) {
                JsonNode next = elements.next();
                try {
                    String host;
                    x = next.get("host");
                    if (x != null) {
                        host = x.asText();
                    } else {
                        host = null;
                    }

                    x = next.get("port");
                    if (x != null) {
                        addServerAddress(host, x.asInt());
                    } else {
                        addServerAddress(host);
                    }
                } catch (UnknownHostException e) {
                    throw new IllegalStateException(e);
                }
            }

        } else {
            JsonNode server = node.get("server");
            if (server != null) {
                try {
                    x = server.get("host");
                    if (x != null) {
                        String host = x.asText();
                        x = server.get("port");
                        if (x != null) {
                            setServer(host, x.asInt());
                        } else {
                            setServer(host);
                        }
                    } else {
                        throw new IllegalStateException("host is required in server");
                    }
                } catch (IllegalStateException | UnknownHostException e) {
                    throw new IllegalStateException(e);
                }
            }
        }
    }
}

From source file:dao.SearchDAO.java

public static JsonNode elasticSearchDatasetByKeyword(String category, String keywords, String source, int page,
        int size) {
    ObjectNode queryNode = Json.newObject();
    queryNode.put("from", (page - 1) * size);
    queryNode.put("size", size);
    JsonNode responseNode = null;
    ObjectNode keywordNode = null;/*w  w w. j  av a2s .  co m*/

    try {
        keywordNode = utils.Search.generateElasticSearchQueryString(category, source, keywords);
    } catch (Exception e) {
        Logger.error("Elastic search dataset input query is not JSON format. Error message :" + e.getMessage());
    }

    if (keywordNode != null) {
        ObjectNode funcScoreNodes = Json.newObject();

        ObjectNode fieldValueFactorNode = Json.newObject();
        fieldValueFactorNode.put("field", "static_boosting_score");
        fieldValueFactorNode.put("factor", 1);
        fieldValueFactorNode.put("modifier", "square");
        fieldValueFactorNode.put("missing", 1);

        funcScoreNodes.put("query", keywordNode);
        funcScoreNodes.put("field_value_factor", fieldValueFactorNode);

        ObjectNode funcScoreNodesWrapper = Json.newObject();
        funcScoreNodesWrapper.put("function_score", funcScoreNodes);

        queryNode.put("query", funcScoreNodesWrapper);

        Logger.debug("The query sent to Elastic Search is: " + queryNode.toString());

        Promise<WSResponse> responsePromise = WS
                .url(Play.application().configuration().getString(SearchDAO.ELASTICSEARCH_DATASET_URL_KEY))
                .post(queryNode);
        responseNode = responsePromise.get(1000).asJson();

        Logger.debug("The responseNode from Elastic Search is: " + responseNode.toString());

    }

    ObjectNode resultNode = Json.newObject();
    Long count = 0L;
    List<Dataset> pagedDatasets = new ArrayList<>();
    resultNode.put("page", page);
    resultNode.put("category", category);
    resultNode.put("source", source);
    resultNode.put("itemsPerPage", size);
    resultNode.put("keywords", keywords);

    if (responseNode != null && responseNode.isContainerNode() && responseNode.has("hits")) {
        JsonNode hitsNode = responseNode.get("hits");
        if (hitsNode != null) {
            if (hitsNode.has("total")) {
                count = hitsNode.get("total").asLong();
            }
            if (hitsNode.has("hits")) {
                JsonNode dataNode = hitsNode.get("hits");
                if (dataNode != null && dataNode.isArray()) {
                    Iterator<JsonNode> arrayIterator = dataNode.elements();
                    if (arrayIterator != null) {
                        while (arrayIterator.hasNext()) {
                            JsonNode node = arrayIterator.next();
                            if (node.isContainerNode() && node.has("_id")) {
                                Dataset dataset = new Dataset();
                                dataset.id = node.get("_id").asLong();
                                if (node.has("_source")) {
                                    JsonNode sourceNode = node.get("_source");
                                    if (sourceNode != null) {
                                        if (sourceNode.has("name")) {
                                            dataset.name = sourceNode.get("name").asText();
                                        }
                                        if (sourceNode.has("source")) {
                                            dataset.source = sourceNode.get("source").asText();
                                        }
                                        if (sourceNode.has("urn")) {
                                            dataset.urn = sourceNode.get("urn").asText();
                                        }
                                        if (sourceNode.has("schema")) {
                                            dataset.schema = sourceNode.get("schema").asText();
                                        }
                                    }
                                }
                                pagedDatasets.add(dataset);
                            }
                        }
                    }

                }
            }

        }
    }
    resultNode.put("count", count);
    resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
    resultNode.set("data", Json.toJson(pagedDatasets));
    return resultNode;
}

From source file:org.pentaho.metaverse.impl.model.kettle.json.TransMetaJsonDeserializerTest.java

@Test
public void testWriteJsonFields() throws Exception {
    JsonNode fields = mock(JsonNode.class);
    ObjectId stepId = new StringObjectId("id");
    List<Map<String, Object>> fieldLists = new ArrayList<Map<String, Object>>();
    Map<String, Object> fieldMap0 = new HashMap<String, Object>() {
        {// ww w.j  a  v  a 2 s  .  c  om
            put("name", "Test 1");
            put("int", 2);
            put("long", 3L);
            put("double", 3.0D);
            put("bool", true);
            put("null", null);
        }
    };
    Map<String, Object> fieldMap1 = new HashMap<String, Object>() {
        {
            put("name", "Test 2");
            put("int", 2);
            put("long", 3L);
            put("double", 3.0D);
            put("bool", true);
            put("null", null);
        }
    };
    fieldLists.add(fieldMap0);
    fieldLists.add(fieldMap1);

    when(fields.toString()).thenReturn("mockedFields");
    when(mapper.readValue("mockedFields", fieldLists.getClass())).then(invocationOnMock -> fieldLists);

    deserializer.writeJsonFields(fields, mapper, stepId);

    verify(repo).saveStepAttribute(null, stepId, 0, "name", "Test 1");
    verify(repo).saveStepAttribute(null, stepId, 1, "name", "Test 2");

    verify(repo, times(2)).saveStepAttribute(any(ObjectId.class), eq(stepId), anyInt(), eq("int"), anyInt());
    verify(repo, times(2)).saveStepAttribute(any(ObjectId.class), eq(stepId), anyInt(), eq("long"), eq(3L));
    verify(repo, times(2)).saveStepAttribute(any(ObjectId.class), eq(stepId), anyInt(), eq("double"), eq(3.0D));
    verify(repo, times(2)).saveStepAttribute(any(ObjectId.class), eq(stepId), anyInt(), eq("bool"), eq(true));
    verify(repo, times(2)).saveStepAttribute(any(ObjectId.class), eq(stepId), anyInt(), eq("null"),
            anyString());
}