org.hamcrest.collection.IsCollectionWithSize#javax.json.JsonObject源码实例Demo

下面列出了org.hamcrest.collection.IsCollectionWithSize#javax.json.JsonObject 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: nifi   文件: TestSiteToSiteStatusReportingTask.java
@Test
public void testRemoteProcessGroupStatusWithNullValues() throws IOException, InitializationException {
    final ProcessGroupStatus pgStatus = generateProcessGroupStatus("root", "Awesome", 1, 0);

    final Map<PropertyDescriptor, String> properties = new HashMap<>();
    properties.put(SiteToSiteUtils.BATCH_SIZE, "4");
    properties.put(SiteToSiteStatusReportingTask.COMPONENT_NAME_FILTER_REGEX, "Awesome.*");
    properties.put(SiteToSiteStatusReportingTask.COMPONENT_TYPE_FILTER_REGEX, "(RemoteProcessGroup)");
    properties.put(SiteToSiteStatusReportingTask.ALLOW_NULL_VALUES,"true");

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

    assertEquals(3, task.dataSent.size());
    final String msg = new String(task.dataSent.get(0), StandardCharsets.UTF_8);
    JsonReader jsonReader = Json.createReader(new ByteArrayInputStream(msg.getBytes()));
    JsonObject firstElement = jsonReader.readArray().getJsonObject(0);
    JsonValue targetURI = firstElement.get("targetURI");
    assertEquals(targetURI, JsonValue.NULL);
}
 
@Test
@Disabled
public void testNow() throws URISyntaxException {
    Response response = given()
            .when()
            .get("/data/time/now")
            .andReturn();

    Assertions.assertEquals(HttpURLConnection.HTTP_OK, response.getStatusCode());
    String replyString = response.body().asString();
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    System.out.println(reply);
    Now numbers = response.as(Now.class);
    System.out.println(numbers);
}
 
@Test
public void addTeamToUserTest() {
    String hashedPassword = String.valueOf(PasswordService.createHash("password".toCharArray()));
    qm.createManagedUser("blackbeard", "Captain BlackBeard", "[email protected]", hashedPassword, false, false, false);
    Team team = qm.createTeam("Pirates", false);
    IdentifiableObject ido = new IdentifiableObject();
    ido.setUuid(team.getUuid().toString());
    ManagedUser user = new ManagedUser();
    user.setUsername("blackbeard");
    Response response = target(V1_USER + "/blackbeard/membership").request()
            .header(X_API_KEY, apiKey)
            .post(Entity.entity(ido, MediaType.APPLICATION_JSON));
    Assert.assertEquals(200, response.getStatus(), 0);
    Assert.assertNull(response.getHeaderString(TOTAL_COUNT_HEADER));
    JsonObject json = parseJsonObject(response);
    Assert.assertNotNull(json);
    Assert.assertEquals("Captain BlackBeard", json.getString("fullname"));
    Assert.assertEquals("[email protected]", json.getString("email"));
    Assert.assertFalse(json.getBoolean("forcePasswordChange"));
    Assert.assertFalse(json.getBoolean("nonExpiryPassword"));
    Assert.assertFalse(json.getBoolean("suspended"));
}
 
源代码4 项目: tcases   文件: ProjectJson.java
/**
 * Returns the base test definition represented by the given JSON value.
 */
private static SystemTestDef asSystemTestDef( JsonValue json)
  {
  try
    {
    SystemTestDef systemTest = null;
    if( json != null && json.getValueType() == OBJECT)
      {
      systemTest = SystemTestJson.asSystemTestDef( (JsonObject) json);
      }

    return systemTest;
    }
  catch( Exception e)
    {
    throw new ProjectException( "Error reading base tests definition", e);
    }
  }
 
源代码5 项目: AIDR   文件: StrictLocationFilter.java
@Override
public boolean test(JsonObject t) {
	JsonValue c = t.get("coordinates");
	if (c.getValueType() != ValueType.OBJECT) {
		return false;
	}
	JsonObject coordinates = (JsonObject) c;
	if (!"Point".equals(coordinates.getString("type"))){
		return false;
	}
	JsonArray a = coordinates.getJsonArray("coordinates");
	assert a.size() == 2;
	double lon = a.getJsonNumber(0).doubleValue();
	double lat = a.getJsonNumber(1).doubleValue();
	for (BRect r : square) {
		if (lon < r.minLon || lon > r.maxLon)
			continue;
		if (lat >= r.minLat || lat <= r.maxLat)
			return true;
	}
	return false;
}
 
源代码6 项目: sample-acmegifts   文件: NotificationResource.java
@POST
@Path("/")
@Consumes("application/json")
public Response notify(JsonObject payload) {

  // Validate the JWT.  At this point, anyone can submit a notification if they
  // have a valid JWT.
  try {
    validateJWT();
  } catch (JWTException jwte) {
    return Response.status(Status.UNAUTHORIZED)
        .type(MediaType.TEXT_PLAIN)
        .entity(jwte.getMessage())
        .build();
  }

  String notification = payload.getString(JSON_KEY_NOTIFICATION);
  logger.info(notification);

  return Response.ok().build();
}
 
@Override
public void accept(JsonObject json, RequestMetaData req, ResponseMetaData res) {

    BattleLog log = AppCondition.get().getBattleResultConfirm();
    if (log != null) {
        BattleResult result = log.getResult();
        Escape escape = result.getEscape();

        Set<Integer> escapeSet = AppCondition.get()
                .getEscape();

        // 退避
        Optional.of(escape.getEscapeIdx())
                .map(e -> e.get(0))
                .map(i -> this.getShipId(log.getDeckMap(), i))
                .ifPresent(escapeSet::add);
        // 護衛
        Optional.of(escape.getTowIdx())
                .map(e -> e.get(0))
                .map(i -> this.getShipId(log.getDeckMap(), i))
                .ifPresent(escapeSet::add);
    }
}
 
/**
 * Responds to a request for getting the object events. It creates a {@link eu.bavenir.ogwapi.commons.messages.NetworkMessageResponse
 * response} that is then sent back to the requesting object.
 * 
 * @param requestMessage A message that came from the network.
 * @return Response to be sent back.
 */
private NetworkMessageResponse respondToGetObjectEvents(NetworkMessageRequest requestMessage) {
	
	JsonObject events = data.getEvents();
	
	NetworkMessageResponse response = new NetworkMessageResponse(config, logger);
	response.setResponseBody(events.toString());
	response.setContentType("application/json");
	response.setError(false);
	response.setResponseCode(CodesAndReasons.CODE_200_OK);
	response.setResponseCodeReason(CodesAndReasons.REASON_200_OK + "Events retrieved.");
	
	// don't forget to set the correlation id so the other side can identify what 
	// request does this response belong to
	response.setRequestId(requestMessage.getRequestId());
			
	return response;
	
}
 
源代码9 项目: fido2   文件: SKFSClient.java
public static String authenticate(String username, String origin, JsonObject signedResponse) {
    JsonObject auth_metadata = javax.json.Json.createObjectBuilder()
            .add("version", PROTOCOL_VERSION) // ALWAYS since this is just the first revision of the code
            .add("last_used_location", "Sunnyvale, CA")
            .add("username", username)
            .add("origin", origin)
            .build();
    JsonObjectBuilder auth_inner_response = javax.json.Json.createObjectBuilder()
            .add("authenticatorData", signedResponse.getJsonObject("response").getString("authenticatorData"))
            .add("signature", signedResponse.getJsonObject("response").getString("signature"))
            .add("userHandle", signedResponse.getJsonObject("response").getString("userHandle"))
            .add("clientDataJSON", signedResponse.getJsonObject("response").getString("clientDataJSON"));
    JsonObject auth_response = javax.json.Json.createObjectBuilder()
            .add("id", signedResponse.getString("id"))
            .add("rawId", signedResponse.getString("rawId"))
            .add("response", auth_inner_response) // inner response object
            .add("type", signedResponse.getString("type"))
            .build();
    JsonObjectBuilder payloadBuilder = Json.createObjectBuilder()
            .add("response", auth_response.toString())
            .add("metadata", auth_metadata.toString());
    return callSKFSRestApi(
        APIURI + Constants.REST_SUFFIX + Constants.AUTHENTICATE_ENDPOINT,
        payloadBuilder);
}
 
源代码10 项目: quarkus   文件: PrimitiveInjectionEndpoint.java
@GET
@Path("/verifyInjectedAudience")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedAudience(@QueryParam("aud") String audience) {
    boolean pass = false;
    String msg;
    // aud
    Set<String> audValue = aud;
    if (audValue == null || audValue.size() == 0) {
        msg = Claims.aud.name() + "value is null or empty, FAIL";
    } else if (audValue.contains(audience)) {
        msg = Claims.aud.name() + " PASS";
        pass = true;
    } else {
        msg = String.format("%s: %s != %s", Claims.aud.name(), audValue, audience);
    }
    JsonObject result = Json.createObjectBuilder()
            .add("pass", pass)
            .add("msg", msg)
            .build();
    return result;
}
 
源代码11 项目: geojson   文件: GeoJsonReader.java
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);
    }
}
 
源代码12 项目: logbook-kai   文件: ApiReqMemberItemuse.java
/**
 * api_data.api_getitem
 *
 * @param array api_getitem
 */
private void apiGetitem(JsonArray array) {
    if (array != null) {
        Map<Integer, SlotItem> map = SlotItemCollection.get()
                .getSlotitemMap();
        for (JsonValue value : array) {
            if (value != null && !JsonValue.NULL.equals(value)) {
                JsonObject obj = (JsonObject) value;
                Optional.ofNullable(obj.getJsonObject("api_slotitem"))
                        .map(SlotItem::toSlotItem)
                        .ifPresent(item -> {
                            item.setLevel(0);
                            item.setLocked(false);
                            map.put(item.getId(), item);
                        });
            }
        }
    }
}
 
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
    description = "Verify that the injected customStringArray claim is as expected")
public void verifyInjectedCustomStringArray() throws Exception {
    Reporter.log("Begin verifyInjectedCustomStringArray\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomStringArray";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", "value0", "value1", "value2")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
源代码14 项目: boost   文件: InventoryEndpointIT.java
public void testHostRegistration() {
    this.visitLocalhost();

    Response response = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
    this.assertResponse(baseUrl, response);

    JsonObject obj = response.readEntity(JsonObject.class);

    int expected = 1;
    int actual = obj.getInt("total");
    assertEquals("The inventory should have one entry for localhost", expected, actual);

    boolean localhostExists = obj.getJsonArray("systems").getJsonObject(0).get("hostname").toString()
            .contains("localhost");
    assertTrue("A host was registered, but it was not localhost", localhostExists);

    response.close();
}
 
/**
 * Verifies the successful single Liveness integration with CDI at the scope of a server runtime
 */
@Test
@RunAsClient
public void testSuccessResponsePayload() {
    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), "successful-check");

    assertOverallSuccess(json);
}
 
源代码16 项目: jaxrs-analyzer   文件: SchemaBuilderTest.java
@Test
public void testSingleDynamicDefinitionMissingNestedType() {
    final TypeIdentifier identifier = TypeIdentifier.ofDynamic();

    final Map<String, TypeIdentifier> properties = new HashMap<>();
    properties.put("test1", INT_IDENTIFIER);
    properties.put("hello1", STRING_IDENTIFIER);
    // unknown type identifier
    properties.put("array1", INT_LIST_IDENTIFIER);

    representations.put(identifier, TypeRepresentation.ofConcrete(identifier, properties));

    cut = new SchemaBuilder(representations);

    assertThat(cut.build(identifier).build(), is(Json.createObjectBuilder().add("$ref", "#/definitions/JsonObject").build()));

    final JsonObject definitions = cut.getDefinitions();
    assertThat(definitions, is(Json.createObjectBuilder()
            .add("JsonObject", Json.createObjectBuilder().add("properties", Json.createObjectBuilder()
                    .add("array1", Json.createObjectBuilder().add("type", "object"))
                    .add("hello1", type("string"))
                    .add("test1", type("integer"))))
            .build()));
}
 
源代码17 项目: logbook-kai   文件: ApiGetMemberDeck.java
@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)));
    }
}
 
源代码18 项目: FHIR   文件: BundleTest.java
@Test(groups = { "batch" })
public void testMissingRequestURL() throws Exception {
    WebTarget target = getWebTarget();

    JsonObjectBuilder bundleObject = TestUtil.getEmptyBundleJsonObjectBuilder();
    JsonObject PatientJsonObject = TestUtil.readJsonObject("Patient_JohnDoe.json");
    JsonObject requestJsonObject = TestUtil.getRequestJsonObject("POST", "Patient");
    JsonObjectBuilder resourceObject = Json.createBuilderFactory(null).createObjectBuilder();
    resourceObject.add( "resource", PatientJsonObject).add("request", requestJsonObject);

    bundleObject.add("Entry", Json.createBuilderFactory(null).createArrayBuilder().add(resourceObject));

    Entity<JsonObject> entity = Entity.entity(bundleObject.build(), FHIRMediaType.APPLICATION_FHIR_JSON);
    Response response = target.request().post(entity, Response.class);
    assertTrue(response.getStatus() >= 400);
}
 
源代码19 项目: component-runtime   文件: TableApiClient.java
@Request(path = "table/{tableName}")
@Codec(decoder = { InvalidContentDecoder.class })
@Documentation("read record from the table according to the data set definition")
Response<JsonObject> get(@Path("tableName") String tableName, @Header(AUTHORIZATION) String auth,
        @Header(X_NO_RESPONSE_BODY) boolean noResponseBody, @Query(SYSPARM_QUERY) String query,
        @Query(SYSPARM_FIELDS) String fields, @Query(SYSPARM_OFFSET) int offset, @Query(SYSPARM_LIMIT) int limit,
        @Query(SYSPARM_EXCLUDE_REFERENCE_LINK) boolean excludeReferenceLink,
        @Query(SYSPARM_SUPPRESS_PAGINATION_HEADER) boolean suppressPaginationHeader);
 
源代码20 项目: KITE   文件: RunInfo.java
/**
 * Gets json.
 *
 * @return the json
 */
public JsonObject getJson() {
  return Json.createObjectBuilder()
      .add("revision", revision)
      .add("product", product)
      .add("browserVersion", browserVersion)
      .add("bits", bits)
      .add("os", os)
      .add("osVersion", osVersion)
      .build();
}
 
源代码21 项目: Java-EE-8-and-Angular   文件: JsonDemo.java
private void simple() {
    JsonObject json = Json.createObjectBuilder()
            .add("name", "Raise alert on failure")
            .add("id", Long.valueOf(2003))
            .build();
    String result = json.toString();
    System.out.println("JsonObject simple : " + result);
}
 
源代码22 项目: rapid   文件: Service.java
@GET
@Path("{id}/logs")
public Response serviceLiogs(@PathParam("id") String id,
                               @DefaultValue("false") @QueryParam("details") boolean details,
                               @DefaultValue("false") @QueryParam("stdout") boolean stdout,
                               @DefaultValue("false") @QueryParam("stderr") boolean stderr,
                               @DefaultValue("0") @QueryParam("since") String since,
                               @DefaultValue("false") @QueryParam("timestamps") boolean timestamps,
                               @DefaultValue("all") @QueryParam("tail") String tail) {

    WebTarget target = resource().path("services").path(id).path("logs")
            .queryParam("details", details)
            .queryParam("follow", false)
            .queryParam("stdout", stdout)
            .queryParam("stderr", stderr)
            .queryParam("since", since)
            .queryParam("timestamps", timestamps)
            .queryParam("tail", tail);

    Response response = getResponse(target);
    try {
        int status = response.getStatus();
        if (status == OK.getStatusCode()) {
            return Response.ok(Json.createObjectBuilder().add("message", response.readEntity(String.class)).build())
                    .build();
        } else {
            return Response
                    .status(response.getStatus())
                    .entity(response.readEntity(JsonObject.class))
                    .build();
        }
    } finally {
        response.close();
    }
}
 
源代码23 项目: iaf   文件: TestXmlSchema2JsonSchema.java
private String jsonPrettyPrint(String json) {
	StringWriter sw = new StringWriter();
	JsonReader jr = Json.createReader(new StringReader(json));
	JsonObject jobj = jr.readObject();

	Map<String, Object> properties = new HashMap<>(1);
	properties.put(JsonGenerator.PRETTY_PRINTING, true);

	JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
	try (JsonWriter jsonWriter = writerFactory.createWriter(sw)) {
		jsonWriter.writeObject(jobj);
	}

	return sw.toString().trim();
}
 
源代码24 项目: smallrye-graphql   文件: CdiExecutionTest.java
@Test
public void testMutationScalarJavaMapping() {
    JsonObject data = executeAndGetData(MUTATION_SCALAR_MAPPING);

    assertFalse(data.isNull("provisionHero"), "provisionHero should not be null");

    assertFalse(data.getJsonObject("provisionHero").isNull("name"), "name should not be null");
    assertEquals("Starlord", data.getJsonObject("provisionHero").getString("name"),
            "Wrong name while provisioning hero");

    assertFalse(data.getJsonObject("provisionHero").isNull("equipment"), "equipment should not be null");
    assertEquals(1, data.getJsonObject("provisionHero").getJsonArray("equipment").size(),
            "Wrong size equipment while provisioning member");

}
 
源代码25 项目: karaf-decanter   文件: JsonUnmarshaller.java
private Map<String, Object> build(JsonObject value) {
    Map<String, Object> map = new HashMap<>();
    Iterator<Map.Entry<String, JsonValue>> entrySet = value.entrySet().iterator();
    while (entrySet.hasNext()) {
        Map.Entry<String, JsonValue> entry = entrySet.next();
        map.put(entry.getKey(), unmarshalAttribute(entry.getValue()));
    }
    return map;
}
 
源代码26 项目: tomee   文件: WeatherServiceTest.java
private void assertJsonFormat(final String metricPath) {
    WebTarget webTarget = this.client.target(this.base.toExternalForm());
    final String metric = webTarget
            .path(metricPath)
            .request()
            .accept(MediaType.APPLICATION_JSON)
            .get(String.class);

    assertNotNull(metric);

    JsonObject metricJson = Json.createReader(new StringReader(metric)).readObject();
    final int temperature = metricJson.getInt("weather_day_temperature");
    assertEquals(temperature, 30);
}
 
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response putRobotType(JsonObject jsonEntity) {
	RobotType newType = RobotType.fromJSon(jsonEntity);

	if ((newType.getTypeId() != null) && !newType.getTypeId().equals(robotTypeId)) {
		return Response.status(409).entity("customerIds differ!\n").build();
	}
	DataAccess.addRobotType(newType);
	return Response.noContent().build();
}
 
源代码28 项目: FHIR   文件: BundleTest.java
@Test(groups = { "batch" })
public void testMissingResource() throws Exception {
    WebTarget target = getWebTarget();

    JsonObjectBuilder bundleObject = TestUtil.getEmptyBundleJsonObjectBuilder();
    JsonObject requestJsonObject = TestUtil.getRequestJsonObject("POST", "Patient");
    JsonObjectBuilder resourceObject = Json.createBuilderFactory(null).createObjectBuilder();
    resourceObject.add("request", requestJsonObject);

    bundleObject.add("Entry", Json.createBuilderFactory(null).createArrayBuilder().add(resourceObject));

    Entity<JsonObject> entity = Entity.entity(bundleObject.build(), FHIRMediaType.APPLICATION_FHIR_JSON);
    Response response = target.request().post(entity, Response.class);
    assertTrue(response.getStatus() >= 400);
}
 
源代码29 项目: charles   文件: JsonWebPageTestCase.java
/**
 * {@link JsonWebPage} can convert a WebPage to JsonObject.
 * @throws Exception - if something goes wrong.
 */
@Test
public void convertsPageToJsonObject() throws Exception {
    WebPage page = new SnapshotWebPage();
    page.setTitle("test page | title");
    page.setTextContent("Text content on this test web page...");
    page.setUrl("http://www.amihaiemil.com");
    JsonObject json = (new JsonWebPage(page)).toJsonObject();
    assertTrue(json.getString("id").equals("http://www.amihaiemil.com"));
    assertTrue(json.getString("url") != null);
    assertTrue(json.getString("title").equals("test page | title"));
    assertTrue(json.getString("textContent").equals("Text content on this test web page..."));
}
 
源代码30 项目: tutorials   文件: JsonUnitTest.java
@Test
public void whenUsingObjectModelToQueryForSpecificProperty_thenExpectedValueIsReturned(
        ) throws IOException, ParseException {
    JsonReader reader = Json.createReader(new StringReader(petshopJson));

    JsonObject jsonObject = reader.readObject();
    
    assertEquals(
            "The query should return the 'name' property of the third pet from the list", 
            "Jake", 
            jsonObject.getJsonArray("pets").getJsonObject(2).getString("name"));
}