001 /*
002 * Copyright 2011-2012 UnboundID Corp.
003 *
004 * This program is free software; you can redistribute it and/or modify
005 * it under the terms of the GNU General Public License (GPLv2 only)
006 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
007 * as published by the Free Software Foundation.
008 *
009 * This program 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
012 * GNU General Public License for more details.
013 *
014 * You should have received a copy of the GNU General Public License
015 * along with this program; if not, see <http://www.gnu.org/licenses>.
016 */
017
018 package com.unboundid.scim.wink;
019
020 import com.unboundid.scim.marshal.Marshaller;
021 import com.unboundid.scim.marshal.json.JsonMarshaller;
022 import com.unboundid.scim.marshal.xml.XmlMarshaller;
023 import com.unboundid.scim.sdk.Debug;
024 import com.unboundid.scim.sdk.SCIMResponse;
025
026 import javax.ws.rs.WebApplicationException;
027 import javax.ws.rs.core.MediaType;
028 import javax.ws.rs.core.Response;
029 import javax.ws.rs.core.StreamingOutput;
030 import java.io.IOException;
031 import java.io.OutputStream;
032
033
034
035 /**
036 * This class is an abstract base class for JAX-RS static SCIM resources
037 * such as the Service Provider Configuration.
038 */
039 public class AbstractStaticResource
040 {
041 /**
042 * Sets the response entity (content) for a SCIM response.
043 *
044 * @param builder A JAX-RS response builder.
045 * @param mediaType The media type to be returned.
046 * @param scimResponse The SCIM response to be returned.
047 */
048 protected void setResponseEntity(final Response.ResponseBuilder builder,
049 final MediaType mediaType,
050 final SCIMResponse scimResponse)
051 {
052 final Marshaller marshaller;
053 builder.type(mediaType);
054 if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE))
055 {
056 marshaller = new JsonMarshaller();
057 }
058 else
059 {
060 marshaller = new XmlMarshaller();
061 }
062
063 final StreamingOutput output = new StreamingOutput()
064 {
065 public void write(final OutputStream outputStream)
066 throws IOException, WebApplicationException
067 {
068 try
069 {
070 scimResponse.marshal(marshaller, outputStream);
071 }
072 catch (Exception e)
073 {
074 Debug.debugException(e);
075 throw new WebApplicationException(
076 e, Response.Status.INTERNAL_SERVER_ERROR);
077 }
078 }
079 };
080 builder.entity(output);
081 }
082 }