/*
 * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.templating;

import com.arsdigita.util.UncheckedWrapperException;

import javax.xml.transform.TransformerException;

/**
 * A simple wrapper around <code>TransformerException</code> that provides a
 * more useful {@link #getMessage()} method.
 *
 * @author  Vadim Nasardinov
 * @since   2003-11-21
 * @version $Id: //core-platform/dev/src/com/arsdigita/templating/WrappedTransformerException.java#3 $
 */
public final class WrappedTransformerException extends UncheckedWrapperException {
    private TransformerException m_trex;

    /**
     * The passed in <code>TransformerException</code> is retrievable later via
     * {@link #getRootCause()}.
     *
     * @pre ex != null
     **/
    public WrappedTransformerException(TransformerException ex) {
        super(ex);
        if ( ex == null ) { throw new NullPointerException("ex"); }
        m_trex = ex;
    }

    /**
     * @see #WrappedTransformerException(TransformerException)
     * @pre ex != null
     **/
    public WrappedTransformerException(String msg, TransformerException ex) {
        super(msg, ex);
        if ( ex == null ) { throw new NullPointerException("ex"); }
        m_trex = ex;
    }

    /**
     * The returned message includes the location information.
     **/
    public String getMessage() {
        StringBuffer sb = new StringBuffer();
        possiblyAppend(sb, super.getMessage());
        appendMessage(m_trex, sb);
        return sb.toString();
    }

    private static void appendMessage(TransformerException ex,
                                        StringBuffer sb) {

        if ( !possiblyAppend(sb, ex.getMessageAndLocation()) ) {
            possiblyAppend(sb, ex.getMessage());
            possiblyAppend(sb, ex.getLocationAsString());
        }
        if ( ex.getCause() instanceof TransformerException ) {
            appendMessage((TransformerException) ex.getCause(), sb);
        } else {
            if ( ex.getCause() != null ) {
                possiblyAppend(sb, ex.getCause().getMessage());
            }
        }
    }

    private static boolean possiblyAppend(StringBuffer sb, String str) {
        if ( str == null ) { return false; }
        sb.append(str).append("; ");
        return true;
    }
}
