javax.json.JsonArray Java Examples

The following examples show how to use javax.json.JsonArray. 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: JsonpTest.java    From ee8-sandbox with Apache License 2.0 8 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 #2
Source File: SingleCustomSuccessfulTest.java    From smallrye-health with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #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: u2fPreauthBean.java    From fido2 with 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 #5
Source File: JsonDemo.java    From Java-EE-8-and-Angular with 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 File: WeiboStatus.java    From albert with 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 #7
Source File: JsonMetadataExporterTest.java    From smallrye-metrics with 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 #8
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 #9
Source File: JSONContentHandler.java    From jcypher with 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 #10
Source File: ProjectLicense.java    From sonarqube-licensecheck with 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 #11
Source File: AmqpClientIT.java    From vertx-spring-boot with 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 #12
Source File: ExecutionErrorsServiceTest.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: FHIRJsonPatchProvider.java    From FHIR with 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 File: WeatherServiceTest.java    From tomee with 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
Source File: VulnerabilityResourceTest.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: VulnerabilityResourceTest.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@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
Source File: RtPlugins.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 File: JSONContentHandler.java    From jcypher with 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 File: GeoJsonReader.java    From geojson with 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 File: GlobalContext.java    From logbook with 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
Source File: VulnerabilityResourceTest.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@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 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 #23
Source File: ResourcesIterator.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 File: CreateOrderNaiveTest.java    From coffee-testing with 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
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 #26
Source File: ProjectResourceTest.java    From dependency-track with 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 File: CdiExecutionTest.java    From smallrye-graphql with 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
Source File: MavenDependencySettingsService.java    From sonarqube-licensecheck with Apache License 2.0 6 votes vote down vote up
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 #29
Source File: QueueControlTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testListMessagesAsJSONWithFilter() throws Exception {
   SimpleString key = new SimpleString("key");
   long matchingValue = RandomUtil.randomLong();
   long unmatchingValue = matchingValue + 1;
   String filter = key + " =" + matchingValue;

   SimpleString address = RandomUtil.randomSimpleString();
   SimpleString queue = RandomUtil.randomSimpleString();

   session.createQueue(new QueueConfiguration(queue).setAddress(address).setDurable(durable));
   QueueControl queueControl = createManagementControl(address, queue);

   ClientProducer producer = session.createProducer(address);
   ClientMessage matchingMessage = session.createMessage(durable);
   matchingMessage.putLongProperty(key, matchingValue);
   producer.send(matchingMessage);
   ClientMessage unmatchingMessage = session.createMessage(durable);
   unmatchingMessage.putLongProperty(key, unmatchingValue);
   producer.send(unmatchingMessage);

   String jsonString = queueControl.listMessagesAsJSON(filter);
   Assert.assertNotNull(jsonString);
   JsonArray array = JsonUtil.readJsonArray(jsonString);
   Assert.assertEquals(1, array.size());

   long l = Long.parseLong(array.getJsonObject(0).get("key").toString().replaceAll("\"", ""));
   Assert.assertEquals(matchingValue, l);

   consumeMessages(2, session, queue);

   jsonString = queueControl.listMessagesAsJSON(filter);
   Assert.assertNotNull(jsonString);
   array = JsonUtil.readJsonArray(jsonString);
   Assert.assertEquals(0, array.size());

   session.deleteQueue(queue);
}
 
Example #30
Source File: JavaxJsonFactories.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public JsonArrayBuilder cloneBuilderExclude( JsonArray jsonArray, JsonValue... values )
{
    List<JsonValue> excludes = Arrays.asList( values );
    JsonArrayBuilder job = builderFactory.createArrayBuilder();
    for( JsonValue entry : jsonArray )
    {
        if( !excludes.contains( entry ) )
        {
            job.add( entry );
        }
    }
    return job;
}