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.fasterxml.jackson.databind.node.ObjectNode;
021import com.unboundid.scim2.client.SearchResultHandler;
022import com.unboundid.scim2.common.messages.ListResponse;
023
024import java.util.LinkedHashMap;
025import java.util.LinkedList;
026import java.util.List;
027import java.util.Map;
028
029/**
030 * A builder for ListResponses that is also a SearchResultHandler
031 * implementation.
032 */
033public class ListResponseBuilder<T>
034    implements SearchResultHandler<T>
035{
036  private Integer totalResults;
037  private List<T> resources = new LinkedList<T>();
038  private Integer startIndex;
039  private Integer itemsPerPage;
040
041  /**
042   * {@inheritDoc}
043   */
044  public void startIndex(final int startIndex)
045  {
046    this.startIndex = startIndex;
047  }
048
049  /**
050   * {@inheritDoc}
051   */
052  public void itemsPerPage(final int itemsPerPage)
053  {
054    this.itemsPerPage = itemsPerPage;
055  }
056
057  /**
058   * {@inheritDoc}
059   */
060  public void totalResults(final int totalResults)
061  {
062    this.totalResults = totalResults;
063  }
064
065  /**
066   * {@inheritDoc}
067   */
068  public boolean resource(final T scimResource)
069  {
070    this.resources.add(scimResource);
071    return true;
072  }
073
074  /**
075   * {@inheritDoc}
076   * <p>
077   * This method currently does not perform any action and should not be used.
078   */
079  public void extension(final String urn,
080                        final ObjectNode extensionObjectNode)
081  {
082    // TODO: do nothing for now
083  }
084
085  /**
086   * Builds a List Response.
087   *
088   * @return generated ListResponse.
089   */
090  public ListResponse<T> build()
091  {
092    final Map<String,Object> properties = new LinkedHashMap<String,Object>();
093    properties.put("totalResults", totalResults == null ?
094      resources.size() : totalResults);
095    properties.put("resources", resources);
096    properties.put("startIndex", startIndex);
097    properties.put("itemsPerPage", itemsPerPage);
098    return new ListResponse<T>(properties);
099  }
100}