001package org.nuxeo.scim.server.jaxrs.marshalling; 002 003import static com.unboundid.scim.sdk.StaticUtils.toLowerCase; 004 005import java.io.IOException; 006import java.io.InputStream; 007import java.util.HashMap; 008import java.util.Iterator; 009import java.util.Map; 010 011import org.json.JSONException; 012import org.json.JSONObject; 013import org.json.JSONTokener; 014import org.nuxeo.common.utils.FileUtils; 015 016import com.unboundid.scim.data.BaseResource; 017import com.unboundid.scim.data.ResourceFactory; 018import com.unboundid.scim.marshal.json.JsonUnmarshaller; 019import com.unboundid.scim.schema.ResourceDescriptor; 020import com.unboundid.scim.sdk.InvalidResourceException; 021 022/** 023 * Copy of the original scimsdk class just to change some org.json constructors 024 * 025 * scimsdk uses a custom version of org.json with a different artifactId and 026 * some code differences but with the same namespace 027 * 028 * @author tiry 029 * @since 7.4 030 * 031 */ 032public class NXJsonUnmarshaller extends JsonUnmarshaller { 033 034 @Override 035 public <R extends BaseResource> R unmarshal(final InputStream inputStream, 036 final ResourceDescriptor resourceDescriptor, 037 final ResourceFactory<R> resourceFactory) 038 throws InvalidResourceException { 039 try { 040 041 String json = FileUtils.read(inputStream); 042 final JSONObject jsonObject = makeCaseInsensitive(new JSONObject( 043 new JSONTokener(json))); 044 045 final NXJsonParser parser = new NXJsonParser(); 046 return parser.doUnmarshal(jsonObject, resourceDescriptor, 047 resourceFactory, null); 048 } catch (JSONException e) { 049 throw new InvalidResourceException("Error while reading JSON: " 050 + e.getMessage(), e); 051 } catch (IOException e) { 052 throw new InvalidResourceException("Error while reading JSON: " 053 + e.getMessage(), e); 054 } 055 } 056 057 protected JSONObject makeCaseInsensitive(final JSONObject jsonObject) 058 throws JSONException { 059 if (jsonObject == null) { 060 return null; 061 } 062 063 Iterator keys = jsonObject.keys(); 064 Map lowerCaseMap = new HashMap(jsonObject.length()); 065 while (keys.hasNext()) { 066 String key = keys.next().toString(); 067 String lowerCaseKey = toLowerCase(key); 068 lowerCaseMap.put(lowerCaseKey, jsonObject.get(key)); 069 } 070 071 return new JSONObject(lowerCaseMap); 072 } 073}