Java Code Examples for com.fasterxml.jackson.databind.JsonNode#asBoolean()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#asBoolean() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DomainParseFilter.java    From storm-crawler with Apache License 2.0 6 votes vote down vote up
public void configure(@SuppressWarnings("rawtypes") Map stormConf,
        JsonNode filterParams) {
    JsonNode node = filterParams.get("key");
    if (node != null && node.isTextual()) {
        mdKey = node.asText("domain");
    }

    String partitionMode = Constants.PARTITION_MODE_DOMAIN;

    node = filterParams.get("byHost");
    if (node != null && node.asBoolean()) {
        partitionMode = Constants.PARTITION_MODE_HOST;
    }

    partitioner = new URLPartitioner();
    Map config = new HashMap();
    config.put(Constants.PARTITION_MODEParamName, partitionMode);
    partitioner.configure(config);
}
 
Example 2
Source File: JsonPatchPatchConverter.java    From spring-sync with Apache License 2.0 6 votes vote down vote up
private Object valueFromJsonNode(String path, JsonNode valueNode) {
	if (valueNode == null || valueNode.isNull()) {
		return null;
	} else if (valueNode.isTextual()) {
		return valueNode.asText();
	} else if (valueNode.isFloatingPointNumber()) {
		return valueNode.asDouble();
	} else if (valueNode.isBoolean()) {
		return valueNode.asBoolean();
	} else if (valueNode.isInt()) {
		return valueNode.asInt();
	} else if (valueNode.isLong()) {
		return valueNode.asLong();
	} else if (valueNode.isObject()) {
		return new JsonLateObjectEvaluator(valueNode);
	} else if (valueNode.isArray()) {
		// TODO: Convert valueNode to array
	}
	
	return null;
}
 
Example 3
Source File: OutputsCapturer.java    From cwlexec with Apache License 2.0 6 votes vote down vote up
private static Object toValueByJson(CWLTypeSymbol outputType, JsonNode jsonNode) {
    switch (outputType) {
    case STRING:
        return jsonNode.asText();
    case INT:
        return jsonNode.asInt();
    case FLOAT:
        return jsonNode.floatValue();
    case DOUBLE:
        return jsonNode.asDouble();
    case BOOLEAN:
        return jsonNode.asBoolean();
    default:
        return null;
    }
}
 
Example 4
Source File: JsonQueryParser.java    From searchbox-core with Apache License 2.0 6 votes vote down vote up
private Object getFieldValue(JsonNode fieldValue){
	Object val;
	
	if(fieldValue.isTextual())
		val = fieldValue.asText();
	else if(fieldValue.isInt())
		val = fieldValue.asInt();
	else if(fieldValue.isDouble())
		val = fieldValue.asDouble();
	else if(fieldValue.isBoolean())
		val = fieldValue.asBoolean();
	else
		val = null;
	
	return val;
}
 
Example 5
Source File: JsonUtils.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
public static Boolean getBooleanProperty(Map<String, JsonNode> properties,
		String name) {
	JsonNode value = properties.get(name);
	if (value != null) {
		return value.asBoolean();
	}
	return false;
}
 
Example 6
Source File: PrimitiveTypeProvider.java    From cineast with MIT License 5 votes vote down vote up
public static PrimitiveTypeProvider fromJSON(JsonNode json) {
  if (json == null) {
    return NothingProvider.INSTANCE;
  }

  if (json.isTextual()) {
    return new StringTypeProvider(json.asText());
  }

  if (json.isInt()) {
    return new IntTypeProvider(json.asInt());
  }

  if (json.isLong()) {
    return new LongTypeProvider(json.asLong());
  }

  if (json.isFloat()) {
    return new FloatTypeProvider(json.floatValue());
  }

  if (json.isDouble()) {
    return new DoubleTypeProvider(json.doubleValue());
  }

  if (json.isBoolean()) {
    return new BooleanTypeProvider(json.asBoolean());
  }

  // TODO are arrays relevant here?
  return NothingProvider.INSTANCE;
}
 
Example 7
Source File: Utils.java    From link-move with Apache License 2.0 5 votes vote down vote up
/**
 * @return For strings, number and booleans - returns value of java.lang.Comparable#compareTo
 * @throws RuntimeException for other types
 */
public static int compare(JsonNode node1, JsonNode node2) {

    if (hasComparableType(node1) && hasComparableType(node2) && ofEqualTypes(node1, node2)) {
        switch (node1.getNodeType()) {
            case STRING: {
                return node1.textValue().compareTo(node2.textValue());
            }
            case BOOLEAN: {
                Boolean left = node1.asBoolean(), right = node2.asBoolean();
                return left.compareTo(right);
            }
            case NUMBER: {
                if (node1.isIntegralNumber()) {
                    Integer left = node1.asInt(), right = node2.asInt();
                    return left.compareTo(right);
                } else if (node1.isFloatingPointNumber()) {
                    Double left = node1.asDouble(), right = node2.asDouble();
                    return left.compareTo(right);
                }
                // fall through
            }
            default: {
                // fall through
            }
        }
    }
    throw new RuntimeException("Unsupported comparable type: " + node1.getNodeType().name());
}
 
Example 8
Source File: JsonNodeELResolver.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
/**
 * If the base object is a map, returns the value associated with the given key, as specified by the property argument. If the key was not found, null is returned. If the base is a Map, the
 * propertyResolved property of the ELContext object must be set to true by this resolver, before returning. If this property is not true after this method is called, the caller should ignore the
 * return value. Just as in java.util.Map.get(Object), just because null is returned doesn't mean there is no mapping for the key; it's also possible that the Map explicitly maps the key to null.
 * 
 * @param context
 *            The context of this evaluation.
 * @param base
 *            The map to analyze. Only bases of type Map are handled by this resolver.
 * @param property
 *            The key to return the acceptable type for. Ignored by this resolver.
 * @return If the propertyResolved property of ELContext was set to true, then the value associated with the given key or null if the key was not found. Otherwise, undefined.
 * @throws ClassCastException
 *             if the key is of an inappropriate type for this map (optionally thrown by the underlying Map).
 * @throws NullPointerException
 *             if context is null, or if the key is null and this map does not permit null keys (the latter is optionally thrown by the underlying Map).
 * @throws ELException
 *             if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
 */
@Override
public Object getValue(ELContext context, Object base, Object property) {
    if (context == null) {
        throw new NullPointerException("context is null");
    }
    Object result = null;
    if (isResolvable(base)) {
        JsonNode resultNode = getResultNode((JsonNode) base, property, context);
        if (resultNode != null && resultNode.isValueNode()) {
            if (resultNode.isBoolean()) {
                result = resultNode.asBoolean();
            } else if (resultNode.isShort() || resultNode.isInt()) {
                result = resultNode.asInt();
            } else if (resultNode.isLong()) {
                result = resultNode.asLong();
            } else if (resultNode.isBigDecimal() || resultNode.isDouble() || resultNode.isFloat()) {
                result = resultNode.asDouble();
            } else if (resultNode.isTextual()) {
                result = resultNode.asText();
            } else if (resultNode.isNull()) {
                result = null;
            } else {
                result = resultNode.toString();
            }

        } else {
            result = resultNode;
        }
        context.setPropertyResolved(true);
    }
    return result;
}
 
Example 9
Source File: CustomEmojiImpl.java    From Javacord with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new custom emoji.
 *
 * @param api The discord api instance.
 * @param data The json data of the emoji.
 */
public CustomEmojiImpl(DiscordApiImpl api, JsonNode data) {
    this.api = api;
    id = data.get("id").asLong();
    JsonNode nameNode = data.get("name");
    name = nameNode == null ? "" : nameNode.asText();
    // Animated field may be missing, default to false
    JsonNode animatedNode = data.get("animated");
    animated = animatedNode != null && animatedNode.asBoolean();
}
 
Example 10
Source File: ReadJsonTestTweetsBuilder.java    From kite with Apache License 2.0 5 votes vote down vote up
private void tryAddBool(Record doc, String solr_field, JsonNode node) {
  if (node == null)
    return;
  Boolean val = node.asBoolean();
  if (val == null) {
    return;
  }
  doc.put(solr_field, val);
}
 
Example 11
Source File: BaseBpmnJsonConverter.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected boolean getValueAsBoolean(String name, JsonNode objectNode) {
    boolean propertyValue = false;
    JsonNode propertyNode = objectNode.get(name);
    if (propertyNode != null && !propertyNode.isNull()) {
        propertyValue = propertyNode.asBoolean();
    }
    return propertyValue;
}
 
Example 12
Source File: AbstractColumnDetailChecker.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public void check(ObjectNode node) {
    Iterator<String> iterator = node.fieldNames();
    ImmutableSet<String> attributes = ImmutableSet.copyOf(iterator);

    Set<String> minAttributes = getMinAttributes();
    Sets.SetView<String> require = Sets.difference(minAttributes, attributes);
    Preconditions.checkArgument(require.isEmpty(), "[%s]还缺少属性%s", name(), require);

    Set<String> maxAttributes = getMaxAttributes();
    Sets.SetView<String> illegal = Sets.difference(attributes, maxAttributes);
    Preconditions.checkArgument(illegal.isEmpty(), "[%s]包含无效属性%s", name(), illegal);

    Context context = doCheck(node);
    JsonNode defaultNode = node.get(TemplateContants.DEFAULT);
    if (defaultNode != null) {
        Preconditions.checkArgument(defaultNode.isTextual(), "default必须是一个文本属性");
        String defaultText = defaultNode.asText();
        Preconditions.checkArgument(defaultText.trim().length() == defaultText.length(), "[%s]默认值前后不能有空格", name());
        if (!Strings.isNullOrEmpty(defaultText)) {
            Preconditions.checkArgument(context.isLegalValue(defaultText), "[%s]默认值[%s]无效", name(), defaultText);
        }
    }
    JsonNode readonlyNode = node.get(TemplateContants.READONLY);
    if (readonlyNode != null) {
        Preconditions.checkArgument(readonlyNode.isBoolean(), "readonly必须是一个布尔属性");
        if (readonlyNode.asBoolean()) {
            Preconditions.checkArgument(defaultNode != null && !Strings.isNullOrEmpty(defaultNode.asText()), "只读只在有默认值时生效");
        }
    }
}
 
Example 13
Source File: JacksonUtil.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
public static Boolean parseBoolean(String body, String field) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node;
    try {
        node = mapper.readTree(body);
        JsonNode leaf = node.get(field);
        if (leaf != null)
            return leaf.asBoolean();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
 
Example 14
Source File: MqttTransportHandler.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
private void checkGatewaySession() {
  Device device = deviceSessionCtx.getDevice();
  if (device != null) {
    JsonNode infoNode = device.getAdditionalInfo();
    if (infoNode != null) {
      JsonNode gatewayNode = infoNode.get("gateway");
      if (gatewayNode != null && gatewayNode.asBoolean()) {
        // gatewaySessionCtx = new GatewaySessionCtx(processor, deviceService,
        // authService, relationService,
        // deviceSessionCtx);
      }
    }
  }
}
 
Example 15
Source File: JsonHelpers.java    From samantha with MIT License 5 votes vote down vote up
/**
 * @return a Boolean from the input JsonNode with the given name, or the defaultVal
 */
public static Boolean getOptionalBoolean(JsonNode json, String name, Boolean defaultVal) throws BadRequestException {
    JsonNode node = json.get(name);
    if (node == null) {
        return defaultVal;
    }
    if (!node.isBoolean()) {
        throw new BadRequestException("json is not a boolean: " + name);
    }
    return node.asBoolean();
}
 
Example 16
Source File: MeterRequestCodec.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public MeterRequest decode(ObjectNode json, CodecContext context) {
    if (json == null || !json.isObject()) {
        return null;
    }

    final JsonCodec<Band> meterBandCodec = context.codec(Band.class);
    CoreService coreService = context.getService(CoreService.class);

    // parse device id
    DeviceId deviceId = DeviceId.deviceId(nullIsIllegal(json.get(DEVICE_ID),
            DEVICE_ID + MISSING_MEMBER_MESSAGE).asText());

    // application id
    ApplicationId appId = coreService.registerApplication(REST_APP_ID);

    // parse burst
    boolean burst = false;
    JsonNode burstJson = json.get("burst");
    if (burstJson != null) {
        burst = burstJson.asBoolean();
    }

    // parse unit type
    String unit = nullIsIllegal(json.get(UNIT), UNIT + MISSING_MEMBER_MESSAGE).asText();
    Meter.Unit meterUnit = null;

    switch (unit) {
        case "KB_PER_SEC":
            meterUnit = Meter.Unit.KB_PER_SEC;
            break;
        case "PKTS_PER_SEC":
            meterUnit = Meter.Unit.PKTS_PER_SEC;
            break;
        default:
            nullIsIllegal(meterUnit, "The requested unit " + unit + " is not defined for meter.");
    }

    // parse meter bands
    List<Band> bandList = new ArrayList<>();
    JsonNode bandsJson = json.get(BANDS);
    checkNotNull(bandsJson);
    if (bandsJson != null) {
        IntStream.range(0, bandsJson.size()).forEach(i -> {
            ObjectNode bandJson = get(bandsJson, i);
            bandList.add(meterBandCodec.decode(bandJson, context));
        });
    }

    MeterRequest meterRequest;
    if (burst) {
        meterRequest = DefaultMeterRequest.builder()
                .fromApp(appId)
                .forDevice(deviceId)
                .withUnit(meterUnit)
                .withBands(bandList)
                .burst().add();
    } else {
        meterRequest = DefaultMeterRequest.builder()
                .fromApp(appId)
                .forDevice(deviceId)
                .withUnit(meterUnit)
                .withBands(bandList).add();
    }

    return meterRequest;
}
 
Example 17
Source File: BusinessObjectDeserializer.java    From bonita-ui-designer with GNU General Public License v2.0 4 votes vote down vote up
private boolean mandatoryValue(JsonNode contractInput) {
    JsonNode jsonNode = contractInput.get(BUSINESS_OBJECT_NULLABLE);
    return jsonNode != null && !jsonNode.asBoolean(true);
}
 
Example 18
Source File: SchemaSetLoader.java    From curator with Apache License 2.0 4 votes vote down vote up
private boolean getBoolean(JsonNode node, String name)
{
    JsonNode namedNode = node.get(name);
    return (namedNode != null) && namedNode.asBoolean();
}
 
Example 19
Source File: YoRCDeserializer.java    From jhipster-online with Apache License 2.0 4 votes vote down vote up
private boolean getDefaultIfNull(JsonNode node, boolean defaultValue) {
    return node == null ? defaultValue : node.asBoolean();
}
 
Example 20
Source File: BlockStateDeserializer.java    From Web-API with MIT License 4 votes vote down vote up
@Override
public BlockState deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    JsonNode root = p.readValueAsTree();
    if (root.path("type").isMissingNode()) {
        throw new IOException("Missing block type");
    }

    String typeStr = root.path("type").isTextual()
            ? root.path("type").asText()
            : root.path("type").path("id").asText();
    Optional<BlockType> optType = Sponge.getRegistry().getType(BlockType.class, typeStr);
    if (!optType.isPresent()) {
        throw new IOException("Invalid block type " + typeStr);
    }
    BlockType type = optType.get();

    BlockState state = type.getDefaultState();
    Collection<BlockTrait<?>> traits = type.getTraits();

    if (!root.path("data").isMissingNode()) {
        Iterator<Map.Entry<String, JsonNode>> it = root.path("data").fields();
        while (it.hasNext()) {
            Map.Entry<String, JsonNode> entry = it.next();

            Optional<BlockTrait<?>> optTrait = traits.stream().filter(t ->
                    t.getName().equalsIgnoreCase(entry.getKey())
            ).findAny();

            if (!optTrait.isPresent())
                throw new IOException("Unknown trait '" + entry.getKey() + "'");

            BlockTrait trait = optTrait.get();
            Object value = null;

            JsonNode nodeValue = entry.getValue();
            if (nodeValue.isBoolean()) {
                value = nodeValue.asBoolean();
            } else if (nodeValue.isInt()) {
                value = nodeValue.asInt();
            } else if (nodeValue.isTextual()) {
                Collection<?> values = trait.getPossibleValues();
                Optional<?> val = values.stream()
                        .filter(v -> v.toString().equalsIgnoreCase(nodeValue.asText()))
                        .findAny();

                if (!val.isPresent()) {
                    String allowedValues = values.stream()
                            .map(Object::toString)
                            .collect(Collectors.joining(", "));
                    throw new IOException("Trait '" + trait.getName() + "' has value '" +
                            nodeValue.asText() + "' but can only have one of: " + allowedValues);
                } else {
                    value = val.get();
                }
            }

            Optional<BlockState> newState = state.withTrait(trait, value);
            if (!newState.isPresent())
                throw new IOException("Could not apply trait '" + trait.getName() + " to block state");

            state = newState.get();
        }
    }

    return state;
}