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.OutputStream;
023import java.lang.annotation.Annotation;
024import java.lang.reflect.Type;
025
026import javax.ws.rs.Produces;
027import javax.ws.rs.WebApplicationException;
028import javax.ws.rs.core.MediaType;
029import javax.ws.rs.core.MultivaluedMap;
030import javax.ws.rs.ext.MessageBodyWriter;
031import javax.ws.rs.ext.Provider;
032
033import com.unboundid.scim.data.BaseResource;
034import com.unboundid.scim.marshal.Marshaller;
035import com.unboundid.scim.marshal.json.JsonMarshaller;
036import com.unboundid.scim.marshal.xml.XmlMarshaller;
037import com.unboundid.scim.sdk.Resources;
038import com.unboundid.scim.sdk.SCIMException;
039
040/**
041 * Handles marshaling for SCIM {@link BaseResource}
042 * @author tiry
043 * @since 7.4
044 */
045@Provider
046@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
047public class ResourcesWriter implements MessageBodyWriter<Resources<BaseResource>> {
048
049    @Override
050    public boolean isWriteable(Class<?> type, Type genericType,
051            Annotation[] annotations, MediaType mediaType) {
052        return Resources.class.isAssignableFrom(type);
053    }
054
055    @Override
056    public long getSize(Resources<BaseResource> t, Class<?> type, Type genericType,
057            Annotation[] annotations, MediaType mediaType) {
058        return -1;
059    }
060
061    @Override
062    public void writeTo(Resources<BaseResource> t, Class<?> type, Type genericType,
063            Annotation[] annotations, MediaType mediaType,
064            MultivaluedMap<String, Object> httpHeaders,
065            OutputStream entityStream) throws IOException,
066            WebApplicationException {
067
068        try {
069            Marshaller marshaller = null;
070            if (mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)) {
071                marshaller = new XmlMarshaller();
072            } else {
073                marshaller = new JsonMarshaller();
074            }
075            marshaller.marshal(t, entityStream);
076        } catch (SCIMException e) {
077            throw new WebApplicationException(e);
078        }
079    }
080
081}