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.
Related
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.)
I am trying to call Web Service that is based on IIS WPF and its WSDL has following policy:
<wsp:Policy wsu:Id="custom_policy">
<wsp:ExactlyOne>
<wsp:All>
<sp:TransportBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<wsp:Policy>
<sp:TransportToken>
<wsp:Policy>
<sp:HttpsToken RequireClientCertificate="false"/>
</wsp:Policy>
</sp:TransportToken>
<sp:AlgorithmSuite>
<wsp:Policy>
<sp:Basic256/>
</wsp:Policy>
</sp:AlgorithmSuite>
<sp:Layout>
<wsp:Policy>
<sp:Strict/>
</wsp:Policy>
</sp:Layout>
<sp:IncludeTimestamp/>
</wsp:Policy>
</sp:TransportBinding>
<sp:SignedSupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<wsp:Policy>
<sp:UsernameToken sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
<wsp:Policy>
<sp:WssUsernameToken10/>
</wsp:Policy>
</sp:UsernameToken>
</wsp:Policy>
</sp:SignedSupportingTokens>
<sp:Wss11 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<wsp:Policy/>
</sp:Wss11>
<sp:Trust10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<wsp:Policy>
<sp:MustSupportIssuedTokens/>
<sp:RequireClientEntropy/>
<sp:RequireServerEntropy/>
</wsp:Policy>
</sp:Trust10>
<wsaw:UsingAddressing/>
</wsp:All>
</wsp:ExactlyOne>
</wsp:Policy>
with Apache CXF client and following code:
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(ITerytWs1.class);
factory.setAddress("https://uslugaterytws1test.stat.gov.pl/terytws1.svc");
ITerytWs1 info = (ITerytWs1) factory.create();
Map ctx = ((BindingProvider)info).getRequestContext();
ctx.put("ws-security.username", "TestPubliczny");
ctx.put("ws-security.password", "1234abcd");
ctx.put("ws-security.callback-handler", ClientPasswordCallback.class.getName());
var zal = info.isLoggedIn();
Dependencies are:
compile group: 'org.apache.cxf', name: 'cxf-rt-frontend-jaxws', version: '3.3.7'
compile group: 'org.apache.cxf', name: 'cxf-rt-transports-http', version: '3.3.7'
compile group: 'com.sun.activation', name: 'javax.activation', version: '1.2.0'
compile group: 'org.apache.cxf', name: 'cxf-rt-ws-security', version: '3.3.7'
compile group: 'com.sun.xml.messaging.saaj', name: 'saaj-impl', version: '1.5.2'
I receive only Read time out:
lip 16, 2020 1:58:31 PM org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
WARNING: Interceptor for {http://tempuri.org/}ITerytWs1Service#{http://tempuri.org/}CiekawostkiSIMC has thrown exception, unwinding now
org.apache.cxf.interceptor.Fault: Could not receive Message.
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:65)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:530)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:441)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:356)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:314)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
[...]
Caused by: java.net.SocketTimeoutException: SocketTimeoutException invoking https://uslugaterytws1test.stat.gov.pl/terytws1.svc: Read timed out
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[..]
Caused by: java.net.SocketTimeoutException: Read timed out
at java.base/java.net.SocketInputStream.socketRead0(Native Method)
[...]
Could not receive Message.
javax.xml.ws.WebServiceException: Could not receive Message.
at org.apache.cxf.jaxws.JaxWsClientProxy.mapException(JaxWsClientProxy.java:183)
[...]
Caused by: java.net.SocketTimeoutException: SocketTimeoutException invoking https://uslugaterytws1test.stat.gov.pl/terytws1.svc: Read timed out
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[...]
How to configure this WS policy right and is it the problem of client or something else?
I had to use SoapUI to check what kind of envelope is sent to the service to get the right answer, then I had to do the same with the code. Problem before was that wrong request was sent to the server and server got internal exception (probably) and has not returned answer of bad request.
This is what I have done with the class:
import lombok.Getter;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.ws.addressing.WSAddressingFeature;
import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.dom.handler.WSHandlerConstants;
import org.tempuri.ITerytWs1;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;
public class WebServiceClient {
#Getter
private ITerytWs1 service;
private final ApiClientConfiguration apiClientConfiguration;
private final ClientPasswordCallback clientPasswordCallback;
#Inject
public WebServiceClient(ApiClientConfiguration apiClientConfiguration) {
this.apiClientConfiguration = apiClientConfiguration;
this.clientPasswordCallback = new ClientPasswordCallback(apiClientConfiguration);
initializeService();
configureService();
}
private void configureService() {
var client = ClientProxy.getClient(service);
var endpoint = client.getEndpoint();
Map<String, Object> outInterceptorProperties = createOutInterceptorProperties();
var wssOutInterceptor = new WSS4JOutInterceptor(outInterceptorProperties);
endpoint.getOutInterceptors().add(wssOutInterceptor);
}
private void initializeService() {
var factory = new JaxWsProxyFactoryBean();
var wsAddressingFeature = new WSAddressingFeature();
factory.getFeatures().add(wsAddressingFeature);
factory.setServiceClass(ITerytWs1.class);
factory.setAddress(apiClientConfiguration.getAddress());
service = (ITerytWs1) factory.create();
}
private Map<String, Object> createOutInterceptorProperties() {
Map<String,Object> outInterceptorProperties = new HashMap<>();
outInterceptorProperties.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
outInterceptorProperties.put(WSHandlerConstants.USER, apiClientConfiguration.getUsername());
outInterceptorProperties.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
outInterceptorProperties.put(WSHandlerConstants.ADD_USERNAMETOKEN_NONCE, "true");
outInterceptorProperties.put(WSHandlerConstants.ADD_USERNAMETOKEN_CREATED, "true");
outInterceptorProperties.put(WSHandlerConstants.MUST_UNDERSTAND, "false");
// Callback used to retrieve password for given user.
outInterceptorProperties.put(WSHandlerConstants.PW_CALLBACK_REF, clientPasswordCallback);
return outInterceptorProperties;
}
}
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
}
I am creating a Java EE application using jpa.
The problem in #PersistenceContext(unitName = "airline") when i comment this line it give me error null_pointer_exception and when put it getting the following error when the code is run on server.
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Severe: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method
Severe: java.lang.RuntimeException: Could not resolve a persistence unit corresponding to the persistence-context-ref-name [com.airline.service.PassengerService/entityManager] in the scope of the module called [FlightPassengersJPA]. Please verify your application.
at com.sun.enterprise.deployment.BundleDescriptor.findReferencedPUViaEMRef(BundleDescriptor.java:731)
at com.sun.enterprise.deployment.BundleDescriptor.findReferencedPUsViaPCRefs(BundleDescriptor.java:719)
at org.glassfish.web.deployment.descriptor.WebBundleDescriptorImpl.findReferencedPUs(WebBundleDescriptorImpl.java:1037)
at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:186)
at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:925)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:434)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:748)
Severe: Exception while preparing the app
Severe: Exception during lifecycle processing
java.lang.RuntimeException: Could not resolve a persistence unit corresponding to the persistence-context-ref-name [com.airline.service.PassengerService/entityManager] in the scope of the module called [FlightPassengersJPA]. Please verify your application.
at com.sun.enterprise.deployment.BundleDescriptor.findReferencedPUViaEMRef(BundleDescriptor.java:731)
at com.sun.enterprise.deployment.BundleDescriptor.findReferencedPUsViaPCRefs(BundleDescriptor.java:719)
at org.glassfish.web.deployment.descriptor.WebBundleDescriptorImpl.findReferencedPUs(WebBundleDescriptorImpl.java:1037)
at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:186)
at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:925)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:434)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:748)
Severe: Exception while preparing the app : Could not resolve a persistence unit corresponding to the persistence-context-ref-name [com.airline.service.PassengerService/entityManager] in the scope of the module called [FlightPassengersJPA]. Please verify your application.
and my code :
AddPassenger.java
package com.airline.controllers;
import com.airline.models.FlightClass;
import com.airline.models.Gender;
import com.airline.models.Passenger;
import com.airline.service.PassengerService;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "AddPassenger", urlPatterns = {"/AddPassenger"})
public class AddPassenger extends HttpServlet {
#EJB
private PassengerService passengerService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
Passenger passenger = new Passenger();
passenger.setFirstName("Loai");
passenger.setLastName("Amr");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1996);
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.DAY_OF_MONTH, 30);
Date dob = cal.getTime();
passenger.setDob(dob);
passenger.setGender(Gender.Male);
passenger.setFlightClass(FlightClass.Couch);
passengerService.addPassenger(passenger);
System.out.println("First name : " + passenger.getFirstName());
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
and class PassengerService :
package com.airline.service;
import com.airline.models.Passenger;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
#Stateless
#LocalBean
public class PassengerService {
public PassengerService() {
}
#PersistenceContext(unitName = "airline")
private EntityManager entityManager;
public void addPassenger(Passenger passenger) {
entityManager.persist(passenger);
System.out.println("Done");
}
}
and persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="FlightPassengersJPAPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/airline</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
You need to define your persistence-unit in a file named persistence.xml. This should reside as resource in META-INF.
An example for that you can see in:
persistence.xml... The datasources you see there is defined in the configuration of the wildfly as you can see it in standalone.xml
In a similar way I think you have do define the datasource in glassfish.
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.