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:RoleFunctionalTest.java

@Test
public void testRoleCreate() throws Exception {

    running(getFakeApplication(), new Runnable() {
        public void run() {
            try {
                String sFakeRole = getRouteAddress();
                FakeRequest requestCreation = new FakeRequest(POST, sFakeRole);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                Result result = route(requestCreation);
                assertRoute(result, "testRoleCreate.create", Status.CREATED, null, true);

                //creates one user in this Role
                String sFakeCreateUser = getFakeUserCreationAddress();
                requestCreation = new FakeRequest(POST, sFakeCreateUser);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                ObjectMapper mapper = new ObjectMapper();
                JsonNode actualObj = mapper.readTree("{\"username\":\"" + userName + "\","
                        + "\"password\":\"test\"," + "\"role\":\"" + roleName + "\"}");
                requestCreation = requestCreation.withJsonBody(actualObj);
                requestCreation = requestCreation.withHeader("Content-Type", "application/json");
                result = route(requestCreation);
                assertRoute(result, "testRoleCreate.createUser", Status.CREATED, null, true);

                //checks the user
                String sFakeCheckUser = getFakeUserAddress();
                requestCreation = new FakeRequest(GET, sFakeCheckUser);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "testRoleCreate.checkUser", Status.OK, "\"name\":\"" + roleName + "\"",
                        true);//from w  w w .j  a v  a  2  s .  c  o  m

                //drops the role
                requestCreation = new FakeRequest(DELETE, sFakeRole);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "testRoleCreate.drop", Status.OK, null, false);

                //checks that the role does not exist
                requestCreation = new FakeRequest(GET, sFakeRole);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "testRoleCreate.role_not_found", Status.NOT_FOUND, null, false);

                //checks that the fake user belongs to the registered role
                sFakeCheckUser = getFakeUserAddress();
                requestCreation = new FakeRequest(GET, sFakeCheckUser);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "testRoleCreate.checkUser", Status.OK, "\"name\":\"registered\"", true);

                //tries to recreate the same role, now with description
                requestCreation = new FakeRequest(POST, sFakeRole);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                mapper = new ObjectMapper();
                actualObj = mapper.readTree("{\"description\":\"this is a test\"}");
                requestCreation = requestCreation.withJsonBody(actualObj);
                requestCreation = requestCreation.withHeader("Content-Type", "application/json");
                result = route(requestCreation);
                assertRoute(result, "testRoleCreate.create_the_same", Status.CREATED, null, true);

                //checks the role
                requestCreation = new FakeRequest(GET, sFakeRole);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "testRoleCreate.check_with_desc", Status.OK,
                        "\"description\":\"this is a test\"", true);

                //updates the role name and description

                requestCreation = new FakeRequest(PUT, sFakeRole);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                mapper = new ObjectMapper();
                actualObj = mapper.readTree("{\"description\":\"this is new test\"}");
                requestCreation = requestCreation.withJsonBody(actualObj, PUT);
                result = route(requestCreation);
                assertRoute(result, "testRoleCreate.update_desc", Status.OK, null, true);

                //checks the role
                requestCreation = new FakeRequest(GET, sFakeRole);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "testRoleCreate.check_with_new_desc", Status.OK,
                        "\"description\":\"this is new test\"", true);

                //
                //finally... drop it, again
                requestCreation = new FakeRequest(DELETE, sFakeRole);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "testRoleCreate.drop_final", Status.OK, null, false);

            } catch (Exception e) {
                e.printStackTrace();
                fail();
            }
        }
    });
}

From source file:com.mnxfst.stream.listener.webtrends.WebtrendsTokenRequest.java

public String execute() throws Exception {

    final String assertion = buildAssertion();
    final Map<String, String> requestParams = new HashMap<String, String>() {
        private static final long serialVersionUID = 1919397363313726934L;

        {// w  ww  .ja v a  2s . co  m
            put(REQUEST_PARAM_CLIENT_ID, clientId);
            put(REQUEST_PARAM_CLIENT_ASSERTION, java.net.URLEncoder.encode(assertion, "UTF-8"));
        }
    };

    final String result = httpPost(requestParams);

    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser jp = factory.createParser(result);
    JsonNode obj = mapper.readTree(jp);

    JsonNode error = obj.findValue("Error");
    if (error != null)
        throw new Exception(obj.findValue("Description").asText());

    return obj.findValue("access_token").asText();
}

From source file:ac.ucy.cs.spdx.service.Compatibility.java

@POST
@Path("/compatible/")
@Consumes(MediaType.TEXT_PLAIN)/*w  w w  .j a v a2  s . c  o m*/
@Produces(MediaType.APPLICATION_JSON)
public String areCompatible(String jsonString) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode fileNode = null;
    try {
        fileNode = mapper.readTree(jsonString);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ArrayList<String> licenses = new ArrayList<String>();
    JsonNode licensesJSON = fileNode.get("licenses");
    StringBuilder compatibleJSON = new StringBuilder();

    for (int i = 0; i < licensesJSON.size(); i++) {
        String licenseId = licensesJSON.get(i).get("identifier").toString();
        licenseId = licenseId.substring(1, licenseId.length() - 1);
        licenses.add(licenseId);
    }

    boolean compatible = LicenseCompatibility.areCompatible(licenses.toArray(new String[licenses.size()]));
    boolean adjustable = true;
    ArrayList<License> proposed = new ArrayList<License>();

    if (!compatible) {
        LicenseCompatibility.proposeLicense(licenses.toArray(new String[licenses.size()]));
    }

    if (proposed.isEmpty()) {
        adjustable = false;
    }

    compatibleJSON.append(
            "{\"compatible\":\"" + compatible + "\",\"adjustable\":\"" + adjustable + "\",\"proposals\":[");
    for (License proposal : proposed) {
        compatibleJSON.append("{\"identifier\":\"" + proposal.getIdentifier() + "\"},");
    }

    if (adjustable) {
        compatibleJSON.deleteCharAt(compatibleJSON.length() - 1);
    }

    compatibleJSON.append("]}");
    return compatibleJSON.toString();// {"licenses":[{"identifier":"Apache-2.0"},{"identifier":"MPL-2.0"}]}
}

From source file:ac.ucy.cs.spdx.service.SpdxViolationAnalysis.java

@POST
@Path("/validate/")
@Consumes(MediaType.TEXT_PLAIN)/*from  w ww .j  a  v  a 2 s  .  c o  m*/
@Produces(MediaType.APPLICATION_JSON)
public String validateSpdx(String jsonString) throws InvalidSPDXAnalysisException {

    ObjectMapper mapper = new ObjectMapper();
    JsonNode fileNode = null;
    try {
        fileNode = mapper.readTree(jsonString);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String fileName = fileNode.get("filename").toString();
    fileName = fileName.substring(1, fileName.length() - 1);
    String content = fileNode.get("content").toString();
    content = StringEscapeUtils.unescapeXml(content);
    content = content.substring(1, content.length() - 1);

    SpdxLicensePairConflictError analysis = null;
    CaptureLicense captured = null;

    try {
        captured = new CaptureLicense(ParseRdf.parseToRdf(fileName, content));
    } catch (InvalidLicenseStringException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        analysis = new SpdxLicensePairConflictError(captured);
    } catch (UnsupportedSpdxVersionException e) {
        e.printStackTrace();
    }

    return analysis.toJson();// {"filename":"","content":""}
}

From source file:ac.ucy.cs.spdx.service.Compatibility.java

@POST
@Path("/edge/")
@Consumes(MediaType.TEXT_PLAIN)/*w  ww .j  av a 2 s .  c  o m*/
@Produces(MediaType.APPLICATION_JSON)
public String addEdge(String jsonString) {

    ObjectMapper mapper = new ObjectMapper();
    JsonNode licenseEdge = null;
    try {
        licenseEdge = mapper.readTree(jsonString);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ArrayList<String> licenseNodes = new ArrayList<String>();
    String nodeIdentifier = licenseEdge.get("nodeIdentifier").toString();
    nodeIdentifier = nodeIdentifier.substring(1, nodeIdentifier.length() - 1);

    String transitivity = licenseEdge.get("transitivity").toString();
    transitivity = transitivity.substring(1, transitivity.length() - 1);
    Boolean isTransitive = Boolean.parseBoolean(transitivity);

    JsonNode nodesJSON = licenseEdge.get("nodeIdentifiers");

    for (int i = 0; i < nodesJSON.size(); i++) {
        String node = nodesJSON.get(i).get("identifier").toString();
        node = node.substring(1, node.length() - 1);
        licenseNodes.add(node);
    }

    try {
        LicenseGraph.connectNode(isTransitive, nodeIdentifier,
                licenseNodes.toArray(new String[licenseNodes.size()]));
    } catch (LicenseEdgeAlreadyExistsException e) {
        e.printStackTrace();
        return "{\"status\":\"failure\",\"message\":\"" + e.getMessage() + "\"}";
    }

    LicenseGraph.exportGraph();

    return "{\"status\":\"success\",\"message\":\"" + nodeIdentifier + " -> " + licenseNodes.toString()
            + " added in the system.\"}";// {"nodeIdentifier":"Caldera","transitivity":"true","nodeIdentifiers":[{"identifier":"Apache-2.0"}]}
}

From source file:org.opendaylight.ovsdb.integrationtest.northbound.OvsdbNorthboundV2IT.java

private String getOvsUuid() {
    if (UuidHelper.getOvsUuid() == null) {
        Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter(USERNAME, PASSWORD));
        String uri = OvsdbNorthboundV2IT.BASE_URI + "/ovsdb/nb/v2/node/OVS/${node}/tables/open_vswitch/rows";
        WebResource webResource = client.resource(expand(uri));
        ClientResponse response = webResource.accept(MEDIA_TYPE_JSON).get(ClientResponse.class);

        assertEquals(200, response.getStatus());

        String row = response.getEntity(String.class);
        assertNotNull(row);//  ww w .j a v a 2s . co  m

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rowsNode = objectMapper.readTree(row).get("rows");
            assertNotNull(rowsNode);
            // The first fieldName is the UUID
            String uuid = rowsNode.fieldNames().next();
            assertNotNull(uuid);
            UuidHelper.setOvsUuid(uuid);
        } catch (IOException e) {
            fail("Cannot get the UUID for the Open_vSwitch table");
        }
    }

    return UuidHelper.getOvsUuid();
}

From source file:uk.ac.soton.itinnovation.sad.service.domain.JsonResponse.java

public JsonResponse(String result, JSONObject response) {
    this.result = result;
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    JsonFactory factory = mapper.getJsonFactory();
    try {/*w w  w .  ja  v a2s .c o m*/
        JsonParser jp = factory.createJsonParser(response.toString());
        this.response = mapper.readTree(jp);
    } catch (IOException ex) {
        logger.error("Failed to parse JSONObject", ex);
    }
}

From source file:uk.ac.soton.itinnovation.sad.service.domain.JsonResponse.java

public JsonResponse(String result, JSONArray response) {
    this.result = result;
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    JsonFactory factory = mapper.getJsonFactory();
    try {//from   ww  w  . ja v  a2 s.  co m
        JsonParser jp = factory.createJsonParser(response.toString());
        this.response = mapper.readTree(jp);
    } catch (IOException ex) {
        logger.error("Failed to parse JSONArray", ex);
    }
}

From source file:com.rmn.qa.servlet.BmpServlet.java

private JsonNode getNodeFromRequest(HttpServletRequest request) throws IOException {
    String jsonString = null;/*from w w  w  . ja v a2  s.  c o  m*/
    ServletInputStream in = null;
    try {
        in = request.getInputStream();
        jsonString = IOUtils.toString(in, "utf-8");
    } finally {
        IOUtils.closeQuietly(in);
    }
    ObjectMapper mapper = new ObjectMapper();
    JsonNode input = mapper.readTree(jsonString);
    return input;
}