I'm trying to interrupt a file upload which doesn't seem possible. It seems that nothing gets executed beyond elem.sendKeys("filename.txt") until the entire file is uploaded. Further, none of the buttons are clickable although available when checked via Firebug or testing manually.
Automating the file upload and the interrupt by clicking a cancel file upload button (which is clickable when doing the test manually) leads to a test failure with the following exception: ElementNotVisibleException: Element is not currently visible and so may not be interacted with.
Is there any way I can enforce the interrupt? are there any other means that aids doing the same exact thing?. I'm using Firefox for this test.
HTML:
<div style="padding-left: 40px;">
<input id="upload" type="file" multiple="" label="File" name="upload[]" size="50">
</div>
Java:
WebElement elem = driver.findElement(By.id("upload"));
elem.sendKeys("filename.txt");
driver.navigate().refresh();
System.out.println("hi");
I have failed to see a point in doing that, but here we go:
I believe u can't stop the elem.sendKeys() method in Selenium(which does the actual upload).
Using it on a input text to set a string is the same as actually uploading a file. It's just Selenium trying to set some values on your input.
One way around would be clicking on a cancel upload button you have implemented.
Since you have tried that, this exception ElementNotVisibleException: Element is not currently visible and so may not be interacted with means exactly the that element exists (Selenium have found it on the DOM) but its not visible (the element has some properties like overflow: hidden display:none etc)
My best guess is that you should work that out and try clicking your button that implements an action of stopping the upload.
My main goal: When i click the link, a new browser window should be opened and displays the content of entire log file. And the window should not have an address bar and navigation buttons (Back, Forward).
Is there any approach to do this in Spring-MVC project?
Here is what i am doing now:
When i click the link, the controller will be called with a parameter logName.
Now the controller have access to get any kind of details of the log file like content, path, etc... I am setting all these details to an object and sending back to JSP.
Here i am not sure how to open a new window and display the content of the log file in that window.
Please suggest me an approach on this!!
It would be very helpful for me if you can share me with some examples...
Spring or JSP have nothing to do with it, the only way to force user's browser to open a link in a new tab is to use client-side Javascript. window.open() allows configuring the popup to hide certain interface elements (see all options in the documentation)
Your code would look something like:
<input type="button" value="Show Log" onclick="showLog(logName)">
function showLog(logName) {
var url = "/path-to-your-controller.html?logName=" + logName;
window.open(url, "LogPage", "toolbar=no,location=no,menubar=no");
}
However, I don't think using a customised browser popup is a good solution; it's been disappearing from the web for a reason. It would be more elegant to fetch raw data using AJAX and display it in a JS popup: it wouldn't interfere with user's page navigation (you tagged the question with jQuery, you could use jQuery UI for that).
What is more, I wouldn't be surprised if window.open wasn't supported by all browsers in the same way† - something to keep in mind if you're targeting a wider audience.
† seems that Chrome ignores location=no, for instance
What I need to do is browse to a webpage, login, then browse to another webpage on that site that requires you to be logged in, so it needs to save cookies. After that, I need to click an element on that page, in which I would fill out the form and get the message that the webpage returns to me. The reason I need to actually go to the page and click the button as suppose to just navigating directly to the link is because the you are assigned a session ID every time you log in and click the link, and its always different. The button looks like this, its not a normal href link:
<span id=":tv" idlink="" class="sA" tabindex="0" role="link">Next</span>
Anyway, what would be the easiest way to do this? Thanks.
Update:
After trying HTMLunit, and other headless browser libraries, it doesnt seem that its happening using anything "headless." Another thing that I recently found out about this page is that that all the HTML is in some weird format... Its all inside a script tag. Here is a sample.
"?ui\x3d2\x26view\x3dss\x26mset\x3dmain\x26ver\x3d-68igm85d1771\x26am\x3d!Zsl-0RZ-XLv0BO3aNKsL0sgMg3nH10t5WrPgJSU8CYS-KNWlyrLmiW3HvC5ykER_n_5dDw\x26fri"],"http://example.com/?ctx\x3d%67mail\x26hl\x3den",,0,"Gmail","Gmail",[["us","c130f0854ca2c2bb",[["n"],["m","New features!"],["u"],["k","0"],["p","1000:500000,10,200000,5,100000,3,75000,2,0,1"],["h","https://survey.googleratings.com/wix/p1679258.aspx?l\x3d1033"],["at","query,5,contacts,5,adv,5,cf,5,default,20"],["v","https://www.youtube.com/embed/Ra8HG6MkOXY?showinfo\x3d0"],
When I do inspect element on the button, the HTML code that I posted above for the button comes up, but not when doing view source. Basically, what I am going to need to do is use some sort of GUI and have the user navigate to the link and then have the program fill out the info. Does anyone know how I can do this? Thanks.
Have a look at the 5 Minute Getting Started Guide for Selenium: http://code.google.com/p/selenium/wiki/GettingStarted
On the login page, look at the form's HTML to see the url it posts to and the url parameters. Then request that url with the same parameters filled in with correct info, and make sure to save all the cookie headers to send to the second page. Then use an html parser to find your link. There are several html parsers available on sourceforge, and you could even try java's built in xml parsers, though if the site has even a tiny html mistake they will glitch.
EDIT didn't notice the fact that it is not a normal link. In that case you will need to look at the site's javascript to see where the link leads. If the link requires javascript to run, it gets more complicated. Java is not able to execute browser javascript, but I found a library called DJ native swing which includes a web browser class that you can add to jframes. It uses your native browser to render, and to run javascript.
This should be possible in Selenium as others have noted.
I have used Selenium to login then crawl a site and discover every permuation of values for every form on the site (30+ forms). These values are later used to fill and submit the form with a specific perumation of values. This site was very JS/jQuery heavy and I used Selenium's built-in support of javascript executor, css selectors, and XPath to accomplish this.
I implemented HtmlUnit and HttpUnit as faster alternatives, but found they were not as reliable as Selenium given the JS semantics of the site I was crawling.
It's hard to give you code on how to accomplish it because your Selenium implementation will be quite page-specific and I can't look at the page you're coding against to figure out what's going on with that button script junk. However, I have include some possibly relevant selenium code (Java) snippets:
Element element = driver.findElements(By.id(value)); //find element on page
List<Element> buttons = parent.findElements(By.xpath("./tr/td/button")); //find child element
button.click();
element.submit() //submit enclosing form
element.sendKeys(text); //enter text in an input
String elementText = (String) ((JavascriptExecutor) driver).executeScript("return arguments[0].innerText || arguments[0].textContent", element); //interact with a selenium element via JS
If you are coding similar functions on different pages, then PageObjects behind interfaces can help.
The link Anew posted is a good starting point and good ol' StackOverflow has answers to just about any Selenium problem ever.
Instead of trying to browse around programmatically, try executing the login request and save the cookies then set those in the next request to the form post.
HTMLUnit is pretty bad at processing JavaScript, the Rhino JS library produces often errors (actually no errors is much the exception). I would advise to use Selenium, which is basically a framework to control headless browsers (chrome, firefox based).
For your question, the following code would do the work
selenium.open(myurl);
selenium.click("id=:tv");
You then have to wait for the page to load
selenium.waitForPageToLoad(someTime);
I would recommend htmlunit any day. It's a great library.
First, check out their web page(http://htmlunit.sourceforge.net/) to get htmlunit up and running. Make sure you use the latest snapshot(2.12 when writing this)
Try these settings to ignore pretty much any obstacle:
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_17);
webClient.getOptions().setRedirectEnabled(true);
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getCookieManager().setCookiesEnabled(true);
Then when fetching your page, make sure you wait for background Javascript before doing anything with the page, like posting a login form:
//Get Page
HtmlPage page1 = webClient.getPage("https://login-url/");
//Wait for background Javascript
webClient.waitForBackgroundJavaScript(10000);
//Get first form on page
HtmlForm form = page1.getForms().get(0);
//Get login input fields using input field name
HtmlTextInput userName = form.getInputByName("UserName");
HtmlPasswordInput password = form.getInputByName("Password");
//Set input values
userName.setValueAttribute("MyUserName");
password.setValueAttribute("MyPassword");
//Find the first button in form using name, id or xpath
HtmlElement button = (HtmlElement) form.getFirstByXPath("//button");
//Post by clicking the button and cast the result, login arrival url, to a new page and repeat what you did with page1 or something else :)
HtmlPage page2 = (HtmlPage) button.click();
//Profit
System.out.println(page2.asXml());
I hope this basic example will help you!
I have a Gwt application and use a FileUpload to allow users to upload files.
Only certain types of files will be accepted and I have validation to check the file types once the user has selected it for uploading but I want to know if there is a way to only show files with certain extensions in the upload dialog box.
E.g. If the user has to upload a .doc file then I only want them to be able to see folders and .doc's, not All file types.
Using Zasz's answer and GWT Element it is possible to have an initial filter applied to the dialog box although it's not bulletproof...
myFileUpload.getElement().setAttribute("accept", ".txt");
At least this worked for me in a learning project. 'accept' has other formats too.
The nearest I can come up with is using this
<input type="file" accept="image/jpg,image/gif">
together with :
<form action="pat/to/action" enctype="multipart/form-data" method="post">
though it does no validations or makes any any changes to the open file dialog itself.
A better option will be to let the user select whatever file and when onClick() use a javascript function to check extension, and a neat little square area below the file upload control that gives the user feedback about the validity of the file he selected.
As per my knowledge
There is no programmatical way to only show files with certain extensions in the upload dialog box.
You need to put validations on selected file
You can create a comma separated string of mime types you want to support (below one is for xls, xlsx etc )
String mimeList = "application/vnd.ms-excel,application/msexcel,application/"
+ "x-msexcel,application/x-ms-excel,application/vnd.ms-excel,application/"
+ "x-excel,application/x-dos_ms_excel,application/xls,application/"
+ "vnd.openxmlformats-officedocument.spreadsheetml.sheet";
myFileUploader.setAcceptedTypes(mimeList);
Please note that there's no guarantee that this will work in all
browsers.
I have tested with Google chrome only and it works!
The W3C spec says only that this "provides the user agent
with a hint of file types to accept". How it does that is up to the
browser, and the browser is free to give the user the option to select
any file, notwithstanding your list of acceptable MIME types. So
you're still going to want to validate the file when the user clicks
the submit button or at the server side.
I need to know if there is a way in java/servlet to make documents(doc,pdf) stored in database available for download to users in requested way(please see below),
for example there is a web page and the link for document in it
right now it is done this way:
if the user clicks that link than a new blank window opens and there the download dialog box is shown and the user is able to download the document but that blank window stays open
and the user have to close it manually
but wish to do it this way:
If the User clicks that link than directly staying on that page a download dialog box should show up asking them to save the file
a servlet url handles the download of the document which is responsible for extracting the doc form database and makes available for download to users
thank you for your time and effort
You need to add following headers in your servlet to make it a downloadable content so browsers don't try to display it,
String value = "attachment;filename=\"" + URLEncoder.encode(filename, "UTF-8") +'"';
response.setHeader("Content-Disposition", value);
response.setHeader("Content-Transfer-Encoding", "binary");
The filename is proposed filename and user can change it.
I wonder if your link html doesn't have something like:
<a href="/foo" **target="_blank"** ....>download</href>
Otherwise, it should work as you want.
This is a bug in IE which depends on several things, the content type is one of them. We had the same problem a few years ago but I don't remember the correct solution anymore, only that we struggled with this for quite some time. Try this:
Use the correct content type (application/pdf)
If that doesn't work, use a wrong file type (like application/octet-stream) which should tell IE to leave the file alone. You may have problems with the file extension, though.
Send or don't send the correct file size
Check which chunking mode you're using.
One of these things made IE behave. Good luck.
You need to remove target="_blank" from your <a> element.
Edit: as per your comments: you need to set Content-Disposition header to attachment. You can find here examples of a simple fileservlet and an advanced fileservlet to get some insights.