Search in sources :

Example 1 with VelocityException

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

the class TemplateModuleBuilder method unzip.

private void unzip(@Nullable final String projectName, String path, final boolean moduleMode, @Nullable ProgressIndicator pI, boolean reportFailuresWithDialog) {
    final WizardInputField basePackage = getBasePackageField();
    try {
        final File dir = new File(path);
        class ExceptionConsumer implements Consumer<VelocityException> {

            private String myPath;

            private String myText;

            private SmartList<Trinity<String, String, VelocityException>> myFailures = new SmartList<>();

            @Override
            public void consume(VelocityException e) {
                myFailures.add(Trinity.create(myPath, myText, e));
            }

            private void setCurrentFile(String path, String text) {
                myPath = path;
                myText = text;
            }

            private void reportFailures() {
                if (myFailures.isEmpty()) {
                    return;
                }
                if (reportFailuresWithDialog) {
                    String dialogMessage;
                    if (myFailures.size() == 1) {
                        dialogMessage = "Failed to decode file \'" + myFailures.get(0).getFirst() + "\'";
                    } else {
                        StringBuilder dialogMessageBuilder = new StringBuilder();
                        dialogMessageBuilder.append("Failed to decode files: \n");
                        for (Trinity<String, String, VelocityException> failure : myFailures) {
                            dialogMessageBuilder.append(failure.getFirst()).append("\n");
                        }
                        dialogMessage = dialogMessageBuilder.toString();
                    }
                    Messages.showErrorDialog(dialogMessage, "Decoding Template");
                }
                StringBuilder reportBuilder = new StringBuilder();
                for (Trinity<String, String, VelocityException> failure : myFailures) {
                    reportBuilder.append("File: ").append(failure.getFirst()).append("\n");
                    reportBuilder.append("Exception:\n").append(ExceptionUtil.getThrowableText(failure.getThird())).append("\n");
                    reportBuilder.append("File content:\n\'").append(failure.getSecond()).append("\'\n");
                    reportBuilder.append("\n===========================================\n");
                }
                LOG.error(LogMessageEx.createEvent("Cannot decode files in template", "", new Attachment("Files in template", reportBuilder.toString())));
            }
        }
        ExceptionConsumer consumer = new ExceptionConsumer();
        List<File> filesToRefresh = new ArrayList<>();
        myTemplate.processStream(new ArchivedProjectTemplate.StreamProcessor<Void>() {

            @Override
            public Void consume(@NotNull ZipInputStream stream) throws IOException {
                ZipUtil.unzip(ProgressManager.getInstance().getProgressIndicator(), dir, stream, path1 -> {
                    if (moduleMode && path1.contains(Project.DIRECTORY_STORE_FOLDER)) {
                        return null;
                    }
                    if (basePackage != null) {
                        return path1.replace(getPathFragment(basePackage.getDefaultValue()), getPathFragment(basePackage.getValue()));
                    }
                    return path1;
                }, new ZipUtil.ContentProcessor() {

                    @Override
                    public byte[] processContent(byte[] content, File file) throws IOException {
                        if (pI != null) {
                            pI.checkCanceled();
                        }
                        FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(FileUtilRt.getExtension(file.getName()));
                        String text = new String(content, CharsetToolkit.UTF8_CHARSET);
                        consumer.setCurrentFile(file.getName(), text);
                        return fileType.isBinary() ? content : processTemplates(projectName, text, file, consumer);
                    }
                }, true);
                myTemplate.handleUnzippedDirectories(dir, filesToRefresh);
                return null;
            }
        });
        if (pI != null) {
            pI.setText("Refreshing...");
        }
        String iml = ContainerUtil.find(dir.list(), s -> s.endsWith(".iml"));
        if (moduleMode) {
            File from = new File(path, iml);
            File to = new File(getModuleFilePath());
            if (!from.renameTo(to)) {
                throw new IOException("Can't rename " + from + " to " + to);
            }
        }
        RefreshQueue refreshQueue = RefreshQueue.getInstance();
        LOG.assertTrue(!filesToRefresh.isEmpty());
        for (File file : filesToRefresh) {
            VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
            if (virtualFile == null) {
                throw new IOException("Can't find " + file);
            }
            refreshQueue.refresh(false, true, null, virtualFile);
        }
        consumer.reportFailures();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : FileUtilRt(com.intellij.openapi.util.io.FileUtilRt) Trinity(com.intellij.openapi.util.Trinity) com.intellij.openapi.module(com.intellij.openapi.module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Task(com.intellij.openapi.progress.Task) JDOMException(org.jdom.JDOMException) SmartList(com.intellij.util.SmartList) ModifiableRootModel(com.intellij.openapi.roots.ModifiableRootModel) CodeStyleFacade(com.intellij.codeStyle.CodeStyleFacade) Messages(com.intellij.openapi.ui.Messages) FileUtil(com.intellij.openapi.util.io.FileUtil) Logger(com.intellij.openapi.diagnostic.Logger) VelocityException(org.apache.velocity.exception.VelocityException) ProgressManager(com.intellij.openapi.progress.ProgressManager) FileTypeManager(com.intellij.openapi.fileTypes.FileTypeManager) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) PathMacroUtil(org.jetbrains.jps.model.serialization.PathMacroUtil) com.intellij.ide.util.projectWizard(com.intellij.ide.util.projectWizard) Nullable(org.jetbrains.annotations.Nullable) LogMessageEx(com.intellij.diagnostic.LogMessageEx) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) ModuleRootManager(com.intellij.openapi.roots.ModuleRootManager) ApplicationManager(com.intellij.openapi.application.ApplicationManager) ModulesProvider(com.intellij.openapi.roots.ui.configuration.ModulesProvider) ConfigurationException(com.intellij.openapi.options.ConfigurationException) NotNull(org.jetbrains.annotations.NotNull) Consumer(com.intellij.util.Consumer) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) RunConfiguration(com.intellij.execution.configurations.RunConfiguration) WriteAction(com.intellij.openapi.application.WriteAction) ZipInputStream(java.util.zip.ZipInputStream) CharsetToolkit(com.intellij.openapi.vfs.CharsetToolkit) Computable(com.intellij.openapi.util.Computable) InvalidDataException(com.intellij.openapi.util.InvalidDataException) ContainerUtil(com.intellij.util.containers.ContainerUtil) ModuleBasedConfiguration(com.intellij.execution.configurations.ModuleBasedConfiguration) ArrayList(java.util.ArrayList) RefreshQueue(com.intellij.openapi.vfs.newvfs.RefreshQueue) StartupManager(com.intellij.openapi.startup.StartupManager) RunManager(com.intellij.execution.RunManager) Project(com.intellij.openapi.project.Project) Properties(java.util.Properties) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) ProjectManagerEx(com.intellij.openapi.project.ex.ProjectManagerEx) ZipUtil(com.intellij.platform.templates.github.ZipUtil) IOException(java.io.IOException) FileType(com.intellij.openapi.fileTypes.FileType) File(java.io.File) StringUtilRt(com.intellij.openapi.util.text.StringUtilRt) ExceptionUtil(com.intellij.util.ExceptionUtil) FileTemplateUtil(com.intellij.ide.fileTemplates.FileTemplateUtil) Attachment(com.intellij.openapi.diagnostic.Attachment) javax.swing(javax.swing) VirtualFile(com.intellij.openapi.vfs.VirtualFile) ArrayList(java.util.ArrayList) Attachment(com.intellij.openapi.diagnostic.Attachment) RefreshQueue(com.intellij.openapi.vfs.newvfs.RefreshQueue) Consumer(com.intellij.util.Consumer) VelocityException(org.apache.velocity.exception.VelocityException) IOException(java.io.IOException) ZipInputStream(java.util.zip.ZipInputStream) FileType(com.intellij.openapi.fileTypes.FileType) SmartList(com.intellij.util.SmartList) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File)

Example 2 with VelocityException

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

the class AnnouncementMojo method processTemplate.

/**
 * Create the velocity template
 *
 * @param context velocity context that has the parameter values
 * @param outputDirectory directory where the file will be generated
 * @param template velocity template which will the context be merged
 * @param announcementFile The file name of the generated announcement
 * @throws VelocityException in case of errors.
 * @throws MojoExecutionException in case of errors.
 */
public void processTemplate(Context context, File outputDirectory, String template, String announcementFile) throws VelocityException, MojoExecutionException {
    File f;
    // Use the name of the template as a default value
    if (StringUtils.isEmpty(announcementFile)) {
        announcementFile = template;
    }
    try {
        f = new File(outputDirectory, announcementFile);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        VelocityEngine engine = velocity.getEngine();
        engine.setApplicationAttribute("baseDirectory", basedir);
        if (StringUtils.isEmpty(templateEncoding)) {
            templateEncoding = ReaderFactory.FILE_ENCODING;
            getLog().warn("File encoding has not been set, using platform encoding " + templateEncoding + ", i.e. build is platform dependent!");
        }
        Writer writer = new OutputStreamWriter(new FileOutputStream(f), templateEncoding);
        Template velocityTemplate = engine.getTemplate(templateDirectory + "/" + template, templateEncoding);
        velocityTemplate.merge(context, writer);
        writer.flush();
        writer.close();
        getLog().info("Created template " + f);
    } catch (ResourceNotFoundException rnfe) {
        throw new ResourceNotFoundException("Template not found. ( " + templateDirectory + "/" + template + " )");
    } catch (VelocityException ve) {
        throw new VelocityException(ve.toString());
    } catch (Exception e) {
        if (e.getCause() != null) {
            getLog().warn(e.getCause());
        }
        throw new MojoExecutionException(e.toString(), e.getCause());
    }
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) FileOutputStream(java.io.FileOutputStream) VelocityException(org.apache.velocity.exception.VelocityException) OutputStreamWriter(java.io.OutputStreamWriter) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) File(java.io.File) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer) VelocityException(org.apache.velocity.exception.VelocityException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) Template(org.apache.velocity.Template)

Example 3 with VelocityException

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

the class AnnouncementMojo method doGenerate.

protected void doGenerate(List<Release> releases, Release release) throws MojoExecutionException {
    try {
        ToolManager toolManager = new ToolManager(true);
        Context context = toolManager.createContext();
        if (getIntroduction() == null || getIntroduction().equals("")) {
            setIntroduction(getUrl());
        }
        context.put("releases", releases);
        context.put("groupId", getGroupId());
        context.put("artifactId", getArtifactId());
        context.put("version", getVersion());
        context.put("packaging", getPackaging());
        context.put("url", getUrl());
        context.put("release", release);
        context.put("introduction", getIntroduction());
        context.put("developmentTeam", getDevelopmentTeam());
        context.put("finalName", getFinalName());
        context.put("urlDownload", getUrlDownload());
        context.put("project", project);
        if (announceParameters == null) {
            // empty Map to prevent NPE in velocity execution
            context.put("announceParameters", Collections.emptyMap());
        } else {
            context.put("announceParameters", announceParameters);
        }
        processTemplate(context, announcementDirectory, template, announcementFile);
    } catch (ResourceNotFoundException rnfe) {
        throw new MojoExecutionException("Resource not found.", rnfe);
    } catch (VelocityException ve) {
        throw new MojoExecutionException(ve.toString(), ve);
    }
}
Also used : Context(org.apache.velocity.context.Context) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) VelocityException(org.apache.velocity.exception.VelocityException) ToolManager(org.apache.velocity.tools.ToolManager) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException)

Example 4 with VelocityException

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

the class DefaultCheckstyleRssGenerator method generateRSS.

@Override
public void generateRSS(CheckstyleResults results, CheckstyleRssGeneratorRequest checkstyleRssGeneratorRequest) throws MavenReportException {
    VelocityTemplate vtemplate = new VelocityTemplate(velocityComponent, CheckstyleReport.PLUGIN_RESOURCES);
    vtemplate.setLog(checkstyleRssGeneratorRequest.getLog());
    Context context = new VelocityContext();
    context.put("results", results);
    context.put("project", checkstyleRssGeneratorRequest.getMavenProject());
    context.put("copyright", checkstyleRssGeneratorRequest.getCopyright());
    context.put("levelInfo", SeverityLevel.INFO);
    context.put("levelWarning", SeverityLevel.WARNING);
    context.put("levelError", SeverityLevel.ERROR);
    context.put("stringutils", new StringUtils());
    try {
        vtemplate.generate(checkstyleRssGeneratorRequest.getOutputDirectory().getPath() + "/checkstyle.rss", "checkstyle-rss.vm", context);
    } catch (ResourceNotFoundException e) {
        throw new MavenReportException("Unable to find checkstyle-rss.vm resource.", e);
    } catch (MojoExecutionException | IOException | VelocityException e) {
        throw new MavenReportException("Unable to generate checkstyle.rss.", e);
    }
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) Context(org.apache.velocity.context.Context) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) VelocityContext(org.apache.velocity.VelocityContext) StringUtils(org.codehaus.plexus.util.StringUtils) VelocityException(org.apache.velocity.exception.VelocityException) IOException(java.io.IOException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) MavenReportException(org.apache.maven.reporting.MavenReportException)

Example 5 with VelocityException

use of org.apache.velocity.exception.VelocityException in project carbon-apimgt by wso2.

the class ThrottlePolicyTemplateBuilder method getThrottlePolicyForGlobalLevel.

/**
 * Generate policy for global level
 *
 * @param policy policy with level 'global'. Multiple pipelines are not allowed. Can define more than one condition
 *               as set of conditions. all these conditions should be passed as a single pipeline
 * @return the generated execution plan for the policy
 * @throws APITemplateException if failed to generate policy
 */
public String getThrottlePolicyForGlobalLevel(GlobalPolicy policy) throws APITemplateException {
    StringWriter writer = new StringWriter();
    if (log.isDebugEnabled()) {
        log.debug("Generating policy for global level :" + policy.toString());
    }
    try {
        VelocityEngine velocityengine = new VelocityEngine();
        APIUtil.initializeVelocityContext(velocityengine);
        velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
        velocityengine.init();
        Template template = velocityengine.getTemplate(getTemplatePathForGlobal());
        VelocityContext context = new VelocityContext();
        setConstantContext(context);
        context.put("policy", policy);
        if (log.isDebugEnabled()) {
            log.debug("Policy : " + writer.toString());
        }
        template.merge(context, writer);
    } catch (VelocityException e) {
        log.error("Velocity Error", e);
        throw new APITemplateException("Velocity Error", e);
    }
    return writer.toString();
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) VelocityException(org.apache.velocity.exception.VelocityException) APITemplateException(org.wso2.carbon.apimgt.impl.template.APITemplateException) Template(org.apache.velocity.Template)

Aggregations

VelocityException (org.apache.velocity.exception.VelocityException)14 VelocityContext (org.apache.velocity.VelocityContext)8 Template (org.apache.velocity.Template)7 VelocityEngine (org.apache.velocity.app.VelocityEngine)7 IOException (java.io.IOException)6 StringWriter (java.io.StringWriter)6 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)5 APITemplateException (org.wso2.carbon.apimgt.impl.template.APITemplateException)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