001/*
002 * (C) Copyright 2015 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library 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 GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nuxeo - initial API and implementation
016 *
017 */
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.ServiceProviderConfig;
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.SCIMException;
038
039/**
040 * Handles marshaling for SCIM {@link ServiceProviderConfig}
041 *
042 * @author tiry
043 * @since 7.4
044 */
045@Provider
046@Produces({ "application/xml", "application/json" })
047public class ServiceProviderConfigWriter implements MessageBodyWriter<ServiceProviderConfig> {
048
049    @Override
050    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
051        return ServiceProviderConfig.class.isAssignableFrom(type);
052    }
053
054    @Override
055    public long getSize(ServiceProviderConfig t, Class<?> type, Type genericType, Annotation[] annotations,
056            MediaType mediaType) {
057        return -1;
058    }
059
060    @Override
061    public void writeTo(ServiceProviderConfig t, Class<?> type, Type genericType, Annotation[] annotations,
062            MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
063            throws IOException, WebApplicationException {
064
065        try {
066            Marshaller marshaller = null;
067            if (mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)) {
068                marshaller = new XmlMarshaller();
069            } else {
070                marshaller = new JsonMarshaller();
071            }
072            marshaller.marshal(t, entityStream);
073        } catch (SCIMException e) {
074            throw new WebApplicationException(e);
075        }
076
077    }
078
079}