I am trying to open the firefox browser in mac machine.
As I am using latest selenium jar file, so for opening the Firefox browser, I am using geckodriver but not able to launch the browser.
Below are the code which I am using for opening the browser using geckodriver:
public class Apache_POI_TC {
private static WebDriver driver = null;
public static void main(String[]arg) throws Exception{
//This is to open the Excel file. Excel path, file name and the sheet name are parameters to this method
ExcelUtils.setExcelFile(Constant.Path_TestData+ Constant.File_TestData, "Sheet1");
System.setProperty("webdriver.gecko.driver", "/Users/ileadsynapse/Desktop/CT/geckodriver");
DesiredCapabilities capabilities= DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);
driver.get("http://www.store.demoqa.com");
SignIn_Action.Execution(driver);
System.out.println("Login successfully.");
Home_Page.lnk_LogOut(driver).click();
driver.quit();
//This is to send the PASS value to the Excel sheet in the result column.
ExcelUtils.setCellData("Pass", 1, 3);
}
}
Error
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/Logger
at org.apache.logging.slf4j.SLF4JLoggerContext.getLogger(SLF4JLoggerContext.java:39)
at org.apache.logging.log4j.jcl.LogAdapter.newLogger(LogAdapter.java:34)
at org.apache.logging.log4j.jcl.LogAdapter.newLogger(LogAdapter.java:30)
at org.apache.logging.log4j.spi.AbstractLoggerAdapter.getLogger(AbstractLoggerAdapter.java:52)
at org.apache.logging.log4j.jcl.LogFactoryImpl.getInstance(LogFactoryImpl.java:40)
at org.apache.logging.log4j.jcl.LogFactoryImpl.getInstance(LogFactoryImpl.java:55)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:655)
at org.apache.http.conn.ssl.AbstractVerifier.<init>(AbstractVerifier.java:61)
at org.apache.http.conn.ssl.AllowAllHostnameVerifier.<init>(AllowAllHostnameVerifier.java:44)
at org.apache.http.conn.ssl.AllowAllHostnameVerifier.<clinit>(AllowAllHostnameVerifier.java:46)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>(SSLConnectionSocketFactory.java:146)
at org.openqa.selenium.remote.internal.HttpClientFactory.getClientConnectionManager(HttpClientFactory.java:71)
at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:57)
at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:60)
at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.getDefaultHttpClientFactory(ApacheHttpClient.java:247)
at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.<init>(ApacheHttpClient.java:224)
at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:93)
at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:72)
at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:59)
at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:49)
at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:207)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:108)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:137)
at automationFramework.Apache_POI_TC.main(Apache_POI_TC.java:31)
Caused by: java.lang.ClassNotFoundException: org.slf4j.Logger
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 24 more
Can anyone please help me to resolve the problem. Thanks in Advance.
My issue for not opening the Firefox browser using geckodriver in mac machine get resolved after configuring the below jars in build path:
log4j-1.2.16.jar
slf4j-api-1.7.6.jar
slf4j-simple-1.7.6.jar
xuggle-xuggler-5.4.jar
Related
I am using Flying Saucer to generate PDF from XHTML. Rendering works nice, but any attempt to password-protect the PDF document fails with an Exception.
I am using code recommended by Ajit Soman in https://stackoverflow.com/a/46024498/4517737. A copy of code is shown below.
If you un-comment the commented line, Exception is thrown in line "renderer.createPDF(os, false)".
The Exception is
"Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException"
(for JavaFX application).
For plain Java, the Exception is "Exception in thread "main" java.lang.NoClassDefFoundError: org/bouncycastle/asn1/ASN1Encodable
at com.itextpdf.text.pdf.PdfEncryption.(PdfEncryption.java:147).....
Caused by: java.lang.ClassNotFoundException:org.bouncycastle.asn1.ASN1Encodable"
final File outputFile = File.createTempFile(fileName, ".pdf");
FileOutputStream os = new FileOutputStream(outputFile);
PDFEncryption pdfEncryption = new PDFEncryption();
String password= "password#123";
pdfEncryption.setUserPassword(password.getBytes());
ITextRenderer renderer = new ITextRenderer();
// the following line causes Exception
// renderer.setPDFEncryption(pdfEncryption);
renderer.setDocumentFromString(htmlContent);
renderer.layout();
renderer.createPDF(os, false);
renderer.finishPDF();
Please help.
Am running the Selenium webdriver(Maven Project) Scripts through Jenkins by calling pom.xml file. I have set below mentioned browser resolution
driver.manage().window().maximize();
Dimension defaultSize = new Dimension(2560,1440);
driver.manage().window().setSize(defaultSize);
However, while running the scripts through Jenkins, Chrome browser window is not set to the new dimension.
Note : In Local machine it's working fine..
Copied from my question - GOCD pipeline, Selenium ChromeDriver window size is not set
his issue looks to have been caused by two issues,
1- When mvn clean test is run from the IDE this process runs under your current user. However, when run by the Continuous Integration environment, the process is owned by the System process. so does not have the same access to resources.
2 When run from the IDE, chrome will pop up. When run from the CI environment I assumed that it defaulted chrome to run in headless mode. It does not, you have to set the --headless argument so my configuration that now works is as follows
public class GoogleChrome extends Base {
private static final Logger logger = LogManager.getLogger(GoogleChrome.class);
private String rootPath = System.getProperty("user.dir").replace("\\","/");
#Autowired
protected WebDriver driver;
public WebDriver startChromeDriver() {
logger.info("Chrome driver path : " + rootPath + "/../Tools/Drivers/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", rootPath + "/../Tools/Drivers/chromedriver.exe");
Map<String, Object> prefs = new HashMap<String, Object>();
logger.info("Disabling Chrome's credentials service");
prefs.put("credentials_enable_service", false);
logger.info("Disabling Chrome's password manager");
prefs.put("password_manager_enabled", false);
final String regex = "^\\D*$";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(System.getProperty("user.name"));
boolean isHuman = matcher.matches();
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
logger.info("Disabling Chrome's info bars");
options.addArguments("disable-infobars");
options.addArguments("--incognito");
options.addArguments("--disable-gpu");
options.addArguments("--no-sandbox");
options.addArguments("--allow-insecure-localhost");
if (isHuman){
logger.info("Chrome starting maximized - isHuman: " +isHuman + " process run by " +System.getProperty("user.name"));
options.addArguments("--start-maximized");
} else {
logger.info("Chrome starting headless - isHuman: " +isHuman + " process run by " +System.getProperty("user.name")) ;
options.addArguments("--headless");
options.addArguments("--window-size=1980,1080");
}
options.setAcceptInsecureCerts(true);
try {
logger.info("Killing Chrome browser");
Runtime.getRuntime().exec("taskkill /F /IM chrome.exe");
} catch (IOException e) {
logger.error("Task Kill IOException : " + e.getMessage());
}
logger.info("Starting Chrome browser...");
sleep(2);
driver = new ChromeDriver(options);
logger.info("Window size: "+ driver.manage().window().getSize());
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
return driver;
}
}
Chrome disallows setting the size larger than the system's screen resolution width, the problem may be this in your case. Some workaround could be to maximize the window to at least have the largest window available on that system.
While sometimes old chromedriver also cause the issue
If still problem exist then you can change the resolution by chrome option as :
chromeOptions.addArguments("window-size=1936,1056");
Full code will be like :-
System.setProperty("webdriver.chrome.driver","D:\\Workspace\\JmeterWebdriverProject\\src\\lib\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("window-size=1936,1056");
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("https://www.google.co.in/");
Hope it will help you :)
I am asking this question because I was unable to find a similar question. I recently completed this college project where I made a console application that connected to the database and everything seemed perfectly fine. The method I used to connect to the database is this:
private static Connection getConnection()
{
Connection connection = null;
try
{
String dbDirectory = "c:/murach/java/db";
System.setProperty("derby.system.home", dbDirectory);
String dbURL = "jdbc:derby:MurachDB2";
String username = "";
String password = "";
connection = DriverManager.getConnection(dbURL, username, password);
System.out.println("connect works");
return connection;
} //end try connection statement
catch (SQLException e)
{
for (Throwable t : e)
{
e.printStackTrace();
System.out.println("something went wrong on connection method");
} //end for loop for errors
} // end catch statement for connection error
return connection;
}
As I said before I created the console application and everything seemed fine and I turned it in. However, I wanted to experiment with something, I wanted to make another version of this application but instead a GUI application using Jform. I used all of the same classes as before, except that instead of a main class, I used a jform. The method and class is exactly the same, because the database didn't change locations in my folder, however when I run it in the Jform application I get a runtime error.
What it was a null point error and I knew it had something to do with connecting to the database because I wrote a System.out.Println in the catch SQL Exception to notify that something went wrong with the method. The connect to the database is fine with the console application, but my question is if there is any further measures I need to take when it comes to working with a JFrame application. Is there anything I am missing or is there any extra step I need to do. For further measures I will display the whole class that works with the database, and I will also use the event handlers in the Jframe.
I want to make this clear in which that I am not required to do this. I am just playing around with Java, and I could easily leave this alone without consequences, but I feel I really want to learn this so this is why I am asking for help. Any kind of advice or if any of you can let you know what I am missing I would really appreciate it.
Edit
adding error information
>java.sql.SQLException: No suitable driver found for jdbc:derby:MurachDB2
something went wrong on connection method
java.lang.NullPointerException
something went from with dislay part
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at CustomerInvoiceDB.getConnection(CustomerInvoiceDB.java:38)
at CustomerInvoiceDB.getCustomers(CustomerInvoiceDB.java:67)
at CutomerInvoice.displayButtonActionPerformed(CutomerInvoice.java:111)
at CutomerInvoice.access$000(CutomerInvoice.java:24)
at CutomerInvoice$1.actionPerformed(CutomerInvoice.java:57)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
I am using selenium web driver and downloading .pdf files from internet using firefox, but i could not able to save these files on local machine using relative path ( i am using windows 7 32 bit machine ). It is working fine if i am using absolute path. But i only want to use relative path as i also need to run it on server later.
My Code:
public static void main(String args[]) throws ClassNotFoundException, IOException{
FirefoxProfile fprofile = new FirefoxProfile();
fprofile.setPreference("browser.download.useDownloadDir", true);
fprofile.setPreference("browser.download.dir", "./Folder");
fprofile.setPreference("browser.download.folderList", 2);
fprofile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf;");
fprofile.setPreference( "browser.download.manager.showWhenStarting", false );
fprofile.setPreference( "pdfjs.disabled", true );
fprofile.setPreference("plugin.scan.plid.all", false);
fprofile.setPreference("plugin.scan.Acrobat", "99.0");
WebDriver driver = new FirefoxDriver(fprofile);
I did something like this in my ruby code
download_directory = File.join(File.absolute_path('../..', File.dirname(__FILE__)),"downloads")
I believe that it will be similiar in java - get absolute path from relative path
Path path = FileSystems.getDefault().getPath("./Folder");
String absolutePath = path.toAbsolutePath().toString();
http://www.javacodex.com/Files/Converting-A-Relative-Path-Into-An-Absolute-Path
Below is my non-working code for the Firefox profile.
#Before
public void setUp() throws Exception {
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.download.dir", "/Location");
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/docx");
driver=new FirefoxDriver(profile);
baseUrl = "<URL>";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void test1() throws Exception {
driver.get("URL");
driver.findElement(By.id("Username")).sendKeys("username");
driver.findElement(By.id("Password")).sendKeys("Password");
driver.findElement(By.xpath(".//*[#id='rowCell0']/td[4]/a[4]")).click();// This line of code is for Download Link on the UI
Now once selenium clicks on it, Firefox will again open the confirmation box asking for "Open with" and "Save File".
Please remove
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.showWhenStarting",false);
and try it should work...let me know
I met this issue too and it blocked me several days!
Please make sure the file type you are trying to download, and then configure with the correct value in below line:
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/docx");
Your site source code is sending back a content header saying the file is xxx to match the preferences you have set.
To reference, the types may be: application/octet-stream, application/vnd.ms-excel, text/csv, text/plain, application/zip, application/exe, application/x-zip, application/x-zip-compressed, application/download