Uploading files using selenium java - java

So I am trying to upload a file using selenium and I know you can do this using
driver.findElement(By.id("myfile")).sendKeys("/filepath");
explained here: http://saucelabs.com/resources/selenium-file-upload
The issue is that the input tag Im sending it to is invisible and throw an ElementNotVisibleException
for this tag:
<input id ="myfile" class="ussr-component-file-uploader-target-file ussr-component-file-uploader-file ussr-helper-display-none" type="file" accept="video/*">
since the type is not hidden not sure how I would use the JavascriptExecuter to make it visible

You can remove the ussr-helper-display-none class from the element.
If the page uses jQuery, this would be easy:
$("#myfile").removeClass("ussr-helper-display-none");
then, invoke your .sendKeys()
If the page doesn't have jQuery, then:
document.getElementById('myfile').className = "ussr-component-file-uploader-target-file ussr-component-file-uploader-file";

Related

Call JSP function with JSoup

I'm trying to scrape a .jsp webpage with Jsoup. The page I'm trying to scrape is basically a 6 steps form, filling each form takes me to another one but to do so I must click a button that calls a jsp function. I don't know how to do so with jsoup.
So here is a piece of the jsp page I'm trying to scrape.
<img id="nextButtonId" onkeypress="disableButtons(this);onIntroductionFormSubmit()" height="50"
alt="suivant" title="suivant" src="/eAppointment54-etrangers/element/images/buttons/next.gif"
**onclick="disableButtons(this);onIntroductionFormSubmit()"** onmouseover="downNextSrcPicture(this);"
onmouseout="upNextSrcPicture(this);" style="display: block;">
I want to call the onclick methods onclick="disableButtons(this);onIntroductionFormSubmit(). Maybe there is a way I can do this without having to simulate the actual clicking.
Thanks in advance !!!
Jsoup is not a browser engine, it is just an HTML parser/writer. To do such a thing you should do one of these, I recommend the first one:
Implement the method yourself (it's probably just an HTTP call)
Use an automation library like Selenium (no experience)
(Not recommended) Run a full browser environment such as JavaFX WebView and inject code to do the action.

Extracting and processing textarea value form without changing the page

I have a JSP file in which there are two textareas and a submit button all in a form ;
<form action="" method="post">
<textarea name="inConsole" id="in" cols="100" rows="10"> </textarea> <br/>
<input type="submit" name="Send Command"/> <br/>
<textarea name="outConsole" id="out" cols="100" rows="10"></textarea>
</form>
this page is supposed to work like any SQL program. so the user types a command in the first textarea and clicks submit, then the value of textarea will be extracted to a field and a method will take care of the command and return a log (1 row inserted, error:bad syntax etc) which will be displayed in the second textarea.
I know how for example make a login page and send data and redirect user to a new page(new jsp) file if user pass is correct.
what I can't find is how can I do all the things that I said above without going to a new page while using form action.
I have checked other questions that linked the action attribute to a servlet which was confusing for me( the way that a servlet was called). I'm looking forward to use a simple scriptlet for this purpose like the one I used for my login page:
<%
DatabaseLoginTest dbLogTest = new DatabaseLoginTest();
if (dbLogTest.DBLoginChecker(request.getParameter("user"), request.getParameter("pass")) == true){
%>
<p>Login Successful</p>
<% } else { %>
<p>Login Failed</p>
<% } %>
also I'm aware that adding java scripts(not Javascript scripts:) ) to html isn't a good practice(and the reasons for it) but I think this might be easier for a simple program that I'm working on.
p.s: I'm using tomcat and Intellij for developing this web application
and I have made a custom SQL so I only need the code that gives me the textarea value and the one that sets the other one's value
Update: now I know I should use javascript but I don't know how can I send the data extracted by javascript to a java method.
If you want to do this while remaining in the same page, you have to use Javascript. This is because if you want the server to be able to re-render the page, there has to be a page refresh.
You would need to write onClick handler for the submit button and make a Ajax call to your server to a specific URL with the user input. This URL would serve the data needed for the necessary UI changes.
You can use a scriptlet to generate the HTML that would be shown in the webpage but this would only suffice for a simple use-case and it would be a lot simpler if, say, your service returned just the data required to make the UI change and actual UI change is handled by the JS.
Also,I don't think it is a bad practice to embed JS in HTML. Sure, you can optimize this by including a JS source file but that's a separate optimization.

How to map server response retrieved in jsp to an iFrame

I'm using struts2 framework(java/js/html/css combo) for my webapp. I am reading a text file from server and I want to write the response to an iFrame present in the same jsp.
Flow:
(1) On click of a link, I pass the relative URL of the text file to jsp.
(2) When the jsp page loads, the java code in the jsp reads the file from server.
(3) Now this response has to be written to an iFrame present in the same jsp file
Can anyone plz help me in writing such response to an iFrame?
Thanks in advance :)
[code not tested, only a demostration of the concept]
here's some very rough idea as to how to fix your code, they definitly not the best but they should be enough to help you understand the concept.
However I'd still recommend going over the whole concept and maybe come up with a more efficent way to do what you need.
if you insist on using iframe, you need to make use of 2 seperate jsp as W3C says in "Implementing HTML Frames":
Any frame that attempts to assign as its SRC a URL used by any of its ancestors is treated as if it has no SRC URL at all (basically a blank frame).
so you'll need 2 jsp, the first one is basically what you have but the the src of the iframe changed to:
<iframe scrolling="yes" width="80%" height="200" src="second.jsp?content=<%=all%>" name="imgbox" id="imgbox">
and the second one will be something like :
<html><body><%= request.getAttribute("content") %></body></html>
From the code you've shown you forced a "content update" on the iframe by using javascript. The proper/usual way to update an iframe is to provide different input parameter to the second jsp and let it update it for you.
Finally, I'd recommend using JSTL as much as possible instead of scriptlets. It is much cleaner.
What you need to do is set the src attribute of the IFRAME to the jsp url when your link is clicked. Another way to do it is doing something like this:
<iframe src="" name="iframe_a"></iframe>
<p>W3Schools.com</p>
with the correct parameters of course

Selenium WebDriver: Java: Mac OS X: how control file upload automation for CuteWebUI_Uploader_Resource from CuteWebUI for ASP.NET

Selenium-2.37.0
Firefox 24.0 (although have also tried on Chrome)
Mac OS X Mountain Lion 10.8.5
Solutions involving Windows, Windows-specific automation tools/libraries or O/S other than Mac OS X are not acceptable answers
Firstly may I remark that very similar questions have be asked often here on Stackoverflow, I have examined every offered answer, and none of them work for the CuteWebUI_Uploader_Resource AJAX file uploader, as I will illustrate in detail below.
I have an Enterprise Java web application with data and files and wish to automate mapping and uploading a selected subset of the data and files from that web application against (into) a separate ASP.NET web application, which uses the CuteWebUI toolkit and the CuteWebUI_Uploader_Resource from CuteSoft.
At the time of writing the http://cutesoft.net server has been down for some days; Googling gives some CuteSoft forum hits that may help with this problem, but I currently can't access them.
Like many file uploaders, the CuteWebUI AJAX file uploader has a Browse button and an Upload button.
I want to be able to upload directly into the CuteWebUI AJAX file uploader without using that Browse button (and without having to play any tricks using the Browse dialog on Mac OS X, because the files I wish to upload will not be available to a browser on a local filesystem, but instead are stored on a server accessible to the Java web application via Java, although for testing I can have them on a local filesystem, as shown below).
I appreciate that this problem has been answered many times for other file uploaders (see exhaustive list at end of this posting), and the process usually described as a solution for most file uploaders is roughly:
Identify the INPUT field for the file upload path (sometimes hidden) populated by the Browse button. Sometimes one needs to unhide this using a JavascriptExecutor and ensure it is a text field, then use sendKeys to populate it.
Identify the matching SUBMIT Upload button and click() it.
This does not work for the CuteWebUI AJAX file uploader.
The system I am targeting does indeed have an INPUT element that by name would suggest it is used to store the file upload path, but in fact when I try it by hand (and examine it using Firebug and Selenium IDE) its value is not populated at all, and instead a completely new temporary table of uploadable files appears.
The following HTML shows the situation before any file browse or upload has been attempted. I have omitted some style markup and some irrelevant values:
<script src="/CuteWebUI_Uploader_Resource.axd?type=script&_ver=" type="text/javascript"></script>
<input
type="hidden"
autocomplete="off"
name="fileuploader_433"
id="fileuploader_433"
isuploaderfield="1"
value="">
<button>Browse</button>
<span style="display: none;"></span>
<button style="display: none;">Cancel upload</button>
<img
showprogressbar="1"
canceluploadmsg="Cancel upload"
resourcehandler="/CuteWebUI_Uploader_Resource.axd"
uploadtype="Auto"
cancelallmsg="Cancel all Uploads"
uploadurl="/Handlers/UploadHandler.ashx"
insertext="Upload a file"
uploadingmsg="Uploading.." filetoolargemsg=".." maxfileslimitmsg=".."
inserttext="Browse"
numfilesshowcancelall="2147483647"
barstyle="Continuous"
showprogressinfo="0"
multiplefilesupload="0"
windowsdialoglimitmsg=".."
manualstartupload="1"
extensions=""
contextvalue=".."
onerror="this.onload()"
onload="this.style.display="none" ;
if(!window.CuteWebUI_AjaxUploader_Initialize){
var xh=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHttp');
xh.open('GET','/CuteWebUI_Uploader_Resource.axd?type=script&amp;_ver=',false);xh.send('');eval(xh.responseText)}CuteWebUI_AjaxUploader_Initialize(this.id);"
src="/CuteWebUI_Uploader_Resource.axd?type=file&file=continuous.gif"
pageupload="1"
namespace="CuteWebUI"
uniqueid="fileuploader_433"
id="fileuploader_433_Loader_unique"
style="display: none;">
<button
onclick="return submitbutton_click('433')"
class="submitbutton"
name="SubmitButton"
id="SubmitButton">Upload</button>
The following Selenium in Java correctly unhides and populates the fileuploader_433 INPUT field, but on executing the click() on the submit I still get a popup window asserting I have to use the browse button with the message "Please use browse for file upload":
String name_fileuploader = "fileuploader_434";
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementsByName('" + name_fileuploader + "')[0].setAttribute('type', 'text');");
WebElement element_uploader = driver.findElement(By.xpath("//input[#name='" + name_fileuploader + "']"));
element_uploader.clear();
String filepath="/path/to/file.pdf";
element_uploader.sendKeys(filepath);
driver.findElement(By.xpath("(//button[#id='SubmitButton'])[2]")).click();
Firebug confirms that even if you do it by hand, that INPUT field is never used ! Instead, a new file queue table appears:
<script src="/CuteWebUI_Uploader_Resource.axd?type=script&_ver=" type="text/javascript"></script>
<input type="hidden" autocomplete="off" name="fileuploader_434" id="fileuploader_434" isuploaderfield="1" value="">
<button>Browse</button>
<table .. class="AjaxUploaderQueueTable">
<tbody>
<tr class="AjaxUploaderQueueTableRow">
<td>
<img src="/CuteWebUI_Uploader_Resource.axd?type=file&file=circle.png&_ver=null" title="">
</td>
<td>file.pdf</td><td>
<img src="/CuteWebUI_Uploader_Resource.axd?type=file&file=stop.png&_ver=null" title="Remove" style="cursor: pointer;">
</td>
</tr>
</tbody>
</table>
<span style="display: none;"></span>
<button style="display: none;">Cancel upload</button>
<img showprogressbar="1" canceluploadmsg="Cancel upload" ..
resourcehandler="/CuteWebUI_Uploader_Resource.axd" uploadtype="Auto"
cancelallmsg="Cancel all Uploads" uploadurl="/Handlers/UploadHandler.ashx" [snip]
onerror="this.onload()" onload="this.style.display="none" ;
if(!window.CuteWebUI_AjaxUploader_Initialize){var xh=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHttp');xh.open('GET','/CuteWebUI_Uploader_Resource.axd?type=script&amp;_ver=',false);xh.send('');eval(xh.responseText)}CuteWebUI_AjaxUploader_Initialize(this.id);"
src="/CuteWebUI_Uploader_Resource.axd?type=file&file=continuous.gif"
pageupload="1" namespace="CuteWebUI" uniqueid="fileuploader_434"
id="fileuploader_434_Loader_unique" style="display: none;">
<button onclick="return submitbutton_click('434')" class="submitbutton" name="SubmitButton" id="SubmitButton">Upload</button>
Please note that:
the hidden INPUT element is never populated with a file path value !
instead, the string file.pdf without the full file path appears in a new TABLE with class="AjaxUploaderQueueTable" below the Browse button.
That inserted AjaxUploaderQueueTable is clearly only cosmetic; it seems that the filepath selected during the Browse operation is stored server-side. I have searched for the full filepath after selecting with the Browse button using Firebug and it is not present in the page.
I am open - for the sake of testing only - to suggestions that instead involve tricks manipulating the Browse dialog in Mac OS X, but that approach does not meet my eventual requirements, because I can't rely on that approach for the final task of uploading many files from an Enterprise Java web application into the targeted ASP.NET web application. I must side-step the Browse dialog completely.
Background research
All of the following have related questions and answers but none of these solve the problem for the CuteWebUI AJAX file uploader:
How to type some text in hidden field in Selenium WebDriver using Java
How to handle windows file upload using Selenium WebDriver?
How to force Selenium WebDriver to click on element which is not currently visible?
how does selenium webdriver upload files to the browser?
How to deal with file uploading in test automation using selenium or webdriver
https://stackoverflow.com/questions/18886970/selenium-webdriver-upload-file-sendkeys-dont-work
File Upload using Selenium WebDriver and Java
How to handle with uploading files from modal window Selenium WebDriver Java
Handling a popup window using selenium
http://selenium.10932.n7.nabble.com/Handling-browser-pop-up-dialog-to-upload-a-file-td29153.html
This probably relevant forum link from CuteSoft is down:
Jul 24, 2012 - Hi,I'm doing automated testing for my web system using selenium webdriver, the problem is that I can't interact with ajaxuploader component
And a WebDriver forum posting with the INPUT unhide trick: https://groups.google.com/forum/#!topic/webdriver/JAXC_qEbQvI
I've found a solution for this; it comes with some caveats but it works for my situation. Hopefully it will help you too.
The biggest caveat is that I only know that it works with the current version of AjaxUploader as downloaded today. I'd been using an older version that worked differently; I can't specify a version number since CuteSoft seem pathologically inclined to make the version numbers of AjaxUploader almost impossible to figure out. I can't find a version number for the current version OR the older one that I was using.
The other caveat is that it relies on there only being one AjaxUploader control on the page at a time. It appears that AjaxUploader DOES create an <input type='file'> element, but it's left dangling in a div at the top of the <body> tag, without any id or name attribute or anything else to link it to a particular uploader. I'm not sure what AjaxUploader does when more than one of it are present: maybe it creates multiple file inputs and tracks which is which by javascript; maybe it shares one. For my situation I didn't need to solve that part so I didn't try it.
Anyway, the trick is to find the file input as follows:
webDriver.findElements(By.cssSelector("body > div > input[type='file']")).get(0).sendKeys(fileName);
Note that the selector here has nothing to do with the ID or any other characteristics of the particular upload button you're using. It's just "the first file input inside a div directly inside the body tag". That's where AjaxUploader inserts its file input.
There appears to be no need to interact with any of the rest of the UI, including the Browse button: sendKeysing the filename to the right file input causes the upload to begin immediately. (This is an edit; I originally thought that clicking the button was necessary too but it doesn't seem to be)
Note that to make sure the timing of your test works correctly, you probably want to follow this click up with a wait operation that waits until the file has finished uploading (eg by waiting for the HTML that the AjaxUploader inserts after uploading is complete) before proceeding to whatever you want to do next.

Wicket display pdf on Page x? (java)

I would like to add a functionality that shows a pdf on a certain page. I have the pdf as a File in my code. So I cannot get it from my webserver.
I also have the pagenumber.
I've seen that the adobe plugin accepts #page=1 but I don't know how to use this in a web based application.
I also found some tutorials wich display it in an Iframe. But these use :
org.apache.wicket.markup.html.DynamicWebResource
And this doesn't exist anymore.
I found it's replaced by
org.apache.wicket.request.resource.ByteArrayResource
Are there any tutorials/tips on how to do this (Wicket 1.5 or higher)?.
You can use ResourceLink with ByteArrayResource, or you can use any link/button and in its onClick/onSubmit() you can do:
getRequestCycle().scheduleRequestHandlerAfterCurrent(
new ResourceRequestHandler(new ByteArrayResource(...)))
In both cases you may need to set the content-disposition header by overriding org.apache.wicket.request.resource.ByteArrayResource#configureResponse() and calling ResourceResponse#setContentDisposition(INLINE) for it.
When you modify the data from you're object tag pass a pagenumber. This passes the page to the adobe plugin and automatically sets the page. (I have only tested this in chrome 21 and IE9)
<object wicket:id="myFile" data="" border="1" width="100%" height="600px"></object>
WebMarkupContainer wmc = new WebMarkupContainer("myFile");
wmc.add(new AttributeModifier("data", (String) urlFor(rr, null)+"#page="+ pageNmbr));
add(wmc);

Categories