How to make a jsp page download 2 files - java

I have a download.jsp page that when loaded, causes a file to download
using the following code:
String contentDisp = "attachment; filename=file_" + "."+DeptNumber+ ".txt";
response.setContentType("text/plain");
response.setHeader("Content-Disposition", contentDisp);
After this, i do some out.write(....) statements and then in the end out.flush()
which is when the user receives a download file request from the browser.
After that i use:
response.sendRedirect("landingpage.jsp");
To move the user on to the next page.
Now, I want to do the same but instead of one file, i want the page to cause 2 files to be generated for download. I did 2 changes:
1) I changed the beginning of the jsp to check for an attribute, and according to the attribute sent, generate the correct file for download.
String downloadDeptNumber = request.getAttribute("dept")==null ? "1" : request.getAttribute("dept").toString();
and
2) In the end of the page instead of redirecting to the next page, i check if the attribute was 1, i change it to 2 and redirect to the same page. If it wasn't 1, i redirect to the end page (landing page) that i used originally with only 1 download above.
if (downloadDeptNumber.equals("1"))
{
redirectUrl="download.jsp" ;
session.setAttribute("dept", "2");
}
else
{
redirectUrl= "landingpage.jsp";
session.removeAttribute("dept");
}
response.sendRedirect(redirectUrl);
But it seems i can't redirect to the same page i am on currently.
Does anyone have a solution for me ?
Thanks.

option # 1 : separate link
Give 2 separate link to download each file
option #2 : zip file
make a single zip file on server using java API and download
option #3 : Use java script
make a java script function that will open the new tab and download the each file simultaneously
Below code should run to download each file
window.open(
'http://download_file_link',
'_blank' // <- This is what makes it open in a new window.
);

Related

Selenium download button indicates a zip file download by browser in Java

I have a download button without href link in a webpage.
I find it with findExtendedelement and click on it.
After the click a zip file download on the hard drive (i dont know where, and it shouldn't be matter)
I would like to catch this downloaded zip and put it in my project, for example build/reports/tests/temp folder.
Is it possible with selenium?
Update
The HTML looks:
https://i.stack.imgur.com/YnhlH.jpg
I tried this code:
#Test
public void userCanDownloadFile() throws FileNotFoundException, IOException
{
// Folder to store downloads and screenshots to.
reportsFolder = "./src/test/profiles/chrome/downloads/";
open("http://chromedriver.storage.googleapis.com/index.html?path=2.16/");
// Download files
$("a[href='/2.16/chromedriver_win32.zip']").download();
$(By.xpath(".//a[#href='/2.16/chromedriver_mac32.zip']")).download();
// Count files in folder, assert 2
int downloadsCount = new File(reportsFolder+"2.16").listFiles().length;
assertEquals("Should be 2 files but founded " + downloadsCount,
downloadsCount, 2);
// Clean after test
FileUtils.deleteDirectory(new File(reportsFolder+"2.16"));
}
Result:
java.lang.IllegalArgumentException: The element does not have href attribute:
The code is from:
http://selenide-recipes.blogspot.com/2015/08/how-to-download-file-with-selenide.html
I'm looking for something like that, I can handle the downloaded file in my project. (in reportsFolder path)
Unfortunately, this solution doesn't work, because the ExtendedElement (findExtendedElement("span", "class", "download_0") doesn't have an "a href" tag)
Thanks
this xpath: "//span[contains(#class,'download_o')]" should work

how to load the local files relative to the current java file in jwebbrowser

how would I load local files relative to the current java file in JWebbrowser?
I know that I could load my page with navigate("path"); the problem is how to set relative path!
for example my java code is in :
D:\Eclipse_Project\MyProject\src\javaCode\browser.java
and the html file is in :
D:\Eclipse_Project\MyProject\src\pages\html.html
but I don't want to use as follow:
webBrowser.navigate("file:///D:/Eclipse_Project/MyProject/src/pages/html.html");
Edit:
my html file also contains CSS an javaScript.
If it's still actual, I had the same problem, this is the solution:
you need to use webserver like that:
webBrowser = new JWebBrowser();
webBrowser.navigate(WebServer.getDefaultWebServer().getClassPathResourceURL(getClass().getName(), "your_html_content.html"));
Please try the following code:
1. Read html content with scanner.
2. Set html string to webBrowser.
String webContent = new Scanner(new File("src\\pages\\html.html")).useDelimiter("\\Z").next();
webBrowser.setHTMLContent(webContent);

How to save .pdf file that pops up in a browser window with no url?

I am working with .pdf files that are available on my companies' website only. I am not aware of any way to download them and store in one folder.
The link that I click to get the .pdf file has the following source code:
<a href="javascript:propertiesView('documentName')">
As I click on the link, a .pdf file pops up in a new browser window with no url and no source code. I presume that there is no way to manipulate that .pdf directly, then how can I save it then in order to manipulate the .pdfs from a folder?
Thank You
You may have luck by simply telling your browser to always save PDF files to disk (credits to Dirk):
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
If that doesn't work, you are probably able to iterate through all open windows/tabs by using the switchTo() methods. Try something like this to get some insight about your opened windows (credits to Prashant Shukla):
public void getWindows() {
Set<String> windows = driver.getWindowHandles();
for (String window : windows) {
driver.switchTo().window(window);
System.out.println(driver.getTitle());
}
}
A non-selenium solution to download the file would be to use the apache-commons library (creadits to Shengyuan Lu):
org.apache.commons.io.FileUtils.copyURLToFile(URL, File)
But this would require that you know the URL of the window, which you probably are able to fetch with the second approach i mentioned (driver.switchTo()) and driver.getCurrentUrl().
I presume that there is no way to manipulate that .pdf directly
That's correct. With Selenium, you cannot.
how can I save it then in order to manipulate the .pdfs from a folder?
I've actually implemented this exact thing in our regression system where I work.
My first step, was to construct a Url based on what the propertiesView(). method did.
in your case, propertiesView() does some sort of window.open is my guess. So your goal is, to extract that Url that it opens, and use concatenation to construct the url.
Once you've found your Url, the rest is a cakewalk. Just download the url to a folder named /pdfs. See this question for how to do that.
It may even require calling that method to figure it out.. Due to my ignorance of your System Under Test, it's difficult for me to give you a code answer, unless you posted it.
A hint that i'll tell you, is if you are using Selenium 1, use
String url =selenium.getEval("var url = something; url;");
to fetch the url and get it into a java object.
(If using selenium 2, use the JavaScriptExecutor#executeScript)
If you want to save a PDF to your hard drive in IE with selenium, you need to use pywinauto with selenium. I just used this code for PDF files that open up in the browser.
//selenium imports
from pywinauto import application //pywinauto import
//write selenium code to open up pdf in the browser
driver = webdriver.Ie("IEDriverServer.exe", capabilities = caps)
//this could be a get or driver.execute_script() to click a link
driver.get("link to pdf")
//save pdf
app = application.Application()
//get the ie window by the title of the application (assuming only one window is open here)
ie = app.window_(title_re = ".*Internet Explorer.*")
//this line focuses on the pdf that is open in the browser
static = ie.Static
//focus on the pdf so we can access the internal controls
static.SetFocus()
//control + h shows the pdf bar, but you don't really need this step
//for it to work. i just used it as a debug
static.TypeKeys("^H")
//open save file dialog
static.TypeKeys("+^S")
//tricky here because the save file dialog opens up as another app instance
//which is how pywinauto sees it
app2 = application.Application()
//bind to the window by title - name of the dialog
save = app2.window_(title_re = ".*Save As.*")
//this is the name of the property where you type in the filename
//way to be undescriptive microsoft
file_name = save[u'FloatNotifySink']
//type in the file name
save.TypeKeys("hello")
//pause for a second - you don't have to do this
time.sleep(4)
//find and bind the save button
button = save[u'&SaveButton']
//click the save button
button.Click()

Download statistics for a remote file

The issue I am struggling with now is the following. I have a zip archive on a remote server. The eclipse plug-in I have developed downloads this archive using the suggestion from this forum:
//Connect readable channel to the URL
ReadableByteChannel rbc = Channels.newChannel(libraryUrl.openStream());
//Create local file
FileOutputStream fos = new FileOutputStream(libraryZipPath);
//Download the remote archive to the local file
fos.getChannel().transferFrom(rbc, 0, libraryUrl.openConnection().getContentLength());
//Close channel
fos.close();
I have an html file at the server that counts visit statistics for the web-page. The javascript that does counting is as follows:
var data = '&r=' + escape(document.referrer) + '&n=' + escape(navigator.userAgent)
+ '&p=' + escape(navigator.userAgent) + '&g=' + escape(document.location.href);
if (navigator.userAgent.substring(0,1)>'3')
data = data + '&sd=' + screen.colorDepth + '&sw=' + escape(screen.width+'x'+screen.height);
document.write('<a href="http://www.1freecounter.com/stats.php?i=89959" target=\"_blank\">');
document.write('<img alt="Free Counter" border=0 hspace=0 '+'vspace=0 src="http://www.1freecounter.com/counter.php?i=89959' + data + '">');
document.write('</a>');
The question is: Is it somehow possible to use this javascript or html file with it to count the download statistics for the archive file?
You are using a third party webcounter which is embedded as a graphic in your website. When the users browser loads this graphic, the third party server notices the access and increments the counter.
This doesn't work for binary downloads, because when a binary file is downloaded, the webcounter graphic isn't requested.
What you could try is to make your Java program also download the counter graphic when it downloads the binary file. Make sure to pass the URL of the zip archive as Referrer HTTP header to the image download so that the script on the server counts it as access to it. You will have to use the URLConnection class in order to set custom HTTP headers like Referrer.
Thank you for the reply, Philipp!
I have figured out how to make it work in a very simple way. Let us consider a counter in the example above ("http://www.1freecounter.com/stats.php?i=89959"). The counter by that address takes 6 parameters in total:
r - document referrer,
n and p are user agent, which consists of a browser name, OS name, OS ver, browser ver etc.,
g is the location,
sd and sw are the colour depth and the screen size (we can skip these two for a binary file).
Then, we form a string for a counting request. For instance,
String cntURL = "http://www.1freecounter.com/counter.php?i=89959&r="+
URLEncoder.encode("some string for a referrer","UTF-8") + "&n="+
URLEncoder.encode("browser name (OS name OS version) browser version", "UTF-8")+"&p="+
URLEncoder.encode("the same as above", "UTF-8")+"&g=<location string>";
Notice that the parameters are encoded into utf-8 character set. Otherwise, the counter will not count the access properly.
Then, simply using URL class, we create an URL object and open a steam:
URL statsUrl = new URL(cntURL);
statsUrl.openStream();
That is it! There is no need to research what parameters are in http header. It is simply a matter of forming a proper string to which to open a connection.
I have written a simple method that retrieves all info required for the request and have inserted a call to it in a method where I download the file from a server.

getAbsolutePath() like method in UploadedFile(org.apache.myfaces.custom.fileupload.UploadedFile;)

I am currently working on an application, where users are given an option to browse and upload excel file, I am badly stuck to get the absolute path of the file being browsed. As location could be anything (Windows/Linux).
import org.apache.myfaces.custom.fileupload.UploadedFile;
-----
-----
private UploadedFile inpFile;
-----
getters and setters
public UploadedFile getInpFile() {
return inpFile;
}
#Override
public void setInpFile(final UploadedFile inpFile) {
this.inpFile = inpFile;
}
we are using jsf 2.0 for UI development and Tomahawk library for browse button.
Sample code for browse button
t:inputFileUpload id="file" value="#{sampleInterface.inpFile}"
valueChangeListener="#{sampleInterface.inpFile}" />
Sample code for upload button
<t:commandButton action="#{sampleInterface.readExcelFile}" id="upload" value="upload"></t:commandButton>
Logic here
Browse button -> user will select the file by browsing the location
Upload button -> on Clicking upload button, it will trigger a method readExcelFile in SampleInterface.
SampleInterface Implementation File
public void readExcelFile() throws IOException {
System.out.println("File name: " + inpFile.getName());
String prefix = FilenameUtils.getBaseName(inpFile.getName());
String suffix = FilenameUtils.getExtension(inpFile.getName());
...rest of the code
......
}
File name : abc.xls
prefix : abc
suffix: xls
Please help me in getting the full path ( as in c:.....) of the file being browsed, this absolute path would then be passed to excelapachepoi class where it will get parsed and contents would be displayed/stored in ArrayList.
Why do you need the absolute file path? What can you do with this information? Creating a File? Sorry no, that is absolutely not possible if the webserver runs at a physically different machine than the webbrowser. Think once again about it. Even more, a proper webbrowser doesn't send information about the absolute file path back.
You just need to create the File based on the uploaded file's content which the client has already sent.
String prefix = FilenameUtils.getBaseName(inpFile.getName());
String suffix = FilenameUtils.getExtension(inpFile.getName());
File file = File.createTempFile(prefix + "-", "." + suffix, "/path/to/uploads");
InputStream input = inpFile.getInputStream();
OutputStream output = new FileOutputStream(file);
try {
IOUtils.copy(input, output);
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(input);
}
// Now you can use File.
See also:
How to get the file path from HTML input form in Firefox 3
I remember to have some problem with this in the past too. If I am not mistaken, I think you cannot get the full file path when uploading a file. I think the browser won't tell you it for security purposes.

Categories

Resources