Java 类com.fasterxml.jackson.databind.JsonNode 实例源码

项目:beaker-notebook-archive    文件:GraphicsSerializerTest.java   
@Test
public void serializeClickActionLineGraphics_resultJsonHasClickAction() throws IOException {
  //when
  Line line = new Line();
  line.onClick(
      new GraphicsActionListener() {
        @Override
        public void execute(GraphicsActionObject actionObject) {}
      });
  graphicsSerializer.serialize(line, jgen, new DefaultSerializerProvider.Impl());
  jgen.flush();
  //then
  JsonNode actualObj = mapper.readTree(sw.toString());
  Assertions.assertThat(actualObj.has("hasClickAction")).isTrue();
  Assertions.assertThat(actualObj.get("hasClickAction").asBoolean()).isTrue();
}
项目:CS6310O01    文件:Records.java   
public static Result create() {
    // Get the form from the request
    Form<Record> form = Form.form(Record.class,Record.creation.class).bindFromRequest();
    // Validate errors
    if(form.hasErrors()) {
        return badRequest(form.errorsAsJson());
    }
    // Get the object from the form
    Record object = form.get();
    // Create the object in db
    Ebean.beginTransaction();
    try {
        Record.create(object);
        JsonNode jsonObject = object.jsonSerialization();
        Ebean.commitTransaction();
        return created(jsonObject);
    } catch (Exception e) {
        appLogger.error(Messages.get("Error creating object"), e);
        return internalServerError("Error creating object");
    } finally {
        Ebean.endTransaction();
    }
}
项目:aem-orchestrator    文件:CredentialsExtractorTest.java   
@Test
@SuppressWarnings("resource")
public void testExtractSuccess() throws Exception {
    //Read file into a string
    File sampleFile = new File(getClass().getResource("/sample-aem-credentials.json").getFile());
    String sampleFileContent = new Scanner(sampleFile).useDelimiter("\\Z").next();

    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(sampleFileContent);

    AemCredentials aemCredentials = CredentialsExtractor.extractAemCredentials(sampleFileContent);

    assertThat(aemCredentials.getOrchestratorCredentials().getUserName(), 
        equalTo(CredentialsExtractor.ORCHESTRATOR_USER));
    assertThat(aemCredentials.getOrchestratorCredentials().getPassword(), 
        equalTo(root.path(CredentialsExtractor.ORCHESTRATOR_USER).asText()));

    assertThat(aemCredentials.getReplicatorCredentials().getUserName(), 
        equalTo(CredentialsExtractor.REPLICATOR_USER));
    assertThat(aemCredentials.getReplicatorCredentials().getPassword(), 
        equalTo(root.path(CredentialsExtractor.REPLICATOR_USER).asText()));
}
项目:sunbird-lms-service    文件:PageControllerTest.java   
@Test
public void testcreatePageSection() {
  PowerMockito.mockStatic(RequestInterceptor.class);
  when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh");
  Map<String , Object> requestMap = new HashMap<>();
  Map<String , Object> innerMap = new HashMap<>();
  innerMap.put("name" , "page1");
  innerMap.put("sectionDataType" , "section01");
  requestMap.put(JsonKey.REQUEST , innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/page/section/create").method("POST");
  req.headers(headerMap);
  Result result = route(req);
  assertEquals(200, result.status());
}
项目:Equella    文件:MyResourcesApiTest.java   
@Test
public void listSearchTypes() throws Exception
{
    JsonNode results = getEntity(context.getBaseUrl() + "api/search/myresources", getToken());
    List<String> subSearches = Lists.newArrayList();
    for( JsonNode result : results )
    {
        subSearches.add(result.get("id").asText());
    }

    ArrayList<String> expected = Lists.newArrayList("published", "draft", "archived", "all", "modqueue");
    for( String name : expected )
    {
        assertTrue(subSearches.contains(name), "Should contain '" + name + ", " + subSearches);
    }
}
项目:athena    文件:OvsdbJsonRpcHandler.java   
/**
 * Processes an JsonNode message received on the channel.
 *
 * @param jsonNode The OvsdbJsonRpcHandler that received the message
 */
private void processOvsdbMessage(JsonNode jsonNode) {

    log.debug("Handle ovsdb message");

    if (jsonNode.has("result")) {

        log.debug("Handle ovsdb result");
        ovsdbProviderService.processResult(jsonNode);

    } else if (jsonNode.hasNonNull("method")) {

        log.debug("Handle ovsdb request");
        if (jsonNode.has("id")
                && !Strings.isNullOrEmpty(jsonNode.get("id").asText())) {
            ovsdbProviderService.processRequest(jsonNode);
        }

    }
    return;
}
项目:athena    文件:RouterWebResource.java   
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createRouter(final InputStream input) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode subnode = mapper.readTree(input);
        Collection<Router> routers = createOrUpdateByInputStream(subnode);

        Boolean result = nullIsNotFound((get(RouterService.class)
                .createRouters(routers)), CREATE_FAIL);
        if (!result) {
            return Response.status(CONFLICT).entity(CREATE_FAIL).build();
        }
        return Response.status(CREATED).entity(result.toString()).build();

    } catch (Exception e) {
        return Response.status(BAD_REQUEST).entity(e.getMessage()).build();
    }
}
项目:openapi-parser    文件:OverlayValidator.java   
public void validate(T object, ValidationResults results, Set<Class<? extends JsonNode>> allowedNodeTypes) {
    JsonOverlay<?> overlay = (JsonOverlay<?>) object;
    JsonNode json = overlay.toJson();
    boolean isValidJsonType = false;
    for (Class<? extends JsonNode> type : allowedNodeTypes) {
        if (type.isAssignableFrom(json.getClass())) {
            isValidJsonType = true;
            break;
        }
    }
    isValidJsonType = isValidJsonType || json.isMissingNode();
    if (!isValidJsonType) {
        results.addError(m.msg("WrongTypeJson|Property bound to incompatible JSON Node type", json.getNodeType(),
                allowedNodeTypes));
    }
}
项目:sunbird-lms-service    文件:CourseBatchController.java   
/**
 * This method will add a new batch for a particular course.
 * 
 * @return Promise<Result>
 */
public Promise<Result> createBatch() {

  try {
    JsonNode requestData = request().body().asJson();
    ProjectLogger.log("create new batch request data=" + requestData, LoggerEnum.INFO.name());
    Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class);
    RequestValidator.validateCreateBatchReq(reqObj);
    reqObj.setOperation(ActorOperations.CREATE_BATCH.getValue());
    reqObj.setRequestId(ExecutionContext.getRequestId());
    reqObj.setEnv(getEnvironment());
    HashMap<String, Object> innerMap = new HashMap<>();
    if (!ProjectUtil.isStringNullOREmpty((String) reqObj.getRequest().get(JsonKey.BATCH_ID))) {
      reqObj.getRequest().put(JsonKey.ID, reqObj.getRequest().get(JsonKey.BATCH_ID));
      reqObj.getRequest().remove(JsonKey.BATCH_ID);
    }
    innerMap.put(JsonKey.BATCH, reqObj.getRequest());
    innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID));
    innerMap.put(JsonKey.HEADER, getAllRequestHeaders(request()));
    reqObj.setRequest(innerMap);
    return actorResponseHandler(getActorRef(), reqObj, timeout, null, request());
  } catch (Exception e) {
    return Promise.<Result>pure(createCommonExceptionResponse(e, request()));
  }
}
项目:athena    文件:PortPairGroupWebResource.java   
/**
 * Creates a new port pair group.
 *
 * @param stream   port pair group from JSON
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createPortPairGroup(InputStream stream) {

    try {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode jsonTree = (ObjectNode) mapper.readTree(stream);
        JsonNode port = jsonTree.get("port_pair_group");

        PortPairGroup portPairGroup = codec(PortPairGroup.class).decode((ObjectNode) port, this);
        Boolean issuccess = nullIsNotFound(get(PortPairGroupService.class).createPortPairGroup(portPairGroup),
                                           PORT_PAIR_GROUP_NOT_FOUND);
        return Response.status(OK).entity(issuccess.toString()).build();
    } catch (IOException e) {
        log.error("Exception while creating port pair group {}.", e.toString());
        throw new IllegalArgumentException(e);
    }
}
项目:GitHub    文件:PropertiesIT.java   
@Test
public void propertyNamesAreLowerCamelCase() throws Exception {
    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/propertiesAreUpperCamelCase.json", "com.example");
    Class<?> generatedType = resultsClassLoader.loadClass("com.example.UpperCase");

    Object instance = generatedType.newInstance();

    new PropertyDescriptor("property1", generatedType).getWriteMethod().invoke(instance, "1");
    new PropertyDescriptor("propertyTwo", generatedType).getWriteMethod().invoke(instance, 2);
    new PropertyDescriptor("propertyThreeWithSpace", generatedType).getWriteMethod().invoke(instance, "3");
    new PropertyDescriptor("propertyFour", generatedType).getWriteMethod().invoke(instance, "4");

    JsonNode jsonified = mapper.valueToTree(instance);

    assertNotNull(generatedType.getDeclaredField("property1"));
    assertNotNull(generatedType.getDeclaredField("propertyTwo"));
    assertNotNull(generatedType.getDeclaredField("propertyThreeWithSpace"));
    assertNotNull(generatedType.getDeclaredField("propertyFour"));

    assertThat(jsonified.has("Property1"), is(true));
    assertThat(jsonified.has("PropertyTwo"), is(true));
    assertThat(jsonified.has(" PropertyThreeWithSpace"), is(true));
    assertThat(jsonified.has("propertyFour"), is(true));
}
项目:GitHub    文件:EnumRule.java   
private void addEnumConstants(JsonNode node, JDefinedClass _enum, JsonNode customNames, JType type) {
    Collection<String> existingConstantNames = new ArrayList<String>();
    for (int i = 0; i < node.size(); i++) {
        JsonNode value = node.path(i);

        if (!value.isNull()) {
            String constantName = getConstantName(value.asText(), customNames.path(i).asText());
            constantName = makeUnique(constantName, existingConstantNames);
            existingConstantNames.add(constantName);

            JEnumConstant constant = _enum.enumConstant(constantName);
            constant.arg(DefaultRule.getDefaultValue(type, value));
            ruleFactory.getAnnotator().enumConstant(constant, value.asText());
        }
    }
}
项目:commercetools-sync-java    文件:CustomUpdateActionUtilsTest.java   
@Test
public void buildSetCustomFieldsUpdateActions_WithDifferentOrderOfCustomFieldValues_ShouldNotBuildUpdateActions() {
    final Map<String, JsonNode> oldCustomFields = new HashMap<>();
    oldCustomFields.put("backgroundColor",
        JsonNodeFactory.instance.objectNode().put("de", "rot").put("es", "rojo"));

    final Map<String, JsonNode> newCustomFields = new HashMap<>();
    newCustomFields.put("backgroundColor",
        JsonNodeFactory.instance.objectNode().put("es", "rojo").put("de", "rot"));

    final List<UpdateAction<Category>> setCustomFieldsUpdateActions =
        buildSetCustomFieldsUpdateActions(oldCustomFields, newCustomFields, mock(Category.class),
            CATEGORY_SYNC_OPTIONS);

    assertThat(setCustomFieldsUpdateActions).isNotNull();
    assertThat(setCustomFieldsUpdateActions).isEmpty();
}
项目:wayf-cloud    文件:HttpTestUtil.java   
public static void assertJsonEquals(String expected, String actual, String... blacklistedFields) {
    LOG.debug("Comparing expected [{}] to actual [{}]", expected, actual);
    DocumentContext expectedDocument = JsonPath.parse(expected);
    DocumentContext actualDocument = JsonPath.parse(actual);

    if (blacklistedFields != null) {
        removeFields(expectedDocument, blacklistedFields);
        removeFields(actualDocument, blacklistedFields);
    }

    try {
        ObjectMapper mapper = new ObjectMapper();

        JsonNode expectedNode = mapper.readTree(expectedDocument.jsonString());
        JsonNode actualNode = mapper.readTree(actualDocument.jsonString());

        assertEquals(expectedNode, actualNode);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:exam    文件:AssessmentSenderActor.java   
private void send(ExamEnrolment enrolment) throws IOException {
    String ref = enrolment.getReservation().getExternalRef();
    Logger.debug("Sending back assessment for reservation " + ref);
    URL url = parseUrl(ref);
    WSRequest request = wsClient.url(url.toString());
    ExternalExam ee = enrolment.getExternalExam();
    Function<WSResponse, Void> onSuccess = response -> {
        if (response.getStatus() != 201) {
            Logger.error("Failed in sending assessment for reservation " + ref);
        } else {
            ee.setSent(DateTime.now());
            ee.update();
            Logger.info("Assessment for reservation " + ref + " processed successfully");
        }
        return null;
    };
    String json = Ebean.json().toJson(ee, PathProperties.parse("(*, creator(id))"));
    ObjectMapper om = new ObjectMapper();
    JsonNode node = om.readTree(json);
    request.post(node).thenApplyAsync(onSuccess);
}
项目:dataplatform-schema-lib    文件:JacksonArrayFormatter.java   
@Override
public JsonNode write( final Object obj ) throws IOException{
  ArrayNode array = new ArrayNode( JsonNodeFactory.instance );
  if( ! ( obj instanceof List ) ){
    return array;
  }

  List<Object> listObj = (List)obj;
  for( Object childObj : listObj ){
    if( childObj instanceof List ){
      array.add( JacksonContainerToJsonObject.getFromList( (List<Object>)childObj ) );
    }
    else if( childObj instanceof Map ){
      array.add( JacksonContainerToJsonObject.getFromMap( (Map<Object,Object>)childObj ) );
    }
    else{
      array.add( ObjectToJsonNode.get( childObj ) );
    }
  }

  return array;
}
项目:sunbird-lms-service    文件:PageController.java   
/**
 * This method will allow admin to create sections for page view
 * 
 * @return Promise<Result>
 */
public Promise<Result> createPageSection() {

  try {
    JsonNode requestData = request().body().asJson();
    ProjectLogger.log("getting create page section data request=" + requestData,
        LoggerEnum.INFO.name());
    Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class);
    RequestValidator.validateCreateSection(reqObj);
    reqObj.setOperation(ActorOperations.CREATE_SECTION.getValue());
    reqObj.setRequestId(ExecutionContext.getRequestId());
    reqObj.getRequest().put(JsonKey.CREATED_BY, ctx().flash().get(JsonKey.USER_ID));
    reqObj.setEnv(getEnvironment());
    HashMap<String, Object> map = new HashMap<>();
    map.put(JsonKey.SECTION, reqObj.getRequest());
    reqObj.setRequest(map);
    return actorResponseHandler(getActorRef(), reqObj, timeout, null, request());
  } catch (Exception e) {
    return Promise.<Result>pure(createCommonExceptionResponse(e, request()));
  }
}
项目:wherehowsX    文件:CfgDao.java   
public static void insertOrUpdateApp(JsonNode app, boolean isInsert) throws Exception {
  Map<String, Object> params = new HashMap<>();
  params.put("appId", JsonUtil.getJsonValue(app, "app_id", Integer.class));
  params.put("appCode", JsonUtil.getJsonValue(app, "app_code", String.class, null));
  params.put("description", JsonUtil.getJsonValue(app, "description", String.class, null));
  params.put("uri", JsonUtil.getJsonValue(app, "uri", String.class, null));
  params.put("shortConnectionString", JsonUtil.getJsonValue(app, "short_connection_string", String.class));
  params.put("techMatrixId", JsonUtil.getJsonValue(app, "techMatrixId", Integer.class, null));
  params.put("parentAppId", JsonUtil.getJsonValue(app, "parent_app_id", Integer.class, null));
  params.put("appStatus", JsonUtil.getJsonValue(app, "app_status", String.class, null));
  params.put("isLogical", ((boolean) JsonUtil.getJsonValue(app, "is_logical", Boolean.class, false) ? "Y" : "N"));

  if (isInsert) {
    JdbcUtil.wherehowsNamedJdbcTemplate.update(INSERT_NEW_APP, params);
  } else {
    JdbcUtil.wherehowsNamedJdbcTemplate.update(UPDATE_APP, params);
  }
}
项目:CS6310O01    文件:Allocations.java   
public static Result list() {  
    try {
        List<Allocation> objects = Allocation.getList();
        JsonNode jsonObjects = Allocation.jsonListSerialization(objects);
        if (jsonObjects.isArray()) {
            int i = 0;
            for (JsonNode object : jsonObjects) {
                ((ObjectNode)object).put("courseSession",objects.get(i).getCourseSession().jsonSerialization());
                i++;
            }
        }
        return ok(jsonObjects);
    }catch(Exception e) {
        appLogger.error("Error listing objects",e);
        return internalServerError("Error listing objects"); 
    }
}
项目:GitHub    文件:MinLengthMaxLengthRule.java   
@Override
public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) {

    if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()
            && (node.has("minLength") || node.has("maxLength"))) {

        JAnnotationUse annotation = field.annotate(Size.class);

        if (node.has("minLength")) {
            annotation.param("min", node.get("minLength").asInt());
        }

        if (node.has("maxLength")) {
            annotation.param("max", node.get("maxLength").asInt());
        }
    }

    return field;
}
项目:iotplatform    文件:DataValidator.java   
protected static void validateJsonStructure(JsonNode expectedNode, JsonNode actualNode) {
    Set<String> expectedFields = new HashSet<>();        
    Iterator<String> fieldsIterator = expectedNode.fieldNames();
    while (fieldsIterator.hasNext()) {
        expectedFields.add(fieldsIterator.next());
    }

    Set<String> actualFields = new HashSet<>();        
    fieldsIterator = actualNode.fieldNames();
    while (fieldsIterator.hasNext()) {
        actualFields.add(fieldsIterator.next());
    }

    if (!expectedFields.containsAll(actualFields) || !actualFields.containsAll(expectedFields)) {
        throw new DataValidationException("Provided json structure is different from stored one '" + actualNode + "'!");
    }

    for (String field : actualFields) {
        if (!actualNode.get(field).isTextual()) {
            throw new DataValidationException("Provided json structure can't contain non-text values '" + actualNode + "'!");
        }
    }
}
项目:CS6310O01    文件:Instructors.java   
public static Result create() {
    // Get the form from the request
    Form<Instructor> form = Form.form(Instructor.class,Instructor.creation.class).bindFromRequest();
    // Validate errors
    if(form.hasErrors()) {
        return badRequest(form.errorsAsJson());
    }
    // Get the object from the form
    Instructor object = form.get();
    // Create the object in db
    Ebean.beginTransaction();
    try {
        Instructor.create(object);
        JsonNode jsonObject = object.jsonSerialization();
        Ebean.commitTransaction();
        return created(jsonObject);
    } catch (Exception e) {
        appLogger.error(Messages.get("Error creating object"), e);
        return internalServerError("Error creating object");
    } finally {
        Ebean.endTransaction();
    }
}
项目:document-management-store-app    文件:AuditTest.java   
@Test
public void should_audit_retrieval() throws Exception {
    final String url = uploadFileAndReturnSelfUrl();

    mvc.perform(get(url)
            .headers(headers));

    final MvcResult auditResponse = mvc.perform(get(url + "/auditEntries")
            .headers(headers))
            .andExpect(status().isOk())
            .andReturn();

    final JsonNode auditEntries = getAuditEntriesFromResponse(auditResponse);

    assertThat(auditEntries.size(), is(3));
    assertThat(auditEntries.get(2).get("action").asText(), equalTo("READ"));
}
项目:devops-cstack    文件:ScriptingController.java   
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public @ResponseBody JsonNode scriptingLoad(@PathVariable @RequestBody Integer id)
        throws ServiceException, JsonProcessingException {
    logger.info("Load");
    User user = authentificationUtils.getAuthentificatedUser();
    try {
        Script script = scriptingService.load(id);
        User user1 = userService.findById(script.getCreationUserId());
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.createObjectNode();
        ((ObjectNode) rootNode).put("id", script.getId());
        ((ObjectNode) rootNode).put("title", script.getTitle());
        ((ObjectNode) rootNode).put("content", script.getContent());
        ((ObjectNode) rootNode).put("creation_date", script.getCreationDate().toString());
        ((ObjectNode) rootNode).put("creation_user", user1.getFirstName() + " " + user1.getLastName());

        return rootNode;
    } finally {
        authentificationUtils.allowUser(user);
    }
}
项目:sunbird-lms-service    文件:OrganisationControllerTest.java   
@Test
public void testsearchOrgs() {
  PowerMockito.mockStatic(RequestInterceptor.class);
  when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh");
  Map<String , Object> requestMap = new HashMap<>();
  Map<String , Object> innerMap = new HashMap<>();
  innerMap.put(JsonKey.ORGANISATION_ID , "org123");
  innerMap.put(JsonKey.STATUS, new BigInteger("1"));
  requestMap.put(JsonKey.REQUEST , innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/search").method("POST");
  req.headers(headerMap);
  Result result = route(req);
  assertEquals(200, result.status());
}
项目:streamdataio-spring-webflux    文件:StreamdataioSpringWebfluxApplication.java   
@Override
public Flux<JsonNode> apply(final Flux<ServerSentEvent<JsonNode>> aFlux) {
    return aFlux.filter(evt -> evt.data().isPresent())
                .filter(evt -> evt.event()
                                  .map(evtType -> "data".equals(evtType)
                                      || "patch".equals(evtType)
                                      || "error".equals(evtType))
                                  .orElse(FALSE))
                .map(new Function<ServerSentEvent<JsonNode>, JsonNode>() {
                    private JsonNode current;

                    @Override
                    public JsonNode apply(final ServerSentEvent<JsonNode> aEvent) {
                        String type = aEvent.event().get();

                        switch (type) {
                            case "data":
                                current = aEvent.data().get();
                                break;

                            case "patch":
                               // current = JsonPatch.apply(aEvent.data().get(), current);
                                current = aEvent.data().get();
                                break;

                            case "error":
                                aEvent.data()
                                      .ifPresent(data -> {
                                          throw new RuntimeException("received an error! " + data);
                                      });
                                break;

                            default:
                                throw new IllegalArgumentException("Unknown type: " + type);
                        }

                        return current;
                    }
                });
}
项目:pac4j-plus    文件:GenericOAuth20Client.java   
@Override
protected GenericOAuth20Profile extractUserProfile(String body) {
    final GenericOAuth20Profile profile = new GenericOAuth20Profile();
    if (attributesDefinition != null) {
        profile.setAttributesDefinition(attributesDefinition);
    }
    final JsonNode json = JsonHelper.getFirstNode(body);
    if (json != null) {
        profile.setId(JsonHelper.getElement(json, "id"));
        for (final String attribute : profile.getAttributesDefinition().getPrimaryAttributes()) {
            profile.addAttribute(attribute, JsonHelper.getElement(json, attribute));
        }
    }
    return profile;
}
项目:beaker-notebook-archive    文件:CategoryStemsSerializerTest.java   
@Test
public void serializeWidthCategoryStems_resultJsonHasWidth() throws IOException {
  //when
  CategoryStems categoryStems = new CategoryStems();
  categoryStems.setWidth(11f);
  categoryStemsSerializer.serialize(categoryStems, jgen, new DefaultSerializerProvider.Impl());
  jgen.flush();
  //then
  JsonNode actualObj = mapper.readTree(sw.toString());
  Assertions.assertThat(actualObj.has("width")).isTrue();
  Assertions.assertThat(actualObj.get("width").asInt()).isEqualTo(11);
}
项目:crnk-framework    文件:BaseMetaPartition.java   
private static String firstToLower(String name) {
    if (name.equals(JsonNode.class.getSimpleName())) {
        return "json";
    }
    if (name.equals(ObjectNode.class.getSimpleName())) {
        return "json.object";
    }
    if (name.equals(ArrayNode.class.getSimpleName())) {
        return "json.array";
    }
    if (name.equals("UUID")) {
        return "uuid";
    }
    return Character.toLowerCase(name.charAt(0)) + name.substring(1);
}
项目:wherehowsX    文件:SchemaHistory.java   
public static int calculateList(JsonNode node) {
    int count = 0;
    Iterator<JsonNode> arrayIterator = node.elements();
    while (arrayIterator.hasNext()) {
        JsonNode element = arrayIterator.next();
        if (element.isArray()) {
            count += calculateList(element);
        } else if (element.isContainerNode()) {
            count += calculateDict(element);
        }
    }
    return count;
}
项目:swaggy-jenkins    文件:RemoteAccessApiController.java   
@ApiAction
public Result getView(String name) throws Exception {
    ListView obj = imp.getView(name);
    obj.validate();
    JsonNode result = mapper.valueToTree(obj);
    return ok(result);


}
项目:async-jackson    文件:AsyncJsonParser.java   
private JsonNode createArray(JsonNode current) {
    if (ObjectNode.class.isInstance(current))
        return ObjectNode.class.cast(current).putArray(fieldName);
    else if (ArrayNode.class.isInstance(current))
        return ArrayNode.class.cast(current).addArray();
    else
        return JsonNodeFactory.instance.arrayNode();
}
项目:ibm-cos-sdk-java    文件:JsonErrorResponseHandlerTest.java   
@Test
public void handle_UnmarshallerReturnsException_WithRequestId() throws Exception {
    httpResponse.setStatusCode(500);
    httpResponse.addHeader(HttpResponseHandler.X_AMZN_REQUEST_ID_HEADER, "1234");
    expectUnmarshallerMatches();
    when(unmarshaller.unmarshall((JsonNode) anyObject()))
            .thenReturn(new CustomException("error"));

    AmazonServiceException ase = responseHandler.handle(httpResponse);

    assertEquals("1234", ase.getRequestId());
}
项目:aws-sdk-java-v2    文件:JsonContent.java   
private static JsonNode parseJsonContent(byte[] rawJsonContent, ObjectMapper mapper) {
    if (rawJsonContent == null || rawJsonContent.length == 0) {
        // Note: behavior of mapper.readTree changed in 2.9 so we need to explicitly
        // check for an empty input and return an empty object or else the return
        // value will be null:
        // https://github.com/FasterXML/jackson-databind/issues/1406
        return mapper.createObjectNode();
    }
    try {
        return mapper.readTree(rawJsonContent);
    } catch (Exception e) {
        LOG.info("Unable to parse HTTP response content", e);
        return mapper.createObjectNode();
    }
}
项目:beaker-notebook-archive    文件:TableDisplaySerializerTest.java   
@Test
public void serializeTableDisplay_resultJsonHasType() throws IOException{
  //when
  JsonNode actualObj = serializeTableDisplay();
  //then
  Assertions.assertThat(actualObj.get("type").asText()).isEqualTo("TableDisplay");
}
项目:centraldogma    文件:CommitMessageDtoDeserializer.java   
@Override
public CommitMessageDto deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    final JsonNode jsonNode = p.readValueAsTree();
    final JsonNode summary = jsonNode.get("summary");
    if (summary == null || summary.textValue() == null) {
        ctxt.reportInputMismatch(CommitMessageDto.class, "commit message should have a summary.");
        // should never reach here
        throw new Error();
    }

    final String detail = jsonNode.get("detail") == null ? "" : jsonNode.get("detail").textValue();
    final JsonNode markupNode = jsonNode.get("markup");
    final Markup markup = Markup.parse(markupNode == null ? "unknown" : markupNode.textValue());
    return new CommitMessageDto(summary.textValue(), detail, markup);
}
项目:hibernate-types    文件:JsonBinarySqlTypeDescriptor.java   
@Override
public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
    return new BasicBinder<X>(javaTypeDescriptor, this) {
        @Override
        protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
            st.setObject(index, javaTypeDescriptor.unwrap(value, JsonNode.class, options), getSqlType());
        }
    };
}
项目:athena    文件:NodeSelection.java   
private Set<String> extractIds(ObjectNode payload) {
    ArrayNode array = (ArrayNode) payload.path(IDS);
    if (array == null || array.size() == 0) {
        return Collections.emptySet();
    }

    Set<String> ids = new HashSet<>();
    for (JsonNode node : array) {
        ids.add(node.asText());
    }
    return ids;
}
项目:spring-cloud-sockets    文件:DispatcherHandler.java   
private JsonNode readConnectionMetadata(String metadata){
    try {
        return mapper.readValue(metadata, JsonNode.class);
    }
    catch (IOException e) {
        throw new IllegalStateException("Could not read metadata from client");
    }
}
项目:bigchaindb-java-driver    文件:SignedBigchaindbTransactionImpl.java   
private ObjectNode requireObjectField(final JsonNode node, final String fieldName) {
    JsonNode value = requireField(node, fieldName);
    if (value.isObject()) {
        return (ObjectNode)value;
    }
    throw new RuntimeException("Value of JSON key/field \"" + fieldName + "\" is required to be an object.");
}