Search in sources :

Example 6 with VelocityException

use of org.apache.velocity.exception.VelocityException in project intellij-community by JetBrains.

the class FileTemplateUtil method mergeTemplate.

private static String mergeTemplate(String templateContent, final VelocityContext context, boolean useSystemLineSeparators, @Nullable Consumer<VelocityException> exceptionHandler) throws IOException {
    final StringWriter stringWriter = new StringWriter();
    try {
        Project project = null;
        final Object projectName = context.get(FileTemplateManager.PROJECT_NAME_VARIABLE);
        if (projectName instanceof String) {
            Project[] projects = ProjectManager.getInstance().getOpenProjects();
            project = ContainerUtil.find(projects, project1 -> projectName.equals(project1.getName()));
        }
        VelocityWrapper.evaluate(project, context, stringWriter, templateContent);
    } catch (final VelocityException e) {
        if (ApplicationManager.getApplication().isUnitTestMode()) {
            LOG.error(e);
        }
        LOG.info("Error evaluating template:\n" + templateContent, e);
        if (exceptionHandler == null) {
            ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(IdeBundle.message("error.parsing.file.template", e.getMessage()), IdeBundle.message("title.velocity.error")));
        } else {
            exceptionHandler.consume(e);
        }
    }
    final String result = stringWriter.toString();
    if (useSystemLineSeparators) {
        final String newSeparator = CodeStyleSettingsManager.getSettings(ProjectManagerEx.getInstanceEx().getDefaultProject()).getLineSeparator();
        if (!"\n".equals(newSeparator)) {
            return StringUtil.convertLineSeparators(result, newSeparator);
        }
    }
    return result;
}
Also used : java.util(java.util) ArrayUtil(com.intellij.util.ArrayUtil) ContainerUtil(com.intellij.util.containers.ContainerUtil) ProjectManager(com.intellij.openapi.project.ProjectManager) CustomFileTemplate(com.intellij.ide.fileTemplates.impl.CustomFileTemplate) ParseException(org.apache.velocity.runtime.parser.ParseException) PsiElement(com.intellij.psi.PsiElement) TIntObjectHashMap(gnu.trove.TIntObjectHashMap) StringUtils(org.apache.velocity.util.StringUtils) FileTypes(com.intellij.openapi.fileTypes.FileTypes) Project(com.intellij.openapi.project.Project) Messages(com.intellij.openapi.ui.Messages) Token(org.apache.velocity.runtime.parser.Token) org.apache.velocity.runtime.parser.node(org.apache.velocity.runtime.parser.node) Logger(com.intellij.openapi.diagnostic.Logger) VelocityException(org.apache.velocity.exception.VelocityException) Extensions(com.intellij.openapi.extensions.Extensions) ClassLoaderUtil(com.intellij.openapi.util.ClassLoaderUtil) FileTypeManager(com.intellij.openapi.fileTypes.FileTypeManager) StringUtil(com.intellij.openapi.util.text.StringUtil) StringWriter(java.io.StringWriter) ProjectManagerEx(com.intellij.openapi.project.ex.ProjectManagerEx) IOException(java.io.IOException) FileType(com.intellij.openapi.fileTypes.FileType) CodeStyleSettingsManager(com.intellij.psi.codeStyle.CodeStyleSettingsManager) FileTypeManagerEx(com.intellij.openapi.fileTypes.ex.FileTypeManagerEx) VelocityContext(org.apache.velocity.VelocityContext) IdeBundle(com.intellij.ide.IdeBundle) CommandProcessor(com.intellij.openapi.command.CommandProcessor) ThrowableComputable(com.intellij.openapi.util.ThrowableComputable) Nullable(org.jetbrains.annotations.Nullable) StringReader(java.io.StringReader) ApplicationManager(com.intellij.openapi.application.ApplicationManager) PsiDirectory(com.intellij.psi.PsiDirectory) Pattern(java.util.regex.Pattern) NotNull(org.jetbrains.annotations.NotNull) Consumer(com.intellij.util.Consumer) javax.swing(javax.swing) Project(com.intellij.openapi.project.Project) StringWriter(java.io.StringWriter) VelocityException(org.apache.velocity.exception.VelocityException)

Example 7 with VelocityException

use of org.apache.velocity.exception.VelocityException in project tdi-studio-se by Talend.

the class TemplateProcessor method processTemplate.

public static boolean processTemplate(String logTag, Map<String, Object> contextParams, OutputStream outputStream, InputStream templateStream) throws IOException {
    final Reader templateReader = new InputStreamReader(templateStream);
    final Writer outputWriter = new OutputStreamWriter(outputStream);
    ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(TemplateProcessor.class.getClassLoader());
        VelocityEngine engine = new VelocityEngine();
        //          engine.setProperty("resource.loader", "classpath"); //$NON-NLS-1$ //$NON-NLS-2$
        //          engine.setProperty("classpath.resource.loader.class", //$NON-NLS-1$
        //                  "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); //$NON-NLS-1$
        engine.setProperty(RuntimeConstants.EVENTHANDLER_REFERENCEINSERTION, EscapeXmlReference.class.getName());
        engine.init();
        VelocityContext context = new VelocityContext(contextParams);
        return engine.evaluate(context, outputWriter, logTag, templateReader);
    } catch (VelocityException ve) {
        // org.apache.velocity.exception.MethodInvocationException;
        throw new IOException(ve);
    } finally {
        Thread.currentThread().setContextClassLoader(originalClassLoader);
        templateReader.close();
        outputWriter.close();
    }
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) InputStreamReader(java.io.InputStreamReader) EscapeXmlReference(org.apache.velocity.app.event.implement.EscapeXmlReference) VelocityContext(org.apache.velocity.VelocityContext) VelocityException(org.apache.velocity.exception.VelocityException) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Example 8 with VelocityException

use of org.apache.velocity.exception.VelocityException in project xwiki-platform by xwiki.

the class WebJarsResourceReferenceHandlerTest method failingResourceEvaluation.

@Test
public void failingResourceEvaluation() throws Exception {
    WebJarsResourceReference reference = new WebJarsResourceReference("wiki:wiki", Arrays.asList("angular", "2.1.11", "angular.js"));
    reference.addParameter("evaluate", "true");
    ByteArrayInputStream resourceStream = new ByteArrayInputStream("content".getBytes());
    when(this.classLoader.getResourceAsStream("META-INF/resources/webjars/angular/2.1.11/angular.js")).thenReturn(resourceStream);
    VelocityManager velocityManager = this.componentManager.getInstance(VelocityManager.class);
    VelocityEngine velocityEngine = mock(VelocityEngine.class);
    when(velocityManager.getVelocityEngine()).thenReturn(velocityEngine);
    when(velocityEngine.evaluate(any(), any(), eq("angular/2.1.11/angular.js"), any(Reader.class))).thenThrow(new VelocityException("Bad code!"));
    this.handler.handle(reference, this.chain);
    // Verify the exception is logged.
    verify(this.componentManager.getMockedLogger()).error(eq("Failed to evaluate the Velocity code from WebJar resource [angular/2.1.11/angular.js]"), any(ResourceReferenceHandlerException.class));
    // Verify that the client is properly notified about the failure.
    verify(this.response.getHttpServletResponse()).sendError(500, "Failed to evaluate the Velocity code from WebJar resource [angular/2.1.11/angular.js]");
    // The next handlers are still called.
    verify(this.chain).handleNext(reference);
}
Also used : ResourceReferenceHandlerException(org.xwiki.resource.ResourceReferenceHandlerException) VelocityEngine(org.xwiki.velocity.VelocityEngine) WebJarsResourceReference(org.xwiki.webjars.internal.WebJarsResourceReference) ByteArrayInputStream(java.io.ByteArrayInputStream) VelocityManager(org.xwiki.velocity.VelocityManager) VelocityException(org.apache.velocity.exception.VelocityException) Reader(java.io.Reader) Test(org.junit.Test)

Example 9 with VelocityException

use of org.apache.velocity.exception.VelocityException in project maven-plugins by apache.

the class VelocityTemplate method generate.

/**
 * Using a specified Velocity Template and provided context, create the outputFilename.
 *
 * @param outputFilename the file to be generated.
 * @param template       the velocity template to use.
 * @param context        the velocity context map.
 * @throws VelocityException if the template was not found or any other Velocity exception.
 * @throws MojoExecutionException if merging the velocity template failed.
 * @throws IOException if there was an error when writing to the output file.
 */
public void generate(String outputFilename, String template, Context context) throws VelocityException, MojoExecutionException, IOException {
    Writer writer = null;
    try {
        File f = new File(outputFilename);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        writer = new FileWriter(f);
        getVelocity().getEngine().mergeTemplate(templateDirectory + "/" + template, context, writer);
    } catch (ResourceNotFoundException e) {
        throw new ResourceNotFoundException("Template not found: " + templateDirectory + "/" + template, e);
    } catch (VelocityException | IOException e) {
        // to get past generic catch for Exception.
        throw e;
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
            getLog().debug("File " + outputFilename + " created...");
        }
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) FileWriter(java.io.FileWriter) VelocityException(org.apache.velocity.exception.VelocityException) IOException(java.io.IOException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) File(java.io.File) FileWriter(java.io.FileWriter) Writer(java.io.Writer) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) VelocityException(org.apache.velocity.exception.VelocityException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException)

Aggregations

VelocityException (org.apache.velocity.exception.VelocityException)9 IOException (java.io.IOException)6 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)5 File (java.io.File)4 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)3 ApplicationManager (com.intellij.openapi.application.ApplicationManager)2 Logger (com.intellij.openapi.diagnostic.Logger)2 FileType (com.intellij.openapi.fileTypes.FileType)2 FileTypeManager (com.intellij.openapi.fileTypes.FileTypeManager)2 Project (com.intellij.openapi.project.Project)2 ProjectManagerEx (com.intellij.openapi.project.ex.ProjectManagerEx)2 Messages (com.intellij.openapi.ui.Messages)2 FileWriter (java.io.FileWriter)2 Reader (java.io.Reader)2 Writer (java.io.Writer)2 VelocityContext (org.apache.velocity.VelocityContext)2 Context (org.apache.velocity.context.Context)2 CodeStyleFacade (com.intellij.codeStyle.CodeStyleFacade)1 LogMessageEx (com.intellij.diagnostic.LogMessageEx)1 RunManager (com.intellij.execution.RunManager)1