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);
}
}
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());
}
}
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);
}
}
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);
}
}
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();
}
Aggregations