001/* 002 * Copyright 2015-2020 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 070 /** 071 * Encodes a string with template parameters name present, specifically the 072 * characters '{' and '}' will be percent-encoded. 073 * 074 * @param s the string with zero or more template parameter names 075 * @return the string with encoded template parameter names. 076 */ 077 public static String encodeTemplateNames(final String s) 078 { 079 String s1 = s; 080 int i = s1.indexOf('{'); 081 if (i != -1) 082 { 083 s1 = s1.replace("{", "%7B"); 084 } 085 i = s1.indexOf('}'); 086 if (i != -1) 087 { 088 s1 = s1.replace("}", "%7D"); 089 } 090 091 return s1; 092 } 093}