context.lookup in not working in weblogic - ejb-3.0

i am new in ejb3 application
my project is:
ServletController.java
package controller;
import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.HelloUser;
public class ServletController extends HttpServlet {
#Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
try {
InitialContext Context = new InitialContext();
Context context = new InitialContext();
HelloUser helloUser = (HelloUser) context.lookup("ejb3/" + HelloUser.class.getSimpleName() + "/local");
System.out.println(".................................");
helloUser.sayHello("reza");
arg1.sendRedirect("reza");
} catch (Exception e) {
e.printStackTrace();
}
}
}
HelloUser.java:
package com;
import javax.ejb.Local;
#Local
public interface HelloUser {
public void sayHello(String name);
}
HelloUserBean.java
package com;
import javax.ejb.Stateless;
#Stateless
public class HelloUserBean implements HelloUser {
public HelloUserBean() {
}
public void sayHello(String name) {
System.out.println("Hello " + name + " welcome to EJB 3!");
}
}
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Baharan-Framework</display-name>
<welcome-file-list>
<welcome-file>Index.jsp</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>controller.ServletController</servlet-class>
</servlet>
</web-app>
the following error is raised when ServletController is called by webbrowser(URL is:http://localhost:7001/weblogic/rest/jkfg):
javax.naming.NameNotFoundException: While trying to lookup 'ejb3.HelloUser/local' didn't find subcontext 'ejb3'. Resolved ''; remaining name 'ejb3/HelloUser/local'
at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:247)

First of all, Weblogic print all jndi names assigned to every Enterprise bean, and you can get it directly. The second, remove context.lookup("ejb3/" + HelloUser.class.getSimpleName() + "/local"); then in simple cases this function can helps you:
public static <T>T lookupBean(Class<T> beanClass) {
final String jndiName = "java:module/" + beanClass.getSimpleName();
logger.info("lookup : {}", jndiName);
try {
T bean = InitialContext.doLookup(jndiName);
logger.info("detected : {}", bean);
return bean;
}
catch(NamingException e) {
logger.error(e.getMessage(), e);
return null;
}

Can you provide me deployments log?? and rather then trying using initialcontext lookup with #EJB annotation.

Related

restful webservices jax-rs post method not working

I am new to restful web services ..when a post request is made to "/adduser" ,like with request data as {"iduser":5,"name":"bob"} , the rest client gives 500 error and eclipse console gives MySqlSyntaxErrorException: Unknown column 'bob' in 'field list'
DbConnection.java
package com.dbproject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnection {
public static Connection getConnection(){
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql://localhost:3307/thedb","root","root");
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
DbServices.java
package com.dbproject;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class DbServices {
Connection con=DbConnection.getConnection();
public String addUser(int iduser,String name) throws SQLException{
PreparedStatement ps=con.prepareStatement("insert into users values("+iduser+","+name+")");
int res=ps.executeUpdate();
con.close();
if(res>0){
System.out.println("Insert Query Successfull");
return "Done";
}
else{
System.out.println("Insert Query Failed");
return "Error";
}
}
}
Resources.java
package com.dbproject;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
#Path("/user")
public class Resources {
DbServices dbServices=new DbServices();
#POST
#Path("/adduser")
#Consumes(MediaType.TEXT_PLAIN)
#Produces(MediaType.TEXT_PLAIN)
public String addUser(String s) throws SQLException{
Gson gson=new Gson();
UserModel userModel=gson.fromJson(s,UserModel.class);
String str=dbServices.addUser(userModel.getIduser(),userModel.getName());
return str;
}
}
UserModel.java
package com.dbproject;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class UserModel {
private int iduser;
private String name;
public int getIduser() {
return iduser;
}
public String getName() {
return name;
}
public void setIduser(int iduser) {
this.iduser = iduser;
}
public void setName(String name) {
this.name = name;
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>dbproject</display-name>
<servlet>
<servlet-name>Jersey Web Services</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.dbproject</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Services</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>
MySqlSyntaxErrorException
Means you have a syntax error on your SQL.
"insert into users values("+iduser+","+name+")"
String values require quotes. The name value needs to be wrapped in quotes
+",'"+name+"')"
Numbers don't need them.
Aside from this, you are not even use PreparedStatement correctly. You should be using ? syntax, and using the PreparedStatment API to replace them. e.g.
PreparedStatement ps=con.prepareStatement("insert into users values(?,?)");
ps.setInt(1, isuser);
ps.setString(2, name);
int result = ps.executeUpdate();
See Also:
Using Prepared Statements

nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field

I'm trying to wire JERSEY rest services with Spring and i'm facing this exception.
PodcastResource
package com.integration.messenger.resources;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.integration.messenger.model.Podcast;
import com.integration.messenger.service.PodcastService;
#Path("/podcasts")
#Component
public class PodcastResource {
#Autowired
PodcastService podcastService;
#GET
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Podcast> getPodcasts(){
return podcastService.getAllPodcasts();
}
/*#GET
#Produces({ MediaType.APPLICATION_JSON})
public String getMessage(){
return "Helooo";
}*/
}
PodcastService
package com.integration.messenger.service;
import java.util.List;
import com.integration.messenger.model.Podcast;
public interface PodcastService {
List<Podcast> getAllPodcasts();
}
PodcastServiceImp
package com.integration.messenger.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.integration.messenger.model.Podcast;
import com.integration.messenger.repository.PodcastRepository;
#Service("podcastService")
public class PodcastServiceImp implements PodcastService {
#Autowired
PodcastRepository podcastRepository;
private Map<Long, Podcast> podcasts = podcastRepository.getPodcasts();
public PodcastServiceImp() {
podcasts.put(1L, new Podcast(1, "Hello World News", "How to Programme", "www.podcastpedia.com/How to Programme", "Programme"));
podcasts.put(2L, new Podcast(2, "Hello Jersey News", "Restfull Implementation", "www.podcastpedia.com/Restfull Implementation", "Restfull"));
}
public List<Podcast> getAllPodcasts() {
return new ArrayList<Podcast>(podcasts.values());
}
}
PodcastRepository
package com.integration.messenger.repository;
import java.util.Map;
import com.integration.messenger.model.Podcast;
public interface PodcastRepository {
Map<Long, Podcast> getPodcasts();
}
PodcastRepositoryImpl
package com.integration.messenger.repository;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.integration.messenger.model.Podcast;
#Repository
public class PodcastRepositoryImpl implements PodcastRepository {
private static Map<Long, Podcast> podcasts = new HashMap<Long, Podcast>();
public Map<Long, Podcast> getPodcasts() {
return podcasts;
}
}
Podcast
package com.integration.messenger.model;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Podcast implements Serializable{
private static final long serialVersionUID = -1471231465385956738L;
#XmlElement(name = "id")
private long id;
#XmlElement(name = "feed")
private String feed;
#XmlElement(name = "title")
private String title;
#XmlElement(name = "linkOnPodcastpedia")
private String linkOnPodcastpedia;
#XmlElement(name = "description")
private String description;
public Podcast(int id, String feed, String title, String linkOnPodcastpedia, String description) {
this.id = id;
this.feed = feed;
this.title = title;
this.linkOnPodcastpedia = linkOnPodcastpedia;
this.description = description;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFeed() {
return feed;
}
public void setFeed(String feed) {
this.feed = feed;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLinkOnPodcastpedia() {
return linkOnPodcastpedia;
}
public void setLinkOnPodcastpedia(String linkOnPodcastpedia) {
this.linkOnPodcastpedia = linkOnPodcastpedia;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
MyApplication
package com.integration.messenger;
import org.glassfish.jersey.jackson1.Jackson1Feature;
import org.glassfish.jersey.server.ResourceConfig;
import com.integration.messenger.resources.PodcastResource;
public class MyApplication extends ResourceConfig{
/**
* Register JAX-RS application components.
*/
public MyApplication() {
// register application resources
register(PodcastResource.class);
// register features
// register Jackson JSON providers - for the application to understand JSON data
register(Jackson1Feature.class);
}
}
ApplicationContext.xml
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:component-scan base-package="com.integration.messenger" />
</beans>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>jersey-Spring-Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.integration.messenger.MyApplication</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-Spring-Application</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<display-name>Restful Web Application</display-name>
</web-app>
ERROR:
WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'podcastResource': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.integration.messenger.service.PodcastService com.integration.messenger.resources.PodcastResource.podcastService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'podcastService' defined in file [C:\My_Workspaces\My_Work\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\messenger\WEB-INF\classes\com\integration\messenger\service\PodcastServiceImp.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.integration.messenger.service.PodcastServiceImp]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
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.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)
I guess you need to make some configuration related changes to integrate Spring with Jersey. Some I can think of,
Register Spring ContextLoaderListener. (This loads the spring xml file).
Make use of spring related jersey servlet com.sun.jersey.spi.spring.container.servlet.SpringServlet or org.glassfish.jersey.servlet.ServletContainer(in the latest versions I believe)
Specify in the spring xml file.
-Madhu.

Problems with CDI - ( Weld + TomCat7 + JSF )

I'm starting a project with CDI using weld, and am getting the following error when I try to injection:
#Inject
private UserRepository repository;
Console:
INFO: Starting Servlet Engine: Apache Tomcat/7.0.12
13:16:22,859 INFO servletWeldServlet:57 - WELD-ENV-001008: Initialize Weld using ServletContainerInitializer
13:16:22,875 INFO Version:151 - WELD-000900: 2.2.5 (Final)
13:16:22,906 INFO Bootstrap:206 - WELD-000101: Transactional services not available. Injection of #Inject UserTransaction not available. Transactional observers will be invoked synchronously.
13:16:22,937 WARN Interceptor:47 - WELD-001700: Interceptor annotation class javax.ejb.PostActivate not found, interception based on it is not enabled
13:16:22,937 WARN Interceptor:47 - WELD-001700: Interceptor annotation class javax.ejb.PrePassivate not found, interception based on it is not enabled
13:16:23,046 INFO servletTomcat:45 - WELD-ENV-001100: Tomcat 7+ detected, CDI injection will be available in Servlets, Filters and Listeners.
org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type UserRepository with qualifiers #Default
at injection point [BackedAnnotatedField] #Inject private br.com.controllers.UserController.repository
at br.com.controllers.UserController.repository(UserController.java:0)
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:372)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:293)
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:167)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:531)
at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:68)
at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:66)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:60)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:53)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
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)
EntityManagerFactory.java
package br.com.util;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class EntityManagerFactory {
#PersistenceContext(unitName="default")
private EntityManager em;
#Produces
public EntityManager create() {
return em;
}
public void close(#Disposes EntityManager em) {
em.close();
}
}
Repository.java
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
public abstract class Repository<T, I extends Serializable> {
#Inject
protected final EntityManager entityManager;
protected final Class<T> clazz;
protected Repository(EntityManager entityManager) {
this.entityManager = entityManager;
#SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
this.clazz = clazz;
}
public void refresh(T entity){
entityManager.refresh(entity);
}
public void create(T entity) {
entityManager.persist(entity);
}
public T update(T entity) {
return entityManager.merge(entity);
}
public void destroy(T entity) {
entityManager.remove(entity);
}
public T find(I id) {
return entityManager.find(clazz, id);
}
public List<T> findAll() {
TypedQuery<T> query = entityManager.createQuery("FROM " + clazz.getName() ,clazz);
List<T> resultList = query.getResultList();
return resultList;
}
}
UserRepositoryImpl.java
package br.com.repositories;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import br.com.models.User;
#Transactional
public class UserRepositoryImpl extends Repository<User, Long >implements UserRepository {
protected UserRepositoryImpl(EntityManager entityManager) {
super(entityManager);
}
}
UserController.java
package br.com.controllers;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import br.com.repositories.UserRepository;
#Named("userController")
#RequestScoped
public class UserController {
#Inject
private UserRepository repository;
UserController(){
}
#PostConstruct
public void init(){
System.out.println("started");
}
public String getMessage(){
return "test";
}
public void create(){
System.out.println("test method");
}
}
META-INF/beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>
META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Manager pathname=""/> <!-- disables storage of sessions across restarts -->
<Resource name="BeanManager"
auth="Container"
type="javax.enterprise.inject.spi.BeanManager"
factory="org.jboss.weld.resources.ManagerObjectFactory"/>
</Context>
WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>wochenbericht</display-name>
<welcome-file-list>
<welcome-file>index.jsf</welcome-file>
</welcome-file-list>
<!-- CDI - WELD -->
<listener>
<listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
</listener>
<resource-env-ref>
<resource-env-ref-name>BeanManager</resource-env-ref-name>
<resource-env-ref-type>
javax.enterprise.inject.spi.BeanManager
</resource-env-ref-type>
</resource-env-ref>
<!-- JSF -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<!-- SESSION TIMEOUT -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- CONTEXT LOCAL -->
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
<param-value>2</param-value>
</context-param>
<context-param>
<param-name>javax.faces.WEBAPP_RESOURCES_DIRECTORY</param-name>
<param-value>/assets</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- SECURITY SETTINGS -->
<security-constraint>
<display-name>Restrict direct access to XHTML files</display-name>
<web-resource-collection>
<web-resource-name>XHTML files</web-resource-name>
<url-pattern>*.xhtml</url-pattern>
</web-resource-collection>
<auth-constraint />
</security-constraint>
My Libs:
antlr-2.7.7.jar
aopalliance.jar
c3p0-0.9.1.jar
cdi-api-1.1.jar
dom4j-1.6.1.jar
EasyCriteria-3.1.0.jar
hibernate-c3p0-4.3.6.Final.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.6.Final.jar
hibernate-entitymanager-4.3.5.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hibernate-validator-4.3.0.Final.jar
javassist-3.18.1-GA.jar
javax.inject.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
jsf-api-2.2.8.jar
jsf-impl-2.2.8.jar
log4j-1.2.16.jar
postgresql-9.2-1003.jdbc4.jar
slf4j-api-1.6.6.jar
slf4j-jdk14-1.6.6.jar
slf4j-log4j12-1.6.1.jar
validation-api-1.0.0.GA.jar
weld-se-core-2.2.5.Final.jar
weld-servlet-2.2.5.Final.jar
weld-servlet-core-2.2.5.Final.jar
Can anyone help me? thank you!
Your first problem is that UserRepositoryImpl class doesn't have default (empty) constructor, and nither there is #Produces method, so there is no way to instantiate it. Remove EntityManager entityManager from constructors from Repository and UserRepositoryImpl classes.
Change the constructor in Repository to:
protected Repository() {
/// this.entityManager = entityManager; // <= this is already injected by
// #Inject protected final EntityManager entityManager;
#SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
this.clazz = clazz;
}
Your second problem will be incorrect injection of PersistenceContext. You either need to use EJB (to inject EntityManager via #PersistenceContext) or for web modules use:
#PersistenceUnit(unitName="default")
EntityManagerFactory emf;
...
EntityManager em = emf.createEntityManager();
And your third problem will be transactions - again you either need to switch to EJB, or handle transactions while persisting your beans.
I'd recommend first read the following before coding:
CDI documentation
Contexts and Dependency Injection for Java EE (Tutorial)
JPA (Tutorial)
Managing Entities
#Gas Thanks for you feedback and links, now works, I do not know if it's the best way:
UserRepositoryImpl
package br.com.repositories;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import br.com.models.User;
#Transactional
public class UserRepositoryImpl extends Repository<User, Long >implements UserRepository {
#Inject
protected UserRepositoryImpl(EntityManager entityManager) {
super(entityManager);
}
}
Repository
package br.com.repositories;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
public abstract class Repository<T, I extends Serializable> {
protected final EntityManager entityManager;
protected final Class<T> clazz;
protected Repository(EntityManager entityManager) {
this.entityManager = entityManager;
#SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
this.clazz = clazz;
}
public void refresh(T entity){
entityManager.refresh(entity);
}
public void create(T entity) {
entityManager.persist(entity);
}
public T update(T entity) {
return entityManager.merge(entity);
}
public void destroy(T entity) {
entityManager.remove(entity);
}
public T find(I id) {
return entityManager.find(clazz, id);
}
public List<T> findAll() {
TypedQuery<T> query = entityManager.createQuery("FROM " + clazz.getName() ,clazz);
return query.getResultList();
}
}
EntityManagerProducer
package br.com.util;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
#ApplicationScoped
public class EntityManagerProducer {
private EntityManagerFactory factory;
public EntityManagerProducer() {
factory = Persistence.createEntityManagerFactory("default");
}
#Produces #RequestScoped
public EntityManager createEntityManager() {
return factory.createEntityManager();
}
public void closeEntityManager(#Disposes EntityManager manager) {
manager.close();
}
}
UserController
package br.com.vw.controllers;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import br.com.models.User;
import br.com.repositories.UserRepository;
#Named("userController")
#RequestScoped
public class UserController {
#Inject UserRepository userRepository;
UserController(){
}
#PostConstruct
public void init(){
System.out.println("Inicialilizado o construtor");
}
public String getMessage(){
return "Conteúdo da mensagem";
}
public void create(){
System.out.println("Método create disparado");
User user = new User();
user.setEmail("email#uol.com.br");
user.setName("Marcos de Freitas");
userRepository.create(user);
}
}
Tks

why is autowired null? use spring jersey integration

I have a application controller with a method getApplication(). This method returns a applicationJson objekt for my client.
In this method i call on an application builder.
The application builder is a factory and generate a special application builder object.
In the special application builders be used mapper and services, the services used daos.
All services and daos sind beans and confirgure in the applicationContext.xml and serviceBeans.xml.
When calling the method getApplication() is an exception in my eclipse java console.
The problem occurs in the class MobileApplicationBuilder and method buildPagenaviData()
Class ApplicationController:
package core.application.controller;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import core.application.builder.ApplicationBuilder;
import core.application.builder.MobileApplicationBuilder;
import core.application.factories.ApplicationControllerProcessHelperFactory;
import core.application.mapper.json.ApplicationJson;
import core.application.process.helper.MobileApplicationBuildHelper;
import core.base.abstracts.ControllerAbstract;
import core.security.model.interfaces.SystemSettingsModelInterface;
import core.security.service.interfaces.SystemLanguagesServiceInterface;
import core.security.service.interfaces.SystemSettingsServiceInterface;
import core.security.service.interfaces.SystemUserServiceInterface;
/**
*
* Class: {#link ApplicationController}
*
* Über diesen Controller wird die Anwendung zusammengebaut und als großes JSON Objekt an den Client geschickt.
*
*/
#Path("/app")
#Component
#Scope("session")
public class ApplicationController extends ControllerAbstract {
private static final String JSON_PATH = System.getProperty("wtp.deploy") + "/decon_fm_version5/WEB-INF/classes/json/";
#Autowired
private ApplicationBuilder applicationBuilder;
#Autowired
#Qualifier("systemUserService")
private SystemUserServiceInterface systemUserService;
#Autowired
#Qualifier("systemLanguagesService")
private SystemLanguagesServiceInterface languagesService;
#Autowired
#Qualifier("systemSettingsService")
private SystemSettingsServiceInterface systemSettings;
private ApplicationJson applicationJson = null;
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
/**
* Process für den Build der gesamten Applikation.
* Es wird ein gemapptes JSON Objekt zurück gegeben welches dann auf dem Client verarbeitet werden kann.
* Größere Build Logiken werden in eine Helper Klasse ausgelagert, welche über eine entsprechende Factory geladen wird.
* #return
*/
#GET
#Path("/build")
#Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public ApplicationJson getApplication() {
// auslesen und Zuwiesung der User Settings
SystemSettingsModelInterface settingsModel = systemSettings.getSettingsByUser(Long.parseLong(session.getAttribute("idUser").toString()));
systemUserService.model().setSettings(settingsModel);
applicationBuilder.setClientApp(settingsModel.getClientView())
.setSession(session)
.setUserModel(this.deconSecurity.getUser());
applicationJson = applicationBuilder.build();
return applicationJson;
}
}
Class ApplicationBuilder:
package core.application.builder;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.WordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import core.application.mapper.json.ApplicationJson;
import core.security.model.interfaces.SystemUserModelInterface;
import core.security.service.interfaces.SystemLanguagesServiceInterface;
public class ApplicationBuilder {
/**
* Klassennamen Suffix für jeden Builder
*/
private static final String CLASS_SUFFIX = "ApplicationBuilder";
/**
* http session objekt aus dem controller
*/
private HttpSession session;
/**
* Client Application die vom Nutzer eingestellt wurde
*/
private String clientApp;
private SystemUserModelInterface userModel;
#Autowired
#Qualifier("systemLanguagesService")
private SystemLanguagesServiceInterface languageService;
/**
* Auszuführender Builder gegen Interface Sicherung
*/
private ApplicationBuilderInterface builder;
public ApplicationJson build() {
ApplicationJson application = null;
try {
builder = (ApplicationBuilderInterface) Class.forName("core.application.builder." + WordUtils.capitalize(clientApp) + CLASS_SUFFIX).newInstance();
builder.setSession(session);
builder.setUserModel(userModel);
builder.setLanguages(languageService.getLanguages());
builder.setFavorite(userModel.getSettings().getFavorite());
application = builder.build();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return application;
}
public ApplicationBuilder setClientApp(String clientApp) {
this.clientApp = clientApp;
return this;
}
public ApplicationBuilder setSession(HttpSession session) {
this.session = session;
return this;
}
public ApplicationBuilder setUserModel(SystemUserModelInterface userModel) {
this.userModel = userModel;
return this;
}
}
Class MobileApplicationBuilder:
package core.application.builder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import core.application.mapper.json.ApplicationAnimateDataJson;
import core.application.mapper.json.ApplicationIconbarJson;
import core.application.mapper.json.ApplicationJson;
import core.application.mapper.json.ApplicationPagenaviJson;
import core.application.mapper.json.Formular;
import core.application.mapper.json.MobileApplicationJson;
import core.cache.model.interfaces.ApplicationCacheModelInterface;
import core.cache.service.ApplicationCacheService;
#Component
#Scope("session")
public class MobileApplicationBuilder extends ApplicationBuilderAbstract implements ApplicationBuilderInterface {
private static final String JSON_PATH = System.getProperty("wtp.deploy") + "/decon_fm_version5/WEB-INF/classes/json/";
private MobileApplicationJson mapper = new MobileApplicationJson();
#Autowired
#Qualifier("applicationCacheService")
private ApplicationCacheService applicationCacheService;
public ApplicationJson build() {
mapper.setStartPage(getFavorite())
.setSystemLangguages(getLanguages())
.setSystemUser(getUserModel());
buildIconbar();
buildAnimateData();
buildPagenaviData();
return mapper;
}
/**
* Zusammenbau sämtlicher Iconbars im System
*/
protected void buildIconbar() {
ApplicationIconbarJson iconbarMapper = new ApplicationIconbarJson();
File directory = new File(JSON_PATH + "/iconbars/");
File[] files = directory.listFiles();
Formular formsMapper = new Formular();
for (int i = 0; i < files.length; i++) {
try {
byte[] iconbar = Files.readAllBytes(Paths.get(files[i].getAbsolutePath()));
iconbarMapper = getObjectMapper().readValue(iconbar, ApplicationIconbarJson.class);
mapper.setIconbars(iconbarMapper.getName().toString(), iconbarMapper);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Zusammenbau der Animate Pages für die Application
*/
protected void buildAnimateData() {
ApplicationAnimateDataJson aadnMapper = new ApplicationAnimateDataJson();
try {
byte[] animateData = Files.readAllBytes(Paths.get(JSON_PATH + "anmiate_data.json"));
aadnMapper = getObjectMapper().readValue(animateData, ApplicationAnimateDataJson.class);
mapper.setAnimateData(aadnMapper);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Zusammenbau des Objektes für Daten der Module welche in der Applikation verfügbar sein sollen
*/
protected void buildPagenaviData() {
String component = "pagenaviData";
// ApplicationCacheServiceInterface cacheService = new ApplicationCacheService();
// here arises a problem
ApplicationCacheModelInterface cache = applicationCacheService.getCacheResource(
Long.parseLong(session.getAttribute("idUser").toString()),
component,
deconSecurity().getUser().getSettings().getClientView());
if (cache == null) {
List<ApplicationPagenaviJson> list = null;
File directory = new File(JSON_PATH + "/pagesnavi/");
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
try {
String key = files[i].getName().substring(0, files[i].getName().indexOf("."));
byte[] navi = Files.readAllBytes(Paths.get(files[i].getAbsolutePath()));
list = getObjectMapper().readValue(navi, getObjectMapper().getTypeFactory().constructCollectionType(
List.class, ApplicationPagenaviJson.class));
mapper.setPagenaviData(key, list);
} catch (IOException e) {
e.printStackTrace();
}
}
// cache Module Event um die Daten für die Pagenavi nach Rechten zu kontrollieren und entsprechend in den Cache zu speichern
eventDispatcher().dispatch("cleanAndCachePagenaviData", this);
} else {
try {
HashMap<String, List<ApplicationPagenaviJson>> map = getObjectMapper().readValue(
cache.getJsonObject(),
HashMap.class);
mapper.setPagenaviData(map);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Class ApplicationCacheService:
package core.cache.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import core.cache.dao.interfaces.ApplicationCacheDaoInterface;
import core.cache.model.interfaces.ApplicationCacheModelInterface;
import core.cache.service.interfaces.ApplicationCacheServiceInterface;
/**
* Class: ApplicationCacheService
*
* Service Klasse für das verwalten einer Application Cache Speicherung
*
*/
#Service
public class ApplicationCacheService implements ApplicationCacheServiceInterface {
#Autowired
#Qualifier("applicationCacheDao")
private ApplicationCacheDaoInterface cacheDao;
public void saveCacheObject(Object obj) {
cacheDao.saveCacheObject(obj);
}
public boolean isCacheUpdated(Long id, String applicationComponent) {
return cacheDao.isCacheUpdated(id, applicationComponent);
}
public ApplicationCacheModelInterface getCacheResource(Long idUser, String applicationComponent, String applicationType) {
return cacheDao.getCacheResource(idUser, applicationComponent, applicationType);
}
}
Class ApplicationCacheDao:
package core.cache.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import core.base.abstracts.DeconDaoAbstract;
import core.cache.dao.interfaces.ApplicationCacheDaoInterface;
import core.cache.model.ApplicationCacheModel;
import core.cache.model.interfaces.ApplicationCacheModelInterface;
/**
* Class: ApplicationCacheDao
*
* DAO Klasse für das speichern, auslesen und verwalten der ApplicationCache Tabelle
*
*/
#Repository
#Transactional
public class ApplicationCacheDao extends DeconDaoAbstract implements ApplicationCacheDaoInterface {
public void saveCacheObject(Object obj) {
try {
super.getSession().save(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isCacheUpdated(Long id, String applicationComponent) {
boolean isUpdated = false;
String hql = "from ApplicationCacheModel where idUser = " + id + " AND applicationComponent = '" + applicationComponent + "'";
List<ApplicationCacheModel> list = super.getSession().createQuery(hql).list();
if (list.size() == 0) {
isUpdated = true;
} else {
ApplicationCacheModel obj = list.get(0);
if (obj.isUpdate() != false) {
isUpdated = true;
}
}
return isUpdated;
}
public ApplicationCacheModelInterface getCacheResource(Long idUser, String applicationComponent, String applicationType) {
String hql = "from ApplicationCacheModel where idUser = " + idUser + " AND applicationComponent = '" + applicationComponent + "' AND applicationType = '" + applicationType +"'";
List<ApplicationCacheModel> list = super.getSession().createQuery(hql).list();
return (list.size() > 0) ? list.get(0) : null;
}
}
serviceBeans.xml
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd">
<!-- User Service -->
<bean id="systemUserService" class="core.security.service.SystemUserService"></bean>
<bean id="systemUserModel" class="core.security.model.SystemUserModel" />
<bean id="systemUserDao" class="core.security.dao.SystemUserDao" />
<!-- SystemRolesService -->
<bean id="systemRoleService" class="core.security.service.SystemRoleService"></bean>
<bean id="systemRoleModel" class="core.security.model.SystemRoleModel"></bean>
<bean id="systemRoleDao" class="core.security.dao.SystemRoleDao"></bean>
<!-- SystemGroupService -->
<bean id="systemGroupService" class="core.security.service.SystemGroupService"></bean>
<bean id="systemGroupModel" class="core.security.model.SystemGroupModel"></bean>
<bean id="systemGroupDao" class="core.security.dao.SystemGroupDao"></bean>
<!-- SystemLanguagesService -->
<bean id="systemLanguagesService" class="core.security.service.SystemLanguagesService"></bean>
<bean id="systemLanguagesModel" class="core.security.model.SystemLanguagesModel"></bean>
<bean id="systemLanguagesDao" class="core.security.dao.SystemLanguagesDao"></bean>
<!-- System Setting Service -->
<bean id="systemSettingsService" class="core.security.service.SystemSettingsService"></bean>
<bean id="systemSettingsModel" class="core.security.model.SystemSettingsModel"></bean>
<bean id="systemSettingsDao" class="core.security.dao.SystemSettingsDao"></bean>
<!-- ApplicationCacheService -->
<bean id="applicationCacheModel" class="core.cache.model.ApplicationCacheModel"></bean>
<bean id="applicationCacheDao" class="core.cache.dao.ApplicationCacheDao"></bean>
<bean id="applicationCacheService" class="core.cache.service.ApplicationCacheService"></bean>
</beans>
applicationContext.xml
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd">
<context:annotation-config />
<context:component-scan base-package="core.application.controller" />
<context:component-scan base-package="core.security.controller" />
<context:component-scan base-package="core.cache.controller" />
<import resource="database/hibernate.cfg.xml"/>
<import resource="serviceBeans.xml"/>
<bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper"></bean>
<bean id="jsonFactory" class="org.codehaus.jackson.JsonFactory"></bean>
<bean id="mobileJsonMapper" class="core.application.mapper.json.MobileApplicationJson"></bean>
<bean id="desktopJsonMapper" class="core.application.mapper.json.DesktopApplicationJson"></bean>
<bean id="mobileApplicationBuilder" class="core.application.builder.MobileApplicationBuilder">
</bean>
<bean id="desktopApplicationBuilder" class="core.application.builder.DesktopApplicationBuilder"></bean>
<bean id="applicationBuilder" class="core.application.builder.ApplicationBuilder"></bean>
<bean id="deconModuleConfigParser" class="core.base.beans.DeconModuleConfigParser"></bean>
<bean id="deconSessionManager" class="core.base.beans.DeconSessionManager" scope="session"></bean>
<bean id="eventConfigLoader" class="core.event.dispatcher.EventConfigLoader">
<constructor-arg ref="deconModuleConfigParser" />
</bean>
<bean id="eventFactory" class="core.event.dispatcher.EventFactory"></bean>
<bean id="eventDispatcher" class="core.event.dispatcher.EventDispatcher">
<constructor-arg ref="eventFactory" />
<constructor-arg ref="eventConfigLoader" />
</bean>
<bean id="deconSecurity" class="core.base.beans.DeconSecurity"></bean>
<!-- <bean id="sce" class="javax.servlet.ServletContextEvent"></bean> -->
<!-- <import resource="jsonMapperBeans.xml"/> -->
</beans>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Decon FM Version 5</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:META-INF/spring/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>core.base.listeners.DeconSession</listener-class>
</listener>
<servlet>
<servlet-name>Rest Service</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>
core.application.controller;
core.security.controller;
core.cache.controller;
org.codehaus.jackson.jaxrs
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Rest Service</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
The Exception message:
SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException
at core.application.builder.MobileApplicationBuilder.buildPagenaviData(MobileApplicationBuilder.java:94)
at core.application.builder.MobileApplicationBuilder.build(MobileApplicationBuilder.java:47)
at core.application.builder.ApplicationBuilder.build(ApplicationBuilder.java:49)
at core.application.controller.ApplicationController.getApplication(ApplicationController.java:81)
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 com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1480)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1411)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1360)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1350)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Thanks for your help.
I had an overview of your code, I figured the issue. Let me explain why null pointer first.
In your code there are two containers created; Spring and Jersey.
When Jersey is executed you are trying to fetch a bean from spring container, this is not possible , so you need a super container like the (Application Context) to retrieve that bean which is in spring container.
The solution is simple in spring.
Solution : Instead of autowired as dependency injection use this WebApplicationContextUtils.getRequiredWebApplicationContext.getBean(“beanName”);
This is just one way, there are many other ways for dependency injection through Application Context. Try to understand the problem it will help you to get to core of spring bean creation. Rest this solution should work. Cheers

Liferay 6.2 + Spring #Autowired not working in a hook

I am using Spring 4.0.6 with Liferay 6.2. Spring isn't able to inject autowired components in to the hook, object comes as null. I have also tried with spring version 3.1 that comes with liferay. Same code works in portlets but not in hooks.
private ApplicationEventPublisher publisher in ActivityEventPublisher.java is null.
web.xml
<?xml version="1.0"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web- app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.liferay.portal.kernel.servlet.SecurePluginContextListener</listener- class>
</listener>
<listener>
<listener-class>com.liferay.portal.kernel.servlet.PortletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>ViewRendererServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ViewRendererServlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>
</web-app>
ActivityEventPublisher.java
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
import connect.activity.solr.document.ActivityData;
#Component
public class ActivityEventPublisher implements ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher;
#Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
public ApplicationEventPublisher getPublisher() {
return publisher;
}
public void setPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
public void publish(ActivityData data) {
ActivityEvent event = new ActivityEvent(this);
event.setActivityData(data);
this.publisher.publishEvent(event);
}
}
Any help will be much appreciated.
Thanks
Unfortunately, autowired mechanisms are not allowed in hooks, wrappers or startup actions at Liferay.
You can implement an ApplicationContextProvider, it's so easy and useful:
#Component("applicationContextProvider")
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext ctx = null;
public static ApplicationContext getApplicationContext() {
return ctx;
}
#Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
ctx = ac;
}
}
An example of use in a Hook will be the following:
public class PostLoginActionHook extends Action {
// That code "replaces" #Autowired annotation
private final UserProxyService userProxyService = (UserProxyService) ApplicationContextProvider.
getApplicationContext().getBean(UserProxyService.class);
#Override
public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException {
UserVO myCustomUser = userProxyService.getCustomUserByLiferayUser(user.getUserId());
{...}
}
Hope it helps!

Resources