Example usage for com.fasterxml.jackson.databind ObjectMapper readTree

List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper readTree.

Prototype

public JsonNode readTree(URL source) throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content as tree expressed using set of JsonNode instances.

Usage

From source file:io.cloudslang.content.json.actions.GetValueFromObject.java

/**
 * This operation accepts an object in the JavaScript Object Notation format (JSON) and returns a value for the specified key.
 *
 * @param object The string representation of a JSON object.
 *               Objects in JSON are a collection of name value pairs, separated by a colon and surrounded with curly brackets {}.
 *               The name must be a string value, and the value can be a single string or any valid JSON object or array.
 *               Examples: {"one":1, "two":2}, {"one":{"a":"a","B":"B"}, "two":"two", "three":[1,2,3.4]}
 * @param key    The key in the object to get the value of.
 *               Examples: city, location[0].city
 * @return a map containing the output of the operation. Keys present in the map are:
 * <p/>//from   ww w  . j  ava 2 s . co m
 * <br><br><b>returnResult</b> - This will contain the value for the specified key in the object.
 * <br><b>exception</b> - In case of success response, this result is empty. In case of failure response,
 * this result contains the java stack trace of the runtime exception.
 * <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure.
 */
@Action(name = "Get Value from Object", outputs = { @Output(OutputNames.RETURN_RESULT),
        @Output(OutputNames.RETURN_CODE), @Output(OutputNames.EXCEPTION) }, responses = {
                @Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
                @Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) })
public Map<String, String> execute(@Param(value = Constants.InputNames.OBJECT, required = true) String object,
        @Param(value = Constants.InputNames.KEY, required = true) String key) {

    Map<String, String> returnResult = new HashMap<>();

    if (StringUtilities.isBlank(object)) {
        return populateResult(returnResult, new Exception("Empty object provided!"));
    }
    if (key == null) {
        return populateResult(returnResult, new Exception("Null key provided!"));
    }

    final JsonNode jsonRoot;
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        jsonRoot = objectMapper.readTree(object);
    } catch (Exception exception) {
        final String value = "Invalid object provided! " + exception.getMessage();
        return populateResult(returnResult, value, exception);
    }

    int startIndex = 0;
    final JsonNode valueFromObject;
    try {
        valueFromObject = getObject(jsonRoot, key.split(ESCAPED_SLASH + "."), startIndex);
    } catch (Exception exception) {
        return populateResult(returnResult, exception);
    }
    if (valueFromObject.isValueNode()) {
        return populateResult(returnResult, valueFromObject.asText(), null);
    } else {
        return populateResult(returnResult, valueFromObject.toString(), null);
    }

}

From source file:ratpack.jackson.internal.JsonParser.java

@Override
public <T> T parse(Context context, TypedData body, Parse<T, JsonParseOpts> parse) {
    JsonParseOpts opts = parse.getOpts();
    Class<T> type = parse.getType();

    ObjectMapper objectMapper = getObjectMapper(opts);
    try {//from www . java 2 s.  c  o  m
        InputStream inputStream = body.getInputStream();
        if (type.equals(JsonNode.class)) {
            return type.cast(objectMapper.readTree(inputStream));
        } else {
            return objectMapper.readValue(inputStream, type);
        }
    } catch (IOException e) {
        throw uncheck(e);
    }
}

From source file:com.baasbox.controllers.User.java

/***
 * Login the user./*from   w w w.  j av a  2  s .  c o  m*/
 * parameters: 
 * username
 * password
 * appcode: the App Code (API KEY)
 * login_data: json serialized string containing info related to the device used by the user. In particular, for push notification, must by supplied:
 *    deviceId
 *    os: (android|ios)
 * @return
 * @throws SqlInjectionException 
 * @throws IOException 
 * @throws JsonProcessingException 
 */
@With({ NoUserCredentialWrapFilter.class })
public static Result login() throws SqlInjectionException, JsonProcessingException, IOException {
    String username = "";
    String password = "";
    String appcode = "";
    String loginData = null;

    RequestBody body = request().body();
    //BaasBoxLogger.debug ("Login called. The body is: {}", body);
    if (body == null)
        return badRequest("missing data: is the body x-www-form-urlencoded or application/json? Detected: "
                + request().getHeader(CONTENT_TYPE));
    Map<String, String[]> bodyUrlEncoded = body.asFormUrlEncoded();
    if (bodyUrlEncoded != null) {
        if (bodyUrlEncoded.get("username") == null)
            return badRequest("The 'username' field is missing");
        else
            username = bodyUrlEncoded.get("username")[0];
        if (bodyUrlEncoded.get("password") == null)
            return badRequest("The 'password' field is missing");
        else
            password = bodyUrlEncoded.get("password")[0];
        if (bodyUrlEncoded.get("appcode") == null)
            return badRequest("The 'appcode' field is missing");
        else
            appcode = bodyUrlEncoded.get("appcode")[0];
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Username " + username);
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Password " + password);
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Appcode " + appcode);
        if (username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername())
                || username.equalsIgnoreCase(BBConfiguration.getBaasBoxUsername()))
            return forbidden(username + " cannot login");

        if (bodyUrlEncoded.get("login_data") != null)
            loginData = bodyUrlEncoded.get("login_data")[0];
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("LoginData" + loginData);
    } else {
        JsonNode bodyJson = body.asJson();
        if (bodyJson == null)
            return badRequest("missing data : is the body x-www-form-urlencoded or application/json? Detected: "
                    + request().getHeader(CONTENT_TYPE));
        if (bodyJson.get("username") == null)
            return badRequest("The 'username' field is missing");
        else
            username = bodyJson.get("username").asText();
        if (bodyJson.get("password") == null)
            return badRequest("The 'password' field is missing");
        else
            password = bodyJson.get("password").asText();
        if (bodyJson.get("appcode") == null)
            return badRequest("The 'appcode' field is missing");
        else
            appcode = bodyJson.get("appcode").asText();
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Username " + username);
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Password " + password);
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Appcode " + appcode);
        if (username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername())
                || username.equalsIgnoreCase(BBConfiguration.getBaasBoxUsername()))
            return forbidden(username + " cannot login");

        if (bodyJson.get("login_data") != null)
            loginData = bodyJson.get("login_data").asText();
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("LoginData" + loginData);
    }
    /* other useful parameter to receive and to store...*/
    //validate user credentials
    ODatabaseRecordTx db = null;
    String user = null;
    try {
        db = DbHelper.open(appcode, username, password);
        user = prepareResponseToJson(UserService.getCurrentUser());

        if (loginData != null) {
            JsonNode loginInfo = null;
            try {
                loginInfo = Json.parse(loginData);
            } catch (Exception e) {
                if (BaasBoxLogger.isDebugEnabled())
                    BaasBoxLogger.debug("Error parsong login_data field");
                if (BaasBoxLogger.isDebugEnabled())
                    BaasBoxLogger.debug(ExceptionUtils.getFullStackTrace(e));
                return badRequest("login_data field is not a valid json string");
            }
            Iterator<Entry<String, JsonNode>> it = loginInfo.fields();
            HashMap<String, Object> data = new HashMap<String, Object>();
            while (it.hasNext()) {
                Entry<String, JsonNode> element = it.next();
                String key = element.getKey();
                Object value = element.getValue().asText();
                data.put(key, value);
            }
            UserService.registerDevice(data);
        }
    } catch (OSecurityAccessException e) {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("UserLogin: " + ExceptionUtils.getMessage(e));
        return unauthorized("user " + username + " unauthorized");
    } catch (InvalidAppCodeException e) {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("UserLogin: " + ExceptionUtils.getMessage(e));
        return badRequest("user " + username + " unauthorized");
    } finally {
        if (db != null && !db.isClosed())
            db.close();
    }
    ImmutableMap<SessionKeys, ? extends Object> sessionObject = SessionTokenProvider.getSessionTokenProvider()
            .setSession(appcode, username, password);
    response().setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));

    ObjectMapper mapper = new ObjectMapper();
    user = user.substring(0, user.lastIndexOf("}")) + ",\"" + SessionKeys.TOKEN.toString() + "\":\""
            + (String) sessionObject.get(SessionKeys.TOKEN) + "\"}";
    JsonNode jn = mapper.readTree(user);

    return ok(jn);
}

From source file:org.fcrepo.importexport.common.BagProfile.java

/**
 * Default constructor./*from  w  w w  . j a  v a 2 s .  co m*/
 * @param in InputStream containing the Bag profile JSON document
 * @throws IOException when there is an I/O error reading JSON
 */
public BagProfile(final InputStream in) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode json = mapper.readTree(in);

    payloadDigestAlgorithms = arrayValues(json, "Manifests-Required");
    tagDigestAlgorithms = arrayValues(json, "Tag-Manifests-Required");
    if (tagDigestAlgorithms == null) {
        tagDigestAlgorithms = payloadDigestAlgorithms;
    }

    metadataFields.put(BAG_INFO_FIELDNAME, metadataFields(json, BAG_INFO_FIELDNAME));
    sections.add(BAG_INFO_FIELDNAME);

    if (json.get("Other-Info") != null) {
        loadOtherTags(json);
    }
}

From source file:org.onosproject.ospf.controller.impl.Controller.java

/**
 * Get the area configuration from a json file.
 *
 * @return areas List<OSPFArea>// w ww  .  ja  v a2 s . co  m
 */
private List getConfiguration() {
    List<OSPFArea> areas = null;
    try {
        // Read network configuration from area-config.json
        // read the configuration area wise .
        File configFile = new File(CONFIG_DIR, configFileName);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(configFile);
        Configuration config = mapper.treeToValue(node, Configuration.class);
        log.debug("OSPF area Configuration : {}", config);
        areas = config.getOspfAreas();
        return areas;

    } catch (Exception e) {
        log.debug("Error::Controller:: {}", e.getMessage());
        return areas;
    }

}

From source file:org.opendaylight.sfc.sbrest.json.SfgExporterTest.java

private boolean testExportSfgJson(String expectedResultFile, boolean nameOnly) throws IOException {
    ServiceFunctionGroup serviceFunctionGroup;
    String exportedSfgString;//from w  w w .  jav a 2s. co m
    SfgExporterFactory sfgExporterFactory = new SfgExporterFactory();

    if (nameOnly) {
        serviceFunctionGroup = this.buildServiceFunctionGroupNameOnly();
        exportedSfgString = sfgExporterFactory.getExporter().exportJsonNameOnly(serviceFunctionGroup);
    } else {
        serviceFunctionGroup = this.buildServiceFunctionGroup();
        exportedSfgString = sfgExporterFactory.getExporter().exportJson(serviceFunctionGroup);
    }

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode expectedSfgJson = objectMapper
            .readTree(this.gatherServiceFunctionGroupJsonStringFromFile(expectedResultFile));
    JsonNode exportedSfgJson = objectMapper.readTree(exportedSfgString);

    System.out.println("EXPECTED: " + expectedSfgJson);
    System.out.println("EXPORTED: " + exportedSfgJson);

    return expectedSfgJson.equals(exportedSfgJson);
}

From source file:org.workspace7.moviestore.utils.MovieDBHelper.java

/**
 * This method queries the external API and caches the movies, for the demo purpose we just query only first page
 *
 * @return - the status code of the invocation
 *//*  ww  w .j  a  v  a 2s .  c  o m*/
protected int queryAndCache() {

    if (this.moviesCache.isEmpty()) {

        log.info("No movies exist in cache, loading cache ..");

        UriComponentsBuilder moviesUri = UriComponentsBuilder
                .fromUriString(movieStoreProps.getApiEndpointUrl() + "/movie/popular")
                .queryParam("api_key", movieStoreProps.getApiKey());

        final URI requestUri = moviesUri.build().toUri();

        log.info("Request URI:{}", requestUri);

        ResponseEntity<String> response = restTemplate.getForEntity(requestUri, String.class);

        log.info("Response Status:{}", response.getStatusCode());

        Map<String, Movie> movieMap = new HashMap<>();

        if (200 == response.getStatusCode().value()) {
            String jsonBody = response.getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode root = objectMapper.readTree(jsonBody);
                JsonNode results = root.path("results");
                results.elements().forEachRemaining(movieNode -> {
                    String id = movieNode.get("id").asText();
                    Movie movie = Movie.builder().id(id).overview(movieNode.get("overview").asText())
                            .popularity(movieNode.get("popularity").floatValue())
                            .posterPath("http://image.tmdb.org/t/p/w92" + movieNode.get("poster_path").asText())
                            .logoPath("http://image.tmdb.org/t/p/w45" + movieNode.get("poster_path").asText())
                            .title(movieNode.get("title").asText())
                            .price(ThreadLocalRandom.current().nextDouble(1.0, 10.0)).build();
                    movieMap.put(id, movie);
                });
            } catch (IOException e) {
                log.error("Error reading response:", e);
            }

            log.debug("Got {} movies", movieMap);
            moviesCache.putAll(movieMap);
        }
        return response.getStatusCode().value();
    } else {
        log.info("Cache already loaded with movies ... will use cache");
        return 200;
    }
}

From source file:DocumentSerializationTest.java

protected Result createDocumentWithVersionNull(String sAddress) throws JsonProcessingException, IOException {
    FakeRequest request = new FakeRequest(POST, sAddress);
    request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
    request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
    ObjectMapper om = new ObjectMapper();
    JsonNode node = om.readTree("{\"k\":0,\"@version\":null}");
    request = request.withJsonBody(node);
    return routeAndCall(request);
}

From source file:DocumentSerializationTest.java

protected Result createDocumentWithJustCollection(String sAddress) throws JsonProcessingException, IOException {
    FakeRequest request = new FakeRequest(POST, sAddress);
    request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
    request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
    ObjectMapper om = new ObjectMapper();
    JsonNode node = om.readTree("[1,2]");
    request = request.withJsonBody(node);
    return routeAndCall(request);
}

From source file:DocumentSerializationTest.java

protected Result createDocumentWithJustOneElement(String sAddress) throws JsonProcessingException, IOException {
    FakeRequest request = new FakeRequest(POST, sAddress);
    request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
    request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
    ObjectMapper om = new ObjectMapper();
    JsonNode node = om.readTree("2");
    request = request.withJsonBody(node);
    return routeAndCall(request);
}