Example usage for com.fasterxml.jackson.databind.node JsonNodeFactory instance

List of usage examples for com.fasterxml.jackson.databind.node JsonNodeFactory instance

Introduction

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

Prototype

JsonNodeFactory instance

To view the source code for com.fasterxml.jackson.databind.node JsonNodeFactory instance.

Click Source Link

Usage

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

/**
 * Get all busy event timeslots in given interval.
 * //from w w w.jav  a 2 s  .  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
 * @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:org.apache.usergrid.client.EntityTestCase.java

@Test
public void testEntityPopInArray() {
    String collectionName = "testEntityProperties" + System.currentTimeMillis();
    String entityName = "testEntity1";

    UsergridEntity entity = new UsergridEntity(collectionName, entityName);
    entity.save();/*from  www  .j a v a2s .  c o m*/

    ArrayList<Object> lenArr = new ArrayList<>();
    lenArr.add(1);
    lenArr.add(2);
    lenArr.add(3);
    entity.putProperty("lenArray", lenArr);
    entity.save();

    // should remove the last value of an existing array
    entity.pop("lenArray");
    entity.save();

    UsergridEntity eLookUp = Usergrid.GET(collectionName, entityName).first();
    assertNotNull("The entity returned is not null.", eLookUp);

    ArrayNode toCompare = new ArrayNode(JsonNodeFactory.instance);
    toCompare.add(1).add(2);
    assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("lenArray"), toCompare);

    // value should remain unchanged if it is not an array
    entity.putProperty("foo", "test1");
    entity.save();

    entity.pop("foo");
    entity.save();

    eLookUp = Usergrid.GET(collectionName, entityName).first();
    assertNotNull("The entity returned is not null.", eLookUp);
    assertEquals("foo should equal test1.", eLookUp.getStringProperty("foo"), "test1");

    //should gracefully handle empty arrays
    ArrayList<Object> lenArr2 = new ArrayList<>();
    entity.putProperty("foo", lenArr2);
    entity.save();
    entity.pop("foo");

    eLookUp = Usergrid.GET(collectionName, entityName).first();
    assertNotNull("The entity returned is not null.", eLookUp);

    toCompare = new ArrayNode(JsonNodeFactory.instance);
    assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("foo"), toCompare);
}

From source file:io.gravitee.management.service.ApiServiceTest.java

private EventEntity mockEvent(EventType eventType) throws Exception {
    final JsonNodeFactory factory = JsonNodeFactory.instance;
    ObjectNode node = factory.objectNode();
    node.set("id", factory.textNode(API_ID));

    Map<String, String> properties = new HashMap<String, String>();
    properties.put(Event.EventProperties.API_ID.getValue(), API_ID);
    properties.put(Event.EventProperties.USERNAME.getValue(), USER_NAME);

    Api api = new Api();
    api.setId(API_ID);//from   w  w w .j av  a  2s  .  c o  m

    EventEntity event = new EventEntity();
    event.setType(eventType);
    event.setId(UUID.randomUUID().toString());
    event.setPayload(objectMapper.writeValueAsString(api));
    event.setCreatedAt(new Date());
    event.setUpdatedAt(event.getCreatedAt());
    event.setProperties(properties);

    return event;
}

From source file:io.gs2.inbox.Gs2InboxClient.java

/**
 * ?????????<br>// ww  w. j a v  a2  s.  co m
 * <br>
 * ?URL??????????200????GS2??????????????????<br>
 * <br>
 * 200 ??????JSON???<br>
 * "success" ?????????ID???????<br>
 * success ???ID???????BadGateway(502)???<br>
 * <br>
 * BadGateway(502) ???????????????????<br>
 * ?????????????????????????????????<br>
 * success ??????ID????reason ????????????<br>
 * ID hoge ????????????????????????????????<br>
 * <br>
 * - : ??? * 10<br>
 * <br>
 *
 * @param request 
        
 * @return ?
        
 */

public ReadMessagesResult readMessages(ReadMessagesRequest request) {

    ObjectNode body = JsonNodeFactory.instance.objectNode();
    if (request.getMessageIds() != null) {
        List<JsonNode> node = new ArrayList<>();
        for (String item : request.getMessageIds()) {
            node.add(JsonNodeFactory.instance.textNode(item));
        }
        body.set("messageIds", JsonNodeFactory.instance.arrayNode().addAll(node));
    }

    HttpPost post = createHttpPost(
            Gs2Constant.ENDPOINT_HOST + "/inbox/"
                    + (request.getInboxName() == null || request.getInboxName().equals("") ? "null"
                            : request.getInboxName())
                    + "/message/multiple",
            credential, ENDPOINT, ReadMessagesRequest.Constant.MODULE, ReadMessagesRequest.Constant.FUNCTION,
            body.toString());
    if (request.getRequestId() != null) {
        post.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
    }

    post.setHeader("X-GS2-ACCESS-TOKEN", request.getAccessToken());

    return doRequest(post, ReadMessagesResult.class);

}

From source file:io.gs2.ranking.Gs2RankingClient.java

/**
 * ???<br>/*  w  ww  .  j  a v a 2  s  .c  o  m*/
 * <br>
 *
 * @param request 
        
 * @return ?
        
 */

public PutScoreResult putScore(PutScoreRequest request) {

    ObjectNode body = JsonNodeFactory.instance.objectNode().put("score", request.getScore());
    if (request.getMeta() != null)
        body.put("meta", request.getMeta());

    HttpPost post = createHttpPost(Gs2Constant.ENDPOINT_HOST + "/ranking/"
            + (request.getRankingTableName() == null || request.getRankingTableName().equals("") ? "null"
                    : request.getRankingTableName())
            + "/mode/"
            + (request.getGameMode() == null || request.getGameMode().equals("") ? "null"
                    : request.getGameMode())
            + "/ranking", credential, ENDPOINT, PutScoreRequest.Constant.MODULE,
            PutScoreRequest.Constant.FUNCTION, body.toString());
    if (request.getRequestId() != null) {
        post.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
    }

    post.setHeader("X-GS2-ACCESS-TOKEN", request.getAccessToken());

    return doRequest(post, PutScoreResult.class);

}

From source file:org.apache.usergrid.client.EntityTestCase.java

@Test
public void testEntityShiftInArray() {
    String collectionName = "testEntityProperties" + System.currentTimeMillis();
    String entityName = "testEntity1";

    //should remove the last value of an existing array
    UsergridEntity entity = new UsergridEntity(collectionName, entityName);
    entity.save();//from   w  w w. j av  a 2 s  .co m

    ArrayList<Object> lenArr = new ArrayList<>();
    lenArr.add(1);
    lenArr.add(2);
    lenArr.add(3);
    entity.putProperty("lenArray", lenArr);
    entity.save();

    entity.shift("lenArray");
    entity.save();

    UsergridEntity eLookUp = Usergrid.GET(collectionName, entityName).first();
    assertNotNull("The entity returned is not null.", eLookUp);

    ArrayNode toCompare = new ArrayNode(JsonNodeFactory.instance);
    toCompare.add(2).add(3);
    assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("lenArray"), toCompare);

    //value should remain unchanged if it is not an array
    entity.putProperty("foo", "test1");
    entity.shift("foo");
    entity.save();

    eLookUp = Usergrid.GET(collectionName, entityName).first();
    assertNotNull("The entity returned is not null.", eLookUp);
    assertEquals("The entity returned is not null.", eLookUp.getStringProperty("foo"), "test1");

    //should gracefully handle empty arrays
    ArrayList<Object> lenArr2 = new ArrayList<>();
    entity.putProperty("foo", lenArr2);
    entity.shift("foo");
    entity.save();

    eLookUp = Usergrid.GET(collectionName, entityName).first();
    assertNotNull("The entity returned is not null.", eLookUp);
    assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("foo"),
            new ArrayNode(JsonNodeFactory.instance));
}

From source file:io.gs2.inbox.Gs2InboxClient.java

/**
 * ????<br>//from   www  .j  a  v a  2  s .com
 * <br>
 * - : 10<br>
 * <br>
 *
 * @param request 
        
 * @return ?
        
 */

public SendMessageResult sendMessage(SendMessageRequest request) {

    ObjectNode body = JsonNodeFactory.instance.objectNode().put("userId", request.getUserId()).put("message",
            request.getMessage());
    if (request.getCooperation() != null)
        body.put("cooperation", request.getCooperation());

    HttpPost post = createHttpPost(
            Gs2Constant.ENDPOINT_HOST + "/inbox/"
                    + (request.getInboxName() == null || request.getInboxName().equals("") ? "null"
                            : request.getInboxName())
                    + "/message",
            credential, ENDPOINT, SendMessageRequest.Constant.MODULE, SendMessageRequest.Constant.FUNCTION,
            body.toString());
    if (request.getRequestId() != null) {
        post.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
    }

    return doRequest(post, SendMessageResult.class);

}

From source file:com.meltmedia.dropwizard.etcd.cluster.ClusterAssignmentIT.java

public static ObjectNode nodeData(String name) {
    return JsonNodeFactory.instance.objectNode().put("name", name);
}

From source file:org.apache.usergrid.android.sdk.UGClient.java

/**
 *  Forms and initiates a raw synchronous http request and processes the response.
 *
 *  @param  httpMethod the HTTP method in the format: 
 *      HTTP_METHOD_<method_name> (e.g. HTTP_METHOD_POST)
 *  @param  params the URL parameters to append to the request URL
 *  @param  data the body of the request
 *  @param  segments  additional URL path segments to append to the request URL 
 *  @return  ApiResponse object//from   ww w  .  j  a  va 2s  . c  om
 */
public ApiResponse doHttpRequest(String httpMethod, Map<String, Object> params, Object data,
        String... segments) {

    ApiResponse response = null;
    OutputStream out = null;
    InputStream in = null;
    HttpURLConnection conn = null;

    String urlAsString = path(apiUrl, segments);

    try {
        String contentType = "application/json";
        if (httpMethod.equals(HTTP_METHOD_POST) && isEmpty(data) && !isEmpty(params)) {
            data = encodeParams(params);
            contentType = "application/x-www-form-urlencoded";
        } else {
            urlAsString = addQueryParams(urlAsString, params);
        }

        //logTrace("Invoking " + httpMethod + " to '" + urlAsString + "'");

        URL url = new URL(urlAsString);
        conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod(httpMethod);
        conn.setRequestProperty("Content-Type", contentType);
        conn.setUseCaches(false);

        if ((accessToken != null) && (accessToken.length() > 0)) {
            String authStr = "Bearer " + accessToken;
            conn.setRequestProperty("Authorization", authStr);
        }

        conn.setDoInput(true);

        if (httpMethod.equals(HTTP_METHOD_POST) || httpMethod.equals(HTTP_METHOD_PUT)) {
            if (isEmpty(data)) {
                data = JsonNodeFactory.instance.objectNode();
            }

            String dataAsString = null;

            if ((data != null) && (!(data instanceof String))) {
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
                dataAsString = objectMapper.writeValueAsString(data);
            } else {
                dataAsString = (String) data;
            }

            //logTrace("Posting/putting data: '" + dataAsString + "'");

            byte[] dataAsBytes = dataAsString.getBytes();

            conn.setRequestProperty("Content-Length", Integer.toString(dataAsBytes.length));
            conn.setDoOutput(true);

            out = conn.getOutputStream();
            out.write(dataAsBytes);
            out.flush();
            out.close();
            out = null;
        }

        in = conn.getInputStream();
        if (in != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }

            String responseAsString = sb.toString();

            //logTrace("response from server: '" + responseAsString + "'");
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            response = (ApiResponse) objectMapper.readValue(responseAsString, ApiResponse.class);
            response.setRawResponse(responseAsString);

            response.setUGClient(this);
        } else {
            response = null;
            logTrace("no response body from server");
        }

        //final int responseCode = conn.getResponseCode();
        //logTrace("responseCode from server = " + responseCode);
    } catch (Exception e) {
        logError("Error " + httpMethod + " to '" + urlAsString + "'");
        if (e != null) {
            e.printStackTrace();
            logError(e.getLocalizedMessage());
        }
        response = null;
    } catch (Throwable t) {
        logError("Error " + httpMethod + " to '" + urlAsString + "'");
        if (t != null) {
            t.printStackTrace();
            logError(t.getLocalizedMessage());
        }
        response = null;
    } finally {
        try {
            if (out != null) {
                out.close();
            }

            if (in != null) {
                in.close();
            }

            if (conn != null) {
                conn.disconnect();
            }
        } catch (Exception ignored) {
        }
    }

    return response;
}