Unable to listen to events using Apache Commons Email - apache-commons-email

I'm sending emails using Apache commons email lib.
However, I'm unable to listen to Connection and Transport events. I have added event listeners using:
email.getMailSession().getTransport().addConnectionListener(this);
email.getMailSession().getTransport().addTransportListener(this);
...but don't receive any events.
My code is as follows:
public class MailSendTest implements ConnectionListener, TransportListener{
final Email email = new SimpleEmail();
public void sendEmail(){
try {
email.setHostName("smtp.host.com");
email.setFrom("from#host.com");
email.addTo("to#host.com");
email.setBounceAddress("from#host.com");
email.setSubject("Testing");
email.setMsg("Test Message");
email.setDebug(true);
email.setAuthentication("from#host.com", "pass");
email.setSslSmtpPort("465");
email.setSocketTimeout(60000);
email.getMailSession().getTransport().addConnectionListener(this);
email.getMailSession().getTransport().addTransportListener(this);
email.send();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Err : "+ex.getMessage());
}
}
#Override
public void opened(ConnectionEvent e) {
System.out.println("####Connected to "+ email.getHostName());
}
#Override
public void disconnected(ConnectionEvent e) {
System.out.println("####Disconnected from "+ email.getHostName());
}
#Override...
}
Any help would be appreciated.

I'm also found it unable to do so, but after do some digging ... I found out that commons mail is dependent to java mail API (mail.jar), so apache commons mail is just abstracting what should be done discreetly if you are using java mail API.
What I suggest is to follow what this tutorial here do, which is creating Session object, then retrieves the Transport object from it ... then you can attach your TransportListener.
I am still doing the above way currently (while writing this), I hope its work!
By the way, use this to define properties for SMTP.
Good luck

Related

How to catch org.jboss.weld.context.ContextNotActiveException

I understand that this is a RuntimeException but for my usecase I need to catch it and set some attributes.
Context: I am using JPA EntityListeners for auditing and everything works fine when user accesses the application. The problem occurs when the application is accessed remotely using RemoteEJB. I am using a session object (Credentials which captures the user) in the EntityListener, so when the call is from RemoteEJB and because there is no session it fails as expected. This is the only exception I anticipate so I want to catch it and hardcode the auditing in this RemoteEJB accessing case. But somehow I am not able to catch it. I tried to catch javax.enterprise.context.ContextNotActiveException but to no avail.
public class CreateListener {
#Inject #Named("credentials") private Credentials credentials;
#PrePersist
public void setCreateAttributes(Auditable entity){
try {
entity.setCreateUserName(credentials.getUserName());
} catch (RuntimeException e) {
entity.setCreateUserName("RemoteEJB");
}
entity.setCreateTmstmp(new Date());
}
}
Environment: JDK 1.8, JBOSS EAP 7.1, hibernate-jpa-2.1-api, Hibernate 5.2.12.Final
Any help of alternative approach is appreciated.
TIA
-Avi

How to catch error when message have been sent from JMS

I am sending an message through my standalone application that uses EJB MDB to communicate to my other application server that is running on JBOSS server.My application server is connected to a MSSQL server. In certain scenario, connection to the database is lost on application server side and we get following error -
Connection is reset.
Later , when i try to send message i don't get any error at my standalone EJB MDB logs and the process just stops executing.I get error log on application server side logs but same logs don't get propagated to my EJB MDB error logs.
As per my understanding, when db connection is lost all the ejb bean present in jboss container get nullified too.(I could be wrong here, i am new to EJB).
I tried implementing below code in my code that use to send message -
QueueConnection qcon = null;
#PostConstruct
public void initialize() {
System.out.println("In PostConstruct");
try {
qcon = qconFactory.createQueueConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
#PreDestroy
public void releaseResources() {
System.out.println("In PreDestroy");
try {
if(qcon != null)
{
qcon.close();
}
if(qcon== null){
throw new Exception(" new exception occured.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
I was in a impression that Queueconnection object will be nullified, when our db connection have been lost(as we are creating bean and making connection for message). But it doesn't seem to work.
I did found a way to call back my application after sending message. I used a separate temporary queue and used setJMSReplyTo method to set the reply destination. More info could be obtained from this
link. Hope this helps others.

custom login module to access httpservletrequest in JBOSS EAP

I am developing a custom login module for jboss' jaas implementation. I would like to be able to access the HttpServletRequest object inside my login module. Does anyone know the best way to do this, if it's possible? I've been researching this, and so far I think I need to use a Callback of some kind, but I'm not sure.I found some WebSphere documentation that shows they have a WSServletRequestCallback that seems to be able to do this. Please suggest a simple example or documentation if jboss' jaas implementation have anything like this.
Update:
#kwart: As per your suggestion, I coded the following. Please suggest if this is the right way:
protected CallbackHandler _callbackHandler;
HttpServletRequest request = null;
ObjectCallback objectCallback = null;
Callback[] callbacks = new Callback[1];
callbacks[0] = objectCallback = new ObjectCallback("HttpServletRequest: ");
try
{
_callbackHandler.handle(callbacks);
}
catch (Exception e)
{
logger.logp(Level.SEVERE, CLASSNAME, METHOD_NAME, "Error handling callbacks", e);
}
try
{
if (objectCallback != null)
{
request = (HttpServletRequest) PolicyContext.getContext("javax.servlet.http.HttpServletRequest");
}
}
catch (PolicyContextException e) {
logger.logp(Level.SEVERE, CLASSNAME, METHOD_NAME, "Error getting request", e);
}
catch (Exception e)
{
logger.logp(Level.SEVERE, CLASSNAME, METHOD_NAME, "Exception occured augmenting JbossSubject", e);
}
You can use JACC PolicyContext to retrieve the HttpRequestObject in the LoginModule methods:
HttpServletRequest request = (HttpServletRequest) javax.security.jacc.PolicyContext
.getContext(HttpServletRequest.class.getName());
Update: Find sample usage in LoginModule here.
I got a solution from this site.
Used JSPI authentication. Configured an auth module in security domain in standalone as explained here .
Created a custom authenticator and a custom login module, configured the authenticator in jboss-web.xml and login module in security domain in standalone xml.
I jar'd them in a separate module and added that to jboss-deployment-structure.xml. Stored http request in ThreadLocal in the authenticator and retrieved it in my login module by simply reading the value stored in the Thread Local.

Endpoint message notification logger in mule does not get invoked

I want to log the payloads (centralized logging) being sent out from my HTTP endpoints (requester) for which I figured it is best to use the EndpointMessageNotificationListener
The server starts up correctly but my notification logger does not get called. I expect the onNotification method to be invoked each time a request is sent out from the HTTP Requester.
Now I have configured the spring bean.
<spring:bean name="endpointNotificationLogger" class="EndpointAuditor" />
My Java class is as below
public class EndpointAuditor implements EndpointMessageNotificationListener<EndpointMessageNotification> {
public EndpointAuditor(){
System.out.println("The EndpointAuditor has been instantiated");
}
#Override
public void onNotification(EndpointMessageNotification notification) {
try {
System.out.println("This comes from the endpoint " + notification.getSource().getPayloadAsString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and my notification configuration as below
<notifications>
<notification event="ENDPOINT-MESSAGE" />
<notification-listener ref="endpointNotificationLogger" />
</notifications>
I have picked up all this from here.
Any ideas why Mule is not happy ?
This one turned out to be a tricky one. I was using Mule 3.6.1 EE with the new HTTP Connector and this feature is not implemented with the HTTP Connector in this particular Mule version.
So basically I was doing all the right things and Mule just did'nt have the feature.
But they have implemented it with Mule 3.6.3 EE and Mule 3.7.X. This commit shows how the code written for it.

JAX-RS Client API async request

I am trying to use the JAX-RS Client API to request a resource through HTTP GET, by using the following code: (I used jersey-client v2.12 and also resteasy-client v3.0.8.Final to test the implementation)
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.InvocationCallback;
public class StackOverflowExample {
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
client.target("http://example.com/").request().async().get(new InvocationCallback<String>() {
#Override
public void completed(String s) {
System.out.println("Async got: " + s);
}
#Override
public void failed(Throwable throwable) {
System.out.println("Async failure...");
}
});
}
}
As I expected the String is printed almost immediately. But the process keeps running about one minute, although there isn't any code that should be executed.
The JAX-RS spec just says that we should use the InvocationCallback and nothing else that matters to my issue. But even if I use a Future the same effect happens. I also tested, if this has something to do with a timeout, which was very unlikely and wrong. The debugger shows that there are some threads running namely DestroyJavaVM and jersey-client-async-executor-0 or pool-1-thread-1 in the case of resteasy.
Do you have any idea what is going wrong here?
It is allways helpful to consult the JavaDoc. Concerning my issue it says:
Clients are heavy-weight objects that manage the client-side communication infrastructure. Initialization as well as disposal of a Client instance may be a rather expensive operation. It is therefore advised to construct only a small number of Client instances in the application. Client instances must be properly closed before being disposed to avoid leaking resources.
If I close the client properly everything is working as expected.
public class StackOverflowExample {
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
// request here
client.close();
}
}