List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree
public JsonNode readTree(URL source) throws IOException, JsonProcessingException
From source file:com.basistech.rosette.dm.json.plain.LanguageCodeJsonTest.java
@Test public void testRoundTrip() throws Exception { List<LanguageDetection.DetectionResult> detectionResults = Lists.newArrayList(); LanguageDetection.DetectionResult detectionResult = new LanguageDetection.DetectionResult.Builder( LanguageCode.KOREAN).encoding("uff-8").script(ISO15924.Hang).confidence(1.0).build(); detectionResults.add(detectionResult); LanguageDetection.Builder builder = new LanguageDetection.Builder(0, 100, detectionResults); LanguageDetection languageDetection = builder.build(); ObjectMapper mapper = objectMapper(); String json = mapper.writeValueAsString(languageDetection); // now read back as a tree. JsonNode tree = mapper.readTree(json); JsonNode resultsNode = tree.get("detectionResults"); ArrayNode resultArray = (ArrayNode) resultsNode; ObjectNode detectionNode = (ObjectNode) resultArray.get(0); assertEquals("kor", detectionNode.get("language").textValue()); assertEquals("Hang", detectionNode.get("script").textValue()); languageDetection = mapper.readValue(json, LanguageDetection.class); assertSame(LanguageCode.KOREAN, languageDetection.getDetectionResults().get(0).getLanguage()); }
From source file:org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfigTest.java
@Before public void setUp() throws Exception { InputStream jsonStream = SegmentRoutingDeviceConfigTest.class.getResourceAsStream("/sr-device-config.json"); adjacencySids1 = new HashMap<>(); Set<Integer> ports1 = new HashSet<>(); ports1.add(2);//ww w. j av a 2 s . c om ports1.add(3); adjacencySids1.put(100, ports1); Set<Integer> ports2 = new HashSet<>(); ports2.add(4); ports2.add(5); adjacencySids1.put(200, ports2); adjacencySids2 = new HashMap<>(); Set<Integer> ports3 = new HashSet<>(); ports3.add(6); adjacencySids2.put(300, ports3); DeviceId subject = DeviceId.deviceId("of:0000000000000001"); String key = "segmentrouting"; ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(jsonStream); ConfigApplyDelegate delegate = new MockDelegate(); config = new SegmentRoutingDeviceConfig(); config.init(subject, key, jsonNode, mapper, delegate); }
From source file:com.baasbox.controllers.User.java
@With({ AdminCredentialWrapFilter.class, ConnectToDBFilter.class }) @BodyParser.Of(BodyParser.Json.class) public static Result signUp() throws JsonProcessingException, IOException { if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method Start"); Http.RequestBody body = request().body(); JsonNode bodyJson = body.asJson();/*from ww w. j a v a2 s. c o m*/ if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("signUp bodyJson: " + bodyJson); if (bodyJson == null) return badRequest( "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json"); //check and validate input if (!bodyJson.has("username")) return badRequest("The 'username' field is missing"); if (!bodyJson.has("password")) return badRequest("The 'password' field is missing"); //extract mandatory fields JsonNode nonAppUserAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER); JsonNode privateAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER); JsonNode friendsAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER); JsonNode appUsersAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER); String username = (String) bodyJson.findValuesAsText("username").get(0); String password = (String) bodyJson.findValuesAsText("password").get(0); String appcode = (String) ctx().args.get("appcode"); if (privateAttributes != null && privateAttributes.has("email")) { //check if email address is valid if (!Util.validateEmail((String) privateAttributes.findValuesAsText("email").get(0))) return badRequest("The email address must be valid."); } if (StringUtils.isEmpty(password)) return status(422, "The password field cannot be empty"); //try to signup new user ODocument profile = null; try { UserService.signUp(username, password, null, nonAppUserAttributes, privateAttributes, friendsAttributes, appUsersAttributes, false); //due to issue 412, we have to reload the profile profile = UserService.getUserProfilebyUsername(username); } catch (InvalidJsonException e) { if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("signUp", e); return badRequest("One or more profile sections is not a valid JSON object"); } catch (UserAlreadyExistsException e) { if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("signUp", e); // Return a generic error message if the username is already in use. return badRequest("Error signing up"); } catch (EmailAlreadyUsedException e) { // Return a generic error message if the email is already in use. if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("signUp", e); return badRequest("Error signing up"); } catch (Throwable e) { BaasBoxLogger.warn("signUp", e); if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e)); else return internalServerError(ExceptionUtils.getMessage(e)); } if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method End"); ImmutableMap<SessionKeys, ? extends Object> sessionObject = SessionTokenProvider.getSessionTokenProvider() .setSession(appcode, username, password); response().setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN)); String result = prepareResponseToJson(profile); ObjectMapper mapper = new ObjectMapper(); result = result.substring(0, result.lastIndexOf("}")) + ",\"" + SessionKeys.TOKEN.toString() + "\":\"" + (String) sessionObject.get(SessionKeys.TOKEN) + "\"}"; JsonNode jn = mapper.readTree(result); return created(jn); }
From source file:io.cloudslang.content.json.actions.MergeArrays.java
/** * This operation merge the contents of two JSON arrays. This operation does not modify either of the input arrays. * The result is the contents or array1 and array2, merged into a single array. The merge operation add into the result * the first array and then the second array. * * @param array1 The string representation of a JSON array object. * Arrays in JSON are comma separated lists of objects, enclosed in square brackets [ ]. * Examples: [1,2,3] or ["one","two","three"] or [{"one":1, "two":2}, 3, "four"] * @param array2 The string representation of a JSON array object. * Arrays in JSON are comma separated lists of objects, enclosed in square brackets [ ]. * Examples: [1,2,3] or ["one","two","three"] or [{"one":1, "two":2}, 3, "four"] * @return a map containing the output of the operation. Keys present in the map are: * <p/>//from w ww . jav a 2 s. co m * <br><br><b>returnResult</b> - This will contain the string representation of the new JSON array with the contents * of array1 and array2. * <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 = "Merge Arrays", 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.ARRAY, required = true) String array1, @Param(value = Constants.InputNames.ARRAY, required = true) String array2) { Map<String, String> returnResult = new HashMap<>(); if (StringUtilities.isBlank(array1)) { final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE.replaceFirst("=", EMPTY_STRING); return populateResult(returnResult, exceptionValue, new Exception(exceptionValue)); } if (StringUtilities.isBlank(array2)) { final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY2_MESSAGE.replaceFirst("=", EMPTY_STRING); return populateResult(returnResult, new Exception(exceptionValue)); } JsonNode jsonNode1; JsonNode jsonNode2; ObjectMapper mapper = new ObjectMapper(); try { jsonNode1 = mapper.readTree(array1); } catch (IOException exception) { final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY1_MESSAGE + array1; return populateResult(returnResult, value, exception); } try { jsonNode2 = mapper.readTree(array2); } catch (IOException exception) { final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY2_MESSAGE + array2; return populateResult(returnResult, value, exception); } final String result; if (jsonNode1 instanceof ArrayNode && jsonNode2 instanceof ArrayNode) { final ArrayNode asJsonArray1 = (ArrayNode) jsonNode1; final ArrayNode asJsonArray2 = (ArrayNode) jsonNode2; final ArrayNode asJsonArrayResult = new ArrayNode(mapper.getNodeFactory()); asJsonArrayResult.addAll(asJsonArray1); asJsonArrayResult.addAll(asJsonArray2); result = asJsonArrayResult.toString(); } else { result = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE + array1 + ARRAY2_MESSAGE + array2; return populateResult(returnResult, new Exception(result)); } return populateResult(returnResult, result, null); }
From source file:br.unicamp.cst.trafficUnjammer.experiments.communication.JsonHandler.java
/** * * @param typerefence/* w w w . j a v a 2s . c o m*/ * @param objectNodeBase * @param jsonData * @return */ public <T> ArrayList<Object> fromJsonDataToListOfObject(TypeReference<T> typerefence, String jsonData) { ObjectMapper mapper = new ObjectMapper(); ArrayList<Object> parsed = null; try { JsonNode node = mapper.readTree(jsonData); parsed = mapper.readValue(node.traverse(), typerefence); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return parsed; }
From source file:eu.cloudwave.wp5.feedbackhandler.metricsources.NewRelicClient.java
/** * {@inheritDoc}/* w ww. j av a2s . c o m*/ */ @Override protected void handleHttpServerException(final HttpStatusCodeException serverError) throws MetricSourceClientException, IOException { // if the status code is 401 UNAUTHORIZED -> the API key is not valid if (serverError.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) { throw new MetricSourceClientException(ErrorType.NEW_RELIC__INVALID_API_KEY, Messages.ERRORS__NEW_RELIC__INVALID_API_KEY); } final ObjectMapper mapper = new ObjectMapper(); final JsonNode errorNode = mapper.readTree(serverError.getResponseBodyAsString()); final JsonNode titleNode = errorNode.findValue(JSON__TITLE); if (titleNode != null) { final String message = titleNode.asText(); ErrorType type = ErrorType.NEW_RELIC__GENERAL; if (message.contains(ERROR__INVALID_APPLICATION_ID) || message.equals(ERROR__INVALID_PARAMETER_APPLICATION_ID)) { type = ErrorType.NEW_RELIC__INVALID_APPLICATION_ID; } else if (message.contains(ERROR__UNKNOWN_METRIC)) { type = ErrorType.UNKNOWN_METRIC; } else if (message.contains(ERROR__INVALID_PARAMETER)) { type = ErrorType.INVALID_PARAMETER; } throw new MetricSourceClientException(type, message); } }
From source file:org.mayocat.accounts.passwords.zxcvbn.ZxcvbnPasswordMeter.java
public PasswordStrength getStrength(String password) { if (!hasInitialized) { this.initialize(); }/*from w w w .ja va2 s.c om*/ Context context = Context.enter(); Scriptable scope = context.newObject(global); scope.setParentScope(global); StringWriter stringWriter = new StringWriter(); scope.put("writer", scope, stringWriter); scope.put("password", scope, password); String inputsAsArrayString = '[' + Joiner.on(",").join(FluentIterable.from(inputs).transform(new Function<String, String>() { public String apply(String input) { return "'" + input + "'"; } })) + ']'; context.evaluateString(scope, "var dump = function(o) { return JSON.stringify(o) };", "dump.js", 1, null); context.evaluateString(scope, "var result = zxcvbn(password, " + inputsAsArrayString + ");" + "writer.write(JSON.stringify(result))", "eval-zxcvbn.js", 1, null); ObjectMapper mapper = new ObjectMapper(); final JsonNode node; try { node = mapper.readTree(stringWriter.toString()); PasswordStrength result = mapper.readValue(new TreeTraversingParser(node), PasswordStrength.class); return result; } catch (IOException e) { throw new RuntimeException("Failed to check password strength", e); } }
From source file:com.seyren.core.util.velocity.VelocityHttpHelperTest.java
@Test public void bodyContainsRightSortsOfThings() throws IOException { Check check = new Check().withId("123").withEnabled(true).withName("test-check") .withDescription("Some great description").withWarn(new BigDecimal("2.0")) .withError(new BigDecimal("3.0")).withState(AlertType.ERROR).withPriority(PriorityType.TRIVIAL) .withTarget("the.test-target"); Subscription subscription = new Subscription().withEnabled(true).withType(SubscriptionType.HTTP) .withTarget("some@email.com"); Alert alert = new Alert().withTarget("some.value").withValue(new BigDecimal("4.0")) .withError(new BigDecimal("2.0")).withWarn(new BigDecimal("1.0")).withTimestamp(new DateTime()) .withFromType(AlertType.OK).withToType(AlertType.ERROR); Alert alert2 = new Alert().withTarget("some.value").withValue(new BigDecimal("4.0")) .withError(new BigDecimal("2.0")).withWarn(new BigDecimal("1.0")).withTimestamp(new DateTime()) .withFromType(AlertType.OK).withToType(AlertType.ERROR); List<Alert> alerts = Arrays.asList(alert, alert2); String body = httpHelper.createHttpContent(check, subscription, alerts); ObjectMapper mapper = new ObjectMapper(); assertThat(body, notNullValue());// ww w .j av a2 s .c o m JsonNode node = mapper.readTree(body); assertThat(node, hasJsonPath("$.seyrenUrl", is("http://localhost:8080/seyren"))); assertThat(node, hasJsonPath("$.check.name", is("test-check"))); assertThat(node, hasJsonPath("$.check.state", is("ERROR"))); assertThat(node, hasJsonPath("$.alerts", hasSize(2))); assertThat(node, hasJsonPath("$.alerts[0].target", is(alert.getTarget()))); assertThat(node, hasJsonPath("$.alerts[0].value", is(4.0))); assertThat(node, hasJsonPath("$.alerts[0].warn", is(1.0))); assertThat(node, hasJsonPath("$.alerts[0].error", is(2.0))); assertThat(node, hasJsonPath("$.alerts[0].fromType", is("OK"))); assertThat(node, hasJsonPath("$.alerts[0].toType", is("ERROR"))); assertThat(node, hasJsonPath("$.alerts[1].target", is(alert2.getTarget()))); assertThat(node, hasJsonPath("$.alerts[1].value", is(4.0))); assertThat(node, hasJsonPath("$.alerts[1].warn", is(1.0))); assertThat(node, hasJsonPath("$.alerts[1].error", is(2.0))); assertThat(node, hasJsonPath("$.alerts[1].fromType", is("OK"))); assertThat(node, hasJsonPath("$.alerts[1].toType", is("ERROR"))); assertThat(node, hasJsonPath("$.preview", Matchers.startsWith("<br />"))); assertThat(node, hasJsonPath("$.preview", containsString(check.getTarget()))); }
From source file:com.mapr.synth.samplers.FileSampler.java
private void readJsonData(InputSupplier<? extends InputStream> input) throws IOException { ObjectMapper om = new ObjectMapper(); try (InputStream in = input.getInput()) { data = om.readTree(in); }/*ww w . j av a 2 s. c o m*/ }