javax.json.JsonNumber Java Examples

The following examples show how to use javax.json.JsonNumber. 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: ClaimValueInjectionEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/verifyInjectedCustomDouble")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedCustomDouble(@QueryParam("value") Double value) {
    boolean pass = false;
    String msg;
    JsonNumber customValue = customDouble.getValue();
    if(customValue == null) {
        msg = "customDouble value is null, FAIL";
    }
    else if(Math.abs(customValue.doubleValue() - value.doubleValue()) < 0.00001) {
        msg = "customDouble PASS";
        pass = true;
    }
    else {
        msg = String.format("customDouble: %s != %.8f", customValue, value);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example #2
Source File: JsonValueResolver.java    From trimou with Apache License 2.0 6 votes vote down vote up
private Object unwrapJsonValueIfNecessary(JsonValue jsonValue) {
    switch (jsonValue.getValueType()) {
    case STRING:
        return ((JsonString) jsonValue).getString();
    case NUMBER:
        return ((JsonNumber) jsonValue).bigDecimalValue();
    case TRUE:
        return Boolean.TRUE;
    case FALSE:
        return Boolean.FALSE;
    case NULL:
        return Placeholder.NULL;
    default:
        return jsonValue;
    }

}
 
Example #3
Source File: JsonIndexedRecord.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Object toObject(final JsonValue jsonValue, final Schema schema) {
    if (jsonValue == null) {
        return null;
    }
    switch (jsonValue.getValueType()) {
    case TRUE:
        return true;
    case FALSE:
        return false;
    case NUMBER:
        return JsonNumber.class.cast(jsonValue).numberValue();
    case STRING:
        return JsonString.class.cast(jsonValue).getString();
    case ARRAY:
        return jsonValue
                .asJsonArray()
                .stream()
                .map(it -> toObject(jsonValue, schema.getElementType()))
                .collect(toList());
    case OBJECT:
        return new JsonIndexedRecord(jsonValue.asJsonObject(), schema);
    case NULL:
    default:
        return null;
    }
}
 
Example #4
Source File: MicroProfileMetricsIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
private void assertComplexMetricValue(CamelContext camelctx, String metricName, Number metricValue) throws Exception {
    String metrics = getMetrics();

    JsonParser parser = Json.createParser(new StringReader(metrics));
    Assert.assertTrue("Metrics endpoint content is empty", parser.hasNext());
    parser.next();

    JsonObject jsonObject = parser.getObject();
    JsonNumber result = null;
    String[] nameParts = metricName.split("\\.");
    for (int i = 0; i < nameParts.length; i++) {
        String jsonKey = i + 1 == nameParts.length ? nameParts[i] + ";camelContext=" + camelctx.getName() : nameParts[i];

        if (i + 1 == nameParts.length) {
            result = jsonObject.getJsonNumber(jsonKey);
            break;
        } else {
            jsonObject = jsonObject.getJsonObject(jsonKey);
        }
    }

    Assert.assertNotNull("Expected to find metric " + metricName, result);
    Assert.assertEquals("Expected metric " + metricName + " to have value " + metricValue, metricValue, result.intValue());
}
 
Example #5
Source File: JwtClaimsBuilderImpl.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
private static Object convertJsonValue(JsonValue jsonValue) {
    if (jsonValue instanceof JsonString) {
        String jsonString = jsonValue.toString();
        return jsonString.toString().substring(1, jsonString.length() - 1);
    } else if (jsonValue instanceof JsonNumber) {
        JsonNumber jsonNumber = (JsonNumber) jsonValue;
        if (jsonNumber.isIntegral()) {
            return jsonNumber.longValue();
        } else {
            return jsonNumber.doubleValue();
        }
    } else if (jsonValue == JsonValue.TRUE) {
        return true;
    } else if (jsonValue == JsonValue.FALSE) {
        return false;
    } else {
        return null;
    }
}
 
Example #6
Source File: Kitap.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Map<String, String> toConfig(final JsonObject object) {
    return object
            .entrySet()
            .stream()
            .filter(e -> !JsonValue.NULL.equals(e.getValue()))
            .collect(toMap(Map.Entry::getKey, e -> {
                switch (e.getValue().getValueType()) {
                case STRING:
                    return JsonString.class.cast(e.getValue()).getString();
                case NUMBER:
                    return String.valueOf(JsonNumber.class.cast(e.getValue()).doubleValue());
                case TRUE:
                case FALSE:
                    return String.valueOf(JsonValue.TRUE.equals(e.getValue()));
                default:
                    throw new IllegalArgumentException("Unsupported json entry: " + e);
                }
            }));
}
 
Example #7
Source File: RawClaimTypeProducer.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Produces
@Claim("")
Double getClaimAsDouble(InjectionPoint ip) {
    CDILogging.log.getClaimAsDouble(ip);
    if (currentToken == null) {
        return null;
    }

    String name = getName(ip);
    Optional<Object> optValue = currentToken.claim(name);
    Double returnValue = null;
    if (optValue.isPresent()) {
        Object value = optValue.get();
        if (value instanceof JsonNumber) {
            JsonNumber jsonValue = (JsonNumber) value;
            returnValue = jsonValue.doubleValue();
        } else {
            returnValue = Double.parseDouble(value.toString());
        }
    }
    return returnValue;
}
 
Example #8
Source File: RawClaimTypeProducer.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Produces
@Claim("")
Long getClaimAsLong(InjectionPoint ip) {
    CDILogging.log.getClaimAsLong(ip);
    if (currentToken == null) {
        return null;
    }

    String name = getName(ip);
    Optional<Object> optValue = currentToken.claim(name);
    Long returnValue = null;
    if (optValue.isPresent()) {
        Object value = optValue.get();
        if (value instanceof JsonNumber) {
            JsonNumber jsonValue = (JsonNumber) value;
            returnValue = jsonValue.longValue();
        } else {
            returnValue = Long.parseLong(value.toString());
        }
    }
    return returnValue;
}
 
Example #9
Source File: RecordConverters.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Object mapJson(final RecordBuilderFactory factory, final JsonValue it) {
    if (JsonObject.class.isInstance(it)) {
        return json2Record(factory, JsonObject.class.cast(it));
    }
    if (JsonArray.class.isInstance(it)) {
        return JsonArray.class.cast(it).stream().map(i -> mapJson(factory, i)).collect(toList());
    }
    if (JsonString.class.isInstance(it)) {
        return JsonString.class.cast(it).getString();
    }
    if (JsonNumber.class.isInstance(it)) {
        return JsonNumber.class.cast(it).numberValue();
    }
    if (JsonValue.FALSE.equals(it)) {
        return false;
    }
    if (JsonValue.TRUE.equals(it)) {
        return true;
    }
    if (JsonValue.NULL.equals(it)) {
        return null;
    }
    return it;
}
 
Example #10
Source File: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testPortStatus() throws IOException, InitializationException {
    ProcessGroupStatus pgStatus = generateProcessGroupStatus("root", "Awesome", 1, 0);

    final Map<PropertyDescriptor, String> properties = new HashMap<>();
    properties.put(SiteToSiteUtils.BATCH_SIZE, "4");
    properties.put(SiteToSiteStatusReportingTask.COMPONENT_NAME_FILTER_REGEX, "Awesome.*");
    properties.put(SiteToSiteStatusReportingTask.COMPONENT_TYPE_FILTER_REGEX, "(InputPort)");
    properties.put(SiteToSiteStatusReportingTask.ALLOW_NULL_VALUES,"false");

    MockSiteToSiteStatusReportingTask task = initTask(properties, pgStatus);
    task.onTrigger(context);

    final String msg = new String(task.dataSent.get(0), StandardCharsets.UTF_8);
    JsonReader jsonReader = Json.createReader(new ByteArrayInputStream(msg.getBytes()));
    JsonObject object = jsonReader.readArray().getJsonObject(0);
    JsonString runStatus = object.getJsonString("runStatus");
    assertEquals(RunStatus.Stopped.name(), runStatus.getString());
    boolean isTransmitting = object.getBoolean("transmitting");
    assertFalse(isTransmitting);
    JsonNumber inputBytes = object.getJsonNumber("inputBytes");
    assertEquals(5, inputBytes.intValue());
    assertNull(object.get("activeThreadCount"));
}
 
Example #11
Source File: VisibilityService.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Object mapValue(final JsonValue value) {
    switch (value.getValueType()) {
    case ARRAY:
        return value.asJsonArray().stream().map(this::mapValue).collect(toList());
    case STRING:
        return JsonString.class.cast(value).getString();
    case TRUE:
        return true;
    case FALSE:
        return false;
    case NUMBER:
        return JsonNumber.class.cast(value).doubleValue();
    case NULL:
        return null;
    case OBJECT:
    default:
        return value;
    }
}
 
Example #12
Source File: SlotExchangeIndex.java    From logbook with MIT License 6 votes vote down vote up
@Override
public void update(DataType type, final Data data) {
    Optional.ofNullable(ShipContext.get().get(Long.valueOf(data.getField("api_id")))).ifPresent(
            ship -> {
                JsonObject apiData = data.getJsonObject().getJsonObject("api_data");
                if (apiData != null) {
                    JsonArray apiSlot = apiData.getJsonArray("api_slot");
                    List<Long> newSlot = new ArrayList<>(apiSlot.size());
                    for (JsonValue jsonValue : apiSlot) {
                        JsonNumber itemid = (JsonNumber) jsonValue;
                        newSlot.add(Long.valueOf(itemid.longValue()));
                    }
                    ship.setSlot(newSlot);
                }
            });
}
 
Example #13
Source File: Message.java    From diirt with MIT License 6 votes vote down vote up
/**
 * Converts the given JSON value to either a vtype, a Java time or a
 * ListNumber.
 *
 * @param msgValue the JSON value
 * @return the converted type
 */
public static Object readValueFromJson(JsonValue msgValue) {
    if (msgValue instanceof JsonObject) {
        return VTypeToJson.toVType((JsonObject) msgValue);
    } else if (msgValue instanceof JsonNumber) {
        return ((JsonNumber) msgValue).doubleValue();
    } else if (msgValue instanceof JsonString){
        return ((JsonString) msgValue).getString();
    } else if (msgValue instanceof JsonArray){
        JsonArray array = (JsonArray) msgValue;
        if (isNumericArray(array)) {
            return toListDouble(array);
        } else if (isStringArray(array)) {
            return toListString(array);
        } else {
            return null;
        }
    } else {
        return null;
    }
}
 
Example #14
Source File: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoteProcessGroupStatus() throws IOException, InitializationException {
    final ProcessGroupStatus pgStatus = generateProcessGroupStatus("root", "Awesome", 1, 0);

    final Map<PropertyDescriptor, String> properties = new HashMap<>();
    properties.put(SiteToSiteUtils.BATCH_SIZE, "4");
    properties.put(SiteToSiteStatusReportingTask.COMPONENT_NAME_FILTER_REGEX, "Awesome.*");
    properties.put(SiteToSiteStatusReportingTask.COMPONENT_TYPE_FILTER_REGEX, "(RemoteProcessGroup)");

    MockSiteToSiteStatusReportingTask task = initTask(properties, pgStatus);
    task.onTrigger(context);

    assertEquals(3, task.dataSent.size());
    final String msg = new String(task.dataSent.get(0), StandardCharsets.UTF_8);
    JsonReader jsonReader = Json.createReader(new ByteArrayInputStream(msg.getBytes()));
    JsonObject firstElement = jsonReader.readArray().getJsonObject(0);
    JsonNumber activeThreadCount = firstElement.getJsonNumber("activeThreadCount");
    assertEquals(1L, activeThreadCount.longValue());
    JsonString transmissionStatus = firstElement.getJsonString("transmissionStatus");
    assertEquals("Transmitting", transmissionStatus.getString());
}
 
Example #15
Source File: JsonReader.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private Reader<?> reader(Location location) {
    switch (value.getValueType()) {
        case ARRAY:
            return new JsonArrayReader(type, location, (JsonArray) value);
        case OBJECT:
            return new JsonObjectReader(type, location, (JsonObject) value);
        case STRING:
            return new JsonStringReader(type, location, (JsonString) value);
        case NUMBER:
            return new JsonNumberReader(type, location, (JsonNumber) value);
        case TRUE:
        case FALSE:
            return new JsonBooleanReader(type, location, value);
        case NULL:
            return new JsonNullReader(type, location, value);
    }
    throw new GraphQlClientException("unreachable code");
}
 
Example #16
Source File: ProviderInjectionEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/verifyInjectedCustomDouble")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedCustomDouble(@QueryParam("value") Double value) {
    boolean pass = false;
    String msg;
    // iat
    JsonNumber customValue = customDouble.get();
    if(customValue == null) {
        msg = "customDouble value is null, FAIL";
    }
    else if(Math.abs(customValue.doubleValue() - value.doubleValue()) < 0.00001) {
        msg = "customDouble PASS";
        pass = true;
    }
    else {
        msg = String.format("customDouble: %s != %.8f", customValue, value);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example #17
Source File: JsonParser.java    From jeddict with Apache License 2.0 6 votes vote down vote up
private String getJsonNumberType(JsonNumber jsonNumber) {
    String type = LONG;
    if (null != jsonNumber.getClass().getSimpleName()) {
        switch (jsonNumber.getClass().getSimpleName()) {
            case "JsonIntNumber":
                type = INT;
                break;
            case "JsonLongNumber":
                type = LONG;
                break;
            default:
                type = DOUBLE;
                break;
        }
    }
    return type;
}
 
Example #18
Source File: GlobalContext.java    From logbook with MIT License 5 votes vote down vote up
/**
 * 艦隊を設定します
 *
 * @param apidata
 */
private static void doDeck(JsonArray apidata) {
    dock.clear();
    for (int i = 0; i < apidata.size(); i++) {
        JsonObject jsonObject = (JsonObject) apidata.get(i);
        String fleetid = Long.toString(jsonObject.getJsonNumber("api_id").longValue());
        String name = jsonObject.getString("api_name");
        JsonArray apiship = jsonObject.getJsonArray("api_ship");

        DockDto dockdto = new DockDto(fleetid, name);
        dock.put(fleetid, dockdto);

        for (int j = 0; j < apiship.size(); j++) {
            Long shipid = Long.valueOf(((JsonNumber) apiship.get(j)).longValue());
            ShipDto ship = ShipContext.get().get(shipid);

            if (ship != null) {
                dockdto.addShip(ship);

                if ((i == 0) && (j == 0)) {
                    ShipContext.setSecretary(ship);
                }
                // 艦隊IDを設定
                ship.setFleetid(fleetid);
            }
        }
    }
}
 
Example #19
Source File: MonaJsonParser.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * read from META_DATA array
 * 
 * @param main
 * @param id
 * @return String or Number or null
 */
private Object readMetaData(JsonObject main, String id) {
  JsonValue j = main.getJsonArray(META_DATA).stream().map(v -> v.asJsonObject())
      .filter(v -> v.getString("name").equals(id)).map(v -> v.get("value")).findFirst()
      .orElse(null);

  if (j != null) {
    if (j.getValueType().equals(ValueType.STRING))
      return ((JsonString) j).getString();
    if (j.getValueType().equals(ValueType.NUMBER))
      return ((JsonNumber) j).numberValue();
  }
  return null;
}
 
Example #20
Source File: JsonParser.java    From jeddict with Apache License 2.0 5 votes vote down vote up
private BeanClass generateClass(EntityMappings entityMappings, String className, JsonObject jsonObject) {
    reporter.accept(getMessage(DocWizardDescriptor.class, "MSG_Progress_Class_Parsing", className));

    BeanClass beanClass = createBeanClass(entityMappings, className);
    jsonObject.forEach((key, value) -> {
        Attribute baseAttribute;
        if (value instanceof JsonString) {
            baseAttribute = createBeanAttribute(beanClass, STRING, key);
        } else if (value instanceof JsonNumber) {
            baseAttribute = createBeanAttribute(beanClass, getJsonNumberType((JsonNumber) value), key);
        } else if (value instanceof JsonArray) {
            JsonArray jsonArray = (JsonArray) value;
            if (!jsonArray.isEmpty()) {
                JsonValue arrayElement = jsonArray.get(0);
                if (arrayElement instanceof JsonString) {
                    baseAttribute = createBeanCollection(beanClass, STRING, key);
                } else if (arrayElement instanceof JsonNumber) {
                    baseAttribute = createBeanCollection(beanClass, getJsonNumberType((JsonNumber) arrayElement), key);
                } else if (arrayElement instanceof JsonObject) {
                    baseAttribute = createOneToManyAssociation(beanClass, generateClass(entityMappings, key, (JsonObject) arrayElement), key);
                } else {
                    baseAttribute = createBeanCollection(beanClass, STRING, key);
                }
            } else {
                baseAttribute = createBeanCollection(beanClass, STRING, key);
            }
        } else if (value instanceof JsonObject) {
            baseAttribute = createOneToOneAssociation(beanClass, generateClass(entityMappings, key, (JsonObject) value), key);
        } else if (value instanceof JsonValue) {
            if (((JsonValue) value).getValueType() == TRUE || ((JsonValue) value).getValueType() == FALSE) {
                baseAttribute = createBeanAttribute(beanClass, BOOLEAN, key);
            } else {
                baseAttribute = createBeanAttribute(beanClass, STRING, key);
            }
        } else {
            baseAttribute = createBeanAttribute(beanClass, STRING, key);
        }
    });
    return beanClass;
}
 
Example #21
Source File: JsonParser.java    From jeddict with Apache License 2.0 5 votes vote down vote up
private Entity generateEntity(EntityMappings entityMappings, String className, JsonObject jsonObject) {
    reporter.accept(getMessage(DocWizardDescriptor.class, "MSG_Progress_Class_Parsing", className));

    Entity entity = createEntity(entityMappings, className);
    jsonObject.forEach((key, value) -> {
        Attribute baseAttribute;
        if (value instanceof JsonString) {
            baseAttribute = createBasicAttribute(entity, STRING, key);
        } else if (value instanceof JsonNumber) {
            baseAttribute = createBasicAttribute(entity, getJsonNumberType((JsonNumber) value), key);
        } else if (value instanceof JsonArray) {
            JsonArray jsonArray = (JsonArray) value;
            if (!jsonArray.isEmpty()) {
                JsonValue arrayElement = jsonArray.get(0);
                if (arrayElement instanceof JsonString) {
                    baseAttribute = createElementCollection(entity, STRING, key);
                } else if (arrayElement instanceof JsonNumber) {
                    baseAttribute = createElementCollection(entity, getJsonNumberType((JsonNumber) arrayElement), key);
                } else if (arrayElement instanceof JsonObject) {
                    baseAttribute = createOneToMany(entity, generateEntity(entityMappings, key, (JsonObject) arrayElement), key);
                } else {
                    baseAttribute = createElementCollection(entity, STRING, key);
                }
            } else {
                baseAttribute = createElementCollection(entity, STRING, key);
            }
        } else if (value instanceof JsonObject) {
            baseAttribute = createOneToOne(entity, generateEntity(entityMappings, key, (JsonObject) value), key);
        } else if (value instanceof JsonValue) {
            if (((JsonValue) value).getValueType() == TRUE || ((JsonValue) value).getValueType() == FALSE) {
                baseAttribute = createBasicAttribute(entity, BOOLEAN, key);
            } else {
                baseAttribute = createBasicAttribute(entity, STRING, key);
            }
        } else {
            baseAttribute = createBasicAttribute(entity, STRING, key);
        }
    });
    return entity;
}
 
Example #22
Source File: BooleanCharacteristic.java    From HAP-Java with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected Boolean convert(JsonValue jsonValue) {
  if (jsonValue.getValueType().equals(ValueType.NUMBER)) {
    return ((JsonNumber) jsonValue).intValue() > 0;
  }
  return jsonValue.equals(JsonValue.TRUE);
}
 
Example #23
Source File: EnumCharacteristic.java    From HAP-Java with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected Integer convert(JsonValue jsonValue) {
  if (jsonValue instanceof JsonNumber) {
    return ((JsonNumber) jsonValue).intValue();
  } else if (jsonValue == JsonObject.TRUE) {
    return 1; // For at least one enum type (locks), homekit will send a true instead of 1
  } else if (jsonValue == JsonObject.FALSE) {
    return 0;
  } else {
    throw new IndexOutOfBoundsException("Cannot convert " + jsonValue.getClass() + " to int");
  }
}
 
Example #24
Source File: RequestCaseJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the DataValue represented by the given number object.
 */
private static DataValue<?> asIntegerValue( RequestCaseContext context, JsonNumber json, String format)
  {
  return
    "int64".equals( format)
    ? new LongValue( json.longValueExact())
    : new IntegerValue( json.intValueExact());
  }
 
Example #25
Source File: Message.java    From diirt with MIT License 5 votes vote down vote up
/**
 * Un-marshals an integer, or returns the default value if it's not able to.
 *
 * @param jObject the JSON object
 * @param name the attribute name where the integer is stored
 * @param defaultValue the value to use if no attribute is found
 * @return the message integer
 * @throws MessageDecodeException if the field is of the wrong type
 */
static int intOptional(JsonObject jObject, String name, int defaultValue) throws MessageDecodeException {
    try {
        JsonNumber jsonNumber = jObject.getJsonNumber(name);
        if (jsonNumber == null) {
            return defaultValue;
        } else {
            return jsonNumber.intValueExact();
        }
    } catch (ClassCastException | ArithmeticException e) {
        throw MessageDecodeException.wrongAttributeType(jObject, name, "integer");
    }
}
 
Example #26
Source File: JSONContentHandler.java    From jcypher with Apache License 2.0 5 votes vote down vote up
@Override
public Object convertContentValue(Object value) {
	if (value instanceof JsonValue) {
		JsonValue val = (JsonValue) value;
		Object ret = null;
		ValueType typ = val.getValueType();
		if (typ == ValueType.NUMBER)
			ret = ((JsonNumber)val).bigDecimalValue();
		else if (typ == ValueType.STRING)
			ret = ((JsonString)val).getString();
		else if (typ == ValueType.FALSE)
			ret = Boolean.FALSE;
		else if (typ == ValueType.TRUE)
			ret = Boolean.TRUE;
		else if (typ == ValueType.ARRAY) {
			JsonArray arr = (JsonArray)val;
			List<Object> vals = new ArrayList<Object>();
			int sz = arr.size();
			for (int i = 0; i < sz; i++) {
				JsonValue v = arr.get(i);
				vals.add(convertContentValue(v));
			}
			ret = vals;
		} else if (typ == ValueType.OBJECT) {
			//JsonObject obj = (JsonObject)val;
		}
		return ret;
	}
	return value;
}
 
Example #27
Source File: Generator.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private static boolean areEqualsIgnoringOrder(final JsonValue oldValue, final JsonValue newValue) {
    if (!oldValue.getValueType().equals(newValue.getValueType())) {
        return false;
    }
    switch (oldValue.getValueType()) {
    case STRING:
        return JsonString.class.cast(oldValue).getString().equals(JsonString.class.cast(newValue).getString());
    case NUMBER:
        return JsonNumber.class.cast(oldValue).doubleValue() == JsonNumber.class.cast(newValue).doubleValue();
    case OBJECT:
        final JsonObject oldObject = oldValue.asJsonObject();
        final JsonObject newObject = newValue.asJsonObject();
        if (!oldObject.keySet().equals(newObject.keySet())) {
            return false;
        }
        return oldObject
                .keySet()
                .stream()
                .map(key -> areEqualsIgnoringOrder(oldObject.get(key), newObject.get(key)))
                .reduce(true, (a, b) -> a && b);
    case ARRAY:
        final JsonArray oldArray = oldValue.asJsonArray();
        final JsonArray newArray = newValue.asJsonArray();
        if (oldArray.size() != newArray.size()) {
            return false;
        }
        if (oldArray.isEmpty()) {
            return true;
        }
        for (final JsonValue oldItem : oldArray) {
            if (newArray.stream().noneMatch(newitem -> areEqualsIgnoringOrder(oldItem, newitem))) {
                return false;
            }
        }
        return true;
    default:
        // value type check was enough
        return true;
    }
}
 
Example #28
Source File: ResultAnalyzer.java    From aceql-http with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    * Returns the error_type in case of failure
    *
    * @return the error_type in case of failure, -1 if no error
    */
   public int getErrorType() {

if (isInvalidJsonStream()) {
    return 0;
}

try {
    JsonReader reader = Json.createReader(new StringReader(jsonResult));
    JsonStructure jsonst = reader.read();

    JsonObject object = (JsonObject) jsonst;
    JsonString status = (JsonString) object.get("status");

    if (status == null) {
	return -1;
    }

    JsonNumber errorType = (JsonNumber) object.get("error_type");

    if (errorType == null) {
	return -1;
    } else {
	return errorType.intValue();
    }
} catch (Exception e) {
    this.parseException = e;
    return -1;
}

   }
 
Example #29
Source File: Occasion.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
public Contribution(JsonObject json) {
  String method = "Contribution";
  logger.entering(clazz, method, json);

  setUserId(json.getString(OCCASION_CONTRIBUTION_USER_ID_KEY, null));

  JsonNumber amount = json.getJsonNumber(OCCASION_CONTRIBUTION_AMOUNT_KEY);
  setAmount((amount == null) ? 0 : amount.doubleValue());

  logger.exiting(clazz, method, "amount: " + getAmount() + ", userId: " + getUserId());
}
 
Example #30
Source File: JWTCallerPrincipal.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void replaceNumber(final String name) {
    try {
        final Number number = claimsSet.getClaimValue(name, Number.class);
        final JsonNumber jsonNumber = (JsonNumber) wrapValue(number);
        claimsSet.setClaim(name, jsonNumber);

    } catch (final MalformedClaimException e) {
        logger.log(Level.WARNING, "replaceNumber failure for: " + name, e);
    }
}