001/*
002 * (C) Copyright 2006-2009 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 * $Id$
020 */
021
022package org.nuxeo.ecm.webdav;
023
024import org.apache.commons.logging.Log;
025import org.apache.commons.logging.LogFactory;
026import org.apache.http.HttpStatus;
027import org.nuxeo.ecm.core.api.RecoverableClientException;
028
029import javax.ws.rs.WebApplicationException;
030import javax.ws.rs.core.Response;
031import javax.ws.rs.ext.ExceptionMapper;
032import javax.ws.rs.ext.Provider;
033
034import java.io.PrintWriter;
035import java.io.StringWriter;
036
037/**
038 * Simple error handler to give back a user-readable status, and log it to the console.
039 * <p>
040 * This is a convenience for trouble-shouting.
041 */
042@Provider
043public class ExceptionHandler implements ExceptionMapper<Exception> {
044
045    private static final Log log = LogFactory.getLog(ExceptionHandler.class);
046
047    @Override
048    public Response toResponse(Exception e) {
049        StringWriter sw = new StringWriter();
050        e.printStackTrace(new PrintWriter(sw));
051        int status = 500;
052        // String msg;
053        if (e instanceof WebApplicationException) {
054            status = ((WebApplicationException) e).getResponse().getStatus();
055            if (status < 400 || status >= 500) {
056                log.error("Status = " + status);
057                log.error(e, e);
058            }
059            // msg = "Error " + status + "\n" + e.getMessage() + "\n" + sw;
060        } else if (e.getCause() instanceof RecoverableClientException
061                && ("QuotaExceededException".equals(e.getCause().getClass().getSimpleName()))) {
062            status = HttpStatus.SC_INSUFFICIENT_STORAGE; // 507
063            log.debug(e, e);
064        } else {
065            log.error(e, e);
066            // msg = "Error\n\n" + e.getMessage() + "\n\n" + sw;
067        }
068        return Response.status(status).build();
069    }
070
071}