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

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

Introduction

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

Prototype

public long asLong() 

Source Link

Usage

From source file:com.turn.shapeshifter.AutoParser.java

/**
 * Reads the value of a JSON node and returns the corresponding Java
 * object./*from   ww w  .j a v a  2  s  . c o  m*/
 *
 * @param jsonNode the node to convert to a Java object
 * @param field the protocol buffer field to which the resulting value will
 * be assigned
 * @param registry used as a source of schemas generated on the fly for
 * sub-objects
 * @return a Java object representing the field's value
 * @throws ParsingException
 * @throws UnmappableValueException in case the JSON value node cannot be
 * converted
 * to a Java object that could be assigned to {@code field}
 */
private Object parseValue(JsonNode jsonNode, FieldDescriptor field, ReadableSchemaRegistry registry)
        throws ParsingException {
    Object value = null;
    switch (field.getType()) {
    case BOOL:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_BOOLEAN_TOKENS);
        value = Boolean.valueOf(jsonNode.asBoolean());
        break;
    case BYTES:
        break;
    case DOUBLE:
        value = new Double(jsonNode.asDouble());
        break;
    case ENUM:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_ENUM_TOKENS);
        String enumValue = jsonNode.asText();
        String convertedValue = AutoSchema.JSON_ENUM_CASE_FORMAT.to(AutoSchema.PROTO_ENUM_CASE_FORMAT,
                enumValue);
        value = field.getEnumType().findValueByName(convertedValue);
        break;
    case FLOAT:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_FLOAT_TOKENS);
        value = new Float(jsonNode.asDouble());
        break;
    case GROUP:
        break;
    case FIXED32:
    case INT32:
    case SFIXED32:
    case SINT32:
    case UINT32:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_INTEGER_TOKENS);
        value = new Integer(jsonNode.asInt());
        break;
    case FIXED64:
    case INT64:
    case SFIXED64:
    case SINT64:
    case UINT64:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_INTEGER_TOKENS);
        value = new Long(jsonNode.asLong());
        break;
    case MESSAGE:
        if (!jsonNode.isObject()) {
            throw new IllegalArgumentException(
                    "Expected to parse object, found value of type " + jsonNode.asToken());
        }
        if (jsonNode.size() != 0) {
            try {
                value = registry.get(field.getMessageType()).getParser().parse(jsonNode, registry);
            } catch (SchemaObtentionException soe) {
                throw new ParsingException(soe);
            }
        }
        break;
    case STRING:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_STRING_TOKENS);
        value = jsonNode.asText();
        break;
    default:
        break;
    }
    return value;
}

From source file:org.waarp.openr66.protocol.http.rest.handler.DbTaskRunnerR66RestMethodHandler.java

@Override
protected DbPreparedStatement getPreparedStatement(HttpRestHandler handler, RestArgument arguments,
        RestArgument result, Object body)
        throws HttpIncorrectRequestException, HttpInvalidAuthenticationException {
    ObjectNode arg = arguments.getUriArgs().deepCopy();
    arg.setAll(arguments.getBody());//from   w  w w.j  a va  2  s  . c o m
    int limit = arg.path(FILTER_ARGS.LIMIT.name()).asInt(0);
    boolean orderBySpecialId = arg.path(FILTER_ARGS.ORDERBYID.name()).asBoolean(false);
    JsonNode node = arg.path(FILTER_ARGS.STARTID.name());
    String startid = null;
    if (!node.isMissingNode()) {
        startid = node.asText();
    }
    if (startid == null || startid.isEmpty()) {
        startid = null;
    }
    node = arg.path(FILTER_ARGS.STOPID.name());
    String stopid = null;
    if (!node.isMissingNode()) {
        stopid = node.asText();
    }
    if (stopid == null || stopid.isEmpty()) {
        stopid = null;
    }
    String rule = arg.path(FILTER_ARGS.IDRULE.name()).asText();
    if (rule == null || rule.isEmpty()) {
        rule = null;
    }
    String req = arg.path(FILTER_ARGS.PARTNER.name()).asText();
    if (req == null || req.isEmpty()) {
        req = null;
    }
    String owner = arg.path(DbTaskRunner.Columns.OWNERREQ.name()).asText();
    if (owner == null || owner.isEmpty()) {
        owner = null;
    }
    boolean pending = arg.path(FILTER_ARGS.PENDING.name()).asBoolean(false);
    boolean transfer = arg.path(FILTER_ARGS.INTRANSFER.name()).asBoolean(false);
    boolean error = arg.path(FILTER_ARGS.INERROR.name()).asBoolean(false);
    boolean done = arg.path(FILTER_ARGS.DONE.name()).asBoolean(false);
    boolean all = arg.path(FILTER_ARGS.ALLSTATUS.name()).asBoolean(false);
    Timestamp start = null;
    node = arg.path(FILTER_ARGS.STARTTRANS.name());
    if (!node.isMissingNode()) {
        long val = node.asLong();
        if (val == 0) {
            DateTime received = DateTime.parse(node.asText());
            val = received.getMillis();
        }
        start = new Timestamp(val);
    }
    Timestamp stop = null;
    node = arg.path(FILTER_ARGS.STOPTRANS.name());
    if (!node.isMissingNode()) {
        long val = node.asLong();
        if (val == 0) {
            DateTime received = DateTime.parse(node.asText());
            val = received.getMillis();
        }
        stop = new Timestamp(val);
    }
    try {
        return DbTaskRunner.getFilterPrepareStatement(handler.getDbSession(), limit, orderBySpecialId, startid,
                stopid, start, stop, rule, req, pending, transfer, error, done, all, owner);
    } catch (WaarpDatabaseNoConnectionException e) {
        throw new HttpIncorrectRequestException("Issue while reading from database", e);
    } catch (WaarpDatabaseSqlException e) {
        throw new HttpIncorrectRequestException("Issue while reading from database", e);
    }
}

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

public Object extension(JsonNode jsonNode) {
    if (jsonNode.getNodeType().equals(JsonNodeType.BOOLEAN)) {
        return jsonNode.asBoolean();
    }/*  w  ww.j  a va 2 s.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:com.turn.shapeshifter.SchemaParser.java

/**
 * Reads the value of a JSON node and returns the corresponding Java object.
 *
 * @param jsonNode the node to convert to a Java object
 * @param field the protocol buffer field to which the resulting value will be assigned
 * @param registry a schema registry in which enclosed message fields are expected to
 * be defined/*  ww w  .  j  a va  2 s .c  o  m*/
 * @return a Java object representing the field's value
 * @throws ParsingException
 * @throws
 * @throws UnmappableValueException in case the JSON value node cannot be converted
 * to a Java object that could be assigned to {@code field}
 */
private Object parseValue(JsonNode jsonNode, FieldDescriptor field, ReadableSchemaRegistry registry)
        throws ParsingException {
    Object value = null;
    if (schema.getTransforms().containsKey(field.getName())) {
        return schema.getTransforms().get(field.getName()).parse(jsonNode);
    }
    switch (field.getType()) {
    case BOOL:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_BOOLEAN_TOKENS);
        value = Boolean.valueOf(jsonNode.asBoolean());
        break;
    case BYTES:
        break;
    case DOUBLE:
        value = new Double(jsonNode.asDouble());
        break;
    case ENUM:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_ENUM_TOKENS);
        String enumValue = schema.getEnumCaseFormat().to(NamedSchema.PROTO_ENUM_CASE_FORMAT, jsonNode.asText());
        value = field.getEnumType().findValueByName(enumValue);
        break;
    case FLOAT:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_FLOAT_TOKENS);
        value = new Float(jsonNode.asDouble());
        break;
    case GROUP:
        break;
    case FIXED32:
    case INT32:
    case SFIXED32:
    case SINT32:
    case UINT32:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_INTEGER_TOKENS);
        value = new Integer(jsonNode.asInt());
        break;
    case FIXED64:
    case INT64:
    case SFIXED64:
    case SINT64:
    case UINT64:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_INTEGER_TOKENS);
        value = new Long(jsonNode.asLong());
        break;
    case MESSAGE:
        if (!jsonNode.isObject()) {
            throw new IllegalArgumentException(
                    "Expected to parse object, found value of type " + jsonNode.asToken());
        }
        Schema subSchema = null;
        if (schema.getSubObjectsSchemas().containsKey(field.getName())) {
            String schemaName = schema.getSubObjectsSchemas().get(field.getName());
            if (registry.contains(schemaName)) {
                subSchema = registry.get(schemaName);
            } else {
                throw new IllegalStateException();
            }
        } else {
            try {
                subSchema = registry.get(field.getMessageType());
            } catch (SchemaObtentionException soe) {
                throw new ParsingException(soe);
            }
        }
        value = subSchema.getParser().parse(jsonNode, registry);
        break;
    case STRING:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_STRING_TOKENS);
        value = jsonNode.asText();
        break;
    default:
        break;
    }
    return value;
}

From source file:org.apache.drill.exec.ref.rse.JSONRecordReader.java

private DataValue convert(JsonNode node) {
    if (node == null || node.isNull() || node.isMissingNode()) {
        return DataValue.NULL_VALUE;
    } else if (node.isArray()) {
        SimpleArrayValue arr = new SimpleArrayValue(node.size());
        for (int i = 0; i < node.size(); i++) {
            arr.addToArray(i, convert(node.get(i)));
        }//from w w  w  . j a va 2  s.  c  o m
        return arr;
    } else if (node.isObject()) {
        SimpleMapValue map = new SimpleMapValue();
        String name;
        for (Iterator<String> iter = node.fieldNames(); iter.hasNext();) {
            name = iter.next();
            map.setByName(name, convert(node.get(name)));
        }
        return map;
    } else if (node.isBinary()) {
        try {
            return new BytesScalar(node.binaryValue());
        } catch (IOException e) {
            throw new RuntimeException("Failure converting binary value.", e);
        }
    } else if (node.isBigDecimal()) {
        throw new UnsupportedOperationException();
        //      return new BigDecimalScalar(node.decimalValue());
    } else if (node.isBigInteger()) {
        throw new UnsupportedOperationException();
        //      return new BigIntegerScalar(node.bigIntegerValue());
    } else if (node.isBoolean()) {
        return new BooleanScalar(node.asBoolean());
    } else if (node.isFloatingPointNumber()) {
        if (node.isBigDecimal()) {
            throw new UnsupportedOperationException();
            //        return new BigDecimalScalar(node.decimalValue());
        } else {
            return new DoubleScalar(node.asDouble());
        }
    } else if (node.isInt()) {
        return new IntegerScalar(node.asInt());
    } else if (node.isLong()) {
        return new LongScalar(node.asLong());
    } else if (node.isTextual()) {
        return new StringScalar(node.asText());
    } else {
        throw new UnsupportedOperationException(String.format("Don't know how to convert value of type %s.",
                node.getClass().getCanonicalName()));
    }

}

From source file:org.opendaylight.groupbasedpolicy.renderer.opflex.mit.MitLib.java

/**
 * Take the {@link ManagedObject} and deserialize the properties
 * into a concrete type to be used by the renderer. It also
 * adds URIs for any children that are referenced in the
 * properties to the MO's "children" array.
 *
 * @param mo/* w  w w.j a v  a 2s .co  m*/
 */
public PolicyObjectInstance deserializeMoProperties(ManagedObject mo, OpflexMit mit) {

    /*
     * The subject gives us the class to use for the schema
     */
    PolicyClassInfo pci = mit.getClass(mo.getSubject());

    // sanity checks
    if (pci == null)
        return null;

    PolicyObjectInstance poi = new PolicyObjectInstance(pci.getClassId());

    if (mo.getProperties() == null)
        return poi;

    for (ManagedObject.Property prop : mo.getProperties()) {
        PolicyPropertyInfo ppi = pci.getProperty(prop.getName());
        if ((ppi == null) || (prop.getData() == null))
            continue;

        JsonNode node = prop.getData();

        boolean vectored = false;
        if (ppi.getPropCardinality().equals(PolicyPropertyInfo.PropertyCardinality.VECTOR)) {
            vectored = true;
        }
        switch (ppi.getType()) {
        case STRING:
            if (vectored == true) {
                if (!node.isArray())
                    continue;

                List<String> sl = new ArrayList<String>();
                for (int i = 0; i < node.size(); i++) {
                    JsonNode jn = node.get(i);
                    if (!jn.isTextual())
                        continue;

                    sl.add(jn.asText());
                }
                poi.setString(ppi.getPropId(), sl);
            } else {
                if (!node.isTextual())
                    continue;

                poi.setString(ppi.getPropId(), node.asText());
            }
            break;

        case U64:
            if (vectored == true) {
                if (!node.isArray())
                    continue;

                List<BigInteger> bil = new ArrayList<BigInteger>();

                for (int i = 0; i < node.size(); i++) {
                    JsonNode jn = node.get(i);
                    if (!jn.isBigInteger())
                        continue;

                    bil.add(new BigInteger(jn.asText()));
                }
                poi.setUint64(ppi.getPropId(), bil);
            } else {
                if (!node.isBigInteger())
                    continue;

                poi.setUint64(ppi.getPropId(), new BigInteger(node.asText()));
            }
            break;

        case S64:
            if (vectored == true) {
                if (!node.isArray())
                    continue;

                List<Long> ll = new ArrayList<Long>();

                for (int i = 0; i < node.size(); i++) {
                    JsonNode jn = node.get(i);

                    if (!jn.isBigInteger())
                        continue;

                    ll.add(jn.asLong());
                }
                poi.setInt64(ppi.getPropId(), ll);
            } else {
                if (!node.isBigInteger())
                    continue;

                poi.setInt64(ppi.getPropId(), node.asLong());
            }
            break;

        case REFERENCE:
            if (vectored == true) {
                if (!node.isArray())
                    continue;

                List<PolicyObjectInstance.PolicyReference> prl = new ArrayList<PolicyObjectInstance.PolicyReference>();

                for (int i = 0; i < node.size(); i++) {
                    JsonNode jn = node.get(i);
                    PolicyObjectInstance.PolicyReference pr = deserializeMoPropertyRef(jn, mit);
                    if (pr == null)
                        continue;

                    prl.add(pr);
                }
                poi.setReference(ppi.getPropId(), prl);
            } else {
                PolicyObjectInstance.PolicyReference pr = deserializeMoPropertyRef(node, mit);
                if (pr == null)
                    continue;

                poi.setReference(ppi.getPropId(), pr);
            }
            break;

        case ENUM8:
        case ENUM16:
        case ENUM32:
        case ENUM64:
            if (vectored == true) {
                if (!node.isArray())
                    continue;

                List<BigInteger> bil = new ArrayList<BigInteger>();

                for (int i = 0; i < node.size(); i++) {
                    JsonNode jn = node.get(i);
                    if (!jn.isTextual())
                        continue;
                    BigInteger bi = deserializeMoPropertyEnum(node, ppi);

                    bil.add(bi);
                }
                poi.setUint64(ppi.getPropId(), bil);
            } else {
                if (!node.isTextual())
                    continue;

                BigInteger bi = deserializeMoPropertyEnum(node, ppi);
                poi.setUint64(ppi.getPropId(), bi);
            }
            break;

        case MAC:
            if (vectored == true) {
                if (!node.isArray())
                    continue;

                List<MacAddress> ml = new ArrayList<MacAddress>();

                for (int i = 0; i < node.size(); i++) {
                    JsonNode jn = node.get(i);

                    if (!jn.isTextual())
                        continue;

                    ml.add(new MacAddress(jn.asText()));
                }
                poi.setMacAddress(ppi.getPropId(), ml);
            } else {
                if (!node.isTextual())
                    continue;

                poi.setMacAddress(ppi.getPropId(), new MacAddress(node.asText()));
            }
            break;

        case COMPOSITE:

        }

    }

    return poi;
}

From source file:com.turn.shapeshifter.NamedSchemaParser.java

/**
 * Reads the value of a JSON node and returns the corresponding Java object.
 *
 * @param jsonNode the node to convert to a Java object
 * @param field the protocol buffer field to which the resulting value will be assigned
 * @param registry a schema registry in which enclosed message fields are expected to
 * be defined//from w  w  w  . j  a v  a  2  s . c  om
 * @return a Java object representing the field's value
 * @throws ParsingException In case the JSON node cannot be parsed
 * @throws UnmappableValueException in case the JSON value node cannot be converted
 * to a Java object that could be assigned to {@code field}
 */
private Object parseValue(JsonNode jsonNode, FieldDescriptor field, ReadableSchemaRegistry registry)
        throws ParsingException {
    Object value = null;
    if (schema.getTransforms().containsKey(field.getName())) {
        return schema.getTransforms().get(field.getName()).parse(jsonNode);
    }
    switch (field.getType()) {
    case BOOL:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_BOOLEAN_TOKENS);
        value = Boolean.valueOf(jsonNode.asBoolean());
        break;
    case BYTES:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_STRING_TOKENS);
        String content = jsonNode.asText();
        byte[] bytes = new byte[content.length()];
        for (int i = 0; i < content.length(); i++) {
            bytes[i] = (byte) content.charAt(i);
        }
        value = ByteString.copyFrom(bytes);
        break;
    case DOUBLE:
        value = new Double(jsonNode.asDouble());
        break;
    case ENUM:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_ENUM_TOKENS);
        String enumValue = schema.getEnumCaseFormat().to(NamedSchema.PROTO_ENUM_CASE_FORMAT, jsonNode.asText());
        value = field.getEnumType().findValueByName(enumValue);
        break;
    case FLOAT:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_FLOAT_TOKENS);
        value = new Float(jsonNode.asDouble());
        break;
    case GROUP:
        break;
    case FIXED32:
    case INT32:
    case SFIXED32:
    case SINT32:
    case UINT32:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_INTEGER_TOKENS);
        value = new Integer(jsonNode.asInt());
        break;
    case FIXED64:
    case INT64:
    case SFIXED64:
    case SINT64:
    case UINT64:
        if (schema.getSurfaceLongsAsStrings()) {
            JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_STRING_TOKENS);
            String longValue = jsonNode.asText();
            value = Long.parseLong(longValue);
        } else {
            JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_INTEGER_TOKENS);
            value = new Long(jsonNode.asLong());
        }
        break;
    case MESSAGE:
        if (!jsonNode.isObject()) {
            throw new IllegalArgumentException(
                    "Expected to parse object, found value of type " + jsonNode.asToken());
        }
        Schema subSchema = null;
        if (schema.getSubObjectsSchemas().containsKey(field.getName())) {
            String schemaName = schema.getSubObjectsSchemas().get(field.getName());
            if (registry.contains(schemaName)) {
                subSchema = registry.get(schemaName);
            } else {
                throw new IllegalStateException();
            }
        } else {
            try {
                subSchema = registry.get(field.getMessageType());
            } catch (SchemaObtentionException soe) {
                throw new ParsingException(soe);
            }
        }
        value = subSchema.getParser().parse(jsonNode, registry);
        break;
    case STRING:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_STRING_TOKENS);
        value = jsonNode.asText();
        break;
    default:
        break;
    }
    return value;
}

From source file:org.waarp.openr66.database.data.DbTaskRunner.java

@Override
public void setFromJson(ObjectNode source, boolean ignorePrimaryKey) throws WaarpDatabaseSqlException {
    for (Columns column : Columns.values()) {
        if (column == Columns.UPDATEDINFO) {
            continue;
        }//from   w ww . j ava  2  s  .  c o m
        JsonNode item = source.get(column.name());
        if (item != null && !item.isMissingNode() && !item.isNull()) {
            switch (column) {
            case BLOCKSZ:
                blocksize = item.asInt();
                break;
            case FILEINFO:
                fileInformation = item.asText();
                break;
            case FILENAME:
                filename = item.asText();
                break;
            case GLOBALLASTSTEP:
                globallaststep = item.asInt();
                break;
            case GLOBALSTEP:
                globalstep = item.asInt();
                break;
            case IDRULE:
                ruleId = item.asText();
                break;
            case INFOSTATUS:
                infostatus = ErrorCode.getFromCode(item.asText());
                break;
            case ISMOVED:
                isFileMoved = item.asBoolean();
                break;
            case MODETRANS:
                mode = item.asInt();
                break;
            case ORIGINALNAME:
                originalFilename = item.asText();
                break;
            case OWNERREQ:
                if (!ignorePrimaryKey) {
                    ownerRequest = item.asText();
                    if (ownerRequest == null || ownerRequest.isEmpty()) {
                        ownerRequest = Configuration.configuration.HOST_ID;
                    }
                }
                break;
            case RANK:
                rank = item.asInt();
                break;
            case REQUESTED:
                if (!ignorePrimaryKey) {
                    requestedHostId = item.asText();
                }
                break;
            case REQUESTER:
                if (!ignorePrimaryKey) {
                    requesterHostId = item.asText();
                }
                break;
            case RETRIEVEMODE:
                isSender = item.asBoolean();
                break;
            case SPECIALID:
                if (!ignorePrimaryKey) {
                    specialId = item.asLong();
                }
                break;
            case STARTTRANS:
                long msstart = item.asLong();
                if (msstart == 0) {
                    start = new Timestamp(System.currentTimeMillis());
                } else {
                    start = new Timestamp(msstart);
                }
                break;
            case STEP:
                step = source.path(Columns.STEP.name()).asInt();
                break;
            case STEPSTATUS:
                status = ErrorCode.getFromCode(item.asText());
                break;
            case STOPTRANS:
                msstart = item.asLong();
                if (msstart == 0) {
                    stop = new Timestamp(System.currentTimeMillis());
                } else {
                    stop = new Timestamp(msstart);
                }
                break;
            case TRANSFERINFO:
                transferInformation = item.asText();
                break;
            case UPDATEDINFO:
                // ignore
                break;
            default:
                break;

            }
        }
    }
    JsonNode node = source.path(JSON_RESCHEDULE);
    if (!node.isMissingNode() || !node.isNull()) {
        rescheduledTransfer = node.asBoolean(false);
    }
    node = source.path(JSON_THROUGHMODE);
    if (!node.isMissingNode() || !node.isNull()) {
        if (RequestPacket.isRecvMode(mode)) {
            isRecvThrough = node.asBoolean();
        } else {
            isSendThrough = node.asBoolean();
        }
    }
    node = source.path(JSON_ORIGINALSIZE);
    if (!node.isMissingNode() || !node.isNull()) {
        originalSize = node.asLong(-1);
    }
    isSaved = false;
    try {
        this.rule = new DbRule(dbSession, ruleId);
        if (mode != rule.mode) {
            if (RequestPacket.isMD5Mode(mode)) {
                mode = RequestPacket.getModeMD5(rule.mode);
            } else {
                mode = rule.mode;
            }
        }
    } catch (WaarpDatabaseException e) {
        // ignore
        this.rule = null;
    }
    if (filename == null || filename.isEmpty() || ruleId == null || ruleId.isEmpty() || ownerRequest == null
            || ownerRequest.isEmpty() || requestedHostId == null || requestedHostId.isEmpty()
            || requestedHostId == null || requestedHostId.isEmpty()) {
        throw new WaarpDatabaseSqlException("Not enough argument to create the object");
    }
    checkThroughMode();
    setToArray();
}

From source file:org.wrml.runtime.schema.generator.SchemaGenerator.java

private Value generateValue(final JsonSchema jsonSchema, final JsonSchema.Property property)
        throws SchemaGeneratorException {

    if (property == null) {
        throw new SchemaGeneratorException("Failed to generate a Value", null, this);
    }//from w  w w  .  j  a v a  2 s .co  m

    final URI schemaUri = jsonSchema.getId();
    if (schemaUri == null) {
        throw new SchemaGeneratorException("Failed to generate a Value", null, this);
    }

    final JsonType jsonType = property.getJsonType();
    if (jsonType == null) {
        throw new SchemaGeneratorException("Failed to generate a Value", null, this);
    }

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();

    final ValueType valueType = getValueType(jsonType);
    Value value = null;

    switch (valueType) {

    case Boolean: {
        final BooleanValue booleanValue = context.newModel(BooleanValue.class);

        final JsonNode defaultNode = property.getValueNode(PropertyType.Default);
        if (defaultNode != null) {
            booleanValue.setDefault(defaultNode.asBoolean());
        }

        value = booleanValue;
        break;
    }
    case Date: {
        break;
    }
    case Double: {
        final DoubleValue doubleValue = context.newModel(DoubleValue.class);

        final JsonNode defaultNode = property.getValueNode(PropertyType.Default);
        if (defaultNode != null) {
            doubleValue.setDefault(defaultNode.asDouble());
        }

        final JsonNode maximumNode = property.getValueNode(PropertyType.Maximum);
        if (maximumNode != null) {
            doubleValue.setMaximum(maximumNode.asDouble());
        }

        final JsonNode minimumNode = property.getValueNode(PropertyType.Minimum);
        if (minimumNode != null) {
            doubleValue.setMinimum(minimumNode.asDouble());
        }

        value = doubleValue;
        break;
    }
    case Integer: {
        final IntegerValue integerValue = context.newModel(IntegerValue.class);

        final JsonNode defaultNode = property.getValueNode(PropertyType.Default);
        if (defaultNode != null) {
            integerValue.setDefault(defaultNode.asInt());
        }

        final JsonNode divisibleByNode = property.getValueNode(PropertyType.DivisibleBy);
        if (divisibleByNode != null) {
            integerValue.setDivisibleBy(divisibleByNode.asInt());
        }

        final JsonNode multipleOfNode = property.getValueNode(PropertyType.MultipleOf);
        if (multipleOfNode != null) {
            integerValue.setDivisibleBy(multipleOfNode.asInt());
        }

        final JsonNode maximumNode = property.getValueNode(PropertyType.Maximum);
        if (maximumNode != null) {
            integerValue.setMaximum(maximumNode.asInt());
        }

        final JsonNode minimumNode = property.getValueNode(PropertyType.Minimum);
        if (minimumNode != null) {
            integerValue.setMinimum(minimumNode.asInt());
        }

        value = integerValue;
        break;
    }
    case Link:
        // NOTE: Falling through the Link switch case on purpose to treat same as Model
        // TODO: Revisit this design.
    case Model: {

        final ModelValue modelValue = context.newModel(ModelValue.class);
        final JsonSchemaLoader jsonSchemaLoader = schemaLoader.getJsonSchemaLoader();
        final JsonSchema modelJsonSchema;

        final URI baseSchemaUri;
        final JsonNode schemaIdNode = property.getValueNode(PropertyType.Id);
        if (schemaIdNode != null) {
            baseSchemaUri = schemaLoader.getDocumentSchemaUri();

            final URI modelSchemaUri = property.getValue(PropertyType.Id);
            if (modelSchemaUri != schemaUri) {
                try {
                    modelJsonSchema = jsonSchemaLoader.load(modelSchemaUri);
                } catch (final IOException e) {
                    throw new SchemaGeneratorException(e.getMessage(), e, this);
                }
            } else {
                modelJsonSchema = jsonSchema;
            }
        } else {

            baseSchemaUri = schemaLoader.getEmbeddedSchemaUri();

            String modelSchemaUriString = schemaUri.toString();

            if (modelSchemaUriString.endsWith(".json")) {
                modelSchemaUriString = modelSchemaUriString.substring(0,
                        modelSchemaUriString.length() - ".json".length());
            }

            int innerClassNumber = 0;

            if (_InnerSchemaCountMap.containsKey(schemaUri)) {
                innerClassNumber = _InnerSchemaCountMap.get(schemaUri);
            }

            innerClassNumber++;

            _InnerSchemaCountMap.put(schemaUri, innerClassNumber);

            final String annonymousInnerSchemaName = ANNONYMOUS_INNER_SCHEMA_PREFIX
                    + String.valueOf(innerClassNumber);

            modelSchemaUriString = modelSchemaUriString.concat(annonymousInnerSchemaName);

            final ObjectNode propertyNode = property.getPropertyNode();
            propertyNode.put(PropertyType.Id.getName(), modelSchemaUriString);

            final URI modelSchemaUri = URI.create(modelSchemaUriString);

            modelJsonSchema = jsonSchemaLoader.load(propertyNode, modelSchemaUri);
        }

        if (modelJsonSchema != jsonSchema) {

            schemaLoader.load(modelJsonSchema, baseSchemaUri);
        }

        modelValue.setModelSchemaUri(modelJsonSchema.getId());

        value = modelValue;
        break;
    }
    case List: {
        final ListValue listValue = context.newModel(ListValue.class);

        final JsonNode uniqueItemsNode = property.getValueNode(PropertyType.UniqueItems);
        if (uniqueItemsNode != null) {
            listValue.setElementUniquenessConstrained(uniqueItemsNode.asBoolean());
        }

        final JsonNode maxItemsNode = property.getValueNode(PropertyType.MaxItems);
        if (maxItemsNode != null) {
            listValue.setMaximumSize(maxItemsNode.asInt());
        }

        final JsonNode minItemsNode = property.getValueNode(PropertyType.MinItems);
        if (minItemsNode != null) {
            listValue.setMinimumSize(minItemsNode.asInt());
        }

        final JsonNode itemsNode = property.getValueNode(PropertyType.Items);
        ObjectNode itemNode = null;
        if (itemsNode instanceof ObjectNode) {
            itemNode = (ObjectNode) itemsNode;

        } else if (itemsNode instanceof ArrayNode) {

            final ArrayNode itemsArrayNode = (ArrayNode) itemsNode;
            if (itemsArrayNode.has(0)) {
                itemNode = (ObjectNode) itemsArrayNode.get(0);
            }
        }

        if (itemNode != null) {
            Property itemsProperty;
            try {
                itemsProperty = new Property(jsonSchema, PropertyType.Items.getName(), itemNode);
                final Value elementValue = generateValue(jsonSchema, itemsProperty);
                final Slot elementSlot = context.newModel(Slot.class);
                elementSlot.setName("E");
                elementSlot.setValue(elementValue);
                listValue.setElementSlot(elementSlot);
            } catch (final IOException e) {
                throw new SchemaGeneratorException(e.getMessage(), e, this);
            }
        }

        value = listValue;
        break;
    }
    case Long: {
        final LongValue longValue = context.newModel(LongValue.class);

        final JsonNode defaultNode = property.getValueNode(PropertyType.Default);
        if (defaultNode != null) {
            longValue.setDefault(defaultNode.asLong());
        }

        final JsonNode divisibleByNode = property.getValueNode(PropertyType.DivisibleBy);
        if (divisibleByNode != null) {
            longValue.setDivisibleBy(divisibleByNode.asLong());
        }

        final JsonNode multipleOfNode = property.getValueNode(PropertyType.MultipleOf);
        if (multipleOfNode != null) {
            longValue.setDivisibleBy(multipleOfNode.asLong());
        }

        final JsonNode maximumNode = property.getValueNode(PropertyType.Maximum);
        if (maximumNode != null) {
            longValue.setMaximum(maximumNode.asLong());
        }

        final JsonNode minimumNode = property.getValueNode(PropertyType.Minimum);
        if (minimumNode != null) {
            longValue.setMinimum(minimumNode.asLong());
        }

        value = longValue;
        break;
    }
    case Native: {
        break;
    }
    case SingleSelect: {
        final SingleSelectValue singleSelectValue = context.newModel(SingleSelectValue.class);
        value = singleSelectValue;
        break;
    }
    case Text: {
        final TextValue textValue = context.newModel(TextValue.class);

        final JsonNode defaultNode = property.getValueNode(PropertyType.Default);
        if (defaultNode != null) {
            textValue.setDefault(defaultNode.asText());
        }

        final JsonNode maxLengthNode = property.getValueNode(PropertyType.MaxLength);
        if (maxLengthNode != null) {
            textValue.setMaximumLength(maxLengthNode.asInt());
        }

        final JsonNode minLengthNode = property.getValueNode(PropertyType.MinLength);
        if (minLengthNode != null) {
            textValue.setMinimumLength(minLengthNode.asInt());
        }

        final JsonNode formatNode = property.getValueNode(PropertyType.Format);
        if (formatNode != null) {

            final String formatKeyword = formatNode.asText();
            final JsonStringFormat jsonStringFormat = JsonStringFormat.forKeyword(formatKeyword);
            if (jsonStringFormat != null) {
                final Class<?> formatJavaType = jsonStringFormat.getJavaType();
                final SyntaxLoader syntaxLoader = context.getSyntaxLoader();
                final URI syntaxUri = syntaxLoader.getSyntaxUri(formatJavaType);
                textValue.setSyntaxUri(syntaxUri);
            }
        }

        textValue.getDisallowedValues();

        value = textValue;

        break;
    }
    default: {
        break;
    }
    }

    if (value instanceof MaybeRequired) {
        final JsonNode requiredNode = property.getValueNode(PropertyType.Required);
        if (requiredNode != null) {
            ((MaybeRequired) value).setRequired(requiredNode.asBoolean());
        }
    }

    if (value instanceof NumericValue) {
        final NumericValue numericValue = (NumericValue) value;

        final JsonNode exclusiveMaximumNode = property.getValueNode(PropertyType.ExclusiveMaximum);
        if (exclusiveMaximumNode != null) {
            numericValue.setExclusiveMaximum(exclusiveMaximumNode.asBoolean());
        }

        final JsonNode exclusiveMinimumNode = property.getValueNode(PropertyType.ExclusiveMinimum);
        if (exclusiveMinimumNode != null) {
            numericValue.setExclusiveMinimum(exclusiveMinimumNode.asBoolean());
        }
    }

    return value;

}

From source file:org.apache.syncope.core.misc.serialization.AttributeDeserializer.java

@Override
public Attribute deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException {

    ObjectNode tree = jp.readValueAsTree();

    String name = tree.get("name").asText();

    List<Object> values = new ArrayList<Object>();
    for (Iterator<JsonNode> itor = tree.get("value").iterator(); itor.hasNext();) {
        JsonNode node = itor.next();
        if (node.isNull()) {
            values.add(null);/*from  ww w. java 2s  .  c o  m*/
        } else if (node.isObject()) {
            values.add(((ObjectNode) node).traverse(jp.getCodec()).readValueAs(GuardedString.class));
        } else if (node.isBoolean()) {
            values.add(node.asBoolean());
        } else if (node.isDouble()) {
            values.add(node.asDouble());
        } else if (node.isLong()) {
            values.add(node.asLong());
        } else if (node.isInt()) {
            values.add(node.asInt());
        } else {
            String text = node.asText();
            if (text.startsWith(AttributeSerializer.BYTE_ARRAY_PREFIX)
                    && text.endsWith(AttributeSerializer.BYTE_ARRAY_SUFFIX)) {

                values.add(Base64.decode(StringUtils.substringBetween(text,
                        AttributeSerializer.BYTE_ARRAY_PREFIX, AttributeSerializer.BYTE_ARRAY_SUFFIX)));
            } else {
                values.add(text);
            }
        }
    }

    return Uid.NAME.equals(name)
            ? new Uid(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString())
            : Name.NAME.equals(name)
                    ? new Name(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString())
                    : AttributeBuilder.build(name, values);
}