Java Code Examples for com.fasterxml.jackson.databind.JsonNode

The following are top voted examples for showing how to use com.fasterxml.jackson.databind.JsonNode. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: beaker-notebook-archive   File: GraphicsSerializerTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 2
Project: CS6310O01   File: Records.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 3
Project: aem-orchestrator   File: CredentialsExtractorTest.java   View source code 6 votes vote down vote up
@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()));
}
 
Example 4
Project: sunbird-lms-service   File: PageControllerTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 5
Project: Equella   File: MyResourcesApiTest.java   View source code 6 votes vote down vote up
@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);
	}
}
 
Example 6
Project: athena   File: OvsdbJsonRpcHandler.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 7
Project: athena   File: RouterWebResource.java   View source code 6 votes vote down vote up
@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();
    }
}
 
Example 8
Project: openapi-parser   File: OverlayValidator.java   View source code 6 votes vote down vote up
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));
	}
}
 
Example 9
Project: sunbird-lms-service   File: CourseBatchController.java   View source code 6 votes vote down vote up
/**
 * 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()));
  }
}
 
Example 10
Project: athena   File: PortPairGroupWebResource.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 11
Project: GitHub   File: PropertiesIT.java   View source code 6 votes vote down vote up
@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));
}
 
Example 12
Project: karate   File: SchemaUtils.java   View source code 6 votes vote down vote up
public static boolean isValid(String json, String schema) throws Exception {
    JsonNode schemaNode = JsonLoader.fromString(schema);       
    JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
    JsonSchema jsonSchema = factory.getJsonSchema(schemaNode); 
    JsonNode jsonNode = JsonLoader.fromString(json);
    ProcessingReport report = jsonSchema.validate(jsonNode);
    logger.debug("report: {}", report);
    return report.isSuccess();
}
 
Example 13
Project: GitHub   File: EnumRule.java   View source code 6 votes vote down vote up
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());
        }
    }
}
 
Example 14
Project: commercetools-sync-java   File: CustomUpdateActionUtilsTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 15
Project: wayf-cloud   File: HttpTestUtil.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 16
Project: exam   File: AssessmentSenderActor.java   View source code 6 votes vote down vote up
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);
}
 
Example 17
Project: dataplatform-schema-lib   File: JacksonArrayFormatter.java   View source code 6 votes vote down vote up
@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;
}
 
Example 18
Project: sunbird-lms-service   File: PageController.java   View source code 6 votes vote down vote up
/**
 * 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()));
  }
}
 
Example 19
Project: wherehowsX   File: CfgDao.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 20
Project: CS6310O01   File: Allocations.java   View source code 6 votes vote down vote up
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"); 
    }
}
 
Example 21
Project: GitHub   File: MinLengthMaxLengthRule.java   View source code 6 votes vote down vote up
@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;
}
 
Example 22
Project: iotplatform   File: DataValidator.java   View source code 6 votes vote down vote up
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 + "'!");
        }
    }
}
 
Example 23
Project: CS6310O01   File: Instructors.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 24
Project: document-management-store-app   File: AuditTest.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 25
Project: devops-cstack   File: ScriptingController.java   View source code 6 votes vote down vote up
@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);
	}
}
 
Example 26
Project: sunbird-lms-service   File: OrganisationControllerTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 27
Project: streamdataio-spring-webflux   File: StreamdataioSpringWebfluxApplication.java   View source code 5 votes vote down vote up
@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;
                    }
                });
}
 
Example 28
Project: pac4j-plus   File: GenericOAuth20Client.java   View source code 5 votes vote down vote up
@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;
}
 
Example 29
Project: beaker-notebook-archive   File: CategoryStemsSerializerTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 30
Project: crnk-framework   File: BaseMetaPartition.java   View source code 5 votes vote down vote up
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);
}
 
Example 31
Project: wherehowsX   File: SchemaHistory.java   View source code 5 votes vote down vote up
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;
}
 
Example 32
Project: swaggy-jenkins   File: RemoteAccessApiController.java   View source code 5 votes vote down vote up
@ApiAction
public Result getView(String name) throws Exception {
    ListView obj = imp.getView(name);
    obj.validate();
    JsonNode result = mapper.valueToTree(obj);
    return ok(result);
    
    
}
 
Example 33
Project: async-jackson   File: AsyncJsonParser.java   View source code 5 votes vote down vote up
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();
}
 
Example 34
Project: ibm-cos-sdk-java   File: JsonErrorResponseHandlerTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 35
Project: aws-sdk-java-v2   File: JsonContent.java   View source code 5 votes vote down vote up
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();
    }
}
 
Example 36
Project: beaker-notebook-archive   File: TableDisplaySerializerTest.java   View source code 5 votes vote down vote up
@Test
public void serializeTableDisplay_resultJsonHasType() throws IOException{
  //when
  JsonNode actualObj = serializeTableDisplay();
  //then
  Assertions.assertThat(actualObj.get("type").asText()).isEqualTo("TableDisplay");
}
 
Example 37
Project: centraldogma   File: CommitMessageDtoDeserializer.java   View source code 5 votes vote down vote up
@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);
}
 
Example 38
Project: hibernate-types   File: JsonBinarySqlTypeDescriptor.java   View source code 5 votes vote down vote up
@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());
        }
    };
}
 
Example 39
Project: athena   File: NodeSelection.java   View source code 5 votes vote down vote up
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;
}
 
Example 40
Project: spring-cloud-sockets   File: DispatcherHandler.java   View source code 5 votes vote down vote up
private JsonNode readConnectionMetadata(String metadata){
	try {
		return mapper.readValue(metadata, JsonNode.class);
	}
	catch (IOException e) {
		throw new IllegalStateException("Could not read metadata from client");
	}
}