Java Code Examples for javax.json.JsonObject#toString()

The following examples show how to use javax.json.JsonObject#toString() . 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: AsciidocWebkitConverter.java    From AsciidocFX with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<ConverterResult> convertContent(String functionName, String asciidoc, JsonObject config) {

        final CompletableFuture<ConverterResult> completableFuture = new CompletableFuture();
        final String taskId = UUID.randomUUID().toString();

        webWorkerTasks.put(taskId, completableFuture);
        final String conf = config.toString();
        threadService.runActionLater(() -> {
            this.setMember("taskId", taskId);
            this.setMember("editorValue", asciidoc);
            this.setMember("editorOptions", conf);
            try {
                webEngine().executeScript(String.format("if ((typeof %s)!== \"undefined\"){ %s(taskId,editorValue,editorOptions) }", functionName, functionName));
            } catch (Exception e) {
                completableFuture.completeExceptionally(e);
            }
        });

        return completableFuture;
    }
 
Example 2
Source File: EncryptorConfigTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void unmarshal() {

    JsonObject json =
            Json.createObjectBuilder()
                    .add("type", "EC")
                    .add(
                            "properties",
                            Json.createObjectBuilder()
                                    .add("greeting", "Hellow")
                                    .add("something", "ELSE")
                                    .addNull("bogus"))
                    .build();

    String data = json.toString();

    EncryptorConfig result = JaxbUtil.unmarshal(new ByteArrayInputStream(data.getBytes()), EncryptorConfig.class);

    assertThat(result.getProperties()).containsKeys("greeting", "something", "bogus");
    assertThat(result.getProperties().get("greeting")).isEqualTo("Hellow");
    assertThat(result.getProperties().get("something")).isEqualTo("ELSE");
    assertThat(result.getProperties().get("bogus")).isNull();
}
 
Example 3
Source File: JsonEncoder.java    From sample.daytrader7 with Apache License 2.0 5 votes vote down vote up
@Override
public String encode(JsonMessage message) throws EncodeException {
    
    JsonObject jsonObject = Json.createObjectBuilder()
            .add("key", message.getKey())
            .add("value", message.getValue()).build();

    return jsonObject.toString();
}
 
Example 4
Source File: clientUtil.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String keyHandleEncode(String key, String origin, String sha1sumkey) {
    JsonObject j;

    j = Json.createObjectBuilder().add("key", key)
            .add("sha1", sha1sumkey)
            .add("origin_hash", origin)
            .build();
    return j.toString();

}
 
Example 5
Source File: clientUtil.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String createRegistrationResponse(String ClientData, String SessionId, String RegistrationData) {

        JsonObject regResp = Json.createObjectBuilder()
                .add(CSConstants.JSON_KEY_BROWSERDATA, ClientData)
                .add(CSConstants.JSON_KEY_SESSIONID, SessionId)
                .add(CSConstants.JSON_KEY_REGISTRATIONDATA, RegistrationData)
                .build();
        return regResp.toString();

    }
 
Example 6
Source File: ActiveMQServerControlMultiThreadTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private String createJsonFilter(String fieldName, String operationName, String value) {
   HashMap<String, Object> filterMap = new HashMap<>();
   filterMap.put("field", fieldName);
   filterMap.put("operation", operationName);
   filterMap.put("value", value);
   JsonObject jsonFilterObject = JsonUtil.toJsonObject(filterMap);
   return jsonFilterObject.toString();
}
 
Example 7
Source File: CommunicationManager.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * getThingDescriptions - Return all pages of the thing descriptions of IoT object(s).
 * 
 * @param sourceObjectId 
 * 
 * @return The list of thing descriptions 
 */
public Representation getThingDescriptions(String sourceObjectId) {
	
	if (sourceObjectId == null || sourceObjectId.isEmpty()) {
		logger.warning("Method parameter sourceObjectId can't be null nor empty.");
		
		return null;
	}
	
	JsonObjectBuilder mainObjectBuilder = Json.createObjectBuilder();
	JsonArrayBuilder mainArrayBuilder = Json.createArrayBuilder();
	
	Representation r = null;
	int i = 0;
	
	do {
		
		r = getThingDescriptions(sourceObjectId, i++);
		
		if (r == null) {
			break;
		}
		
		JsonArray tds = parseThingDescriptionsFromRepresentation(r);
		tds.forEach(item -> {
			mainArrayBuilder.add(item);
		});
	}
	while (true);
	
	mainObjectBuilder.add(ATTR_TDS, mainArrayBuilder);
	JsonObject json = mainObjectBuilder.build();
	
	return new JsonRepresentation(json.toString());
}
 
Example 8
Source File: InvokeWithJsonPProviderTest.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
private void testPut(JsonPClient client, String clientType) {
    reset();
    stubFor(put(urlEqualTo("/id"))
                .willReturn(aResponse()
                            .withHeader("Content-Type", "application/json")
                            .withStatus(200).withBody("{\"someOtherKey\":\"newValue\"}")));

    JsonObject jsonObject = Json.createObjectBuilder().add("someKey", "newValue").build();
    String jsonObjectAsString = jsonObject.toString();
    JsonObject response = client.update("id", jsonObject);
    assertEquals(response.getString("someOtherKey"), "newValue",
        "The value of 'someOtherKey' on response should be 'someOtherKey' in client "+clientType);

    verify(1, putRequestedFor(urlEqualTo("/id")).withRequestBody(equalTo(jsonObjectAsString)));
}
 
Example 9
Source File: FHIRNotificationUtil.java    From FHIR with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes the notification event into a JSON string.
 * @param event the FHIRNotificationEvent structure to be serialized
 * @param includeResource a flag that controls whether or not the resource object within
 * the event structure should be included in the serialized message.
 * @return the serialized message as a String
 * @throws FHIRException 
 */
public static String toJsonString(FHIRNotificationEvent event, boolean includeResource) throws FHIRException {
    JsonObjectBuilder builder = JSON_BUILDER_FACTORY.createObjectBuilder();
    builder.add("lastUpdated", event.getLastUpdated());
    builder.add("location", event.getLocation());
    builder.add("operationType", event.getOperationType());
    builder.add("resourceId", event.getResourceId());
    if (includeResource && event.getResource() != null) {
        builder.add("resource", JsonSupport.toJsonObject(event.getResource()));
    }
    JsonObject jsonObject = builder.build();
    String jsonString = jsonObject.toString();
    return jsonString;
}
 
Example 10
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 11
Source File: FacetFieldsSearchTest.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
@BeforeClass(alwaysRun = true)
public void dataPreparation() throws Exception
{
    serverHealth.assertServerIsOnline();
    
    fname = unique_searchString + "facet";

    testSite = new SiteModel(RandomData.getRandomName("SiteSearch"));
    testSite.setVisibility(Visibility.PRIVATE);
    
    testSite = dataSite.usingUser(testUser).createSite(testSite);
    
    // Create another user who would not have access to the Private Site created by testUser
    userWithNoAccess = dataUser.createRandomTestUser("UserSearch2");
    userCanAccessTextFile = dataUser.createRandomTestUser("UserSearch3");
    
    // Create a folder and a file as test User
    FolderModel testFolder = new FolderModel(fname);
    dataContent.usingUser(testUser).usingSite(testSite).createFolder(testFolder);

    FileModel textFile = new FileModel(fname + "-1.txt", fname, fname, FileType.TEXT_PLAIN, fname + " file for search ");
    dataContent.usingUser(testUser).usingSite(testSite).createContent(textFile);

    FileModel htmlFile = new FileModel(fname + "-2.html", FileType.HTML, fname + " file 2 for search ");
    dataContent.usingUser(testUser).usingSite(testSite).createContent(htmlFile);
    
    // Set Node Permissions to allow access for user for text File
    JsonObject userPermission = Json.createObjectBuilder()
            .add("permissions", Json.createObjectBuilder().add("isInheritanceEnabled", false)
                    .add("locallySet",Json.createObjectBuilder().add("authorityId", userCanAccessTextFile.getUsername())
                            .add("name", "SiteConsumer").add("accessStatus", "ALLOWED")))
            .build();
    String putBody = userPermission.toString();

    restClient.authenticateUser(testUser).withCoreAPI().usingNode(textFile).updateNode(putBody);
    
    // Wait for the file to be indexed
    waitForContentIndexing(htmlFile.getContent(), true);
}
 
Example 12
Source File: WeiboUser.java    From albert with MIT License 5 votes vote down vote up
private void init(JsonObject json) throws WeiboException {
	if (json != null) {
		try {
			id = json.getJsonNumber("id").longValue();
			screenName = json.getString("screen_name");
			name = json.getString("name");
			province = Integer.parseInt(json.getString("province"));
			city = Integer.parseInt(json.getString("city"));
			location = json.getString("location");
			description = WeiboResponseUtil.withNonBmpStripped(json.getString("description"));
			url = json.getString("url");
			profileImageUrl = json.getString("profile_image_url");
			domain = json.getString("domain");
			gender = json.getString("gender");
			followersCount = json.getInt("followers_count");
			friendsCount = json.getInt("friends_count");
			favouritesCount = json.getInt("favourites_count");
			statusesCount = json.getInt("statuses_count");
			createdAt = WeiboResponseUtil.parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
			following = json.getBoolean("following");
			verified = json.getBoolean("verified");
			verifiedType = json.getInt("verified_type");
			verifiedReason = json.getString("verified_reason");
			allowAllActMsg = json.getBoolean("allow_all_act_msg");
			allowAllComment = json.getBoolean("allow_all_comment");
			followMe = json.getBoolean("follow_me");
			avatarLarge = json.getString("avatar_large");
			onlineStatus = json.getInt("online_status");
			biFollowersCount = json.getInt("bi_followers_count");
			if (!json.getString("remark").isEmpty()) {
				remark = json.getString("remark");
			}
			lang = json.getString("lang");
			weihao = json.getString("weihao");
		} catch (JsonException jsone) {
			throw new WeiboException(jsone.getMessage() + ":" + json.toString(), jsone);
		}
	}
}
 
Example 13
Source File: SearchPermissionsTest.java    From SearchServices with GNU Lesser General Public License v3.0 4 votes vote down vote up
@BeforeClass(alwaysRun = true)
public void dataPreparation() throws Exception
{
    /*
     * Create the following file structure in the same Site  : In addition to the preconditions created in dataPreparation
     * |- permGrandParent
     *    |-- permChild1
     *    |------ permFile1 
     *    |-- permChild2
     *    |------ permFile2 
     *    |-- permChild3 (Later: In test 2)
     */

    parentFolder = new FolderModel("permGrandParent");
    dataContent.usingUser(testUser).usingSite(testSite).createFolder(parentFolder);
    folder1 = dataContent.usingUser(testUser).usingSite(testSite).usingResource(parentFolder).createFolderCmisApi("permChild1");
    folder2 = dataContent.usingUser(testUser).usingSite(testSite).usingResource(parentFolder).createFolderCmisApi("permChild2");

    file1 = new FileModel("permFile1", FileType.TEXT_PLAIN, "File1 with inherited permissions");
    file2 = new FileModel("permFile2", FileType.TEXT_PLAIN, "File2 with inherited permissions");
    
    // Create test users
    testUser1 = dataUser.createRandomTestUser("UserSiteMember");
    testUser2 = dataUser.createRandomTestUser("UserNotASiteMemeber");
    testUser3 = dataUser.createRandomTestUser("UserWithoutContentAccess");

    dataUser.addUserToSite(testUser1, testSite, UserRole.SiteCollaborator);

    dataContent.usingUser(testUser).usingSite(testSite).usingResource(folder1).createContent(file1);
    dataContent.usingUser(testUser).usingSite(testSite).usingResource(folder2).createContent(file2);
    
    // Deny testUser1 - access to file1
    JsonObject userPermission = Json
            .createObjectBuilder()
            .add("permissions",
                    Json.createObjectBuilder()
                            .add("isInheritanceEnabled", false)
                            .add("locallySet",
                                    Json.createObjectBuilder()
                                        .add("authorityId", testUser1.getUsername())
                                        .add("name", "SiteCollaborator")
                                        .add("accessStatus", "DENIED")
                                    )).build();
    String putBody = userPermission.toString();
    restClient.authenticateUser(testUser).withCoreAPI().usingNode(file1).updateNode(putBody);

    // Allow testUser2 - access to file2, user is not a site member
    userPermission = Json
            .createObjectBuilder()
            .add("permissions",
                    Json.createObjectBuilder()
                            .add("isInheritanceEnabled", false)
                            .add("locallySet",
                                    Json.createObjectBuilder()
                                        .add("authorityId", testUser2.getUsername())
                                        .add("name", "SiteContributor")
                                        .add("accessStatus", "ALLOWED")
                                    )).build();
    putBody = userPermission.toString();
    restClient.authenticateUser(testUser).withCoreAPI().usingNode(file2).updateNode(putBody);

    waitForContentIndexing(file2.getContent(), true);
}
 
Example 14
Source File: MetricsTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private String getPayload(String query) {
    JsonObject jsonObject = createRequestBody(query);
    return jsonObject.toString();
}
 
Example 15
Source File: AbstractGraphQLTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
protected String getPayload(String query) {
    JsonObject jsonObject = createRequestBody(query);
    return jsonObject.toString();
}
 
Example 16
Source File: PayloadCreator.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public static String getPayload(String query) {
    JsonObject jsonObject = createRequestBody(query);
    return jsonObject.toString();
}
 
Example 17
Source File: JSONTextEncoder.java    From blog-tutorials with MIT License 4 votes vote down vote up
@Override
public String encode(JsonObject object) throws EncodeException {
    return object.toString();
}
 
Example 18
Source File: JsonPointerCrud.java    From tutorials with MIT License 4 votes vote down vote up
public String fetchListValues(String key) {
    JsonPointer jsonPointer = Json.createPointer("/" + key);
    JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure);

    return jsonObject.toString();
}
 
Example 19
Source File: replicateSKFEObjectBean.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public String execute(Integer entityType, Integer replicationOperation, String primarykey, Object obj) {

    //Json return object
    JsonObject retObj;

    //Declaring variables
    Boolean status = true;
    String errmsg;

    try {
        String replpk = persistro.execute(entityType, replicationOperation, primarykey);
        if (replpk == null) {
            sc.setRollbackOnly();
            strongkeyLogger.exiting(skceConstants.SKEE_LOGGER, classname, "execute");
            strongkeyLogger.logp(skceConstants.SKEE_LOGGER, Level.SEVERE, classname, "execute", "FIDOJPA-ERR-1001", "persist repl object");
            errmsg = skceCommon.getMessageProperty("FIDOJPA-ERR-1001") + " persist repl object";
            retObj = Json.createObjectBuilder().add("status", status).add("message", errmsg).build();
            return retObj.toString();
        }
        switch (entityType) {
            case applianceConstants.ENTITY_TYPE_FIDO_KEYS:
                FidoKeys fk = (FidoKeys) obj;
                publishSKCEObj.execute(replpk, entityType, replicationOperation, primarykey, fk);
                break;
            case applianceConstants.ENTITY_TYPE_FIDO_POLICIES:
                FidoPolicies fp = (FidoPolicies) obj;
                publishSKCEObj.execute(replpk, entityType, replicationOperation, primarykey, fp);
                break;
            case applianceConstants.ENTITY_TYPE_ATTESTATION_CERTIFICATES:
                AttestationCertificates ak = (AttestationCertificates) obj;
                publishSKCEObj.execute(replpk, entityType, replicationOperation, primarykey, ak);
                break;
            case applianceConstants.ENTITY_TYPE_FIDO_USERS:
                FidoUsers user = (FidoUsers) obj;
                publishSKCEObj.execute(replpk, entityType, replicationOperation, primarykey, user);
                break;
            case applianceConstants.ENTITY_TYPE_MAP_USER_SESSION_INFO:
                UserSessionInfo session = (UserSessionInfo) obj;
                publishSKCEObj.execute(replpk, entityType, replicationOperation, primarykey, session);
                break;
            default:
                break;
        }
    } catch (Exception e) {
        sc.setRollbackOnly();
        strongkeyLogger.exiting(skceConstants.SKEE_LOGGER, classname, "execute");
        throw new RuntimeException(e.getLocalizedMessage());
    }
    return null;
}
 
Example 20
Source File: SearchPermissionsTest.java    From SearchServices with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test(priority = 2)
public void searchResultsRespectInheritedPermissionsDisabled() throws Exception
{
    // Create folder
    FolderModel folder3 = dataContent.usingUser(testUser).usingSite(testSite).usingResource(parentFolder).createFolderCmisApi("permChild3");

    // Turn off inherited permissions for folder3
    JsonObject userPermission = Json.createObjectBuilder().add("permissions", Json.createObjectBuilder().add("isInheritanceEnabled", false)).build();
    String putBody = userPermission.toString();
    restClient.authenticateUser(testUser).withCoreAPI().usingNode(folder3).updateNode(putBody);

    // Wait for indexing
    waitForIndexing(folder3.getName(), true);

    /**
     * Private Site Folder Structure available now for this test
     * |- permGrandParent
     *    |-- permChild1
     *    |------ permFile1 (inheritance disabled, deny permission to testUser1)
     *    |-- permChild2
     *    |------ permFile2 (inheritance disabled, allow permission to testUser2)
     *    |-- permChild3 (inheritance disabled)
     */

    // Search as testUser: expect all: 6 results: When user is a Site Manager
    SearchResponse response = queryAsUser(testUser, "cm:name:perm*");
    int resultCount = response.getPagination().getCount();
    Assert.assertEquals(resultCount, 6, "Unexpected Result count for testUser: Expected 6, received: " + resultCount);

    // Search as testUser1: expect 3 results: when user is a site member but without permission to a content
    response = queryAsUser(testUser1, "cm:name:perm*");
    resultCount = response.getPagination().getCount();
    Assert.assertEquals(resultCount, 3, "Unexpected Result count for testUser1: Expected 3, received: " + resultCount);

    // Search as testUser2: expect 1 result: When user isn't a site member but has granular permissions to a content
    response = queryAsUser(testUser2, "cm:name:perm*");
    resultCount = response.getPagination().getCount();
    Assert.assertEquals(resultCount, 1, "Unexpected Result count for testUser2: Expected 1, received: " + resultCount);

    // Search as testUser3: expect none: 0 results: When user isn't a site member / does not have granular permissions to the content
    response = queryAsUser(testUser3, "cm:name:perm*");
    resultCount = response.getPagination().getCount();
    Assert.assertEquals(resultCount, 0, "Unexpected Result count for testUser3: Expected 0, received: " + resultCount);
}