call birt report from action class - struts2

I am developing a project in Java EE Struts 2 and Hibernate for airline reservations. Now my all work is done and I have to generate a ticket. Instead of generating a simple JSP or HTML ticket, I want to generate a downloadable report (like Crystal Reports in Java). I have my entire ticket info in a session that (as on internet) I can get on BIRT report using script.
I am totally new to BIRT and wanted to know how I can generate a BIRT report or maybe call its execution engine from one of my action classes. Any ready example will be a great help.

I guess you're trying to send PDF ticket to customers. Please create your template and pass parameters using these lines:
ReportAdminServiceRemote birtAdmService = (ReportAdminServiceRemote)MXServer.getMXServer().lookup(“BIRTREPORT”);
byte[] abyte0 = birtAdmService .runReport(userInfo, reportName, appName, parameterData, filename, “pdf”);
Once you have the bytes generated you can do this way:
public String actionDownload() throws Exception{
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Disposition","attachment; filename=\"" + example.pdf+ "\"");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayInputStream bis = new ByteArrayInputStream(abyte0);
inputStream = bis;
return SUCCESS;
}
All the credits goes to authors on these pages:
http://www.maximonews.com/?p=65
http://www.coderanch.com/t/432713/Struts/Struts-Files-DownLoad-Streaming-as

Related

Fetch Thymeleaf Templates from Remote Location

I want to fetch the email Template from GITHUB and use the template in my Thymeleaf configuration to send email. I don't want to save my Template inside my JAR running at PCF. It should be on fly.
I was successful in fetching the HTML file from GITHUB
Now the HTML file is maintained as InputStream
Now the question is how use this Inputstream at TemplateResolver and set my variables and create the String value of the HTML content to send Email ?
You can process a String template like this:
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
Context ctx = new Context();
ctx.setVariable("variable", "value");
String processedTemplate = templateEngine.process("<html><div th:text='${variable}' /></html>", ctx);
System.out.println(processedTemplate);

Primefaces data exporter

I am using p:dataExporter to export the data to client machine. It creates a file in given format based on the data from table mentioned in the tareget method. On export button click file would be exported to client machine.This all goes fine.
Now I want to provide an 'open' button to let open the file with/without downloading the file to client machine. p:dataExporter dont have such property. Does JSF provide such property or any other component recommended?
Here is my code sample,
<p:dataExporter type="#{applicationFilterBean.exportFileType}" target=":appForm:appTable"
fileName="#{applicationFilterBean.exportFileName}" />
Thanks for your suggestion Michele, I have created my customExport class. The only change needed was to change responseHeader to Content-Disposition-inline,
response.setHeader("Content-disposition", "inline;filename="+ fileName + ".pdf");
This is working absolutely fine.
no it is not possible because content-disposition is hardcode.
for example, look through org.primefaces.component.export.PDFExporter source code:
protected void writePDFToResponse(ExternalContext externalContext, ByteArrayOutputStream baos, String fileName) throws IOException, DocumentException {
externalContext.setResponseContentType("application/pdf");
externalContext.setResponseHeader("Expires", "0");
externalContext.setResponseHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
externalContext.setResponseHeader("Pragma", "public");
externalContext.setResponseHeader("Content-disposition", "attachment;filename="+ fileName + ".pdf");
externalContext.setResponseContentLength(baos.size());
externalContext.addResponseCookie(Constants.DOWNLOAD_COOKIE, "true", Collections.<String, Object>emptyMap());
OutputStream out = externalContext.getResponseOutputStream();
baos.writeTo(out);
externalContext.responseFlushBuffer();
}
maybe some other library provide this feature, otherwise you should develop your own DataExporter.

Download link encodedKeyStore

I've been generated a PKCS12 keystore through a API, but the return of the process is a KeyStore object. I need to send it, directly to the browser to be downloaded when the client send the requisition.
How can I do that?
I'm using java and jboss 5AS.
You can use KeyStore#store() to write it out to an OutputStream.
keyStore.store(outputStream, password);
That's basically it. The OutputStream could be the one of the HTTP response. For a generic kickoff example of how to provide a file download in JSF wherein you need to integrate this line, head to this answer: How to provide a file download from a JSF backing bean? Use a content type of application/x-pkcs12.
Here is the code:
public void cadastrar () throws Exception
{
byte[] encodedKeyStore = controlador.cadastrar(certificadoModel);
java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12");
keyStore.load(new ByteArrayInputStream(encodedKeyStore), certificadoModel.getPassword().toCharArray());
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset();
ec.setResponseContentType("application/x-pkcs12");
//ec.setResponseContentLength(contentLength);
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + certificadoModel.getUsername() + ".p12" + "\"");
OutputStream output = ec.getResponseOutputStream();
keyStore.store(output, certificadoModel.getPassword().toCharArray());
fc.responseComplete();
}

XSSFWorkbook#write() results in empty response

I'm trying to get my JSF to export a spreadsheet for download. I'm using Apache's POI library for the Excel document writing. I get the following error in an alert box when the code runs:
emptyResponse: An empty response was received from the server.
The method generating the spreadsheet and exporting to the OutputStream is below (I have renamed classes, methods etc for simplicity sake).
private void generateSpreadsheet(Object object) throws Exception {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
String fileName = object.getProperty() + ".xlsx";
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName +"\"");
OutputStream os = response.getOutputStream();
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet 1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("test");
wb.write(os);
os.flush();
os.close();
FacesContext.getCurrentInstance().responseComplete();
}
Any advice much appreciated, thanks.
If it makes a difference, I'm using AJAX (<f:ajax> tag) on the form submit that calls this method.
It makes definitely difference. You can not download files by Ajax. Ajax is executed by JavaScript code. But JavaScript has no facilities to force a Save As dialogue or to execute the platform default application associated with the file's mime type (thankfully; that would have been a major security/intrusion problem). Further, the JSF Ajax API expects a XML response in a specified structure conform the JSF specs. When you send a complete Excel file instead, the whole Ajax response would be ignored as ununderstandable garbage by the JSF Ajax API.
You need to send a normal synchronous request. Remove the <f:ajax> tag from the command link/button. The current page will remain the same anyway if the download is sent as an attachment.

Why doesn't my PDF document render/download in ASP.NET MVC2?

I have an ASP.NET MVC2 application in development and I am having problems rendering a .pdf file from our production server.
On my Visual Studio 2010 integrated development server everything works fine, but after I publish the application to the production server, it breaks. It does not throw any exceptions or errors of any kind, it simply does not show the file.
Here's my function for displaying the PDF document:
public static void PrintExt(byte[] FileToShow, String TempFileName,
String Extension)
{
String ReportPath = Path.GetTempFileName() + '.' + Extension;
BinaryWriter bwriter =
new BinaryWriter(System.IO.File.Open(ReportPath, FileMode.Create));
bwriter.Write(FileToShow);
bwriter.Close();
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = ReportPath;
p.StartInfo.UseShellExecute = true;
p.Start();
}
My production server is running Windows Server 2008 and IIS 7.
You cannot expect opening the default program associated with PDF file browsing on the server. Try returning the file into the response stream which will effectively open it on the client machine:
public ActionResult ShowPdf()
{
byte[] fileToShow = FetchPdfFile();
return File(fileToShow, "application/pdf", "report.pdf");
}
And now navigate to /somecontroller/showPdf. If you want the PDF opening inside the browser instead of showing the download dialog you may try adding the following to the controller action before returning:
Response.AddHeader("Content-Disposition", "attachment; filename=report.pdf");
i suggest you use ASP.NET MVC FileResult Class to display the PDF.
see http://msdn.microsoft.com/en-us/library/system.web.mvc.fileresult.aspx
your code open`s the PDF on the webserver.
Here's how I did it.
public ActionResult PrintPDF(byte[] FileToShow, String TempFileName, String Extension)
{
String ReportPath = Path.GetTempFileName() + '.' + Extension;
BinaryWriter bwriter = new BinaryWriter(System.IO.File.Open(ReportPath, FileMode.Create));
bwriter.Write(FileToShow);
bwriter.Close();
return base.File(FileToShow, "application/pdf");
}
Thank you all for your efforts. Solution I used is the most similar to the Darin's one (almost the same, but his is prettier :D), so I will accept his solution.
Vote up for all of you folks (both for answers and comments)
Thanks

Resources