Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.
- Sendo assim:
- public class Country implements Serializable {
- // atributos
- @OneToMany(mappedBy = "country")
- private List<State> states;
- // getters e setters
- }
- ========================================================== TESTE 1 ==========================================================
- ========================================================== Objeto ==========================================================
- Tenho um rest que retorna o país onde é passado o ID por parâmetro, então fiz o seguinte:
- @GET
- @Path("{id}")
- @Produces(MediaType.APPLICATION_JSON)
- public Country getCountryId(@PathParam("id") String id) {
- if (id == null || id.equals("")) {
- return null;
- }
- // código que busca o país
- return country;
- }
- 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:
- 20:13:20,392 INFO [org.hibernate.Version] (default task-3) HHH000412: Hibernate Core {5.2.10.Final}
- 20:13:20,394 INFO [org.hibernate.cfg.Environment] (default task-3) HHH000206: hibernate.properties not found
- 20:13:20,899 INFO [org.hibernate.annotations.common.Version] (default task-3) HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
- 20:13:21,005 WARN [org.hibernate.orm.connections.pooling] (default task-3) HHH10001002: Using Hibernate built-in connection pool (not for production use!)
- 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]
- 20:13:21,006 INFO [org.hibernate.orm.connections.pooling] (default task-3) HHH10001001: Connection properties: {user=wb, password=****, autocommit=false}
- 20:13:21,006 INFO [org.hibernate.orm.connections.pooling] (default task-3) HHH10001003: Autocommit mode: false
- 20:13:21,007 INFO [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (default task-3) HHH000115: Hibernate connection pool size: 20 (min=1)
- 20:13:21,207 INFO [org.hibernate.dialect.Dialect] (default task-3) HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
- 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
- 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.
- 20:13:22,344 INFO [org.hibernate.hql.internal.QueryTranslatorFactoryInitiator] (default task-3) HHH000397: Using ASTQueryTranslatorFactory
- 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=?
- 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]
- ========================================================== TESTE 2 ==========================================================
- =========================================================== Gson ============================================================
- Alterei o método do serviço para conforme abaixo (coloquei um retorno de String pois o método toJson retorna String):
- @GET
- @Path("{id}")
- @Produces(MediaType.APPLICATION_JSON)
- public String getCountryId(@PathParam("id") String id) {
- if (id == null || id.equals("")) {
- return null;
- }
- // código que busca o país
- return new Gson().toJson(country);
- }
- Resultado:
- 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=?
- 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]
- 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
- at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:423)
- at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
- at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
- at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
- at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
- at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
- at com.wimbeer.util.FilterAcess.doFilter(FilterAcess.java:66)
- at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
- at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
- at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
- at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
- at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
- at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
- at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
- at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
- at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
- at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
- at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
- at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
- at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
- at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
- at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
- at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
- at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
- at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
- at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
- at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
- at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
- at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
- at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
- at java.lang.Thread.run(Thread.java:748)
- Caused by: java.lang.NullPointerException
- at org.hibernate.collection.internal.AbstractPersistentCollection.openTemporarySessionForLoading(AbstractPersistentCollection.java:275)
- at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:198)
- at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:561)
- at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132)
- at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:277)
- at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
- at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61)
- at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
- at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:125)
- at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:243)
- at com.google.gson.Gson.toJson(Gson.java:669)
- at com.google.gson.Gson.toJson(Gson.java:648)
- at com.google.gson.Gson.toJson(Gson.java:603)
- at com.google.gson.Gson.toJson(Gson.java:583)
- at com.wimbeer.rest.RestCountry.getCountryId(RestCountry.java:51)
- 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:498)
- at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
- at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
- at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
- at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
- at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
- at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
- at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
- at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
- at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:308)
- 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:291)
- at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1140)
- at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:403)
- ... 45 more
- ========================================================== TESTE 3 ==========================================================
- ======================================================== JSONObject ==========================================================
- Fiz novas alterações agora retornando uma String, através de um JSONObject:
- @GET
- @Path("{id}")
- @Produces(MediaType.APPLICATION_JSON)
- public String getCountryId(@PathParam("id") String id) {
- if (id == null || id.equals("")) {
- return null;
- }
- // código que busca o país
- JSONObject json = new JSONObject();
- json.put("country", country);
- return json.toString();
- }
- Resultado: Retorna quase certo, porém ao invés dos atributos, retorna o endereço do objeto:
- {
- "country": "com.wimbeer.entities.Country@5f3bb4d6"
- }
- ========================================================== TESTE 4 ==========================================================
- ======================================================== Jackson ==========================================================
- Alterações:
- Obs: utilizei @JsonIgnore no outro lado do relacionamento
- @GET
- @Path("{id}")
- @Produces(MediaType.APPLICATION_JSON)
- public String getCountryId(@PathParam("id") String id) {
- if (id == null || id.equals("")) {
- return null;
- }
- // código que busca o país
- ObjectMapper mapper = new ObjectMapper();
- return mapper.writeValueAsString(country);
- }
- Resultado:
- 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]
- 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"])
- at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:423)
- at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
- at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
- at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
- at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
- at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
- at com.wimbeer.util.FilterAcess.doFilter(FilterAcess.java:66)
- at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
- at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
- at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
- at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
- at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
- at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
- at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
- at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
- at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
- at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
- at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
- at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
- at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
- at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
- at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
- at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
- at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
- at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
- at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
- at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
- at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
- at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
- at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
- at java.lang.Thread.run(Thread.java:748)
- Caused by: org.glassfish.jersey.server.ContainerException: com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.wimbeer.entities.Country["states"])
- at org.glassfish.jersey.servlet.internal.ResponseWriter.rethrow(ResponseWriter.java:256)
- at org.glassfish.jersey.servlet.internal.ResponseWriter.failure(ResponseWriter.java:238)
- at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:486)
- at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:316)
- 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:291)
- at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1140)
- at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:403)
- ... 45 more
- Caused by: com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.wimbeer.entities.Country["states"])
- at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:378)
- at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:338)
- at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:342)
- at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:686)
- at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
- at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:130)
- at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3631)
- at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2998)
- at com.wimbeer.rest.RestCountry.getCountryId(RestCountry.java:55)
- 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:498)
- at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
- at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
- at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
- at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
- at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
- at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
- at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
- at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
- at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:308)
- ... 54 more
- Caused by: java.lang.NullPointerException
- at org.hibernate.collection.internal.AbstractPersistentCollection.openTemporarySessionForLoading(AbstractPersistentCollection.java:275)
- at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:198)
- at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:145)
- at org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:261)
- at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:102)
- at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25)
- at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:672)
- at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
- ... 72 more
- ========================================================== TESTE 5 ==========================================================
- ======================================================== Response ==========================================================
- Utilizando Response, que é o que realmente eu quero usar para fazer controle dos retorno pelos códigos HTTP:
- @GET
- @Path("{id}")
- @Produces(MediaType.APPLICATION_JSON)
- public Response getCountryId(@PathParam("id") String id) {
- if (id == null || id.equals("")) {
- return Response.status(404).build();
- }
- // código que busca o país
- return Response.status(200).entity(new Gson().toJson(country)).build();
- }
- Resultado:
- 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]
- 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
- at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:423)
- at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
- at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
- at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
- at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
- at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
- at com.wimbeer.util.FilterAcess.doFilter(FilterAcess.java:66)
- at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
- at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
- at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
- at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
- at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
- at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
- at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
- at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
- at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
- at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
- at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
- at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
- at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
- at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
- at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
- at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
- at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
- at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
- at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
- at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
- at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
- at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
- at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
- at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
- at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
- at java.lang.Thread.run(Thread.java:748)
- Caused by: java.lang.NullPointerException
- at org.hibernate.collection.internal.AbstractPersistentCollection.openTemporarySessionForLoading(AbstractPersistentCollection.java:275)
- at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:198)
- at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:561)
- at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132)
- at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:277)
- at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
- at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61)
- at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
- at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:125)
- at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:243)
- at com.google.gson.Gson.toJson(Gson.java:669)
- at com.google.gson.Gson.toJson(Gson.java:648)
- at com.google.gson.Gson.toJson(Gson.java:603)
- at com.google.gson.Gson.toJson(Gson.java:583)
- at com.wimbeer.rest.RestCountry.getCountryId(RestCountry.java:49)
- 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:498)
- at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
- at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
- at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
- at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
- at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
- at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
- at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
- at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
- at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:308)
- 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:291)
- at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1140)
- at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:403)
- ... 45 more
- ========================================================== TESTE 6 ==========================================================
- ======================================================== Response ==========================================================
- 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):
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- public Response getCountry() {
- return Response.status(200).entity(
- new Gson().toJson(new CountryControls().getAll())).build();
- }
- Resultado:
- 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?
- 20:46:46,226 INFO [stdout] (default task-18) Hibernate: /* Country.searchAll */
Add Comment
Please, Sign In to add comment