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