Java Code Examples for javax.json.JsonArray

The following examples show how to use javax.json.JsonArray. These examples are extracted from open source projects. 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
@Test
public void getAllVulnerabilitiesTest() throws Exception {
    new SampleData();
    Response response = target(V1_VULNERABILITY).request()
            .header(X_API_KEY, apiKey)
            .get(Response.class);
    Assert.assertEquals(200, response.getStatus(), 0);
    Assert.assertEquals(String.valueOf(5), response.getHeaderString(TOTAL_COUNT_HEADER));
    JsonArray json = parseJsonArray(response);
    Assert.assertNotNull(json);
    Assert.assertEquals(5, json.size());
    Assert.assertEquals("INT-1", json.getJsonObject(0).getString("vulnId"));
    Assert.assertEquals("INT-2", json.getJsonObject(1).getString("vulnId"));
    Assert.assertEquals("INT-3", json.getJsonObject(2).getString("vulnId"));
    Assert.assertEquals("INT-4", json.getJsonObject(3).getString("vulnId"));
    Assert.assertEquals("INT-5", json.getJsonObject(4).getString("vulnId"));
}
 
Example 2
Source Project: smallrye-metrics   Source File: JsonMetadataExporterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void exportByMetricNameWithMultipleMetrics() {
    JsonMetadataExporter exporter = new JsonMetadataExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    applicationRegistry.counter("counter1", new Tag("key1", "value1"));
    applicationRegistry.counter("counter1", new Tag("key1", "value2"));
    applicationRegistry.counter("counter1", new Tag("key1", "value3"));

    String result = exporter.exportMetricsByName(MetricRegistry.Type.APPLICATION, "counter1").toString();
    JsonObject json = Json.createReader(new StringReader(result)).read().asJsonObject();

    JsonArray outerTagsArray = json.getJsonObject("counter1").getJsonArray("tags");
    assertEquals(3, outerTagsArray.size());

    JsonArray innerArray1 = outerTagsArray.getJsonArray(0);
    assertEquals(1, innerArray1.size());
    assertEquals("key1=value1", innerArray1.getString(0));

    JsonArray innerArray2 = outerTagsArray.getJsonArray(1);
    assertEquals(1, innerArray2.size());
    assertEquals("key1=value2", innerArray2.getString(0));

    JsonArray innerArray3 = outerTagsArray.getJsonArray(2);
    assertEquals(1, innerArray3.size());
    assertEquals("key1=value3", innerArray3.getString(0));
}
 
Example 3
Source Project: fido2   Source File: u2fPreauthBean.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Executes the pre-authentication process which primarily includes generating
 * authentication challenge parameters for the given username complying to the
 * protocol specified. did is the FIDO domain credentials.
 *
 * NOTE : The did will be used for the production
 * version of the FIDO server software. They can be ignored for the open-source
 * version.
 * @param did       - FIDO domain id
 * @param protocol  - U2F protocol version to comply with.
 * @param username  - username
 * @param keyhandle - The user could have multiple fido authenticators registered
 *                      successfully. An authentication challenge can pertain
 *                      to only one unique fido authenticator (key handle).
 * @param appidfromDB
 * @param transports
 * @return          - FEReturn object that binds the U2F registration challenge
 *                      parameters in addition to a set of messages that explain
 *                      the series of actions happened during the process.
 */
@Override
public FEreturn execute(Long did,
                        String protocol,
                        String username,
                        String keyhandle,
                        String appidfromDB,
                        JsonArray transports) {

    //  Log the entry and inputs
    skfsLogger.entering(skfsConstants.SKFE_LOGGER,classname, "execute");
    skfsLogger.logp(skfsConstants.SKFE_LOGGER,Level.FINE, classname, "execute", skfsCommon.getMessageProperty("FIDO-MSG-5001"),
                    " EJB name=" + classname +
                    " did=" + did +
                    " protocol=" + protocol +
                    " username=" + username);

    //  Generate a new U2FAuthenticationChallenge object and returns the same
    FEreturn fer = new FEreturn();
    fer.setResponse(new U2FAuthenticationChallenge(protocol, username, keyhandle,appidfromDB, transports));

    //  log the exit and return
    skfsLogger.logp(skfsConstants.SKFE_LOGGER,Level.FINE, classname, "execute", skfsCommon.getMessageProperty("FIDO-MSG-5002"), classname);
    skfsLogger.exiting(skfsConstants.SKFE_LOGGER,classname, "execute");
    return fer;
}
 
Example 4
/**
 * 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 5
Source Project: Java-EE-8-and-Angular   Source File: JsonDemo.java    License: MIT License 6 votes vote down vote up
private void jsonStreamFilter() {
    JsonReader reader = Json.createReader(JsonDemo.class.getResourceAsStream("/sample_priority.json"));
    JsonArray jsonarray = reader.readArray();

    JsonArray result = jsonarray.getValuesAs(JsonObject.class)
            .stream()
            .filter(j -> "High".equals(j.getString("priority")))
            .collect(JsonCollectors.toJsonArray());
    System.out.println("Stream Filter: " + result);
}
 
Example 6
Source Project: microprofile-jwt-auth   Source File: JWKxPEMTest.java    License: 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 7
Source Project: albert   Source File: WeiboStatus.java    License: MIT License 6 votes vote down vote up
public static StatusWapper constructWapperStatus(JsonObject res) throws WeiboException {
	// JsonObject jsonStatus = res.asJsonObject(); // asJsonArray();
	JsonObject jsonStatus = res;
	JsonArray statuses = null;
	try {
		if (!jsonStatus.isNull("statuses")) {
			statuses = jsonStatus.getJsonArray("statuses");
		}
		int size = statuses.size();
		List<WeiboStatus> status = new ArrayList<WeiboStatus>(size);
		for (int i = 0; i < size; i++) {
			status.add(new WeiboStatus(statuses.getJsonObject(i)));
		}
		long previousCursor = jsonStatus.getJsonNumber("previous_cursor").longValue();
		long nextCursor = jsonStatus.getJsonNumber("next_cursor").longValue();
		long totalNumber = jsonStatus.getJsonNumber("total_number").longValue();
		String hasvisible = String.valueOf(jsonStatus.getBoolean("hasvisible"));
		return new StatusWapper(status, previousCursor, nextCursor, totalNumber, hasvisible);
	} catch (JsonException jsone) {
		throw new WeiboException(jsone);
	}
}
 
Example 8
Source Project: jcypher   Source File: JSONContentHandler.java    License: Apache License 2.0 6 votes vote down vote up
private JsonArray getNodeLabelsObject(long id, int rowIndex) {
	JsonObject graphObject = getGraphObject(rowIndex);
	JsonArray elemsArray = graphObject.getJsonArray("nodes");
	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.getJsonArray("labels");
		}
	}
	return null;
}
 
Example 9
Source Project: sonarqube-licensecheck   Source File: ProjectLicense.java    License: Apache License 2.0 6 votes vote down vote up
public static List<ProjectLicense> fromString(String projectLicensesString)
{
    List<ProjectLicense> projectLicenses = new ArrayList<>();

    try (JsonReader jsonReader = Json.createReader(new StringReader(projectLicensesString)))
    {
        JsonArray projectLicensesJson = jsonReader.readArray();
        for (int i = 0; i < projectLicensesJson.size(); i++)
        {
            JsonObject projectLicenseJson = projectLicensesJson.getJsonObject(i);
            projectLicenses.add(new ProjectLicense(
                projectLicenseJson.getString("projectKey"),
                projectLicenseJson.getString("license"),
                projectLicenseJson.getString("status")));
        }
    }

    return projectLicenses;
}
 
Example 10
Source Project: vertx-spring-boot   Source File: AmqpClientIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonArray() {
    JsonArray original = Json.createArrayBuilder()
        .add(1)
        .add(true)
        .add("test")
        .add(Json.createObjectBuilder().add("key", "value"))
        .add(Json.createArrayBuilder(Arrays.asList(1, 2, 3)))
        .build();

    Mono<JsonArray> resultMono = createReceiver("test-queue")
        .mono()
        .map(AmqpMessage::bodyAsJsonArray);

    AmqpMessage message = AmqpMessage.create()
        .withJsonArrayAsBody(original)
        .build();
    createSender("test-queue")
        .send(message);

    StepVerifier.create(resultMono)
        .expectNext(original)
        .expectComplete()
        .verify(Duration.ofSeconds(5));
}
 
Example 11
@Test
void testToJsonErrors_WhenExceptionWhileDataFetchingErrorCaught_ShouldReturnJsonBodyWithCustomExtensions() {
    // Given
    Map<String, Object> extensions = new HashMap<>();
    extensions.put("code", "OPERATION_FAILED");
    GraphqlErrorException graphqlErrorException = GraphqlErrorException.newErrorException()
            .extensions(extensions)
            .build();
    ExceptionWhileDataFetching exceptionWhileDataFetching = new ExceptionWhileDataFetching(ExecutionPath.rootPath(),
            graphqlErrorException, new SourceLocation(1, 1));

    // When
    JsonArray jsonArray = executionErrorsService.toJsonErrors(singletonList(exceptionWhileDataFetching));

    // Then
    JsonObject extensionJsonObject = jsonArray.getJsonObject(0).getJsonObject("extensions");
    assertThat(extensionJsonObject.getString("exception")).isEqualTo("graphql.GraphqlErrorException");
    assertThat(extensionJsonObject.getString("classification")).isEqualTo("DataFetchingException");
    assertThat(extensionJsonObject.getString("code")).isEqualTo("OPERATION_FAILED");
}
 
Example 12
Source Project: ee8-sandbox   Source File: JsonpTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonPatch() {
    JsonReader reader = Json.createReader(JsonpTest.class.getResourceAsStream("/persons.json"));
    JsonArray jsonaArray = reader.readArray();

    JsonPatch patch = Json.createPatchBuilder()        
            .replace("/0/name", "Duke Oracle")
            .remove("/1")
            .build();

    JsonArray result = patch.apply(jsonaArray);
    System.out.println(result.toString());
    
    Type type = new ArrayList<Person>() {}.getClass().getGenericSuperclass();

    List<Person> person = JsonbBuilder.create().fromJson(result.toString(), type);
    assertEquals("Duke Oracle", person.get(0).getName());

}
 
Example 13
Source Project: FHIR   Source File: FHIRJsonPatchProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public JsonArray readFrom(Class<JsonArray> type, Type genericType, Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    log.entering(this.getClass().getName(), "readFrom");
    try (JsonReader reader = JSON_READER_FACTORY.createReader(nonClosingInputStream(entityStream))) {
        return reader.readArray();
    } catch (JsonException e) {
        if (RuntimeType.SERVER.equals(runtimeType)) {
            String acceptHeader = httpHeaders.getFirst(HttpHeaders.ACCEPT);
            Response response = buildResponse(
                buildOperationOutcome(Collections.singletonList(
                    buildOperationOutcomeIssue(IssueSeverity.FATAL, IssueType.INVALID, "FHIRProvider: " + e.getMessage(), null))), getMediaType(acceptHeader));
            throw new WebApplicationException(response);
        } else {
            throw new IOException("an error occurred during JSON Patch deserialization", e);
        }
    } finally {
        log.exiting(this.getClass().getName(), "readFrom");
    }
}
 
Example 14
Source Project: tomee   Source File: WeatherServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(3)
public void testHealthCheckDownService() {
    WebTarget webTarget = this.client.target(this.base.toExternalForm());
    String json = webTarget.path("/health").request(MediaType.APPLICATION_JSON).get().readEntity(String.class);

    JsonArray checks = this.readJson(json).getJsonArray("checks");
    JsonObject data = checks.getJsonObject(0).getJsonObject("data");

    assertEquals("Your account is temporary blocked due to exceeding of requests limitation of " +
                    "your subscription type. Please choose the proper subscription http://openweathermap.org/price",
            data.getString("weatherServiceErrorMessage"));

    assertEquals("OpenWeatherMap", checks.getJsonObject(0).getString("name"));
    assertEquals("DOWN", checks.getJsonObject(0).getString("state"));
}
 
Example 15
private void initMavenDependencies()
{
    JsonArray jsonArray = Json
        .createArrayBuilder()
        .add(Json.createObjectBuilder().add("nameMatches", "org.apache..*").add("license", "Apache-2.0"))
        .add(Json.createObjectBuilder().add("nameMatches", "org.glassfish..*").add("license", "CDDL-1.0"))
        .build();
    String initValueMavenDepependencies = jsonArray.toString();

    String mavenDependencies = persistentSettings.getSettings().getString(ALLOWED_DEPENDENCIES_KEY);

    if ((mavenDependencies != null) && !mavenDependencies.isEmpty())
    {
        return;
    }

    persistentSettings.getSettings().setProperty(ALLOWED_DEPENDENCIES_KEY, initValueMavenDepependencies);
    persistentSettings.saveProperty(ALLOWED_DEPENDENCIES_KEY, initValueMavenDepependencies);
}
 
Example 16
@Test
public void getVulnerabilitiesByComponentSha1Test() throws Exception {
    SampleData sampleData = new SampleData();
    Response response = target(V1_VULNERABILITY + "/component/" + sampleData.c1.getSha1()).request()
            .header(X_API_KEY, apiKey)
            .get(Response.class);
    Assert.assertEquals(200, response.getStatus(), 0);
    Assert.assertEquals(String.valueOf(2), response.getHeaderString(TOTAL_COUNT_HEADER));
    JsonArray json = parseJsonArray(response);
    Assert.assertNotNull(json);
    Assert.assertEquals(2, json.size());
    Assert.assertEquals("INT-1", json.getJsonObject(0).getString("vulnId"));
    Assert.assertEquals("INTERNAL", json.getJsonObject(0).getString("source"));
    Assert.assertEquals("Description 1", json.getJsonObject(0).getString("description"));
    Assert.assertEquals("CRITICAL", json.getJsonObject(0).getString("severity"));
    Assert.assertTrue(UuidUtil.isValidUUID(json.getJsonObject(0).getString("uuid")));
    Assert.assertEquals("INT-2", json.getJsonObject(1).getString("vulnId"));
    Assert.assertEquals("INTERNAL", json.getJsonObject(1).getString("source"));
    Assert.assertEquals("Description 2", json.getJsonObject(1).getString("description"));
    Assert.assertEquals("HIGH", json.getJsonObject(1).getString("severity"));
    Assert.assertTrue(UuidUtil.isValidUUID(json.getJsonObject(1).getString("uuid")));
}
 
Example 17
@Override
public void pullAndInstall(final String remote, final String name,
                           final JsonArray properties)
    throws IOException, UnexpectedResponseException {
    final HttpPost pull =
        new HttpPost(
            new UncheckedUriBuilder(this.baseUri.toString().concat("/pull"))
                .addParameter("remote", remote)
                .addParameter("name", name)
                .build()
        );
    try {
        pull.setEntity(
            new StringEntity(properties.toString())
        );
        this.client.execute(
            pull,
            new MatchStatus(
                pull.getURI(),
                HttpStatus.SC_NO_CONTENT
            )
        );
    } finally {
        pull.releaseConnection();
    }
}
 
Example 18
Source Project: jcypher   Source File: JSONContentHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getRelationType(long relationId, int rowIndex) {
	if (rowIndex >= 0) {
		JsonObject graphObject = getGraphObject(rowIndex);
		JsonArray 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 (relationId == elemId) {
				return elem.getString("type");
			}
		}
	}
	return null;
}
 
Example 19
Source Project: geojson   Source File: GeoJsonReader.java    License: Apache License 2.0 6 votes vote down vote up
private void parsePolygon(final JsonObject feature, final JsonArray coordinates) {
    if (coordinates.size() == 1) {
        createWay(coordinates.getJsonArray(0), true)
            .ifPresent(way -> fillTagsFromFeature(feature, way));
    } else if (coordinates.size() > 1) {
        // create multipolygon
        final Relation multipolygon = new Relation();
        multipolygon.put(TYPE, "multipolygon");
        createWay(coordinates.getJsonArray(0), true)
            .ifPresent(way -> multipolygon.addMember(new RelationMember("outer", way)));

        for (JsonValue interiorRing : coordinates.subList(1, coordinates.size())) {
            createWay(interiorRing.asJsonArray(), true)
                .ifPresent(way -> multipolygon.addMember(new RelationMember("inner", way)));
        }

        fillTagsFromFeature(feature, multipolygon);
        getDataSet().addPrimitive(multipolygon);
    }
}
 
Example 20
Source Project: logbook   Source File: GlobalContext.java    License: MIT License 6 votes vote down vote up
/**
 * 建造を更新します
 * @param data
 */
private static void doKdock(Data data) {
    try {
        // 建造ドックの空きをカウントします
        if (lastBuildKdock != null) {
            ResourceDto resource = getShipResource.get(lastBuildKdock);
            if (resource != null) {
                int freecount = 0;
                JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
                for (int i = 0; i < apidata.size(); i++) {
                    int state = ((JsonObject) apidata.get(i)).getJsonNumber("api_state").intValue();
                    if (state == 0) {
                        freecount++;
                    }
                }
                // 建造ドックの空きをセットします
                resource.setFreeDock(Integer.toString(freecount));
                KdockConfig.store(lastBuildKdock, resource);
            }
        }
        addConsole("建造を更新しました");
    } catch (Exception e) {
        LoggerHolder.LOG.warn("建造を更新しますに失敗しました", e);
        LoggerHolder.LOG.warn(data);
    }
}
 
Example 21
@Test
public void getVulnerabilitiesByComponentUuidTest() throws Exception {
    SampleData sampleData = new SampleData();
    Response response = target(V1_VULNERABILITY + "/component/" + sampleData.c1.getUuid().toString()).request()
            .header(X_API_KEY, apiKey)
            .get(Response.class);
    Assert.assertEquals(200, response.getStatus(), 0);
    Assert.assertEquals(String.valueOf(2), response.getHeaderString(TOTAL_COUNT_HEADER));
    JsonArray json = parseJsonArray(response);
    Assert.assertNotNull(json);
    Assert.assertEquals(2, json.size());
    Assert.assertEquals("INT-1", json.getJsonObject(0).getString("vulnId"));
    Assert.assertEquals("INTERNAL", json.getJsonObject(0).getString("source"));
    Assert.assertEquals("Description 1", json.getJsonObject(0).getString("description"));
    Assert.assertEquals("CRITICAL", json.getJsonObject(0).getString("severity"));
    Assert.assertTrue(UuidUtil.isValidUUID(json.getJsonObject(0).getString("uuid")));
    Assert.assertEquals("INT-2", json.getJsonObject(1).getString("vulnId"));
    Assert.assertEquals("INTERNAL", json.getJsonObject(1).getString("source"));
    Assert.assertEquals("Description 2", json.getJsonObject(1).getString("description"));
    Assert.assertEquals("HIGH", json.getJsonObject(1).getString("severity"));
    Assert.assertTrue(UuidUtil.isValidUUID(json.getJsonObject(1).getString("uuid")));
}
 
Example 22
Source Project: fabric-sdk-java   Source File: HFCAIdentity.java    License: 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 23
/**
 * Ctor.
 * @param client Used HTTP Client.
 * @param request HTTP Request.
 * @param mapper Function which should map the received JsonObject
 *  to the specified resource.
 */
ResourcesIterator(
    final HttpClient client, final HttpGet request,
    final Function<JsonObject, T> mapper
) {
    try {
        final JsonArray array = client.execute(
            request,
            new ReadJsonArray(
                new MatchStatus(request.getURI(), HttpStatus.SC_OK)
            )
        );
        this.resources = array.stream()
            .map(json -> (JsonObject) json)
            .map(
                json -> mapper.apply(json)
            ).collect(Collectors.toList())
            .iterator();
    } catch (final IOException ex) {
        throw new IllegalStateException(
            "IOException when calling " + request.getURI().toString(), ex
        );
    } finally {
        request.releaseConnection();
    }
}
 
Example 24
Source Project: coffee-testing   Source File: CreateOrderNaiveTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void createVerifyOrder() {
    Order order = new Order("Espresso", "Colombia");
    JsonObject requestBody = createJson(order);

    Response response = ordersTarget.request().post(Entity.json(requestBody));

    if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL)
        throw new AssertionError("Status was not successful: " + response.getStatus());

    URI orderUri = response.getLocation();

    Order loadedOrder = client.target(orderUri)
            .request(MediaType.APPLICATION_JSON_TYPE)
            .get(Order.class);

    Assertions.assertThat(loadedOrder).isEqualToComparingOnlyGivenFields(order, "type", "origin");

    List<URI> orders = ordersTarget.request(MediaType.APPLICATION_JSON_TYPE)
            .get(JsonArray.class).getValuesAs(JsonObject.class).stream()
            .map(o -> o.getString("_self"))
            .map(URI::create)
            .collect(Collectors.toList());

    assertThat(orders).contains(orderUri);
}
 
Example 25
/**
 * 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 26
Source Project: dependency-track   Source File: ProjectResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getProjectsDescOrderedRequestTest() {
    qm.createProject("ABC", null, "1.0", null, null, null, true, false);
    qm.createProject("DEF", null, "1.0", null, null, null, true, false);
    Response response = target(V1_PROJECT)
            .queryParam(ORDER_BY, "name")
            .queryParam(SORT, SORT_DESC)
            .request()
            .header(X_API_KEY, apiKey)
            .get(Response.class);
    Assert.assertEquals(200, response.getStatus(), 0);
    Assert.assertEquals(String.valueOf(2), response.getHeaderString(TOTAL_COUNT_HEADER));
    JsonArray json = parseJsonArray(response);
    Assert.assertNotNull(json);
    Assert.assertEquals("DEF", json.getJsonObject(0).getString("name"));
}
 
Example 27
Source Project: smallrye-graphql   Source File: CdiExecutionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMutationWithInvalidTimeInput() {
    JsonArray errors = executeAndGetError(MUTATION_INVALID_TIME_SCALAR);

    assertEquals(1, errors.size(),
            "Wrong size for errors while startPatrolling with wrong date");

    JsonObject error = errors.getJsonObject(0);

    assertFalse(error.isNull("message"), "message should not be null");

    assertEquals(
            "Validation error of type WrongType: argument 'time' with value 'StringValue{value='Today'}' is not a valid 'Time' @ 'startPatrolling'",
            error.getString("message"),
            "Wrong error message while startPatrolling with wrong date");
}
 
Example 28
/**
 * Verifies the custom health integration with CDI at the scope of a server runtime
 */
@Test
@RunAsClient
public void testSuccessResponsePayload() {
    Response response = getUrlCustomHealthContents("group1");

    // 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 29
Collection.CollectionConfigPackage parse(JsonArray jsonConfig) throws ChaincodeCollectionConfigurationException {

        Collection.CollectionConfigPackage.Builder colcofbuilder = Collection.CollectionConfigPackage.newBuilder();
        for (int i = jsonConfig.size() - 1; i > -1; --i) {

            Collection.StaticCollectionConfig.Builder ssc = Collection.StaticCollectionConfig.newBuilder();

            JsonValue j = jsonConfig.get(i);
            if (j.getValueType() != JsonValue.ValueType.OBJECT) {
                throw new ChaincodeCollectionConfigurationException(format("Expected StaticCollectionConfig to be Object type but got: %s", j.getValueType().name()));
            }

            JsonObject jsonObject = j.asJsonObject();
            JsonObject scf = getJsonObject(jsonObject, "StaticCollectionConfig"); // oneof .. may have different values in the future
            ssc.setName(getJsonString(scf, "name"))
                    .setBlockToLive(getJsonLong(scf, "blockToLive"))
                    .setMaximumPeerCount(getJsonInt(scf, "maximumPeerCount"))
                    .setMemberOrgsPolicy(Collection.CollectionPolicyConfig.newBuilder()
                            .setSignaturePolicy(parseSignaturePolicyEnvelope(scf)).build())
                    .setRequiredPeerCount(getJsonInt(scf, "requiredPeerCount"));

            colcofbuilder.addConfig(Collection.CollectionConfig.newBuilder().setStaticCollectionConfig(ssc).build());

        }
        return colcofbuilder.build();

    }
 
Example 30
Source Project: nifi   Source File: TestSiteToSiteMetricsReportingTask.java    License: 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();
}