HtmlUnitDriver to invoke local html file - java

I am trying to invoke a locally stored html file using the get() method of the HtmlUnitDriver, but the page is not getting loaded. I tried to get the page source and I got 404 not found as the response. If I use the chrome driver in headless mode I am able to invoke the file. Is it possible to do this using HtmlUnitDriver?
Below is a code snippet
HtmlUnitDriver unitDriver = new HtmlUnitDriver();
public class Test {
public void clickOn() {
String filePath =
"home/test-output/100071234.html";
try {
unitDriver.get(filePath);
WebElement ele = unitDriver.findElement(By.id("submitPayment"));
ele.click();
} catch (Exception ex) {
ex.printStackTrace();
}
}

If you need to open local file you have to adhere the URI format. So for Linux it would be (if home folder is under the root folder):
String filePath =
"file:///home/test-output/100071234.html";
Here you can find other examples (Windows, Mac OS): https://en.wikipedia.org/wiki/File_URI_scheme

Related

How to Upload file in selenium using Java

I am trying to upload the file in selenium using java. When I run my test case then it passed every time but the file is not uploading. See below site and my code where I performing.
Site URL: https://files.fm/
Xpath where i want to upload: //input[#name='file_upload[]']
Note: If this xpath is incorrect then please update in comment.
Code:
#BeforeTest
public void OpenBrowser() {
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://files.fm/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void FileUpload() throws InterruptedException, IOException {
Thread.sleep(2000);
WebElement file = driver.findElement(By.xpath("//input[#name='file_upload[]']"));
file.sendKeys("C:/Users/Admin/Pictures/Lighthouse.jpg");
}
use below code :
WebElement file = driver.findElement(By.xpath("//input[#id='file_upload']//following-sibling::input"));
file.sendKeys("C:/Users/Admin/Pictures/Lighthouse.jpg");
WebElement startUploadButton = driver.findElement(By.xpath("//div[#id='savefiles']//div"));
startUploadButton.click();
Hope that helps you:)
You choosed the wrong input. I tried to send to the other input and it worked
Here is xpath of it.
String inPath = "//*[#id='uploadifive-file_upload']/input[2]";

How can I crawl a webPage which through javascript dynamically generated like this

I hava crawl the webPageSource by use the selenium and the code like this
public static String getCurrentPageSource(String url) {
webDriver = new ChromeDriver();
webDriver.get(url);
String src = webDriver.getPageSource();
//writeInfile(src);
webDriver.close();
return src;
}
but I can't see the remain time in the pageSource I have crawl Because it is dynamically generated by JS.

Crawling GitHub with JGit

I'm trying to crawl a GitHub Wiki with JGit.
When I try it with one URL, it worked perfectly fine. Then I tried it with another random URL and got an error.
Please see the extract of my code:
import java.io.File;
import java.io.IOException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
public class Main {
// with this URL I get an error
String url = "https://github.com/radiant/radiant.wiki.git";
// this URL works
// String url = "https://github.com/WardCunningham/Smallest-Federated-Wiki.wiki.git";
public static void main(String[] args) {
Main m = new Main();
m.jgitTest();
System.out.println("Done!");
}
public void jgitTest() {
try {
File localPath = File.createTempFile("TestGitRepository", "");
localPath.delete();
Git.cloneRepository().setURI(url).setDirectory(localPath).call();
} catch (IOException | GitAPIException e) {
System.err.println("excepton: " + e.getMessage());
e.printStackTrace();
}
}
}
This is the stack trace:
Exception in thread "main" org.eclipse.jgit.dircache.InvalidPathException: Invalid path (contains separator ':'): How-To:-Create-an-Extension.textile
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPathSegment(DirCacheCheckout.java:1243)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPathSegment(DirCacheCheckout.java:1225)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPath(DirCacheCheckout.java:1185)
at org.eclipse.jgit.dircache.DirCacheCheckout.processEntry(DirCacheCheckout.java:311)
at org.eclipse.jgit.dircache.DirCacheCheckout.prescanOneTree(DirCacheCheckout.java:290)
at org.eclipse.jgit.dircache.DirCacheCheckout.doCheckout(DirCacheCheckout.java:408)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkout(DirCacheCheckout.java:393)
at org.eclipse.jgit.api.CloneCommand.checkout(CloneCommand.java:236)
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:127)
at Main.jgitTest(Main.java:21)
at Main.main(Main.java:13)
If you visit the wiki page of the URL that doesn't work (https://github.com/radiant/radiant/wiki), you will find this page: How To: Create an Extension.
The title of this page is the cause of the error: Invalid path (contains separator ':'): How-To:-Create-an-Extension.textile.
I assume I need to escape all output.
I suppose you are on windows. You can't create a file on windows having the ":" in the name. JGit should handle it somehow, so I suppose this is a bug in JGit.
I had the same problem with pure git, and this answer helped me:
git config core.protectNTFS false

Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure. when running selenium tests

I want to run my selenium tests on different browsers based on the browser name set in the Properties file.
I have a method named as initiateDriver() in which I get the browser name as set in the Properties file(valid values being ff, chrome or ie) and do the necessary settings for each of the web driver type. This method will return a WebDriver object to my methods.
public WebDriver initiateDriver()
{
// Created webdriver instance
WebDriver _drv = null;
String IEDriverPath, ChromeDriverPath;
try
{
//Get the Browser Name set in the properties file
String browserType = loadPropertiesFile("BrowserName");
Log4j.logger.warn("Browser name-----------"+browserType);
//Test if the browser is IE
if (browserType.equalsIgnoreCase("ie"))
{
//Currently, IEDriverServer.exe is copied on to Drivers folder of framework
IEDriverPath= "\\Drivers\\IEDriverServer.exe";
//Set the required properties to instantiate IE driver. Place any latest IEDriverServer.exe files under Drivers folder
System.setProperty("webdriver.ie.driver", IEDriverPath);
DesiredCapabilities cap= new DesiredCapabilities();
cap.setCapability("ignoreProtectedModeSettings", true);
_drv = new InternetExplorerDriver(cap);
}
//Check if BrowserType is set to Firefox
else if (browserType.equalsIgnoreCase("ff") || browserType.equalsIgnoreCase("firefox"))
{
//Getting the default Firefox with some settings
FirefoxProfile fp = new FirefoxProfile();
fp.setAcceptUntrustedCertificates(false);
//setting the Firefox preference "auto upgrade browser" to false and to prevent compatibility issues
fp.setPreference("app.update.enabled", false);
_drv = new FirefoxDriver();
}
//Check if BrowserType is set to Chrome
else if (browserType.equalsIgnoreCase("chrome"))
{
//Currently, chromedriver.exe is copied on to Drivers folder of framework
ChromeDriverPath= "\\Drivers\\chromedriver.exe";
//Set the required properties to instantiate Chrome driver. Place any latest Chromedriver.exe files under Drivers folder
System.setProperty("webdriver.chrome.driver", ChromeDriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
_drv= new ChromeDriver(options);
}
else
{
Reporter.log("Invalid browser name. Please check the Resources/PropertiesLocation.properties file.");
System.out.println("Invalid browser name. Please check the Resources/PropertiesLocation.properties file.");
System.exit(0);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
Reporter.log("Enter valid browser name---");
System.exit(0);
}
return _drv;
}`
I am calling this method in the following class.
public class SmokeTest1
{
WebDriver d;
#BeforeClass
public void setUp() throws Exception
{
d = gm.initiateDriver();
d.manage().window().maximize();
d.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void firstSmokeTest() throws Exception
{
loginTest(d);
}
}
I am running my tests via ant build.xml file. However I am getting error as -
Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure."
Can somebody suggest what is going wrong or am I missing anything?

java: Open folder on button click

In java, how can we open a separate folder (e.g. c:) for user on click of a button, e.g like the way " locate this file on disk" or "open containing folder" does when we download a file and we want to know where it was saved. The goal is to save user's time to open a browser and locate the file on disk.
Thanks ( image below is an example from what firefox does)
I got the answer:
Here is what worked for me in Windows 7:
File foler = new File("C:\\"); // path to the directory to be opened
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
try {
desktop.open(foler);
} catch (IOException e) {
}
Thanks to #AlexS
I assume you have a file. With java.awt.Desktop you can use something like this:
public static void openContaiingFolder(File file) {
String absoluteFilePath = file.getAbsolutePath();
File folder = new File(absoluteFilePath.substring(0, absoluteFilePath.lastIndexOf(File.separator)));
openFolder(folder);
}
public static void openFolder(File folder) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(folder);
}
}
Be awrae that if you call this with a File that is no directory at least Windows will try to open the file with the default program for the filetype.
But I don't know on which platforms this is supported.

Categories

Resources