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

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

Introduction

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

Prototype

public String textValue() 

Source Link

Usage

From source file:com.pkrete.locationservice.admin.deserializers.OwnerJSONDeserializer.java

@Override
public Owner deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException {

    LocatingStrategy strategy = null;// w  w w  . j ava2  s . c  o m
    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);
    // Parse id
    int id = node.get("id") == null ? 0 : node.get("id").intValue();
    // Parse code
    String code = node.get("code") == null ? "" : node.get("code").textValue();
    // Parse name
    String name = node.get("name") == null ? "" : node.get("name").textValue();
    // Parse color
    String color = node.get("color") == null ? "" : node.get("color").textValue();
    // Parse opacity
    String opacity = node.get("opacity") == null ? "" : node.get("opacity").textValue();
    // Parse locating strategy
    String strategyStr = node.get("locating_strategy") == null ? null
            : node.get("locating_strategy").textValue();
    // If strategyStr not null, convert from string to LocatingStrategy object
    if (strategyStr != null) {
        // Get converterService bean from Application Context
        ConverterService converterService = (ConverterService) ApplicationContextUtils.getApplicationContext()
                .getBean("converterService");
        // Convert strategyStr to LocatingStrategy object
        strategy = (LocatingStrategy) converterService.convert(strategyStr, LocatingStrategy.class,
                LocatingStrategy.INDEX);
    }
    // String for ip addresses
    String ips = null;
    // Does allowed_ips node exist
    if (node.path("allowed_ips") != null) {
        // Parse allowed ip addresses
        Iterator<JsonNode> ite = node.path("allowed_ips").elements();
        // Init ips variable
        ips = "";
        // Iterate ips
        while (ite.hasNext()) {
            // Get next ip node
            JsonNode temp = ite.next();
            // Add ip to the ips string
            ips += temp.textValue();
            // Add line break, if there are more ips to read
            if (ite.hasNext()) {
                ips += "\n";
            }
        }
    }
    // Variables for redirects
    List<PreprocessingRedirect> preprocessingRedirect = null;
    List<NotFoundRedirect> notFoundRedirect = null;

    // Does redirects node exist
    if (node.path("redirects") != null) {
        preprocessingRedirect = new ArrayList<PreprocessingRedirect>();
        notFoundRedirect = new ArrayList<NotFoundRedirect>();
        // Parse redirects
        Iterator<JsonNode> ite = node.path("redirects").elements();
        // Iterate redirects
        while (ite.hasNext()) {
            // Get next redirect
            JsonNode temp = ite.next();
            // Parse id
            int redirectId = temp.get("id") == null ? 0 : temp.get("id").intValue();
            // Parse type
            String redirectType = temp.get("type") == null ? "" : temp.get("type").textValue();
            // Parse operation
            String condition = temp.get("condition") == null ? "" : temp.get("condition").textValue();
            // Parse operation
            String operation = temp.get("operation") == null ? "" : temp.get("operation").textValue();
            // Is active
            boolean redirectActive = true;
            if (temp.get("is_active") != null) {
                // Parse is_active
                redirectActive = temp.get("is_active").asBoolean();
            }
            CallnoModification redirect = null;
            if (redirectType.equalsIgnoreCase("PREPROCESS")) {
                redirect = new PreprocessingRedirect();
            } else if (redirectType.equalsIgnoreCase("NOTFOUND")) {
                redirect = new NotFoundRedirect();
            } else {
                continue;
            }
            redirect.setId(redirectId);
            redirect.setCondition(condition);
            redirect.setOperation(operation);
            redirect.setIsActive(redirectActive);
            if (redirectType.equalsIgnoreCase("PREPROCESS")) {
                preprocessingRedirect.add((PreprocessingRedirect) redirect);
            } else if (redirectType.equalsIgnoreCase("NOTFOUND")) {
                notFoundRedirect.add((NotFoundRedirect) redirect);
            }
        }
    }
    // Create new Owner object
    Owner owner = new Owner(code, name);
    // Set values
    owner.setPreprocessingRedirects(preprocessingRedirect);
    owner.setNotFoundRedirects(notFoundRedirect);
    owner.setColor(color);
    owner.setOpacity(opacity);
    owner.setLocatingStrategy(strategy);
    owner.setAllowedIPs(ips);
    if (node.get("exporter_visible") != null && node.get("exporter_visible").booleanValue()) {
        // Parse exporter visible
        owner.setExporterVisible(node.get("exporter_visible").asBoolean());
    }
    // Return Owner
    return owner;
}

From source file:com.wealdtech.jackson.modules.IntervalDeserializer.java

private DateTime deserializeDateTime(final JsonNode node, final String prefix) throws IOException {
    final JsonNode datetimenode = node.get(prefix + "datetime");
    if (datetimenode == null) {
        LOGGER.warn("Attempt to deserialize malformed interval");
        throw new IOException("Invalid interval value");
    }//from w  ww  . j  av a2s.  com
    final String datetime = datetimenode.textValue();
    // Obtain values
    final JsonNode tznode = node.get(prefix + "timezone");
    String timezone = null;
    if (tznode != null) {
        timezone = tznode.textValue();
    }

    DateTime result = null;
    try {
        if ((timezone == null) || ("UTC".equals(timezone))) {
            result = formatter.parseDateTime(datetime).withZone(utczone);
        } else {
            result = formatter.parseDateTime(datetime).withZone(DateTimeZone.forID(timezone));
        }
    } catch (IllegalArgumentException iae) {
        LOGGER.warn("Attempt to deserialize invalid interval {},{}", datetime, timezone);
        throw new IOException("Invalid datetime value", iae);
    }
    return result;
}

From source file:com.netflix.zeno.json.JsonFrameworkDeserializer.java

@Override
public String deserializeString(JsonReadGenericRecord record, String fieldName) {
    JsonNode node = record.getNode().isTextual() ? record.getNode() : getJsonNode(record, fieldName);
    if (node == null)
        return null;
    return node.textValue();
}

From source file:com.github.fge.jsonschema.core.keyword.syntax.checkers.SyntaxCheckersTest.java

@Test(dependsOnMethods = "keywordIsSupportedInThisDictionary", dataProvider = "getPointerTests")
public final void pointerDelegationWorksCorrectly(final JsonNode schema, final ArrayNode expectedPointers)
        throws ProcessingException, JsonPointerException {
    final SchemaTree tree = new CanonicalSchemaTree(SchemaKey.anonymousKey(), schema);

    checker.checkSyntax(pointers, BUNDLE, report, tree);

    final List<JsonPointer> expected = Lists.newArrayList();
    for (final JsonNode node : expectedPointers)
        expected.add(new JsonPointer(node.textValue()));

    assertEquals(pointers, expected);//from  w ww .  jav  a  2s  .  c om
}

From source file:uk.ac.imperial.presage2.db.json.JsonStorage.java

private <T> T returnAsType(JsonNode n, Class<T> type) {
    if (type == String.class)
        return type.cast(n.textValue());
    else if (type == Integer.class || type == Integer.TYPE)
        return type.cast(n.asInt());
    else if (type == Double.class || type == Double.TYPE)
        return type.cast(n.asDouble());
    else if (type == Boolean.class || type == Boolean.TYPE)
        return type.cast(n.asBoolean());
    else if (type == Long.class || type == Long.TYPE)
        return type.cast(n.asLong());

    throw new RuntimeException("Unknown type cast request");
}

From source file:eu.modaclouds.sla.mediator.ViolationSubscriber.java

private String extractOutputMetric(GuaranteeTerm guarantee) {
    String slo = guarantee.getServiceLevelObjetive().getKpitarget().getCustomServiceLevel();

    ObjectMapper mapper = new ObjectMapper();
    String constraint = null;//from  w  w w .  j  ava  2  s. c o m
    JsonNode rootNode = null;
    try {
        rootNode = mapper.readTree(slo);
    } catch (JsonProcessingException e) {
        throw new MediatorException("Error processing slo json", e);
    } catch (IOException e) {
        throw new MediatorException("Error processing slo json", e);
    }
    JsonNode constraintNode = rootNode.path(TemplateGenerator.CONSTRAINT);
    constraint = constraintNode.textValue();

    int pos = constraint.indexOf(' ');
    String violation = constraint.substring(0, pos == -1 ? slo.length() : pos);
    return violation;
}

From source file:org.openecomp.sdnc.dmaapclient.SdncFlatJsonDmaapConsumer.java

public void processMsg(String msg, String mapDirName) throws InvalidMessageException {

    if (msg == null) {
        throw new InvalidMessageException("Null message");
    }//from  w w  w .j a v  a2  s.  com

    ObjectMapper oMapper = new ObjectMapper();
    JsonNode instarRootNode = null;
    ObjectNode sdncRootNode = null;

    String instarMsgName = null;

    try {
        instarRootNode = oMapper.readTree(msg);
    } catch (Exception e) {
        throw new InvalidMessageException("Cannot parse json object", e);
    }

    Iterator<Map.Entry<String, JsonNode>> instarFields = instarRootNode.fields();

    while (instarFields.hasNext()) {
        Map.Entry<String, JsonNode> entry = instarFields.next();

        instarMsgName = entry.getKey();
        instarRootNode = entry.getValue();
        break;
    }

    Map<String, String> fieldMap = loadMap(instarMsgName, mapDirName);

    if (fieldMap == null) {
        throw new InvalidMessageException("Unable to process message - cannot load field mappings");
    }

    if (!fieldMap.containsKey(SDNC_ENDPOINT)) {
        throw new InvalidMessageException("No SDNC endpoint known for message " + instarMsgName);
    }

    String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT);

    sdncRootNode = oMapper.createObjectNode();
    ObjectNode inputNode = oMapper.createObjectNode();

    for (String fromField : fieldMap.keySet()) {

        if (!SDNC_ENDPOINT.equals(fromField)) {
            JsonNode curNode = instarRootNode.get(fromField);
            if (curNode != null) {
                String fromValue = curNode.textValue();

                inputNode.put(fieldMap.get(fromField), fromValue);
            }
        }
    }
    sdncRootNode.put("input", inputNode);

    try {
        String rpcMsgbody = oMapper.writeValueAsString(sdncRootNode);
        String odlUrlBase = getProperty("sdnc.odl.url-base");
        String odlUser = getProperty("sdnc.odl.user");
        String odlPassword = getProperty("sdnc.odl.password");

        if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) {
            SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + sdncEndpoint, odlUser,
                    odlPassword);

            conn.send("POST", "application/json", rpcMsgbody);
        } else {
            LOG.info("POST message body would be:\n" + rpcMsgbody);
        }
    } catch (Exception e) {

    }

}

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

@Test
public void stringToJson() {
    JsonNode converted = converter.fromConnectData(Schema.STRING_SCHEMA, "test-string");
    assertEquals("test-string", converted.textValue());
}

From source file:org.agorava.facebook.impl.GraphApiImpl.java

@SuppressWarnings("unchecked")
private <T> List<T> deserializeDataList(JsonNode jsonNode, final Class<T> elementType) {
    try {/*from w ww  .j  ava2s  .  c  o m*/
        CollectionType listType = TypeFactory.defaultInstance().constructCollectionType(List.class,
                elementType);
        return (List<T>) objectMapper.readValue(jsonNode.textValue(), listType);
    } catch (IOException e) {
        throw new AgoravaException("Error deserializing data from Facebook: " + e.getMessage(), e);
    }
}

From source file:com.liferay.sync.engine.document.library.handler.DownloadFilesHandler.java

@Override
protected void doHandleResponse(HttpResponse httpResponse) throws Exception {

    long syncAccountId = getSyncAccountId();

    final Session session = SessionManager.getSession(syncAccountId);

    Header header = httpResponse.getFirstHeader("Sync-JWT");

    if (header != null) {
        session.addHeader("Sync-JWT", header.getValue());
    }/*from w  w w .  j  a va2  s . c om*/

    Map<String, DownloadFileHandler> handlers = (Map<String, DownloadFileHandler>) getParameterValue(
            "handlers");

    InputStream inputStream = null;

    try {
        HttpEntity httpEntity = httpResponse.getEntity();

        inputStream = new CountingInputStream(httpEntity.getContent()) {

            @Override
            protected synchronized void afterRead(int n) {
                session.incrementDownloadedBytes(n);

                super.afterRead(n);
            }

        };

        inputStream = new RateLimitedInputStream(inputStream, syncAccountId);

        ZipInputStream zipInputStream = new ZipInputStream(inputStream);

        ZipEntry zipEntry = null;

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String zipEntryName = zipEntry.getName();

            if (zipEntryName.equals("errors.json")) {
                JsonNode rootJsonNode = JSONUtil.readTree(new CloseShieldInputStream(zipInputStream));

                Iterator<Map.Entry<String, JsonNode>> fields = rootJsonNode.fields();

                while (fields.hasNext()) {
                    Map.Entry<String, JsonNode> field = fields.next();

                    Handler<Void> handler = handlers.remove(field.getKey());

                    JsonNode valueJsonNode = field.getValue();

                    JsonNode exceptionJsonNode = valueJsonNode.get("exception");

                    handler.handlePortalException(exceptionJsonNode.textValue());
                }

                break;
            }

            DownloadFileHandler downloadFileHandler = handlers.get(zipEntryName);

            if (downloadFileHandler == null) {
                continue;
            }

            SyncFile syncFile = (SyncFile) downloadFileHandler.getParameterValue("syncFile");

            if (downloadFileHandler.isUnsynced(syncFile)) {
                handlers.remove(zipEntryName);

                continue;
            }

            if (_logger.isTraceEnabled()) {
                _logger.trace("Handling response {} file path {}", DownloadFileHandler.class.getSimpleName(),
                        syncFile.getFilePathName());
            }

            try {
                downloadFileHandler.copyFile(syncFile, Paths.get(syncFile.getFilePathName()),
                        new CloseShieldInputStream(zipInputStream), false);
            } catch (Exception e) {
                if (!isEventCancelled()) {
                    _logger.error(e.getMessage(), e);

                    downloadFileHandler.removeEvent();

                    FileEventUtil.downloadFile(getSyncAccountId(), syncFile, false);
                }
            } finally {
                handlers.remove(zipEntryName);

                downloadFileHandler.removeEvent();
            }
        }
    } catch (Exception e) {
        if (!isEventCancelled()) {
            _logger.error(e.getMessage(), e);

            retryEvent();
        }
    } finally {
        StreamUtil.cleanUp(inputStream);
    }
}