001/*
002 *  Copyright 2012 Anyware Services
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 */
016package org.ametys.core.util;
017
018import java.net.SocketException;
019
020import org.apache.log4j.spi.Filter;
021import org.apache.log4j.spi.LoggingEvent;
022import org.apache.log4j.spi.ThrowableInformation;
023
024import org.ametys.runtime.authentication.AuthorizationRequiredException;
025
026/**
027 * Simple {@link Filter} not logging internal exceptions, such as AuthorizationRequiredException.
028 */
029public class AmetysExceptionFilter extends Filter
030{
031    @Override
032    public int decide(LoggingEvent event)
033    {
034        ThrowableInformation info = event.getThrowableInformation();
035        if (info != null && info.getThrowable() != null)
036        {
037            Throwable t = info.getThrowable();
038            if (_unroll(t) instanceof AuthorizationRequiredException)
039            {
040                return Filter.DENY;
041            }
042            
043            if (_unroll(t) instanceof SocketException)
044            {
045                return Filter.DENY;
046            }
047        }
048        
049        return Filter.NEUTRAL;
050    }
051    
052    private Throwable _unroll(Throwable t)
053    {
054        Throwable cause = t.getCause();
055        
056        if (cause == null)
057        {
058            return t;
059        }
060        else
061        {
062            return _unroll(cause);
063        }
064    }
065}