Java Code Examples for javax.json.JsonArray#getJsonObject()

The following examples show how to use javax.json.JsonArray#getJsonObject() . 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: HFCAIdentity.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private void getHFCAIdentity(JsonObject result) {
    type = result.getString("type");
    if (result.containsKey("secret")) {
        this.secret = result.getString("secret");
    }
    maxEnrollments = result.getInt("max_enrollments");
    affiliation = result.getString("affiliation");
    JsonArray attributes = result.getJsonArray("attrs");

    Collection<Attribute> attrs = new ArrayList<Attribute>();
    if (attributes != null && !attributes.isEmpty()) {
        for (int i = 0; i < attributes.size(); i++) {
            JsonObject attribute = attributes.getJsonObject(i);
            Attribute attr = new Attribute(attribute.getString("name"), attribute.getString("value"), attribute.getBoolean("ecert", false));
            attrs.add(attr);
        }
    }
    this.attrs = attrs;
}
 
Example 2
Source File: JavaxJsonCollectionSerializationTest.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@Test
public void serializeMapWithMixedKeysAsJsonArrayOfEntryObjects()
{
    Map<Object, String> map = new LinkedHashMap<>();
    map.put( "foo", "bar" );
    map.put( newSomeValue( "baz" ), "bazar" );

    JsonValue json = jsonSerialization.toJson( map );
    assertThat( json.getValueType(), is( JsonValue.ValueType.ARRAY ) );

    JsonArray jsonArray = (JsonArray) json;
    JsonObject fooEntry = jsonArray.getJsonObject( 0 );
    JsonObject bazEntry = jsonArray.getJsonObject( 1 );
    assertThat( fooEntry.getString( "key" ), equalTo( "foo" ) );
    assertThat( fooEntry.getString( "value" ), equalTo( "bar" ) );
    assertThat( bazEntry.getJsonObject( "key" ).getString( "foo" ), equalTo( "baz" ) );
    assertThat( bazEntry.getString( "value" ), equalTo( "bazar" ) );
}
 
Example 3
Source File: ConfigPropertyResourceTest.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@Test
public void updateConfigPropertiesAggregateTest() {
    ConfigProperty prop1 = qm.createConfigProperty("my.group", "my.string1", "ABC", IConfigProperty.PropertyType.STRING, "A string");
    ConfigProperty prop2 = qm.createConfigProperty("my.group", "my.string2", "DEF", IConfigProperty.PropertyType.STRING, "A string");
    ConfigProperty prop3 = qm.createConfigProperty("my.group", "my.string3", "GHI", IConfigProperty.PropertyType.STRING, "A string");
    prop1 = qm.detach(ConfigProperty.class, prop1.getId());
    prop2 = qm.detach(ConfigProperty.class, prop2.getId());
    prop3 = qm.detach(ConfigProperty.class, prop3.getId());
    prop3.setPropertyValue("XYZ");
    Response response = target(V1_CONFIG_PROPERTY+"/aggregate").request()
            .header(X_API_KEY, apiKey)
            .post(Entity.entity(Arrays.asList(prop1, prop2, prop3), MediaType.APPLICATION_JSON));
    Assert.assertEquals(200, response.getStatus(), 0);
    JsonArray json = parseJsonArray(response);
    JsonObject modifiedProp = json.getJsonObject(2);
    Assert.assertNotNull(modifiedProp);
    Assert.assertEquals("my.group", modifiedProp.getString("groupName"));
    Assert.assertEquals("my.string3", modifiedProp.getString("propertyName"));
    Assert.assertEquals("XYZ", modifiedProp.getString("propertyValue"));
    Assert.assertEquals("STRING", modifiedProp.getString("propertyType"));
    Assert.assertEquals("A string", modifiedProp.getString("description"));
}
 
Example 4
Source File: JWKSResTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Validate that the jwks: protocol handler works
 * @throws Exception on failure
 */
@Test
public void testJwksURL() throws Exception {
    // Load the /signer-keyset.jwk resource from the classpath as a JWKS
    URL signerJwk = new URL("jwks:/signer-keyset.jwk");
    String signerJwksContent = signerJwk.getContent().toString();
    System.out.println(signerJwksContent);
    JsonObject jwks = Json.createReader(new StringReader(signerJwksContent)).readObject();
    JsonArray keys = jwks.getJsonArray("keys");
    JsonObject key = keys.getJsonObject(0);
    Assert.assertEquals(key.getJsonString("kty").getString(), "RSA");
    Assert.assertEquals(key.getJsonString("use").getString(), "sig");
    Assert.assertEquals(key.getJsonString("kid").getString(), "jwk-test");
    Assert.assertEquals(key.getJsonString("alg").getString(), "RS256");
    Assert.assertEquals(key.getJsonString("e").getString(), "AQAB");
    Assert.assertTrue(key.getJsonString("n").getString().startsWith("uGU_nmjYC7cKRR89NCAo"));
}
 
Example 5
Source File: JWKxPEMTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void generatePublicKeyFromJWKs() throws Exception {
    String jsonJwk = TokenUtils.readResource("/signer-keyset4k.jwk");
    System.out.printf("jwk: %s\n", jsonJwk);
    JsonObject jwks = Json.createReader(new StringReader(jsonJwk)).readObject();
    JsonArray keys = jwks.getJsonArray("keys");
    JsonObject jwk = keys.getJsonObject(0);
    String e = jwk.getString("e");
    String n = jwk.getString("n");

    byte[] ebytes = Base64.getUrlDecoder().decode(e);
    BigInteger publicExponent = new BigInteger(1, ebytes);
    byte[] nbytes = Base64.getUrlDecoder().decode(n);
    BigInteger modulus = new BigInteger(1, nbytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
    PublicKey publicKey = kf.generatePublic(rsaPublicKeySpec);
    System.out.printf("publicKey=%s\n", publicKey);
    String pem = new String(Base64.getEncoder().encode(publicKey.getEncoded()));
    System.out.printf("pem: %s\n", pem);
}
 
Example 6
Source File: NvdParser.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
private List<VulnerableSoftware> parseCpes(final QueryManager qm, final JsonObject node, final Vulnerability vulnerability) {
    final List<VulnerableSoftware> vsList = new ArrayList<>();
    if (node.containsKey("cpe_match")) {
        final JsonArray cpeMatches = node.getJsonArray("cpe_match");
        for (int k = 0; k < cpeMatches.size(); k++) {
            final JsonObject cpeMatch = cpeMatches.getJsonObject(k);
            if (cpeMatch.getBoolean("vulnerable", true)) { // only parse the CPEs marked as vulnerable
                final VulnerableSoftware vs = generateVulnerableSoftware(qm, cpeMatch, vulnerability);
                if (vs != null) {
                    vsList.add(vs);
                }
            }
        }
    }
    return vsList;
}
 
Example 7
Source File: SimpleTokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Decode a JWK(S) encoded private key string to an RSA PrivateKey
 * @param jwksValue - JWKS string value
 * @return PrivateKey from RSAPrivateKeySpec
 */
public static PrivateKey decodeJWKSPrivateKey(String jwksValue) throws Exception {
    JsonObject jwks = Json.createReader(new StringReader(jwksValue)).readObject();
    JsonArray keys = jwks.getJsonArray("keys");
    JsonObject jwk;
    if(keys != null) {
        jwk = keys.getJsonObject(0);
    }
    else {
        jwk = jwks;
    }
    String d = jwk.getString("d");
    String n = jwk.getString("n");

    byte[] dbytes = Base64.getUrlDecoder().decode(d);
    BigInteger privateExponent = new BigInteger(1, dbytes);
    byte[] nbytes = Base64.getUrlDecoder().decode(n);
    BigInteger modulus = new BigInteger(1, nbytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, privateExponent);
    return kf.generatePrivate(rsaPrivateKeySpec);
}
 
Example 8
Source File: JSONContentHandler.java    From jcypher with Apache License 2.0 6 votes vote down vote up
private JsonObject getPropertiesObject(long id, int rowIndex, ElemType typ) {
	JsonObject graphObject = getGraphObject(rowIndex);
	JsonArray elemsArray = null;
	if (typ == ElemType.NODE)
		elemsArray = graphObject.getJsonArray("nodes");
	else if (typ == ElemType.RELATION)
		elemsArray = graphObject.getJsonArray("relationships");
	int sz = elemsArray.size();
	for (int i = 0; i < sz; i++) {
		JsonObject elem = elemsArray.getJsonObject(i);
		String idStr = elem.getString("id");
		long elemId;
		try {
			elemId = Long.parseLong(idStr);
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}
		if (id == elemId) {
			return elem.getJsonObject("properties");
		}
	}
	return null;
}
 
Example 9
Source File: HFCAAffiliation.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
HFCAAffiliationResp(JsonObject result) {
    if (result.containsKey("affiliations")) {
        JsonArray affiliations = result.getJsonArray("affiliations");
        if (affiliations != null && !affiliations.isEmpty()) {
            for (int i = 0; i < affiliations.size(); i++) {
                JsonObject aff = affiliations.getJsonObject(i);
                this.childHFCAAffiliations.add(new HFCAAffiliation(aff));
            }
        }
    }
    if (result.containsKey("identities")) {
        JsonArray ids = result.getJsonArray("identities");
        if (ids != null && !ids.isEmpty()) {
            for (int i = 0; i < ids.size(); i++) {
                JsonObject id = ids.getJsonObject(i);
                HFCAIdentity hfcaID = new HFCAIdentity(id);
                this.identities.add(hfcaID);
            }
        }
    }
    if (result.containsKey("statusCode")) {
        this.statusCode = result.getInt("statusCode");
    }
}
 
Example 10
Source File: AsyncHealthTest.java    From smallrye-health with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncReadiness() {
    JsonObject json = smallRyeHealthReporter.getReadinessAsync().await().atMost(Duration.ofSeconds(5)).getPayload();

    // response size
    JsonArray checks = json.getJsonArray("checks");
    Assert.assertEquals(checks.size(), 1, "Expected one check response");

    JsonObject checkJson = checks.getJsonObject(0);
    Assert.assertEquals(SuccessReadinessAsync.class.getName(), checkJson.getString("name"));
    verifySuccessStatus(checkJson);

    assertOverallSuccess(json);
}
 
Example 11
Source File: HealthCheckResponseAttributesTest.java    From microprofile-health with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the health integration with CDI at the scope of a server runtime
 */
@Test
@RunAsClient
public void testSuccessResponsePayload() {
    Response response = getUrlHealthContents();

    // status code
    Assert.assertEquals(response.getStatus(), 200);

    JsonObject json = readJson(response);

    // response size
    JsonArray checks = json.getJsonArray("checks");
    Assert.assertEquals(checks.size(), 1, "Expected a single check response");

    // single procedure response
    JsonObject check = checks.getJsonObject(0);

    assertSuccessfulCheck(check, "attributes-check");

    // response payload attributes
    JsonObject data = check.getJsonObject("data");
    
    Assert.assertEquals(
            data.getString("first-key"),
            "first-val"
    );

    Assert.assertEquals(
            data.getString("second-key"),
            "second-val"
    );

    assertOverallSuccess(json);
}
 
Example 12
Source File: TestSiteToSiteMetricsReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testAmbariFormatWithNullValues() throws IOException, InitializationException {

    final Map<PropertyDescriptor, String> properties = new HashMap<>();
    properties.put(SiteToSiteMetricsReportingTask.FORMAT, SiteToSiteMetricsReportingTask.AMBARI_FORMAT.getValue());
    properties.put(SiteToSiteMetricsReportingTask.ALLOW_NULL_VALUES, "true");

    MockSiteToSiteMetricsReportingTask task = initTask(properties);
    task.onTrigger(context);

    assertEquals(1, task.dataSent.size());
    final String msg = new String(task.dataSent.get(0), StandardCharsets.UTF_8);
    JsonReader jsonReader = Json.createReader(new ByteArrayInputStream(msg.getBytes()));
    JsonArray array = jsonReader.readObject().getJsonArray("metrics");
    for(int i = 0; i < array.size(); i++) {
        JsonObject object = array.getJsonObject(i);
        assertEquals("nifi", object.getString("appid"));
        assertEquals("1234", object.getString("instanceid"));
        if(object.getString("metricname").equals("BytesReadLast5Minutes")) {
            for(Entry<String, JsonValue> kv : object.getJsonObject("metrics").entrySet()) {
                assertEquals("\"null\"", kv.getValue().toString());
            }
            return;
        }
    }
    fail();
}
 
Example 13
Source File: RoleInfo.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an array of RoleInfo corresponding to the JSON serialization returned
 * by {@link AddressControl#getRolesAsJSON()}.
 */
public static RoleInfo[] from(final String jsonString) throws Exception {
   JsonArray array = JsonUtil.readJsonArray(jsonString);
   RoleInfo[] roles = new RoleInfo[array.size()];
   for (int i = 0; i < array.size(); i++) {
      JsonObject r = array.getJsonObject(i);
      RoleInfo role = new RoleInfo(r.getString("name"), r.getBoolean("send"), r.getBoolean("consume"), r.getBoolean("createDurableQueue"), r.getBoolean("deleteDurableQueue"), r.getBoolean("createNonDurableQueue"), r.getBoolean("deleteNonDurableQueue"), r.getBoolean("manage"), r.getBoolean("browse"), r.getBoolean("createAddress"));
      roles[i] = role;
   }
   return roles;
}
 
Example 14
Source File: UserDefinedMetrics.java    From mysql_perf_analyzer with Apache License 2.0 5 votes vote down vote up
public static UserDefinedMetrics createFromJson(java.io.InputStream in)
{
	JsonReader jsonReader = null;
	UserDefinedMetrics udm = null;
	try
	{
		jsonReader = javax.json.Json.createReader(in);
		JsonObject jsonObject = jsonReader.readObject();
		jsonReader.close();
		udm = new UserDefinedMetrics(jsonObject.getString("groupName"));
		udm.setAuto("y".equalsIgnoreCase(jsonObject.getString("auto", null)));
		udm.setStoreInCommonTable("y".equalsIgnoreCase(jsonObject.getString("storeInCommonTable", null)));
		udm.setSource(jsonObject.getString("source"));
		udm.setUdmType(jsonObject.getString("type"));
		udm.setNameCol(jsonObject.getString("nameColumn", null));
		udm.setValueCol(jsonObject.getString("valueColumn", null));
		udm.setKeyCol(jsonObject.getString("keyColumn", null));
		udm.setSql(jsonObject.getString("sql", null));
		
		JsonArray metrics = jsonObject.getJsonArray("metrics");
		if(metrics != null )
		{
			int mlen = metrics.size();
			for(int i=0; i<mlen; i++)
			{
				JsonObject mobj = metrics.getJsonObject(i);
				udm.addmetric(mobj.getString("name"), 
						mobj.getString("sourceName"), 
						"y".equalsIgnoreCase(mobj.getString("inc")),
						Metric.strToMetricDataType(mobj.getString("dataType")));
			}
		}
	}catch(Exception ex)
	{
		logger.log(Level.WARNING, "Error to parse UDM", ex);
		//TODO
	}
	return udm;
}
 
Example 15
Source File: Alignment.java    From BioSolr with Apache License 2.0 4 votes vote down vote up
public Alignment(JsonObject hit) {
  target = hit.getString("acc");
  species = hit.getString("species");
  description = hit.getString("desc");
  score = Double.parseDouble(hit.getString("score"));
  eValue = Double.parseDouble(hit.getString("evalue"));

  JsonArray domains = hit.getJsonArray("domains");
  for (int i = 0; i < domains.size(); ++i) {
    JsonObject domain = domains.getJsonObject(i);
    
    // skip insignificant matches (by ind. eValue)
    eValueInd = Double.parseDouble(domain.getString("ievalue"));
    if (eValueInd >= SIGNIFICANCE_THRESHOLD) continue;
    
    eValueCond = Double.parseDouble(domain.getString("cevalue"));
    
    querySequence = domain.getString("alimodel");
    querySequenceStart = domain.getInt("alihmmfrom");
    querySequenceEnd = domain.getInt("alihmmto");
    
    match = domain.getString("alimline");
    
    targetSequence = domain.getString("aliaseq");
    targetSequenceStart = domain.getInt("alisqfrom");
    targetSequenceEnd = domain.getInt("alisqto");
    
    targetEnvelopeStart = domain.getInt("ienv");
    targetEnvelopeEnd = domain.getInt("jenv");
    
    posteriorProbability = domain.getString("alippline");
    
    bias = Double.parseDouble(domain.getString("bias"));
    accuracy = Double.parseDouble(domain.getString("oasc"));
    bitScore = domain.getJsonNumber("bitscore").doubleValue();
    
    identityPercent = 100 * domain.getJsonNumber("aliId").doubleValue();
    identityCount = domain.getInt("aliIdCount");
    
    similarityPercent = 100 * domain.getJsonNumber("aliSim").doubleValue();
    similarityCount = domain.getInt("aliSimCount");
    
    // we consider only the first significant match
    break;
  }
}
 
Example 16
Source File: MavenLicense.java    From sonarqube-licensecheck with Apache License 2.0 4 votes vote down vote up
public static List<MavenLicense> fromString(String mavenLicenseString)
{
    List<MavenLicense> mavenLicenses = new ArrayList<>();

    if (mavenLicenseString != null && mavenLicenseString.startsWith("["))
    {
        try (JsonReader jsonReader = Json.createReader(new StringReader(mavenLicenseString)))
        {
            JsonArray licensesJson = jsonReader.readArray();
            for (int i = 0; i < licensesJson.size(); i++)
            {
                JsonObject licenseJson = licensesJson.getJsonObject(i);
                String regex;
                try
                {
                    regex = licenseJson.getString("regex");
                }
                catch (NullPointerException e)
                {
                    regex = licenseJson.getString("licenseNameRegEx", null);
                }

                if (regex != null)
                {
                    mavenLicenses.add(new MavenLicense(regex, licenseJson.getString("license")));
                }
            }
        }
    }
    else if (StringUtils.isNotEmpty(mavenLicenseString))
    {
        // deprecated - remove with later release
        String[] mavenLicenseEntries = mavenLicenseString.split(";");
        for (String mavenLicenseEntry : mavenLicenseEntries)
        {
            String[] mavenLicenseEntryParts = mavenLicenseEntry.split("~");
            mavenLicenses.add(new MavenLicense(mavenLicenseEntryParts[0], mavenLicenseEntryParts[1]));
        }
    }

    return mavenLicenses;
}
 
Example 17
Source File: JmxServerControlTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testListConsumers() throws Exception {
   // Without this, the RMI server would bind to the default interface IP (the user's local IP mostly)
   System.setProperty("java.rmi.server.hostname", JMX_SERVER_HOSTNAME);

   // I don't specify both ports here manually on purpose. See actual RMI registry connection port extraction below.
   String urlString = "service:jmx:rmi:///jndi/rmi://" + JMX_SERVER_HOSTNAME + ":" + JMX_SERVER_PORT + "/jmxrmi";

   JMXServiceURL url = new JMXServiceURL(urlString);
   JMXConnector jmxConnector = null;

   try {
      jmxConnector = JMXConnectorFactory.connect(url);
      System.out.println("Successfully connected to: " + urlString);
   } catch (Exception e) {
      jmxConnector = null;
      e.printStackTrace();
      Assert.fail(e.getMessage());
   }

   try {
      MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
      String brokerName = "0.0.0.0";  // configured e.g. in broker.xml <broker-name> element
      ObjectNameBuilder objectNameBuilder = ObjectNameBuilder.create(ActiveMQDefaultConfiguration.getDefaultJmxDomain(), brokerName, true);
      ActiveMQServerControl activeMQServerControl = MBeanServerInvocationHandler.newProxyInstance(mBeanServerConnection, objectNameBuilder.getActiveMQServerObjectName(), ActiveMQServerControl.class, false);

      String addressName = "test_list_consumers_address";
      String queueName = "test_list_consumers_queue";
      activeMQServerControl.createAddress(addressName, RoutingType.ANYCAST.name());
      activeMQServerControl.createQueue(new QueueConfiguration(queueName).setAddress(addressName).setRoutingType(RoutingType.ANYCAST).toJSON());
      String uri = "tcp://localhost:61616";
      try (ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactory(uri, null)) {
         MessageConsumer consumer = cf.createConnection().createSession(true, Session.SESSION_TRANSACTED).createConsumer(new ActiveMQQueue(queueName));

         try {
            String options = JsonUtil.toJsonObject(ImmutableMap.of("field","queue", "operation", "EQUALS", "value", queueName)).toString();
            String consumersAsJsonString = activeMQServerControl.listConsumers(options, 1, 10);

            JsonObject consumersAsJsonObject = JsonUtil.readJsonObject(consumersAsJsonString);
            JsonArray array = (JsonArray) consumersAsJsonObject.get("data");

            Assert.assertEquals("number of consumers returned from query", 1, array.size());
            JsonObject jsonConsumer = array.getJsonObject(0);
            Assert.assertEquals("queue name in consumer", queueName, jsonConsumer.getString("queue"));
            Assert.assertEquals("address name in consumer", addressName, jsonConsumer.getString("address"));
         } finally {
            consumer.close();
         }
      }
   } finally {
      jmxConnector.close();
   }
}
 
Example 18
Source File: JsonReporterTest.java    From revapi with Apache License 2.0 4 votes vote down vote up
@Test
public void testReportsWritten() throws Exception {
    JsonReporter reporter = new JsonReporter();

    Revapi r = new Revapi(PipelineConfiguration.builder().withReporters(JsonReporter.class).build());

    AnalysisContext ctx = AnalysisContext.builder(r)
            .withOldAPI(API.of(new FileArchive(new File("old-dummy.archive"))).build())
            .withNewAPI(API.of(new FileArchive(new File("new-dummy.archive"))).build())
            .build();

    AnalysisContext reporterCtx = r.prepareAnalysis(ctx).getFirstConfigurationOrNull(JsonReporter.class);

    reporter.initialize(reporterCtx);

    buildReports().forEach(reporter::report);

    StringWriter out = new StringWriter();
    PrintWriter wrt = new PrintWriter(out);

    reporter.setOutput(wrt);

    reporter.close();

    JsonReader reader = Json.createReader(new StringReader(out.toString()));
    JsonArray diffs = reader.readArray();

    assertEquals(2, diffs.size());
    JsonObject diff = diffs.getJsonObject(0);
    assertEquals("code1", diff.getString("code"));
    assertEquals("old1", diff.getString("old"));
    assertEquals("new1", diff.getString("new"));
    JsonArray classifications = diff.getJsonArray("classification");
    assertEquals(1, classifications.size());
    JsonObject classification = classifications.getJsonObject(0);
    assertEquals("SOURCE", classification.getString("compatibility"));
    assertEquals("BREAKING", classification.getString("severity"));
    JsonArray attachments = diff.getJsonArray("attachments");
    JsonObject attachment = attachments.getJsonObject(0);
    assertEquals("at1", attachment.getString("name"));
    assertEquals("at1val", attachment.getString("value"));

    diff = diffs.getJsonObject(1);
    assertEquals("code2", diff.getString("code"));
    assertEquals("old2", diff.getString("old"));
    assertEquals("new2", diff.getString("new"));
    classifications = diff.getJsonArray("classification");
    assertEquals(1, classifications.size());
    classification = classifications.getJsonObject(0);
    assertEquals("BINARY", classification.getString("compatibility"));
    assertEquals("BREAKING", classification.getString("severity"));
    attachments = diff.getJsonArray("attachments");
    attachment = attachments.getJsonObject(0);
    assertEquals("at2", attachment.getString("name"));
    assertEquals("at2val", attachment.getString("value"));
}
 
Example 19
Source File: TestMetricsBuilder.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuildMetricsObject() {
    final Map<String, ?> config = Collections.emptyMap();
    final JsonBuilderFactory factory = Json.createBuilderFactory(config);

    final String instanceId = "1234-5678-1234-5678";
    final String applicationId = "NIFI";
    final String hostname = "localhost";
    final long timestamp = System.currentTimeMillis();

    final Map<String,String> metrics = new HashMap<>();
    metrics.put("a", "1");
    metrics.put("b", "2");

    final MetricsBuilder metricsBuilder = new MetricsBuilder(factory);
    final JsonObject metricsObject = metricsBuilder
            .applicationId(applicationId)
            .instanceId(instanceId)
            .hostname(hostname)
            .timestamp(timestamp)
            .addAllMetrics(metrics)
            .build();

    final JsonArray metricsArray = metricsObject.getJsonArray("metrics");
    Assert.assertNotNull(metricsArray);
    Assert.assertEquals(2, metricsArray.size());

    JsonObject firstMetric = metricsArray.getJsonObject(0);
    if (!"a".equals(firstMetric.getString(MetricFields.METRIC_NAME))) {
        firstMetric = metricsArray.getJsonObject(1);
    }

    Assert.assertEquals("a", firstMetric.getString(MetricFields.METRIC_NAME));
    Assert.assertEquals(applicationId, firstMetric.getString(MetricFields.APP_ID));
    Assert.assertEquals(instanceId, firstMetric.getString(MetricFields.INSTANCE_ID));
    Assert.assertEquals(hostname, firstMetric.getString(MetricFields.HOSTNAME));
    Assert.assertEquals(String.valueOf(timestamp), firstMetric.getString(MetricFields.TIMESTAMP));

    final JsonObject firstMetricValues = firstMetric.getJsonObject("metrics");
    Assert.assertEquals("1", firstMetricValues.getString("" + timestamp));
}
 
Example 20
Source File: Alignment.java    From BioSolr with Apache License 2.0 4 votes vote down vote up
public Alignment(JsonObject hit) {
  target = hit.getString("acc");
  species = hit.getString("species");
  description = hit.getString("desc");
  score = Double.parseDouble(hit.getString("score"));
  eValue = Double.parseDouble(hit.getString("evalue"));

  JsonArray domains = hit.getJsonArray("domains");
  for (int i = 0; i < domains.size(); ++i) {
    JsonObject domain = domains.getJsonObject(i);
    
    // skip insignificant matches (by ind. eValue)
    eValueInd = Double.parseDouble(domain.getString("ievalue"));
    if (eValueInd >= SIGNIFICANCE_THRESHOLD) continue;
    
    eValueCond = Double.parseDouble(domain.getString("cevalue"));
    
    querySequence = domain.getString("alimodel");
    querySequenceStart = domain.getInt("alihmmfrom");
    querySequenceEnd = domain.getInt("alihmmto");
    
    match = domain.getString("alimline");
    
    targetSequence = domain.getString("aliaseq");
    targetSequenceStart = domain.getInt("alisqfrom");
    targetSequenceEnd = domain.getInt("alisqto");
    
    targetEnvelopeStart = domain.getInt("ienv");
    targetEnvelopeEnd = domain.getInt("jenv");
    
    posteriorProbability = domain.getString("alippline");
    
    bias = Double.parseDouble(domain.getString("bias"));
    accuracy = Double.parseDouble(domain.getString("oasc"));
    bitScore = domain.getJsonNumber("bitscore").doubleValue();
    
    identityPercent = 100 * domain.getJsonNumber("aliId").doubleValue();
    identityCount = domain.getInt("aliIdCount");
    
    similarityPercent = 100 * domain.getJsonNumber("aliSim").doubleValue();
    similarityCount = domain.getInt("aliSimCount");
    
    // we consider only the first significant match
    break;
  }
}