javax.json.JsonObject Java Examples

The following examples show how to use javax.json.JsonObject. 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: BundleTest.java    From FHIR with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #2
Source File: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: UserResourceAuthenticatedTest.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #4
Source File: WorldClockApiTest.java    From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License 6 votes vote down vote up
@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);
}
 
Example #5
Source File: SKFSClient.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
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);
}
 
Example #6
Source File: ProjectJson.java    From tcases with MIT License 6 votes vote down vote up
/**
 * 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);
    }
  }
 
Example #7
Source File: StrictLocationFilter.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: NotificationResource.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
@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();
}
 
Example #9
Source File: ApiReqCombinedBattleGobackPort.java    From logbook-kai with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example #10
Source File: ConnectionDescriptor.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
	
}
 
Example #11
Source File: PrimitiveInjectionEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #12
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 #13
Source File: ApiReqMemberItemuse.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * 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);
                        });
            }
        }
    }
}
 
Example #14
Source File: JsonValueInjectionTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #15
Source File: InventoryEndpointIT.java    From boost with Eclipse Public License 1.0 6 votes vote down vote up
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();
}
 
Example #16
Source File: SingleLivenessSuccessfulTest.java    From microprofile-health with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #17
Source File: SchemaBuilderTest.java    From jaxrs-analyzer with Apache License 2.0 6 votes vote down vote up
@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()));
}
 
Example #18
Source File: ApiGetMemberDeck.java    From logbook-kai with MIT License 6 votes vote down vote up
@Override
public void accept(JsonObject json, RequestMetaData req, ResponseMetaData res) {
    JsonArray array = json.getJsonArray("api_data");
    if (array != null) {
        Map<Integer, DeckPort> deckMap = JsonHelper.toMap(array, DeckPort::getId, DeckPort::toDeckPort);
        DeckPortCollection.get()
                .setDeckPortMap(deckMap);
        DeckPortCollection.get()
                .setMissionShips(deckMap.values()
                        .stream()
                        .filter(d -> d.getMission().get(0) != 0)
                        .map(DeckPort::getShip)
                        .flatMap(List::stream)
                        .collect(Collectors.toCollection(LinkedHashSet::new)));
    }
}
 
Example #19
Source File: OrdersResource.java    From scalable-coffee-shop with Apache License 2.0 5 votes vote down vote up
@GET
@Path("{id}")
public JsonObject getOrder(@PathParam("id") UUID orderId) {
    final CoffeeOrder order = queryService.getOrder(orderId);

    if (order == null)
        throw new NotFoundException();

    return Json.createObjectBuilder()
            .add("status", order.getState().name().toLowerCase())
            .add("type", order.getOrderInfo().getType().name().toLowerCase())
            .add("beanOrigin", order.getOrderInfo().getBeanOrigin())
            .build();
}
 
Example #20
Source File: BulkProcessorWithoutAfterGroup.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@ElementListener
public void process(@Input("in") final JsonObject in, @Output final OutputEmitter<JsonObject> out) {
    if (in == null) {
        return;
    }
    out.emit(in);
}
 
Example #21
Source File: CadfMetric.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static CadfMetric parse(InputStream in)
        throws FHIRException {
    try (JsonReader jsonReader =
            JSON_READER_FACTORY.createReader(in, StandardCharsets.UTF_8)) {
        JsonObject jsonObject = jsonReader.readObject();
        return parse(jsonObject);
    } catch (Exception e) {
        throw new FHIRException("Problem parsing the CadfCredential", e);
    }
}
 
Example #22
Source File: BattleResult.java    From logbook-kai with MIT License 5 votes vote down vote up
/**
 * JsonObjectから{@link Escape}を構築します
 *
 * @param json JsonObject
 * @return {@link Escape}
 */
public static Escape toEscape(JsonObject json) {
    Escape bean = new Escape();
    JsonHelper.bind(json)
            .setIntegerList("api_escape_idx", bean::setEscapeIdx)
            .setIntegerList("api_tow_idx", bean::setTowIdx);
    return bean;
}
 
Example #23
Source File: AbstractEmbeddedDBAccess.java    From jcypher with Apache License 2.0 5 votes vote down vote up
private JsonObject build() {
	for (int i = 0; i < this.innerResultsObjects.size(); i++) {
		this.innerResultsObjects.get(i).add("data", this.dataArrays.get(i));
		this.resultsArray.add(this.innerResultsObjects.get(i));
	}
	this.resultObject.add("results", this.resultsArray);
	this.resultObject.add("errors", this.errorsArray);
	return this.resultObject.build();
}
 
Example #24
Source File: InMemCollector.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
public static Collection<JsonObject> getShadedOutputs(final ClassLoader loader) {
    try {
        return Collection.class
                .cast(loader
                        .loadClass("org.talend.test.generated.target.InMemCollector")
                        .getField("OUTPUTS")
                        .get(null));
    } catch (final Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example #25
Source File: JsonDemo.java    From Java-EE-8-and-Angular with MIT License 5 votes vote down vote up
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);
}
 
Example #26
Source File: CdiExecutionTest.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
@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");

}
 
Example #27
Source File: RequestCaseJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the RequestCase instances represented by the given JSON array.
 */
public static List<RequestCase> asRequestCases( JsonArray json)
  {
  RequestCaseContext context = new RequestCaseContext();
  return
    json.getValuesAs( JsonObject.class)
    .stream()
    .map( rcJson -> asRequestCase( context, rcJson))
    .collect( toList());
  }
 
Example #28
Source File: ConversionUtilTest.java    From jcypher with Apache License 2.0 5 votes vote down vote up
private Statement convert(String input) {
	RecordedQuery rq = new RecordedQuery(false);
	StringReader sr = new StringReader(input);
	JsonReader reader = Json.createReader(sr);
	JsonObject jsonResult = reader.readObject();
	JSONConverter jc = new JSONConverter();
	List<Statement> statements = new ArrayList<Statement>();
	JSONConverterAccess.readStatement(jc, jsonResult, statements, rq);
	return statements.get(0);
}
 
Example #29
Source File: TableApiClient.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@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);
 
Example #30
Source File: TestXmlSchema2JsonSchema.java    From iaf with Apache License 2.0 5 votes vote down vote up
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();
}