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.runtime.exception;
017
018import java.io.IOException;
019
020import org.apache.avalon.framework.context.Context;
021import org.apache.avalon.framework.context.ContextException;
022import org.apache.avalon.framework.context.Contextualizable;
023import org.apache.avalon.framework.logger.AbstractLogEnabled;
024import org.apache.avalon.framework.thread.ThreadSafe;
025import org.apache.cocoon.Constants;
026import org.apache.excalibur.source.impl.FileSource;
027
028/**
029 * Simple ExceptionHandler pointing to the default error XSL.<br>
030 * In <code>WEB-INF/stylesheets/error</code> or in the runtime jar in <code>pages/error/error.xsl</code>
031 */
032public class DefaultExceptionHandler extends AbstractLogEnabled implements ExceptionHandler, ThreadSafe, Contextualizable
033{
034    private org.apache.cocoon.environment.Context _cocoonContext;
035    
036    /**
037     * Constructor as component
038     */
039    public DefaultExceptionHandler()
040    {
041        // empty
042    }
043    
044    /**
045     * Constructor for default behavior when application is not starting
046     * @param context The cocoon context
047     */
048    DefaultExceptionHandler(org.apache.cocoon.environment.Context context)
049    {
050        _cocoonContext = context;
051    }
052    
053    @Override
054    public void contextualize(Context context) throws ContextException
055    {
056        _cocoonContext = (org.apache.cocoon.environment.Context) context.get(Constants.CONTEXT_ENVIRONMENT_CONTEXT);
057    }
058    
059    public String getExceptionXSLURI(String code)
060    {
061        String uri = null;
062        try
063        {
064            uri = "file://" + _cocoonContext.getRealPath("/WEB-INF/stylesheets/error/error_" + code + ".xsl");
065            if (new FileSource(uri).exists())
066            {
067                return uri;
068            }
069        }
070        catch (IOException e)
071        {
072            getLogger().warn("Unable to find XSL error '" + uri + "'", e);
073        }
074        
075        return "plugin:core-ui://pages/error/" + code + ".xsl";
076    }
077}