How to use MQTT.fx to connect to IOT central? - azure-iot-hub

I am trying to use MQTT directly to connect to IOT central.
I just followed below documentation,
https://learn.microsoft.com/en-us/azure/iot-central/concepts-connectivity#connect-a-single-device
https://www.instructables.com/id/Azure-IoT-Hub-Set-Up-MQTTfx-Sigfox-Callback-and-Dr/
https://github.com/MediaTek-Labs/aws_mbedtls_mqtt/pull/9/files?short_path=04c6e90
https://docs.azure.cn/zh-cn/articles/azure-operations-guide/iot-hub/aog-iot-hub-howto-connect-with-tool-mqtt-fx (Translate to english)
Above documentation I used dps_cstr tool from github to generate connection string with SAS token from this link
https://learn.microsoft.com/en-us/azure/iot-central/tutorial-add-device#prepare-the-client-code
Broker Address = saas-iothub-947867dc-cd5d-446c-90ff-e0f964f020fe.azure-devices.net
Broker port = 8883
Client ID = 92ff3e25-00e5-4249-9074
User Name = saas-iothub-947867dc-cd5d-446c-90ff.azure-devices.net/92ff3e25-00e5-4249-9074
MQTT Version = 3.1.1
Password = OfAlY0BGstmuinZzOcdDDf
I have configured the MQTT.fx with connection profile for iot central by using above connection string and details.
Attached the snap of that
When i try to connect to this, I am getting an error "Not authorized to connect".
Log:
2018-12-20 00:42:49,738 INFO --- BrokerConnectorController : onConnect
2018-12-20 00:42:49,740 INFO --- ScriptsController : Clear console.
2018-12-20 00:42:49,804 INFO --- MqttFX ClientModel : MqttClient with ID 92ff3e25-00e5-4249-9074-854b43b5a949 assigned.
2018-12-20 00:42:53,571 ERROR --- MqttFX ClientModel : Error when connecting
org.eclipse.paho.client.mqttv3.MqttSecurityException: Not authorized to connect
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:988) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:145) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.FutureTask.run(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_181]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_181]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_181]
2018-12-20 00:42:53,572 ERROR --- MqttFX ClientModel : Please verify your Settings (e.g. Broker Address, Broker Port & Client ID) and the user credentials!
org.eclipse.paho.client.mqttv3.MqttSecurityException: Not authorized to connect
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:988) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:145) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.FutureTask.run(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_181]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_181]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_181]
2018-12-20 00:42:53,574 INFO --- ScriptsController : Clear console.
2018-12-20 00:42:53,574 ERROR --- BrokerConnectService : Not authorized to connect
EDIT:
I created a CA certificate from https://github.com/Azure/azure-iot-sdk-c/blob/master/certs/certs.c as CACert.cer
I selected CS Certificate file option in SSL/TLS option and tried again.
But i have got the same error

I have just finished a test using a MQTT.fx client connected to the Azure IoT Central.
Based on the doc Using the MQTT protocol directly the password must be in the following format, see example:
SharedAccessSignature sr={your hub name}.azure-devices.net%2Fdevices%2FMyDevice01%2Fapi-version%3D2016-11-14&sig=vSgHBMUG.....Ntg%3d&se=1456481802
You have to generate the above password (sas token) string. You can use the following helper function:
string sasToken = SharedAccessSignatureBuilder.GetSASTokenFromConnectionString(connectionString);
public sealed class SharedAccessSignatureBuilder
{
public static string GetHostNameNamespaceFromConnectionString(string connectionString)
{
return GetPartsFromConnectionString(connectionString)["HostName"].Split('.').FirstOrDefault();
}
public static string GetSASTokenFromConnectionString(string connectionString, uint hours = 24)
{
var parts = GetPartsFromConnectionString(connectionString);
return GetSASToken(parts["HostName"], parts["SharedAccessKey"], parts.Keys.Contains("SharedAccessKeyName") ? parts["SharedAccessKeyName"] : null, hours);
}
public static string GetSASToken(string resourceUri, string key, string keyName = null, uint hours = 24)
{
var expiry = GetExpiry(hours);
string stringToSign = System.Web.HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(key));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}", HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry);
if(!string.IsNullOrEmpty(keyName))
sasToken += String.Format(CultureInfo.InvariantCulture, "&skn={0}", keyName);
return sasToken;
}
#region Helpers
private static Dictionary<string, string> GetPartsFromConnectionString(string connectionString)
{
return connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Split(new[] { '=' }, 2)).ToDictionary(x => x[0].Trim(), x => x[1].Trim());
}
// default expiring = 24 hours
private static string GetExpiry(uint hours = 24)
{
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
return Convert.ToString((int)sinceEpoch.TotalSeconds + 3600 * hours);
}
#endregion
}
The following screen snippets show the MQTT.fx device (myfirstdevice) connected to the Azure IoT Central and the device Dashboard.

Related

CXF SSL configuration for consuming SOAP webservice

Overview
I am going to set SSL configuration for calling a SOAP webservice.
Certificate info:
Certificate file: sureft.p12
Password: sureft
CXF configuration file (cxf.xml):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:sec="http://cxf.apache.org/configuration/security"
xmlns:http="http://cxf.apache.org/transports/http/configuration"
xmlns:jaxws="http://java.sun.com/xml/ns/jaxws" xmlns:cxf="http://www.springframework.org/schema/c"
xsi:schemaLocation="
http://cxf.apache.org/configuration/security
http://cxf.apache.org/schemas/configuration/security.xsd
http://cxf.apache.org/transports/http/configuration
http://cxf.apache.org/schemas/configuration/http-conf.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<http:conduit name="{http://tmr.qld.gov.au/srvc/getregistrationstatus/v2_0}GetRegistrationStatusPort.http-conduit">
<http:tlsClientParameters>
<sec:keyManagers keyPassword="sureft">
<sec:keyStore type="pksc12" password="sureft"
file="keystore/sureft.p12"/>
</sec:keyManagers>
</http:tlsClientParameters>
<http:client AutoRedirect="true" Connection="Keep-Alive"/>
</http:conduit>
</beans>
Issue
However, when the webservice invoked it throws 403:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 403: Forbidden
I had a look on http://cxf.apache.org/docs/client-http-transport-including-ssl-support.html but I couldn't solve the isse.
Now I would be grateful if anyone can help me find solution for this problem.
Update Level 1:
I did the following changes but again 403 raised:
. Creating truststore:
Export Create cer file with name myCert.cer from sureft.p12
Create truststore certificate with name of myTruststore.jks by running: keytool -import -file myCert.cer -alias firstCA -keystore myTrustStore.jks
Changing cxf.xml file as follows to add truststore:
...
<http:tlsClientParameters>
<sec:keyManagers keyPassword="sureft">
<sec:keyStore type="pkcs12" password="sureft"
file="keystore/sureft.p12"/>
</sec:keyManagers>
<sec:trustManagers>
<sec:keyStore type="JKS" password="123456"
file="keystore/myTrustStore.jks"/>
</sec:trustManagers>
</http:tlsClientParameters>
...
Update Level 2
I changed my code as following and the 403 solved but another issue raised:
#RequestMapping(method = RequestMethod.GET)
public void getBillInfo2(String plateNumber) {
QName qname = new QName("http://testURL/srvc/getregistrationstatus/v2_0/", "GetRegistrationStatusService");
URL wsdl = getClass().getResource("wsdl/test.getregistrationstatus.v2_0.wsdl");
GetRegistrationStatusService service = new GetRegistrationStatusService(wsdl, qname);
GetRegistrationStatus registrationStatus = service.getPort(qname, GetRegistrationStatus.class);
Client client = ClientProxy.getClient(registrationStatus);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(36000);
httpClientPolicy.setAllowChunking(false);
httpClientPolicy.setReceiveTimeout(32000);
httpClientPolicy.setContentType("application/soap+xml; charset=utf-8");
http.setClient(httpClientPolicy);
GetRegistrationStatusRequest request = new GetRegistrationStatusRequest();
request.setPlateNo(plateNumber);
GetRegistrationStatusResponse result = registrationStatus.execute(request);
log.debug(result.toString());
}
The Exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.xml.ws.soap.SOAPFaultException: Fault string, and possibly fault code, not set
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:980)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.ShallowEtagHeaderFilter.doFilterInternal(ShallowEtagHeaderFilter.java:87)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at com.blss.trails.registration.RegistrationSearchInvocationTest.test(RegistrationSearchInvocationTest.java:47)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: javax.xml.ws.soap.SOAPFaultException: Fault string, and possibly fault code, not set
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:161)
at com.sun.proxy.$Proxy104.execute(Unknown Source)
at com.blss.trails.registration.RegistrationSearchInvocation.getBillInfo2(RegistrationSearchInvocation.java:72)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
... 46 more
Caused by: java.lang.NullPointerException
at org.apache.cxf.transport.http.URLConnectionHTTPConduit.createConnection(URLConnectionHTTPConduit.java:104)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit.setupConnection(URLConnectionHTTPConduit.java:117)
at org.apache.cxf.transport.http.HTTPConduit.prepare(HTTPConduit.java:497)
at org.apache.cxf.interceptor.MessageSenderInterceptor.handleMessage(MessageSenderInterceptor.java:46)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:514)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:423)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:324)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:277)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:139)
... 61 more
Any help would be highly appreciated.
I did the following steps and the problem solved:
Exporting publickey certificate from p12 certificate
Adding it as truststore to my jre cacerts (More info for importing the truststore can be fount in How to solve javax.net.ssl.SSLHandshakeException Error?):
.
keytool -import -file <the cert file> -alias <some meaningful name> keystore <path to cacerts file>
.
Modifying the code as follows:
...
#RequestMapping(method = RequestMethod.GET, path = "/billinfo")
public void getBillInfo(String plateNumber) {
QName qname = new QName("http://tmr.qld.gov.au/srvc/getregistrationstatus/v2_0/", "GetRegistrationStatusService");
URL wsdl = getClass().getResource("wsdl/myWSDL.wsdl");
GetRegistrationStatusService service = new GetRegistrationStatusService(wsdl, qname);
service.addPort(qname, SOAPBinding.SOAP12HTTP_BINDING, "https://myurl/getregistrationstatus_v2_0/");
GetRegistrationStatus registrationStatus = service.getPort(qname, GetRegistrationStatus.class);
Client cxfClient = ClientProxy.getClient(registrationStatus);
cxfClient.getInInterceptors().add(new LoggingInInterceptor());
cxfClient.getOutInterceptors().add(new LoggingOutInterceptor());
cxfClient.getOutFaultInterceptors().add(new FaultOutInterceptor());
HTTPConduit httpConduit = (HTTPConduit) cxfClient.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(36000);
httpClientPolicy.setAllowChunking(false);
httpClientPolicy.setReceiveTimeout(32000);
httpClientPolicy.setContentType("application/soap+xml;charset=utf-8");
httpConduit.setClient(httpClientPolicy);
//Keystore setting
try {
final TLSClientParameters tlsCP = new TLSClientParameters();
File p12File = new File("sureft.p12");
KeyStore.Builder builder = KeyStore.Builder.newInstance("PKCS12", null, p12File, new KeyStore.PasswordProtection("sureft".toCharArray()));
KeyStore keyStore = builder.getKeyStore();
String keyPassword = "sureft";
final KeyManager[] myKeyManagers = getKeyManagers(keyStore, keyPassword);
tlsCP.setKeyManagers(myKeyManagers);
httpConduit.setTlsClientParameters(tlsCP);
} catch (Exception e) {
e.printStackTrace();
}
GetRegistrationStatusRequest request = new GetRegistrationStatusRequest();
request.setPlateNo(plateNumber);
GetRegistrationStatusResponse result = registrationStatus.execute(request);
log.debug("Result: " + result.toString());
}
private static KeyManager[] getKeyManagers(KeyStore keyStore, String keyPassword) throws GeneralSecurityException, IOException {
String alg = KeyManagerFactory.getDefaultAlgorithm();
char[] keyPass = keyPassword != null ? keyPassword.toCharArray() : null;
KeyManagerFactory fac = KeyManagerFactory.getInstance(alg);
fac.init(keyStore, keyPass);
return fac.getKeyManagers();
}
...
This was my solution but I would be grateful if anyone could share their solutions here.

I am using RFC 6238 to generate OTP with slight modification.

Now i want to send this otp to gmail and from there i have to read the otp and then enter in login page and make authentication sucess.
I am using java API to send mail, this is the program which am using to send mail (apache version 7-local host am using)
package com.otp;
import java.util.Properties;
import javax.mail.Message;
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 {
public static void send(String to, String sub, String msg,
final String user, final String pass) {
// create an instance of Properties Class
Properties props = new Properties();
/*
* Specifies the IP address of your default mail server for e.g if you
* are using gmail server as an email sever you will pass smtp.gmail.com
* as value of mail.smtp host. As shown here in the code. Change
* accordingly, if your email id is not a gmail id
*/
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.starttls.enable","true");
/*
* Pass Properties object(props) and Authenticator object for
* authentication to Session instance
*/
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
});
try {
/*
* Create an instance of MimeMessage, it accept MIME types and
* headers
*/
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
message.setSubject(sub);
message.setText(msg);
/* Transport class is used to deliver the message to the recipients */
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
But i am getting following Error.
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2054)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at com.otp.SendMail.send(SendMail.java:60)
at com.otp.Generate.doGet(Generate.java:57)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2522)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2511)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.UnknownHostException: smtp.gmail.com
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:331)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2020)
... 31 more
How to Resolve it. And make to send the otp code to My Gmail account?
Is There any other method to send the generated otp digit to Gmail or How to resolve The above problem. Please guide me in this issue.

Polling with Javamail and POP3 SSL causes error while DH keypair generation after a few hours

I ran into a strange problem. We have to poll a mailbox every 10 minutes and check for new mails (POP3, IMAP). We tested our implementation with several mail providers (gmail, 1and1, web.de, gmx, ...) and all worked fine.
Now we have to use a mailbox from outlook.office365.com with POP3 and SSL. Starting our service everything is working, but after a few hours the mailbox check throws errors while opening the mailbox store.
javax.mail.MessagingException: Connect failed;
nested exception is:
javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:210)
at javax.mail.Service.connect(Service.java:295)
at com.heiler.hbc.sil.mail.internal.MailerServiceImpl.createStore(MailerServiceImpl.java:298)
at com.heiler.hbc.sil.mail.internal.MailerServiceImpl.retrieveMails(MailerServiceImpl.java:499)
at com.heiler.hbc.sil.mail.internal.MailerServiceImpl.accessMailbox(MailerServiceImpl.java:180)
at sun.reflect.GeneratedMethodAccessor1272.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.osgi.service.importer.support.internal.aop.ServiceInvoker.doInvoke(ServiceInvoker.java:58)
at org.springframework.osgi.service.importer.support.internal.aop.ServiceInvoker.invoke(ServiceInvoker.java:62)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:132)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.osgi.service.util.internal.aop.ServiceTCCLInterceptor.invokeUnprivileged(ServiceTCCLInterceptor.java:56)
at org.springframework.osgi.service.util.internal.aop.ServiceTCCLInterceptor.invoke(ServiceTCCLInterceptor.java:39)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.osgi.service.importer.support.LocalBundleContextAdvice.invoke(LocalBundleContextAdvice.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:132)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy323.accessMailbox(Unknown Source)
at com.heiler.hbc.sil.pinquiry.internal.ReceiveResponseService.service(ReceiveResponseService.java:103)
at com.heiler.hbc.sil.pinquiry.internal.ReceiveResponseService.service(ReceiveResponseService.java:34)
at com.heiler.hbc.service.executor.internal.PInquiryCheckMailboxService.execute(PInquiryCheckMailboxService.java:110)
at com.heiler.hbc.service.executor.internal.AbstractSchedulerService.run(AbstractSchedulerService.java:61)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:53)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1884)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1842)
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1825)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1346)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:548)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:352)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:207)
at com.sun.mail.pop3.Protocol.<init>(Protocol.java:111)
at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:261)
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:206)
... 37 more
Caused by: java.lang.RuntimeException: Could not generate DH keypair
at sun.security.ssl.ECDHCrypt.<init>(ECDHCrypt.java:80)
at sun.security.ssl.ClientHandshaker.serverKeyExchange(ClientHandshaker.java:632)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:218)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
... 44 more
Caused by: java.security.InvalidAlgorithmParameterException: parameter object not a ECParameterSpec
at org.bouncycastle.jce.provider.JDKKeyPairGenerator$EC.initialize(Unknown Source)
at sun.security.ssl.ECDHCrypt.<init>(ECDHCrypt.java:75)
... 51 more
This is my createStore method:
private void createStore() throws MessagingException
{
if ( store == null )
{
store = session.getStore( authType.getType() );
}
if ( store != null && !store.isConnected() )
{
try
{
store.connect( popHost, popPort, user, password );
}
catch ( MessagingException e )
{
store = null;
logger.error( "Cannot connect to configured mailbox: [Host: " + popHost + ", Port: " + popPort + ", User: " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ user + "]" ); //$NON-NLS-1$
logger.debug( "", e );
}
}
}
On store.connect(..) the error occurs.
Anyone out there with an idea what can couse this error?
Thanks
Stephan
Updating the BouncyCastle dependencies solved the problem.
It looks like the BouncyCastle provider has a problem:
Caused by: java.security.InvalidAlgorithmParameterException: parameter object not a ECParameterSpec
at org.bouncycastle.jce.provider.JDKKeyPairGenerator$EC.initialize(Unknown Source)
Is your program doing anything to change the BouncyCastle configuration while it's running? If not, perhaps it's a bug in BouncyCastle? Otherwise, I don't know what would cause it to work for awhile and then fail.
Check if you have an outdated org.bouncycastle lib in your classpath (incompatible with your java version).
See http://iwang.github.io/support/2014/03/14/cxf-cause-https-error.html for an in-depth explanation.

Facing issue with java.lang.NoClassDefFoundError: org/apache/velocity/context/Context

I'm a new learner velocity. I am trying to display the template in HTML format by writing a servlet for that. The following is my servlet code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
VelocityEngine velocityEngine = new VelocityEngine();
try {
velocityEngine.init();
Template template = velocityEngine.getTemplate("./src/Menu.txt");
VelocityContext context = new VelocityContext();
context.put( "special-1", "./src/special-1.txt" );
context.put( "special-2", "./src/special-2.txt" );
context.put( "special-3", "./src/special-3.txt" );
StringWriter writer = new StringWriter();
template.merge(context, writer);
out.println(writer);
} catch (Exception e) {
e.printStackTrace();
}
}
And following is the stack trace im getting...
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
... 7 more
Caused by: java.lang.NoClassDefFoundError: org/apache/velocity/context/Context
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Unknown Source)
at java.lang.Class.getDeclaredFields(Unknown Source)
at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:263)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:142)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:67)
at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:405)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:881)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
Caused by: java.lang.ClassNotFoundException: org.apache.velocity.context.Context
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
... 21 more
Can anybody help me out?
You need to add the velocity-version.jar to your server classpath, you can put it in the lib folder of your tomcat server, or you can put this jar in the WEB-INF/lib folder of your project.
Download velocity-1.7 jar and add in to eclipse Deployment Assembly then restart the server.

beans.xml file and java.lang.UnsupportedOperationException: JBAS011859: Naming context is read-only

I have very strange exception after starting using beans.xml file in our EJB and jar files.
We use JBoss7.1.1 release.
Our application is packaged as ear file.
It was deployed and works correctly earlier.
There is some Module1 EJB component. Now we use #Inject annotation for some beans in Module1 and therefore added META-INF/beans.xml.
Another EJB component Module2 uses EJB from Module1 like:
#EJB
private IOmistajaFinderLocal omistajaFinder;
But now application cannot be deployed on JBoss. There following exception:
java.lang.UnsupportedOperationException: JBAS011859: Naming context is read-only
at org.jboss.as.naming.WritableServiceBasedNamingStore.requireOwner(WritableServiceBasedNamingStore.java:126)
at org.jboss.as.naming.WritableServiceBasedNamingStore.createSubcontext(WritableServiceBasedNamingStore.java:116)
at org.jboss.as.naming.NamingContext.createSubcontext(NamingContext.java:338)
at org.jboss.as.naming.InitialContext.createSubcontext(InitialContext.java:229)
at org.jboss.as.naming.NamingContext.createSubcontext(NamingContext.java:346)
at javax.naming.InitialContext.createSubcontext(Unknown Source)
at com.sun.jersey.server.impl.cdi.CDIExtension$1.stepInto(CDIExtension.java:280)
at com.sun.jersey.server.impl.cdi.CDIExtension.diveIntoJNDIContext(CDIExtension.java:267)
at com.sun.jersey.server.impl.cdi.CDIExtension.createJerseyConfigJNDIContext(CDIExtension.java:273)
at com.sun.jersey.server.impl.cdi.CDIExtension.initialize(CDIExtension.java:192)
at com.sun.jersey.server.impl.cdi.CDIExtension.beforeBeanDiscovery(CDIExtension.java:297)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:264)
at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:52)
at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:137)
at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:260)
at org.jboss.weld.introspector.jlr.WeldMethodImpl.invokeOnInstance(WeldMethodImpl.java:170)
at org.jboss.weld.introspector.ForwardingWeldMethod.invokeOnInstance(ForwardingWeldMethod.java:51)
at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:154)
at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:241)
at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:229)
at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:207)
at org.jboss.weld.bootstrap.events.AbstractContainerEvent.fire(AbstractContainerEvent.java:75)
at org.jboss.weld.bootstrap.events.AbstractDefinitionContainerEvent.fire(AbstractDefinitionContainerEvent.java:46)
at org.jboss.weld.bootstrap.events.BeforeBeanDiscoveryImpl.fire(BeforeBeanDiscoveryImpl.java:46)
at org.jboss.weld.bootstrap.WeldBootstrap.startInitialization(WeldBootstrap.java:322)
at org.jboss.as.weld.WeldContainer.start(WeldContainer.java:81)
at org.jboss.as.weld.services.WeldService.start(WeldService.java:76)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
at org.jboss.as.weld.services.WeldService.start(WeldService.java:83)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [rt.jar:1.7.0_09]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [rt.jar:1.7.0_09]
at java.lang.Thread.run(Unknown Source) [rt.jar:1.7.0_09]
Caused by: org.jboss.weld.exceptions.DefinitionException: Exception List with 1 exceptions:
Exception 0 :
java.lang.UnsupportedOperationException: JBAS011859: Naming context is read-only
at
org.jboss.as.naming.WritableServiceBasedNamingStore.requireOwner(WritableServiceBasedNamingStore.java:126)
at org.jboss.as.naming.WritableServiceBasedNamingStore.createSubcontext(WritableServiceBasedNamingStore.java:116)
at org.jboss.as.naming.NamingContext.createSubcontext(NamingContext.java:338)
at org.jboss.as.naming.InitialContext.createSubcontext(InitialContext.java:229)
at org.jboss.as.naming.NamingContext.createSubcontext(NamingContext.java:346)
at javax.naming.InitialContext.createSubcontext(Unknown Source)
at com.sun.jersey.server.impl.cdi.CDIExtension$1.stepInto(CDIExtension.java:280)
at com.sun.jersey.server.impl.cdi.CDIExtension.diveIntoJNDIContext(CDIExtension.java:267)
at com.sun.jersey.server.impl.cdi.CDIExtension.createJerseyConfigJNDIContext(CDIExtension.java:273)
at com.sun.jersey.server.impl.cdi.CDIExtension.initialize(CDIExtension.java:192)
at com.sun.jersey.server.impl.cdi.CDIExtension.beforeBeanDiscovery(CDIExtension.java:297)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:264)
at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:52)
at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:137)
at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:260)
at org.jboss.weld.introspector.jlr.WeldMethodImpl.invokeOnInstance(WeldMethodImpl.java:170)
at org.jboss.weld.introspector.ForwardingWeldMethod.invokeOnInstance(ForwardingWeldMethod.java:51)
at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:154)
at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:241)
at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:229)
at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:207)
at org.jboss.weld.bootstrap.events.AbstractContainerEvent.fire(AbstractContainerEvent.java:75)
at org.jboss.weld.bootstrap.events.AbstractDefinitionContainerEvent.fire(AbstractDefinitionContainerEvent.java:46)
at org.jboss.weld.bootstrap.events.BeforeBeanDiscoveryImpl.fire(BeforeBeanDiscoveryImpl.java:46)
at org.jboss.weld.bootstrap.WeldBootstrap.startInitialization(WeldBootstrap.java:322)
at org.jboss.as.weld.WeldContainer.start(WeldContainer.java:81)
at org.jboss.as.weld.services.WeldService.start(WeldService.java:76)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
at org.jboss.weld.bootstrap.events.AbstractDefinitionContainerEvent.fire(AbstractDefinitionContainerEvent.java:48)
at org.jboss.weld.bootstrap.events.BeforeBeanDiscoveryImpl.fire(BeforeBeanDiscoveryImpl.java:46)
at org.jboss.weld.bootstrap.WeldBootstrap.startInitialization(WeldBootstrap.java:322)
at org.jboss.as.weld.WeldContainer.start(WeldContainer.java:81)
at org.jboss.as.weld.services.WeldService.start(WeldService.java:76)
... 5 more
08:55:05,315 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"Helle.ear\".WeldService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"Helle.ear\".WeldService: org.jboss.weld.exceptions.DefinitionException: Exception List with 1 exceptions:
Exception 0 :
java.lang.UnsupportedOperationException: JBAS011859: Naming context is read-only
at org.jboss.as.naming.WritableServiceBasedNamingStore.requireOwner(WritableServiceBasedNamingStore.java:126)
at org.jboss.as.naming.WritableServiceBasedNamingStore.createSubcontext(WritableServiceBasedNamingStore.java:116)
at org.jboss.as.naming.NamingContext.createSubcontext(NamingContext.java:338)
at org.jboss.as.naming.InitialContext.createSubcontext(InitialContext.java:229)
at org.jboss.as.naming.NamingContext.createSubcontext(NamingContext.java:346)
at javax.naming.InitialContext.createSubcontext(Unknown Source)
at com.sun.jersey.server.impl.cdi.CDIExtension$1.stepInto(CDIExtension.java:280)
at com.sun.jersey.server.impl.cdi.CDIExtension.diveIntoJNDIContext(CDIExtension.java:267)
at com.sun.jersey.server.impl.cdi.CDIExtension.createJerseyConfigJNDIContext(CDIExtension.java:273)
at com.sun.jersey.server.impl.cdi.CDIExtension.initialize(CDIExtension.java:192)
at com.sun.jersey.server.impl.cdi.CDIExtension.beforeBeanDiscovery(CDIExtension.java:297)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:264)
at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:52)
at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:137)
at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:260)
at org.jboss.weld.introspector.jlr.WeldMethodImpl.invokeOnInstance(WeldMethodImpl.java:170)
at org.jboss.weld.introspector.ForwardingWeldMethod.invokeOnInstance(ForwardingWeldMethod.java:51)
at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:154)
at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:241)
at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:229)
at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:207)
at org.jboss.weld.bootstrap.events.AbstractContainerEvent.fire(AbstractContainerEvent.java:75)
at org.jboss.weld.bootstrap.events.AbstractDefinitionContainerEvent.fire(AbstractDefinitionContainerEvent.java:46)
at org.jboss.weld.bootstrap.events.BeforeBeanDiscoveryImpl.fire(BeforeBeanDiscoveryImpl.java:46)
at org.jboss.weld.bootstrap.WeldBootstrap.startInitialization(WeldBootstrap.java:322)
at org.jboss.as.weld.WeldContainer.start(WeldContainer.java:81)
at org.jboss.as.weld.services.WeldService.start(WeldService.java:76)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
"}}}}
Both Module1 and Module2 are included in application.xml file and generated ear file.
Deleting beans.xml resolves the deploying process but in this case we can not use #Injection annotation.
What is the problem and how can I resolve it? Thank you.
This is a known issue when using jersey. Try to add below option to your jvm, which will fix your issue. If you are running the jboss server from eclipse then add to the server runtime configuration. If you are starting the jboss from command prompt using standalone.bat then add the below option to standalone.conf.bat. Similarly if you are using *Nix then add to standalone.conf.
set "JAVA_OPTS=%JAVA_OPTS% -Dcom.sun.jersey.server.impl.cdi.lookupExtensionInBeanManager=true"
For use in eclipse (run and debug), open server properties, launch configuration properties and set the VM arguments:
-Dcom.sun.jersey.server.impl.cdi.lookupExtensionInBeanManager=true
I am able to manage this. Add a patch in naming jar. Just change org.jboss.as.naming.service.NamingStoreService -> readOnly = true
Full java class -
public class NamingStoreService implements Service<ServiceBasedNamingStore> {
private final boolean readOnly = false;
private volatile ServiceBasedNamingStore store;
public NamingStoreService() {
this(false);
System.out.println("Setting readOnly "+readOnly);
}
public NamingStoreService(boolean readOnly) {
System.out.println("Setting readOnly "+readOnly);
}
/**
* Creates the naming store if not provided by the constructor.
*
* #param context The start context
* #throws StartException If any problems occur creating the context
*/
public void start(final StartContext context) throws StartException {
if(store == null) {
final ServiceRegistry serviceRegistry = context.getController().getServiceContainer();
final ServiceName serviceNameBase = context.getController().getName();
final ServiceTarget serviceTarget = context.getChildTarget();
store = readOnly ? new ServiceBasedNamingStore(serviceRegistry, serviceNameBase) : new WritableServiceBasedNamingStore(serviceRegistry, serviceNameBase, serviceTarget);
}
}
/**
* Destroys the naming store.
*
* #param context The stop context
*/
public void stop(StopContext context) {
if(store != null) {
try {
store.close();
store = null;
} catch (NamingException e) {
throw MESSAGES.failedToDestroyRootContext(e);
}
}
}
/**
* Get the context value.
*
* #return The naming store
* #throws IllegalStateException
*/
public ServiceBasedNamingStore getValue() throws IllegalStateException {
return store;
}
}