001/*
002 * Copyright 2015-2018 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.server.utils;
019
020import javax.ws.rs.core.MediaType;
021import javax.ws.rs.core.Response;
022
023import java.util.List;
024
025import static com.unboundid.scim2.common.utils.ApiConstants.MEDIA_TYPE_SCIM;
026
027/**
028 * Utility methods for server side use.
029 */
030public class ServerUtils
031{
032  /**
033   * The SCIM media type.
034   */
035  public static final MediaType MEDIA_TYPE_SCIM_TYPE =
036      MediaType.valueOf(MEDIA_TYPE_SCIM);
037
038  /**
039   * Sets the appropriate response content type while taking the accept header
040   * into account.
041   *
042   * @param response The response builder.
043   * @param acceptableTypes The list of acceptable types from
044   *                        Request.getAcceptableMediaTypes.
045   * @return The response builder.
046   */
047  public static Response.ResponseBuilder setAcceptableType(
048      final Response.ResponseBuilder response,
049      final List<MediaType> acceptableTypes)
050  {
051    MediaType responseType = null;
052    for(MediaType mediaType : acceptableTypes)
053    {
054      if(mediaType.isCompatible(MEDIA_TYPE_SCIM_TYPE))
055      {
056        responseType = MEDIA_TYPE_SCIM_TYPE;
057        break;
058      }
059      else if(mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE))
060      {
061        responseType = MediaType.APPLICATION_JSON_TYPE;
062        break;
063      }
064    }
065    response.type(responseType == null ? MEDIA_TYPE_SCIM_TYPE : responseType);
066
067    return response;
068  }
069}