I'm creating a WS that connects to a PostgreSQL DB and performs a query on a single table.
I try to run it locally, but the problem is when I run the application it 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 answer this request.
exception
javax.servlet.ServletException: java.lang.NullPointerException causa-raiz
java.lang.NullPointerException
Note: Full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.0 logs.
I think it's not so complex, but since I have no experience with language, I'm 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: Following 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)