Java Code Examples for javax.json.JsonObject#getJsonNumber()

The following examples show how to use javax.json.JsonObject#getJsonNumber() . 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: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializedForm() 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, ".*");

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

    assertEquals(16, 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);
    JsonString componentId = firstElement.getJsonString("componentId");
    assertEquals(pgStatus.getId(), componentId.getString());
    JsonNumber terminatedThreads = firstElement.getJsonNumber("terminatedThreadCount");
    assertEquals(1, terminatedThreads.longValue());
    JsonString versionedFlowState = firstElement.getJsonString("versionedFlowState");
    assertEquals("UP_TO_DATE", versionedFlowState.getString());
}
 
Example 2
Source File: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnectionStatus() 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, "(Connection)");

    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 backpressure = object.getJsonString("isBackPressureEnabled");
    JsonString source = object.getJsonString("sourceName");
    assertEquals("true", backpressure.getString());
    assertEquals("source", source.getString());
    JsonString dataSizeThreshold = object.getJsonString("backPressureDataSizeThreshold");
    JsonNumber bytesThreshold = object.getJsonNumber("backPressureBytesThreshold");
    assertEquals("1 KB", dataSizeThreshold.getString());
    assertEquals(1024, bytesThreshold.intValue());
    assertNull(object.get("destinationName"));
}
 
Example 3
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 4
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 5
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 6
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 7
Source File: RegistrationsTest.java    From javaee-bce-pom with Apache License 2.0 5 votes vote down vote up
@Test
public void convertFilledListToJson() {
    List<Registration> registrations = new ArrayList<>();
    Registration expected = mock(Registration.class);
    when(expected.getId()).thenReturn(42l);
    registrations.add(expected);
    mockQuery(Registration.findAll, registrations);
    final JsonArray result = this.cut.allAsJson();
    assertNotNull(result);
    assertThat(result.size(), is(1));
    JsonObject actual = result.getJsonObject(0);
    JsonNumber actualId = actual.getJsonNumber(Registrations.CONFIRMATION_ID);
    assertThat(expected.getId(), is(actualId.longValue()));

}
 
Example 8
Source File: RegistrationsTest.java    From javaee-bce-archetype with Apache License 2.0 5 votes vote down vote up
@Test
public void convertFilledListToJson() {
    List<Registration> registrations = new ArrayList<>();
    Registration expected = mock(Registration.class);
    when(expected.getId()).thenReturn(42l);
    registrations.add(expected);
    mockQuery(Registration.findAll, registrations);
    final JsonArray result = this.cut.allAsJson();
    assertNotNull(result);
    assertThat(result.size(), is(1));
    JsonObject actual = result.getJsonObject(0);
    JsonNumber actualId = actual.getJsonNumber(Registrations.CONFIRMATION_ID);
    assertThat(expected.getId(), is(actualId.longValue()));

}
 
Example 9
Source File: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessorStatus() 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, "(Processor)");

    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 parentName = object.getJsonString("parentName");
    assertTrue(parentName.getString().startsWith("Awesome.1-"));
    JsonString parentPath = object.getJsonString("parentPath");
    assertTrue(parentPath.getString().startsWith("NiFi Flow / Awesome.1"));
    JsonString runStatus = object.getJsonString("runStatus");
    assertEquals(RunStatus.Running.name(), runStatus.getString());
    JsonNumber inputBytes = object.getJsonNumber("inputBytes");
    assertEquals(9, inputBytes.intValue());
    JsonObject counterMap = object.getJsonObject("counters");
    assertNotNull(counterMap);
    assertEquals(10, counterMap.getInt("counter1"));
    assertEquals(5, counterMap.getInt("counter2"));
    assertNull(object.get("processorType"));
}
 
Example 10
Source File: Message.java    From diirt with MIT License 5 votes vote down vote up
/**
 * Un-marshals an integer, or throws an exception if it's not able to.
 *
 * @param jObject the JSON object
 * @param name the attribute name where the integer is stored
 * @return the message integer
 * @throws MessageDecodeException if the field is missing or of the wrong type
 */
static int intMandatory(JsonObject jObject, String name) throws MessageDecodeException {
    try {
        JsonNumber jsonNumber = jObject.getJsonNumber(name);
        if (jsonNumber == null) {
            throw MessageDecodeException.missingMandatoryAttribute(jObject, name);
        } else {
            return jsonNumber.intValueExact();
        }
    } catch (ClassCastException | ArithmeticException e) {
        throw MessageDecodeException.wrongAttributeType(jObject, name, "integer");
    }
}
 
Example 11
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 12
Source File: applianceCommon.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Given a JSON string and a search-key, this method looks up the 'key' in
 * the JSON and if found, returns the associated value. Returns NULL in all
 * error conditions.
 *
 * @param jsonstr String containing JSON
 * @param key String containing the search-key
 * @param datatype String containing the data-type of the value-object
 * @return Object containing the value for the specified key if valid; null
 * in all error cases.
 */
public static Object getJsonValue(String jsonstr, String key, String datatype) {
    if (jsonstr == null || jsonstr.isEmpty()) {
        if (key == null || key.isEmpty()) {
            if (datatype == null || datatype.isEmpty()) {
                return null;
            }
        }
    }

    try (JsonReader jsonreader = Json.createReader(new StringReader(jsonstr))) {
        JsonObject json = jsonreader.readObject();

        if (!json.containsKey(key)) {
            strongkeyLogger.log(applianceConstants.APPLIANCE_LOGGER, Level.FINE, "APPL-ERR-1003", "'" + key + "' does not exist in the json");
            return null;
        }

        switch (datatype) {
            case "Boolean":
                return json.getBoolean(key);
            case "Int":
                return json.getInt(key);
            case "Long":
                return json.getJsonNumber(key).longValueExact();
            case "JsonArray":
                return json.getJsonArray(key);
            case "JsonNumber":
                return json.getJsonNumber(key);
            case "JsonObject":
                return json.getJsonObject(key);
            case "JsonString":
                return json.getJsonString(key);
            case "String":
                return json.getString(key);
            default:
                return null;
        }
    } catch (Exception ex) {
        strongkeyLogger.log(applianceConstants.APPLIANCE_LOGGER, Level.WARNING, "APPL-ERR-1000", ex.getLocalizedMessage());
        return null;
    }
}
 
Example 13
Source File: GnpsJsonParser.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
public SpectralDBEntry getDBEntry(JsonObject main) {
  // extract dps
  DataPoint[] dps = getDataPoints(main);
  if (dps == null)
    return null;

  // extract meta data
  Map<DBEntryField, Object> map = new EnumMap<>(DBEntryField.class);
  for (DBEntryField f : DBEntryField.values()) {
    String id = f.getGnpsJsonID();
    if (id != null && !id.isEmpty()) {

      try {
        Object o = null;
        if (f.getObjectClass() == Double.class || f.getObjectClass() == Integer.class
            || f.getObjectClass() == Float.class) {
          o = main.getJsonNumber(id);
        } else {
          o = main.getString(id, null);
          if (o != null && o.equals("N/A"))
            o = null;
        }
        // add value
        if (o != null) {
          if (o instanceof JsonNumber) {
            if (f.getObjectClass().equals(Integer.class)) {
              o = ((JsonNumber) o).intValue();
            } else {
              o = ((JsonNumber) o).doubleValue();
            }
          }
          // add
          map.put(f, o);
        }
      } catch (Exception e) {
        logger.log(Level.WARNING, "Cannot convert value to its type", e);
      }
    }
  }

  return new SpectralDBEntry(map, dps);
}
 
Example 14
Source File: GnpsJsonParser.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
public SpectralDBEntry getDBEntry(JsonObject main) {
  // extract dps
  DataPoint[] dps = getDataPoints(main);
  if (dps == null)
    return null;

  // extract meta data
  Map<DBEntryField, Object> map = new EnumMap<>(DBEntryField.class);
  for (DBEntryField f : DBEntryField.values()) {
    String id = f.getGnpsJsonID();
    if (id != null && !id.isEmpty()) {

      try {
        Object o = null;
        if (f.getObjectClass() == Double.class || f.getObjectClass() == Integer.class
            || f.getObjectClass() == Float.class) {
          o = main.getJsonNumber(id);
        } else {
          o = main.getString(id, null);
          if (o != null && o.equals("N/A"))
            o = null;
        }
        // add value
        if (o != null) {
          if (o instanceof JsonNumber) {
            if (f.getObjectClass().equals(Integer.class)) {
              o = ((JsonNumber) o).intValue();
            } else {
              o = ((JsonNumber) o).doubleValue();
            }
          }
          // add
          map.put(f, o);
        }
      } catch (Exception e) {
        logger.log(Level.WARNING, "Cannot convert value to its type", e);
      }
    }
  }

  return new SpectralDBEntry(map, dps);
}