Java Code Examples for com.eclipsesource.json.JsonObject#add()

The following examples show how to use com.eclipsesource.json.JsonObject#add() . 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: BoxTask.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a new assignment to this task using user's login as identifier.
 * @param assignToLogin the login of user to assign the task to.
 * @return information about the newly added task assignment.
 */
public BoxTaskAssignment.Info addAssignmentByLogin(String assignToLogin) {
    JsonObject taskJSON = new JsonObject();
    taskJSON.add("type", "task");
    taskJSON.add("id", this.getID());

    JsonObject assignToJSON = new JsonObject();
    assignToJSON.add("login", assignToLogin);

    JsonObject requestJSON = new JsonObject();
    requestJSON.add("task", taskJSON);
    requestJSON.add("assign_to", assignToJSON);

    URL url = ADD_TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL());
    BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST");
    request.setBody(requestJSON.toString());
    BoxJSONResponse response = (BoxJSONResponse) request.send();
    JsonObject responseJSON = JsonObject.readFrom(response.getJSON());

    BoxTaskAssignment addedAssignment = new BoxTaskAssignment(this.getAPI(), responseJSON.get("id").asString());
    return addedAssignment.new Info(responseJSON);
}
 
Example 2
Source File: BoxMetadataFilter.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Set a filter to the filterList, example: key=documentNumber, gt : "", lt : "".
 * @param key the key that the filter should be looking for.
 * @param dateRange the date range that is start and end dates
 */
public void addDateRangeFilter(String key, DateRange dateRange) {

    JsonObject opObj = new JsonObject();

    if (dateRange.getFromDate() != null) {
        String dateGtString = BoxDateFormat.format(dateRange.getFromDate());
        //workaround replacing + and - 000 at the end with 'Z'
        dateGtString = dateGtString.replaceAll("(\\+|-)(?!-\\|?!\\+)\\d+$", "Z");
        opObj.add("gt", dateGtString);
    }
    if (dateRange.getToDate() != null) {
        String dateLtString = BoxDateFormat.format(dateRange.getToDate());
        //workaround replacing + and - 000 at the end with 'Z'
        dateLtString = dateLtString.replaceAll("(\\+|-)(?!-\\|?!\\+)\\d+$", "Z");
        opObj.add("lt", dateLtString);
    }

    this.filtersList.add(key, opObj);
}
 
Example 3
Source File: LargeFileUpload.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
private BoxFileUploadSession.Info createUploadSession(BoxAPIConnection boxApi, String folderId,
                                                     URL url, String fileName, long fileSize) {

    BoxJSONRequest request = new BoxJSONRequest(boxApi, url, HttpMethod.POST);

    //Create the JSON body of the request
    JsonObject body = new JsonObject();
    body.add("folder_id", folderId);
    body.add("file_name", fileName);
    body.add("file_size", fileSize);
    request.setBody(body.toString());

    BoxJSONResponse response = (BoxJSONResponse) request.send();
    JsonObject jsonObject = JsonObject.readFrom(response.getJSON());

    String sessionId = jsonObject.get("id").asString();
    BoxFileUploadSession session = new BoxFileUploadSession(boxApi, sessionId);

    return session.new Info(jsonObject);
}
 
Example 4
Source File: BoxBrowseFolderGridFragment.java    From box-android-browse-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method that returns a folder object without its item collection. This is done to ensure
 * a single source of truth for the item collection
 *
 * @param folder the folder which may contain items
 * @return box folder without any items
 */
protected BoxFolder createFolderWithoutItems(BoxFolder folder) {
    JsonObject jsonObject = new JsonObject();
    for (String key: folder.getPropertiesKeySet()){
        if (!key.equals(BoxFolder.FIELD_ITEM_COLLECTION)){
            jsonObject.add(key, folder.getPropertyValue(key));
        } else {
            JsonObject itemCollection = new JsonObject();
            BoxIteratorItems iteratorItems = folder.getItemCollection();
            for (String collectionKey : iteratorItems.getPropertiesKeySet()){
                if (!collectionKey.equals(BoxIterator.FIELD_ENTRIES)) {
                    itemCollection.add(collectionKey, iteratorItems.getPropertyValue(collectionKey));
                } else {
                    itemCollection.add(collectionKey, new JsonArray());
                }
            }
            jsonObject.add(key, itemCollection);
        }
    }
    return new BoxFolder(jsonObject);
}
 
Example 5
Source File: BoxUser.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * @deprecated  As of release 2.22.0, replaced by {@link #transferContent(String)} ()}
 *
 *
 * Moves all of the owned content from within one user’s folder into a new folder in another user's account.
 * You can move folders across users as long as the you have administrative permissions and the 'source'
 * user owns the folders. Per the documentation at the link below, this will move everything from the root
 * folder, as this is currently the only mode of operation supported.
 *
 * See also https://developer.box.com/en/reference/put-users-id-folders-id/
 *
 * @param sourceUserID the user id of the user whose files will be the source for this operation
 * @return info for the newly created folder
 */
@Deprecated
public BoxFolder.Info moveFolderToUser(String sourceUserID) {
    // Currently the API only supports moving of the root folder (0), hence the hard coded "0"
    URL url = MOVE_FOLDER_TO_USER_TEMPLATE.build(this.getAPI().getBaseURL(), sourceUserID, "0");
    BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT");
    JsonObject idValue = new JsonObject();
    idValue.add("id", this.getID());
    JsonObject ownedBy = new JsonObject();
    ownedBy.add("owned_by", idValue);
    request.setBody(ownedBy.toString());
    BoxJSONResponse response = (BoxJSONResponse) request.send();
    JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
    BoxFolder movedFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString());

    return movedFolder.new Info(responseJSON);
}
 
Example 6
Source File: BoxApiCollaboration.java    From box-android-sdk with Apache License 2.0 6 votes vote down vote up
protected BoxCollaborationItem createStubItem(BoxCollaborationItem collaborationItem) {
    JsonObject jsonObject = new JsonObject();
    jsonObject.add(BoxItem.FIELD_ID, collaborationItem.getId());
    jsonObject.add(BoxItem.FIELD_TYPE, collaborationItem.getType());

    try {
        Object stub = collaborationItem.getClass().newInstance();
        if (stub instanceof BoxCollaborationItem){
            ((BoxCollaborationItem) stub).createFromJson(jsonObject);
        }

    } catch (InstantiationException e){

    } catch (IllegalAccessException e1){

    }
    return (BoxCollaborationItem)BoxItem.createEntityFromJson(jsonObject);
}
 
Example 7
Source File: BoxFolder.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new child folder inside this folder.
 *
 * @param name the new folder's name.
 * @return the created folder's info.
 */
public BoxFolder.Info createFolder(String name) {
    JsonObject parent = new JsonObject();
    parent.add("id", this.getID());

    JsonObject newFolder = new JsonObject();
    newFolder.add("name", name);
    newFolder.add("parent", parent);

    BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), CREATE_FOLDER_URL.build(this.getAPI().getBaseURL()),
            "POST");
    request.setBody(newFolder.toString());
    BoxJSONResponse response = (BoxJSONResponse) request.send();
    JsonObject responseJSON = JsonObject.readFrom(response.getJSON());

    BoxFolder createdFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString());
    return createdFolder.new Info(responseJSON);
}
 
Example 8
Source File: BoxFile.java    From box-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * A convenience method to create an empty file with just the id and type fields set. This allows
 * the ability to interact with the content sdk in a more descriptive and type safe manner
 *
 * @param fileId the id of file to create
 * @param name the name of the file to create
 * @return an empty BoxFile object that only contains id and type information
 */
public static BoxFile createFromIdAndName(String fileId, String name) {
    JsonObject object = new JsonObject();
    object.add(BoxItem.FIELD_ID, fileId);
    object.add(BoxItem.FIELD_TYPE, BoxFile.TYPE);
    if (!TextUtils.isEmpty(name)) {
        object.add(BoxItem.FIELD_NAME, name);
    }
    return new BoxFile(object);
}
 
Example 9
Source File: BoxRetentionPolicy.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Used to create a new retention policy with optional parameters.
 * @param api the API connection to be used by the created user.
 * @param name the name of the retention policy.
 * @param type the type of the retention policy. Can be "finite" or "indefinite".
 * @param length the duration in days that the retention policy will be active for after being assigned to content.
 * @param action the disposition action can be "permanently_delete" or "remove_retention".
 * @param optionalParams the optional parameters.
 * @return the created retention policy's info.
 */
private static BoxRetentionPolicy.Info createRetentionPolicy(BoxAPIConnection api, String name, String type,
                                                             int length, String action,
                                                             RetentionPolicyParams optionalParams) {
    URL url = RETENTION_POLICIES_URL_TEMPLATE.build(api.getBaseURL());
    BoxJSONRequest request = new BoxJSONRequest(api, url, "POST");
    JsonObject requestJSON = new JsonObject()
            .add("policy_name", name)
            .add("policy_type", type)
            .add("disposition_action", action);
    if (!type.equals(TYPE_INDEFINITE)) {
        requestJSON.add("retention_length", length);
    }
    if (optionalParams != null) {
        requestJSON.add("can_owner_extend_retention", optionalParams.getCanOwnerExtendRetention());
        requestJSON.add("are_owners_notified", optionalParams.getAreOwnersNotified());

        List<BoxUser.Info> customNotificationRecipients = optionalParams.getCustomNotificationRecipients();
        if (customNotificationRecipients.size() > 0) {
            JsonArray users = new JsonArray();
            for (BoxUser.Info user : customNotificationRecipients) {
                JsonObject userJSON = new JsonObject()
                        .add("type", "user")
                        .add("id", user.getID());
                users.add(userJSON);
            }
            requestJSON.add("custom_notification_recipients", users);
        }
    }
    request.setBody(requestJSON.toString());
    BoxJSONResponse response = (BoxJSONResponse) request.send();
    JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
    BoxRetentionPolicy createdPolicy = new BoxRetentionPolicy(api, responseJSON.get("id").asString());
    return createdPolicy.new Info(responseJSON);
}
 
Example 10
Source File: Settings.java    From java-disassembler with GNU General Public License v3.0 5 votes vote down vote up
public static void saveFrame(JsonObject windowsSection, IPersistentWindow f) {
    String name = f.getWindowId();
    if (windowsSection.get(name) == null)
        windowsSection.add(name, new JsonObject());

    JsonObject windowSettings = windowsSection.get(name).asObject();
    Point pos = f.getPersistentPosition();
    Dimension size = f.getPersistentSize();
    windowSettings.add("x", pos.x);
    windowSettings.add("y", pos.y);
    windowSettings.add("width", size.width);
    windowSettings.add("height", size.height);
    windowSettings.add("state", f.getState());
}
 
Example 11
Source File: ChatImpl.java    From Skype4J with Apache License 2.0 5 votes vote down vote up
protected void putOption(String option, JsonValue value, boolean global) throws ConnectionException {
    JsonObject obj = new JsonObject();
    obj.add(option, value);
    (global ? Endpoints.CONVERSATION_PROPERTY_GLOBAL : Endpoints.CONVERSATION_PROPERTY_SELF)
            .open(getClient(), getIdentity(), option)
            .expect(200, "While updating option")
            .put(obj);
}
 
Example 12
Source File: SyncOpportunities.java    From REST-Sample-Code with MIT License 5 votes vote down vote up
private JsonObject buildRequest(){
	JsonObject requestBody = new JsonObject(); //Create a new JsonObject for the Request Body
	JsonArray in = new JsonArray(); //Create a JsonArray for the "input" member to hold Opp records
	for (JsonObject jo : input) {
		in.add(jo); //add our Opportunity records to the input array
	}
	requestBody.add("input", in);
	if (this.action != null){
		requestBody.add("action", action); //add the action member if available
	}
	if (this.dedupeBy != null){
		requestBody.add("dedupeBy", dedupeBy); //add the dedupeBy member if available
	}
	return requestBody;
}
 
Example 13
Source File: ChatImpl.java    From Skype4J with Apache License 2.0 5 votes vote down vote up
@Override
public ChatMessage sendMessage(Message message) throws ConnectionException {
    long ms = System.currentTimeMillis();

    JsonObject obj = new JsonObject();
    obj.add("content", message.write());
    obj.add("messagetype", "RichText");
    obj.add("contenttype", "text");
    obj.add("clientmessageid", String.valueOf(ms));

    Endpoints.SEND_MESSAGE_URL.open(getClient(), getIdentity()).expect(201, "While sending message").post(obj);

    return Factory.createMessage(this, getSelf(), null, String.valueOf(ms), ms, message,
            getClient());
}
 
Example 14
Source File: SimpleStatisticsReporter.java    From plog with Apache License 2.0 5 votes vote down vote up
public final String toJSON() {
    final JsonObject result = new JsonObject()
            .add("version", getPlogVersion())
            .add("uptime", System.currentTimeMillis() - startTime)
            .add("udp_simple_messages", udpSimpleMessages.get())
            .add("udp_invalid_version", udpInvalidVersion.get())
            .add("v0_invalid_type", v0InvalidType.get())
            .add("v0_invalid_multipart_header", v0InvalidMultipartHeader.get())
            .add("unknown_command", unknownCommand.get())
            .add("v0_commands", v0Commands.get())
            .add("exceptions", exceptions.get())
            .add("unhandled_objects", unhandledObjects.get())
            .add("holes_from_dead_port", holesFromDeadPort.get())
            .add("holes_from_new_message", holesFromNewMessage.get())
            .add("v0_fragments", arrayForLogStats(v0MultipartMessageFragments))
            .add("v0_invalid_checksum", arrayForLogStats(v0InvalidChecksum))
            .add("v0_invalid_fragments", arrayForLogLogStats(invalidFragments))
            .add("dropped_fragments", arrayForLogLogStats(droppedFragments));

    if (defragmenter != null) {
        final CacheStats cacheStats = defragmenter.getCacheStats();
        result.add("defragmenter", new JsonObject()
                .add("evictions", cacheStats.evictionCount())
                .add("hits", cacheStats.hitCount())
                .add("misses", cacheStats.missCount()));
    }

    final JsonArray handlersStats = new JsonArray();
    result.add("handlers", handlersStats);
    for (Handler handler : handlers) {
        final JsonObject statsCandidate = handler.getStats();
        final JsonObject stats = (statsCandidate == null) ? new JsonObject() : statsCandidate;
        handlersStats.add(stats.set("name", handler.getName()));
    }

    return result.toString();
}
 
Example 15
Source File: R2ServerClientTest.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaveMetrics() throws InterruptedException {
	JsonHttpResponse handler = new JsonHttpResponse("r2cloudclienttest/empty-response.json", 200);
	server.setMetricsMock(handler);
	JsonObject metric = new JsonObject();
	metric.add("name", "temperature");
	metric.add("value", 0.1d);
	JsonArray metrics = new JsonArray();
	metrics.add(metric);
	client.saveMetrics(metrics);
	handler.awaitRequest();
	assertEquals("application/json", handler.getRequestContentType());
	assertJson("r2cloudclienttest/metrics-request.json", handler.getRequest());
}
 
Example 16
Source File: SyncOpportunityRoles.java    From REST-Sample-Code with MIT License 5 votes vote down vote up
private JsonObject buildRequest(){
	JsonObject requestBody = new JsonObject(); //Create a new JsonObject for the Request Body
	JsonArray in = new JsonArray(); //Create a JsonArray for the "input" member to hold Opp records
	for (JsonObject jo : input) {
		in.add(jo); //add our Opportunity records to the input array
	}
	requestBody.add("input", in);
	if (this.action != null){
		requestBody.add("action", action); //add the action member if available
	}
	if (this.dedupeBy != null){
		requestBody.add("dedupeBy", dedupeBy); //add the dedupeBy member if available
	}
	return requestBody;
}
 
Example 17
Source File: BoxFile.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a new task to this file. The task can have an optional message to include, due date,
 * and task completion rule.
 *
 * @param action  the action the task assignee will be prompted to do.
 * @param message an optional message to include with the task.
 * @param dueAt   the day at which this task is due.
 * @param completionRule the rule for completing the task.
 * @return information about the newly added task.
 */
public BoxTask.Info addTask(BoxTask.Action action, String message, Date dueAt,
                            BoxTask.CompletionRule completionRule) {
    JsonObject itemJSON = new JsonObject();
    itemJSON.add("type", "file");
    itemJSON.add("id", this.getID());

    JsonObject requestJSON = new JsonObject();
    requestJSON.add("item", itemJSON);
    requestJSON.add("action", action.toJSONString());

    if (message != null && !message.isEmpty()) {
        requestJSON.add("message", message);
    }

    if (dueAt != null) {
        requestJSON.add("due_at", BoxDateFormat.format(dueAt));
    }

    if (completionRule != null) {
        requestJSON.add("completion_rule", completionRule.toJSONString());
    }

    URL url = ADD_TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL());
    BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST");
    request.setBody(requestJSON.toString());
    BoxJSONResponse response = (BoxJSONResponse) request.send();
    JsonObject responseJSON = JsonObject.readFrom(response.getJSON());

    BoxTask addedTask = new BoxTask(this.getAPI(), responseJSON.get("id").asString());
    return addedTask.new Info(responseJSON);
}
 
Example 18
Source File: MetadataTemplateTest.java    From box-java-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@Category(UnitTest.class)
public void testSetOptionReturnsCorrectly() throws IOException {
    String result = "";
    final String metadataTemplateURL = "/metadata_templates/schema";
    result = TestConfig.getFixture("BoxMetadataTemplate/CreateMetadataTemplate200");

    JsonObject keyObject = new JsonObject();
    keyObject.add("key", "FY16");

    JsonObject secondKeyObject = new JsonObject();
    secondKeyObject.add("key", "FY17");

    JsonArray optionsArray = new JsonArray();
    optionsArray.add(keyObject);
    optionsArray.add(secondKeyObject);

    JsonObject enumObject = new JsonObject();
    enumObject.add("type", "enum")
              .add("key", "fy")
              .add("displayName", "FY")
              .add("options", optionsArray);

    JsonArray fieldsArray = new JsonArray();
    fieldsArray.add(enumObject);

    JsonObject templateBody = new JsonObject();
    templateBody.add("scope", "enterprise")
                .add("displayName", "Document Flow 03")
                .add("hidden", false)
                .add("templateKey", "documentFlow03")
                .add("fields", fieldsArray);

    WIRE_MOCK_CLASS_RULE.stubFor(WireMock.post(WireMock.urlPathEqualTo(metadataTemplateURL))
            .withRequestBody(WireMock.equalToJson(templateBody.toString()))
            .willReturn(WireMock.aResponse()
                    .withHeader("Content-Type", "application/json")
                    .withBody(result)));

    MetadataTemplate.Field fyField = new MetadataTemplate.Field();
    fyField.setType("enum");
    fyField.setKey("fy");
    fyField.setDisplayName("FY");

    List<String> options = new ArrayList<String>();
    options.add("FY16");
    options.add("FY17");
    fyField.setOptions(options);

    List<MetadataTemplate.Field> fields = new ArrayList<MetadataTemplate.Field>();
    fields.add(fyField);

    MetadataTemplate template = MetadataTemplate.createMetadataTemplate(this.api, "enterprise",
            "documentFlow03", "Document Flow 03", false, fields);

    Assert.assertEquals("FY16", template.getFields().get(0).getOptions().get(0));
    Assert.assertEquals("FY17", template.getFields().get(0).getOptions().get(1));
}
 
Example 19
Source File: BoxFolder.java    From box-java-sdk with Apache License 2.0 3 votes vote down vote up
/**
 * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't already have a Box
 * account.
 *
 * @param email       the email address of the collaborator to add.
 * @param role        the role of the collaborator.
 * @param notify      the user/group should receive email notification of the collaboration or not.
 * @param canViewPath the view path collaboration feature is enabled or not.
 *                    View path collaborations allow the invitee to see the entire ancestral path to the associated
 *                    folder. The user will not gain privileges in any ancestral folder.
 * @return info about the new collaboration.
 */
public BoxCollaboration.Info collaborate(String email, BoxCollaboration.Role role,
                                         Boolean notify, Boolean canViewPath) {
    JsonObject accessibleByField = new JsonObject();
    accessibleByField.add("login", email);
    accessibleByField.add("type", "user");

    return this.collaborate(accessibleByField, role, notify, canViewPath);
}
 
Example 20
Source File: BoxFolder.java    From box-java-sdk with Apache License 2.0 3 votes vote down vote up
/**
 * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't already have a Box
 * account.
 *
 * @param email the email address of the collaborator to add.
 * @param role  the role of the collaborator.
 * @return info about the new collaboration.
 */
public BoxCollaboration.Info collaborate(String email, BoxCollaboration.Role role) {
    JsonObject accessibleByField = new JsonObject();
    accessibleByField.add("login", email);
    accessibleByField.add("type", "user");

    return this.collaborate(accessibleByField, role, null, null);
}