Primefaces data exporter - jsf-2

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.

Related

.Net MVC returning a File

I'm working a Controller that will generate/retrieve files. These will optionally set headers.
public IActionResult SampleFileReport()
{
I see the return type is IActionResult (a data contract). I see inside the function I can still set
response.ContentType
Is there a preferred pattern for how to set ContentType in a controller?
I'm thinking it should be part of the DataContract and setting response.contentype is an anti-pattern, however I see examples such as this that utilize it. Returning a file to View/Download in ASP.NET MVC
All you need to do is return File:
public IActionResult SampleFileReport()
{
// do stuff
return File(bytes, mimetype, filename);
}
File also has overloads that accept Stream and string (path and filename to a file on the filesystem) in addition to byte[]. The mimetype is your content type, e.g. application/pdf, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (Excel), etc. The final filename param is optional. If it's provided, a Content-Disposition: attachment header is sent with the response, which prompts the browser to pop a download dialog. Otherwise, the default Content-Disposition: inline is used, and the browser will try to load the returned file directly the browser tab/window, assuming the mime-type is supported for native rendering the browser. If not, then you'll get a download dialog, regardless.
If we are talking about MVC (not .NET Core) then you can change IActionResult to FileContentResult
public FileContentResult SampleFileReport()
{
byte[] fileBytes = GetFileBytes();
return File(fileBytes, MediaTypeNames.Application.Octet, "fileName");
}
Just checked this class still exists. FileContentResult .NET Core

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

Blackberry-not getting soap response xml

I am trying to consume SOAP response xml by passing request xml in a string, using BlackBerry Java plugin for Eclipse. I have been struck on this for the past two days looking for a way to solve it.
I have attached the sample code below.
public String CheckXml()
{
final String requestXml="<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\"><header xmlns=\"http://schemas.cordys.com/General/1.0/\"></header><SOAP:Body><authenticateAgainstOID xmlns=\"http://schemas.cordys.com/OIDAuthentication\"><stringParam>HEMANTS_MUM013</stringParam><stringParam1>TATA2012</stringParam1></authenticateAgainstOID></SOAP:Body></SOAP:Envelope>";
final String HOST_ADDRESS = "http://xyz.com/cordys/com.eibus.web.soap.Gateway.wcp?organization=o=B2C,cn=cordys,cn=cbop,o=tatamotors.com&SAMLart=MDFn+8e5dRDaRMRIwMY7nI84eEccbx+lIiV0VhsOQ7u+SKG6n5+WNB58";
String result="";
try {
HttpConnection url=(HttpConnection)Connector.open(HOST_ADDRESS);
url.setRequestProperty("Content-Type", "text/xml");
url.setRequestMethod(HttpConnection.GET);
OutputStreamWriter writer=new OutputStreamWriter(url.openOutputStream());
writer.write(requestXml);
writer.flush();
writer.close();
StringBuffer buffer1=new StringBuffer();
InputStreamReader reader=new InputStreamReader(url.openInputStream());
StringBuffer buffer=new StringBuffer();
char[] cbuf=new char[2048];
int num;
while (-1 != (num = reader.read(cbuf))) {
buffer.append(cbuf, 0, num);
}
String result1 = buffer.toString();
} catch (Exception e) {
System.out.println(e);
}
return result;
}
I think the main issue that you aren't asking http. getResponseCode(). I think BB doesn't do any interaction until you call it.
I would also be careful with this code on the real devices. Search for correct opening connection on the BlackBerries.
I noticed that you are not including the SoapAction header in the request.
SOAP Web services usually have a fixed URL, and the differents methods are selected with the SoapAction header. You can check the header by opening the WSDL in a browser and inspecting the format for the method you want to invoke.
Once you know which action to select, set it as a regular http header:
url.setRequestProperty("SOAPAction", <your action here>);
Another source of problems in your code is that you are using the old HttpConnection class that requires appending a suffix to the URL depending on the transport type (MDS, BIS, Wi-Fi, etc). You don't need to use this legacy class unless you are targeting OS 4.5 and lower. So have a look at ConnectionFactory class, which is much easier to use. It is available since OS 5.0.

ASP.NET MVC open pdf file in new window

I have a MVC application. I need to open the pdf file when user clicks the open button on the page. The filepath where the pdf is stored is read from the database and it is a file on c:. How do I open it in my html code? I have this code:
Open
but this doesn't open my file. What do I have to do? I need to specify somewhere that it is a pdf??
You will need to provide a path to an action that will receive a filename, resolve the full path, and then stream the file on disk from the server to the client. Clients out in the web, thankfully, cannot read files directly off your server's file system (unless... are you suggesting #Model.CertificatePath is the path to the file on the remote user's machine?).
public ActionResult Download(string fileName)
{
string path = Path.Combine(#"C:\path\to\files", fileName);
return File(path, "application/pdf");
}
Update
If #Model.CertificatePath is the location on the client's actual machine, try:
Open
Note that some browsers may have security settings disallowing you from opening local files.
Try like this in your View
#Html.ActionLink("View", "ViewPDF", new { target = "_blank" })
Now Link will open in new window. You can write the pdf bytes in ViewPDF controller method
You could have the link fire a method such as the one below which will then stream your chosen file to the file download rather than opening the pdf in the broswer.
/// <summary>
/// Forces a file to be displayed to the user for download.
/// </summary>
/// <param name="virtualPath"></param>
/// <param name="fileName"></param>
public static void ForceDownload(string virtualPath, string fileName)
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.AddHeader("content-disposition", "attachment; filename=" + fileName);
response.WriteFile(virtualPath);
response.ContentType = "";
response.End();
}
Well if your getting the path value and the value is in #Model.CertificatePath
this wiil not work
Open
You will need to add this
Open
and make sure you path is relative by adding this ~
for example if your path is /Content/pdfs/CertificatePath.pdf
it would need to look like
~/Content/pdfs/CertificatePath.pdf
This should be the simplest way to make it work.
Hope this helps.
Unfortunately you can't dictate where the PDF will be opened, mainly because you can't guarantee the Adobe Acrobat reader plugin is installed or how it functions.
You could in theory open a new window, and in that new window have a JavaScript function to open the PDF file, but again you can't guarantee it will open in a embedded window without the plugin, the best you can hope for is "best try".

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.

Resources