    001    package org.nanocontainer.script.groovy;
    002
    003    import java.util.Collections;
    004    import java.util.List;
    005
    006    import org.codehaus.groovy.control.CompilationFailedException;
    007    import org.codehaus.groovy.control.ErrorCollector;
    008    import org.codehaus.groovy.control.ProcessingUnit;
    009    import org.codehaus.groovy.control.messages.ExceptionMessage;
    010    import org.nanocontainer.script.NanoContainerMarkupException;
    011
    012    /**
    013     * @author Paul Hammant
    014     * @version $Revision: 3144 $
    015     */
    016    public class GroovyCompilationException extends NanoContainerMarkupException {
    017        private CompilationFailedException compilationFailedException;
    018
    019        public GroovyCompilationException(String message, CompilationFailedException e) {
    020            super(message,e);
    021            this.compilationFailedException = e;
    022        }
    023
    024        public String getMessage() {
    025            StringBuffer sb = new StringBuffer();
    026            sb.append(super.getMessage() + "\n");
    027            List errors = getErrors(compilationFailedException);
    028            for (int i = 0; i < errors.size(); i++) {
    029                Object o = errors.get(i);
    030                if (o instanceof ExceptionMessage) {
    031                    ExceptionMessage em = (ExceptionMessage) o;
    032                    sb.append(em.getCause().getMessage() + "\n");
    033                }
    034            }
    035            return sb.toString();
    036        }
    037
    038        /**
    039         * Extract errors from groovy exception, coding defensively against
    040         * possible null values.
    041         * @param e the CompilationFailedException
    042         * @return A List of errors
    043         */
    044        private List getErrors(CompilationFailedException e) {
    045            ProcessingUnit unit = e.getUnit();
    046            if ( unit != null ){
    047                ErrorCollector collector = unit.getErrorCollector();
    048                if ( collector != null ){
    049                    List errors = collector.getErrors();
    050                    if ( errors != null ){
    051                        return errors;
    052                    }
    053                }
    054            }
    055            return Collections.EMPTY_LIST;
    056        }
    057    }