1
votes

i'm trying to delete certain rows that are clicked out of the database. Every row is shown and has a delete button to delete that certain row. Onclick i take the ID from the row and all this works. Just when i look in the network it returns a 500 error. This is my code

         $("body").on('click', '#delete', function(){
         var trid = $(this).closest('tr').attr('id');
         console.log(trid);
         $.ajax({
             url: '/firstapp/restservices/countries/delete/' + trid,
             type: 'DELETE',
             success: function(response) {
                 console.log(response);
             }
         });
     });

And the Java

    @Path("countries")
    public class WorldResource {
    private CountryPostgresDaoImpl CountryPostgresDao = new 
    CountryPostgresDaoImpl();

    @Path("delete/{code}")
    @DELETE
    @Produces("application/json")
    public Response deleteCountry(@PathParam("code") String code) throws SQLException {
         Country country = ServiceProvider.getWorldService().getCountryByCode(code);
        if(!CountryPostgresDao.Delete(country)) {
            return Response.status(404).build();
        }
        return Response.ok().build();

    }

Returning

Request URL: http://localhost:8888/firstapp/restservices/countries/delete/AF
Request Method: DELETE
Status Code: 500 
Remote Address: [::1]:8888
Referrer Policy: no-referrer-when-downgrade

On the server returns a huge error where im not sure where to look

jun. 12, 2018 1:50:48 P.M. org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [Jersey REST Service] in context with path [/firstapp] threw exception [java.lang.IndexOutOfBoundsException: Index 0 out-of-bounds for length 0] with root cause java.lang.IndexOutOfBoundsException: Index 0 out-of-bounds for length 0 at java.base/jdk.internal.util.Preconditions.outOfBounds(Unknown Source) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Unknown Source) at java.base/jdk.internal.util.Preconditions.checkIndex(Unknown Source) at java.base/java.util.Objects.checkIndex(Unknown Source) at java.base/java.util.ArrayList.get(Unknown Source) at nl.hu.v1wac.firstapp.persistence.CountryPostgresDaoImpl.findByCode(CountryPostgresDaoImpl.java:74) at nl.hu.v1wac.firstapp.webservices.WorldService.getCountryByCode(WorldService.java:52) at nl.hu.v1wac.firstapp.webservices.WorldResource.deleteCountry(WorldResource.java:103) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.base/java.lang.reflect.Method.invoke(Unknown Source) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:76) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:148) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:191) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:200) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:103) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:493) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:415) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:104) at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:277) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:272) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:268) at org.glassfish.jersey.internal.Errors.process(Errors.java:316) at org.glassfish.jersey.internal.Errors.process(Errors.java:298) at org.glassfish.jersey.internal.Errors.process(Errors.java:268) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:703) at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416) at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:407) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Unknown Source)

The worldservice code is as following

public Country getCountryByCode(String code) throws SQLException {
    return CountryPostgresDao.findByCode(code);
}

Which refers to the Dao findbycode which is:

    public Country findByCode(String cd) throws SQLException {
    return findCountries("SELECT code, iso3, name, continent, region, surfacearea, population, latitude, longitude, capital, governmentform FROM country WHERE code = " + cd).get(0);
}

With the findcountries method

    public List<Country> findCountries(String query) throws SQLException{
    List<Country> results = new ArrayList<Country>();

    try (Connection con = super.getConnection()) {
        Statement stmt = con.createStatement();
        ResultSet dbResultSet = stmt.executeQuery(query);

        while (dbResultSet.next()) {
            String code  = dbResultSet.getString("code");
            String iso3 = dbResultSet.getString("iso3");
            String name = dbResultSet.getString("name");
            String capital = dbResultSet.getString("capital");
            String continent = dbResultSet.getString("continent");
            String region = dbResultSet.getString("region");
            Double surfacearea = dbResultSet.getDouble("surfacearea");
            int population = dbResultSet.getInt("population");
            Double latitude = dbResultSet.getDouble("latitude");
            Double longitude = dbResultSet.getDouble("longitude");
            String governmentform = dbResultSet.getString("governmentform");

            results.add(new Country(code,iso3,name,capital,continent,region,surfacearea,population,governmentform,latitude,longitude));
        }
    } catch (SQLException sqle) {
        sqle.printStackTrace();
    }

    return results;


}

The delete DAO

    public boolean Delete(Country country) throws SQLException {
    boolean result = false;
    boolean countryExists = findByCode(country.getCode()) != null;

    if (countryExists) {
        String query = "DELETE FROM country WHERE code = " + country.getCode(); 

        try (Connection con = super.getConnection()) {

            Statement stmt = con.createStatement();
            if (stmt.executeUpdate(query) == 1) { // 1 row updated!
                result = true;
            }
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    }

    return result;
}
1
'500' means something wrong happens in the server side,you need to add server logslucumt
You should have a Stack Trace on the server logs. Please check there. Maybe paste it here so we can help.Guilherme Mussi
i think i added it! Not sure where to look for the correct error thoWesley van Straalen
look at getCountryByCode method or just post that here.possible post WorldResource and WorldService classessrinij
@srini Updated!Wesley van Straalen

1 Answers

0
votes

Change this findByCode code to as below

public Country findByCode(String cd) throws SQLException {
List<Country> countries= findCountries("SELECT code, iso3, name, 
continent, region, surfacearea, population, 
latitude, longitude, capital, governmentform FROM country WHERE code = 
'" + code + "'");
}
if(!countries.isEmpty()) {
return countries.get(0);
}
return null;
}

and the query is wrong, it should be

"SELECT code, iso3, name, continent, region, surfacearea, population, 
latitude, longitude, capital, governmentform FROM country WHERE code = 
'" + code + "'"