3
I am creating a WS that connects to a DB Postgresql and performs a query in a single table.
I try to run it locally, but the problem is when running the application gives the following error:
HTTP 500 status - Internal Server Error
type: Exception report
message: Internal Server Error
description: The server encountered an internal error ({0}) that prevented it from meet this request.
exception
javax.servlet.ServletException: java.lang.NullPointerException causa-raiz
java.lang.NullPointerException
Note: Full exception stack crawls and their root causes are available in Glassfish Server Open Source Edition 4.0 logs .
I believe it is not so complex, but as I have no experience with language, I am having difficulties.
My codes are:
Dbconnection.java
package br.com.dbconnection;
import br.com.findfriends.entidade.Friend;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class DBConnection {
private String databaseURL = "jdbc:postgresql://localhost:8080/wsfindfriends";
private String usuario = "postgres";
private String senha = "senhaPostgres";
private String driverName = "org.postgresql.Driver";
private PreparedStatement stmt = null;
private ResultSet rs = null;
public Connection conn = null;
public void DBConnection() {
try {
Class.forName(driverName).newInstance();
this.conn = DriverManager.getConnection(databaseURL, usuario, senha);
System.out.println("Conexão obtida com sucesso.");
}
catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
catch (Exception e) {
System.out.println("Problemas ao tentar conectar com o banco de dados: " + e);
}
}
public List<Friend> executeQuery(String query) {
try {
List<Friend> list = new ArrayList<Friend>();
this.stmt = this.conn.prepareStatement(query);
this.rs = this.stmt.executeQuery();
while (rs.next()) {
// criando o objeto Friend
Friend friend = new Friend();
friend.setId(rs.getInt("id"));
friend.setNome(rs.getString("nome"));
friend.setNome(rs.getString("fone"));
// adicionando o objeto à lista
list.add(friend);
}
this.close();
return list;
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void close(){
try {
this.stmt.close();
this.rs.close();
this.conn.close();
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
Findfriendsservice.java
package br.com.findfriends;
import br.com.dbconnection.DBConnection;
import br.com.findfriends.entidade.Friend;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.core.MediaType;
@Path("findfriends")
public class FindFriendsService {
@Context
private UriInfo context;
/**
* Creates a new instance of FindFriendsService
*/
public FindFriendsService() {
}
/**
* Retrieves representation of an instance of br.com.findfriends.FindFriendsService
* @return an instance of java.lang.String
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getJson() {
//TODO return proper representation object
DBConnection dbc = new DBConnection();
List<Friend> list = new ArrayList<Friend>();
list = dbc.executeQuery("SELECT * FROM locationfriends");
Gson gson = new Gson();
return gson.toJson(list);
}
/**
* PUT method for updating or creating an instance of FindFriendsService
* @param content representation for the resource
* @return an HTTP response with content of the updated or created resource.
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public void putJson(String content) {
}
}
Friend.java
package br.com.findfriends.entidade;
public class Friend {
private int id;
private String nome, fone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getFone() {
return fone;
}
public void setFone(String fone) {
this.fone = fone;
}
}
=====================================
Edit: Stacktrace:
java.lang.NullPointerException
at br.com.dbconnection.DBConnection.executeQuery(DBConnection.java:51)
at br.com.findfriends.FindFriendsService.getJson(FindFriendsService.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:125)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:91)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:346)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:341)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:101)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:224)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:323)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:745)
Please paste the stack-trace into a Pastebin for us, without it you won’t know the problem.
– Edgar Muniz Berlinck
Where you are hosting your webservice?
– Math
+Edgar Muniz Berlinck, I didn’t know what stacktrace was, but I did a quick search and I think I figured it out. Post updated. +Math, I’m testing locally only.
– LeoFelipe
What is line 51 on your
DBConnection.java
?– Math
line 51: this.stmt = this.conn.prepareStatement(query);
– LeoFelipe
No further exceptions were made? Because the error is indicating that the variable
conn
is not referencing an object, however it should have been initialized in the constructor, but it is possible that the constructor has not run entirely if there has been a problem in it.– Math
No. When I run the application gives the bug right away without launching exception.
– LeoFelipe
Is your Postgresql actually running on port 8080? By default this is the Glassfish port. In the connection URL it is not necessary to put the port, unless Postgresql is running on another port that is not the default.
– Luídne
when running the application, access the webservice by the url: http://localhost:8080/wsfindfriends/webresources/findfriends. In case I try to access http://localhost/wsfindfriends/webresources/findfriends, removing the door 8080, gives Notfound. Has any relationship?
– LeoFelipe
Yes, for you to access the application you really must access localhost:8080/Your application, but the URL of the connection to the database is different, it is not the same that is used to access the application.
– Luídne
how can I find out if this URL is correct? And if not, how to know the correct url to use?
– LeoFelipe