001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Thierry Delprat
018 */
019package org.nuxeo.scim.server.jaxrs.marshalling;
020
021import java.io.IOException;
022import java.io.InputStream;
023import java.lang.annotation.Annotation;
024import java.lang.reflect.Type;
025
026import javax.ws.rs.Consumes;
027import javax.ws.rs.WebApplicationException;
028import javax.ws.rs.core.MediaType;
029import javax.ws.rs.core.MultivaluedMap;
030import javax.ws.rs.ext.MessageBodyReader;
031import javax.ws.rs.ext.Provider;
032
033import com.unboundid.scim.data.UserResource;
034import com.unboundid.scim.marshal.Unmarshaller;
035import com.unboundid.scim.marshal.xml.XmlUnmarshaller;
036import com.unboundid.scim.schema.CoreSchema;
037import com.unboundid.scim.sdk.InvalidResourceException;
038
039/**
040 * Handles marshaling for SCIM {@link UserResource}
041 *
042 * @author tiry
043 * @since 7.4
044 */
045@Provider
046@Consumes({ "application/xml", "application/json" })
047public class UserResourceReader implements MessageBodyReader<UserResource> {
048
049    @Override
050    public boolean isReadable(Class<?> type, Type genericType,
051            Annotation[] annotations, MediaType mediaType) {
052        return UserResource.class.isAssignableFrom(type);
053    }
054
055    @Override
056    public UserResource readFrom(Class<UserResource> type, Type genericType,
057            Annotation[] annotations, MediaType mediaType,
058            MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
059            throws IOException, WebApplicationException {
060
061        Unmarshaller unmarshaller = null;
062        if (mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)) {
063            unmarshaller = new XmlUnmarshaller();
064        } else {
065            unmarshaller = new NXJsonUnmarshaller();
066        }
067         try {
068            return unmarshaller.unmarshal(entityStream, CoreSchema.USER_DESCRIPTOR, UserResource.USER_RESOURCE_FACTORY);
069        } catch (InvalidResourceException e) {
070            // TODO Auto-generated catch block
071            e.printStackTrace();
072        }
073        return null;
074    }
075
076}