001 /******************************************************************************* 002 * Copyright (C) PicoContainer Organization. All rights reserved. 003 * --------------------------------------------------------------------------- 004 * The software in this package is published under the terms of the BSD style 005 * license a copy of which has been included with this distribution in the 006 * LICENSE.txt file. 007 ******************************************************************************/ 008 package org.picocontainer.script.groovy; 009 010 import java.util.Collections; 011 import java.util.List; 012 013 import org.codehaus.groovy.control.CompilationFailedException; 014 import org.codehaus.groovy.control.ErrorCollector; 015 import org.codehaus.groovy.control.ProcessingUnit; 016 import org.codehaus.groovy.control.messages.ExceptionMessage; 017 import org.picocontainer.script.ScriptedPicoContainerMarkupException; 018 019 /** 020 * Thrown when a groovy compilation error occurs 021 * 022 * @author Paul Hammant 023 */ 024 @SuppressWarnings("serial") 025 public final class GroovyCompilationException extends ScriptedPicoContainerMarkupException { 026 private final CompilationFailedException compilationFailedException; 027 028 public GroovyCompilationException(String message, CompilationFailedException e) { 029 super(message,e); 030 this.compilationFailedException = e; 031 } 032 033 public String getMessage() { 034 StringBuffer sb = new StringBuffer(); 035 sb.append(super.getMessage()).append("\n"); 036 List<?> errors = getErrors(compilationFailedException); 037 for (Object error : errors) { 038 if (error instanceof ExceptionMessage) { 039 ExceptionMessage em = (ExceptionMessage) error; 040 sb.append(em.getCause().getMessage()).append("\n"); 041 } 042 } 043 return sb.toString(); 044 } 045 046 /** 047 * Extract errors from groovy exception, coding defensively against 048 * possible null values. 049 * @param e the CompilationFailedException 050 * @return A List of errors 051 */ 052 private List<?> getErrors(CompilationFailedException e) { 053 ProcessingUnit unit = e.getUnit(); 054 if ( unit != null ){ 055 ErrorCollector collector = unit.getErrorCollector(); 056 if ( collector != null ){ 057 List<?> errors = collector.getErrors(); 058 if ( errors != null ){ 059 return errors; 060 } 061 } 062 } 063 return Collections.EMPTY_LIST; 064 } 065 }