001/*
002 * (C) Copyright 2006-2012 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.ecm.platform.web.common.exceptionhandling;
022
023import java.util.Arrays;
024import java.util.List;
025
026import javax.servlet.ServletException;
027
028import org.nuxeo.ecm.core.api.DocumentSecurityException;
029
030public class ExceptionHelper {
031
032    private ExceptionHelper() {
033    }
034
035    public static Throwable unwrapException(Throwable t) {
036        Throwable cause = null;
037        if (t instanceof ServletException) {
038            cause = ((ServletException) t).getRootCause();
039        } else if (t instanceof Exception) {
040            cause = t.getCause();
041        }
042
043        if (cause == null) {
044            return t;
045        } else {
046            return unwrapException(cause);
047        }
048    }
049
050    protected static final List<String> ERROR_MESSAGES = Arrays.asList("java.lang.SecurityException",
051            DocumentSecurityException.class.getName(), SecurityException.class.getName());
052
053    public static boolean isSecurityError(Throwable t) {
054        if (t == null) {
055            return false;
056        } else if (t instanceof DocumentSecurityException || t.getCause() instanceof DocumentSecurityException
057                || t.getCause() instanceof SecurityException) {
058            return true;
059        } else if (t.getMessage() != null) {
060            String message = t.getMessage();
061            for (String errorMessage : ERROR_MESSAGES) {
062                if (message.contains(errorMessage)) {
063                    return true;
064                }
065            }
066        }
067        return false;
068    }
069
070}