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