How to upload multiple files in selenium for validation? - java

In a folder 5 CSV files and i need to upload one by one for validation purpose but even single file is not uploading i tried so many methods,can anyone suggest any methods, i'm doing in salesforce.
WebElement uploadElement = driver.findElement(By.xpath("//div[#class='cBatchMaster']//input[1]"));
uploadElement.sendKeys("E:\\Automation\\Error Inventory.csv");
above the code is for single file and directly i'm giving the exact file location but i want to upload the files in one folder
Thanks

Below is the solution in C#. A similar approach can be used in Java
Use AutoITX to upload files. You would need to add AutoItX.Dotnet in your nuget package
using AutoIt;
public static void UploadDocument(IWebElement uploadElement, string path)
{
uploadElement.Click();
AutoItX.WinActivate("Open");
string filepath = Path.Combine(System.IO.Path.GetFullPath(#"..\..\"),path);
Thread.Sleep(1000);
AutoItX.Send(filepath);
AutoItX.Send("{ENTER}");
}
You should be able to upload multiple files from AutoIT once you are able to upload the single file

Related

Groovy: Save gform input type file to the assets pipeline (or similar)

(Sorry if this is simple; this is my first post)
Is the groovy/grails asset pipeline modifiable at runtime?
Problem: I am creating an application where users create the objects. The objects are stored as text files so that only the necessary objects are built at runtime. Currently, the text file includes a string which represents the filename of the image. The plan was to have these images stored in assets/images/ as this works best for later displaying the object. However, now I am running into issues with saving files to assets/images/ at run time, and I can't even figure out if this is possible. *Displaying images already works in the way I require if I drag and drop the images into the desired folder, however I need a way for the controller to put the image there instead. The relevant section of controller code:
def folder = new File("languageDevelopment/grails-app/assets/images/")
//println folder
def f = request.getFile('keyImage');
if (f.empty)
{
flash.message = 'file cannot be empty'
render(view: 'create')
return
}
f.transferTo(folder)
The error I'm receiving is a fileNotFoundException
"/var/folders/9c/0brqct9j6pj4j85wnc5zljvc0000gn/T/languageDevelopment/grails-app/assets/images (No such file or directory)"
on f.transferTo(folder)
What is the section it is adding to the beginning of my "folder" object?
Thanks in advance. If you need more information or have a suggestion to a different route please let me know!
new File("languageDevelopment/grails-app/assets/images/")
This folder is present only in your sources
After deployment it will looks like "/PATH-TO-TOMCAT/webapps/ROOT/assets/" if you use tomcat.
Also asset/images, asset/font etc. will be merged to assets folder.
If you'd like to store temporary files you can create some directory under src/resources folder.
For example "src/resources/images"
And you can get access to this folder from classloader:
this.class.classLoader.getResource('images/someImage.png').path

Extracting files from res folder in Executable JAR (txt files to be specific)

I would like to ask if its possible to put text files into my jar, I use them to make my map in my game, but users can get Highscores. now I want to save the Highscores with the map, so I have to save the map on the user their PC. Is there any way how I could do this? I've searched the internet for some ideas but I could not find anything that even came close to what I've wanted. I only had 3/4th of a year java so I don't know much about these things, everything that happens outside the debug of eclipse are problems for me(files are mainly one of those things, null exceptions, etc).
The main question now.
Is it possible to do? If yes, do you have any terms I could search on, or some sites/guides/tutorials? If no, is there any other way how I could save the highscores?
EDIT:
to make clear
Can I get the text file (the text inside the file) to be extracted to a different file in like the home directory of my game (where I save the settings and stuff) the basic maps are inside the jar file, so I want them to be extracted on the first start-up of the program
Greetings Carolien
"extracted to a different file in like the home directory of my game (where i save the settings and stuff) the basic maps are inside the jar file, so i want them to be extracted on the first startup of the program"
You can get the URL by using getClass().getResource()
URL url = getClass().getResource("/res/myfile.txt");
Then create a File object from the URI of the URL
File file = new File(url.toURI());
Then just perform your normal file operations.
if (file.renameTo(new File(System.getProperty("user.home") + "\\" + file.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
Assuming your file structure is like below, it should work fine
ProjectRoot
src
res
myfile.txt
Note: the above is moving the entire file. If you want to extract just the data inside the file, then you can simple use
InputStream is = getClass().getResourceAsStream("/res/myfile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The just do normal IO operation with the reader. See here for help with writing the file.

Using selenium webdriver to upload a file

I'm trying to build some automated test for a mailbox application and I'm trying to attach a file. I've read all the documentation from previous post and was able to come up with this:
public void I_attach_a_file_that_exceeds_the_limit() throws Throwable {
WebElement attachFile = driver.findElement(By.id("attachment"));
File f = new File("C:\\coop-provider-swm-specs\\src\\test\\resources\\attachments\\20481kb.txt");
attachFile.sendKeys(f.getCanonicalPath());
}
The problem with this is that the file that it attaches is not the real file. The file that is attached is blank (not sure how that works). The file that I need to attach is a big file and I need to do this in order the authenticate that the user does not exceed the limit for attachments that is allowed.
Change:
attachFile.sendKeys(f.getCanonicalPath());
To:
attachFile.sendKeys(f.getCanonicalPath()).submit();

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

Show list of files on server

We are saving .csv files on a tomcat6.0 server that are sent via cron to an external vendor. On occasion, the send doesn't work and we need to get the .csv file from the server and email it to the vendor. Instead of having to log in to the server, I am trying to add another function on our webpage (that lives on the same server) that will allow administrators to download the file to their desktop and email it that way. If I know the name of the file, all is well and I have that part working, but I need to be able to select a file from the directory on the server. Finally my question: How can I show the list of files from a particular directory in my java servlet?
Following function will return an arraylist of files present inside a folder.
public ArrayList<String> getReportNames() throws IllegalArgumentException {
String path=getServletContext().getRealPath("/WEB-INF");
File[] list = new File(path+"/YOUR_FOLDERNAME_INSIDE_WEBINF").listFiles(new MyFileNameFilter());
ArrayList<String> fileNames=new ArrayList<String>();
for (File file: list)
fileNames.add(file.getName());
return fileNames;
}
List the files in the directory (using File.listFiles) and display a page with the list. Unclear if you are asking for something more.

Categories

Resources