001package org.nuxeo.scim.server.jaxrs.marshalling;
002
003import java.io.IOException;
004import java.io.OutputStream;
005import java.lang.annotation.Annotation;
006import java.lang.reflect.Type;
007
008import javax.ws.rs.Produces;
009import javax.ws.rs.WebApplicationException;
010import javax.ws.rs.core.MediaType;
011import javax.ws.rs.core.MultivaluedMap;
012import javax.ws.rs.ext.MessageBodyWriter;
013import javax.ws.rs.ext.Provider;
014
015import com.unboundid.scim.data.UserResource;
016import com.unboundid.scim.marshal.Marshaller;
017import com.unboundid.scim.marshal.json.JsonMarshaller;
018import com.unboundid.scim.marshal.xml.XmlMarshaller;
019import com.unboundid.scim.sdk.SCIMException;
020
021/**
022 * Handles marshaling for SCIM {@link UserResource}
023 *
024 * @author tiry
025 * @since 7.4
026 */
027@Provider
028@Produces({ "application/xml", "application/json" })
029public class UserResourceWriter implements MessageBodyWriter<UserResource> {
030
031    @Override
032    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
033        return UserResource.class.isAssignableFrom(type);
034    }
035
036    @Override
037    public long getSize(UserResource t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
038        return -1;
039    }
040
041    @Override
042    public void writeTo(UserResource t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
043            MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException,
044            WebApplicationException {
045
046        try {
047            Marshaller marshaller = null;
048            httpHeaders.remove("Content-Type");
049            if (t instanceof UserResourceWithMimeType) {
050                if (((UserResourceWithMimeType) t).getMediaType().equals(MediaType.APPLICATION_JSON_TYPE)) {
051                    marshaller = new JsonMarshaller();
052                    httpHeaders.add("Content-Type", MediaType.APPLICATION_JSON);
053                } else {
054                    marshaller = new XmlMarshaller();
055                    httpHeaders.add("Content-Type", MediaType.APPLICATION_XML);
056                }
057            } else {
058                if (mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)) {
059                    marshaller = new XmlMarshaller();
060                    httpHeaders.add("Content-Type", MediaType.APPLICATION_XML);
061                } else {
062                    marshaller = new JsonMarshaller();
063                    httpHeaders.add("Content-Type", MediaType.APPLICATION_JSON);
064                }
065            }
066            marshaller.marshal(t, entityStream);
067        } catch (SCIMException e) {
068            throw new WebApplicationException(e);
069        }
070    }
071
072}