I might be missing something trivial or is it a bug that I could able to follow any property annotated with #DBRef(lazy = true) for my entity objects using Spring Data Rest. I see following exception when I access the property annotated with above annotation.
{
"cause": null,
"message": "Id must be assignable to Serializable! Object of class [null] must be an instance of interface java.io.Serializable"
}
Environment:
Java - 7
Spring Data Rest - 2.1.1.RELEASE
Spring Data Mongo - 1.5.0.RELEASE
Tomcat - 7.x
Update 1:
Entity class:
#Document(collection = "people")
public class Employee {
#Id
private String id;
#DBRef(lazy = true)
private Employee manager;
.... truncated getters/setters
}
Here is the stacktrace
13:57:47.092 [http-bio-8080-exec-4] ERROR o.s.d.r.w.AbstractRepositoryRestController - Id must be assignable to Serializable! Object of class [null] must be an instance of interface java.io.Serializable
java.lang.IllegalArgumentException: Id must be assignable to Serializable! Object of class [null] must be an instance of interface java.io.Serializable
at org.springframework.util.Assert.isInstanceOf(Assert.java:337) ~[spring-core-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at org.springframework.data.rest.webmvc.support.RepositoryEntityLinks.linkToSingleResource(RepositoryEntityLinks.java:147) ~[spring-data-rest-webmvc-2.1.0.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.getSelfLinkFor(PersistentEntityResourceAssembler.java:88) ~[spring-data-rest-webmvc-2.1.0.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.toResource(PersistentEntityResourceAssembler.java:64) ~[spring-data-rest-webmvc-2.1.0.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController$1.apply(RepositoryPropertyReferenceController.java:141) ~[spring-data-rest-webmvc-2.1.0.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController$1.apply(RepositoryPropertyReferenceController.java:110) ~[spring-data-rest-webmvc-2.1.0.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.doWithReferencedProperty(RepositoryPropertyReferenceController.java:463) ~[spring-data-rest-webmvc-2.1.0.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.followPropertyReference(RepositoryPropertyReferenceController.java:148) ~[spring-data-rest-webmvc-2.1.0.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_55]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_55]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_55]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_55]
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) ~[spring-web-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) ~[spring-web-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) ~[spring-webmvc-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:685) ~[spring-webmvc-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) ~[spring-webmvc-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919) ~[spring-webmvc-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851) ~[spring-webmvc-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953) [spring-webmvc-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844) [spring-webmvc-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) [servlet-api.jar:na]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829) [spring-webmvc-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) [servlet-api.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) [catalina.jar:7.0.50]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.50]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat7-websocket.jar:7.0.50]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) [catalina.jar:7.0.50]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.50]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) [catalina.jar:7.0.50]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) [catalina.jar:7.0.50]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) [catalina.jar:7.0.50]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) [catalina.jar:7.0.50]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) [catalina.jar:7.0.50]
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) [catalina.jar:7.0.50]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) [catalina.jar:7.0.50]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:409) [catalina.jar:7.0.50]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1044) [tomcat-coyote.jar:7.0.50]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) [tomcat-coyote.jar:7.0.50]
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315) [tomcat-coyote.jar:7.0.50]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_55]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_55]
at java.lang.Thread.run(Thread.java:745) [na:1.7.0_55]
Update 2:
Repository
#RestResource(rel = "employees", path = "employees")
public interface EmployeeRepository extends
PagingAndSortingRepository<Employee, String> {
}
WebConfiguration
public class WebApplicationInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
public static String CURIE_NAMESPACE = "reference";
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { ApplicationConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfiguration.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/api/*" };
}
#Configuration
#Import({ RespositoryConfig.class })
#ComponentScan(excludeFilters = #Filter({ Service.class,
Configuration.class }))
public static class WebConfiguration extends DelegatingWebMvcConfiguration {
#Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CorsInterceptor());
super.addInterceptors(registry);
}
}
#Configuration
public static class RespositoryConfig extends
RepositoryRestMvcConfiguration {
#Override
public RequestMappingHandlerMapping repositoryExporterHandlerMapping() {
RequestMappingHandlerMapping mapping = super
.repositoryExporterHandlerMapping();
mapping.setInterceptors(new Object[] { new CorsInterceptor() });
return mapping;
}
#Override
protected void configureJacksonObjectMapper(ObjectMapper objectMapper) {
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.configure(
DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
}
#Override
protected void configureRepositoryRestConfiguration(
RepositoryRestConfiguration config) {
config.exposeIdsFor(App.class, BusinessUnit.class, City.class,
Country.class, Employee.class, EmployeeTalentProfile.class,
Feed.class, Goc.class, ManagedGeography.class,
ManagedSegment.class);
}
}
}
Request : http://localhost:8080/reference/api/employees/1010065136/manager
Update 3:
Line 462 of RepositoryPropertyReferenceControllers BeanWrapper.getProperty(prop) is returning default object. Digging further into BeanWrapper code line 125 obj = ReflectionUtils.getField(field, bean) returns LazyLoadingProxy. No call to database is made to populate the object.
Related
I have the next piece of code:
Main class
#SpringBootApplication
#EnableScheduling
public class GeolocalizacionApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(GeolocalizacionApplication.class, args);
}
}
Dao
#Transactional
#Repository
public class UsigRequestPersistanceDaoImpl implements UsigRequestPersistanceDao {
#PersistenceContext
private EntityManager em;
public List<UsigRequestPersistance> getRequest() {
Query query = em.createQuery("select v.requestId from UsigRequestSeq v").getFirstResult();
}
}
Model class
#Entity
#Table(name= "seq_usig_request", schema = "xxxx")
public class UsigRequestSeq {
#Id
#Column(name = "request_id", nullable = false)
private Integer requestId;
public Integer getRequestId() {
return requestId;
}
public void setRequestId(Integer requestId) {
this.requestId = requestId;
}
}
Configuration
#Configuration
#EnableTransactionManagement
public class DatabaseConfiguration {
#Bean
public LocalSessionFactoryBean sessionFactory(){
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan("xxxx");
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.teradata.jdbc.TeraDriver");
dataSource.setUrl("jdbc:teradata://teradata.xxxx/TMODE=ANSI,CHARSET=UTF8");
dataSource.setUsername("xxxx");
dataSource.setPassword("xxxx");
return dataSource;
}
#Bean(name = "properties")
public Properties hibernateProperties(){
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.TeradataDialect");
//properties.put("hibernate.show_sql", "true");
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(){
HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
hibernateTransactionManager.setSessionFactory(sessionFactory().getObject());
return hibernateTransactionManager;
}
}
Application.properties
spring.jpa.database-platform=org.hibernate.dialect.TeradataDialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Then I do have a controller, but I think it's not necessary to put it here. In my controller y havec a method which calls getRequest() method.
Here I have some of the stack
java.lang.NullPointerException: null
at com.xxxx.Geolocalizacion.dao.UsigRequestPersistanceDaoImpl.getRequest(UsigRequestPersistanceDaoImpl.java:82) ~[classes/:na]
at com.xxxx.Geolocalizacion.controller.GeoController.ejecutar(GeoController.java:51) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_181]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_181]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_181]
I believe that I have problems with the createQuery native method, I debug the program and there's where it breaks, but I canĀ“t finds why. Am I missing something?
I'm trying to create my own RouteBuilder but I'm getting the following error:
java.lang.IllegalArgumentException: onException must be defined before any routes in the RouteBuilder
at org.apache.camel.builder.RouteBuilder.onException(RouteBuilder.java:214)
at com.mdw360.ttt.mongo.fab.route.ExceptionBuilder.configure(ExceptionBuilder.java:18)
at org.apache.camel.builder.RouteBuilder.checkInitialized(RouteBuilder.java:322)
at org.apache.camel.builder.RouteBuilder.configureRoutes(RouteBuilder.java:276)
at org.apache.camel.builder.RouteBuilder.addRoutesToCamelContext(RouteBuilder.java:262)
at org.apache.camel.impl.DefaultCamelContext.addRoutes(DefaultCamelContext.java:679)
at org.apache.camel.test.junit4.CamelTestSupport.doSetUp(CamelTestSupport.java:302)
at org.apache.camel.test.junit4.CamelTestSupport.setUp(CamelTestSupport.java:217)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
On my ExceptionBuilder I have this code:
public class ExceptionBuilder extends RouteBuilder{
#Override
public void configure() throws Exception {
ExceptionProcessor exceptionProcessor = new ExceptionProcessor();
onException(Exception.class).process(exceptionProcessor);
}
}
And on my test I have that:
#Test
public void testExceptionWhileRouting() throws Exception {
getMockEndpoint("mock:http").expectedBodiesReceived("Camel rocks");
getMockEndpoint("mock:http").whenAnyExchangeReceived(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("ERROR");
exchange.setException(new ConnectException("Simulated connection error"));
}
});
template.sendBody("direct:file", "Camel rocks");
assertMockEndpointsSatisfied();
}
#Override
protected RouteBuilder createRouteBuilder() {
ExceptionBuilder routeBuilder = new ExceptionBuilder();
routeBuilder.from("direct:file").to("mock:http");
return routeBuilder;
}
As I'm adding the onException into the configure, why it's saying that I must define it before any route?
You need to move this:
from("direct:file").to("mock:http");
to the configure() method, after you call onException(). So it looks like this:
public class ExceptionBuilder extends RouteBuilder{
#Override
public void configure() throws Exception {
onException(Exception.class).process(new ExceptionProcessor());
from("direct:file").to("mock:http");
}
}
Then your createRouteBuilder() method should look like this:
#Override
protected RouteBuilder createRouteBuilder() {
return new ExceptionBuilder();
}
I think the reason it's giving you an error is because routes are expected to contain the from() method call.
You might be able to do something like this if you're trying to create a common exception handling route:
public class ExceptionBuilder extends RouteBuilder{
#Override
public void configure() throws Exception {
from("direct:onException").process(new ExceptionProcessor());
}
}
public class TestRouteBuilder extends RouteBuilder{
#Override
public void configure() throws Exception {
onException(Exception.class).to("direct:onException");
from("direct:start").to("mock:end");
}
}
In my java class i have something like below:
from("direct:dcrm:input")
.routeId("dcrm-route"
.convertBodyTo(Message.class)
.setHeader(
"recipientListHeader",
simple("activemq:"+rdvrQueueName+ ".${body.controllerID}?jmsMessageType=Text&timeToLive="
+ rdvrMessageTimeToLive
+ "&deliveryPersistent=" + deliveryPersistent))
.choice()
.when(simple("${body.messageType} == 'rdvr'"))
.bean(new DcrmMessageHandler(), "process")
.marshal(requestMessage)
.recipientList(header("recipientListHeader"))
.onPrepare(new MesssageProcessor()).parallelProcessing()
.end()
.setBody(constant(StatusCode.SUCCESS))
.otherwise()
.endChoice();
while writing Junit i am doint like this :
#Test
public void testSendMatchingMessage() throws Exception {
String expectedBody = "<matched/>";
resultEndpoint.expectedBodiesReceived(expectedBody);
template.sendBodyAndHeader(expectedBody, "recipientListHeader", 0);
resultEndpoint.assertIsSatisfied();
}
#Override
protected RouteBuilder createRouteBuilder() throws Exception {
//return new DcrmOutboundRoute();
return new RouteBuilder() {
#Override
public void configure() throws Exception {
// TODO Auto-generated method stub
from("direct:dcrm:input")
.filter(header("recipientListHeader").isEqualTo(constant(StatusCode.SUCCESS)))
.bean(new DcrmMessageHandler(), "process").to("mock:result");
}
};
}
But I am getting the bellow error:
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/NoResultException
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
Check your classpath or your Maven dependencies, in particular the one referencing JPA (javax.persistence). You should have a dependency with groupId javax.persistence and probably artifactId persistence-api, replace it by org.hibernate.javax.persistence or org.eclipse.persistence dependency.
I try to lookup a #Stateless bean inside a POJO which is in the same package where the bean is. The bean is not null when I use it in my #ManagedBean controller class and I can do CRUD operations.
Here is the code for lookup in ArticlesBundle.java:
public class ArticlesBundle extends ResourceBundle{
protected static final String BASE_NAME = "ArticlesLcl.findForLocale";
private Map<String,String> messages = new HashMap<>();
private Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
protected final Control DB_CONTROL = new DBControl();
public ArticlesBundle(){
setParent(ResourceBundle.getBundle(BASE_NAME, FacesContext.getCurrentInstance().getViewRoot().getLocale(), DB_CONTROL));
}
protected ArticlesBundle(Locale locale){
setParent(ResourceBundle.getBundle(BASE_NAME, locale, DB_CONTROL));
}
public ArticlesBundle(Map<String,String> messages){
this.messages = messages;
}
#Override
protected Object handleGetObject(String key){
return messages != null ? messages.get(key) : parent.getObject(key);
}
#Override
public Enumeration<String> getKeys(){
return parent.getKeys();
}
protected class DBControl extends Control{
#Override
public ResourceBundle newBundle
(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException
{
String language = locale.getLanguage();
Map<String,String> messages = getArticless(locale);
System.out.println("getArticles("+language+") = "+getArticles(locale));
return new ArticlesBundle(messages);
}
public Map<String,String> getArticles(Locale locale){
String language = locale.getLanguage();
try {
Context ctx = new InitialContext();
ArticlesLclFacade arBean = (ArticlesLclFacade) ctx.lookup("java:gesht/ArticlesLclFacade");
List<ArticlesLcl> articles = arBean.getArticles(language);
for(Iterator<ArticlesLcl> it = articles.iterator(); it.hasNext();){
ArticlesLcl article = it.next();
messages.put(article.getArId().getArId().toString(), article.getArTitle());
}
} catch (NamingException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
return messages;
}
}
}
In ArticlesFacade:
#Stateless
public class ArticlesFacade extends AbstractFacade<ArticlesLcl> {
#PersistenceContext(unitName = "gtestPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public ArticlesFacade() {
super(ArticlesLcl.class);
}
public List<ArticlesLcl> getArticless(String language){
Query q = em.createNamedQuery("ArticlesLcl.findForLocale", ArticlesLcl.class);
q.setParameter("lang", language);
return q.getResultList();
}
}
Faces-Config.xml
<resource-bundle>
<base-name>com.gesht.bundles.ArticlesBundle</base-name>
<var>article</var>
</resource-bundle>
It throws the following exception:
SEVERE: javax.naming.NamingException: Lookup failed for 'java:gtest/ArticlesLclFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: No object bound to name java:gtest/ArticlesLclFacade]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at java.util.ResourceBundle.loadBundle(ResourceBundle.java:1436)
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1400)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1296)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:841)
at com.gtest.bundles.test.<init>(test.java:50)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at java.util.ResourceBundle$Control.newBundle(ResourceBundle.java:2571)
at java.util.ResourceBundle.loadBundle(ResourceBundle.java:1436)
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1400)
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1354)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1296)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:1028)
at com.sun.faces.application.ApplicationResourceBundle.getResourceBundle(ApplicationResourceBundle.java:124)
at com.sun.faces.application.ApplicationAssociate.getResourceBundle(ApplicationAssociate.java:608)
at com.sun.faces.application.ApplicationImpl.getResourceBundle(ApplicationImpl.java:700)
at javax.faces.application.ApplicationWrapper.getResourceBundle(ApplicationWrapper.java:526)
at com.sun.faces.el.FacesResourceBundleELResolver.getValue(FacesResourceBundleELResolver.java:83)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:103)
at com.sun.el.parser.AstValue.getValue(AstValue.java:179)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:224)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIOutput.getValue(UIOutput.java:169)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1764)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeDynamicBody(PanelGridRenderer.java:92)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeBody(PanelGridRenderer.java:60)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeEnd(PanelGridRenderer.java:49)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:61)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:45)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:59)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:45)
at org.primefaces.component.datagrid.DataGridRenderer.encodeTable(DataGridRenderer.java:156)
at org.primefaces.component.datagrid.DataGridRenderer.encodeMarkup(DataGridRenderer.java:91)
at org.primefaces.component.datagrid.DataGridRenderer.encodeEnd(DataGridRenderer.java:53)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1764)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1757)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at org.ocpsoft.rewrite.faces.RewriteViewHandler.renderView(RewriteViewHandler.java:186)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:191)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.naming.NameNotFoundException: No object bound to name java:gtest/ArticlesLclFacade
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:772)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:744)
at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:177)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:498)
... 108 more
I use Glassfish Server 3+
#Stateless(mappedName="articlesLclFacade")
public class ArticlesLclFacade extends AbstractFacade {
then in your try clause
ArticlesLclFacade arBean = (ArticlesLclFacade)ctx.lookup("articlesLclFacadee");
Or I can guess you can also use the EJB annotation as this :
#EJB
private ArticlesLclFacade arBean;
I used syntax ArticlesLclFacade arBean = (ArticlesLclFacade) ctx.lookup("java:global/gtest/ArticlesLclFacade"); and there is no more NamingException thrown.
I have two classes PaymentJDO and PaymentItemJDO. A payment can have several items. Any payment item is associated with an invoice.
I want to retrieve every payment which is related to a particular invoice. I have the invoice Id to query.
#PersistenceCapable(identityType = IdentityType.APPLICATION)
public class PaymentJDO implements BaseOwnedObject, BasicBean {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
protected Long id;
#Persistent
private Date date;
#Persistent
private String customerId;
#Persistent
private String pelicamoId = null;
#Persistent
#Element(dependent = "true")
private List<PaymentItemJDO> items;
public void setId(Long id) { this.id = id;}
public String getId() {
if( id == null ) return null;
return id.toString();
}
public void setId(String id) {
if(id!=null) {
this.id = Long.parseLong(id);
}
}
public Date getDate() { return date;}
public void setDate(Date date) { this.date = date;}
public String getCustomerId() { return customerId;}
public void setCustomerId(String customerId) { this.customerId = customerId;}
public List<PaymentItemJDO> getItems() { return items;}
public void setItems(List<PaymentItemJDO> items) {this.items = items;}
public String getPelicamoId() { return pelicamoId;}
public void setPelicamoId(String pelicamoId) { this.pelicamoId = pelicamoId;}
}
#PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true")
public class PaymentItemJDO {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
protected Key id;
#Persistent
private String invoiceId;
#Persistent
private double amount;
public PaymentItemJDO(String invoiceId) {
setInvoiceId(invoiceId);
}
//override equals method for List .contains
#Override
public boolean equals(Object item) {
return ((PaymentItemJDO)item).getInvoiceId().equals(this.invoiceId);
}
public Key getId() { return id;}
public String getInvoiceId() { return invoiceId;}
public void setInvoiceId(String invoiceId) { this.invoiceId = invoiceId;}
public double getAmount() { return amount;}
public void setAmount(double amount) { this.amount = amount;}
}
I have the next function to query the payments related to a particular invoice
public List<PaymentJDO> getJDOPayments(String invoiceId) throws SessionExpiredException {
PersistenceManager pm = JdoUtil.getPm();
Query query = pm.newQuery(PaymentJDO.class);
String pelicamoId = getCurrentPelicamoId();
query.setFilter("items.contains(:invoice)");
return (List<PaymentJDO>) query.execute(new PaymentItemJDO(invoiceId));
}
I get the next error
javax.jdo.JDOFatalUserException: Illegal argument
at org.datanucleus.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException(NucleusJDOHelper.java:344)
at org.datanucleus.jdo.JDOQuery.execute(JDOQuery.java:252)
at com.softamo.pelicamo.server.MainServiceImpl.getJDOPayments(MainServiceImpl.java:947)
at com.softamo.pelicamo.server.MainServiceImpl.getIncomeSummaries(MainServiceImpl.java:817)
at com.softamo.pelicamo.server.IncomeServiceTest.testGetIncomeSummaries(IncomeServiceTest.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:73)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:46)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
NestedThrowablesStackTrace:
java.lang.IllegalArgumentException: items: com.softamo.pelicamo.server.jdo.PaymentItemJDO is not a supported property type.
at com.google.appengine.api.datastore.DataTypeUtils.checkSupportedSingleValue(DataTypeUtils.java:184)
at com.google.appengine.api.datastore.DataTypeUtils.checkSupportedValue(DataTypeUtils.java:157)
at com.google.appengine.api.datastore.Query$FilterPredicate.<init>(Query.java:549)
at com.google.appengine.api.datastore.Query.addFilter(Query.java:235)
at org.datanucleus.store.appengine.query.DatastoreQuery.addLeftPrimaryExpression(DatastoreQuery.java:1138)
at org.datanucleus.store.appengine.query.DatastoreQuery.handleContainsOperation(DatastoreQuery.java:987)
at org.datanucleus.store.appengine.query.DatastoreQuery.addExpression(DatastoreQuery.java:880)
at org.datanucleus.store.appengine.query.DatastoreQuery.addFilters(DatastoreQuery.java:827)
at org.datanucleus.store.appengine.query.DatastoreQuery.performExecute(DatastoreQuery.java:228)
at org.datanucleus.store.appengine.query.JDOQLQuery.performExecute(JDOQLQuery.java:89)
at org.datanucleus.store.query.Query.executeQuery(Query.java:1489)
at org.datanucleus.store.query.Query.executeWithArray(Query.java:1371)
at org.datanucleus.jdo.JDOQuery.execute(JDOQuery.java:243)
at com.softamo.pelicamo.server.MainServiceImpl.getJDOPayments(MainServiceImpl.java:947)
at com.softamo.pelicamo.server.MainServiceImpl.getIncomeSummaries(MainServiceImpl.java:817)
at com.softamo.pelicamo.server.IncomeServiceTest.testGetIncomeSummaries(IncomeServiceTest.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:73)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:46)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Don't you need to declare your parameter?
query.declareParameters("PaymentItemJDO invoice");
Obviously GAE/J's plugin doesn't support "collField.contains(parameter)". Why they don't only they can answer.
AFAIK "contains" works the other way around. It is satisfied, when a query parameter that is a collection contains a property value of an entity.
In your case, "items == invoiceParameter" should do the trick