Example usage for com.fasterxml.jackson.databind JsonNode toString

List of usage examples for com.fasterxml.jackson.databind JsonNode toString

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode toString.

Prototype

public abstract String toString();

Source Link

Usage

From source file:org.apache.usergrid.java.client.model.UsergridEntity.java

public void updatePropertiesWithJsonNode(@NotNull final JsonNode node) {
    try {/*w w w .j a  v  a2s.  c om*/
        entityUpdateReader.readValue(node);
    } catch (IOException e) {
        System.out.print("Usergrid Error: Unable to update properties from jsonNode - " + node.toString());
    }
}

From source file:org.openmhealth.shim.healthvault.HealthvaultShim.java

@Override
public ShimDataResponse getData(final ShimDataRequest shimDataRequest) throws ShimException {
    final HealthVaultDataType healthVaultDataType;
    try {//ww  w  .jav  a  2  s .com
        healthVaultDataType = HealthVaultDataType
                .valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'hh:mm:ss");

    /***
     * Setup default date parameters
     */
    DateTime today = new DateTime();

    DateTime startDate = shimDataRequest.getStartDate() == null ? today.minusDays(1)
            : shimDataRequest.getStartDate();
    String dateStart = startDate.toString(formatter);

    DateTime endDate = shimDataRequest.getEndDate() == null ? today.plusDays(1) : shimDataRequest.getEndDate();
    String dateEnd = endDate.toString(formatter);

    long numToReturn = shimDataRequest.getNumToReturn() == null || shimDataRequest.getNumToReturn() <= 0 ? 100
            : shimDataRequest.getNumToReturn();

    Request request = new Request();
    request.setMethodName("GetThings");
    request.setInfo("<info>" + "<group max=\"" + numToReturn + "\">" + "<filter>" + "<type-id>"
            + healthVaultDataType.getDataTypeId() + "</type-id>" + "<eff-date-min>" + dateStart
            + "</eff-date-min>" + "<eff-date-max>" + dateEnd + "</eff-date-max>" + "</filter>" + "<format>"
            + "<section>core</section>" + "<xml/>" + "</format>" + "</group>" + "</info>");

    RequestTemplate template = new RequestTemplate(connection);
    return template.makeRequest(shimDataRequest.getAccessParameters(), request,
            new Marshaller<ShimDataResponse>() {
                public ShimDataResponse marshal(InputStream istream) throws Exception {

                    /**
                     * XML Document mappings to JSON don't respect repeatable
                     * tags, they don't get properly serialized into collections.
                     * Thus, we pickup the 'things' via the 'group' root tag
                     * and create a new JSON document out of each 'thing' node.
                     */
                    XmlMapper xmlMapper = new XmlMapper();
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document doc = builder.parse(istream);
                    NodeList nodeList = doc.getElementsByTagName("thing");

                    /**
                     * Collect JsonNode from each 'thing' xml node.
                     */
                    List<JsonNode> thingList = new ArrayList<>();
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        Node node = nodeList.item(i);
                        Document thingDoc = builder.newDocument();
                        Node newNode = thingDoc.importNode(node, true);
                        thingDoc.appendChild(newNode);
                        thingList.add(xmlMapper.readTree(convertDocumentToString(thingDoc)));
                    }

                    /**
                     * Rebuild JSON document structure to pass to deserializer.
                     */
                    String thingsJson = "{\"things\":[";
                    String thingsContent = "";
                    for (JsonNode thingNode : thingList) {
                        thingsContent += thingNode.toString() + ",";
                    }
                    thingsContent = "".equals(thingsContent) ? thingsContent
                            : thingsContent.substring(0, thingsContent.length() - 1);
                    thingsJson += thingsContent;
                    thingsJson += "]}";

                    /**
                     * Return raw re-built 'things' or a normalized JSON document.
                     */
                    ObjectMapper objectMapper = new ObjectMapper();
                    if (shimDataRequest.getNormalize()) {
                        SimpleModule module = new SimpleModule();
                        module.addDeserializer(ShimDataResponse.class, healthVaultDataType.getNormalizer());
                        objectMapper.registerModule(module);
                        return objectMapper.readValue(thingsJson, ShimDataResponse.class);
                    } else {
                        return ShimDataResponse.result(HealthvaultShim.SHIM_KEY,
                                objectMapper.readTree(thingsJson));
                    }
                }
            });
}

From source file:com.baasbox.service.push.providers.APNServer.java

@Override
public boolean send(String message, List<String> deviceid, JsonNode bodyJson) throws Exception {
    PushLogger pushLogger = PushLogger.getInstance();
    pushLogger.addMessage("............ APN Push Message: -%s- to the device(s) %s", message, deviceid);
    ApnsService service = null;/*from   w  w  w . j  ava  2s . c o m*/
    try {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("APN Push message: " + message + " to the device " + deviceid);
        if (!isInit) {
            pushLogger.addMessage("............ APNS is not initialized!");
            return true;
        }

        String payload = null;
        try {
            service = getService();
        } catch (com.notnoop.exceptions.InvalidSSLConfig e) {
            pushLogger.addMessage("Error sending push notification ...");
            pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
            BaasBoxLogger.error("Error sending push notification");
            throw new PushNotInitializedException(
                    "Error decrypting certificate.Verify your password for given certificate");
            //icallbackPush.onError(ExceptionUtils.getMessage(e));
        }

        JsonNode contentAvailableNode = bodyJson.findValue("content-available");
        Integer contentAvailable = null;
        if (!(contentAvailableNode == null)) {
            if (!(contentAvailableNode.isInt()))
                throw new PushContentAvailableFormatException(
                        "Content-available MUST be an Integer (1 for silent notification)");
            contentAvailable = contentAvailableNode.asInt();
        }

        JsonNode categoryNode = bodyJson.findValue("category");
        String category = null;
        if (!(categoryNode == null)) {
            if (!(categoryNode.isTextual()))
                throw new PushCategoryFormatException("Category MUST be a String");
            category = categoryNode.asText();
        }

        JsonNode soundNode = bodyJson.findValue("sound");
        String sound = null;
        if (!(soundNode == null)) {
            if (!(soundNode.isTextual()))
                throw new PushSoundKeyFormatException("Sound value MUST be a String");
            sound = soundNode.asText();
        }

        JsonNode actionLocKeyNode = bodyJson.findValue("actionLocalizedKey");
        String actionLocKey = null;

        if (!(actionLocKeyNode == null)) {
            if (!(actionLocKeyNode.isTextual()))
                throw new PushActionLocalizedKeyFormatException("ActionLocalizedKey MUST be a String");
            actionLocKey = actionLocKeyNode.asText();
        }

        JsonNode locKeyNode = bodyJson.findValue("localizedKey");
        String locKey = null;

        if (!(locKeyNode == null)) {
            if (!(locKeyNode.isTextual()))
                throw new PushLocalizedKeyFormatException("LocalizedKey MUST be a String");
            locKey = locKeyNode.asText();
        }

        JsonNode locArgsNode = bodyJson.get("localizedArguments");

        List<String> locArgs = new ArrayList<String>();
        if (!(locArgsNode == null)) {
            if (!(locArgsNode.isArray()))
                throw new PushLocalizedArgumentsFormatException(
                        "LocalizedArguments MUST be an Array of String");
            for (JsonNode locArgNode : locArgsNode) {
                if (locArgNode.isNumber())
                    throw new PushLocalizedArgumentsFormatException(
                            "LocalizedArguments MUST be an Array of String");
                locArgs.add(locArgNode.toString());
            }
        }

        JsonNode customDataNodes = bodyJson.get("custom");

        Map<String, JsonNode> customData = new HashMap<String, JsonNode>();

        if (!(customDataNodes == null)) {
            customData.put("custom", customDataNodes);
        }

        JsonNode badgeNode = bodyJson.findValue("badge");
        int badge = 0;
        if (!(badgeNode == null)) {
            if (!(badgeNode.isNumber()))
                throw new PushBadgeFormatException("Badge value MUST be a number");
            else
                badge = badgeNode.asInt();
        }

        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("APN Push message: " + message + " to the device " + deviceid + " with sound: "
                    + sound + " with badge: " + badge + " with Action-Localized-Key: " + actionLocKey
                    + " with Localized-Key: " + locKey);
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Localized arguments: " + locArgs.toString());
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Custom Data: " + customData.toString());

        pushLogger.addMessage("APN Push message: " + message + " to the device " + deviceid + " with sound: "
                + sound + " with badge: " + badge + " with Action-Localized-Key: " + actionLocKey
                + " with Localized-Key: " + locKey);
        pushLogger.addMessage("Localized arguments: " + locArgs.toString());
        pushLogger.addMessage("Custom Data: " + customData.toString());
        pushLogger.addMessage("Timeout: " + timeout);

        PayloadBuilder payloadBuilder = APNS.newPayload().alertBody(message).sound(sound)
                .actionKey(actionLocKey).localizedKey(locKey).localizedArguments(locArgs).badge(badge)
                .customFields(customData).category(category);
        if (contentAvailable != null && contentAvailable.intValue() == 1) {
            payloadBuilder.instantDeliveryOrSilentNotification();
        }
        payload = payloadBuilder.build();

        Collection<? extends ApnsNotification> result = null;
        if (timeout <= 0) {
            try {
                result = service.push(deviceid, payload);
            } catch (NetworkIOException e) {
                pushLogger.addMessage("Error sending push notification ...");
                pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
                BaasBoxLogger.error("Error sending push notification");
                BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
                throw new PushNotInitializedException("Error processing certificate, maybe it's revoked");
                //icallbackPush.onError(ExceptionUtils.getMessage(e));
            }
        } else {
            try {
                Date expiry = new Date(Long.MAX_VALUE);
                pushLogger.addMessage("Timeout is > 0 (%d), expiration date is set to %s", timeout,
                        expiry.toString());
                result = service.push(deviceid, payload, expiry);
            } catch (NetworkIOException e) {
                pushLogger.addMessage("Error sending push notification ...");
                pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
                BaasBoxLogger.error("Error sending enhanced push notification");
                BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
                throw new PushNotInitializedException("Error processing certificate, maybe it's revoked");
                //icallbackPush.onError(ExceptionUtils.getMessage(e));
            }

        }
        if (result != null) {
            Iterator<? extends ApnsNotification> it = result.iterator();
            while (it.hasNext()) {
                ApnsNotification item = it.next();
                //item.
            }

        }
        //icallbackPush.onSuccess();
        return false;
    } catch (Exception e) {
        pushLogger.addMessage("Error sending push notification (APNS)...");
        pushLogger.addMessage(ExceptionUtils.getMessage(e));
        throw e;
    } finally {
        if (service != null)
            service.stop();
    }
}

From source file:kr.ac.postech.lispconfig.LispConfigManager.java

public boolean configureDevice(String name, String password, String address, String port) {
    ApplicationId netConfAppId = coreService.getAppId(NETCONF_APP_NAME);

    InputStream is = null;//  w w  w  . j  a  v  a2  s  . c  o  m
    try {
        is = context.getBundleContext().getBundle().getEntry(DEVICE_CFG_JSON).openStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jsonFactory = mapper.getFactory();
    JsonParser jsonParser = null;
    try {
        jsonParser = jsonFactory.createParser(is);
    } catch (IOException e) {
        e.printStackTrace();
    }

    JsonNode jsonNode = null;
    try {
        jsonNode = mapper.readTree(jsonParser);
    } catch (IOException e) {
        e.printStackTrace();
    }

    JsonNode appRoot = jsonNode.get(APP_SUBJECT_CLASS_KEY);
    appRoot = appRoot.get(NETCONF_APP_NAME);

    jsonNode = appRoot.get(APP_CONFIG_KEY).get(0);

    ((ObjectNode) jsonNode).put("name", name);
    ((ObjectNode) jsonNode).put("password", password);
    ((ObjectNode) jsonNode).put("ip", address);
    ((ObjectNode) jsonNode).put("port", port);

    log.info(appRoot.toString());

    Object result = cfgService.applyConfig(APP_SUBJECT_CLASS_KEY, netConfAppId, APP_CONFIG_KEY,
            appRoot.path(APP_CONFIG_KEY));

    return result != null ? true : false;
}

From source file:com.servioticy.api.commons.data.SO.java

/** Generate response to a SO creation
 *
 * @return String/*from  w  w w.  j a  va  2  s.  c  om*/
 */
public String responseCreateSO() {
    JsonNode root = mapper.createObjectNode();

    try {
        ((ObjectNode) root).put("id", soId);
        ((ObjectNode) root).put("createdAt", soRoot.get("createdAt").asLong());
    } catch (Exception e) {
        LOG.error(e);
        throw new ServIoTWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, null);
    }
    return root.toString();
}

From source file:fr.gouv.vitam.query.parser.EsQueryParser.java

/**
 * $flt : { $fields : [ name1, name2 ], $like : like_text }
 *
 * @param refCommand/*from w  w w .ja va2s .  c o m*/
 * @param command
 * @param tr0
 * @param req
 * @throws InvalidParseOperationException
 */
@Override
protected final void analyzeXlt(final String refCommand, final JsonNode command, final TypeRequest tr0,
        final REQUEST req) throws InvalidParseOperationException {
    if (command == null) {
        throw new InvalidParseOperationException("Not correctly parsed: " + refCommand);
    }
    tr0.isOnlyES = true;
    LOGGER.debug("ES only: {}", refCommand);
    final ArrayNode fields = (ArrayNode) command.get(REQUESTARGS.fields.exactToken());
    final JsonNode like = command.get(REQUESTARGS.like.exactToken());
    if (fields == null || like == null) {
        throw new InvalidParseOperationException("Incorrect command: " + refCommand + " : " + command);
    }
    String[] names = new String[fields.size()];
    int i = 0;
    for (JsonNode name : fields) {
        names[i++] = name.toString();
    }
    switch (req) {
    case flt:
        tr0.query = QueryBuilders.fuzzyLikeThisQuery(names).likeText(like.toString());
        break;
    case mlt:
        tr0.query = QueryBuilders.moreLikeThisQuery(names).likeText(like.toString());
        break;
    default:
        throw new InvalidParseOperationException("Not correctly parsed: " + req);
    }
}

From source file:io.robusta.rra.representation.implementation.JacksonRepresentation.java

@Override
public List<String> getValues(String key) throws RepresentationException {
    List<String> list = new ArrayList<String>();
    for (JsonNode elt : asObject().get(key)) {
        list.add(elt.toString());
    }/*w  w  w . j  a v a 2 s  .c  o m*/
    return list;
}

From source file:com.digitalpebble.stormcrawler.filtering.basic.BasicURLNormalizer.java

@Override
public void configure(Map stormConf, JsonNode paramNode) {
    JsonNode node = paramNode.get("removeAnchorPart");
    if (node != null) {
        removeAnchorPart = node.booleanValue();
    }/* w ww.  j  av  a  2s  .  c  om*/

    node = paramNode.get("unmangleQueryString");
    if (node != null) {
        unmangleQueryString = node.booleanValue();
    }

    node = paramNode.get("queryElementsToRemove");
    if (node != null) {
        if (!node.isArray()) {
            LOG.warn("Failed to configure queryElementsToRemove.  Not an array: {}", node.toString());
        } else {
            ArrayNode array = (ArrayNode) node;
            for (JsonNode element : array) {
                queryElementsToRemove.add(element.asText());
            }
        }
    }

    node = paramNode.get("checkValidURI");
    if (node != null) {
        checkValidURI = node.booleanValue();
    }
}

From source file:org.pentaho.metaverse.impl.model.kettle.json.TransMetaJsonDeserializerTest.java

@Test
public void testWriteJsonAttributes() throws Exception {
    JsonNode attributes = mock(JsonNode.class);
    ObjectId stepId = new StringObjectId("id");

    Map<String, Object> attrMap = new HashMap<String, Object>() {
        {//from w  w w.j  a  va  2  s  .co  m
            put("name", "Test");
            put("int", 2);
            put("long", 3L);
            put("double", 3.0D);
            put("bool", true);
            put("null", null);
        }
    };

    when(attributes.toString()).thenReturn("mockedAttributes");
    when(mapper.readValue("mockedAttributes", attrs0.getClass())).then(invocationOnMock -> attrMap);

    deserializer.writeJsonAttributes(attributes, mapper, stepId);

    verify(repo).saveStepAttribute(null, stepId, "name", "Test");
    verify(repo).saveStepAttribute(null, stepId, "int", 2);
    verify(repo).saveStepAttribute(null, stepId, "long", 3L);
    verify(repo).saveStepAttribute(null, stepId, "double", 3.0D);
    verify(repo).saveStepAttribute(null, stepId, "bool", true);
    verify(repo).saveStepAttribute(null, stepId, "null", null);
}

From source file:com.spoiledmilk.ibikecph.search.SearchAutocompleteActivity.java

public void finishAndPutData() {
    runOnUiThread(new Runnable() {

        @Override//ww w  .  ja v a 2 s.  c o m
        public void run() {
            progressBar.setVisibility(View.INVISIBLE);
            if (isFinishing) {
                return;
            }
            isFinishing = true;
            Intent intent = new Intent();
            if (currentSelection != null) {
                if (isAddressSearched && addr != null) {
                    intent.putExtra("number", addr.number);
                }
                if (currentSelection instanceof KortforData && !((KortforData) currentSelection).isPlace()) {
                    String name = currentSelection.getName();
                    if (addr != null && addr.number != null && !addr.number.equals("")
                            && !addr.number.equals("1") && AddressParser.containsNumber(addr.number)) {
                        name += " " + addr.number;
                    }
                    if (currentSelection.getZip() != null && !currentSelection.getZip().equals("")) {
                        name += ", " + currentSelection.getZip();
                    }
                    if (currentSelection.getCity() != null && !currentSelection.getCity().equals("")) {
                        name += " " + currentSelection.getCity();
                    }
                    intent.putExtra("name", name);
                } else {
                    intent.putExtra("name", currentSelection.getName());
                }
                if (currentSelection.type == nodeType.FOURSQUARE || (currentSelection instanceof KortforData
                        && ((KortforData) currentSelection).isPlace()))
                    intent.putExtra("poi", currentSelection.getName());
                if (currentSelection.getAdress() != null) {
                    String address = currentSelection.getAdress();
                    intent.putExtra("address", address);
                }
                intent.putExtra("source", currentSelection.getSource());
                intent.putExtra("subsource", currentSelection.getSubSource());
                intent.putExtra("lat", currentSelection.getLatitude());
                intent.putExtra("lon", currentSelection.getLongitude());
                if (currentSelection instanceof FoursquareData || (currentSelection instanceof KortforData
                        && ((KortforData) currentSelection).isPlace())) {
                    intent.putExtra("isPoi", true);
                }
                if (currentSelection.getZip() != null && !currentSelection.getZip().trim().equals("")) {
                    intent.putExtra("zip", currentSelection.getZip());
                }
                if (currentSelection.getCity() != null && !currentSelection.getCity().trim().equals("")) {
                    intent.putExtra("city", currentSelection.getCity());
                }
                if (currentSelection.getStreet() != null && !currentSelection.getStreet().trim().equals("")) {
                    intent.putExtra("street", currentSelection.getStreet());
                }
                SearchAutocompleteActivity.this.setResult(RESULT_AUTOTOCMPLETE_SET, intent);
            } else {
                SearchAutocompleteActivity.this.setResult(RESULT_AUTOTOCMPLETE_NOT_SET, intent);
            }
            SharedPreferences prefs = getPreferences(MODE_PRIVATE);
            if (currentSelection != null) {
                JsonNode node = currentSelection.getJsonNode();
                if (node != null) {
                    prefs.edit().putString("lastSearchItem", node.toString()).commit();
                }
            }
            finish();
        }
    });
}