001package com.box.sdk;
002
003import com.box.sdk.http.HttpMethod;
004import com.eclipsesource.json.Json;
005import com.eclipsesource.json.JsonObject;
006import com.eclipsesource.json.JsonValue;
007import java.net.URL;
008
009/**
010 * Represents a BoxStoragePolicyAssignment.
011 */
012@BoxResourceType("storage_policy_assignment")
013public class BoxStoragePolicyAssignment extends BoxResource {
014
015    /**
016     * Storage Policies Assignment URL Template.
017     */
018    public static final URLTemplate STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE = new
019        URLTemplate("storage_policy_assignments");
020
021    /**
022     * Storage Policy Assignment URL Template.
023     */
024    public static final URLTemplate STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE = new
025        URLTemplate("storage_policy_assignments/%s");
026
027    /**
028     * Constructs a BoxStoragePolicyAssignment for a BoxStoragePolicy with a givenID.
029     *
030     * @param api the API connection to be used by the file.
031     * @param id  the ID of the file.
032     */
033    public BoxStoragePolicyAssignment(BoxAPIConnection api, String id) {
034        super(api, id);
035    }
036
037    /**
038     * Create a BoxStoragePolicyAssignment for a BoxStoragePolicy.
039     *
040     * @param api      the API connection to be used by the resource.
041     * @param policyID the policy ID of the BoxStoragePolicy.
042     * @param userID   the user ID of the to assign the BoxStoragePolicy to.
043     * @return the information about the BoxStoragePolicyAssignment created.
044     */
045    public static BoxStoragePolicyAssignment.Info create(BoxAPIConnection api, String policyID, String userID) {
046        URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.build(api.getBaseURL());
047        BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);
048        JsonObject requestJSON = new JsonObject()
049            .add("storage_policy", new JsonObject()
050                .add("type", "storage_policy")
051                .add("id", policyID))
052            .add("assigned_to", new JsonObject()
053                .add("type", "user")
054                .add("id", userID));
055
056        request.setBody(requestJSON.toString());
057        try (BoxJSONResponse response = request.send()) {
058            JsonObject responseJSON = Json.parse(response.getJSON()).asObject();
059
060            BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api,
061                responseJSON.get("id").asString());
062
063            return storagePolicyAssignment.new Info(responseJSON);
064        }
065    }
066
067    /**
068     * Returns a BoxStoragePolicyAssignment information.
069     *
070     * @param api             the API connection to be used by the resource.
071     * @param resolvedForType the assigned entity type for the storage policy.
072     * @param resolvedForID   the assigned entity id for the storage policy.
073     * @return information about this {@link BoxStoragePolicyAssignment}.
074     */
075    public static BoxStoragePolicyAssignment.Info getAssignmentForTarget(final BoxAPIConnection api,
076                                                                         String resolvedForType, String resolvedForID) {
077        QueryStringBuilder builder = new QueryStringBuilder();
078        builder.appendParam("resolved_for_type", resolvedForType)
079            .appendParam("resolved_for_id", resolvedForID);
080        URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());
081        BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.GET);
082        try (BoxJSONResponse response = request.send()) {
083
084            BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api,
085                response.getJsonObject().get("entries").asArray().get(0).asObject().get("id").asString());
086
087            return storagePolicyAssignment
088                .new Info(response.getJsonObject().get("entries").asArray().get(0).asObject());
089        }
090    }
091
092    /**
093     * Checks if there is already a Storage Policy Assignment and creates one if one does not exist.
094     *
095     * @param api             the API connection to be used by the resource.
096     * @param storagePolicyID the ID of the Storage Policy you want to assign to user.
097     * @param userID          the ID of the user you want to assign the Storage Policy to.
098     * @return information about this {@link BoxStoragePolicyAssignment}.
099     */
100    public static BoxStoragePolicyAssignment.Info assign(BoxAPIConnection api, String storagePolicyID, String userID) {
101        BoxStoragePolicyAssignment.Info assignmentInfo;
102        assignmentInfo = getAssignmentForTarget(api, "user", userID);
103
104        if (assignmentInfo.getStoragePolicyID().equals(storagePolicyID)) {
105            return assignmentInfo;
106        }
107
108        if (assignmentInfo.getAssignedToType().equals("enterprise")) {
109            return create(api, storagePolicyID, userID);
110        }
111
112        assignmentInfo.setStoragePolicyID(storagePolicyID);
113        BoxStoragePolicyAssignment assignment = new BoxStoragePolicyAssignment(api, assignmentInfo.getID());
114        assignment.updateInfo(assignmentInfo);
115        return assignmentInfo;
116    }
117
118    /**
119     * Updates the information about the BoxStoragePolicyAssignment with any info fields that have been
120     * modified locally.
121     *
122     * @param info the updated info.
123     */
124    public void updateInfo(BoxStoragePolicyAssignment.Info info) {
125        URL url = STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID());
126        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT");
127        request.setBody(info.getPendingChanges());
128
129        try (BoxJSONResponse response = request.send()) {
130            JsonObject responseJSON = Json.parse(response.getJSON()).asObject();
131            info.update(responseJSON);
132        }
133    }
134
135    /**
136     * @return information about this {@link BoxStoragePolicyAssignment}.
137     */
138    public BoxStoragePolicyAssignment.Info getInfo() {
139        URL url = STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID());
140        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET);
141        try (BoxJSONResponse response = request.send()) {
142            return new Info(Json.parse(response.getJSON()).asObject());
143        }
144    }
145
146    /**
147     * Deletes this BoxStoragePolicyAssignment.
148     */
149    public void delete() {
150        URL url = STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID());
151        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.DELETE);
152        request.send().close();
153    }
154
155    /**
156     * Contains information about a BoxStoragePolicyAssignment.
157     */
158    public class Info extends BoxResource.Info {
159
160        /**
161         * @see #getStoragePolicyID()
162         */
163        private String storagePolicyID;
164
165        /**
166         * @see #getStoragePolicyType()
167         */
168        private String storagePolicyType;
169
170        /**
171         * @see #getAssignedToID()
172         */
173        private String assignedToID;
174
175        /**
176         * @see #getAssignedToType()
177         */
178        private String assignedToType;
179
180        /**
181         * Constructs an empty Info object.
182         */
183        public Info() {
184            super();
185        }
186
187        /**
188         * Constructs an Info object by parsing information from a JSON string.
189         *
190         * @param json the JSON string to parse.
191         */
192        public Info(String json) {
193            super(json);
194        }
195
196        /**
197         * Constructs an Info object using an already parsed JSON object.
198         *
199         * @param jsonObject the parsed JSON object.
200         */
201        Info(JsonObject jsonObject) {
202            super(jsonObject);
203        }
204
205        @Override
206        public BoxResource getResource() {
207            return BoxStoragePolicyAssignment.this;
208        }
209
210        /**
211         * @return the entity type that this is assigned to.
212         */
213        public String getAssignedToType() {
214            return this.assignedToType;
215        }
216
217        /**
218         * @return the entity id that this is assigned to.
219         */
220        public String getAssignedToID() {
221            return this.assignedToID;
222        }
223
224        /**
225         * @return storage policy id that is assigned to.
226         */
227        public String getStoragePolicyID() {
228            return this.storagePolicyID;
229        }
230
231        /**
232         * Sets the storage policy of the storage policy assignment.
233         *
234         * @param storagePolicyID the Id of the storage policy you wish to assign.
235         */
236        public void setStoragePolicyID(String storagePolicyID) {
237            this.storagePolicyID = storagePolicyID;
238            JsonObject storagePolicyObject = new JsonObject();
239            storagePolicyObject.add("type", "storage_policy");
240            storagePolicyObject.add("id", storagePolicyID);
241
242            this.addPendingChange("storage_policy", storagePolicyObject);
243        }
244
245        /**
246         * @return storage policy type that is assigned to.
247         */
248        public String getStoragePolicyType() {
249            return this.storagePolicyType;
250        }
251
252        /**
253         * {@inheritDoc}
254         */
255        @Override
256        void parseJSONMember(JsonObject.Member member) {
257            super.parseJSONMember(member);
258            String memberName = member.getName();
259            JsonValue value = member.getValue();
260            try {
261                if (memberName.equals("assigned_to")) {
262                    JsonObject assignmentJSON = value.asObject();
263                    this.assignedToType = assignmentJSON.get("type").asString();
264                    this.assignedToID = assignmentJSON.get("id").asString();
265                } else if (memberName.equals("storage_policy")) {
266                    JsonObject storagePolicyJSON = value.asObject();
267                    this.storagePolicyID = storagePolicyJSON.get("id").asString();
268                    this.storagePolicyType = storagePolicyJSON.get("type").asString();
269                }
270            } catch (Exception e) {
271                throw new BoxDeserializationException(memberName, value.toString(), e);
272            }
273        }
274    }
275}