EJB server error on Wildfly 8.0 - ejb

I have just started learning EJB and just wanted to execute my first code.
However, I am unable to remove this error:
Error-11:24:22,065 INFO [org.jboss.as.naming] (default task-3) JBAS011806:
Channel end notification received, closing channel Channel ID 4fb1d052
(inbound) of Remoting connection 6e42fa05 to null
I am using Java 1.8 with wildfly 8.0
Code ClientBean
public static void main(String[] args) throws CommunicationException {
try {
Context context = getInitialContext();
Hello remote=(Hello)context.lookup("HelloBean/remote");
System.out.println(remote.Hello());
}
catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Context getInitialContext() throws javax.naming.NamingException {
Properties properties=new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
properties.put(Context.PROVIDER_URL,"http-remoting://localhost:8080");
properties.put("jboss.naming.client.ejb.context", true);
return new javax.naming.InitialContext(properties);
}

Are you able to invoke your EJB and you see this error after that ?
Also please add credentials to InitialContext Properties ,like below
properties.put("java.naming.security.principal", "user");
properties.put("java.naming.security.credentials", "pass");
You can add this user to wildfly , using addUser.bat/sh scripts. It will ask for something like "use this user for EJB remote communication " , say yes for that.

Related

How to handle Internal server error (500) on spring rest API to custom the message?

I am working on spring rest api and I would like to sure everything is working fine. I would like to log abnormal behaviors database connection error among others, I'm working with couchbase database and I'm getting in the endpoint response for example for this kind of exception: CouchbaseQueryExecutionException the next message: Unable to execute query due to the following n1ql errors: \n{\"msg\":\"No index available on keyspace kids_club that matches your query. Use CREATE INDEX or CREATE PRIMARY INDEX to create an index, or check that your expected index is online.\",\"code\":4000} and a very long trace.
For this i found a solution on internet that is extend ResponseEntityExceptionHandler and override handleExceptionInternal method like this:
#ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
private static String DEFAULT_VALIDATION_ERROR_CODE = "KC-0020";
#ExceptionHandler(MiddlewareException.class)
protected ResponseEntity<ResponseBody> handleKidsClubException(MiddlewareException ex) {
return buildErrorResponse(HttpStatus.valueOf(ex.getHttpStatus()), ex.toError());
}
#ExceptionHandler(ServiceUnavailableException.class)
protected ResponseEntity<ResponseBody> handleServiceUnavailable(ServiceUnavailableException ex) {
return buildErrorResponse(INTERNAL_SERVER_ERROR, ex);
}
#ExceptionHandler(NoSuchElementException.class)
protected ResponseEntity<ResponseBody> handleNoFoundElement(NoSuchElementException ex) {
return buildErrorResponse(NOT_FOUND, ex);
}
#ExceptionHandler(CouchbaseQueryExecutionException.class)
protected ResponseEntity<ResponseBody> handleCouchbaseQueryException(ConstraintViolationException ex) {
return buildErrorResponse(BAD_REQUEST, ex);
}
}
But I'm not able to catch any kind of Internal Server Error in this way.
It seems like spring is handle and building the final message to the user.
Any ideas to resolve this?
Thanks.
#ExceptionHandler(NullPointerException.class)
public final ResponseEntity<Object> handleNullPointerException(NullPointerException ex, WebRequest request) {
LOGGER.info("Entering into the handleAllException method");
System.out.println("Exception is : " + ex.getClass());
ResponseData error = new ResponseData();
error.setRespCode(HttpStatus.NOT_FOUND.toString());
error.setRespMessage(ex.getLocalizedMessage());
error.setTimestamp(LocalDateTime.now());
return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
please try this way below to check whether you are able to catch exception or not.. From the sysout you will get the exact exception. Then you can use that exception to catch any particular exception from that business logic..

Unable to throw exception by KafkaTemplate when topic is not available/ kafka broker is down

I am sending message to Kafka by Kafka Template but I wanted to test exception, So I have provided wrong topic name but When I run the code, it says " Error while fetching metadata with correlation id 2 : {ocf-oots-gr-outbound_123=LEADER_NOT_AVAILABLE" not available but the topic itself is created in Kafka that I can also see through Kafka tool and when broker is stopped, it is also not throwing exception.
Code:
KafkaTemplate<String, Object> kafkaTemplate = (KafkaTemplate<String, Object>) CommonAppContextProvider.getApplicationContext().getBean("kafkaTemplate");
//kafkaTemplate.send(CommonAppContextProvider.getApplicationContext().getEnvironment().getProperty("kafka.transalators.outbound.topic"), kafkaMessageFormat);
ListenableFuture listenableFuture = kafkaTemplate.send(CommonAppContextProvider.getApplicationContext().
getEnvironment().getProperty("kafka.transalators.outbound.topic"), kafkaMessageFormat);
listenableFuture.addCallback(new ListenableFutureCallback<SendResult<?, ?>>() {
#Override
public void onSuccess(SendResult<?, ?> result) {
System.out.println("Sent");
}
#Override
public void onFailure(Throwable ex) {
throw new KafkaException();
}
});
}
It should throw exception may be KafkaException, TimeOutException, Interrupted exception etc.
You have to call get(time, timeUnit) on the future to get the result (success or otherwise).

Message Driven Bean listen to JMS remote destinations (Weblogic)

Greeting, I'm new to Java EE and especially message driven bean so i followed the tutorial which has been working with internal JMS destinations (e.g. weblogic server that runs on my local machine). Now I'm trying to listen to new messages from remote destinations (e.g. another weblogic server run on different machine). I'm thinking about jndi naming lookup however I don't see any appropriate place to implement in the MDB. My question is do I need any config files in order for this to work? or is it even possible to listen to remote JMS destinations?
#MessageDriven(mappedName="jms/myQueue") //jms/myQueue is remote queue name
public class PMQueueListener implements MessageListener{
#Resource
private MessageDrivenContext mdc;
/**
* Default constructor.
*/
public PMQueueListener() {
System.out.println("This is onmessage()");
}
/**
* #see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
TextMessage msg = null;
try
{
if (message instanceof TextMessage)
{
msg = (TextMessage) message;
System.out.println("MESSAGE BEAN: Message received: " +
msg.getText());
}
else
{
System.out.println("Message of wrong type: " +
message.getClass().getName());
}
}
catch (JMSException e)
{
e.printStackTrace();
mdc.setRollbackOnly();
}
catch (Throwable te)
{
te.printStackTrace();
}
}
}
You can add below annotation on your MDB and see if it works for you.
#TransactionManagement(TransactionManagementType.CONTAINER)
#TransactionAttribute(TransactionAttributeType.REQUIRED)

Implementing WebSocket on Spring MVC based Server

I searched a lot about implementing WebSocket/XMPP on Spring MVC based server but couldn't reach to a concrete answer. So here is my requirement
Receive a message from a client (in my case it will be a android/iOS mobile) via WebSocket/XMPP on tomcat server and parse the actual message at server side
Send a message from server app to WebSocket/XMPP client
If somebody could help me to point on some good tutorial or demo code, it would be a great help.
run Tomee 1.5.2
http://openejb.apache.org/downloads.html
activate the ActiveMQ JMS Server. create an OpenEJB configuration.
http://www.mail-archive.com/users#openejb.apache.org/msg04327.html
setup an XMPP ActiveMQ server protocol listener (in the activemq.xml)
in your Spring services configuration, create a Spring JMS listener (Spring ListenerContainer) configuration on the Topic/Queue.
you can use the JmsTemplate to push a message out to the Queue/Topic via ActiveMQ, the XMPP client will receive the message.
Enjoy!
BTW: This is exactly what I am in the middle of setting up right now...still learning.
check this out: www.xchat.io. It was built based on Asynchronous Spring MVC (DefferredResult, you know), XMPP, and jQuery. it's promising.
I am not sure if this is just perfect way to achieve or not, but for now I have found a solution and it would be glad to share it here.
There are two steps that you have to done.
1. Instead of ordinary HTTPServlet sub class, create a sub class of WebSocketServlet and
2. Create a sub class of MessageInbound class and override its required methods.
P.S. : Only latest version of tomcat supports WebSocket (apache tomcat 7.0.42 or higher).
Here is a WebSocket class.
public class WsChatServlet extends WebSocketServlet {
private static final long serialVersionUID = 1456546233L;
#Override
protected StreamInbound createWebSocketInbound(String protocol,
HttpServletRequest request) {
return new IncomingMessageHandler();
}
}
And this is a simple class which can send/receive message (String/binary).
public class IncomingMessageHandler extends MessageInbound {
#Override
public void onOpen(WsOutbound outbound) {
logger.info("Open Client.");
}
#Override
public void onClose(int status) {
logger.info("Close Client.");
}
#Override
public void onTextMessage(CharBuffer cb) throws IOException {
logger.info("Text Message received:" + cb.toString());
}
#Override
public void onBinaryMessage(ByteBuffer bb) throws IOException {
}
public synchronized void sendTextMessage(String message) {
try {
CharBuffer buffer = CharBuffer.wrap(message);
this.getMyoutbound().writeTextMessage(buffer);
this.getMyoutbound().flush();
} catch (IOException e) {
// Handle Exception
}
}
}

Injecting jms resource in servlet & best practice for MDB

using ejb 3.1, servlet 3.0 (glassfish server v3)
Scenario:
I have MDB that listen to jms messages and give processing to some other session bean (Stateless).
Servelet injecting jms resource.
Question 1: Why servlet can`t inject jms resources when they use static declaration ?
#Resource(mappedName = "jms/Tarturus")
private static ConnectionFactory connectionFactory;
#Resource(mappedName = "jms/StyxMDB")
private static Queue queue;
private Connection connection;
and
#PostConstruct
public void postConstruct() {
try {
connection = connectionFactory.createConnection();
} catch (JMSException e) {
e.printStackTrace();
}
}
#PreDestroy
public void preDestroy() {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
The error that I get is :
[#|2010-05-03T15:18:17.118+0300|WARNING|glassfish3.0|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=35;_ThreadName=Thread-1;|StandardWrapperValve[WorkerServlet]:
PWC1382: Allocate exception for
servlet WorkerServlet
com.sun.enterprise.container.common.spi.util.InjectionException:
Error creating managed object for
class
ua.co.rufous.server.services.WorkerServiceImpl
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:312)
at
com.sun.enterprise.web.WebContainer.createServletInstance(WebContainer.java:709)
at
com.sun.enterprise.web.WebModule.createServletInstance(WebModule.java:1937)
at
org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1252)
Caused by:
com.sun.enterprise.container.common.spi.util.InjectionException:
Exception attempting to inject
Unresolved Message-Destination-Ref
ua.co.rufous.server.services.WorkerServiceImpl/queue#java.lang.String#null
into class
ua.co.rufous.server.services.WorkerServiceImpl
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:614) at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:384)
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:141)
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:127)
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:306)
... 27 more Caused by:
com.sun.enterprise.container.common.spi.util.InjectionException:
Illegal use of static field private
static javax.jms.Queue
ua.co.rufous.server.services.WorkerServiceImpl.queue
on class that only supports
instance-based injection at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:532) ... 31 more |#]
my MDB :
/**
* asadmin commands
* asadmin create-jms-resource --restype javax.jms.ConnectionFactory jms/Tarturus
* asadmin create-jms-resource --restype javax.jms.Queue jms/StyxMDB
* asadmin list-jms-resources
*/
#MessageDriven(mappedName = "jms/StyxMDB", activationConfig =
{
#ActivationConfigProperty(propertyName = "connectionFactoryJndiName", propertyValue = "jms/Tarturus"),
#ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class StyxMDB implements MessageListener {
#EJB
private ActivationProcessingLocal aProcessing;
public StyxMDB() {
}
public void onMessage(Message message) {
try {
TextMessage msg = (TextMessage) message;
String hash = msg.getText();
GluttonyLogger.getInstance().writeInfoLog("geted jms message hash = " + hash);
} catch (JMSException e) {
}
}
}
everything work good without static declaration:
#Resource(mappedName = "jms/Tarturus")
private ConnectionFactory connectionFactory;
#Resource(mappedName = "jms/StyxMDB")
private Queue queue;
private Connection connection;
Question 2:
what is the best practice for working with MDB : processing full request in onMessage() or calling another bean(Stateless bean in my case) in onMessage() method that would process it.
Processing including few calls to soap services, so the full processing time could be for a 3 seconds.
Thank you.
Answers:
1. You cannot inject a resource into a static field. Injection into member fields occurs during object construction, static fields are not part of the object (only part of the class). In addition EJBs and servlets are threaded objects so this could possibly be dangerous to do.
2. If splitting the processing up into multiple EJB(s) makes sense do it that way, otherwise processing in onMessage() is perfectly valid.
One additional suggestion that I can give, is that you should take a look at CDI which is a new addition to the EE 6 specification and provides rich dependency injection.
Are you using an MDB to perform asynchronous operations, Servlet 3.0 has some neat asynchronous capabilities. I suggest you watch the entire presentation if you are not familiar with Servlet 3.0.

Resources