injecting Session bean from another session bean in JBoss 7.1 - ejb-3.1

I am not able to inject a SLSB in another SLSB. Actually created 3 projects
1) created a EJB project with an MDB
2) created a EJB project with a stateless session bean for posting the message
3) created a EJB project with a stateless session bean for injecting the above session bean
But while injecting I am not able to inject the EJB it is returning null
the code is as below
1) MDB:
#MessageDriven(
activationConfig = {
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
#ActivationConfigProperty(propertyName = "destination", propertyValue = "activemq/queue/TestQueue"),
#ActivationConfigProperty(propertyName="acknowledgeMode", propertyValue="Auto-acknowledge")
})
#ResourceAdapter("activemq-ra.rar")
public class ConsumerMDB implements MessageListener {
public void onMessage(Message message) {
try {
System.out.println("Queue: Received a TextMessage at " + new Date());
TextMessage msg = (TextMessage) message;
System.out.println("Message is : " + msg.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
2) Session Bean 1
package com.springboard.session;
import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
#Stateless
#LocalBean
public class ProducerSession implements ProducerSessionLocal {
#Resource(mappedName="java:jboss/activemq/QueueConnectionFactory")
public static QueueConnectionFactory factory;
#Resource(mappedName = "java:jboss/activemq/queue/TestQueue")
public static Queue queue;
#Override
public void sendMessage(String msg) {
System.out.println("****************Entering into method********************");
try {
System.out.println(queue.getQueueName());
QueueConnection qConnection = factory.createQueueConnection();
QueueSession qSession = qConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
TextMessage message = qSession.createTextMessage();
message.setText(msg);
QueueSender qSender = qSession.createSender(queue);
qSender.send(message);
qSender.close();
qSession.close();
qConnection.close();
} catch (JMSException e) {
e.printStackTrace();
}
System.out.println("****************Exiting into method********************");
}
}
and the interface is
package com.springboard.session;
import javax.ejb.Local;
#Local
public interface ProducerSessionLocal {
public void sendMessage(String msg);
}
3) Second session bean to inject the first session
#Stateless
public class TestProducerLocalBean implements TestProducerLocalBeanLocal {
#EJB(mappedName = "java:global/ProducerSessionActiveMQ/ProducerSession!com.springboard.session.ProducerSessionLocal")
public ProducerSessionLocal producer;
public TestProducerLocalBean() {
System.out.println("*************Testing Producer****************");
if(producer!=null){
producer.sendMessage("This Message is from SessionBean to Session Bean to MDB");
}
else{
System.out.println("EJB is null");
}
System.out.println("**********End************************");
}
#Override
public void messageSend(String msg) {
// TODO Auto-generated method stub
}
and for testing purpose used a class
import javax.ejb.EJB;
import com.springboard.session.test.TestProducerLocalBean;
public class testEJB {
#EJB
public static TestProducerLocalBean local =new TestProducerLocalBean();
public static void main(String[] args) {
}
}
At producer EJB always retuns null. With using servlet to inject ProducerSession i am able to do it. but injecting with another EJB i not able to get it.
Could any one please help me out what i am missing
Thanks in advance

It's incorrect to use initialization ... = new Xyz() when using injection because initialization of those fields is the responsibility of the container. You probably attempted that because you noticed that the field was null, and that's because injection (including #EJB) is not supported in the main class unless you use an application client container.

Related

Whitelabel Error Page error (Spring Boot + React)

localhost:9000 is opening fine on the browser. And if I navigate to a link from the menu like localhost:9000/about, it is working fine.
But if I hit localhost:9000/about directly without going to localhost:9000 then nothing happens on the local and if I do the same on server, following error is produced:
Whitelabel Error Page This application has no explicit mapping for
/error, so you are seeing this as a fallback.
Mon Feb 12 14:09:05 IST 2018 There was an unexpected error (type=Not
Found, status=404). No message available
Please help!!
This is happening because in your application you have not defined what your application should do when it will get url request localhost:9000.
For every Request mapping you need to define the operation you want to perform. In your case for localhost:9000 you have to write what you want to do as you have done for local:9000/about.
#RequestMapping("")
#ResponseBody
Function_For_HandlingRequest{}
When you hit http://localhost:9090/about directly, SpringBoot redirect To a /login.html.
So, Redirect every page to index.html .
https://github.com/geowarin/boot-react/blob/master/backend/src/main/java/react/config/SinglePageAppConfig.java
The WebMvcConfigurer interface, starting with Spring 5, contains default implementations for all its methods. As a result, the abstract adapter (WebMvcConfigurerAdapter) class was marked as deprecated.
package your.package.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.ResourceResolver;
import org.springframework.web.servlet.resource.ResourceResolverChain;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* Redirects every page to index.html
* Used to handle the router
*/
#Configuration
public class SinglePageAppConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.resourceChain(false)
.addResolver(new PushStateResourceResolver());
}
private class PushStateResourceResolver implements ResourceResolver {
private Resource index = new ClassPathResource("/static/index.html");
private List<String> handledExtensions = Arrays.asList("html", "js", "json", "csv", "css", "png", "svg", "eot", "ttf", "woff", "appcache", "jpg", "jpeg", "gif", "ico");
private List<String> ignoredPaths = Arrays.asList("api");
#Override
public Resource resolveResource(HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) {
return resolve(requestPath, locations);
}
#Override
public String resolveUrlPath(String resourcePath, List<? extends Resource> locations, ResourceResolverChain chain) {
Resource resolvedResource = resolve(resourcePath, locations);
if (resolvedResource == null) {
return null;
}
try {
return resolvedResource.getURL().toString();
} catch (IOException e) {
return resolvedResource.getFilename();
}
}
private Resource resolve(String requestPath, List<? extends Resource> locations) {
if (isIgnored(requestPath)) {
return null;
}
if (isHandled(requestPath)) {
return locations.stream()
.map(loc -> createRelative(loc, requestPath))
.filter(resource -> resource != null && resource.exists())
.findFirst()
.orElseGet(null);
}
return index;
}
private Resource createRelative(Resource resource, String relativePath) {
try {
return resource.createRelative(relativePath);
} catch (IOException e) {
return null;
}
}
private boolean isIgnored(String path) {
return ignoredPaths.contains(path);
}
private boolean isHandled(String path) {
String extension = StringUtils.getFilenameExtension(path);
return handledExtensions.stream().anyMatch(ext -> ext.equals(extension));
}
}
}
in Application
#Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return factory -> {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
factory.addErrorPages(error404Page);
};
}
enter image description here

spring aop pointcut not triggered

The issue is the #Before and #AfterReturning are working but it's not the case for Pointcut.
Here is my aspect.
As part of a springboot service, What I want do is trigger the pointcut with first method profile to show execution time and other things.
Am I missing something ?
package com.myproj.service.myagg.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
/**
* Created by shammami on 26/05/2017.
*/
#Aspect
#Component
public class LoggingService {
#Pointcut("execution(public void com.myproj.service.myagg.listener.MyMessageConsumer.handleMessage(..))")
public Object profile(ProceedingJoinPoint pjp) throws Throwable {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
boolean isExceptionThrown = false;
try {
// execute the profiled method
return pjp.proceed();
} catch (RuntimeException e) {
isExceptionThrown = true;
throw e;
} finally {
stopWatch.stop();
StopWatch.TaskInfo taskInfo = stopWatch.getLastTaskInfo();
// Log the method's profiling result
String profileMessage = taskInfo.getTaskName() + ": " + taskInfo.getTimeMillis() + " ms" +
(isExceptionThrown ? " (thrown Exception)" : "");
System.out.println(profileMessage);
}
}
#Before("execution(public void com.myproj.service.myagg.listener.MyMessageConsumer.handleMessage(..))")
public void before(JoinPoint joinPoint) {
System.out.println("Started: " + joinPoint.getStaticPart().getSignature().toLongString());
}
#AfterReturning("execution(public void com.myproj.service.myagg.listener.MyMessageConsumer.handleMessage(..))")
public void completed(JoinPoint joinPoint) {
System.out.println("Completed: " + joinPoint.getStaticPart().getSignature().toLongString());
}
}
When you annotate something with #Pointcut you are basically defining the pointcut signature, you can not do any sort of processing in there. What you need to do is to create another method which has all the processing details and uses the pointcut signature you evaluated above. Hence,
#Pointcut("execution(public void com.myproj.service.myagg.listener.MyMessageConsumer.handleMessage(..))")
public void myPointcutSignature(){
//This basically has nothing :)
}
#Around("myPointcutSignature")
public Object profile(ProceedingJoinPoint pjp) throws Throwable {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
boolean isExceptionThrown = false;
//And the remaining code
-------
}
Hope this works. Also remember that ProceedingJoinPoint can be used only with #Around advice.

implementing publisher and subscriber functionality using activemq-jms from browser(web-client-application(angularjs or javascript or jsp))

i want to implement an application where i should be able to login as a subscriber and i should be able to see the messages/data coming from publisher which am subscribed to.then i should be able to unsubscribe and subscribe to other publishers if i want to.
using JMS,ActiveMQ,SpringBoot i have created a sample standalone application but from here how to connect and communicate to my web application back and forth.
Here is my implemented standalone application code
application.properties
spring.jms.pub-sub-domain=true
#spring.jms.template.default-destination=testTopic
Publisher.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
#Component
public class Publisher implements CommandLineRunner{
#Autowired
private JmsTemplate jmsTemplate ;
#Autowired
private Topic topic1;
#Autowired
private Topic topic2;
#Override
public void run(String... arg0) throws Exception {
// TODO Auto-generated method stub
Thread.sleep(5000); // wait for subscriptions, unless they are durable
this.jmsTemplate.convertAndSend(this.topic1,"-----> 1st message from publisher -- topic 1");
Thread.sleep(5000);
this.jmsTemplate.convertAndSend(this.topic1,"-----> 2nd message from publisher -- topic 1");
/**
* for topic2
*/
// TODO Auto-generated method stub
Thread.sleep(5000); // wait for subscriptions, unless they are durable
this.jmsTemplate.convertAndSend(this.topic2,"-----> 1st message from publisher -- topic 2");
Thread.sleep(5000);
this.jmsTemplate.convertAndSend(this.topic2,"-----> 2nd message from publisher -- topic 2");
}
}
Subscriber.java
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
#Component
public class Subscriber {
#JmsListener(destination = "Topic1")
public void listener1(String in) {
System.out.println("Listener1: " + in);
}
#JmsListener(destination = "Topic1,Topic2")
public void listener2(String in) {
System.out.println("Listener2: " + in);
}
#JmsListener(destination = "Topic2")
public void listener3(String in) {
System.out.println("Listener3: " + in+"\n listener 3 is just ");
}
}
mainclass : springBootApplication
PubSubJmsBootApplication.java
import javax.jms.Topic;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
#SpringBootApplication
#EnableJms
public class PubSubJmsBootApplication {
#Bean
public Topic topic1() {
return new ActiveMQTopic("Topic1");
}
#Bean
public Topic topic2() {
return new ActiveMQTopic("Topic2");
}
public static void main(String[] args) {
SpringApplication.run(PubSubJmsBootApplication.class, args);
}
}

Akka + Camel + Context-Provider

Dear Camel/Akka/Netty Masters!
I've created UntypedConsumerActor which consumes tcp connection:
public class TcpEndpoint extends UntypedConsumerActor {
private static final Logger log = LoggerFactory.getLogger(TcpEndpoint.class);
public static Props props = Props.create(TcpEndpoint.class);
#Override
public String getEndpointUri() {
return "netty4:tcp://localhost:8000?decoders=#fdDecoder,#fdHandler";
}
#Override
public void onReceive(Object message) throws Throwable {
log.error("onReceived");
}
}
In case to configure decoders for netty component, I've created ContextProvider:
public class FDCamelContext implements ContextProvider {
public DefaultCamelContext getContext(ExtendedActorSystem system) {
JndiRegistry registry = new JndiRegistry();
registry.bind("fdDecoder", new FDDecoder());
registry.bind("fdHandler", new FDHandler());
DefaultCamelContext context = new DefaultCamelContext(registry);
return context;
}
}
Now, when I send message there is no call on onReceive method. Why? When I set DefaultContextProvider and configure netty to consumes textlines everything works as expected.
Ok, I found problem. Maybe it helps someone:
It is necesarry to fire channelRead event:
ctx.fireChannelRead(msg);

Ejb3 -Accessing Local Enterprise Beans Using the No-Interface View

I'm trying to learn EJB3,
I created an EJB project with just a bean class:
package com;
import javax.ejb.Local;
import javax.ejb.Stateless;
#Stateless
#LocalBean
public class MyBean {
public MyBean() {
// TODO Auto-generated constructor stub
}
public String getMessage(){
return "Hello";
};
}
I deployed this project on Jboss 6 , then i create a Java project (adding in the build path the ejbProject above and Jboss-client.jar to make RMI calls).
for testing , this is the class i created:
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.MyBean;
public class LanceProgram {
// #EJB
//public static MyBean mybean;
public static void main(String[] args) {
Context ctx;
try {
ctx = new InitialContext();
MyBean exampleBean = (MyBean) ctx.lookup("MyBean");
System.out.println(exampleBean.getMessage());
} catch (NamingException e) {
e.printStackTrace();
}
}
}
Normally, when running this, i should have a reference to MyBean,but it's null and i have this error message (using JNDI lookup):
Exception in thread "main" java.lang.ClassCastException: org.jnp.interfaces.NamingContext cannot be cast to com.MyBean
at LanceProgram.main(LanceProgram.java:17)
While with an EJB injection i have a NullPointerException !
this i my jndi.properties file specifications:
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.provider.url=localhost:1099
java.naming.factory.url.pkgs=org.jboss.ejb.client.naming
I'm trying to make a call to a bean which doesn't implements an interface.
Thanks for helping

Resources