Example usage for com.fasterxml.jackson.databind.node ObjectNode get

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode get

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ObjectNode get.

Prototype

public JsonNode get(String paramString) 

Source Link

Usage

From source file:io.wcm.caravan.pipeline.impl.JsonPipelineImplTest.java

@Test
public void cacheMissAndStore() throws JSONException {

    CacheStrategy strategy = CacheStrategies.timeToLive(1, TimeUnit.SECONDS);

    JsonPipeline a = newPipelineWithResponseBody("{a: 123}");
    JsonPipeline cached = a.addCachePoint(strategy);

    String cacheKey = "abcdef";

    when(caching.getCacheKey(SERVICE_NAME, a.getDescriptor())).thenReturn(cacheKey);

    when(caching.get(eq(cacheKey), anyBoolean(), anyInt())).thenReturn(Observable.empty());

    String output = cached.getStringOutput().toBlocking().single();

    // get must have been called to check if the document is available in the cache
    verify(caching).get(eq(cacheKey), eq(false), eq(1));

    // put must have been called with an cache envelope version of the JSON, that contains an additional _cacheInfo
    verify(caching).put(eq(cacheKey), Matchers.argThat(new BaseMatcher<String>() {

        @Override/*from w  w w .  jav  a2  s.c  om*/
        public boolean matches(Object item) {
            ObjectNode storedNode = JacksonFunctions.stringToObjectNode(item.toString());

            return storedNode.has("metadata") && storedNode.has("content")
                    && storedNode.get("content").get("a").asInt() == 123;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("Expected storedObject to contain original value & _cacheInfo");
        }

    }), eq(1));

    // the _cacheInfo however should not be contained in the output
    JSONAssert.assertEquals("{a: 123}", output, JSONCompareMode.STRICT);
}

From source file:com.almende.eve.transport.xmpp.XmppService.java

/**
 * Store connection./*  w w w. j  av  a2  s. c  om*/
 * 
 * @param agentId
 *            the agent id
 * @param username
 *            the username
 * @param password
 *            the password
 * @param resource
 *            the resource
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws InvalidKeyException
 *             the invalid key exception
 * @throws InvalidAlgorithmParameterException
 *             the invalid algorithm parameter exception
 * @throws NoSuchAlgorithmException
 *             the no such algorithm exception
 * @throws InvalidKeySpecException
 *             the invalid key spec exception
 * @throws NoSuchPaddingException
 *             the no such padding exception
 * @throws IllegalBlockSizeException
 *             the illegal block size exception
 * @throws BadPaddingException
 *             the bad padding exception
 */
private void storeConnection(final String agentId, final String username, final String password,
        final String resource)
        throws IOException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {

    final State state = agentHost.getStateFactory().get(agentId);

    final String conns = state.get(CONNKEY, String.class);
    ArrayNode newConns;
    if (conns != null) {
        newConns = (ArrayNode) JOM.getInstance().readTree(conns);
    } else {
        newConns = JOM.createArrayNode();
    }

    final ObjectNode params = JOM.createObjectNode();
    params.put("username", EncryptionUtil.encrypt(username));
    params.put("password", EncryptionUtil.encrypt(password));
    if (resource != null && !resource.equals("")) {
        params.put("resource", EncryptionUtil.encrypt(resource));
    }
    for (final JsonNode item : newConns) {
        if (item.get("username").equals(params.get("username"))) {
            return;
        }
    }
    newConns.add(params);
    if (!state.putIfUnchanged(CONNKEY, JOM.getInstance().writeValueAsString(newConns), conns)) {
        // recursive retry
        storeConnection(agentId, username, password, resource);
    }
}

From source file:com.almende.eve.agent.google.GoogleCalendarAgent.java

/**
 * Retrieve a list with all calendars in this google calendar.
 * //from  w  ww .j  a  va2  s . c  om
 * @return the calendar list
 * @throws Exception
 *             the exception
 */
@Override
public ArrayNode getCalendarList() throws Exception {
    final String url = CALENDAR_URI + "users/me/calendarList";
    final String resp = HttpUtil.get(url, getAuthorizationHeaders());
    final ObjectNode calendars = JOM.getInstance().readValue(resp, ObjectNode.class);

    // check for errors
    if (calendars.has("error")) {
        final ObjectNode error = (ObjectNode) calendars.get("error");
        throw new JSONRPCException(error);
    }

    // get items from response
    ArrayNode items = null;
    if (calendars.has("items")) {
        items = (ArrayNode) calendars.get("items");
    } else {
        items = JOM.createArrayNode();
    }

    return items;
}

From source file:com.almende.eve.agent.google.GoogleCalendarAgent.java

/**
 * Get all events in given interval./*  w  w w  . ja v a  2s .  c  o m*/
 * 
 * @param timeMin
 *            start of the interval
 * @param timeMax
 *            end of the interval
 * @param calendarId
 *            optional calendar id. If not provided, the default calendar is
 *            used
 * @return the events
 * @throws Exception
 *             the exception
 */
@Override
public ArrayNode getEvents(@Optional @Name("timeMin") final String timeMin,
        @Optional @Name("timeMax") final String timeMax, @Optional @Name("calendarId") String calendarId)
        throws Exception {
    // initialize optional parameters
    if (calendarId == null) {
        calendarId = getState().get("email", String.class);
    }

    // built url with query parameters
    String url = CALENDAR_URI + calendarId + "/events";
    final Map<String, String> params = new HashMap<String, String>();
    if (timeMin != null) {
        params.put("timeMin", new DateTime(timeMin).toString());
    }
    if (timeMax != null) {
        params.put("timeMax", new DateTime(timeMax).toString());
    }
    // Set singleEvents=true to expand recurring events into instances
    params.put("singleEvents", "true");
    url = HttpUtil.appendQueryParams(url, params);

    // perform GET request
    final Map<String, String> headers = getAuthorizationHeaders();
    final String resp = HttpUtil.get(url, headers);
    final ObjectMapper mapper = JOM.getInstance();
    final ObjectNode json = mapper.readValue(resp, ObjectNode.class);

    // check for errors
    if (json.has("error")) {
        final ObjectNode error = (ObjectNode) json.get("error");
        throw new JSONRPCException(error);
    }

    // get items from the response
    ArrayNode items = null;
    if (json.has("items")) {
        items = (ArrayNode) json.get("items");

        // convert from Google to Eve event
        for (int i = 0; i < items.size(); i++) {
            final ObjectNode item = (ObjectNode) items.get(i);
            toEveEvent(item);
        }
    } else {
        items = JOM.createArrayNode();
    }

    return items;
}

From source file:com.msopentech.odatajclient.engine.data.json.JSONPropertyDeserializer.java

@Override
protected JSONProperty doDeserializeV4(JsonParser parser, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);
    final JSONProperty property = new JSONProperty();

    try {//from   ww  w .  ja v  a2  s.  c om
        final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document document = builder.newDocument();

        Element content = document.createElement(ODataConstants.ELEM_PROPERTY);

        JsonNode subtree = null;
        if (tree.has(ODataConstants.JSON_VALUE)) {
            if (tree.has(v4AnnotationPrefix + ODataConstants.JSON_TYPE)
                    && StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {

                content.setAttribute(ODataConstants.ATTR_M_TYPE,
                        tree.get(v4AnnotationPrefix + ODataConstants.JSON_TYPE).asText());
            }

            final JsonNode value = tree.get(ODataConstants.JSON_VALUE);
            if (value.isValueNode()) {
                content.appendChild(document.createTextNode(value.asText()));
            } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                subtree = tree.objectNode();
                ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE));
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
            } else {
                subtree = tree.get(ODataConstants.JSON_VALUE);
            }
        } else {
            subtree = tree;
        }

        if (subtree != null) {
            DOMTreeUtilsV4.buildSubtree(content, subtree);
        }

        final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE);
        if (children.size() == 1) {
            final Element value = (Element) children.iterator().next();
            if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) {
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    value.setAttribute(ODataConstants.ATTR_M_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
                content = value;
            }
        }

        property.setContent(content);
    } catch (ParserConfigurationException e) {
        throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e);
    }

    return property;
}

From source file:com.almende.eve.agent.google.GoogleCalendarAgent.java

/**
 * Delete an existing event.//from   w  w  w .j  av a 2  s .  c  o m
 * 
 * @param eventId
 *            id of the event to be deleted
 * @param calendarId
 *            Optional calendar id. the primary calendar is used by default
 * @throws Exception
 *             the exception
 */
@Override
public void deleteEvent(@Name("eventId") final String eventId, @Optional @Name("calendarId") String calendarId)
        throws Exception {
    // initialize optional parameters
    if (calendarId == null) {
        calendarId = getState().get("email", String.class);
    }

    // built url
    final String url = CALENDAR_URI + calendarId + "/events/" + eventId;

    // perform POST request
    final Map<String, String> headers = getAuthorizationHeaders();
    final String resp = HttpUtil.delete(url, headers);
    if (!resp.isEmpty()) {
        final ObjectNode node = JOM.getInstance().readValue(resp, ObjectNode.class);

        // check error code
        if (node.has("error")) {
            final ObjectNode error = (ObjectNode) node.get("error");
            final Integer code = error.has("code") ? error.get("code").asInt() : null;
            if (code != null && (code.equals(404) || code.equals(410))) {
                throw new JSONRPCException(CODE.NOT_FOUND);
            }

            throw new JSONRPCException(error);
        } else {
            throw new Exception(resp);
        }
    }
}

From source file:org.apache.streams.graph.GraphHttpPersistWriter.java

@Override
protected ObjectNode executePost(HttpPost httpPost) {

    Objects.requireNonNull(httpPost);

    ObjectNode result = null;

    CloseableHttpResponse response = null;

    String entityString = null;//from   ww w  . java  2s.co  m
    try {
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == 200
                || response.getStatusLine().getStatusCode() == 201 && entity != null) {
            entityString = EntityUtils.toString(entity);
            result = mapper.readValue(entityString, ObjectNode.class);
        }
        LOGGER.debug("Writer response:\n{}\n{}\n{}", httpPost.toString(),
                response.getStatusLine().getStatusCode(), entityString);
        if (result == null || (result.get("errors") != null && result.get("errors").isArray()
                && result.get("errors").iterator().hasNext())) {
            LOGGER.error("Write Error: " + result.get("errors"));
        } else {
            LOGGER.debug("Write Success");
        }
    } catch (IOException ex) {
        LOGGER.error("IO error:\n{}\n{}\n{}", httpPost.toString(), response, ex.getMessage());
    } catch (Exception ex) {
        LOGGER.error("Write Exception:\n{}\n{}\n{}", httpPost.toString(), response, ex.getMessage());
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException ignored) {
            LOGGER.trace("ignored IOException", ignored);
        }
    }
    return result;
}

From source file:com.almende.eve.agent.google.GoogleCalendarAgent.java

/**
 * Get all busy event timeslots in given interval.
 * //from   w  w w. j ava2 s. co m
 * @param timeMin
 *            start of the interval
 * @param timeMax
 *            end of the interval
 * @param calendarId
 *            optional calendar id. If not provided, the default calendar is
 *            used
 * @param timeZone
 *            Time zone used in the response. Optional. The default is UTC.
 * @return the busy
 * @throws Exception
 *             the exception
 */
@Override
public ArrayNode getBusy(@Name("timeMin") final String timeMin, @Name("timeMax") final String timeMax,
        @Optional @Name("calendarId") String calendarId, @Optional @Name("timeZone") final String timeZone)
        throws Exception {
    // initialize optional parameters
    if (calendarId == null) {
        calendarId = getState().get("email", String.class);
    }

    // build request body
    final ObjectNode request = new ObjectNode(JsonNodeFactory.instance);
    request.put("timeMin", new DateTime(timeMin).toString());
    request.put("timeMax", new DateTime(timeMax).toString());

    if (timeZone != null) {
        request.put("timeZone", timeZone);
    }

    final ArrayNode node = request.putArray("items");
    node.addObject().put("id", calendarId);

    final String url = "https://www.googleapis.com/calendar/v3/freeBusy";

    // perform POST request
    final ObjectMapper mapper = JOM.getInstance();
    final String body = mapper.writeValueAsString(request);
    final Map<String, String> headers = getAuthorizationHeaders();
    headers.put("Content-Type", "application/json");
    final String resp = HttpUtil.post(url, body, headers);
    final ObjectNode response = mapper.readValue(resp, ObjectNode.class);

    // check for errors
    if (response.has("error")) {
        final ObjectNode error = (ObjectNode) response.get("error");
        throw new JSONRPCException(error);
    }

    // get items from the response
    ArrayNode items = null;
    if (response.has("calendars")) {
        final JsonNode calendars = response.get("calendars");
        if (calendars.has(calendarId)) {
            final JsonNode calendar = calendars.get(calendarId);
            if (calendar.has("busy")) {
                items = (ArrayNode) calendar.get("busy");
            }
        }
    }

    if (items == null) {
        items = JOM.createArrayNode();
    }

    return items;
}

From source file:com.heliosapm.mws.server.net.json.JSONRequest.java

/**
 * Creates a new JSONRequest/*from   w ww  .  j av a  2  s  . co m*/
 * @param channel The channel that the request came in on. Ignored if null 
 * @param tCode the type code of the request
 * @param requestId The client supplied request ID
 * @param inReferenceToRequestId The client supplied in regards to request ID
 * @param serviceName The service name requested
 * @param opName The op name requested
 * @param request The original request
 */
protected JSONRequest(Channel channel, String tCode, long rid, long rerid, String serviceName, String opName,
        JsonNode request) {
    this.channel = channel;
    this.tCode = tCode;
    this.requestId = rid;
    this.inReferenceToRequestId = rerid;
    this.serviceName = serviceName;
    this.opName = opName;
    this.request = request;
    JsonNode argNode = request.get("args");
    if (argNode != null) {
        if (argNode instanceof ArrayNode) {
            ArrayNode an = (ArrayNode) argNode;
            for (int i = 0; i < an.size(); i++) {
                arguments.put("" + i, an.get(i));
            }
        } else if (argNode instanceof ObjectNode) {
            ObjectNode on = (ObjectNode) argNode;
            for (Iterator<String> siter = on.fieldNames(); siter.hasNext();) {
                String fieldName = siter.next();
                arguments.put(fieldName, on.get(fieldName));
            }
        }
    }
}

From source file:org.modeshape.web.jcr.rest.handler.ItemHandlerImpl.java

protected List<JSONChild> getChildren(JsonNode jsonNode) {
    List<JSONChild> children;
    JsonNode childrenNode = jsonNode.get(CHILD_NODE_HOLDER);
    if (childrenNode instanceof ObjectNode) {
        ObjectNode childrenObject = (ObjectNode) childrenNode;
        children = new ArrayList<>(childrenObject.size());
        for (Iterator<?> iterator = childrenObject.fields(); iterator.hasNext();) {
            String childName = iterator.next().toString();
            //it is not possible to have SNS in the object form, so the index will always be 1
            children.add(new JSONChild(childName, childrenObject.get(childName), 1));
        }/*from ww w. ja va2  s . co m*/
        return children;
    } else {
        ArrayNode childrenArray = (ArrayNode) childrenNode;
        children = new ArrayList<>(childrenArray.size());
        Map<String, Integer> visitedNames = new HashMap<>(childrenArray.size());

        for (int i = 0; i < childrenArray.size(); i++) {
            JsonNode child = childrenArray.get(i);
            if (child.size() == 0) {
                continue;
            }
            if (child.size() > 1) {
                logger.warn(
                        "The child object {0} has more than 1 elements, only the first one will be taken into account",
                        child);
            }
            String childName = child.fields().next().toString();
            int sns = visitedNames.containsKey(childName) ? visitedNames.get(childName) + 1 : 1;
            visitedNames.put(childName, sns);

            children.add(new JSONChild(childName, child.get(childName), sns));
        }
        return children;
    }
}