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:services.bizdockapi.BizdockApiClientImpl.java

@Override
public JsonNode call(String applicationKey, String secretKey, ApiMethod apiMethod, String url, JsonNode content)
        throws BizdockApiException {

    // convert the JSON content to a string
    String contentString = null;/*from  w w  w .ja  v  a2s.co m*/
    if (content != null) {
        try {
            contentString = getMapper().writeValueAsString(content);
            Logger.info("contentString: " + contentString);
        } catch (JsonProcessingException e) {
            throw new BizdockApiException(e.getMessage(), 500);
        }
    }

    // set the timestamp as now
    Date timestamp = new Date();

    // generate the timestamp
    byte[] signatureAsByte = null;
    try {
        SignatureGeneratorImpl signatureGenerator = new SignatureGeneratorImpl(secretKey, applicationKey);
        byte[] contentAsByte = contentString != null ? contentString.getBytes() : null;
        signatureAsByte = signatureGenerator.getRequestSignature(apiMethod, url, contentAsByte,
                timestamp.getTime());
    } catch (Exception e) {
        throw new BizdockApiException(e.getMessage(), 500);
    }

    // construct the request
    WSRequest request = WS.url(url).setHeader("Content-Type", "application/json");

    request.setHeader(IApiConstants.APPLICATION_KEY_HEADER, applicationKey);
    request.setHeader(IApiConstants.SIGNATURE_HEADER, new String(signatureAsByte));
    request.setHeader(IApiConstants.TIMESTAMP_HEADER, String.valueOf(timestamp.getTime()));

    // process the request
    Promise<WSResponse> response = null;

    switch (apiMethod) {
    case GET:
        response = request.get();
        break;
    case POST:
        response = request.post(contentString);
        break;
    case PUT:
        response = request.put(contentString);
        break;
    case DELETE:
        response = request.delete();
        break;
    default:
        break;
    }

    Promise<Pair<Integer, JsonNode>> jsonPromise = response
            .map(new Function<WSResponse, Pair<Integer, JsonNode>>() {
                public Pair<Integer, JsonNode> apply(WSResponse response) {
                    try {
                        return Pair.of(response.getStatus(), response.asJson());
                    } catch (Exception e) {
                        JsonNode error = JsonNodeFactory.instance.textNode(e.getMessage());
                        return Pair.of(response.getStatus(), error);
                    }
                }
            });

    Pair<Integer, JsonNode> responseContent = jsonPromise.get(WS_TIMEOUT);

    // treat the response
    if (responseContent.getLeft().equals(200) || responseContent.getLeft().equals(204)) {
        return responseContent.getRight();
    } else {
        String errorMessage = "BizDock API call error / url: " + url + " / status: " + responseContent.getLeft()
                + " / errors: " + responseContent.getRight().toString();
        throw new BizdockApiException(errorMessage, responseContent.getLeft());
    }

}

From source file:es.bsc.amon.controller.AppsDBMapper.java

/**
 *
 * @param start/*from w  w w .java  2s  .  c  o  m*/
 * @param end
 * @param showInstances if true, shows instances information instead of nodes information
 * @return
 */
public ObjectNode getAllApps(long start, long end, boolean showInstances) {
    DBObject query = (DBObject) JSON.parse("{ '$or' : [" + "{ '$and' : [ { timestamp : { '$gte' : " + start
            + " }}, { timestamp : {'$lte' : " + end + "}} ] }," + "{ '$and' : [ { endtime : { '$gte' : " + start
            + " }}, { endtime : {'$lte' : " + end + "}} ] }" + "]}");
    //DBObject orderby = new BasicDBObject("timestamp":-1);
    BasicDBList ret = DBManager.instance.find(EventsDBMapper.COLL_NAME, query);

    Map<String, Set<String>> appsInfo = new HashMap<>();

    Iterator<Object> iter = ret.iterator();
    while (iter.hasNext()) {
        DBObject event = (DBObject) iter.next();
        try {
            String appName = event.get(EventsDBMapper.APPID).toString();
            Object node = event.get(showInstances ? EventsDBMapper.INSTANCEID : EventsDBMapper.NODEID);
            String nodeName = node == null ? "" : node.toString();
            Set<String> appSet = appsInfo.get(appName);
            if (appSet == null) {
                appSet = new TreeSet<String>();
                appsInfo.put(appName, appSet);
            }
            appSet.add(nodeName);
        } catch (NullPointerException ex) {
            Logger.warn("This element did not parsed as an application: " + event.toString()
                    + ". Removing it from DB...");
            try {
                EventsDBMapper.getInstance().remove(event);
            } catch (Exception e) {
                Logger.error("Cannot remove it from database");
            }
        }
    }

    ObjectNode all = new ObjectNode(JsonNodeFactory.instance);
    for (Map.Entry<String, Set<String>> entry : appsInfo.entrySet()) {
        ArrayNode nodes = new ArrayNode(JsonNodeFactory.instance);
        for (String n : entry.getValue()) {
            nodes.add(n);
        }
        all.put(entry.getKey(), nodes);
    }
    return all;
}

From source file:com.stratio.ingestion.sink.druid.DruidSinkIT.java

private Event getTrackerEvent() {
    Random random = new Random();
    String[] users = new String[] { "user1@santander.com", "user2@santander.com", "user3@santander.com",
            "user4@santander.com" };
    String[] isoCode = new String[] { "DE", "ES", "US", "FR" };
    TimeUnit[] offset = new TimeUnit[] { TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.SECONDS };
    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    Map<String, String> headers;
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = null;/*w ww  .j ava 2s.c o  m*/
    final String fileName = "/trackerSample" + random.nextInt(4) + ".json";
    try {
        jsonNode = mapper.readTree(getClass().getResourceAsStream(fileName));
    } catch (IOException e) {
        e.printStackTrace();
    }
    headers = mapper.convertValue(jsonNode, Map.class);
    headers.put("timestamp",
            String.valueOf(new Date().getTime() + getOffset(offset[random.nextInt(3)]) * random.nextInt(100)));
    headers.put("santanderID", users[random.nextInt(4)]);
    headers.put("isoCode", isoCode[random.nextInt(4)]);

    return EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
}

From source file:com.datamountaineer.streamreactor.connect.json.SimpleJsonConverterTest.java

@Test
public void mapToJsonNonStringKeys() {
    Schema intIntMap = SchemaBuilder.map(Schema.INT32_SCHEMA, Schema.INT32_SCHEMA).build();
    Map<Integer, Integer> input = new HashMap<>();
    input.put(1, 12);/*w w  w  . j  ava 2  s. com*/
    input.put(2, 15);
    JsonNode converted = converter.fromConnectData(intIntMap, input);

    assertTrue(converted.isArray());
    ArrayNode payload = (ArrayNode) converted;
    assertEquals(2, payload.size());
    Set<JsonNode> payloadEntries = new HashSet<>();
    for (JsonNode elem : payload)
        payloadEntries.add(elem);
    assertEquals(new HashSet<>(Arrays.asList(JsonNodeFactory.instance.arrayNode().add(1).add(12),
            JsonNodeFactory.instance.arrayNode().add(2).add(15))), payloadEntries);
}

From source file:com.dotweblabs.friendscube.rest.resources.gae.GaeFileServerResource.java

@Override
public String upload(Representation entity) throws Exception {
    if (entity != null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
            Request restletRequest = getRequest();
            HttpServletRequest servletRequest = ServletUtils.getRequest(restletRequest);
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator fileIterator = upload.getItemIterator(servletRequest);
            getLogger().info("content type: " + servletRequest.getContentType());
            getLogger().info("content: " + new ServletRequestContext(servletRequest).getContentLength());

            getLogger().info("iterator: " + fileIterator.hasNext());
            while (fileIterator.hasNext()) {
                FileItemStream item = fileIterator.next();

                String name = item.getName();
                String fileName = getQueryValue("client_token") + "_" + name; // TODO note storing client_token is dangerous
                GcsFilename gcsFilename = new GcsFilename(getBucketName(), fileName);
                getLogger().info("using bucket.. " + getBucketName());
                byte[] byteContent = ByteStreams.toByteArray(item.openStream());
                // TODO byteContent is basicallly the file uploaded

                getLogger().info("contentType: " + item.getContentType());
                GcsOutputChannel outputChannel = gcsService.createOrReplace(gcsFilename,
                        GcsFileOptions.getDefaultInstance());
                outputChannel.write(ByteBuffer.wrap(byteContent));
                outputChannel.close();/*from w  w  w  .  jav a  2s  .co  m*/
                getLogger().info("uploaded");

                BlobKey blobKey = blobstoreService.createGsBlobKey(
                        "/gs/" + gcsFilename.getBucketName() + "/" + gcsFilename.getObjectName());

                ObjectNode result = JsonNodeFactory.instance.objectNode();
                processFile(blobKey, getQueryValue("client_token"), getQueryValue("upload_type"), result);
                return result.toString();
            }
        } else {
            setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        }
    } else {
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    }
    return null;
}

From source file:com.github.fge.jsonschema.servlets.SyntaxValidateServlet.java

private static JsonNode buildParsingError(final JsonProcessingException e, final boolean crlf) {
    final JsonLocation location = e.getLocation();
    final ObjectNode ret = JsonNodeFactory.instance.objectNode();

    /*//ww w.j  a  v  a 2s  .  c o  m
     * Unfortunately, for some reason, Jackson botches the column number in
     * its JsonPosition -- I cannot figure out why exactly. However, it does
     * have a correct offset into the buffer.
     *
     * The problem is that if the input has CR/LF line terminators, its
     * offset will be "off" by the number of lines minus 1 with regards to
     * what JavaScript sees as positions in text areas. Make the necessary
     * adjustments so that the caret jumps at the correct position in this
     * case.
     */
    final int lineNr = location.getLineNr();
    int offset = (int) location.getCharOffset();
    if (crlf)
        offset = offset - lineNr + 1;
    ret.put(ParseError.LINE, lineNr);
    ret.put(ParseError.OFFSET, offset);

    // Finally, put the message
    ret.put(ParseError.MESSAGE, e.getOriginalMessage());
    return ret;
}

From source file:com.flipkart.zjsonpatch.JsonDiff.java

private static ArrayNode getJsonNodes(List<Diff> diffs) {
    JsonNodeFactory FACTORY = JsonNodeFactory.instance;
    final ArrayNode patch = FACTORY.arrayNode();
    for (Diff diff : diffs) {
        ObjectNode jsonNode = getJsonNode(FACTORY, diff);
        patch.add(jsonNode);/*from  w ww  .jav  a 2  s  .  c o  m*/
    }
    return patch;
}

From source file:easyrpc.server.serialization.jsonrpc.JSONCallee.java

byte[] returnJsonRpcError(Object id, Exception e) {
    ObjectNode object = JsonNodeFactory.instance.objectNode();
    object.put("jsonrpc", "2.0");
    object.put("id", id.toString());
    ObjectNode error = object.putObject("error");
    error.put("code", -1);
    error.put("message", e.getClass().getCanonicalName() + " : " + e.getMessage());
    object.put("error", error);

    return object.toString().getBytes();
}

From source file:io.gs2.auth.Gs2AuthClient.java

/**
 * GS2-Account??????????<br>//  w w  w. ja v  a2s.c o  m
 * <br>
 *
 * @param request 
        
 * @return ?
        
 */

public LoginWithSignResult loginWithSign(LoginWithSignRequest request) {

    ObjectNode body = JsonNodeFactory.instance.objectNode().put("serviceId", request.getServiceId())
            .put("userId", request.getUserId()).put("keyName", request.getKeyName())
            .put("sign", request.getSign());

    HttpPost post = createHttpPost(Gs2Constant.ENDPOINT_HOST + "/login/signed", credential, ENDPOINT,
            LoginWithSignRequest.Constant.MODULE, LoginWithSignRequest.Constant.FUNCTION, body.toString());
    if (request.getRequestId() != null) {
        post.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
    }

    return doRequest(post, LoginWithSignResult.class);

}

From source file:uk.ac.gate.cloud.data.DataBundle.java

/**
 * Upload a file to an open bundle.//from w w w . j ava 2 s  .c  om
 * 
 * @param fileName the name to use for the bundle entry
 * @param contentLength the number of bytes to upload
 * @param source an input stream from which the file's content can be
 *          read. It must provide exactly <code>contentLength</code>
 *          bytes up to end-of-file. The stream will be read to EOF
 *          but will not be closed by this method, the caller is
 *          responsible for ensuring the stream is properly closed.
 */
public void addFile(String fileName, int contentLength, InputStream source) {
    ObjectNode request = JsonNodeFactory.instance.objectNode();
    request.put("fileName", fileName);
    // create the input
    AddResult addRes = client.post(url + "/add", new TypeReference<AddResult>() {
    }, request);
    try {
        // upload the file
        HttpURLConnection putConnection = (HttpURLConnection) addRes.putUrl.openConnection();
        putConnection.setDoOutput(true);
        putConnection.setRequestMethod("PUT");
        putConnection.setRequestProperty("Content-Type", "application/octet-stream");
        putConnection.setFixedLengthStreamingMode(contentLength);
        OutputStream out = putConnection.getOutputStream();
        try {
            IOUtils.copy(source, out);
        } finally {
            IOUtils.closeQuietly(out);
        }
    } catch (IOException e) {
        throw new RestClientException(e);
    }
}