Guest User

Tentativas JSON

a guest
Sep 13th, 2017
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 72.59 KB | None | 0 0
  1. Tenho uma classe Country que é o objeto país, e no banco de dados tenho os países registrados, ao todos são 144 registros. Na minha classe País existe uma lista com os estados deste país, devido a um relacionamento um para muitos, pois um país pode ter vários estados e um estado pertence a um país.
  2.  
  3. Sendo assim:
  4. public class Country implements Serializable {
  5.     // atributos
  6.  
  7.     @OneToMany(mappedBy = "country")
  8.     private List<State> states;
  9.    
  10.     // getters e setters
  11. }
  12.  
  13.  
  14. ========================================================== TESTE 1 ==========================================================
  15. ========================================================== Objeto ==========================================================
  16. Tenho um rest que retorna o país onde é passado o ID por parâmetro, então fiz o seguinte:
  17.  
  18. @GET
  19. @Path("{id}")
  20. @Produces(MediaType.APPLICATION_JSON)
  21. public Country getCountryId(@PathParam("id") String id) {
  22.     if (id == null || id.equals("")) {
  23.           return null;
  24.         }
  25.         // código que busca o país
  26.         return country;
  27. }
  28.  
  29. Ao fazer uma requisição para o serviço acima, há o retorno com código 500 dizendo que ocorreu erro interno no servidor, mas no log do servidor não há nenhuma exceção:
  30.  
  31. 20:13:20,392 INFO  [org.hibernate.Version] (default task-3) HHH000412: Hibernate Core {5.2.10.Final}
  32. 20:13:20,394 INFO  [org.hibernate.cfg.Environment] (default task-3) HHH000206: hibernate.properties not found
  33. 20:13:20,899 INFO  [org.hibernate.annotations.common.Version] (default task-3) HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
  34. 20:13:21,005 WARN  [org.hibernate.orm.connections.pooling] (default task-3) HHH10001002: Using Hibernate built-in connection pool (not for production use!)
  35. 20:13:21,005 INFO  [org.hibernate.orm.connections.pooling] (default task-3) HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/wimbeerdb?autoReconnect=true&useSSL=false&useTimezone=true&serverTimezone=UTC]
  36. 20:13:21,006 INFO  [org.hibernate.orm.connections.pooling] (default task-3) HHH10001001: Connection properties: {user=wb, password=****, autocommit=false}
  37. 20:13:21,006 INFO  [org.hibernate.orm.connections.pooling] (default task-3) HHH10001003: Autocommit mode: false
  38. 20:13:21,007 INFO  [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (default task-3) HHH000115: Hibernate connection pool size: 20 (min=1)
  39. 20:13:21,207 INFO  [org.hibernate.dialect.Dialect] (default task-3) HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
  40. 20:13:21,426 WARN  [org.hibernate.orm.deprecation] (default task-3) HHH90000018: Found use of deprecated transaction factory setting [hibernate.transaction.factory_class]; use the new TransactionCoordinatorBuilder settings [hibernate.transaction.coordinator_class] instead
  41. 20:13:21,882 INFO  [org.hibernate.orm.connections.access] (default task-3) HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@29b79b23] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
  42. 20:13:22,344 INFO  [org.hibernate.hql.internal.QueryTranslatorFactoryInitiator] (default task-3) HHH000397: Using ASTQueryTranslatorFactory
  43. 20:13:22,567 INFO  [stdout] (default task-3) Hibernate: select country0_.id_country as id_count1_12_0_, country0_.iso as iso2_12_0_, country0_.iso3 as iso3_12_0_, country0_.name_country as name_cou4_12_0_, country0_.num_code as num_code5_12_0_ from countries country0_ where country0_.id_country=?
  44.  
  45. 20:13:22,613 INFO  [org.hibernate.orm.connections.pooling] (default task-3) HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/wimbeerdb?autoReconnect=true&useSSL=false&useTimezone=true&serverTimezone=UTC]
  46.  
  47.  
  48. ========================================================== TESTE 2 ==========================================================
  49. =========================================================== Gson ============================================================
  50. Alterei o método do serviço para conforme abaixo (coloquei um retorno de String pois o método toJson retorna String):
  51.  
  52. @GET
  53. @Path("{id}")
  54. @Produces(MediaType.APPLICATION_JSON)
  55. public String getCountryId(@PathParam("id") String id) {
  56.     if (id == null || id.equals("")) {
  57.           return null;
  58.         }
  59.         // código que busca o país
  60.     return new Gson().toJson(country);
  61. }
  62.  
  63. Resultado:
  64.  
  65. 20:18:32,192 INFO  [stdout] (default task-5) Hibernate: select country0_.id_country as id_count1_12_0_, country0_.iso as iso2_12_0_, country0_.iso3 as iso3_12_0_, country0_.name_country as name_cou4_12_0_, country0_.num_code as num_code5_12_0_ from countries country0_ where country0_.id_country=?
  66. 20:18:32,213 INFO  [org.hibernate.orm.connections.pooling] (default task-5) HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/wimbeerdb?autoReconnect=true&useSSL=false&useTimezone=true&serverTimezone=UTC]
  67. 20:18:32,244 ERROR [io.undertow.request] (default task-5) UT005023: Exception handling request to /wimbeerbackend/api/v1/country/1: javax.servlet.ServletException: java.lang.NullPointerException
  68.     at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:423)
  69.     at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
  70.     at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
  71.     at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
  72.     at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
  73.     at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
  74.     at com.wimbeer.util.FilterAcess.doFilter(FilterAcess.java:66)
  75.     at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
  76.     at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
  77.     at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
  78.     at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
  79.     at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
  80.     at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
  81.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  82.     at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
  83.     at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
  84.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  85.     at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
  86.     at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
  87.     at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
  88.     at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
  89.     at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
  90.     at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
  91.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  92.     at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
  93.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  94.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  95.     at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
  96.     at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
  97.     at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
  98.     at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
  99.     at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
  100.     at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
  101.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  102.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  103.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  104.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  105.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  106.     at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
  107.     at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
  108.     at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
  109.     at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
  110.     at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
  111.     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  112.     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  113.     at java.lang.Thread.run(Thread.java:748)
  114. Caused by: java.lang.NullPointerException
  115.     at org.hibernate.collection.internal.AbstractPersistentCollection.openTemporarySessionForLoading(AbstractPersistentCollection.java:275)
  116.     at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:198)
  117.     at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:561)
  118.     at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132)
  119.     at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:277)
  120.     at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
  121.     at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61)
  122.     at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
  123.     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:125)
  124.     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:243)
  125.     at com.google.gson.Gson.toJson(Gson.java:669)
  126.     at com.google.gson.Gson.toJson(Gson.java:648)
  127.     at com.google.gson.Gson.toJson(Gson.java:603)
  128.     at com.google.gson.Gson.toJson(Gson.java:583)
  129.     at com.wimbeer.rest.RestCountry.getCountryId(RestCountry.java:51)
  130.     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  131.     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  132.     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  133.     at java.lang.reflect.Method.invoke(Method.java:498)
  134.     at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
  135.     at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
  136.     at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
  137.     at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
  138.     at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
  139.     at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
  140.     at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
  141.     at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
  142.     at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:308)
  143.     at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
  144.     at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
  145.     at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
  146.     at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
  147.     at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
  148.     at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
  149.     at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:291)
  150.     at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1140)
  151.     at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:403)
  152.     ... 45 more
  153.  
  154. ========================================================== TESTE 3 ==========================================================
  155. ======================================================== JSONObject ==========================================================
  156.  
  157. Fiz novas alterações agora retornando uma String, através de um JSONObject:
  158.  
  159. @GET
  160. @Path("{id}")
  161. @Produces(MediaType.APPLICATION_JSON)
  162. public String getCountryId(@PathParam("id") String id) {
  163.         if (id == null || id.equals("")) {
  164.             return null;
  165.         }
  166.         // código que busca o país
  167.         JSONObject json = new JSONObject();
  168.         json.put("country", country);
  169.         return json.toString();
  170. }
  171.  
  172. Resultado: Retorna quase certo, porém ao invés dos atributos, retorna o endereço do objeto:
  173. {
  174.     "country": "com.wimbeer.entities.Country@5f3bb4d6"
  175. }
  176.  
  177. ========================================================== TESTE 4 ==========================================================
  178. ======================================================== Jackson ==========================================================
  179.  
  180. Alterações:
  181. Obs: utilizei @JsonIgnore no outro lado do relacionamento
  182.  
  183. @GET
  184. @Path("{id}")
  185. @Produces(MediaType.APPLICATION_JSON)
  186. public String getCountryId(@PathParam("id") String id) {
  187.         if (id == null || id.equals("")) {
  188.             return null;
  189.         }
  190.         // código que busca o país
  191.         ObjectMapper mapper = new ObjectMapper();
  192.         return mapper.writeValueAsString(country);
  193. }
  194.  
  195. Resultado:
  196.  
  197. 20:33:26,407 INFO  [org.hibernate.orm.connections.pooling] (default task-13) HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/wimbeerdb?autoReconnect=true&useSSL=false&useTimezone=true&serverTimezone=UTC]
  198. 20:33:26,407 ERROR [io.undertow.request] (default task-13) UT005023: Exception handling request to /wimbeerbackend/api/v1/country/1: javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.wimbeer.entities.Country["states"])
  199.     at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:423)
  200.     at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
  201.     at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
  202.     at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
  203.     at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
  204.     at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
  205.     at com.wimbeer.util.FilterAcess.doFilter(FilterAcess.java:66)
  206.     at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
  207.     at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
  208.     at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
  209.     at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
  210.     at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
  211.     at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
  212.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  213.     at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
  214.     at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
  215.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  216.     at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
  217.     at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
  218.     at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
  219.     at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
  220.     at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
  221.     at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
  222.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  223.     at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
  224.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  225.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  226.     at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
  227.     at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
  228.     at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
  229.     at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
  230.     at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
  231.     at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
  232.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  233.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  234.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  235.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  236.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  237.     at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
  238.     at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
  239.     at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
  240.     at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
  241.     at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
  242.     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  243.     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  244.     at java.lang.Thread.run(Thread.java:748)
  245. Caused by: org.glassfish.jersey.server.ContainerException: com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.wimbeer.entities.Country["states"])
  246.     at org.glassfish.jersey.servlet.internal.ResponseWriter.rethrow(ResponseWriter.java:256)
  247.     at org.glassfish.jersey.servlet.internal.ResponseWriter.failure(ResponseWriter.java:238)
  248.     at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:486)
  249.     at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:316)
  250.     at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
  251.     at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
  252.     at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
  253.     at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
  254.     at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
  255.     at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
  256.     at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:291)
  257.     at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1140)
  258.     at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:403)
  259.     ... 45 more
  260. Caused by: com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.wimbeer.entities.Country["states"])
  261.     at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:378)
  262.     at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:338)
  263.     at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:342)
  264.     at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:686)
  265.     at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
  266.     at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:130)
  267.     at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3631)
  268.     at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2998)
  269.     at com.wimbeer.rest.RestCountry.getCountryId(RestCountry.java:55)
  270.     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  271.     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  272.     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  273.     at java.lang.reflect.Method.invoke(Method.java:498)
  274.     at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
  275.     at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
  276.     at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
  277.     at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
  278.     at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
  279.     at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
  280.     at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
  281.     at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
  282.     at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:308)
  283.     ... 54 more
  284. Caused by: java.lang.NullPointerException
  285.     at org.hibernate.collection.internal.AbstractPersistentCollection.openTemporarySessionForLoading(AbstractPersistentCollection.java:275)
  286.     at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:198)
  287.     at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:145)
  288.     at org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:261)
  289.     at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:102)
  290.     at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25)
  291.     at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:672)
  292.     at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
  293.     ... 72 more
  294.  
  295. ========================================================== TESTE 5 ==========================================================
  296. ======================================================== Response ==========================================================
  297.  
  298. Utilizando Response, que é o que realmente eu quero usar para fazer controle dos retorno pelos códigos HTTP:
  299.  
  300. @GET
  301. @Path("{id}")
  302. @Produces(MediaType.APPLICATION_JSON)
  303. public Response getCountryId(@PathParam("id") String id) {
  304.         if (id == null || id.equals("")) {
  305.             return Response.status(404).build();
  306.         }
  307.         // código que busca o país
  308.         return Response.status(200).entity(new Gson().toJson(country)).build();
  309. }
  310.  
  311. Resultado:
  312.  
  313. 20:44:37,161 INFO  [org.hibernate.orm.connections.pooling] (default task-15) HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/wimbeerdb?autoReconnect=true&useSSL=false&useTimezone=true&serverTimezone=UTC]
  314. 20:44:37,177 ERROR [io.undertow.request] (default task-15) UT005023: Exception handling request to /wimbeerbackend/api/v1/country/1: javax.servlet.ServletException: java.lang.NullPointerException
  315.     at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:423)
  316.     at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
  317.     at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
  318.     at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
  319.     at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
  320.     at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
  321.     at com.wimbeer.util.FilterAcess.doFilter(FilterAcess.java:66)
  322.     at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
  323.     at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
  324.     at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
  325.     at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
  326.     at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
  327.     at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
  328.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  329.     at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
  330.     at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
  331.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  332.     at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
  333.     at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
  334.     at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
  335.     at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
  336.     at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
  337.     at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
  338.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  339.     at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
  340.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  341.     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  342.     at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
  343.     at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
  344.     at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
  345.     at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
  346.     at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
  347.     at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
  348.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  349.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  350.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  351.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  352.     at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  353.     at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
  354.     at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
  355.     at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
  356.     at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
  357.     at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
  358.     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  359.     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  360.     at java.lang.Thread.run(Thread.java:748)
  361. Caused by: java.lang.NullPointerException
  362.     at org.hibernate.collection.internal.AbstractPersistentCollection.openTemporarySessionForLoading(AbstractPersistentCollection.java:275)
  363.     at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:198)
  364.     at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:561)
  365.     at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132)
  366.     at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:277)
  367.     at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
  368.     at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61)
  369.     at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
  370.     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:125)
  371.     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:243)
  372.     at com.google.gson.Gson.toJson(Gson.java:669)
  373.     at com.google.gson.Gson.toJson(Gson.java:648)
  374.     at com.google.gson.Gson.toJson(Gson.java:603)
  375.     at com.google.gson.Gson.toJson(Gson.java:583)
  376.     at com.wimbeer.rest.RestCountry.getCountryId(RestCountry.java:49)
  377.     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  378.     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  379.     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  380.     at java.lang.reflect.Method.invoke(Method.java:498)
  381.     at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
  382.     at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
  383.     at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
  384.     at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
  385.     at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
  386.     at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
  387.     at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
  388.     at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
  389.     at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:308)
  390.     at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
  391.     at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
  392.     at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
  393.     at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
  394.     at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
  395.     at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
  396.     at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:291)
  397.     at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1140)
  398.     at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:403)
  399.     ... 45 more
  400.  
  401.  
  402. ========================================================== TESTE 6 ==========================================================
  403. ======================================================== Response ==========================================================
  404.  
  405. Se eu utilizar o response com o Gson(), e tentar retornar todos os países(Mesma configuração do teste 5, porém retornando todos):
  406.  
  407. @GET
  408. @Produces(MediaType.APPLICATION_JSON)
  409. public Response getCountry() {
  410.     return Response.status(200).entity(
  411.             new Gson().toJson(new CountryControls().getAll())).build();
  412. }
  413.  
  414. Resultado:
  415.  
  416. Obs: Se verificar, está retornando tudo que tem no país, nesse caso, se eu quiser retornar somente o país e não retornar os objetos relacionados ao mesmo, como posso fazer?
  417.  
  418. 20:46:46,226 INFO  [stdout] (default task-18) Hibernate: /* Country.searchAll */
Add Comment
Please, Sign In to add comment