下面列出了org.hamcrest.collection.IsCollectionWithSize#javax.json.Json 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
description = "Verify that the injected raw token claim is as expected")
public void verifyInjectedRawToken() throws Exception {
Reporter.log("Begin verifyInjectedRawToken\n");
String uri = baseURL.toExternalForm() + "endp/verifyInjectedRawToken";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
.queryParam(Claims.raw_token.name(), token)
.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"));
}
/**
* RtNetworks can return its Docker parent.
*/
@Test
public void returnsDocker() {
MatcherAssert.assertThat(
new ListedNetworks(
new AssertRequest(
new Response(
HttpStatus.SC_OK,
Json.createArrayBuilder().build().toString()
)
),
URI.create("http://localhost"),
DOCKER
).docker(),
new IsEqual<>(DOCKER)
);
}
private static List<Map<String, String>> readJsonAsMap() throws FileNotFoundException {
List<Map<String, String>> mapList = new ArrayList<>();
try (JsonReader jsonReader = Json.createReader(new BufferedReader(new FileReader("big.json")))) {
// memory leak happens if reading & testing from the same methods
JsonArray array = jsonReader.readArray();
for (JsonValue jsonValue : array) {
JsonObject object= (JsonObject) jsonValue;
Map<String, String> map = new HashMap<>();
for (String key: object.keySet()) {
map.put(key.intern(), object.getString(key));
}
mapList.add(map);
}
}
return mapList;
}
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
description = "Verify that the injected customDouble claim is as expected")
public void verifyInjectedCustomDouble() throws Exception {
Reporter.log("Begin verifyInjectedCustomDouble\n");
String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomDouble";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
.queryParam("value", 3.141592653589793)
.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"));
}
@DELETE
@Path("{id}")
public Response deleteConfig(@PathParam("id") String configId) {
WebTarget target = resource().path(CONFIGS).path(configId);
Response response = deleteResponse(target);
String entity = response.readEntity(String.class);
if (entity.isEmpty()) {
JsonObjectBuilder jsonObject = Json.createObjectBuilder();
jsonObject.add("id", configId);
jsonObject.add("message", "the config is deleted.");
return Response.ok(jsonObject.build()).build();
}
try (JsonReader json = Json.createReader(new StringReader(entity))) {
return Response.status(response.getStatus()).entity(json.read()).build();
}
}
@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);
}
@DELETE
@Path("{id}")
public Response deleteService(@PathParam("id") String id) {
WebTarget target = resource().path("services").path(id);
Response response = deleteResponse(target);
try {
if (response.getStatus() == OK.getStatusCode())
return Response.ok(Json.createObjectBuilder().add("message", id + " service deleted.").build()).build();
else
return Response.status(response.getStatus()).entity(response.readEntity(JsonObject.class)).build();
} finally {
response.close();
}
}
private static JsonObject createJsonChannel(JsonArray orderers, JsonObject peers, JsonArray chaincodes) {
JsonObjectBuilder builder = Json.createObjectBuilder();
if (orderers != null) {
builder.add("orderers", orderers);
}
if (peers != null) {
builder.add("peers", peers);
}
if (chaincodes != null) {
builder.add("chaincodes", chaincodes);
}
return builder.build();
}
/**
* Verify that the token aud claim is as expected
*
*/
@Test()
public void verifyAudience2() {
io.restassured.response.Response response = RestAssured.given().auth()
.oauth2(token)
.when()
.queryParam(Claims.aud.name(), "")
.queryParam(Claims.iss.name(), "https://server.example.com")
.queryParam(Claims.auth_time.name(), authTimeClaim)
.get("/endp/verifyOptionalAudience").andReturn();
Assertions.assertEquals(HttpURLConnection.HTTP_OK, response.getStatusCode());
String replyString = response.body().asString();
JsonReader jsonReader = Json.createReader(new StringReader(replyString));
JsonObject reply = jsonReader.readObject();
Assertions.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
private void initializeDB() {
try (JsonReader reader = Json.createReader(new FileReader("Database.img"))) {
JsonObject dbData = reader.readObject();
int dbPort = dbData.getInt("dbPort", 3306);
String dbName = dbData.getString("dbGameWorld", "orionalpha");
String dbSource = dbData.getString("dbGameWorldSource", "127.0.0.1");
String[] dbInfo = dbData.getString("dbGameWorldInfo", "root,").split(",");
// Construct the instance of the Database
Database.createInstance(dbName, dbSource, dbInfo[0], dbInfo.length == 1 ? "" : dbInfo[1], dbPort);
// Load the initial instance of the Database
Database.getDB().load();
Logger.logReport("DB configuration parsed successfully");
} catch (FileNotFoundException ex) {
ex.printStackTrace(System.err);
}
}
/**
* Returns a JSON encoded array string representing this object.
* @return returns the current array as a JSON encode string
*/
@Override
public String toString(){
JsonArrayBuilder ab = Json.createArrayBuilder();
for (int x = 0; x < list.size(); ++x){
JsonValue value = list.get(x);
if (value instanceof EcommerceItem){
ab.add(((EcommerceItem)value).toJsonArray());
}
else{
ab.add(value);
}
}
return ab.build().toString();
}
/**
* RtContainer can wait with no problem.
* @throws Exception If something goes wrong.
*/
@Test
public void waitsOk() throws Exception {
int retval = new RtContainer(
Json.createObjectBuilder().add("Id", "123").build(),
new AssertRequest(
new Response(
HttpStatus.SC_OK,
Json.createObjectBuilder()
.add("StatusCode", 0)
.build().toString()
),
new Condition(
"Method should be a POST",
req -> req.getRequestLine().getMethod().equals("POST")
),
new Condition(
"Resource path must be /123/wait",
req -> req.getRequestLine().getUri().endsWith("/wait")
)
),
URI.create("http://localhost:80/1.30/containers/123"),
Mockito.mock(Docker.class)
).waitOn(null);
assertEquals(0, retval);
}
@GET
@Path("/verifyInjectedCustomString")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("Tester")
public JsonObject verifyInjectedCustomString(@QueryParam("value") String value) {
boolean pass = false;
String msg;
// iat
String customValue = customString.getString();
if(customValue == null || customValue.length() == 0) {
msg = "customString value is null or empty, FAIL";
}
else if(customValue.equals(value)) {
msg = "customString PASS";
pass = true;
}
else {
msg = String.format("customString: %s != %s", customValue, value);
}
JsonObject result = Json.createObjectBuilder()
.add("pass", pass)
.add("msg", msg)
.build();
return result;
}
private String buildGroupResponseObject(String name, String[] members, String[] occasions) {
JsonObjectBuilder group = Json.createObjectBuilder();
group.add(JSON_KEY_GROUP_NAME, name);
JsonArrayBuilder membersArray = Json.createArrayBuilder();
for (int i = 0; i < members.length; i++) {
membersArray.add(members[i]);
}
group.add(JSON_KEY_MEMBERS_LIST, membersArray.build());
JsonArrayBuilder occasionsArray = Json.createArrayBuilder();
for (int i = 0; i < occasions.length; i++) {
occasionsArray.add(occasions[i]);
}
group.add(JSON_KEY_OCCASIONS_LIST, occasionsArray.build());
return group.build().toString();
}
@POST
@Path("{id}/update")
public Response updateSecret(@PathParam("id") String id,
@QueryParam("version") String version,
JsonObject content) {
WebTarget target = resource().path("secrets").path(id).path("update").queryParam("version", version);
Response response = postResponse(target, content);
String entity = response.readEntity(String.class);
try {
if (entity.isEmpty()) {
return Response.ok(Json.createObjectBuilder().add("message", id + " updated.").build())
.build();
} else {
return Response.status(response.getStatus())
.entity(Json.createReader(new StringReader(entity)).read())
.build();
}
} finally {
response.close();
}
}
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
description = "Verify that the injected iat claim is as expected")
public void verifyInjectedIssuedAt() throws Exception {
Reporter.log("Begin verifyInjectedIssuedAt\n");
String uri = baseURL.toExternalForm() + "endp/verifyInjectedIssuedAt";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
.queryParam(Claims.iat.name(), iatClaim)
.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"));
}
@Override
public Properties readFrom(Class<Properties> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
JsonReader jr = Json.createReader(entityStream);
JsonObject json = jr.readObject();
Properties retVal = new Properties();
json.keySet().forEach(key -> {
JsonValue value = json.get(key);
if (!JsonValue.NULL.equals(value)) {
if (value.getValueType() != JsonValue.ValueType.STRING) {
throw new IllegalArgumentException(
"Non-String JSON prop value found in payload. Sample data is more than this sample can deal with. It's not intended to handle any payload.");
}
JsonString jstr = (JsonString) value;
retVal.setProperty(key, jstr.getString());
}
});
return retVal;
}
/**
* Get actions
*
* @return all actions from TD file in JsonObject format
*/
public JsonObject getActions() {
JsonObject actions = null;
if (thingDescription != null) {
try {
JsonArray actionsArr = thingDescription.getJsonArray("actions");
actions = Json.createObjectBuilder().add("actions", actionsArr).build();
} catch (JSONException e) {
logger.info("There are no actions in TD for object: " + objectId);
}
}
return actions;
}
@GET
@Path("/verifyInjectedIssuedAtStandard")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedIssuedAtStandard(@QueryParam("iat") Long iat) {
boolean pass = false;
String msg;
// iat
Long iatValue = issuedAtStandard.getValue();
if(iatValue == null || iatValue.intValue() == 0) {
msg = Claims.iat.name()+"value is null or empty, FAIL";
}
else if(iatValue.equals(iat)) {
msg = Claims.iat.name()+" PASS";
pass = true;
}
else {
msg = String.format("%s: %s != %s", Claims.iat.name(), iatValue, iat);
}
JsonObject result = Json.createObjectBuilder()
.add("pass", pass)
.add("msg", msg)
.build();
return result;
}
/**
* Content is a simple string containing the chat message.
* @return constructed message
*/
public static Message createChatMessage(String username, String message) {
// player,*,{...}
// {
// "type": "chat",
// "username": "username",
// "content": "<message>",
// "bookmark": "String representing last message seen"
// }
JsonObjectBuilder payload = Json.createObjectBuilder();
payload.add(TYPE, "chat");
payload.add(USERNAME, username);
payload.add(CONTENT, message);
payload.add(BOOKMARK, PREFIX + bookmark.incrementAndGet());
return new Message(Target.player, ALL, payload.build().toString());
}
@Test
public void testConnectionStatusWithNullValues() 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, "(Connection)");
properties.put(SiteToSiteStatusReportingTask.ALLOW_NULL_VALUES,"true");
MockSiteToSiteStatusReportingTask task = initTask(properties, pgStatus);
task.onTrigger(context);
final String msg = new String(task.dataSent.get(0), StandardCharsets.UTF_8);
JsonReader jsonReader = Json.createReader(new ByteArrayInputStream(msg.getBytes()));
JsonObject object = jsonReader.readArray().getJsonObject(0);
JsonValue destination = object.get("destinationName");
assertEquals(destination, JsonValue.NULL);
}
/**
* Given a Histogram with unit=MINUTES,
* check that the statistics from JsonExporter will be presented in MINUTES.
*/
@Test
public void histogram_json() {
MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
Metadata metadata = Metadata.builder()
.withName("timer1")
.withType(MetricType.TIMER)
.withUnit(MetricUnits.MINUTES)
.build();
Timer metric = registry.timer(metadata);
metric.update(Duration.ofHours(1));
metric.update(Duration.ofHours(2));
metric.update(Duration.ofHours(3));
JsonExporter exporter = new JsonExporter();
String exported = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID("timer1")).toString();
JsonObject json = Json.createReader(new StringReader(exported)).read().asJsonObject().getJsonObject("timer1");
assertEquals(120.0, json.getJsonNumber("p50").doubleValue(), 0.001);
assertEquals(120.0, json.getJsonNumber("mean").doubleValue(), 0.001);
assertEquals(60.0, json.getJsonNumber("min").doubleValue(), 0.001);
assertEquals(180.0, json.getJsonNumber("max").doubleValue(), 0.001);
}
@GET
@Path("/verifyInjectedIssuer")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedIssuer(@QueryParam("iss") String iss) {
boolean pass = false;
String msg;
String issValue = issuer.get();
if(issValue == null || issValue.length() == 0) {
msg = Claims.iss.name()+"value is null or empty, FAIL";
}
else if(issValue.equals(iss)) {
msg = Claims.iss.name()+" PASS";
pass = true;
}
else {
msg = String.format("%s: %s != %s", Claims.iss.name(), issValue, iss);
}
JsonObject result = Json.createObjectBuilder()
.add("pass", pass)
.add("msg", msg)
.build();
return result;
}
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
description = "Verify that the injected aud claim is as expected from Token2")
public void verifyInjectedAudience2() throws Exception {
Reporter.log("Begin verifyInjectedAudience2\n");
String token2 = TokenUtils.generateTokenString("/Token2.json");
String uri = baseURL.toExternalForm() + "endp/verifyInjectedAudience";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
.queryParam(Claims.aud.name(), "s6BhdRkqt3.2")
.queryParam(Claims.auth_time.name(), authTimeClaim);
Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token2).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"));
}
private void addObject(final JsonObjectBuilder builder, final TypeIdentifier identifier, final Map<String, TypeIdentifier> properties) {
final String definition = definitionNameBuilder.buildDefinitionName(identifier.getName(), jsonDefinitions);
if (jsonDefinitions.containsKey(definition)) {
builder.add("$ref", "#/definitions/" + definition);
return;
}
// reserve definition
jsonDefinitions.put(definition, Pair.of(identifier.getName(), Json.createObjectBuilder().build()));
final JsonObjectBuilder nestedBuilder = Json.createObjectBuilder();
properties.entrySet().stream().sorted(mapKeyComparator()).forEach(e -> nestedBuilder.add(e.getKey(), build(e.getValue())));
jsonDefinitions.put(definition, Pair.of(identifier.getName(), Json.createObjectBuilder().add("properties", nestedBuilder).build()));
builder.add("$ref", "#/definitions/" + definition);
}
@Path("/{name}")
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public Response deleteResponse(@PathParam("name") String name) {
System.out.println("Deleting database called " + name);
String response;
try {
ResponseHandler responseHandler = new ResponseHandler("/" + name);
response = responseHandler.invoke(RequestType.DELETE);
return Response.ok("Deleted database " + response).build();
} catch (Exception e) {
JsonObject exception = Json.createObjectBuilder().add("Exception", e.getMessage()).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(exception).build();
}
}
private RobotType[] getAllTypes(SpanContext parent) {
List<RobotType> types = new ArrayList<RobotType>();
String result = doGeneralGetCall(urlFactory + "/robottypes", parent, References.CHILD_OF);
JsonReader reader = Json.createReader(new StringReader(result));
JsonArray array = reader.readArray();
for (JsonValue jsonValue : array) {
types.add(RobotType.fromJSon(jsonValue.asJsonObject()));
}
return types.toArray(new RobotType[0]);
}
@Override
protected void writeInternal(JsonPatch jsonPatch, HttpOutputMessage outputMessage)
throws HttpMessageNotWritableException {
try (JsonWriter writer = Json.createWriter(outputMessage.getBody())) {
writer.write(jsonPatch.toJsonArray());
} catch (Exception e) {
throw new HttpMessageNotWritableException(e.getMessage(), e);
}
}
@Override
protected JsonMergePatch readInternal(Class<? extends JsonMergePatch> clazz, HttpInputMessage inputMessage)
throws HttpMessageNotReadableException {
try (JsonReader reader = Json.createReader(inputMessage.getBody())) {
return Json.createMergePatch(reader.readValue());
} catch (Exception e) {
throw new HttpMessageNotReadableException(e.getMessage(), inputMessage);
}
}
@POST
@Path("update")
public Response updateSwarm(@QueryParam("version") String version,
@DefaultValue("false") @QueryParam("rotateWorkerToken") boolean rotateWorkerToken,
@DefaultValue("false") @QueryParam("rotateManagerToken") boolean rotateManagerToken,
@DefaultValue("false") @QueryParam("rotateManagerUnlockKey") boolean rotateManagerUnlockKey,
JsonObject content) {
WebTarget target = resource().path("swarm").path("update")
.queryParam("rotateWorkerToken", rotateWorkerToken)
.queryParam("rotateManagerToken", rotateManagerToken)
.queryParam("rotateManagerUnlockKey", rotateManagerUnlockKey);
if (Objects.nonNull(version))
target = target.queryParam("version", version);
Response response = postResponse(target, content);
String entity = response.readEntity(String.class);
try {
if (entity.isEmpty()) {
return Response.ok(Json.createObjectBuilder().add("message", "Swarm updated.").build())
.build();
} else {
return Response.status(response.getStatus())
.entity(Json.createReader(new StringReader(entity)).read())
.build();
}
} finally {
response.close();
}
}