public String createChallangeNAClaims(String req, String claimDefs, int size) throws Exception { ObjectMapper mapper = new ObjectMapper(); ArrayNode claimDefNodes = (ArrayNode) mapper.readTree(claimDefs); req = req.replaceAll("\"", ""); byte[] reqElemBytes = Base64.decode(req); Element reqElem = null; ArrayList<IdentityClaimDefinition> icds = new ArrayList<IdentityClaimDefinition>(); for (int i = 0; i < size; i++) { String onVal = claimDefNodes.get(i).getTextValue(); ObjectNode claimDefOn = (ObjectNode) mapper.readTree(onVal); IdentityClaimDefinition idClaimDef = new IdentityClaimDefinition(claimDefOn); icds.add(idClaimDef); if (reqElem == null) { Pairing pairing = idClaimDef.getParams().getPairing(); reqElem = pairing.getG1().newElement(); reqElem.setFromBytes(reqElemBytes); // System.out.println(reqElem); } } Pairing pairing = icds.get(0).getParams().getPairing(); Field gt = pairing.getGT(); Element sessionKey = gt.newRandomElement().getImmutable(); Element sessionKeyOrig = sessionKey.getImmutable(); // System.out.println("Key: " + sessionKey); JsonNode rootNode = mapper.createObjectNode(); ObjectNode on = (ObjectNode) rootNode; Encrypt encrypt = new Encrypt(); for (int i = 0; i < size; i++) { IdentityClaimDefinition claimDef = icds.get(i); Element share = null; if (i < (size - 1)) { share = gt.newRandomElement().getImmutable(); sessionKey = sessionKey.sub(share).getImmutable(); } else { // Last one should be the remaining part of session key share = sessionKey; } encrypt.init(claimDef.getParams()); // System.out.println("Part : " + i + " : " + share); AECipherTextBlock ct = encrypt.doEncrypt(share, reqElem); on.put(claimDef.getName(), ct.serializeJSON()); } // System.out.println(sessionKeyOrig); String sk = new String(Base64.encode(sessionKeyOrig.toBytes())); sk = sk.replaceAll(" ", ""); on.put("SessionKey", sk); return on.toString(); }
@Test public void testExtractTwigMultipleInArrayObjectVariable() throws QueryNodeException, ProjectionException, IOException { String query = "{" + "\"twig\" : { " + "\"root\" : \"actors\"," + "\"child\" : [{\"occur\":\"MUST\"," // blank node + "\"twig\": {" + "\"child\":[{\"occur\":\"MUST\"," + "\"twig\": {" + "\"root\":\"last_name\"," + "\"child\":[" + "{\"occur\":\"MUST\"," + "\"node\" : { \"query\" : \"e*\" } " + "}" + "]" + "}" + "}" + "]" + "}" + "}" + ", {\"occur\" : \"MUST\", \"variable\" : {}}" + "]" + "}" + "}"; Query q = parser.parse(query, ""); SimpleJsonByQueryExtractor extractor = new SimpleJsonByQueryExtractor(); assertEquals( mapper.readTree( "[{\"last_name\":\"Eastwood\",\"first_name\":\"Clint\",\"birth_date\":1930,\"role\": \"William Munny\"}," + "{\"first_name\": \"Morgan\",\"last_name\": \"Ereeman\",\"birth_date\": 1937,\"role\": \"Ned Logan\"}]"), mapper.readTree(extractor.extractAsString(json, q))); }
@Test public void testSimpleNumericRangeNoVars() throws QueryNodeException, ProjectionException, IOException { String query = "{ \"twig\": " + "{ \"root\":\"year\"," + " \"child\": [{\"occur\":\"MUST\"," + " \"node\" : { \"query\" : \"http://www.w3.org/2001/XMLSchema#long([1991 TO 2000])\" }}]}}"; Query q = parser.parse(query, ""); SimpleJsonByQueryExtractor extractor = new SimpleJsonByQueryExtractor(); assertEquals(mapper.readTree(json), mapper.readTree(extractor.extractAsString(json, q))); }
@Test public void testTwoVariablesPrimitiveAndObject() throws QueryNodeException, ProjectionException, IOException { String twig0 = "\"twig\": {" + "\"root\":\"title\"" + ",\"child\":[" + "{\"occur\":\"MUST\"" + ",\"node\" : { \"query\" : \"Unforgiven\" }" + "}" + ", {\"occur\" : \"MUST\", \"variable\" : {}}" + "]" + "}"; String twig1 = "\"twig\" : { " + "\"root\" : \"director\"," + "\"child\" : [{\"occur\":\"MUST\"," // blank node + "\"twig\": {" + "\"child\":[{\"occur\":\"MUST\"," + "\"twig\": {" + "\"root\":\"first_name\"," + "\"child\":[" + "{\"occur\":\"MUST\"," + "\"node\" : { \"query\" : \"Clint\" } " + "}" + "]" + "}" + "}" + "]" + "}" + "}" + ", {\"occur\" : \"MUST\", \"variable\" : {}}" + "]" + "}"; Query q = parser.parse( "{\"boolean\":{\"clause\":[{\"occur\":\"MUST\"," + twig0 + "},{\"occur\":\"MUST\"," + twig1 + "}]}}", ""); SimpleJsonByQueryExtractor extractor = new SimpleJsonByQueryExtractor(); assertEquals( mapper.readTree( "{\"title\":\"Unforgiven\",\"director\":{\"last_name\":\"Eastwood\",\"first_name\":\"Clint\",\"birth_date\":1930}}"), mapper.readTree(extractor.extractAsString(json, q))); }
public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\\Java SE\\src\\json\\jackson_tree_model\\file.json")); JsonNode jsonRoot = mapper.readTree(bufferedReader); JsonNode jsonNode = jsonRoot.path("name"); System.out.println(jsonNode.getTextValue()); JsonNode jsonNode1 = jsonRoot.path("age"); System.out.println(jsonNode1.getTextValue()); JsonNode jsonNode2 = jsonRoot.path("messages"); Iterator<JsonNode> nodeIterator = jsonNode2.getElements(); while (nodeIterator.hasNext()) { JsonNode jsonNode3 = nodeIterator.next(); System.out.println(jsonNode3.getTextValue()); } ((ObjectNode) jsonRoot).put("nickname", "new nickname"); ((ObjectNode) jsonRoot).put("name", "updated name"); ((ObjectNode) jsonRoot).remove("age"); mapper.writeValue(new File("D:\\Java SE\\src\\json\\jackson_tree_model\\file.json"), jsonRoot); }
@RequestMapping( value = "/json/view/{studyOID}/{studySubjectIdentifier}/{studyEventOID}/{formVersionOID}", method = RequestMethod.GET) public @ResponseBody JsonNode getClinicalData( @PathVariable("studyOID") String studyOID, @PathVariable("formVersionOID") String formVersionOID, @PathVariable("studyEventOID") String studyEventOID, @PathVariable("studySubjectIdentifier") String studySubjectIdentifier, @RequestParam(value = "includeDNs", defaultValue = "n", required = false) String includeDns, @RequestParam(value = "includeAudits", defaultValue = "n", required = false) String includeAudits, HttpServletRequest request) throws Exception { ResourceBundleProvider.updateLocale(new Locale("en_US")); String result = odmClinicaDataResource.getODMClinicaldata( studyOID, formVersionOID, studyEventOID, studySubjectIdentifier, includeDns, includeAudits, request); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readTree(result); }
@Test public void shouldReturnFalseWhenNodeDoesNotHaveAllPairs() throws IOException { JsonNode node = mapper.readTree("{\"key\" : \"value\", \"anotherKey\" : \"value\"}"); assertFalse( new TAMAJsonNode(node) .hasAllPairs(pair("key", "value"), pair("anotherKey", "anotherValue"))); }
/** * Request URL * * @param urlParts List<String> request of url directories. * @return JSONArray from JSON response. */ private JsonNode doRequest(List<String> urlParts) { StringBuilder url = new StringBuilder(); Iterator url_iterator = urlParts.iterator(); url.append(getBaseUrl()); // Generate URL with UTF-8 Encoding while (url_iterator.hasNext()) { try { String url_bit = (String) url_iterator.next(); url.append("/").append(_encodeURIcomponent(url_bit)); } catch (Exception e) { return createResponse("Failed UTF-8 Encoding URL."); } } // Fail if string too long if (url.length() > MESSAGE_LIMIT) { return createResponse("Message too long"); } try { WebResource webResource = httpClient.resource(url.toString()); String response = webResource.get(String.class); return mapper.readTree(response); } catch (Exception e) { return createResponse("Failed JSONP HTTP Request."); } }
private String getFacebookProfileId(OAuthResourceResponse resourceResponse) throws IOException { String resourceResponseBody = resourceResponse.getBody(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(resourceResponseBody); JsonNode idNode = jsonNode.get("id"); return (idNode != null) ? idNode.asText() : null; }
public Boolean createScore( String gameId, String username, Long score, String platform, String uniqueId, String difficulty) throws RequestException { Petition request = null; String rawResponse = null; String value = null; // Build the request. try { request = new Petition(this.requestUrl + "createScore", this.apiKey); value = gameId; request.addParameter("game_id", value); value = username; request.addParameter("username", value); request.addParameter("score", String.valueOf(score)); value = "json"; request.addParameter("response", value); } catch (MalformedURLException e) { throw new RequestException("Bad URL: " + this.requestUrl + "createScore", e); } catch (UnsupportedEncodingException e) { throw new RequestException("Bad enconding for parameter value: " + value, e); } // Send the request and get the JSON response. try { rawResponse = this.client.doPost(request); } catch (IOException e) { throw new RequestException("Something went wrong sending the request", e); } // Map the JSON response to the model object. ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode; JsonNode childNode = null; try { rootNode = mapper.readTree(rawResponse); childNode = rootNode.findValue("success"); if (childNode != null) { return true; } else { childNode = rootNode.findValue("error"); if (childNode != null) { throw new RequestException(rootNode.findValue("error").toString()); } } } catch (JsonProcessingException e) { throw new RequestException("JSON error", e); } catch (IOException e) { throw new RequestException("IO error", e); } return false; }
/** * POST /api/v1/janitor will try a add a new event with the information in the url context. * * @param content the Json content passed to the http POST request * @return the response * @throws IOException */ @POST public Response addEvent(String content) throws IOException { ObjectMapper mapper = new ObjectMapper(); LOGGER.info(String.format("JSON content: '%s'", content)); JsonNode input = mapper.readTree(content); String eventType = getStringField(input, "eventType"); String resourceId = getStringField(input, "resourceId"); Response.Status responseStatus; ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8); gen.writeStartObject(); gen.writeStringField("eventType", eventType); gen.writeStringField("resourceId", resourceId); if (StringUtils.isEmpty(eventType) || StringUtils.isEmpty(resourceId)) { responseStatus = Response.Status.BAD_REQUEST; gen.writeStringField("message", "eventType and resourceId parameters are all required"); } else { if (eventType.equals("OPTIN")) { responseStatus = optInResource(resourceId, true, gen); } else if (eventType.equals("OPTOUT")) { responseStatus = optInResource(resourceId, false, gen); } else { responseStatus = Response.Status.BAD_REQUEST; gen.writeStringField("message", String.format("Unrecognized event type: %s", eventType)); } } gen.writeEndObject(); gen.close(); LOGGER.info("entity content is '{}'", baos.toString("UTF-8")); return Response.status(responseStatus).entity(baos.toString("UTF-8")).build(); }
// allow json parsing to be unit tested from a local file public List<String> parseJson(final String fullFile) throws JsonParseException, IOException { final InputStream is = ClassLoader.getSystemResourceAsStream(fullFile); final JsonParser jp = factory.createJsonParser(is); final JsonNode node = mapper.readTree(jp); return parseJson(node); }
private static TupleMRConfig parse(JsonParser parser) throws IOException { try { return parse(MAPPER.readTree(parser)); } catch (JsonParseException e) { throw new IOException(e); } }
private static String getChannelURL(String responseBody) { try { ObjectMapper mapper = new ObjectMapper(); JsonFactory f = mapper.getJsonFactory(); JsonParser jp = f.createJsonParser(responseBody); JsonToken current = jp.nextToken(); if (current != JsonToken.START_OBJECT) { throw new IllegalStateException("FAIL - Error: root should be an object: quiting."); } JsonNode node = mapper.readTree(jp); if (node.has("notificationChannel")) { node = node.get("notificationChannel"); if (node.has("channelData")) { node = node.get("channelData"); if (node.has("channelURL")) { return node.get("channelURL").getTextValue(); } } } jp.close(); } catch (IOException e) { throw new IllegalStateException("FAIL - Error parsing the body, is a JSON?"); } return null; }
/** * Create a session key, encrypt it with the given request and claimDef. Return a serialized JSON * node with the session key and challenge. * * @param request Request from user: Base64 encoded bytes of the request element. * @param claimDef Claim definition to use: JSON encoded * @return * @throws Exception */ public String createChallange(String request, String claimDef) throws Exception { ObjectMapper mapper = new ObjectMapper(); ObjectNode claimDefOn = (ObjectNode) mapper.readTree(claimDef); IdentityClaimDefinition idClaimDef = new IdentityClaimDefinition(claimDefOn); byte[] reqElemBytes = Base64.decode(request); Element reqElem = idClaimDef.getParams().getPairing().getG1().newElement(); reqElem.setFromBytes(reqElemBytes); Element sessionKey = idClaimDef.getParams().getPairing().getGT().newRandomElement().getImmutable(); // Encrypt session key Encrypt encrypt = new Encrypt(); encrypt.init(idClaimDef.getParams()); AECipherTextBlock ct = encrypt.doEncrypt(sessionKey, reqElem); JsonNode rootNode = mapper.createObjectNode(); ObjectNode on = (ObjectNode) rootNode; on.put(idClaimDef.getName(), ct.serializeJSON()); String sk = new String(Base64.encode(sessionKey.toBytes())); sk = sk.replaceAll(" ", ""); on.put("SessionKey", sk); return on.toString(); }
public static JsonNode getJsonNodeFromString(String jsonString) { try { return objmapper.readTree(jsonString); } catch (IOException e) { LOG.error("", e); return null; } }
@Test public void testSelectByNumericRangeFromArray() throws QueryNodeException, ProjectionException, IOException { String query = "{" + "\"twig\" : { " + "\"root\" : \"actors\"," + "\"child\" : [{\"occur\":\"MUST\"," // blank node + "\"twig\": {" + "\"child\":[{\"occur\":\"MUST\"," + "\"twig\": {" + "\"root\":\"birth_date\"," + "\"child\":[" + "{\"occur\":\"MUST\"," + "\"node\" : { \"query\" : \"http://www.w3.org/2001/XMLSchema#long([* TO 1932])\" } " + "}" + "]" + "}" + "}" + "]" + "}" + "}" + ", {\"occur\" : \"MUST\", \"variable\" : {}}" + "]" + "}" + "}"; Query q = parser.parse(query, ""); SimpleJsonByQueryExtractor extractor = new SimpleJsonByQueryExtractor(); assertEquals( mapper.readTree( " [" + "{" + "\"first_name\": \"Clint\"," + "\"last_name\": \"Eastwood\"," + "\"birth_date\": 1930," + "\"role\": \"William Munny\"" + "}," + "{" + "\"first_name\": \"Gene\"," + "\"last_name\": \"Hackman\"," + "\"birth_date\": 1930," + "\"role\": \"Little Bill Dagget\"" + "}]"), mapper.readTree(extractor.extractAsString(json, q))); }
public static String getMediaId(String treeStr) throws JsonProcessingException, IOException { ObjectMapper jsonMapper = new ObjectMapper(); JsonNode jn = jsonMapper.readTree(treeStr); if (jn.get("media_id") != null) { return jn.get("media_id").getTextValue(); } return null; }
private String readBody(JsonParser jp) throws IOException { JsonNode node = mapper.readTree(jp); StringWriter out = new StringWriter(); JsonGenerator gen = jsonFactory.createJsonGenerator(out); mapper.writeTree(gen, node); gen.flush(); gen.close(); return out.toString(); }
public void testJson2() throws Exception { String json = "{\"resourceWithType\":{\"parentId\":0,\"pluginId\":0,\"pluginName\":\"Platforms\",\"resourceId\":10001,\"resourceName\":\"snert\",\"typeId\":10057,\"typeName\":\"Mac OS X\"}}"; ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(json); JsonNode content = root.getElements().next(); ResourceWithType rwt = mapper.readValue(content, ResourceWithType.class); }
public static JsonNode buildJsonMessage(String str) { ObjectMapper mapper = new ObjectMapper(); JsonNode actualObj = null; try { actualObj = mapper.readTree(str); } catch (IOException e) { Assert.fail(e.getMessage()); } return actualObj; }
public Long countBestScores( String gameId, String startDate, String endDate, String platform, String difficulty) throws RequestException { Petition request = null; String rawResponse = null; Long response = -1l; // Build the request. try { request = new Petition(this.requestUrl + "countBestScores", this.apiKey); request.addParameter("game_id", gameId); request.addParameter("start_date", startDate); request.addParameter("end_date", endDate); request.addParameter("platform", platform); request.addParameter("difficulty", difficulty); request.addParameter("response", "json"); } catch (MalformedURLException e) { throw new RequestException("Bad URL: " + this.requestUrl + "countScores", e); } catch (UnsupportedEncodingException e) { throw new RequestException("Bad enconding for parameter value", e); } // Send the request and get the JSON response. try { rawResponse = this.client.doPost(request); } catch (IOException e) { throw new RequestException("Something went wrong sending the request", e); } // Map the JSON response to the model object. ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode; JsonNode childNode = null; try { rootNode = mapper.readTree(rawResponse); childNode = rootNode.findValue("best_scores"); if (childNode != null) { response = childNode.asLong(); } else { childNode = rootNode.findValue("error"); if (childNode != null) { throw new RequestException(rootNode.findValue("error").toString()); } } } catch (JsonProcessingException e) { throw new RequestException("JSON error", e); } catch (IOException e) { throw new RequestException("IO error", e); } return response; }
@BeforeClass public static void initBeforeClass() throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getJsonFactory(); JsonParser jp = factory.createJsonParser(TestTimedEventBuffer.class.getResourceAsStream("/event1.json")); JsonNode sampleJsonNode = mapper.readTree(jp); timedEvent1 = TimedEvent.fromJson(sampleJsonNode); jp = factory.createJsonParser(TestTimedEventBuffer.class.getResourceAsStream("/event2.json")); sampleJsonNode = mapper.readTree(jp); timedEvent2 = TimedEvent.fromJson(sampleJsonNode); EventQueryParser queryParser = new EventQueryParser(); queryModel = queryParser.parseEventQuery( "request1.within(\"1990/07/04 12:08:56 PST\", \"2012/07/04 12:08:56 PST\")"); // queryModel = queryParser.parseEventQuery("request.last(\"4hours\").eq(/\"service\"," + // "#\"Cluster\").eq(/\"service\",#\"Cluster\")"); }
@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response login(String json) throws Exception { JsonNode node = mapper.readTree(json); String user = node.get("user").asText(); String password = node.get("password").asText(); logger.info("got post! {} {}", user, password); ObjectNode login = Statics.userService.login(user, password); return Response.ok(login.toString()).build(); }
/** * Initialises the database. */ static { try { ObjectMapper om = new ObjectMapper(); om.configure( JsonParser.Feature.ALLOW_COMMENTS, true ); String jsonText = Resources.loadResourceAsString( DATABASE_NAME ); // workaround for bug #779, see http://jira.codehaus.org/browse/JACKSON-779 database = om.readTree( jsonText ); } catch ( Exception e ) { throw new ExceptionInInitializerError( e ); } }
@Test public void testDeserialize() throws Exception { final String json = MAPPER.writeValueAsString( new GDDateTimeClass(new DateTime(2012, 3, 20, 14, 31, 5, 3, DateTimeZone.UTC))); final JsonNode node = MAPPER.readTree(json); assertThat(node.path("date").getTextValue(), is("2012-03-20 14:31:05")); final GDDateTimeClass date = MAPPER.readValue(json, GDDateTimeClass.class); assertThat(date.getDate(), is(new DateTime(2012, 3, 20, 14, 31, 5, DateTimeZone.UTC))); }
/** It only fetches properties in the first level */ private String fetchValueFromJson(String jsonString, String propetyName) { String result = null; try { ObjectMapper m = new ObjectMapper(); JsonNode rootNode = m.readTree(jsonString); JsonNode nameNode = rootNode.path(propetyName); if (nameNode != null) result = nameNode.getTextValue(); } catch (Exception e) { } return result; }
public static void main(String args[]) { JacksonTester tester = new JacksonTester(); try { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); JsonNode marksNode = mapper.createArrayNode(); ((ArrayNode) marksNode).add(100); ((ArrayNode) marksNode).add(90); ((ArrayNode) marksNode).add(85); ((ObjectNode) rootNode).put("name", "Mahesh Kumar"); ((ObjectNode) rootNode).put("age", 21); ((ObjectNode) rootNode).put("verified", false); ((ObjectNode) rootNode).put("marks", marksNode); mapper.writeValue(new File("student.json"), rootNode); rootNode = mapper.readTree(new File("student.json")); JsonNode nameNode = rootNode.path("name"); System.out.println("Name: " + nameNode.getTextValue()); JsonNode ageNode = rootNode.path("age"); System.out.println("Age: " + ageNode.getIntValue()); JsonNode verifiedNode = rootNode.path("verified"); System.out.println("Verified: " + (verifiedNode.getBooleanValue() ? "Yes" : "No")); JsonNode marksNode1 = rootNode.path("marks"); Iterator<JsonNode> iterator = marksNode1.getElements(); System.out.print("Marks: [ "); while (iterator.hasNext()) { JsonNode marks = iterator.next(); System.out.print(marks.getIntValue() + " "); } System.out.println("]"); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
private void updateByOpts(File file, E model) { try { File optsFile = new File(file.getAbsolutePath().replace(".js", ".opts")); log().info("Looking for opts file: " + optsFile); if (!optsFile.exists() || !optsFile.isFile()) { return; } ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(optsFile); JsonUtils.parse(model, node); } catch (IOException e) { log().error(String.format("Failed to update via opts file %s with %s", file, model), e); } }
@Test public void testTwoPrimitiveVariables() throws QueryNodeException, ProjectionException, IOException { String twig0 = "\"twig\": {" + "\"root\":\"title\"" + ",\"child\":[" + "{\"occur\":\"MUST\"" + ",\"node\" : { \"query\" : \"Unforgiven\" }" + "}" + ", {\"occur\" : \"MUST\", \"variable\" : {}}" + "]" + "}"; String twig1 = "\"twig\": {" + "\"root\":\"country\"" + ",\"child\":[" + "{\"occur\":\"MUST\"" + ",\"node\" : { \"query\" : \"USA\" }" + "}" + ", {\"occur\" : \"MUST\", \"variable\" : {}}" + "]" + "}"; Query q = parser.parse( "{\"boolean\":{\"clause\":[{\"occur\":\"MUST\"," + twig0 + "},{\"occur\":\"MUST\"," + twig1 + "}]}}", ""); SimpleJsonByQueryExtractor extractor = new SimpleJsonByQueryExtractor(); assertEquals( mapper.readTree("{\"country\":\"USA\",\"title\":\"Unforgiven\"}"), mapper.readTree(extractor.extractAsString(json, q))); }