Webdriver: Browser is launched. But not calls URL when GeckoDriver is used - selenium-webdriver

Actually I have installed all latest versions. My firefox browser launches. But URL is not called.
Following are my System details.
OS: Ubuntu 14.04
Firefox Version: 56.0
Selenium Server: selenium-server-standalone-3.6.0
GeckoDriver: geckodriver-v0.19.0-linux64
Browser Launch Code
if(BrowserCode.equalsIgnoreCase("FF"))
{
System.setProperty("webdriver.gecko.driver",System.getProperty("user.dir")+"/AllDrivers/geckodriver");
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver(capabilities);
}
I am getting following eror. Can anyone please help me in this.
[TestNG] Running:
/home/vishalpachpute/workspace/ER_CustomerCare/ERCC_Login.xml
/home/vishalpachpute/workspace/ER_CustomerCare
1507724942300 geckodriver INFO geckodriver 0.19.0
1507724942306 geckodriver INFO Listening on 127.0.0.1:3966
1507724942723 mozrunner::runner INFO Running command: "/usr/lib/firefox/firefox" "-marionette" "-profile" "/tmp/rust_mozprofile.qsoDFMATTikn"
1507724942948 addons.xpi WARN Error parsing extensions state: [Exception... "Component returned failure code: 0x80520012 (NS_ERROR_FILE_NOT_FOUND) [amIAddonManagerStartup.readStartupData]" nsresult: "0x80520012 (NS_ERROR_FILE_NOT_FOUND)" location: "JS frame :: resource://gre/modules/addons/XPIProvider.jsm :: loadExtensionState :: line 1554" data: no] Stack trace: loadExtensionState()#resource://gre/modules/addons/XPIProvider.jsm:1554 < getInstallState()#resource://gre/modules/addons/XPIProvider.jsm:1589 < checkForChanges()#resource://gre/modules/addons/XPIProvider.jsm:3109 < startup()#resource://gre/modules/addons/XPIProvider.jsm:2188 < callProvider()#resource://gre/modules/AddonManager.jsm:269 < _startProvider()#resource://gre/modules/AddonManager.jsm:739 < startup()#resource://gre/modules/AddonManager.jsm:906 < startup()#resource://gre/modules/AddonManager.jsm:3090 < observe()#jar:file:///usr/lib/firefox/omni.ja!/components/addonManager.js:65
1507724943785 Marionette INFO Enabled via --marionette
(firefox:22169): GLib-GObject-CRITICAL **: g_object_ref: assertion 'object->ref_count > 0' failed
(firefox:22169): GLib-GObject-CRITICAL **: g_object_unref: assertion 'object->ref_count > 0' failed
(firefox:22169): GLib-GObject-CRITICAL **: g_object_ref: assertion 'object->ref_count > 0' failed
(firefox:22169): GLib-GObject-CRITICAL **: g_object_unref: assertion 'object->ref_count > 0' failed
(/usr/lib/firefox/firefox:22219): GLib-GObject-CRITICAL **: g_object_ref: assertion 'object->ref_count > 0' failed
(/usr/lib/firefox/firefox:22219): GLib-GObject-CRITICAL **: g_object_unref: assertion 'object->ref_count > 0' failed
(/usr/lib/firefox/firefox:22219): GLib-GObject-CRITICAL **: g_object_ref: assertion 'object->ref_count > 0' failed
(/usr/lib/firefox/firefox:22219): GLib-GObject-CRITICAL **: g_object_unref: assertion 'object->ref_count > 0' failed
1507724946494 Marionette INFO Listening on port 38903
1507725070118 Marionette WARN TLS certificate errors will be ignored for this session
1507725070153 Marionette DEBUG Register listener.js for window 2147483649
Oct 11, 2017 6:01:10 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
1507725070269 Marionette DEBUG Received DOM event "beforeunload" for "about:blank"
1507725160564 Marionette DEBUG Received DOM event "beforeunload" for "about:blank"
1507725160566 Marionette DEBUG Received DOM event "pagehide" for "about:blank"
1507725160567 Marionette DEBUG Received DOM event "unload" for "about:blank"
1507725160612 Marionette DEBUG Received DOM event "DOMContentLoaded" for "about:neterror?e=netTimeout&u=http%3A//localhost%3A8888/ercc/&c=UTF-8&f=regular&d=The%20server%20at%20localhost%20is%20taking%20too%20long%20to%20respond."
org.openqa.selenium.WebDriverException: Reached error page: about:neterror?e=netTimeout&u=http%3A//localhost%3A8888/ercc/&c=UTF-8&f=regular&d=The%20server%20at%20localhost%20is%20taking%20too%20long%20to%20respond.
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'vfrootThinkPadT450', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '3.16.0-30-generic', java.version: '1.8.0_111'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{moz:profile=/tmp/rust_mozprofile.qsoDFMATTikn, rotatable=false, timeouts={implicit=0, pageLoad=300000, script=30000}, pageLoadStrategy=normal, moz:headless=false, platform=LINUX, specificationLevel=0, moz:accessibilityChecks=false, acceptInsecureCerts=true, browserVersion=56.0, platformVersion=3.16.0-30-generic, moz:processID=22169, browserName=firefox, javascriptEnabled=true, platformName=LINUX}]
Session ID: 12542456-e71a-40f4-944d-c476840f3c99
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:185)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:120)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
at org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:310)
at com.vodafone.er.cc.test.integration.PlatformLayer.LaunchApplication.Execute(LaunchApplication.java:173)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
at org.testng.TestRunner.beforeRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:616)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
at org.testng.SuiteRunner.run(SuiteRunner.java:261)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.run(TestNG.java:1048)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
===============================================
ER
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 1
===============================================
Attached my full LaunchApplication.java file for more details
package com.vodafone.er.cc.test.integration.PlatformLayer;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
//import java.sql.Date;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import atu.testng.reports.ATUReports;
import atu.testrecorder.ATUTestRecorder;
import atu.testrecorder.exceptions.ATUTestRecorderException;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
/*#Listeners({ ATUReportsListener.class, ConfigurationListener.class,
MethodListener.class })*/
public class LaunchApplication {
{
System.setProperty("atu.reporter.config", "./atu.properties");
}
public static WebDriver driver=null;
ATUTestRecorder recorder;
Date date;
#BeforeTest (alwaysRun = true)
#Parameters({"RunUsingSG","BrowserCode","URL","Title","Platform","Version"})
public void Execute(String RunUsingSG,String BrowserCode,String URL,String Title,String Platform,String Version) throws IOException, InterruptedException, ATUTestRecorderException
{
System.out.println(System.getProperty("user.dir"));
DesiredCapabilities dc=new DesiredCapabilities();
//This code is for recording. if you want to do recording, just uncomment the following code.
/*DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH-mm-ss");
Date date = new Date();
// For Recording the Execution using ATU Reporter.
recorder = new ATUTestRecorder("./ScriptVideos","TestVideo-" +dateFormat.format(date),false);
recorder.start();*/
// For IE 32 Bits
if(BrowserCode.equalsIgnoreCase("IE32"))
{
dc.setBrowserName("internet explorer");
dc.setVersion(Version);
if(RunUsingSG.equalsIgnoreCase("Y"))
{driver=new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),dc);}
else
{
System.setProperty("webdriver.ie.driver",System.getProperty("user.dir")+"/AllDrivers/IEDriverServer_32bit_OS.exe");
driver = new InternetExplorerDriver();
}
}
// For PhantomJS
if(BrowserCode.equalsIgnoreCase("PJS"))
{
dc.setJavascriptEnabled(true);
dc.setVersion(Version);
dc.setBrowserName("Phantom JS");
dc.setCapability("phantomjs.binary", "/AllDrivers/phantomjs");
driver = new PhantomJSDriver(dc);
}
//For IE 64 Bits
if(BrowserCode.equalsIgnoreCase("IE64"))
{
//System.setProperty("webdriver.ie.driver",System.getProperty("user.dir")+"/AllDrivers/IEDriverServer_64bit_OS.exe");
System.setProperty("webdriver.ie.driver",System.getProperty("user.dir")+"/AllDrivers/IEDriverServer_x64_2.41.0/IEDriverServer_V2.41_64bit.exe");
dc.setBrowserName("internet explorer");
dc.setVersion(Version);
if(RunUsingSG.equalsIgnoreCase("Y"))
{
driver=new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),dc);
}
else
{
//System.setProperty("webdriver.ie.driver",System.getProperty("user.dir")+"/AllDrivers/IEDriverServer_64bit_OS.exe");
System.setProperty("webdriver.ie.driver",System.getProperty("user.dir")+"/AllDrivers/IEDriverServer_x64_2.41.0/IEDriverServer_V2.41_64bit.exe");
driver = new InternetExplorerDriver();}
}
/*//For Firefox
if(BrowserCode.equalsIgnoreCase("FF"))
{
FirefoxProfile firefoxProfile = new FirefoxProfile();
dc.setBrowserName("firefox");
//dc.setVersion(Version);
if(RunUsingSG.equalsIgnoreCase("Y"))
{
driver=new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),dc);
}
else
{
driver=new FirefoxDriver();
}
}*/
//For Firefox GeckoDriver
if(BrowserCode.equalsIgnoreCase("FF"))
{
System.setProperty("webdriver.gecko.driver",System.getProperty("user.dir")+"/AllDrivers/geckodriver");
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);
driver.get("URL");
}
// For Chrome
if(BrowserCode.equalsIgnoreCase("CH"))
{
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
dc.setCapability("chrome.binary","./AllDrivers/chromedriver/");
dc.setCapability(ChromeOptions.CAPABILITY, options);
dc.setBrowserName("Google Chrome");
dc.setVersion(Version);
if(RunUsingSG.equalsIgnoreCase("Y"))
{
driver=new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),dc);
}
else
{
System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"/AllDrivers/chromedriver");
driver = new ChromeDriver(dc);
}
}
if(Platform.equalsIgnoreCase("WINDOWS"))
try
{
{dc.setPlatform(org.openqa.selenium.Platform.WINDOWS);}
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.get(URL);
Thread.sleep(3000);
Assert.assertEquals(driver.getTitle(), Title);
driver.manage().window().maximize();
Thread.sleep(2000);
// ATU Reports
ATUReports.setWebDriver(LaunchApplication.driver);
ATUReports.indexPageDescription = "ER-CC Automation Scripts Results.";
}
catch (Exception e)
{
Reporter.log("Exception occured " +e.getMessage());
e.printStackTrace();
Assert.fail();
driver.quit();
}
}
#AfterTest
//#Parameters({"RunUsingSG","BrowserCode","URL","Title","Platform","Version"})
public void TearDown() throws MalformedURLException, ATUTestRecorderException
{
driver.close();
//driver.quit();
//recorder.stop();
}
}

This code dont have any URL
if(BrowserCode.equalsIgnoreCase("FF"))
{
System.setProperty("webdriver.gecko.driver",System.getProperty("user.dir")+"/AllDrivers/geckodriver");
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver(capabilities);
driver.get("URL"); //add it
}

Related

Capture browser network logs running in Sauce labs

Capture browser network logs running in Saucelabs.
I used following code to catpuring browser network logs running in Saucelabs.
Its working in local machine, able to capture logs in local, but not able capture when running in saucelabs.
Here is the code. can anybody please though some light on this?
++++++++++ Local working fine +++++++++
package automation.networklogs;
import net.lightbody.bmp.BrowserMobProxy;
import net.lightbody.bmp.BrowserMobProxyServer;
import net.lightbody.bmp.client.ClientUtil;
import net.lightbody.bmp.core.har.Har;
import net.lightbody.bmp.proxy.CaptureType;
import org.openqa.selenium.By;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
public class NetWorkLogsWithMobProxyLocal {
public static String sFileName = "C:/Users/DELL/Desktop/New folder/harfile2.har";
public static WebDriver driver;
public static BrowserMobProxy proxy;
public static void main(String[] args) throws InterruptedException, MalformedURLException {
try {
proxy = new BrowserMobProxyServer();
proxy.start(0);
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
try {
String hostIp = Inet4Address.getLocalHost().getHostAddress();
seleniumProxy.setHttpProxy(hostIp + ":" + proxy.getPort());
seleniumProxy.setSslProxy(hostIp + ":" + proxy.getPort());
} catch (UnknownHostException e) {
e.printStackTrace();
}
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
System.setProperty("webdriver.chrome.driver", "C:/Users/DELL/IdeaProjects/prodigy-client-repo/zenq/src/test/resources/browser_drivers/chromedriver.exe" );
ChromeOptions options = new ChromeOptions();
options.merge(capabilities);
driver = new ChromeDriver(options);
driver.manage().window().maximize();
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
proxy.newHar("yahoo.com" );
driver.get("https://yahoo.com" );
Thread.sleep(10);
Har har = proxy.getHar();
File harFile = new File(sFileName);
try {
har.writeTo(harFile);
} catch (IOException ex) {
System.out.println(ex.toString());
System.out.println("Could not find file " + sFileName);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("ENTER IN EXCEPTION firstName" );
} finally {
if (driver != null) {
proxy.stop();
driver.quit();
}
}
}
}
+++++++++ ++++++++++ saucelabs not working +++++++++
package automation.networklogs;
import net.lightbody.bmp.BrowserMobProxy;
import net.lightbody.bmp.BrowserMobProxyServer;
import net.lightbody.bmp.client.ClientUtil;
import net.lightbody.bmp.core.har.Har;
import net.lightbody.bmp.proxy.CaptureType;
import org.openqa.selenium.By;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
public class NetWorkLogsWithMobProxySL {
public static String sFileName = "C:/Users/DELL/Desktop/New folder/harfile3.har";
public static WebDriver driver;
public static BrowserMobProxy proxy;
public static void main(String[] args) throws InterruptedException, MalformedURLException {
try {
proxy = new BrowserMobProxyServer();
proxy.start(0);
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
String hostIp = Inet4Address.getLocalHost().getHostAddress();
seleniumProxy.setHttpProxy(hostIp + ":" + proxy.getPort());
seleniumProxy.setSslProxy(hostIp + ":" + proxy.getPort());
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
MutableCapabilities sauceOpts = new MutableCapabilities();
sauceOpts.setCapability("username", "username" );
sauceOpts.setCapability("accessKey", "acceskey" );
sauceOpts.setCapability("seleniumVersion", "3.141.59" );
sauceOpts.setCapability("name", "test" );
sauceOpts.setCapability("proxy", hostIp+":"+proxy.getPort() );
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("browser.visible", true);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
options.merge(capabilities);
MutableCapabilities cap = new MutableCapabilities();
cap.setCapability("sauce:options", sauceOpts);
cap.setCapability("goog:chromeOptions", options);
cap.setCapability("platformName", "Windows 10" );
cap.setCapability("browserName", "chrome" );
cap.setCapability("browserVersion", "latest" );
String sauceURL = "https://ondemand.saucelabs.com:443/wd/hub";
driver = new RemoteWebDriver(new URL(sauceURL), cap);
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
proxy.newHar("yahoo.com" );
driver.get("https://yahoo.com" );
Thread.sleep(10);
Har har = proxy.getHar();
File harFile = new File(sFileName);
try {
har.writeTo(harFile);
} catch (IOException ex) {
System.out.println(ex.toString());
System.out.println("Could not find file " + sFileName);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("ENTER IN EXCEPTION firstName" );
} finally {
if (driver != null) {
proxy.stop();
driver.quit();
}
}
}
}
+++++++++ got below error for running in Saucelabs
log4j:WARN No appenders could be found for logger (io.netty.util.internal.logging.InternalLoggerFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Sep 17, 2020 12:20:09 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
org.openqa.selenium.WebDriverException: unknown error: net::ERR_PROXY_CONNECTION_FAILED
(Session info: chrome=85.0.4183.83)
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: 'RAVILAPTOP', ip: '192.168.147.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_77'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities [{networkConnectionEnabled=false, chrome={chromedriverVersion=85.0.4183.38 (9047dbc2c693f044042bbec5c91401c708c7c26a-refs/branch-heads/4183#{#779}), userDataDir=C:\Users\ADMINI~1\AppData\Local\Temp\scoped_dir2300_1366152112}, timeouts={implicit=0, pageLoad=300000, script=30000}, pageLoadStrategy=normal, unhandledPromptBehavior=dismiss and notify, strictFileInteractability=false, platform=WINDOWS, proxy=Proxy(manual, http=192.168.147.1:59693, ssl=192.168.147.1:59693), goog:chromeOptions={debuggerAddress=localhost:49770}, browserVersion=85.0.4183.83, acceptInsecureCerts=false, browserName=chrome, javascriptEnabled=true, platformName=WINDOWS, setWindowRect=true, webauthn:virtualAuthenticators=true}]
Session ID: ebf16fbb5f7a4f5d8a91755b8a0966f9
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:185)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:120)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
at org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:310)
at automation.networklogs.NetWorkLogsWithMobProxySL.main(NetWorkLogsWithMobProxySL.java:77)
You're getting org.openqa.selenium.WebDriverException: unknown error: net::ERR_PROXY_CONNECTION_FAILED because BrowserMob Proxy is running on your local machine, and is completely inaccessible from the Sauce Labs browser.
Normally, to access local-only resources during a test on Sauce Labs, you'd use Sauce Connect. That won't work here, because Sauce Connect is itself configured as a system proxy for the browser under test. If you configure a different proxy using Selenium's proxy settings, Sauce Connect will no longer work.
You can do one of two things. The complicated solution is to set up Sauce Connect, and configure it so that the client you run on your machine uses BrowserMob Proxy. There's some documentation on here.
The second, and much easier solution, is to use extended debugging. Then, Sauce Labs'll automatically capture the HAR file for you, along with JS Console logging. As long as the platform you're testing with supports it, you'll just have to add the desired capability extendedDebugging and set it to true. After a test is finished, you can download the HAR file from the REST API or Web UI.
(If you're using BrowserMob Proxy to alter requests as they come through, then you might find extended debugging's traffic editing useful... Although I personally recommend avoiding this kind of fiddling in tests as much as possible.)

Unable To Perform Actions In Appium Because PageFactory Not Identified

I want to launch and perform actions like enter username details in application
but my execution is failing again and again because of error
My Code
public class VerifyProjectFromApp {
WebDriver driver;
AppLaunch toDoistAppLaunch;
HomePage homePage;
LoginPage login;
#BeforeMethod
public void startapplication() {
toDoistAppLaunch= new AppLaunch(driver);
this.driver=toDoistAppLaunch.launchApplication();
}
#Test
public void verifyCreatedProjectInApp() {
try{
//-Read create project value from properties file
Properties prop = new Properties();
InputStream input = null;
input = new FileInputStream(System.getProperty("user.dir") +
File.separator +"TodoistInputData.properties");
prop.load(input);
//-Read uuid from properties file
String email_id = prop.getProperty("email_id");
System.out.println("\t" + "email_id =" + email_id + "\r\n");
//-Read project name from properties file
String password = prop.getProperty("password");
System.out.println("\t" + "projectName =" + password + "\r\n");
login = new LoginPage(driver);
homePage = new HomePage(driver);
login.loginInApplication(email_id, password);
Utils.waitForPageLoadingToComplete(driver);
homePage.clickOnSideMenu();
Utils.pauseTestExecution(10);
} catch (Exception e) {
e.printStackTrace();
}
}
===================================================
public class LoginPage {
public static final String packageName = "com.todoist";
AndroidDriver<MobileElement> driver;
public LoginPage(WebDriver driver){
this.driver = (AndroidDriver<MobileElement>)driver;
PageFactory.initElements(new AppiumFieldDecorator(driver), this);
}
#AndroidFindBy(id=packageName+":id/btn_welcome_continue_with_email")
MobileElement continueButtonWithGmail;
#AndroidFindBy(id=packageName+":id/email_exists_input")
MobileElement enterEmailId;
#AndroidFindBy(id=packageName+":id/log_in_password")
MobileElement enterPassword;
#AndroidFindBy(id=packageName+":id/btn_continue_with_email")
MobileElement loginwithGmail;
#AndroidFindBy(id=packageName+":id/btn_log_in")
MobileElement loginButton;
public void clickOnContinueButtonWithGmail() {
continueButtonWithGmail.click();
}
public void enterEmailAddress(String emailId) {
enterEmailId.sendKeys(emailId);
}
public void enterPassword(String pass) {
enterPassword.sendKeys(pass);
}
public void clickOnGmailButton() {
loginwithGmail.click();
}
public void clickOnLoginButton() {
loginButton.click();
}
public void loginInApplication(String emailId,String password) {
try {
clickOnContinueButtonWithGmail();
Utils.waitForPageLoadingToComplete(driver);
enterEmailAddress(emailId);
Utils.waitForPageLoadingToComplete(driver);
clickOnGmailButton();
Utils.waitForPageLoadingToComplete(driver);
enterPassword(password);
Utils.waitForPageLoadingToComplete(driver);
clickOnLoginButton();
} catch(Exception e) {
e.printStackTrace();
}
}
=============================================================================================
Error Coming
[TestNG] Running:
C:\Users\Daffodil-255\AppData\Local\Temp\testng-eclipse--467741697\testng-customsuite.xml
Print app path E:\TodoistAutomation\Android_Todoist_Project\apkfile\Todoist_v12.8_apkpure.com.apk
Jul 25, 2018 11:57:52 AM io.appium.java_client.remote.AppiumCommandExecutor$1 lambda$0
INFO: Detected dialect: W3C
email_id =tarun.dabbs#daffodilsw.com
projectName =123456
Jul 25, 2018 11:57:52 AM org.openqa.selenium.remote.ErrorCodes toStatus
INFO: HTTP Status: '404' -> incorrect JSON status mapping for 'unknown method' (405 expected)
FAILED CONFIGURATION: #AfterMethod closeApplication
org.openqa.selenium.UnsupportedCommandException: Method has not yet been implemented
Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:32:14.902Z'
System info: host: 'DAFFODILLAP-265', ip: '172.18.1.128', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_65'
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities {app: E:\TodoistAutomation\Androi..., appActivity: com.todoist.activity.HomeAc..., appPackage: com.todoist, appium-version: 1.8.1, databaseEnabled: false, desired: {app: E:\TodoistAutomation\Androi..., appActivity: com.todoist.activity.HomeAc..., appPackage: com.todoist, appium-version: 1.8.1, deviceName: Nexus5X1, platformName: android, platformVersion: 7.1.1}, deviceManufacturer: Google, deviceModel: Android SDK built for x86, deviceName: emulator-5554, deviceScreenSize: 1080x1920, deviceUDID: emulator-5554, javascriptEnabled: true, locationContextEnabled: false, networkConnectionEnabled: true, platform: LINUX, platformName: Android, platformVersion: 7.1.1, takesScreenshot: true, warnings: {}, webStorageEnabled: false}
Session ID: 7333c28b-2ec8-48b2-89c0-b04e2c90ec74
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:231)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:46)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
at org.openqa.selenium.remote.RemoteWebDriver.close(RemoteWebDriver.java:438)
at com.todoist.tests.VerifyProjectFromApp.closeApplication(VerifyProjectFromApp.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:703)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:774)
at org.testng.TestRunner.run(TestRunner.java:624)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
at org.testng.SuiteRunner.run(SuiteRunner.java:261)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.run(TestNG.java:1048)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
FAILED: verifyCreatedProjectInApp
java.lang.NoClassDefFoundError: net/sf/cglib/proxy/MethodInterceptor
at com.todoist.pages.LoginPage.<init>(LoginPage.java:22)
at com.todoist.tests.VerifyProjectFromApp.verifyCreatedProjectInApp(VerifyProjectFromApp.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:774)
at org.testng.TestRunner.run(TestRunner.java:624)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
at org.testng.SuiteRunner.run(SuiteRunner.java:261)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.run(TestNG.java:1048)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
Caused by: java.lang.ClassNotFoundException: net.sf.cglib.proxy.MethodInterceptor
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 26 more
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
Configuration Failures: 1, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
Configuration Failures: 1, Skips: 0
===============================================
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter#19bb089b: 171 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter#35bbe5e8: 14 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter#6bdf28bb: 8 ms
[TestNG] Time taken by org.testng.reporters.jq.Main#1fbc7afb: 65 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2#129a8472: 15 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 11 ms
Issue happens due this:
ClassNotFoundException: net.sf.cglib.proxy.MethodInterceptor
to fix this you need to add cglib:cglib dependency:
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.7</version>
</dependency>
hope this helps,
Add both cglib and asm dependency in your project. This will solve your problem.
cglib-3.2.7.jar
asm-6.2.jar

The same Test Suite is passed on IDEA, but fails when running on Teamcity

Need a help. I have the same test suite. I have run this test suite in IDEA on my local machine. And the tests are passed. Then I run this test suite in TeamCity. The tests are failed with the next stack trace:
======= Failed test run #1 ==========
org.openqa.selenium.ElementNotVisibleException: element not visible
(Session info: chrome=54.0.2840.71)
(Driver info: chromedriver=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 18 milliseconds
Build info: version: 'unknown', revision: '31c43c8', time: '2016-08-02 21:57:56 -0700'
System info: host: 'build', ip: '175.35.15.235', os.name: 'Windows Server 2012 R2', os.arch: 'x86', os.version: '6.3', java.version: '1.8.0_66'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf), userDataDir=C:\TeamCity\buildAgent\temp\buildTmp\scoped_dir948_4499}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=54.0.2840.71, platform=WIN8_1, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: e69e7517d0cc60ff138519603c9efe99
org.openqa.selenium.ElementNotVisibleException:
element not visible
(Session info: chrome=54.0.2840.71)
(Driver info: chromedriver=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 18 milliseconds
Build info: version: 'unknown', revision: '31c43c8', time: '2016-08-02 21:57:56 -0700'
System info: host: 'build', ip: '175.35.15.235', os.name: 'Windows Server 2012 R2', os.arch: 'x86', os.version: '6.3', java.version: '1.8.0_66'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf), userDataDir=C:\TeamCity\buildAgent\temp\buildTmp\scoped_dir948_4499}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=54.0.2840.71, platform=WIN8_1, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: e69e7517d0cc60ff138519603c9efe99
at com.automation.webdriver.testStoryReportsNavigation.policiesWithPremium(testStoryReportsNavigation.java:122)
122 line of code like this:
driver.findElement (By.xpath ( "// * [# id = \" 0 \ "]")) click ();
(No matter for xpath looking for, or id - in TeamCity the same result)
In what may be the cause of this error?
Tests are run with agent on the same machine that serves TeamCity.
There is a code:
package com.automation.webdriver;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.server.handler.CaptureScreenshot;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.ITestResult;
import org.testng.annotations.*;
import pageObjects.homePage;
import utility.Constant;
import utility.ExcelUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class testStoryReportsNavigation {
public WebDriver driver;
private int storyNumber;
private String storyDescription;
#Factory(dataProvider = "dataMethod", dataProviderClass = dataProvider.class)
public testStoryReportsNavigation(int storyNumber, String storyDescription) {
this.storyNumber = storyNumber;
this.storyDescription = storyDescription;
}
#BeforeMethod
public void beforeClass() throws Exception {
System.setProperty(Constant.chromeDriver,Constant.chromeDriverPath);
driver = new ChromeDriver();
ExcelUtils.setExcelFile(Constant.File_userData,"Users");
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get(Constant.devUrl + Constant.loginPage);
WebDriverWait waitLoginPage = new WebDriverWait(driver, 10);
waitLoginPage.until(ExpectedConditions.titleIs("Log in Milliman"));
if (driver.findElements(By.className("glimpse-icon")).size()!=0) {
driver.get(Constant.devUrl + Constant.glimpseSettings);
driver.findElement(By.id("buttonTurnGlimpseOff")).click();
driver.getPageSource().contains("Glimpse cookie set 'Off'");
driver.get(Constant.devUrl + Constant.loginPage);
} else {
System.out.println("Glimpse disabled");
}
WebDriverWait waitLoginPageAgain = new WebDriverWait(driver, 10);
waitLoginPageAgain.until(ExpectedConditions.titleIs("Log in Milliman"));
WebElement eMail = driver.findElement(By.id("Email"));
eMail.sendKeys(ExcelUtils.getCellData(1, 1));
WebElement password = driver.findElement(By.id("Password"));
password.sendKeys(ExcelUtils.getCellData(1, 2));
password.submit();
//Check that Grid View appears after user login:
WebDriverWait wait = new WebDriverWait(driver, 3);
wait.until(ExpectedConditions.urlContains(Constant.gridView));
System.out.println("Login Successful");
//Navigate to Story
System.out.println("Navigating to " + Constant.devUrl + Constant.storyPage + storyNumber + "(" + storyDescription + ")");
driver.get(Constant.devUrl + Constant.storyPage + storyNumber);
WebDriverWait waitLogout = new WebDriverWait(driver, 20);
waitLogout.until(ExpectedConditions.elementToBeClickable(By.className("FiltersShortSummaryBlock")));
//Check that story loaded
driver.findElement(By.className("FiltersShortSummaryBlock")).click();
WebDriverWait waitUrButton = new WebDriverWait(driver, 20);
waitUrButton.until(ExpectedConditions.elementToBeClickable(By.id("UpdateResults")));
//Select Data Source value
driver.findElement(By.xpath("//*[#id=\"PanelGeneral\"]/table/tbody/tr[2]/td[1]/table/tbody/tr[1]/td[2]/button")).click();
WebDriverWait waitDataSource = new WebDriverWait(driver, 10);
waitDataSource.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(), 'Market Basket')]")));
driver.findElement(By.xpath("//span[contains(text(), 'Market Basket')]")).click();
//Select Primary Carrier value
driver.findElement(By.xpath("//*[#id=\"PanelGeneral\"]/table/tbody/tr[2]/td[1]/table/tbody/tr[3]/td[2]/button")).click();
driver.findElement(By.xpath("/html/body/div[60]/ul/li[2]/label")).click();
//Select Secondary Carriers value
driver.findElement(By.xpath("//*[#id=\"PanelGeneral\"]/table/tbody/tr[2]/td[1]/table/tbody/tr[4]/td[2]/button")).click();
driver.findElement(By.xpath("/html/body/div[14]/div/ul/li[1]/a/span[2]")).click();
//Click Update Results button
WebDriverWait waitButton = new WebDriverWait(driver, 30);
waitButton.until(ExpectedConditions.elementToBeClickable(By.id("UpdateResults")));
WebElement updateResults = driver.findElement(By.id("UpdateResults"));
updateResults.click();
//Check that Results were updated
WebDriverWait waitUpdateResults = new WebDriverWait(driver, 30);
waitUpdateResults.until(ExpectedConditions.elementToBeClickable(By.id("storyUnsaved")));
}
#Test (priority = 11)
public void policiesWithPremium() throws Exception {
//Generate report #0 and check that it was generated
driver.findElement(By.xpath("//*[#id=\"0\"]")).click();
//Check that report #0 was generated
WebDriverWait waitReportZero = new WebDriverWait(driver, 120);
waitReportZero.until(ExpectedConditions.visibilityOfElementLocated(By.id("RiskWithPremiumForm")));
}

ClassNotFoundException using JavaMail

I have created a new project in Netbeans, where I set up a servlet (Tomcat 8) and I want to implement a way to send email with gmail. I found many examples (like this). I created a class
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
final String username = "mymail#gmail.com";
final String password = "pass";
public SendMail() {
}
public void send(){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, //<- points1 here
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
and in the servlet I called that method
SendMail send = new SendMail();
send.send(); //<- points 2
And I get an error: java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [MyServlet] in context with path [/MyServlet] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1295)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1147)
at javax.mail.Session.initLogger(Session.java:227)
at javax.mail.Session.<init>(Session.java:212)
at javax.mail.Session.getInstance(Session.java:248)
at com.myPackage.MyServlet.SendMail.send(SendMail.java:35) //->points 1
at com.myPackage.MyServlet.MyServlet.processRequest(MyServlet.java:77) //->points 2
at com.myPackage.MyServlet.MyServlet.doGet(MyServlet.java:266)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.myPackage.MyServlet.LogFilter.doFilter(LogFilter.java:22)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:724)
I have added the 2 jars javaee.jar and mail.jar in my project.
You are mixing multiple versions of JavaMail. The javaee.jar only includes the API classes for compiling not execution. The mail.jar is going to be an old version of JavaMail. If you require just JavaMail then download the javax.mail.jar and use that instead.

Generate JFreeChart in servlet

I'm trying to generate graphs using JFreeChart. I added record in web.xml, installed jfreechart library. Compiled servlet. Below code of servlet has shown:
import java.io.IOException;
import java.io.OutputStream;
import java.io.File;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.Color;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
public class diagram extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doTestPieChart(request,response);
}
protected void doTestPieChart(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
OutputStream out = response.getOutputStream();
try
{
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("Graphic Novels", 192);
dataset.setValue("History", 125);
dataset.setValue("Military Fiction", 236);
dataset.setValue("Mystery", 547);
dataset.setValue("Performing Arts", 210);
dataset.setValue("Science, Non-Fiction", 70);
dataset.setValue("Science Fiction", 989);
JFreeChart chart = ChartFactory.createPieChart(
"Books by Type",
dataset,
true,
false,
false
);
chart.setBackgroundPaint(Color.white);
response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(out, chart, 400, 300);
/*
ServletContext sc = getServletContext();
String filename = sc.getRealPath("pie.png");
File file = new File(filename);
ChartUtilities.saveChartAsPNG(file,chart,400,300);
*/
}
catch (Exception e)
{
System.out.println(e.toString());
}
finally
{
out.close();
}
}
}
When i launch the servlet, mistake has shown :
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class diagram
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Thread.java:619)
root cause
java.lang.NoClassDefFoundError: org/jfree/data/general/PieDataset
java.lang.Class.getDeclaredConstructors0(Native Method)
java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
java.lang.Class.getConstructor0(Class.java:2699)
java.lang.Class.newInstance0(Class.java:326)
java.lang.Class.newInstance(Class.java:308)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Thread.java:619)
root cause
java.lang.ClassNotFoundException: org.jfree.data.general.PieDataset
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1484)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1329)
java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316)
java.lang.Class.getDeclaredConstructors0(Native Method)
java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
java.lang.Class.getConstructor0(Class.java:2699)
java.lang.Class.newInstance0(Class.java:326)
java.lang.Class.newInstance(Class.java:308)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Thread.java:619)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.24 logs.
Help me to solve a problem. and where is problem?
Make sure you have JFreeChart jar inside your
WEB-INF/lib
directory or your WAR deployment file.

Resources