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

The following examples show how to use javax.json.JsonObject#getJsonArray() . 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: SingleLivenessFailedTest.java    From microprofile-health with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies the failed single Liveness integration with CDI at the scope of a server runtime
 */
@Test
@RunAsClient
public void testFailureResponsePayload() {
    Response response = getUrlLiveContents();

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

    JsonObject json = readJson(response);

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

    // single procedure response
    assertFailureCheck(checks.getJsonObject(0), "failed-check");

    assertOverallFailure(json);
}
 
Example 2
Source File: LibrariesTest.java    From appengine-plugins-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testServiceRoleMapping_hasNoDuplicateRoles() {
  for (JsonObject api : apis) {
    JsonArray serviceRoles = api.getJsonArray("serviceRoles");
    if (serviceRoles != null) {
      Set<String> roles = Sets.newHashSet();
      for (int i = 0; i < serviceRoles.size(); i++) {
        String role = serviceRoles.getString(i);
        if (roles.contains(role)) {
          Assert.fail("Role: " + role + " is defined multiple times");
        }
        roles.add(role);
      }
    }
  }
}
 
Example 3
Source File: SingleReadinessSuccessfulTest.java    From microprofile-health with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies the successful Readiness integration with CDI at the scope of a server runtime
 */
@Test
@RunAsClient
public void testSuccessResponsePayload() {
    Response response = getUrlReadyContents();

    // 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
    assertSuccessfulCheck(checks.getJsonObject(0), "successful-check");

    assertOverallSuccess(json);
}
 
Example 4
Source File: CustomersResource.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@PUT
@Path("batchadd/")
@Consumes(MediaType.APPLICATION_JSON)
public Response putUsers(JsonObject jsonEntity) {
	JsonArray jsonArray = jsonEntity.getJsonArray("customers");
	final JsonArrayBuilder result = Json.createArrayBuilder();
	jsonArray.forEach((jsonValue) -> {
		try {
			Customer c = createCustomer(jsonValue.asJsonObject());
			result.add(c.toJSon());
		} catch (ValidationException e) {
			result.add(Utils.errorAsJSon(e));
		}
	});
	return Response.accepted(result.build()).build();
}
 
Example 5
Source File: CDIProducedProceduresTest.java    From microprofile-health with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies the liveness and readiness health integration with CDI when the
 * Health Check procedures are defined with CDI Producers.
 */
@Test
@RunAsClient
public void testSuccessfulLivenessResponsePayload() {
    Response response = getUrlLiveContents();

    // 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
    assertSuccessfulCheck(checks.getJsonObject(0), "cdi-produced-successful-check");

    assertOverallSuccess(json);
}
 
Example 6
Source File: JobProcessor.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
String getStorageNames( JobDefinition od ) {
	String correlation = od.getCorrelation();
	String storageNames = "?";

	if ( !StringUtils.isEmpty( correlation ) && !correlation.equals( "null" ) ) {
		JsonReader reader = Json.createReader( new StringReader( correlation ) );
		JsonObject object = reader.readObject();
		if ( object.containsKey( "businessObject" ) ) {
			JsonObject ob = object.getJsonObject( "businessObject" );
			if ( ob.containsKey( "storageNames" ) ) {
				JsonArray a = ob.getJsonArray( "storageNames" );
				storageNames = "";
				for ( int i = 0; i < a.size(); i++ ) {
					storageNames += a.getString( i );
					if ( i != a.size() - 1 ) {
						storageNames += ",";
					}
				}
			}
		}
	}
	return storageNames;
}
 
Example 7
Source File: SingleReadinessFailedTest.java    From microprofile-health with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies the failed Readiness integration with CDI at the scope of a server runtime
 */
@Test
@RunAsClient
public void testFailureResponsePayload() {
    Response response = getUrlReadyContents();

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

    JsonObject json = readJson(response);

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

    // single procedure response
    assertFailureCheck(checks.getJsonObject(0), "failed-check");

    assertOverallFailure(json);
}
 
Example 8
Source File: DelayedCheckTest.java    From microprofile-health with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies the health integration with CDI when the bean creation takes longer than
 * the first request
 */
@Test
@RunAsClient
public void testSuccessResponsePayload() {
    Response response = getUrlReadyContents();

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

    JsonObject json = readJson(response);

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

    // single procedure response
    assertFailureCheck(checks.getJsonObject(0), "delayed-check");

    assertOverallFailure(json);
}
 
Example 9
Source File: ApiReqKousyouRemodelSlot.java    From logbook-kai with MIT License 6 votes vote down vote up
@Override
public void accept(JsonObject json, RequestMetaData req, ResponseMetaData res) {
    JsonObject data = json.getJsonObject("api_data");
    if (data != null) {
        Map<Integer, SlotItem> itemMap = SlotItemCollection.get()
                .getSlotitemMap();

        // 改修後装備
        JsonObject afterSlot = data.getJsonObject("api_after_slot");
        if (afterSlot != null) {
            SlotItem replace = SlotItem.toSlotItem(afterSlot);
            itemMap.put(replace.getId(), replace);
        }

        // 消費装備
        JsonArray useSlotId = data.getJsonArray("api_use_slot_id");
        if (useSlotId != null) {
            for (Integer slotId : JsonHelper.toIntegerList(useSlotId)) {
                itemMap.remove(slotId);
            }
        }
    }
}
 
Example 10
Source File: HealthCheckResponseValidationTest.java    From microprofile-health with Apache License 2.0 6 votes vote down vote up
/**
 * Validates the HealthCheckResponse concrete class definition by verifying if its 
 * deserialized properties correctly maps to the JSON schema protocol defined by the 
 * specification and the JSON health check response returned by the implementation.
 */
@Test
@RunAsClient
public void testValidateConcreteHealthCheckResponse() throws Exception {
    Response response = getUrlHealthContents();

    Assert.assertEquals(response.getStatus(), 200);
    
    JsonObject json = readJson(response);
    JsonArray checks = json.getJsonArray("checks");
    
    ObjectMapper mapper = new ObjectMapper(); 
    List<HealthCheckResponse> hcr = mapper.readValue(checks.toString(), new TypeReference<List<HealthCheckResponse>>() {});

    // Validates the name property from the HealthCheckResponse class
    Assert.assertEquals(
            hcr.get(0).getName(),
            "successful-check",
            String.format("Unexpected value for the HealthCheckResponse \"name\" property : %s", hcr.get(0).getName())
        );
    
    // Validates the status property from the HealthCheckResponse class
    Assert.assertEquals(hcr.get(0).getStatus(), HealthCheckResponse.Status.UP, 
            "Expected a successful check status for the HealthCheckResponse \"status\" property.");
}
 
Example 11
Source File: ApiGetMemberDeck.java    From logbook-kai with MIT License 6 votes vote down vote up
@Override
public void accept(JsonObject json, RequestMetaData req, ResponseMetaData res) {
    JsonArray array = json.getJsonArray("api_data");
    if (array != null) {
        Map<Integer, DeckPort> deckMap = JsonHelper.toMap(array, DeckPort::getId, DeckPort::toDeckPort);
        DeckPortCollection.get()
                .setDeckPortMap(deckMap);
        DeckPortCollection.get()
                .setMissionShips(deckMap.values()
                        .stream()
                        .filter(d -> d.getMission().get(0) != 0)
                        .map(DeckPort::getShip)
                        .flatMap(List::stream)
                        .collect(Collectors.toCollection(LinkedHashSet::new)));
    }
}
 
Example 12
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 13
Source File: MultipleLivenessFailedTest.java    From microprofile-health with Apache License 2.0 6 votes vote down vote up
/**
 * Test that Readiness is up
 */
@Test
@RunAsClient
public void testSuccessfulReadinessResponsePayload() {
    Response response = getUrlReadyContents();

    // 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
    assertSuccessfulCheck(checks.getJsonObject(0), "successful-check");

    assertOverallSuccess(json);
}
 
Example 14
Source File: GlobalContext.java    From logbook with MIT License 5 votes vote down vote up
/**
 * 遠征(帰還)を更新します
 *
 * @param data
 */
private static void doMissionResult(Data data) {
    try {
        JsonObject apidata = data.getJsonObject().getJsonObject("api_data");

        MissionResultDto result = new MissionResultDto();

        int clearResult = apidata.getJsonNumber("api_clear_result").intValue();
        result.setClearResult(clearResult);
        result.setQuestName(apidata.getString("api_quest_name"));

        if (clearResult != 0) {
            JsonArray material = apidata.getJsonArray("api_get_material");
            result.setFuel(material.getJsonNumber(0).toString());
            result.setAmmo(material.getJsonNumber(1).toString());
            result.setMetal(material.getJsonNumber(2).toString());
            result.setBauxite(material.getJsonNumber(3).toString());
        }

        CreateReportLogic.storeCreateMissionReport(result);
        missionResultList.add(result);

        addConsole("遠征(帰還)情報を更新しました");
    } catch (Exception e) {
        LoggerHolder.LOG.warn("遠征(帰還)を更新しますに失敗しました", e);
        LoggerHolder.LOG.warn(data);
    }
}
 
Example 15
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 16
Source File: CommunicationManager.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
public JsonArray parseThingDescriptionsFromRepresentation(Representation tds) {
	
	JsonObject json = null;
	
	try {
		json = readJsonObject(tds.getText());
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	if (json == null) {
		logger.warning("Can't parse representation.");
		return null;
	}
	
	JsonArray thingDescriptions = null;
	
	JsonObject message = json.getJsonObject("message");
	if (message == null) {
		
		thingDescriptions = json.getJsonArray("thingDescriptions");
	} else {
		thingDescriptions = message.getJsonArray("thingDescriptions");
	}
	
	if (thingDescriptions == null) {
		logger.warning("Can't parse representation.");
		return null;
	}
	
	return thingDescriptions;
}
 
Example 17
Source File: AsyncHealthTest.java    From smallrye-health with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncLiveness() {
    JsonObject json = smallRyeHealthReporter.getLivenessAsync().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(SuccessLivenessAsync.class.getName(), checkJson.getString("name"));
    verifySuccessStatus(checkJson);

    assertOverallSuccess(json);
}
 
Example 18
Source File: WebauthnService.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
private JsonArray getKeyIdsFromInput(JsonObject input){
    JsonArray keyIds = input.getJsonArray(Constants.RP_JSON_KEY_KEYIDS);
    if (keyIds == null) {
        throw new IllegalArgumentException("keyIds missing");
    }
    return keyIds;
}
 
Example 19
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 20
Source File: SparqlQuery.java    From vicinity-gateway-api with GNU General Public License v3.0 3 votes vote down vote up
private String getPropertyOfRemoteObject(String remoteObjectID, String propertyName, Map<String, String> parameters, String key) {
	
	StatusMessage statusMessage = descriptor.getPropertyOfRemoteObject(remoteObjectID, propertyName, parameters, null);
	
	if (statusMessage.isError()) {
		return null;
	}
	
	JsonObject jsonObject  = statusMessage.buildMessage();
	JsonArray jsonArray = jsonObject.getJsonArray(StatusMessage.ATTR_MESSAGE);
	
	logger.fine("JSON String: " + jsonArray.get(0).toString());
	
	return jsonArray.get(0).toString();
}