Glassfish with Mojarra 2.2 and EJB: Injection Fail (NullPointerException) - glassfish

i have a normal dynamic web project with a Glassfish 3 server.
I have a managed-bean that injects a stateless bean.
With Mojarra 2.1.6 all works fine.
But when i add javax.faces-2.2.7.jar (Mojarra) to my Web-Inf lib folder and try to access to my site i get an Nullpointerexception for my "service".
The deploy and the new mojarra version is successful accepted.
EXCEPTION: java.lang.NullPointerException
at bean.MyBean.init(MyBean.java:18)
Example Code:
Managed- Bean:
#ManagedBean
#ViewScoped
public class MyBean {
#EJB
private MyStatelessBean statelessBean;
private String hello;
#PostConstruct
public void init(){
setHello(statelessBean.sayHello());
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
}
Stateless- Bean:
#Stateless
public class MyStatelessBean {
public String sayHello(){
return "Hello";
}
}
XHTML:
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
</h:head>
<h:body>
<h:outputText value="#{myBean.hello}" />
</h:body>
</html>

Solution was reset glassfish cache and all works fine ;)

Related

Spring AMQP application configuration from XML to Java

I'm struggling with rewriting RabbitMQ application configuration from XML to Java. Sadly once the code is executed, quite general error appears:
org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException:
Failed to invoke target method 'receiveMessage' with
argument type = [class [B], value = [{[B#3bd0e47}]
...
Caused by: java.lang.NoSuchMethodException: com.mycompany.MessageListener.receiveMessage([B)
Application works if I base my configuration on XML, listed below.
I tried to rewrite it, basing on Spring Integration, AMQP, Rabbit documentation. Nevertheless, spring configuration documentation is mostly xml based, hence my question.
XML conf:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="http://www.springframework.org/schema/integration/amqp
http://www.springframework.org/schema/integration/amqp/spring-integration-amqp.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<rabbit:connection-factory id="connectionFactory" host="mycompany-host"
username="mycompany-username"
password="mycompany-password"
virtual-host="mycompany-vhost"/>
<rabbit:template id="mycompany-template" connection-factory="connectionFactory" />
<rabbit:admin id="admin" connection-factory="connectionFactory" />
<!-- ##### -->
<rabbit:queue id="queue-id" name="queue-name" declared-by="admin"/>
<rabbit:direct-exchange name="mycompany-incoming-events" declared-by="admin">
<rabbit:bindings>
<rabbit:binding queue="queue-name" key="" />
</rabbit:bindings>
</rabbit:direct-exchange>
<!-- ##### -->
<int-amqp:inbound-channel-adapter channel="mycompany-channel"
queue-names="queue-name" connection-factory="connectionFactory" />
<int:chain input-channel="mycompany-channel">
<int:transformer>
<bean class="com.mycompany.MyCompanyParser"/>
</int:transformer>
<int:filter expression="payload.header != null"/>
<int:transformer>
<bean class="com.mycompany.MyCompanyHeaderEnricher"/>
</int:transformer>
<int:recipient-list-router>
<int:recipient channel="dataSubmittedChannel"/>
</int:recipient-list-router>
</int:chain>
<int:chain input-channel="dataSubmittedChannel">
<int:filter expression="headers.mycompany_enriched_header.name().equals('MY_COMPANY_CONSTRAINT')" />
<int:service-activator>
<bean class="com.mycompany.MessageListener"/>
</int:service-activator>
</int:chain>
</beans>
Java listener:
#Component
public class MessageListener {
public void receiveMessage(final MyCompanyParsedType msg){
System.out.println(msg.toString());
}
}
After some rewriting I managed to came up with this Java based configuration:
import com.nxcs3.gamefetcher.configuration.SampleConfiguration;
import com.nxcs3.gamefetcher.listener.GameMessageListener;
import nxcs.drept.nxcs2events.EventHeadersEnricher;
import nxcs.drept.nxcs2events.EventParser;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter;
import org.springframework.integration.dsl.IntegrationFlow;
#SpringBootApplication
public class MyCompanySpringBootApp {
public static final String MESSAGE_QUEUE = "queue-name";
public static final String MESSAGE_EXCHANGE = "mycompany-incoming-events";
public static void main(String[] args) {
SpringApplication.run(MyCompanySpringBootApp.class);
}
#Bean
public DirectExchange exchange(){
return new DirectExchange(MESSAGE_EXCHANGE);
}
#Bean
public Queue queue(){
return new Queue(MESSAGE_QUEUE, true);
}
#Bean
public Binding binding(Queue queue){
return BindingBuilder.bind(queue).to(exchange()).with(MESSAGE_QUEUE);
}
#Bean
MessageListenerAdapter listenerAdapter(MessageListener receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}
#Bean
public IntegrationFlow flow(){
return f -> f.log()
.transform(new MyCompanyParser())
.filter("payload.header != null")
.transform(new MyCompanyHeaderEnricher())
.filter("headers.mycompany_enriched_header.name().equals('MY_COMPANY_CONSTRAINT')");
}
#Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(MESSAGE_QUEUE);
container.setMessageListener(listenerAdapter);
return container;
}
}
I supply connection details through yaml.
As I mentioned previously, I clearly miss something.
Any ideas where did the configuration went wrong?
Added section after comments, proposed solution:
So I removed MessageListenerAdapter and replaced it using AmqpInboundChannelAdapter and #ServiceActivator
Result would look like:
#SpringBootApplication
public class MyCompanySpringBootApp {
public static final String MESSAGE_QUEUE = "queue-name";
public static final String MESSAGE_EXCHANGE = "mycompany-incoming-events";
public static void main(String[] args) {
SpringApplication.run(MyCompanySpringBootApp.class);
}
#Bean
public DirectExchange exchange(){
return new DirectExchange(MESSAGE_EXCHANGE);
}
#Bean
public Queue queue(){
return new Queue(MESSAGE_QUEUE, true);
}
#Bean
public Binding binding(Queue queue){
return BindingBuilder.bind(queue).to(exchange()).with(MESSAGE_QUEUE);
}
#Bean
public AmqpInboundChannelAdapter
channelAdapter(SimpleMessageListenerContainer container){
AmqpInboundChannelAdapter amqpInboundChannelAdapter = new
AmqpInboundChannelAdapter(container);
amqpInboundChannelAdapter.setOutputChannelName("adapter");
return amqpInboundChannelAdapter;
}
#Bean
public MessageListener handler(){
return new MessageListener();
}
#Bean
public IntegrationFlow flow(){
return f -> f.log()
.transform(new MyCompanyParser())
.filter("payload.header != null")
.transform(new MyCompanyHeaderEnricher())
.filter("headers.mycompany_enriched_header.name().equals('MY_COMPANY_CONSTRAINT')");
}
#Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(MESSAGE_QUEUE);
container.setMessageListener(listenerAdapter);
return container;
}
}
and listener:
#Component
public class MessageListener {
#ServiceActivator(inputChannel = "adapter")
public void receiveMessage(final MyCompanyParsedType msg){
System.out.println(msg.toString());
}
}
Which brings us a little bit closer, because messages are being accepted and processed inside of receiveMessage method.
However somehow coming messages do not pass through IntegrationFlow filters. Messages appear to be totally random. I added imports
The MessageListenerAdapter uses a SimpleMessageConverter by default.
And its logic is based on the presence of the contentType property.
According to your error, that sounds like there is no this property in the consumed message, therefore it falls back to the message.getBody(), which is byte[] anyway.
You may consider to specify a desired MessageConverter into that MessageListenerAdapter, e.g. SerializerMessageConverter with the ignoreContentType = true.

How to use arquillian to test EJB calling webservices using #webserviceref annotation

I'm trying to use arquillian to test one method of an EJB using a webservice through #WebServiceRef annotation
In my method decorated by #Deployment I declared the resource
#Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class)
.addPackages(true, .... PortType.class.getPackage())
.addAsResource("test-my.wsdl","my.wsdl")
.addAsManifestResource("META-INF/beans.xml", "beans.xml").addAsManifestResource("META-INF/test-persistence.xml", "persistence.xml");
}
Then I coded the bean as following
#Stateless
#LocalBean
public class WSBean {
#WebServiceRef(wsdlLocation = "/my.wsdl")
PortType portType;
public void test() throws Exception{
portType.lireAdresseClient(null, null);
}
}
and the test
#RunWith(Arquillian.class)
public class WSintegrationTest extends DefaultServicesIntegrationTest {
#Deployment
....
#Inject
private WSBean wsBean;
#Test
public void testAppel() throws Exception {
System.out.println("TEST APPEL");
wsBean.test();
}
}
Can I do that with Arquillian ?
How can I fix it ?
Thanks
Regards
Also if you want you can take a look at https://github.com/javaee-samples/javaee7-samples/tree/master/jaxws you will find examples of JAXWS with its Arquillian test.

EJB2 Authorization related simple program ( java.lang.SecurityException: User: manager, failed to be authenticated.)

I have written the following files
-------------------------------
ejb-jar.xml
-------------
<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC
'-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN'
'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>HelloEJB2</ejb-name>
<home>com.jlcindia.ejb2.hello.HelloHome</home>
<remote>com.jlcindia.ejb2.hello.HelloRemote</remote>
<ejb-class>com.jlcindia.ejb2.hello.HelloBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<security-role-ref>
<role-name>managers</role-name>
<role-link>manager</role-link>
</security-role-ref>
<security-role-ref>
<role-name>students</role-name>
<role-link>student</role-link>
</security-role-ref>
<security-role-ref>
<role-name>administrators</role-name>
<role-link>administrator</role-link>
</security-role-ref>
</session>
</enterprise-beans>
<assembly-descriptor>
<security-role>
<role-name>manager</role-name>
</security-role>
<security-role>
<role-name>student</role-name>
</security-role>
<security-role>
<role-name>administrator</role-name>
</security-role>
</assembly-descriptor>
</ejb-jar>
weblogic-ejb-jar.xml (using weblogic 8)
----------------------
<?xml version="1.0"?>
<!DOCTYPE weblogic-ejb-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 8.1.0 EJB//EN'
'http://www.bea.com/servers/wls810/dtd/weblogic-ejb-jar.dtd'>
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>HelloEJB2</ejb-name>
<jndi-name>JLCHelloHomeJNDI2</jndi-name>
</weblogic-enterprise-bean>
<security-role-assignment>
<role-name>manager</role-name>
<principal-name>managers</principal-name>
</security-role-assignment>
</weblogic-ejb-jar>
HelloHome.java
-----------------
package com.jlcindia.ejb2.hello;
import java.rmi.RemoteException;
import javax.ejb.*;
public interface HelloHome extends EJBHome{
public HelloRemote create()throws CreateException,RemoteException;
}
HelloRemote.java
----------------
package com.jlcindia.ejb2.hello;
import java.rmi.RemoteException;
import javax.ejb.*;
public interface HelloRemote extends EJBObject{
public String getMessage(String name)throws RemoteException;
public void balance()throws RemoteException;
public void updateAccount()throws RemoteException;
}
HelloBean.java
------------
package com.jlcindia.ejb2.hello;
import java.rmi.RemoteException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
public class HelloBean implements SessionBean{
SessionContext sc;
public void ejbCreate()throws EJBException,RemoteException{
System.out.println("HelloBean-ejbCreate()");
}
public void ejbActivate() throws EJBException, RemoteException {
System.out.println("HelloBean-ejbActivate()");
}
public void ejbPassivate() throws EJBException, RemoteException {
System.out.println("HelloBean-ejbPassivate()");
}
public void ejbRemove() throws EJBException, RemoteException {
System.out.println("HelloBean-ejbRemove()");
}
public void setSessionContext(SessionContext sc) throws EJBException,
RemoteException {
System.out.println("HelloBean-setSessionContext()");
this.sc=sc;
}
public String getMessage(String name){
String msg="Hello!"+name+"welcome to EJB2 with weblogic8";
System.out.println(msg);
return msg;
}
public void balance(){
if(sc.isCallerInRole("managers")||sc.isCallerInRole("cashiers"))
System.out.println("inside balance");
else{
System.out.println("not manager or administrator for balance");
}
}
public void updateAccount(){
if(sc.isCallerInRole("administrators"))
System.out.println("update account");
else{
System.out.println("not administrators for updatation");
}
}
}
HelloClient.java
-------------
package com.jlcindia.ejb2.hello;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
public class HelloClient {
public static void main(String[] args) {
try{
Properties p=new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
p.put(Context.PROVIDER_URL, "t3://localhost:7001");
p.put(Context.SECURITY_PRINCIPAL, "manager");
p.put(Context.SECURITY_CREDENTIALS, "manager");
Context ctx=new InitialContext(p);
Object obj=ctx.lookup("JLCHelloHomeJNDI2");
HelloHome home=(HelloHome)obj;
HelloRemote hello=home.create();
String msg=hello.getMessage("srinivas");
hello.updateAccount();
hello.balance();
System.out.println(msg);
}catch(Exception e){
e.printStackTrace();
}
}
}
and I m using weblogic 8
after deploying and
runnig the HelloClient
m getting the following Exception
-----------------
javax.naming.AuthenticationException. Root exception is java.lang.SecurityException: User: manager, failed to be authenticated.at weblogic.common.internal.RMIBootServiceImpl.authenticate(RMIBootServiceImpl.java:95)
at weblogic.common.internal.RMIBootServiceImpl_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:466)
at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:409)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:353)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:144)
at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:404)
at weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:30)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
Please tell me the solution for this n thanks in adv.
There can be several reasons to this:
1) The User: manager does not exists in the Weblogic login realms. In this case, Check your Users/Groups settings in Weblogic.
2) You are not mapping User: manager to any of the roles defined in the deployment descriptor before or after the deployment. Check your deployed application and see if User: manager is mapped to any of the provided roles.
3) Your code is referencing wrong role name.
For ex:
isUserInRole("Manager");
This code won't work because it is not referencing any of the <role-name> defined in the deployment descriptor. Check lowercase, uppercase, exact characters. Because isUserInRole is case sensitive.
Note: Please post the code which does the role checking and also post possible full error stack trace.

Unable to inject dependencies of injected bean with Arquillian

I am using Arquillian to inject the dependencies for my tests. It works OK if I inject the beans directly to my test class, but if the beans have dependencies of their own tht have to be injected, those dependencies do not get injected.
For example: the FacLptConfiguration bean gets imported correctly into my Test Class, but it does not get injected into the CfdFileCreator bean. I injected FacLptConfigurtion to the test class just to confirm that the injection works, but the user of this class is CfdFileCreator.
#RunWith(Arquillian.class)
public class CfdFileCreatorArquillianTest {
#Deployment
public static WebArchive createDepolyment() {
return ShrinkWrap.create(WebArchive.class)
.addClass(FacLptConfiguration.class)
.addClass(InterimFileCreator.class)
.addClass(CfdFileCreator.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsWebInfResource(new File("C:/aLearn/FacLpt/web/WEB-INF/env-entries.properties"));
}
public static String TEST_FOLDER = "C:/aLearn/FacLpt/src/test/testdata/pruebas/";
#Inject
private FacLptConfiguration facLptConfiguration;
#Inject
private CfdFileCreator cfdFileCreator;
#Test
public void createCfd() {
System.out.println("in createCFD");
cfdFileCreator.createCFDFile();
}
}
These injections are not working:
#Singleton
public class CfdFileCreator {
#Inject
private InterimFileCreator interimFileCreator;
#Inject
private FacLptConfiguration facLptConfiguration;
I think your problem is the location of the beans.xml. For a web archive it should be WEB-INF/beans.xml. Use:
addAsWebInfResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"))
See also https://community.jboss.org/thread/175404

Guice not working as expected (with Tomcat, Jersey...)

I'm trying to build an app using Jersey, Rest, Tomcat, c3p0 etc.
I have a ConfigurationManager class I want to be an eager singleton, and Connection pool class I also want to be an eager singleton. Connection pool is using a Configuration Manager annotated with inject but configuration manager inside Connection pool is null, it's not injected for some reason. It's instantiated by guice I can see this from log.
When I inject it in Rest resource class it is working as expected.
Also when I inject it in StartupServlet it's null.
I would very much appreciate it if anyone can shed some light on this. Below you can find web.xml and classes.
web.xml
<servlet>
<servlet-name>StartupServlet</servlet-name>
<servlet-class>net.nemanjakovacevic.ft1p.configuration.StartupServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- set up Google Guice Servlet integration -->
<filter>
<filter-name>guiceFilter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>guiceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>net.nemanjakovacevic.ft1p.configuration.GuiceServletConfiguration</listener-class>
</listener>
GuiceServletConfiguration.java
public class GuiceServletConfiguration extends GuiceServletContextListener {
#Override
protected Injector getInjector() {
return Guice.createInjector(new GuiceConfigurationModule(), new JerseyServletModule() {
#Override
protected void configureServlets() {
/* bind the REST resources */
bind(Test.class);
serve("/*").with(GuiceContainer.class);
}
});
}
}
GuiceConfigurationModule.java
public class GuiceConfigurationModule extends AbstractModule {
#Override
protected void configure() {
bind(ConfigurationManager.class).asEagerSingleton();
bind(ConnectionPool.class).asEagerSingleton();
}
}
ConfigurationManager
public class ConfigurationManager {
// Nothing important here, loading from config file
}
ConnectionPool (It's not working here)
public class ConnectionPool {
private static final Logger log = LoggerFactory.getLogger(ConnectionPool.class);
private ComboPooledDataSource pooledDataSource;
#Inject
private ConfigurationManager cManager;
public ConnectionPool() {
log.info("Initializing c3p0 coonection pool");
pooledDataSource = new ComboPooledDataSource();
try {
//Null pointer exception here, cManager is null
pooledDataSource.setDriverClass(cManager.getJdbcDriverClassName());
pooledDataSource.setJdbcUrl(cManager.getJdbcUrl());
pooledDataSource.setUser(cManager.getDatabaseUsername());
pooledDataSource.setPassword(cManager.getDatabasePassword());
} catch (PropertyVetoException e) {
log.error("Exception during c3p0 initalisation.", e);
//TODO obrada izuzetaka
}
}
}
Test.java (It's working here)
#Path("/test")
public class Test {
#Inject
ConfigurationManager cManager;
#GET
#Path("/{param}")
public Response getMsg(#PathParam("param") String msg){
// cManager is not null, it's injected as it should be
String output = cManager.getDatabaseHostName();
return Response.status(200).entity(output).build();
}
}
Field ConfigurationManager cManager will be injected when object construction is completed. That's why you are getting NPE in constructor and everything is fine in Test.java class.
Consider replacing field injection with constructor injection.
Just try this code
public class ConnectionPool {
#Inject
public ConnectionPool(ConfigurationManager cManager) {
...
}
}