001/*
002 * Copyright 2015-2023 Ping Identity Corporation
003 *
004 * This program is free software; you can redistribute it and/or modify
005 * it under the terms of the GNU General Public License (GPLv2 only)
006 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
007 * as published by the Free Software Foundation.
008 *
009 * This program is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
012 * GNU General Public License for more details.
013 *
014 * You should have received a copy of the GNU General Public License
015 * along with this program; if not, see <http://www.gnu.org/licenses>.
016 */
017
018package com.unboundid.scim2.client.requests;
019
020import com.unboundid.scim2.common.ScimResource;
021import com.unboundid.scim2.common.exceptions.ScimException;
022
023import javax.ws.rs.client.Entity;
024import javax.ws.rs.client.WebTarget;
025import javax.ws.rs.core.Response;
026
027/**
028 * A builder for SCIM create requests.
029 */
030public final class CreateRequestBuilder<T extends ScimResource>
031    extends ResourceReturningRequestBuilder<CreateRequestBuilder<T>>
032{
033  private final T resource;
034
035  /**
036   * Create a new SCIM create request builder that will POST the given resource
037   * to the given web target.
038   *
039   * @param target The WebTarget to POST to.
040   * @param resource The SCIM resource to POST.
041   */
042  public CreateRequestBuilder(final WebTarget target, final T resource)
043  {
044    super(target);
045    this.resource = resource;
046  }
047
048  /**
049   * Invoke the SCIM create request.
050   *
051   * @return The successfully create SCIM resource.
052   * @throws ScimException If an error occurred.
053   */
054  @SuppressWarnings("unchecked")
055  public T invoke() throws ScimException
056  {
057    return (T) invoke(resource.getClass());
058  }
059
060  /**
061   * Invoke the SCIM create request.
062   *
063   * @param <C> The type of object to return.
064   * @param cls The Java class object used to determine the type to return.
065   * @return The successfully modified SCIM resource.
066   * @throws javax.ws.rs.ProcessingException If a JAX-RS runtime exception occurred.
067   * @throws ScimException If the SCIM service provider responded with an error.
068   */
069  public <C> C invoke(final Class<C> cls) throws ScimException
070  {
071    Response response = buildRequest().post(
072        Entity.entity(resource, getContentType()));
073    try
074    {
075      if(response.getStatusInfo().getFamily() ==
076          Response.Status.Family.SUCCESSFUL)
077      {
078        return response.readEntity(cls);
079      }
080      else
081      {
082        throw toScimException(response);
083      }
084    }
085    finally
086    {
087      response.close();
088    }
089  }
090}