Example usage for com.fasterxml.jackson.databind ObjectMapper createObjectNode

List of usage examples for com.fasterxml.jackson.databind ObjectMapper createObjectNode

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper createObjectNode.

Prototype

@Override
public ObjectNode createObjectNode() 

Source Link

Document

Note: return type is co-variant, as basic ObjectCodec abstraction can not refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)

Usage

From source file:com.clicktravel.cheddar.event.EventMessageHandlerTest.java

@Test
public void shouldRegsisterAndInvokeAllMultipleHandlers_withMessageAndHandleException() throws Exception {
    // Given/*  ww  w.  j a va2s  . c  om*/
    final String testValue = Randoms.randomString(5);
    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode rootNode = mapper.createObjectNode();
    rootNode.put("testValue", testValue);
    final String serializedEvent = mapper.writeValueAsString(rootNode);

    final TypedMessage message = mock(TypedMessage.class);
    final String eventType = Randoms.randomString(5);
    when(message.getType()).thenReturn(eventType);
    when(message.getPayload()).thenReturn(serializedEvent);

    final TestConcreteEventHandler mockDomainEventHandler1 = mock(TestConcreteEventHandler.class);
    final TestConcreteEventHandler concreteDomainEventHandler = new TestConcreteEventHandler();
    doReturn(concreteDomainEventHandler.getEventClass()).when(mockDomainEventHandler1).getEventClass();

    final TestOtherConcreteEventHandler mockDomainEventHandler2 = mock(TestOtherConcreteEventHandler.class);
    final TestOtherConcreteEventHandler concreteOtherDomainEventHandler = new TestOtherConcreteEventHandler();
    doReturn(concreteOtherDomainEventHandler.getEventClass()).when(mockDomainEventHandler2).getEventClass();
    doThrow(IllegalStateException.class).when(mockDomainEventHandler2).handle(any(Event.class));

    final EventMessageHandler<Event> eventMessageHandler = new EventMessageHandler<>();
    eventMessageHandler.registerEventHandler(eventType, mockDomainEventHandler1);
    eventMessageHandler.registerEventHandler(eventType, mockDomainEventHandler2);

    // When
    eventMessageHandler.handle(message);

    // Then
    verify(mockDomainEventHandler1).handle(any(TestConcreteEvent.class));
}

From source file:com.gsma.mobileconnect.cache.DiscoveryCacheValueTest.java

@Test
public void hasExpired_whenExpired_shouldReturnTrue() {
    // GIVEN/*  w  ww  . j  a va 2s .c  om*/
    ObjectMapper objectMapper = new ObjectMapper();
    DiscoveryCacheValue value = new DiscoveryCacheValue(new Date(new Date().getTime() - 1),
            objectMapper.createObjectNode());

    // WHEN
    boolean hasExpired = value.hasExpired();

    // THEN
    assertTrue(hasExpired);
}

From source file:org.onosproject.cli.net.AddFlowsCommand.java

private Object json(ObjectMapper mapper, boolean isSuccess, ArrayList<Long> elapsed) {
    ObjectNode result = mapper.createObjectNode();
    result.put("Success", isSuccess);
    ArrayNode node = result.putArray("elapsed-time");
    for (Long v : elapsed) {
        node.add(v);/*from   w ww  . ja  v a 2s. c om*/
    }
    return result;
}

From source file:com.gsma.mobileconnect.cache.DiscoveryCacheValueTest.java

@Test
public void hasExpired_whenNotExpired_shouldReturnFalse() {
    // GIVEN//from w w w  .j  a va2  s.c  om
    ObjectMapper objectMapper = new ObjectMapper();
    DiscoveryCacheValue value = new DiscoveryCacheValue(new Date(new Date().getTime() + 60),
            objectMapper.createObjectNode());

    // WHEN
    boolean hasExpired = value.hasExpired();

    // THEN
    assertFalse(hasExpired);
}

From source file:com.ikanow.aleph2.analytics.hadoop.services.BeStreamParser.java

@Override
public Tuple2<Long, IBatchRecord> getNextRecord(long currentFileIndex, String fileName, InputStream inStream) {
    logger.debug("StreamParser.getNextRecord");

    ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());
    Tuple2<Long, IBatchRecord> t2 = null;
    try {//  www  .ja  v  a  2 s .c om
        JsonNode node = mapper.createObjectNode();
        ((ObjectNode) node).put("fileName", fileName);
        // create output stream
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        int readedBytes;
        byte[] buf = new byte[1024];
        while ((readedBytes = inStream.read(buf)) > 0) {
            outStream.write(buf, 0, readedBytes);
        }
        outStream.close();
        t2 = new Tuple2<Long, IBatchRecord>(currentFileIndex,
                new BatchRecordUtils.BatchRecord(node, outStream));
    } catch (Exception e) {
        logger.error("JsonParser caught exception", e);
    }
    return t2;
}

From source file:org.workspace7.moviestore.controller.SessionsController.java

@CrossOrigin
@RequestMapping(method = RequestMethod.GET, value = "/sessions", produces = "application/json")
public @ResponseBody String sessions(HttpServletRequest request) {

    final String hostname = System.getenv().getOrDefault("HOSTNAME", "unknown");

    ObjectMapper sessions = new ObjectMapper();

    ObjectNode rootNode = sessions.createObjectNode().put("hostName", hostname);

    String jsonResponse = "{\"message\":\"NO SESSIONS AVAILABLE\"}";

    try {/*from  w w w.j  a  v a  2 s .c o m*/

        AdvancedCache<Object, Object> sessionCache = cacheManager.getCache("moviestore-sessions-cache")
                .getAdvancedCache();

        if (sessionCache != null && !sessionCache.isEmpty()) {

            ArrayNode sessionsArray = rootNode.arrayNode();

            Map<Object, Object> sessionsCacheMap = sessionCache.entrySet().stream().collect(CacheCollectors
                    .serializableCollector(() -> Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));

            sessionsCacheMap.forEach((s, o) -> {

                MapSession mapSession = (MapSession) o;

                log.debug("Session Controller Map Session Id {} value : {}", s, mapSession);

                if (log.isDebugEnabled()) {
                    StringBuilder debugMessage = new StringBuilder();

                    mapSession.getAttributeNames().forEach(key -> {
                        debugMessage.append("Attribute :" + s + " Value: " + mapSession.getAttribute(key));
                    });

                    log.debug("Map Session Attributes : {}", debugMessage);
                }

                MovieCart movieCart = mapSession.getAttribute(ShoppingCartController.SESSION_ATTR_MOVIE_CART);

                if (movieCart != null) {

                    ObjectNode movieCartNode = sessions.createObjectNode();
                    movieCartNode.put("sessionId", mapSession.getId());
                    movieCartNode.put("orderId", movieCart.getOrderId());

                    ArrayNode movieItemsNode = movieCartNode.arrayNode();

                    movieCart.getMovieItems().forEach((movieId, qty) -> {
                        ObjectNode movieItem = movieItemsNode.addObject();
                        movieItem.put("movieId", movieId);
                        movieItem.put("orderQuantity", qty);
                    });

                    movieCartNode.set("movies", movieItemsNode);

                    sessionsArray.add(movieCartNode);
                }
            });
            rootNode.set("sessions", sessionsArray);
        }
        jsonResponse = sessions.writeValueAsString(rootNode);
    } catch (Exception e) {
        log.error("Error building JSON response for sesisons", e);
    }

    return jsonResponse;
}

From source file:gov.lanl.adore.djatoka.openurl.OpenURLJP2Ping.java

/**
 * Returns the OpenURLResponse of a JSON object defining image status. Status Codes:
 *///from  ww  w  .j  ava  2  s .c om
@Override
public OpenURLResponse resolve(final ServiceType serviceType, final ContextObject contextObject,
        final OpenURLRequest openURLRequest, final OpenURLRequestProcessor processor) {
    final String responseFormat = RESPONSE_TYPE;
    int status = HttpServletResponse.SC_NOT_FOUND;
    byte[] bytes = new byte[] {};

    try {
        final String id = ((URI) contextObject.getReferent().getDescriptors()[0]).toASCIIString();
        status = ReferentManager.getResolver().getStatus(id);

        if (status != HttpServletResponse.SC_NOT_FOUND) {
            final ObjectMapper mapper = new ObjectMapper();
            final ObjectNode rootNode = mapper.createObjectNode();

            String res_status = null;

            if (status == HttpServletResponse.SC_OK) {
                res_status = STATUS_OK;
            } else if (status == HttpServletResponse.SC_ACCEPTED) {
                res_status = STATUS_ACCEPTED;
            }

            rootNode.put("identifier", id);
            rootNode.put("status", res_status);
            bytes = mapper.writeValueAsBytes(rootNode);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    final HashMap<String, String> header_map = new HashMap<String, String>();
    header_map.put("Content-Length", Integer.toString(bytes.length));
    header_map.put("Date", HttpDate.getHttpDate());
    return new OpenURLResponse(status, responseFormat, bytes, header_map);
}

From source file:org.onosproject.tvue.TopologyResource.java

private ObjectNode json(ObjectMapper mapper, int count, String src, String dst) {
    return mapper.createObjectNode().put("source", src).put("target", dst).put("value", count);
}

From source file:com.ikanow.aleph2.security.db.SessionDb.java

protected JsonNode serialize(Object session) {
    ObjectNode sessionOb = null;/*from   w  w w. jav a 2s  . com*/
    if (session instanceof Session) {
        Session s = (Session) session;
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        sessionOb = mapper.createObjectNode();
        sessionOb.put("_id", s.getId().toString());
        sessionOb.put("last_access_time", s.getLastAccessTime().getTime());
        sessionOb.put("start_time_stamp", s.getStartTimestamp().getTime());
        sessionOb.put("timeout", s.getTimeout());
        sessionOb.put("host", s.getHost());
        ObjectNode attributesOb = sessionOb.putObject("attributes");
        for (Iterator<Object> it = s.getAttributeKeys().iterator(); it.hasNext();) {
            Object key = it.next();
            Object value = s.getAttribute(key);
            if (value != null) {
                // base64 encode objects in session
                logger.debug("Storing session attribute:" + key + "=" + value);
                attributesOb.put(escapeMongoCharacters("" + key), SerializableUtils.serialize(value));
            }
        }
    }
    return sessionOb;
}

From source file:scott.barleyrs.rest.AdminService.java

/**
 * Gets the entity type as a JSON schema.<br/>
 * The schema is compatibly extended with extra barley information.
 *
 *//*from w w  w. jav  a2s  .  co m*/
@GET
@Path("/entitytypes/{namespace}/{entityType}")
@Produces(MediaType.APPLICATION_JSON)
public JsonNode getEntityTypeJsonSchema(@PathParam("namespace") String namespace,
        @PathParam("entityType") String entityTypeName, @QueryParam("options") boolean withOptions) {

    Definitions definitions = env.getDefinitions(namespace);
    EntityType entityType = definitions.getEntityTypeMatchingInterface(entityTypeName, true);

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode response = mapper.createObjectNode();

    JsonNode jsonSchema = toJsonSchema(mapper, namespace, entityType);
    response.set("schema", jsonSchema);

    ObjectNode options = mapper.createObjectNode();
    if (withOptions) {
        ObjectNode fields = mapper.createObjectNode();
        for (NodeType nodeType : entityType.getNodeTypes()) {
            ObjectNode optionsForNode = createOptionsForNode(nodeType, mapper);
            if (optionsForNode != null) {
                fields.set(nodeType.getName(), optionsForNode);
            }
        }
        options.set("fields", fields);
    }
    response.set("options", options);
    return response;
}