In Intellij, I have the file located in class path resources folder and the folder is marked as resources also.
But, still when I use:
new FileInputStream("myFile.xml");
I am getting:
java.io.FileNotFoundException: myFile.xml (No such file or directory)
Where am I wrong? Thanks ahead
Assuming your myFile.xml is in resources folder
Try reading like this
InputStream inputStream = YourClassName.class.getResourceAsStream("/myFile.xml");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
Related
When I download a file in Ubuntu to /tmp using selenium, the file doesn't appear. However, the count postfix of the filename keeps increasing in Chrome, e.g. file (1).txt - meaning the browser finds the previously downloaded files.
Example App.java:
public class App
{
public static void main( String[] args ) throws InterruptedException {
final ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", Map.of("download.default_directory", "/tmp/"));
final ChromeDriver driver = new ChromeDriver(options);
driver.get("file:///home/.../download.html");
Thread.sleep(5000);
driver.quit();
}
}
download.html
<div>Hello</div>
<script>
const element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent("Hello World"));
element.setAttribute('download', "file.txt");
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
</script>
After running this java code, the file cannot be found in /tmp or anywhere else in the filesystem: find . 2>/dev/null -name file.txt yields nothing. However, while the code is running, selenium keeps increasing the postfix of the filename:
Where is the downloaded file?
I guess the files are downloaded into your /home/username/Downloads folder, not to /tmp folder as you expecting.
I've converted an NUnit test project from .NET Framework to .NET Core. When I try to execute a Selenium test using Visual Studio, I am seeing this error:
OpenQA.Selenium.DriverServiceNotFoundException : The chromedriver.exe
file does not exist in the current directory or in a directory on the
PATH environment variable. The driver can be downloaded at
http://chromedriver.storage.googleapis.com/index.html.
I've included the Selenium.WebDriver.ChromeDriver Nuget Package and chromedriver.exe appears in the output bin folder. Without having to set the ChromeDriver url as an environment variable, how do I get Visual Studio to find the file?
[Test]
public void Test()
{
var driver = new ChromeDriver();
driver.Url = "http://www.google.com";
}
This happens because in .Net Core the NuGet packages are loaded from a global location instead of the packages folder in .NET Framework projects.
You can use the following and it will run correctly:
ChromeDriver driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
This works for me
var currentDirectory = Directory.GetCurrentDirectory();
var driverService = ChromeDriverService.CreateDefaultService(currentDirectory);
driverService.Start();
var driver = new ChromeDriver(driverService);
What i did when i had the problem was to set a var:
var driverDirectory = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
And just pass it to ChromeDriver on creation.
I have a html file in my local machine. When running my selenium-java code locally through eclipse, I can access the html file through the code mentioned below -
File file = new File(url);
driver.get("file:///" + file.getAbsolutePath());
If I run the code through selenium grid, registered node doesn't pick up the html file path to be opened in chrome since the absolute path points to the local machine.
Is there any solution available to open the locally available html file through selenium grid-node?
You should use a LocalFileDetector.
import org.openqa.selenium.remote.LocalFileDetector
import org.openqa.selenium.remote.RemoteWebDriver
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), DesiredCapabilities.firefox());
driver.setFileDetector(new LocalFileDetector())
Your upload should now work.
There are basically two ways in which you can get this done. I will list out both the approaches. Please feel free to pick and choose whichever works for you.
Using custom node servlet
You need to follow the below steps:
Create a new custom servlet, using which you can upload a file using a HTTP POST method.
It could look something like below [ This code is borrowed from a journaldev post here and being included here only for the sake of completeness] You may need to tweak the code before use and not necessarily use it as is. The current code returns a html response, but you may need to change it so that it returns a JSON response which contains the actual path where the file was uploaded to. This path is what you will use in your driver.get() call.
package com.journaldev.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadDownloadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletFileUpload uploader = null;
#Override
public void init() throws ServletException{
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
fileFactory.setRepository(filesDir);
this.uploader = new ServletFileUpload(fileFactory);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
if(fileName == null || fileName.equals("")){
throw new ServletException("File Name can't be null or empty");
}
File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
if(!file.exists()){
throw new ServletException("File doesn't exists on server.");
}
System.out.println("File location on server::"+file.getAbsolutePath());
ServletContext ctx = getServletContext();
InputStream fis = new FileInputStream(file);
String mimeType = ctx.getMimeType(file.getAbsolutePath());
response.setContentType(mimeType != null? mimeType:"application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
ServletOutputStream os = response.getOutputStream();
byte[] bufferData = new byte[1024];
int read=0;
while((read = fis.read(bufferData))!= -1){
os.write(bufferData, 0, read);
}
os.flush();
os.close();
fis.close();
System.out.println("File downloaded at client successfully");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head></head><body>");
try {
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
while(fileItemsIterator.hasNext()){
FileItem fileItem = fileItemsIterator.next();
System.out.println("FieldName="+fileItem.getFieldName());
System.out.println("FileName="+fileItem.getName());
System.out.println("ContentType="+fileItem.getContentType());
System.out.println("Size in bytes="+fileItem.getSize());
File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileItem.getName());
System.out.println("Absolute Path at server="+file.getAbsolutePath());
fileItem.write(file);
out.write("File "+fileItem.getName()+ " uploaded successfully.");
out.write("<br>");
out.write("Download "+fileItem.getName()+"");
}
} catch (FileUploadException e) {
out.write("Exception in uploading file.");
} catch (Exception e) {
out.write("Exception in uploading file.");
}
out.write("</body></html>");
}
}
Create a sample project, which includes a dependency on the selenium libraries and which contains the servlet built in step (1) and create a jar out of it. For instructions on how to do all of this, you can refer to my blog post here (or) to the official selenium documentation here.
Start the node, along with the -servlets parameter so that your newly created node servlet, gets injected into the node and is available via http://<Node_IP_Address>:<Node_Port>/extra/UploadDownloadFileServlet (since our sample servlet's name was UploadDownloadFileServlet)
Now in your test code, you can create a new RemoteWebDriver instance as always.
You now need to upload your html file to the remote node where the new session was created. For doing that, you need to know the IP of the node where your test ran. So you make use of a library such as talk2grid (I built this library) or leverage the approach of determining this information on your own by referring to my blog here
Once you have the IP and port, you now trigger a HTTP POST to the servlet you created earlier by hitting the endpoint http://<Node_IP_Address>:<Node_Port>/extra/UploadDownloadFileServlet and get back the path to where it was uploaded in the response.
Now use the path that was returned in step (6) in your driver.get() call (don't forget to include the file:/// protocol)
That should do.
Using Javascript
In this approach, you basically start off by loading a blank page (for e.g., driver.get("about:blank"); and then make use of Javascript to start dynamically creating your web page via document.createElement() call (Refer to this article for more information ) and create the entire page. You can now start interacting with the page.
Approach (1) would be useful only when you are working with a grid environment wherein you are allowed to add servlets etc and access its IP and port.
Approach (2) will work in all use cases including third party remote execution environment providers such as SauceLabs or BrowserStack (In case you use them as well)
I want to read content of image using selenium and asprise jars and added below jar files in my project :
aocr.jar
AspriseOCR
and below is my code :
BufferedImage image = ImageIO.read(new File("C:\\Users\\siddhesh.kalgaonkar\\Desktop\\love.jpg"));
String imageText = new OCR().recognizeCharacters((RenderedImage)image);
System.out.println("Text From Image : \n"+ imageText);
System.out.println("Length of total text : \n"+ imageText.length());
but its giving below error :
java.lang.UnsatisfiedLinkError: no AspriseOCR in java.library.path
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.loadLibrary0(Unknown Source)
at java.lang.System.loadLibrary(Unknown Source)
at com.asprise.util.ocr.OCR.loadLibrary(OCR.java:247)
at com.asprise.util.ocr.OCR.<init>(OCR.java:56)
at com.image.selenium.ImageVerification.start(ImageVerification.java:52)
I also tried setting java.library.path using this link but of no use. Please help anyone.
I got an answer to my own question. We can now do it with the help of below information:
Add latest aocr.jar to your project. Download it from
this link.
Include pom.xml file in your project for maven dependencies and add this dependency :
<dependency>
<groupId>com.asprise.ocr</groupId>
<artifactId>java-ocr-api</artifactId>
<version>[15,)</version>
</dependency>
Write below code in your java file :
public class ImageVerification
{
WebDriver driver;
#Test
public void start() throws IOException {
Ocr ocr = new Ocr(); // create a new OCR engine
ocr.startEngine("eng", Ocr.SPEED_FASTEST); // English
String s = ocr.recognize(new File[] { new File("C:\\Users\\siddhesh.kalgaonkar\\Desktop\\love.jpg") },
Ocr.RECOGNIZE_TYPE_TEXT, Ocr.OUTPUT_FORMAT_PLAINTEXT);
System.out.println(s);
ocr.stopEngine();
}
For more details refer this link
Enjoy :)
NOTE: It works only for images with plain text.It doesn't work for images with data in graph format or pie chart or trend chart
The test is to download a file by clicking the link for download template. When I execute the script in my local machine, it is working perfectly. Able to create the download folder and the file downloaded is stored in the newly created "download" folder.
But when I integrate it to the jenkins pipeline, there is no folder created and no file downloaded.
Note: In the jenkins pipeline, the script is executed using chrome in the selenium grid. Please refer to the configuration in the chrome driver.
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", System.getProperty("user.dir") + "\\src\\main\\resources\\downloads");
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
options.setExperimentalOption("prefs", chromePrefs);
options.addArguments("--test-type");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
driver = new RemoteWebDriver(new URL(seleniumGridUrl), cap);
If you are not going to check the contents of the downloaded file in your test, I'd like to suggest using a kind of by-pass approach. Using HTTP library, you may just execute Head http call to the resource, you need to download. In the response you'll get the file type and its size. In your test you simply assert against them to validate correctness of accessed for downloading file.
I think the issue you get is connected somehow with the permissions, that does not allow creating folders / files on the environment, where test is executed.