001/*
002 * Copyright 2015-2016 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
018package com.unboundid.scim2.server.providers;
019
020import com.unboundid.scim2.common.messages.ErrorResponse;
021import com.unboundid.scim2.server.utils.ServerUtils;
022
023import javax.ws.rs.WebApplicationException;
024import javax.ws.rs.core.Context;
025import javax.ws.rs.core.HttpHeaders;
026import javax.ws.rs.core.Request;
027import javax.ws.rs.core.Response;
028import javax.ws.rs.ext.ExceptionMapper;
029import javax.ws.rs.ext.Provider;
030
031/**
032 * A JAX-RS ExceptionMapper for to convert standard WebApplicationExceptions to
033 * SCIM ErrorResponses.
034 */
035@Provider
036public class RuntimeExceptionMapper implements
037    ExceptionMapper<RuntimeException>
038{
039  @Context
040  private Request request;
041  @Context
042  private HttpHeaders headers;
043
044  /**
045   * {@inheritDoc}
046   */
047  public Response toResponse(final RuntimeException exception)
048  {
049    ErrorResponse errorResponse;
050
051    if(exception instanceof WebApplicationException)
052    {
053      errorResponse = new ErrorResponse(
054          ((WebApplicationException)exception).getResponse().getStatus());
055      errorResponse.setDetail(exception.getMessage());
056    }
057    else
058    {
059      errorResponse = new ErrorResponse(500);
060      errorResponse.setDetail(exception.toString());
061    }
062
063    return ServerUtils.setAcceptableType(
064        Response.status(errorResponse.getStatus()).entity(errorResponse),
065        headers.getAcceptableMediaTypes()).build();
066  }
067}