How to get the uploaded file path in JSF - jsf

I'm importing Excel document for reading and displaying the content in the UI. I need to know how to get the path of the file uploaded using browse in order to read the content of the excel file.

I need to know how to get the path of the file uploaded using browse in order to read the content of the excel file.
There's a major thinking mistake here.
Imagine that I am the client who want to upload the file and that you are the server who need to get the file's contents. I give you the path c:\path\to\foo.xls as sole information. How would you as being the server ever get its contents? Do you have an open TCP/IP connection to my local hard disk file system? Really? Is everyone else's local disk file system with all that sensitive information really so easily accessible by Internet?
That isn't how uploading files works. This would only ever work if the server runs at physically the same machine as the client, so that you can just use FileInputStream with that path (which would only occur in local development environment).
You should instead be interested in the sole file contents which the client has sent to you along with the HTTP request body. In HTML terms, you can use <input type="file"> for this. But until the upcoming JSF 2.2 there is no equivalent standard JSF <h:xxx> component for this. You need to look for JSF component libraries offering a component for this. In your case, with RichFaces (as tagged in your question), you can use <rich:fileUpload> for this. It's unclear which RichFaces version you're using, but for RF 3.3.3 you can find a complete example in the 3.3.3 showcase site and for RF 4.0 in the 4.0 showcase site.
Whatever way you choose, you should in your JSF managed bean ultimately end up with a byte[] or an InputStream representing the file contents. Then you've all the freedom to store it wherever you want on the server's local disk file system using for example FileOutputStream. You can even also just feed it directly to whatever Excel API you're using, most of them have just a method taking an InputStream or byte[].

you better take a look at this article. The solution that uses Tomahawk 2.0 ( http://myfaces.apache.org/tomahawk-project/tomahawk20/index.html ) by BalusC is great
JSF 2.0 File upload
Everything you need is there

String fileName = FilenameUtils.getName(uploadedFile.getName());
byte[] bytes = uploadedFile.getBytes();
FileOutputStream outputStream = null;
try {
String filePath = System.getProperty("java.io.tmpdir") + "" + fileName;
outputStream = new FileOutputStream(new File(filePath));
outputStream.write(bytes);
outputStream.close();
readExcelFile(filePath);
} catch (Exception ex) {
}
In the above code Iam uploading the file using tomahawk after uploading storing the file in a temporary location.And from there i will be reading using poi.
public static void readExcelFile(String fileName)
{
try{
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(myFileSystem);
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
Iterator rowIter = sheet.rowIterator();
for(Row row : sheet) {
//u can read the file contents by iterating.
}
} catch (Exception ex) {
}
}

Related

Sending excel data to Tally

I have a macro enabled worksheet which saves the data as XML format.
I have prepared the excel template which saves the out put file in XML format. Then i import the XML file in Tally manually with import data option.
Now i am looking for a solution which would make the process automatic i.e. once i save the file as XML format, immediately the data should get imported in Tally without any manual process.
Hope i explained my query properly.
Thanks in Advance.
Best Regards,
You can use Requests to send the xml to tally. Here's a C# example, you can translate it to your preferred language -
private static string Connect(string host, string request)
{
string response = "";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(host);
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = (long)request.Length;
StreamWriter writer = new StreamWriter(httpWebRequest.GetRequestStream());
writer.Write(request);
writer.Close();
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream receiveStream = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
response = reader.ReadToEnd();
reader.Close();
httpResponse.Close();
}
Where host is your tally server ip - usually http://localhost:9000/ and request is your xml - load your xml file as a string.
Ensure your ODBC Server is enabled on Tally. Set your Tally to act as both server and client & choose your port - https://help.tallysolutions.com/article/Tally.ERP9/sync/configuring_client_server.htm
You'll get a response from tally which will have either of the following XML tags -
<CREATED>1</CREATED>
or
<ERROR> // some error </ERROR>
Tally Intergration documentation isn't great but it can still give you an idea - http://mirror.tallysolutions.com/tallyweb/tally/td9/Tally.ERP9_Integration_Capabilities.pdf
Lastly, for automatic upload to tally when the file is created - you can use FileSystemWatcher (C#) or Watchdog library to watch for when the file is created/modified within your specified folder. There is plenty of help in regards to this on stackoverflow.

Send full client side file path to server side using p:fileUpload

I'm using:
PrimeFaces 5.0
GlassFish 4.1
Netbeans 8.0.2
My case: I have an intranet web application where I'd like to let the client browse the intranet network disk file system and send the full client side file path to the server side. In other words, I do not need the file contents, but only the full file path, as it is in the intranet network.
I tried using <p:fileUpload> for this:
public void handleFileUpload(FileUploadEvent event) throws IOException {
UploadedFile uploadedFile = event.getFile();
InputStream inputStream = uploadedFile.getInputstream();
File file = new File(uploadedFile.getFileName());
System.out.println(file.getAbsolutePath());
String realPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");
System.out.println(realPath);
}
The file.getAbsolutePath() prints the following:
C:\Users\XXX\AppData\Roaming\NetBeans\8.0.2\config\GF_4.1\domain1\config\file.txt
And, the realPath prints the following:
C:\Users\XXX\Documents\NetBeansProjects\PROJECT\dist\gfdeploy\PROJECT\PROJECT-war_war\
However, I'm expecting to see
\\MACHINE\Documents\file.txt
How can I achieve this?
You're basically looking in the wrong direction for the solution. And, you're looking at JSF/PrimeFaces in a wrong way. JSF is in the context of this question just a HTML code generator.
HTML does not support sending full client side file path to the server side. True, older Internet Explorer versions had the awkward security bug that the full client side file path was sent along the file name. But, this is not mandated by HTML. The sole purpose of <input type="file"> is to send the file content from client to server, which you're supposed to read via getInputStream() and save on a fixed location yourself. The filename is here just additional metadata. This is usually never used as-is to save the file in the server, to avoid overwrites by other uploads with coincidentally the same filename. The file name is at most used as prefix of the final file name in the server side, or only remembered in order to be redisplayed in "Save As" during a download. But that's it.
All your attempts failed because here,
File file = new File(uploadedFile.getFileName());
System.out.println(file.getAbsolutePath());
.. the getFileName() only returns the file name, not the file path. The new File(...) constructor will interpret the file name relative to the "current working directory", i.e. the directory which was open at the moment the JVM (in your case, the server), was started. Basically, you're attempting to locate a non-existing file. The actual file is stored elsewhere, usually in the OS-managed temporary file location beyond your control. However, this is also not what you're looking for.
And here,
String realPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");
System.out.println(realPath);
.. the getRealPath() only converts the webcontent-relative path to absolute disk file system path. In other words, it gives you the path to the deploy folder where all contents of the expanded WAR file are stored. Usually it are the XHTML/JS/CSS files and such. This is also definitely not what you're looking for. Moreover, there is no single sensible real world use case for getRealPath(). You should absolutely avoid using it.
You need to look for the solution in a different direction than HTML. You need a client side application capable of grabbing the full client side file path and then sending it to the server side. HTML can't do it (even not HTML5). CSS can't do it. JS can't do it. But Java can do it. You can use Swing JFileChooser to browse and pick the actual File. You only need to execute it in the client side instead of the server side. You can use an Applet for this which you in turn can easily embed in any webpage, even a JSF page; you know, it's just a HTML code generator.
Basically:
In applet, grab full file path via JFileChooser.
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
String selectedFileAbsolutePath = selectedFile.getAbsolutePath();
// ...
} else {
// User pressed cancel.
}
Additional advantage is, you can use FileSystemView to restrict it to certain (network) drives or folders, so that the enduser won't accidentally select completely irrelevant drives/folders.
Send the full file path as query parameter via URLConnection to server side.
String url = "/someServletURL?selectedFileAbsolutePath=" + URLDecoder.decode(selectedFileAbsolutePath, "UTF-8");
URLConnection connection = new URL(getCodeBase(), url).openConnection();
connection.setRequestProperty("Cookie", "JSESSIONID=" + getParameter("sessionId"));
InputStream response = connection.getInputStream();
// ...
Read it in a servlet.
#WebServlet("/someServletURL")
public class SomeServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse resposne) throws ServletException, IOException {
String selectedFileAbsolutePath = request.getParameter("selectedFileAbsolutePath");
// ...
}
}
Don't forget to pass session ID as applet parameter when embedding the applet in JSF page.
<applet ...>
<param name="sessionId" value="#{session.id}" />
</applet>
This way the servlet will have access to exactly the same HTTP session as the JSF page, and then you can share/communicate data between them.

Store PDF for a limited time on app server and make it available for download

Hei there, I'm using PrimeFaces 5/JSF 2 and tomcat!
Can someone show me or give me an idea on how to store pdfs for a limited time on an application server(I'm using tomcat) and then download it (if that's what the user requests). This functionality relates to invoices so I can't use the dataExporter.
To be more specific, I pretty much implemented this but I don't feel so sure about it. One big question is... where do I store my generated files? I've browsed around and people said that it's not ok to save the files in the webApp or in the tomcat directory. What other solutiuon do I have?
Make use of File#createTempFile() facility. The servletcontainer-managed temporary folder is available as application scoped attribute with ServletContext.TEMPDIR as key.
String tempDir = (String) externalContext.getApplicationMap().get(ServletContext.TEMPDIR);
File tempPdfFile = File.createTempFile("generated-", ".pdf", tempDir);
// Write to it.
Then just pass the autogenerated file name around to the one responsible for serving it. E.g.
String tempPdfFileName = tempPdfFile.getName();
// ...
Finally, once the one responsible for serving it is called with the file name as parameter, for example a simple servlet, then just stream it as follows:
String tempDir = (String) getServletContext().getAttribute(ServletContext.TEMPDIR);
File tempPdfFile = new File(tempDir, tempPdfFileName);
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Length", String.valueOf(tempPdfFile.length()));
response.setHeader("Content-Disposition", "inline; filename=\"generated.pdf\"");
Files.copy(tempPdfFile.toPath(), response.getOutputStream());
See also:
How to save generated file temporarily in servlet based web application
Recommended way to save uploaded files in a servlet application
Your question is vague, but if my understanding is good:
First if you want to store the PDF for a limited time you can create a job that clean you PDFs every day or week or whatever you need.
For the download side, you can use <p:fileDownload> (http://www.primefaces.org/showcase/ui/file/download.xhtml) to download any file from the application server.

Fortify Path Manipulation error

Fority Scan reported "Path Manipulation" security issues in following snippet
String filePath = getFilePath(fileLocation, fileName);
final File file = new File(filePath);
LOGGER.info("Saving report at : " + filePath);
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
fileWriter.write(fileContent);
so i am checking for blacklisted characters in fileLocation and throwing exception, still the Fortify is throwing the exception.
try {
String filePath = getFilePath(fileLocation, fileName);
if (isSecurePath(filePath)) {
final File file = new File(filePath);
LOGGER.info("Saving report at : " + filePath);
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
fileWriter.write(fileContent);
} else {
throw new Exception("Security Issue. File Path has blacklisted characters");
}
} catch (final Exception e) {
LOGGER.error("Unable to prepare mail attachment : ", e);
message = "Mail cannot be send, Unable to prepare mail attachment";
}
private boolean isSecurePath(String filePath) {
String[] blackListChars = {".."};
return (StringUtils.indexOfAny(filePath, blackListChars)< 0);
}
should i ignore the scan report or what would be the correct fix for this?
Firstly SCA is a static analysis tool, so can't check your custom validation to determine whether it works correctly or not, as this is something a dynamic tool such as WebInspect is designed to do.
Secondly, blacklisting is a poor way of securing anything, whitelisting is the far more secure method and the fact you're mentioning blacklisting validation to stdout would entice an attacker. This is because you have to account for every single possible way of being attacked, including ways that may not have been discovered yet, so could easily become out of date before the software is even released.
Thirdly, this definitely wouldn't suffice against stopping path manipulation since you're only accounting for people looking for relative paths and more specifically relative paths above the current directory.
There's no way you have of detecting if somebody specifies a full path, or if somebody goes to a directory that's a symbolic link to a separate directory altogether, along with a couple of other possible alternative attacks.
Ideally you should follow the recommendations shown by SCA and have a very specific allowed paths & filenames. Where this isn't possible, use a whitelisting technique to specify the only characters that are allowed, and then validate to specify that it's not for example a SMB share or a full path specified. If it doesn't validate according to the specification of what users should be specifying, reject it.
Doing this will get rid of the issue itself, but SCA will likely still show the issue in the results (again due to the differences between static vs dynamic analysis). This can be worked around by auditing it as such or creating a custom cleanse rule for the function that validates the issue.

How to save Excel file to local drive from browser

I've got an XPage that creates an Excel file using server-side javascript (thank to Russ Maher). I know how to save it to the C: drive if I'm running the XPage locally in a browser, but don't know how to save it to the user's machine when it's running on the server without first saving it to the server. The following code is used to save it from the server's perspective.
var fileOut = new java.io.FileOutputStream(directory+fileName);
xl.write(fileOut);
fileOut.close();
Any ideas how I can direct that to the user's drive?
Instead of writing the Excel workbook to a FileOutputStream, you should write it to a ByteArrayOutputStream:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
xl.write(outputStream);
You probably need to use an XAgent to create the output and then link to the XAgent from your XPage. Maybe this blog entry by Declan Lynch combined with this answer on how to do it in a servlet can guide you in the right direction.
Paul Calhoun sent me some sample code that I massaged to get it to produce the spreadsheet that I wanted. I don't know what it was that he'd done that I hadn't, but, for now, I think this is the heart of the solution, just harnessing an OutputStream instead of either a FileOutputStream or ByteArrayOutputStream.
// The Faces Context global object provides access to the servlet environment via the external content
var extCont = facesContext.getExternalContext();
// The servlet's response object provides control to the response object
var pageResponse = extCont.getResponse();
//Get the output stream to stream binary data
var pageOutput = pageResponse.getOutputStream();
// Set the content type and headers
pageResponse.setContentType("application/x-ms-excel");
pageResponse.setHeader("Cache-Control", "no-cache");
pageResponse.setHeader("Content-Disposition","inline; filename=" + fileName);
//Write the output, flush the buffer and close the stream
wb.write(pageOutput);
pageOutput.flush();
pageOutput.close();
// Terminate the request processing lifecycle.
facesContext.responseComplete();
I will gladly provide help if someone else encounters this issue and, hopefully, by the time someone asks, I will understand more of what was different that worked....

Resources