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.unboundid.scim2.common.GenericScimResource.java

/**
 * Gets the date represented by the supplied JsonNode.
 *
 * @param node the JsonNode representing the date.
 * @return the date represented by the JsonNode.
 * @throws ScimException thrown if an error occurs.
 *///  w  w  w  .  j av  a 2s.c om
public static Date getDateFromJsonNode(final JsonNode node) throws ScimException {
    return getDateForString(node.textValue());
}

From source file:io.swagger.parser.util.SwaggerDeserializer.java

public Boolean getBoolean(String key, ObjectNode node, boolean required, String location, ParseResult result) {
    Boolean value = null;/* w w  w .  ja  va 2s. c o  m*/
    JsonNode v = node.get(key);
    if (node == null || v == null) {
        if (required) {
            result.missing(location, key);
            result.invalid();
        }
    } else {
        if (v.getNodeType().equals(JsonNodeType.BOOLEAN)) {
            value = v.asBoolean();
        } else if (v.getNodeType().equals(JsonNodeType.STRING)) {
            String stringValue = v.textValue();
            return Boolean.parseBoolean(stringValue);
        }
    }
    return value;
}

From source file:controllers.EntryController.java

@Transactional
@BodyParser.Of(BodyParser.Json.class)
public Result enter() {
    Entry entry = new Entry();
    ArrayList<String> missing = new ArrayList<String>();
    JsonNode json = request().body().asJson();
    Logger.debug("GOT: " + json.toString());
    boolean retServerId = false;
    JsonNode value;
    value = json.findValue("tech_id");
    if (value == null) {
        missing.add("tech_id");
    } else {// w  ww.j  a  v  a2 s.c  o  m
        entry.tech_id = value.intValue();
    }
    value = json.findValue("date");
    if (value == null) {
        missing.add("date");
    } else {
        entry.entry_time = new Date(value.longValue());
    }
    value = json.findValue("server_id");
    if (value != null) {
        entry.id = value.longValue();
        retServerId = true;
        Entry existing;
        if (entry.id > 0) {
            existing = Entry.find.byId(entry.id);
            existing.entry_time = entry.entry_time;
            existing.tech_id = entry.tech_id;
        } else {
            existing = Entry.findByDate(entry.tech_id, entry.entry_time);
        }
        if (existing != null) {
            entry = existing;
        }
    }
    int truck_number;
    String license_plate;
    value = json.findValue("truck_number");
    if (value != null) {
        truck_number = value.intValue();
    } else {
        truck_number = 0;
    }
    value = json.findValue("license_plate");
    if (value != null) {
        license_plate = value.textValue();
    } else {
        license_plate = null;
    }
    if (truck_number == 0 && license_plate == null) {
        missing.add("truck_number");
        missing.add("license_plate");
    } else {
        // Note: I don't call Version.inc(Version.VERSION_TRUCK) intentionally.
        // The reason is that other techs don't need to know about a local techs truck updates.
        Truck truck = Truck.add(truck_number, license_plate, entry.tech_id);
        entry.truck_id = truck.id;
    }
    value = json.findValue("project_id");
    if (value == null) {
        missing.add("project_id");
    } else {
        entry.project_id = value.longValue();
    }
    value = json.findValue("status");
    if (value != null) {
        entry.status = Entry.Status.from(value.textValue());
    }
    value = json.findValue("address_id");
    if (value == null) {
        value = json.findValue("address");
        if (value == null) {
            missing.add("address_id");
        } else {
            String address = value.textValue().trim();
            if (address.length() > 0) {
                try {
                    Company company = Company.parse(address);
                    Company existing = Company.has(company);
                    if (existing != null) {
                        company = existing;
                    } else {
                        company.created_by = entry.tech_id;
                        company.save();
                        Version.inc(Version.VERSION_COMPANY);
                    }
                    entry.company_id = company.id;
                } catch (Exception ex) {
                    return badRequest2("address: " + ex.getMessage());
                }
            } else {
                return badRequest2("address");
            }
        }
    } else {
        entry.company_id = value.longValue();
    }
    value = json.findValue("equipment");
    if (value != null) {
        if (value.getNodeType() != JsonNodeType.ARRAY) {
            Logger.error("Expected array for element 'equipment'");
        } else {
            int collection_id;
            if (entry.equipment_collection_id > 0) {
                collection_id = (int) entry.equipment_collection_id;
                EntryEquipmentCollection.deleteByCollectionId(entry.equipment_collection_id);
            } else {
                collection_id = Version.inc(Version.NEXT_EQUIPMENT_COLLECTION_ID);
            }
            boolean newEquipmentCreated = false;
            Iterator<JsonNode> iterator = value.elements();
            while (iterator.hasNext()) {
                JsonNode ele = iterator.next();
                EntryEquipmentCollection collection = new EntryEquipmentCollection();
                collection.collection_id = (long) collection_id;
                JsonNode subvalue = ele.findValue("equipment_id");
                if (subvalue == null) {
                    subvalue = ele.findValue("equipment_name");
                    if (subvalue == null) {
                        missing.add("equipment_id");
                        missing.add("equipment_name");
                    } else {
                        String name = subvalue.textValue();
                        List<Equipment> equipments = Equipment.findByName(name);
                        Equipment equipment;
                        if (equipments.size() == 0) {
                            equipment = new Equipment();
                            equipment.name = name;
                            equipment.created_by = entry.tech_id;
                            equipment.save();
                        } else {
                            if (equipments.size() > 1) {
                                Logger.error("Too many equipments found with name: " + name);
                            }
                            equipment = equipments.get(0);
                        }
                        collection.equipment_id = equipment.id;
                        newEquipmentCreated = true;
                    }
                } else {
                    collection.equipment_id = subvalue.longValue();
                }
                collection.save();
            }
            entry.equipment_collection_id = collection_id;
            if (newEquipmentCreated) {
                Version.inc(Version.VERSION_EQUIPMENT);
            }
        }
    }
    value = json.findValue("picture");
    if (value != null) {
        if (value.getNodeType() != JsonNodeType.ARRAY) {
            Logger.error("Expected array for element 'picture'");
        } else {
            int collection_id;
            if (entry.picture_collection_id > 0) {
                collection_id = (int) entry.picture_collection_id;
                PictureCollection.deleteByCollectionId(entry.picture_collection_id, null);
            } else {
                collection_id = Version.inc(Version.NEXT_PICTURE_COLLECTION_ID);
            }
            Iterator<JsonNode> iterator = value.elements();
            while (iterator.hasNext()) {
                JsonNode ele = iterator.next();
                PictureCollection collection = new PictureCollection();
                collection.collection_id = (long) collection_id;
                JsonNode subvalue = ele.findValue("note");
                if (subvalue != null) {
                    collection.note = subvalue.textValue();
                }
                subvalue = ele.findValue("filename");
                if (subvalue == null) {
                    missing.add("filename");
                } else {
                    collection.picture = subvalue.textValue();
                    collection.save();
                }
            }
            entry.picture_collection_id = collection_id;
        }
    }
    value = json.findValue("notes");
    if (value != null) {
        if (value.getNodeType() != JsonNodeType.ARRAY) {
            Logger.error("Expected array for element 'notes'");
        } else {
            int collection_id;
            if (entry.note_collection_id > 0) {
                collection_id = (int) entry.note_collection_id;
                EntryNoteCollection.deleteByCollectionId(entry.note_collection_id);
            } else {
                collection_id = Version.inc(Version.NEXT_NOTE_COLLECTION_ID);
            }
            Iterator<JsonNode> iterator = value.elements();
            while (iterator.hasNext()) {
                JsonNode ele = iterator.next();
                EntryNoteCollection collection = new EntryNoteCollection();
                collection.collection_id = (long) collection_id;
                JsonNode subvalue = ele.findValue("id");
                if (subvalue == null) {
                    subvalue = ele.findValue("name");
                    if (subvalue == null) {
                        missing.add("note:id, note:name");
                    } else {
                        String name = subvalue.textValue();
                        List<Note> notes = Note.findByName(name);
                        if (notes == null || notes.size() == 0) {
                            missing.add("note:" + name);
                        } else if (notes.size() > 1) {
                            Logger.error("Too many notes with name: " + name);
                            missing.add("note:" + name);
                        } else {
                            collection.note_id = notes.get(0).id;
                        }
                    }
                } else {
                    collection.note_id = subvalue.longValue();
                }
                subvalue = ele.findValue("value");
                if (value == null) {
                    missing.add("note:value");
                } else {
                    collection.note_value = subvalue.textValue();
                }
                collection.save();
            }
            entry.note_collection_id = collection_id;
        }
    }
    if (missing.size() > 0) {
        return missingRequest(missing);
    }
    if (entry.id != null && entry.id > 0) {
        entry.update();
        Logger.debug("Updated entry " + entry.id);
    } else {
        entry.save();
        Logger.debug("Created new entry " + entry.id);
    }
    long ret_id;
    if (retServerId) {
        ret_id = entry.id;
    } else {
        ret_id = 0;
    }
    return ok(Long.toString(ret_id));
}

From source file:com.okta.tools.awscli.java

private static String ProcessPolicyDocument(String policyDoc) {

    String strRoleToAssume = null;
    try {//from  w  ww.  j a  va  2  s . c  om
        String policyDocClean = URLDecoder.decode(policyDoc, "UTF-8");
        logger.debug("Clean Policy Document: " + policyDocClean);
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            JsonNode rootNode = objectMapper.readTree(policyDocClean);
            JsonNode statement = rootNode.path("Statement");
            logger.debug("Statement node: " + statement.toString());
            JsonNode resource = null;
            if (statement.isArray()) {
                logger.debug("Statement is array");
                for (int i = 0; i < statement.size(); i++) {
                    String action = statement.get(i).path("Action").textValue();
                    if (action != null && action.equals("sts:AssumeRole")) {
                        resource = statement.get(i).path("Resource");
                        logger.debug("Resource node: " + resource.toString());
                        break;
                    }
                }
            } else {
                logger.debug("Statement is NOT array");
                if (statement.get("Action").textValue().equals("sts:AssumeRole")) {
                    resource = statement.path("Resource");
                    logger.debug("Resource node: " + resource.toString());
                }
            }
            if (resource != null) {
                if (resource.isArray()) { //if we're handling a policy with an array of AssumeRole attributes
                    ArrayList<String> lstRoles = new ArrayList<String>();
                    for (final JsonNode node : resource) {
                        lstRoles.add(node.asText());
                    }
                    strRoleToAssume = SelectRole(lstRoles);
                } else {
                    strRoleToAssume = resource.textValue();
                    logger.debug("Role to assume: " + roleToAssume);
                }
            }
        } catch (IOException ioe) {
        }
    } catch (UnsupportedEncodingException uee) {

    }
    return strRoleToAssume;
}

From source file:io.swagger.parser.util.SwaggerDeserializer.java

public Object extension(JsonNode jsonNode) {
    if (jsonNode.getNodeType().equals(JsonNodeType.BOOLEAN)) {
        return jsonNode.asBoolean();
    }//from w ww . java 2s  .c  o m
    if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) {
        return jsonNode.asText();
    }
    if (jsonNode.getNodeType().equals(JsonNodeType.NUMBER)) {
        NumericNode n = (NumericNode) jsonNode;
        if (n.isLong()) {
            return jsonNode.asLong();
        }
        if (n.isInt()) {
            return jsonNode.asInt();
        }
        if (n.isBigDecimal()) {
            return jsonNode.textValue();
        }
        if (n.isBoolean()) {
            return jsonNode.asBoolean();
        }
        if (n.isFloat()) {
            return jsonNode.floatValue();
        }
        if (n.isDouble()) {
            return jsonNode.doubleValue();
        }
        if (n.isShort()) {
            return jsonNode.intValue();
        }
        return jsonNode.asText();
    }
    if (jsonNode.getNodeType().equals(JsonNodeType.ARRAY)) {
        ArrayNode an = (ArrayNode) jsonNode;
        List<Object> o = new ArrayList<Object>();
        for (JsonNode i : an) {
            Object obj = extension(i);
            if (obj != null) {
                o.add(obj);
            }
        }
        return o;
    }
    return jsonNode;
}

From source file:org.apache.parquet.cli.json.AvroJson.java

public static Object convertToAvro(GenericData model, JsonNode datum, Schema schema) {
    if (datum == null) {
        return null;
    }/*from w w w . ja  v  a  2 s.  co  m*/
    switch (schema.getType()) {
    case RECORD:
        RecordException.check(datum.isObject(), "Cannot convert non-object to record: %s", datum);
        Object record = model.newRecord(null, schema);
        for (Schema.Field field : schema.getFields()) {
            model.setField(record, field.name(), field.pos(),
                    convertField(model, datum.get(field.name()), field));
        }
        return record;

    case MAP:
        RecordException.check(datum.isObject(), "Cannot convert non-object to map: %s", datum);
        Map<String, Object> map = Maps.newLinkedHashMap();
        Iterator<Map.Entry<String, JsonNode>> iter = datum.fields();
        while (iter.hasNext()) {
            Map.Entry<String, JsonNode> entry = iter.next();
            map.put(entry.getKey(), convertToAvro(model, entry.getValue(), schema.getValueType()));
        }
        return map;

    case ARRAY:
        RecordException.check(datum.isArray(), "Cannot convert to array: %s", datum);
        List<Object> list = Lists.newArrayListWithExpectedSize(datum.size());
        for (JsonNode element : datum) {
            list.add(convertToAvro(model, element, schema.getElementType()));
        }
        return list;

    case UNION:
        return convertToAvro(model, datum, resolveUnion(datum, schema.getTypes()));

    case BOOLEAN:
        RecordException.check(datum.isBoolean(), "Cannot convert to boolean: %s", datum);
        return datum.booleanValue();

    case FLOAT:
        RecordException.check(datum.isFloat() || datum.isInt(), "Cannot convert to float: %s", datum);
        return datum.floatValue();

    case DOUBLE:
        RecordException.check(datum.isDouble() || datum.isFloat() || datum.isLong() || datum.isInt(),
                "Cannot convert to double: %s", datum);
        return datum.doubleValue();

    case INT:
        RecordException.check(datum.isInt(), "Cannot convert to int: %s", datum);
        return datum.intValue();

    case LONG:
        RecordException.check(datum.isLong() || datum.isInt(), "Cannot convert to long: %s", datum);
        return datum.longValue();

    case STRING:
        RecordException.check(datum.isTextual(), "Cannot convert to string: %s", datum);
        return datum.textValue();

    case ENUM:
        RecordException.check(datum.isTextual(), "Cannot convert to string: %s", datum);
        return model.createEnum(datum.textValue(), schema);

    case BYTES:
        RecordException.check(datum.isBinary(), "Cannot convert to binary: %s", datum);
        try {
            return ByteBuffer.wrap(datum.binaryValue());
        } catch (IOException e) {
            throw new RecordException("Failed to read JSON binary", e);
        }

    case FIXED:
        RecordException.check(datum.isBinary(), "Cannot convert to fixed: %s", datum);
        byte[] bytes;
        try {
            bytes = datum.binaryValue();
        } catch (IOException e) {
            throw new RecordException("Failed to read JSON binary", e);
        }
        RecordException.check(bytes.length < schema.getFixedSize(), "Binary data is too short: %s bytes for %s",
                bytes.length, schema);
        return model.createFixed(null, bytes, schema);

    case NULL:
        return null;

    default:
        // don't use DatasetRecordException because this is a Schema problem
        throw new IllegalArgumentException("Unknown schema type: " + schema);
    }
}

From source file:net.sf.jasperreports.engine.json.expression.filter.evaluation.BasicFilterExpressionEvaluator.java

protected boolean applyOperator(JsonNode valueNode) {
    ValueDescriptor valueDescriptor = expression.getValueDescriptor();
    JsonOperatorEnum operator = expression.getOperator();
    FilterExpression.VALUE_TYPE type = valueDescriptor.getType();

    // do null comparison first
    if (FilterExpression.VALUE_TYPE.NULL.equals(type)) {
        switch (operator) {
        case EQ:/*from   ww  w . j ava 2 s .  com*/
            return valueNode.isNull() || valueNode.isMissingNode();
        case NE:
            return !(valueNode.isNull() || valueNode.isMissingNode());
        }
    } else {
        // compare numbers with numbers
        if (valueNode.isNumber() && (FilterExpression.VALUE_TYPE.INTEGER.equals(type)
                || FilterExpression.VALUE_TYPE.DOUBLE.equals(type))) {

            BigDecimal opRight = new BigDecimal(valueDescriptor.getValue());
            BigDecimal opLeft;

            if (valueNode.isBigDecimal()) {
                opLeft = valueNode.decimalValue();
            } else {
                opLeft = new BigDecimal(valueNode.asText());
            }

            switch (operator) {
            case EQ:
                return opLeft.compareTo(opRight) == 0;
            case NE:
                return opLeft.compareTo(opRight) != 0;
            case GT:
                return opLeft.compareTo(opRight) > 0;
            case GE:
                return opLeft.compareTo(opRight) >= 0;
            case LT:
                return opLeft.compareTo(opRight) < 0;
            case LE:
                return opLeft.compareTo(opRight) <= 0;
            }
        }
        // compare strings with strings
        else if (valueNode.isTextual() && FilterExpression.VALUE_TYPE.STRING.equals(type)) {
            switch (operator) {
            case EQ:
                return valueNode.textValue().equals(valueDescriptor.getValue());
            case NE:
                return !valueNode.textValue().equals(valueDescriptor.getValue());
            case CONTAINS:
                return valueNode.textValue().contains(valueDescriptor.getValue());
            }
        }
        // compare booleans with booleans
        else if (valueNode.isBoolean() && FilterExpression.VALUE_TYPE.BOOLEAN.equals(type)) {
            switch (operator) {
            case EQ:
                return valueNode.booleanValue() == Boolean.parseBoolean(valueDescriptor.getValue());
            case NE:
                return valueNode.booleanValue() != Boolean.parseBoolean(valueDescriptor.getValue());
            }
        }
    }

    return false;
}

From source file:com.appdynamics.analytics.processor.event.ElasticSearchEventService.java

private String find(String field, JsonNode node) throws JsonProcessingException {
    /* 1606 */ String fieldValue = null;
    /* 1607 */ JsonNode fieldNode = node.get(field);
    /* 1608 */ if (fieldNode != null) {
        /* 1609 */ fieldValue = fieldNode.textValue();
        /*      */ }
    /* 1611 */ return fieldValue;
    /*      */ }/*from   ww w .  ja  v  a 2 s. c  o  m*/

From source file:com.appdynamics.analytics.processor.event.ElasticSearchEventService.java

private EventTypeMetaData preProcessBodyNodeAndReturnMetaData(int requestVersion, String accountName,
        String eventType, ObjectNode bodyNode, EventTypeMetaData existingMetaData)
/*      */ {//from w  ww . ja va2s  . c  om
    /* 1347 */ JsonNode meta = bodyNode.remove("metaData");
    /*      */ EventTypeMetaData metaData;
    /* 1349 */ EventTypeMetaData metaData;
    if (meta == null) {
        EventTypeMetaData metaData;
        /* 1350 */ if (existingMetaData != null) {
            /* 1351 */ metaData = existingMetaData;
            /*      */ } else {
            /* 1353 */ metaData = new EventTypeMetaData(accountName, eventType,
                    this.eventServiceConfiguration.getEventTypeMetaDataDefaults());
            /*      */ }
        /*      */ }
    /*      */ else
    /*      */ {
        /* 1358 */ JsonNode dataCapNode = ((ObjectNode) meta).remove("dailyDataCapVolume");
        /* 1359 */ Long dataCapBytes = null;
        /* 1360 */ if (dataCapNode != null) {
            /*      */ try {
                /* 1362 */ dataCapBytes = Long.valueOf(ByteSizes.parseToBytes(dataCapNode.textValue()));
                /*      */ } catch (IllegalArgumentException e) {
                /* 1364 */ log.error(
                        "Could not resolve number of bytes for data cap for account [{}] event type [{}] with body [{}] using default.",
                        new Object[] { accountName, eventType, bodyNode, e });
                /*      */ }
            /*      */ }
        /*      */
        /*      */
        /*      */
        /*      */ try
        /*      */ {
            /* 1372 */ metaData = (EventTypeMetaData) Reader.DEFAULT_JSON_MAPPER.reader(EventTypeMetaData.class)
                    .readValue(meta);
            /* 1373 */ metaData.fill(accountName, eventType,
                    this.eventServiceConfiguration.getEventTypeMetaDataDefaults());
            /* 1374 */ metaData.setMaxDailyDataVolumeBytes(dataCapBytes);
            /*      */ } catch (IOException e) {
            /* 1376 */ throw Throwables.propagate(e);
            /*      */ }
        /*      */ }
    /*      */
    /*      */
    /* 1381 */ if ((bodyNode.get("properties") != null) && (bodyNode.get("properties").size() > 0)) {
        /* 1382 */ boolean shouldDefaultNotAnalyzedStringFields = (existingMetaData == null)
                && (shouldDefaultNotAnalyzedStringFields(requestVersion));
        /*      */
        /* 1384 */ performEventServiceMappingTransformation(bodyNode, shouldDefaultNotAnalyzedStringFields,
                this.eventServiceConfiguration.isAllFieldDisabled());
        /*      */ }
    /*      */
    /*      */
    /* 1388 */ return metaData;
    /*      */ }