RESTful web service: java.lang.NullPointerException service.AbstractFacade.findAll - mysql

I created a simple XML web service using NetBeans 7's "RESTful Web Services from Database..." wizard. At this point, I want to publish a list of users from the associated mySQL database.
When I attempt to access the service via its URL (http://localhost:8080/database/resources/users), I get an error that reads "java.lang.NullPointerException". The stack trace:
service.AbstractFacade.findAll(AbstractFacade.java:41)
service.UserFacade.findAll(UserFacade.java:51)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:165)
com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:67)
com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:276)
com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:83)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:133)
com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:71
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1171) com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1103) com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1053)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1043)
com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:406)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:477)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:662)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
User entity:
package entities;
...
#Entity
#Table(name="users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),
...
I've also changed the named query to User.findAll in case the names needs to align with the entity's name. This did not solve the problem.
I'm not certain if it is 'normal' or not, but the wizard created a fairly sparse UserFacade class; I added the missing methods after researching the topic. Furthermore, the javax.ejb.Stateless package seems to be missing (perhaps not on my workstation's CLASSPATH); this is the reason that the #Stateless annotation is disabled.
UserFacade class:
//#Stateless
#Path("users")
public class UserFacade extends AbstractFacade<User> {
#PersistenceContext(unitName="databasePU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public UserFacade() {
super(User.class);
}
#GET
#Path("{id}")
#Produces({"application/xml", "application/json"})
public User find(#PathParam("id") BigDecimal id) {
return super.find(id);
}
#GET
#Override
#Produces({"application/xml", "application/json"})
public List<User> findAll() {
return super.findAll();
}
}
Exception is thrown at the first line in the AbstractFacade's findAll method:
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
...
}
Questions:
Is the #Stateless annotation required for this to function?
Does this pattern require J2EE 6 rather than J2SE 6 (which is what is installed on my OS X workstation)? The 'javax.ejb' namespace seems to suggest enterprise java beans.
** edit **
Java SE 6 (1.6.0_29-b11-402)

The auto-generated query "SELECT u FROM Users u" works without any problems. As per the comment suggesting that "u" might be wrong because it doesn't represent a column, that suggestion is not correct because here "u" is an alias for the table users.
I would debug further the findAll() to check if something is null, i.e. the EntityManager.
The #Stateless annotation in the UserFacade is necessary, and removing it would probably cause the EntityManager to be null (note that I wrote "removing" because NetBeans places if for you, if you use "RestFul Web Services from Database" wizard). See here a similar question.
Regarding your latest edit: yes, these features need to be built using the Java Platform, Enterprise Edition. In particular, RESTFul web services make use of the Java API for RESTful Web Services (JAX-RS) which is included in the Java EE 6 platform as explained here.
GlassFish Server Open Source Edition is the first compatible implementation of the Java EE 6 platform specification: I suggest using this Application Server and following the tutorials linked above.

I think #ori is on the the answer. Your table Users probably don't have a column named u so you get an exception when it tries to match the column u to the database.
Change to u.* and it should work fine.

Related

Spring Boot 2 Upgrade Issue - Error Page Always returns HTML

I have recently upgraded our project to Spring Boot 2. The App is just a Rest API. And now all our 400 and 500 responses are being returned as html instead of json.
I am defining a custom ErrorAttributes, just like the docs say to do.
#Configuration
public class WebConfig implements WebMvcConfigurer {
...
#Bean
public ErrorAttributes errorAttributes() {
return new DefaultErrorAttributes() {
#Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest,
boolean includeStackTrace) {
Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, true);
return errorAttributes;
}
};
}
...
I would like to debug this issue locally, but I cannot find in the code where Spring Boot makes this decision to add a JSON Response for errors. The docs here: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling says:
For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message.
I'm thinking that I must have a Bean defined locally that is causing this not to be configured correctly in the Spring Boot Auto configuration.
I finally figured this out. I think there were some changes in Spring Security 4 to Spring Security 5 that was causing a NPE early in the filter chain for our app. Also, compounding the difficulty of debugging the issue is that with the Spring Boot upgrade, the /error route was forced to be authenticated.
I ended up fixing the NPE, allowing for everyone to see the /error mapping and then making sure ErrorMvcAutoConfiguration was being initialized correctly. All is working now.

Repository uses N1QL

I'm getting the following exception:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'answerRepository': Invocation of init method failed; nested exception is org.springframework.data.couchbase.core.UnsupportedCouchbaseFeatureException: Repository uses N1QL
I'm using Spring 4.2.0.RELEASE with spring-data-couchbase 2.0.0.M1 against Couchbase 2.5.1 enterprise edition (build-1083)
I can't see any explanation in the doc for this error.
Here is the repository:
public interface AnswerRepository extends BaseRepository<Answer, String> {
final static String DESIGN_DOCUMENT = "answers";
#View(viewName = "answers_by_quizId_startTime", designDocument = DESIGN_DOCUMENT)
public List<Answer> findByQuizIdAndStartTime(String quizId, long startTime);
Answer findByUuid(String uuid);
}
#NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {
}
Maybe my Couchbase server does not support this feature, whereas my repository expects it.
I might need to code my repository differently.
It's too bad it doesn't say which method is the invalid one here.
Or it is my using of the CrudRepository in the base class ?
I wonder how to find out which views it expects to find in my Couchbase server.
Repositories in Spring Data Couchbase 2.0 rely almost exclusively on Views and N1QL. A good chunk of the new features in this version are made possible by N1QL, which is now the default mechanism Spring Data uses for things like "query derivation" (implementing a repository method by producing some sort of query that is derived from the method name).
Couchbase Server 2.5.1 doesn't have access to N1QL (which came with Couchbase Server 4.0 and of course also in the brand new 4.1 version).
If you want Spring Data to implement findByUuid for you, you'll have to annotate that method with #View and create the appropriate view that emits uuids from your Answer documents.
View query derivations are heavily restricted and give you more work since you have to write the correct map function:
a repository method based on a view can only query with one criteria.
you have to create your view correctly, emitting the correct keys corresponding to the criteria you'll query with.
you have to create one view per entity class, restricting the view to only emit if the "_class" field in the JSON matches said entity (note: this field can be renamed in the configuration so make sure to use the relevant one).
So that means that your findByQuizIdAndStartTime cannot work either. You may have to implement this (and maybe findByUuid) in the BaseRepository, relying on the CouchbaseTemplate and using its findByView method (or even queryView as a last resort).
The UnsupportedCouchbaseFeatureException is mentioned in the M1 doc chapter 7 (on N1QL based querying).
See also the section on view query derivation further down the documentation.

Java EE and JPA under Glassfish, NoClassDefFound com/mysql/jdbc/ResultSetMetaData

I have a problem when I acces my MySql Database from an EJB. After deploying my EAR to the Glassfish server, and calling the method that use the entity class I get an exception like this:
java.lang.NoClassDefFoundError: com/mysql/jdbc/ResultSetMetaData
I am using a local MySql Database, the connection to these still works. To acces the tables of these Databese I am using entity classes generated by Netbeans. This classes are situated in external Library (OthelloLibrarie). Here you can also find the remote interface of my Session Bean.
I had to put the entity classes in an external library because I'm using them in an Enterprise Client Application which is connected to my EAR.
My Enterprise Application Project contains the main Session bean and somes Session beans from entity classes which uses my entity classes in the external Library. It also contains the persistence XML and it includes my JDBC driver:
The error appears when I call the method createPartie from the Client Application:
Partie p = eJBOthelloGame.createPartie(jTextFieldPseudo.getText());
SessionBeanOthelloRemote.java:
#Stateless
public class SessionBeanOthello implements SessionBeanOthelloRemote {
#EJB
private PlayerFacadeLocal playerFacade;
#EJB
private PartieFacadeLocal partieFacade;
#Override
public Partie createPartie(String player) {
//Ajout du tuple
Partie p = new Partie();
Player p1 = new Player();
p1.setId(1);
p1.setNom(player);
playerFacade.create(p1);
p.setPlayer1(p1);
partieFacade.create(p);
return p;
}
Partie and Player are Entity classes used with generated facades.
I searched yet on the web but I never found this kind of error. It seems that only the package or class ResultSetMetaData from JDBC has a problem and not the entire driver.
Can you help me?
You need to include in your project the mysql-connector-java.jar file that provides the MySql JDBC driver classes. As you are using Netbeans, just add it as a library jar.
You can find it, along with download and installation instructions, at this link.

CloudFoundry MySQL Java configuration

I have a Spring MVC app that is running fine on local tomcat etc. Its a Spring 3.1 MVC/Hibernate app.
I am using (where possible) pure Java #Configuration for the app - and I am now trying to deploy the app to CloudFoundry (via STS), but I am struggling to get the MySql db configured (from memory, with xml config you dont need to do anything and Spring/CloudFoundry auto-injects the required user/password etc, but its been a while since I deployed anything to CF).
I have tried both of the following configurations:
#Bean
public BasicDataSource dataSource() throws PropertyVetoException {
//CloudFoundry config
final CloudEnvironment cloudEnvironment = new CloudEnvironment();
final List<MysqlServiceInfo> mysqlServices = cloudEnvironment.getServiceInfos(MysqlServiceInfo.class);
final MysqlServiceInfo serviceInfo = mysqlServices.get(0);
BasicDataSource bean = new BasicDataSource();
bean.setDriverClassName("com.mysql.jdbc.Driver");
bean.setUrl(serviceInfo.getUrl());
bean.setUsername(serviceInfo.getUserName());
bean.setPassword(serviceInfo.getPassword());
return bean;
}
The above failed on out of bounds on the .get(0) line of the mysqlServices. This was based on the answer suggested here.
I also tried leaving the datasource as what it runs on as local to see if the properties just get injected, but no luck there either. (the below was tried with the values as per the Spring sample code here, and also using property placeholders from my db.connection props file)
#Bean
public BasicDataSource dataSource() throws PropertyVetoException {
BasicDataSource bean = new BasicDataSource();
bean.setDriverClassName("com.mysql.jdbc.Driver");
bean.setUrl("");
bean.setUsername("spring");
bean.setPassword("spring");
return bean;
}
Edit
I have also used the getServiceInfo(String, Class) method passing in the name of the MySql service that I have created and bound to the application, but that just NPEs similar to the getServiceInfos(..) approach
Ok, this was just a stupid mistake - when I deployed the app via STS I had selected Java Web app rather than the "Spring" type. Not sure why that would make the CloudEnvironment properties not be available (I was under the impression that approach was the common method to inject the details in non-Spring apps) - but re-deploying it to the server as a Spring app resolved the probs!

To many EntityCollections in Entity raise "implement IConvertible" exception in RIA Services

I have a Entity object create with the Entity Framework and used in Silverlight with the RIA Services framework.
The Entity in question has two EntityCollections which are included in the IQueriable sent to the client.
The Entity looks like this:
public class Ad:Entity
{
[Include]
public EntityCollection<PublishingDates> PublishingDates {get;set;}
[Include]
public EntityCollection<Notice> Notice {get;set;}
}
The domain service method includes both collection using Include as this:
[Query]
public IQueryable<Ad> GetAds()
{
return this.ObjectContext.Ad.Include("PublishingDates").Include("Notice");
}
On the client side when the service is called and the result returned the following exception was raise : "The object must implement IConvertible".
If only one EntityCollection is included everything works fine. If both, the previously mentioned exception is raise.
[EDIT]
I use MySQL with MySQL Net Connector version 6.3.5. as the database.
I think its a bug in Net Connector, a very similar bug was reported here http://bugs.mysql.com/bug.php?id=55349
EDIT:
Im not sure this applies to your specific case but for me the latest community server (5.5.9) works a lot better. Note that this is the db not .net connector, which seems not to be involved in the errors I got.
I have the same problem now. The interesting thing is my query works excellent with linux-driven Mysql instance but doesn't work on Windows. May be you will succeed moving to Linux