Hot questions for Using GlassFish in spring

Question:

I am trying to create a transaction comprising two REST web services, whose data source point to the same data base. The first service, named 1, invokes another web service named 2 using Spring RestTemplate.

To implement the transaction I am using a JNDI connection pool, the MySql JDBC driver (version 5.1.35), JTA, XA, Spring and the GlassFish 5 AppServer.

Now, I have downloaded the maven dependencies in the Spring project, defined a configuration class using JtaTransactionManager, and configured the datasource and JTA properties in an application.yml file, like in the following code:

Configuration class:

@Configuration
@EnableTransactionManagement
public class Transacciones {

    @Bean
     public PlatformTransactionManager platformTransactionManager(){ 
        return new JtaTransactionManager();
    }

}

application.yml file

spring:
  datasource:
    jndi-name: jdbc/Prueba  
    driver-class-name: com.mysql.jdbc.Driver

  jta:
    enabled: true                               

I configured the JNDI datasource in GlassFish 5 defining a "JDBC Resource" named jdbc/Prueba in the "Connections pools" page using a javax.sql.XADataSourcedatasource named pruebaXA:

In the control layer of the web service 1, the method calls the service 2 using the RestTemplate class of Spring Framework:

Service 1 code:

@RestController
@RequestMapping("/servicio")
@EnableTransactionManagement
public class a {

    @Autowired
    private JdbcTemplate objJdbcTemplate;


    @Transactional(rollbackFor = RuntimeException.class)
    @GetMapping("/1")
    public Integer getValor(){
        try{
            int numero;
            int n=50;
            RestTemplate restTemplate = new RestTemplate();

            Integer intRes1;
            Integer intRes2;
            numero = (int) (Math.random() * n) + 1;

            intRes2 = restTemplate.postForObject("http://localhost:8080/servicio2-1.0-SNAPSHOT/servicio/2",numero,Integer.class);

            intRes1=objJdbcTemplate.update("INSERT INTO A VALUES(" +numero + ")");

            return numero;
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }
}

Service 2 code:

@RestController
@RequestMapping("/servicio")
public class a {

    @Autowired
    private JdbcTemplate objJdbcTemplate;

    @Transactional(rollbackFor = RuntimeException.class)
    @PostMapping("/2")
    public Integer getValor(@RequestBody Integer intNum){
        try{
            Integer intRes;

            intRes=objJdbcTemplate.update("INSERT INTO B VALUES(" + intNum + ")");
            return intRes;
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }
}

If the two services work without errors, there is not problem. However, when the service 1 falls, the service 2 does not know about the error and does not do the rollback.

I do not know if I need to configure another feature/option in the GlassFish 5, or in the Spring program.

I have read that in Spring only needs a JtaTransactionManager bean and the framework performs all the work related to configure and use JTA-transactions.Spring and JTA

JTA

Now, if you still need to use JTA, at least the choice is yours to make. There are two common scenarios: using JTA in a heavyweight application server (which has all the nasty disadvantages of being tied to a JavaEE server), or using a standalone JTA implementation. Spring provides support for JTA-based global transaction implementations through a PlatformTransactionManager implementation called JtaTransactionManager. If you use it on a JavaEE application server, it will automatically find the correct javax.transaction.UserTransaction reference from JNDI. Additionally, it will attempt to find the container-specific javax.transaction.TransactionManager reference in 9 different application servers for more advanced use cases like transaction suspension. Behind the scenes, Spring loads different JtaTransactionManager subclasses to take advantage of specific, extra features in different servers when available, for example: WebLogicJtaTransactionManager, WebSphereUowTransactionManager and OC4JJtaTransactionManager.

So, if you’re inside a Java EE application server, and can’t escape, but want to use Spring’s JTA support, then chances are good that you can use the following namespace configuration support to factory a JtaTransactionManager correctly (and automatically):

Alternatively, you can register a JtaTransactionManager bean instance as appropriate, with no constructor arguments, like this:

@Bean public PlatformTransactionManager platformTransactionManager(){

return new JtaTransactionManager(); } Either way, the end result in a JavaEE application server is that you can now use JTA to manage

your transactions in a unified manner thanks to Spring.

Thanks for your help and time.


Answer:

How to do Distributed Transactions XA ?

If you invoke first a REST or web service and then another one, both operations will not be part of a transaction. To form a transaction, these operations must "start" a transaction or be "joined" to an existing one. To execute that transaction, your program must interact with a transaction monitor (TM) such as the proposed by AT&T/Oracle Tuxedo (released in the 80s), the X/Open XA standard (released in the 90s) and the JTA-based systems.

Note how the TM-based transaction works:

  • A transaction using XA datasources is basically a program that invokes database operations on two different databases. The same program (e.g. invoking methods in one or more bean) starts the transaction, performs some operations on a database and performs other operations on another database. If one of the operation fails, the other operations are not performed or are rollbacked.

  • A transaction using XA datasources and JTA-enabled components is basically a program that combines operations on one or more databases with other transaction-enabled operations. For instance, you can combine operations on a database with operations on a content repository or a network-based file system. You can define transactions that, when a database operation fails, does not perform or rollbacks operations on the file system. Non-transactional applications such as COBOL-based programs can be integrated in a transaction by defining operations and compensations in the transaction monitor.

  • A transaction integrating web-services requires an special handling. For instance, there is a proposal for webservice transactions such as the WS-Transaction and WS-Coordination specification. There is a coordinator that works like the transaction monitor. The software must invoke the coordinator to start the transaction. Each participant in the transaction reports if each operation is successful or failed. The coordinator invokes the other operations or invokes the compensations according to the results.

Nowadays, there are some proposals for software architecture that do not rely on TM-based transactions. Designs based on CQRS and Event Sourcing implement transactions using the Sagas design pattern. If you are interested on defining a transaction-like operation that invokes two REST services, you may consider to avoid the XA/JTA and program a Sagas.

How to do Distributed Transactions XA in Spring and GlassFish 5?

You may check many tutorials in the Internet. For instance,

  • a tutorial that shows you three use cases: one updating two databases, one combining database operations and outgoing JMS-messages, and another one combining incoming JMS messages and database operations.
  • a video describing how to manage distributed transactions in Spring with JTA
  • and the documentation from the Spring Framework.

If the two services work without errors, there is not problem. However, when the service 1 falls, the service 2 does not know about the error and does not do the rollback.

That is the correct behavior. When you invoke a REST/webservice, the operations performed by that REST/webservice do not join to the transaction. If the invoking service fails, the invoked service will not notice it and will not rollback their operations in the database.

I do not know if I need to configure another feature/option in GlassFish 5, or in the Spring program.

No. You only have to configure the XA-datasources. Spring will use your configuration class and annotations to join automatically into a transaction the operations performed by your application on these datasources. For instance, if you have a bean that invokes multiple methods that performs operations on one or more XA-datasources, these operations will join into a transaction.

However, when you invoke a method in REST/webservice in another application, the database operations performed by that REST/webservice will not join to the transaction.

Question:

I'm having this error while trying to connect to mySQL database:

No object bound to name java:comp/env/jdbc/mySql

This is my configuration class:

@Configuration
@EnableTransactionManagement
@ComponentScan({ "org.onmyown.config" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {

@Autowired
private Environment environment;

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "org.onmyown" });
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

@Bean
public DataSource dataSource() {
    DataSource dataSource = null;
    try {
        Context initialContext = new InitialContext();
        Context environmentContext = (Context)initialContext.lookup("java:comp/env");
        dataSource = (DataSource) environmentContext.lookup("jdbc/mySql");
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
    properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
    return properties;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
    HibernateTransactionManager txManager = new HibernateTransactionManager();
    txManager.setSessionFactory(s);
    return txManager;
}
}

I can ping from GlassFish just fine. I put all the properties I need (I think). My friend did this configuration with Derby database and it works. Is there any difference?

@edit

I 'fixed' something. I added web.xml, everything is here:

https://github.com/afterlook/SpringMVC

The problem now is that the application doesn't really care that i put mySql as a data source. It searches for DerbyPool which is one of the defaults in GlassFish. Any idea why?


Answer:

The problem you posted originaly tries to use a datasource that is looked up using JNDI with the key comp/env/jdbc/mySql and this is not configured.

If you want to use a connection pool of Glasfish, you have to configure Glasfish so it creates that pool and publishes it as a JNDI component with the key comp/env/jdbc/mySql mysql glasfish shows how this is done.

With your fix you commented the JNDI code out, instead you set the connection url from a property.

db.url=jdbc:mysql://localhost:3306/app

without additional configuration, this seems to point to the Glasfish default connection pool using the derby db.

If you want to use the Glasfish connection pool :

  1. Configure Glasfish to crate that pool using mysql as described in the linked document.
  2. You will configure url,user,password for the Glsfish connection pool, so I think you dont have to provide it in the spring config again. Take the datasource as you get it from the JNDI lookup.
  3. Revert your fix that commented out the JNDI lookup. Your code should look like this :

     @Bean
      public DataSource dataSource() {
        DataSource dataSource = null;
        try {
            Context initialContext = new InitialContext();
            Context environmentContext =   (Context)initialContext.lookup("java:comp/env");
            dataSource = (DataSource) environmentContext.lookup("jdbc/mySql");
        } catch (NamingException e) {
            e.printStackTrace();
        }*/
        return dataSource;
    }
    

Question:

I want to create a web application using Spring MVC framework, so I followed this steps :

  1. I download spring-framework-5.1.2.RELEASE-dist.
  2. I opened a new project (Web Application) using IntelliJ IDEA.
  3. I created a lib directory under WEB-INF and I added all JAR file downloaded previously.
  4. I created a view directory under WEB-INF for all my JSP views
  5. I added two XML files: web.xml and spring-demo-servlet.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

<display-name>spring-mvc-demo</display-name>

<!-- Spring MVC Configs -->

<!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc-demo-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

spring-demo-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
     http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package="com.pindc.springdemo" />

<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>

<!-- Step 5: Define Spring MVC view resolver -->
<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/" />
    <property name="suffix" value=".jsp" />
</bean>

When I run my application with GlassFish Server I get this following Exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1270)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:696)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:662)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:710)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:587)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:526)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:169)
at javax.servlet.GenericServlet.init(GenericServlet.java:244)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1481)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1280)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5381)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5626)
at com.sun.enterprise.web.WebModule.start(WebModule.java:540)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:917)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:900)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:684)
at   com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2044)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1690)
at com.sun.enterprise.web.WebApplication.start(WebApplication.java:107)
at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
     Caused by: org.springframework.beans.BeanInstantiationException:  Failed to instantiate  [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:184)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1262)
... 70 more
Caused by: java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException
at org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter.<init>(AllEncompassingFormHttpMessageConverter.java:76)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.<init>(RequestMappingHandlerAdapter.java:208)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:172)
... 72 more
  Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.databind.exc.InvalidDefinitionException
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1621)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1471)



    [2018-11-30T19:30:07.388+0100] [glassfish 5.0] [WARNING] []    [javax.enterprise.web] [tid: _ThreadID=46 _ThreadName=admin-listener(4)]   [timeMillis: 1543602607388] [levelValue: 900] [[
    java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException:  org.apache.catalina.LifecycleException: java.lang.ClassNotFoundException:  com.fasterxml.jackson.databind.exc.InvalidDefinitionException
 java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.ClassNotFoundException: com.fasterxml.jackson.databind.exc.InvalidDefinitionException
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:921)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:900)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:684)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2044)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1690)
    at    com.sun.enterprise.web.WebApplication.start(WebApplication.java:107)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)

Thank's for helping!


Answer:

Either you failed to include jackson-databind jar or the proper version of that jar for your current Spring project. The latest is 2.9.7, try to build the project with that version.

Please note that the way you are handling the jar dependencies is not the correct way to do this. As @chrylis suggested in the comment, you should be using a build tool either Maven or Gradle for this.

Question:

EDITED

i have a problem with my application. I am using glassfish 4 and java 8, because my environment can't take spring 5, so i'm using spring 4 instead. I just need a few libraries to access API from another server. One of the function is RestTemplate. Everytime restTemplate.exchange is triggered, it always give HTTP 500 Error. But no exception at all. I know this is HTTP 500 error by looking at web.xml. There is no Exception message, even i've tried to add try-catch. It happens on my production server, in my development server, it's running well. In my laptop, it's running well. Can you please help me with this?

Here is my log4j

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.logger.org.hibernate=DEBUG, stdout
log4j.logger.com.opensymphony.xwork2=INFO,stdout
log4j.logger.org.apache.struts2=INFO,stdout
log4j.logger.uk.ltd.getahead.dwr=WARN, stdout
log4j.logger.freemarker.cache=INFO,stdout
log4j.logger.com.jwebs=DEBUG, stdout
log4j.logger.org.springframework=WARNING, stdout

log4j.appender.R.File=application.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.R=org.apache.log4j.RollingFileAppender

log4j.logger.com.opensymphony.xwork2.util.OgnlUtil=error
log4j.logger.com.opensymphony.xwork2.ognl.OgnlValueStack=error

Here i attach my code

        RestTemplate templatet = new RestTemplate();

        String url = "http:someurl";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Some header to get", "get");
        headers.add("Some authorization", "authorization");
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> request = new HttpEntity<Object>(headers);
        ResponseEntity<String> sapSecurity = templatet.exchange(url, HttpMethod.GET, request, String.class);

Thank you


Answer:

SOLVED

Seems like there is a crash in the library. Java read the same library but different version. I have spring.jar and spring-web.4.3.6-RELEASE.jar, that's why it's crashed and didn't show any exception. The only way to extract the exception, is through the servlet. You can see the following tutorial by Tutorialspoint:

https://www.tutorialspoint.com/servlets/servlets-exception-handling.htm

Question:

I'm using GlassFish Server Open Source Edition 4.1.2. And I have the following code:

Usuario.java (a custom class where i want to store json response):

package masterticket.models;

import java.io.Serializable;

public class Usuario implements Serializable{
    private static final long serialVersionUID = 1L;
    int id;
    String nombre;
    String apellidos;
    String tipo;
    String email;
    String password;
    java.sql.Timestamp created;

    public Usuario(){
    }

    public Usuario(String nombre, String apellidos, String tipo, String email, String password){
        this.nombre   = nombre;
        this.apellidos = apellidos;
        this.tipo = tipo;
        this.email = email;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getApellidos() {
        return apellidos;
    }

    public void setApellidos(String apellidos) {
        this.apellidos = apellidos;
    }

    public String getTipo() {
        return tipo;
    }

    public void setTipo(String tipo) {
        this.tipo = tipo;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public java.sql.Timestamp getCreated() {
        return created;
    }

    public void setCreated(java.sql.Timestamp created) {
        this.created = created;
    }

}

A spring controller:

package es.uc3m.tiw;


import es.uc3m.tiw.domains.*;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.http.*;
import org.json.JSONObject;

@Controller
public class Usuarios_Controller {

    @Autowired
    UsuarioDAO daousu;

    @RequestMapping("/todosusuarios")
    public @ResponseBody List<Usuario> getEventos(){
        return daousu.findAll();
    }

    @RequestMapping("/usuarios/{email}")
    public @ResponseBody Usuario getEventosByIdUsuario(@PathVariable String email){
        return daousu.findByEmail(email);
    }

    @RequestMapping(value="/usuarios", method = RequestMethod.POST)
    public @ResponseBody Usuario saveuser(@RequestBody Usuario puser){
        return daousu.save(puser);
    }

}

And a servlet where i execute the call to the spring app:

...
client = ClientBuilder.newClient();
            webResource = client.target("http://localhost:10507/usuarios/"+email+"/");
            System.out.println("http://localhost:10506/usuarios/"+email+"/ poniendo usuario");
            Usuario usu=    webResource.request().accept("application/json").get(Usuario.class);
            System.out.println(usu.getApellidos());
...

For some reason im not able to understand im getting this error on the glassfish log and this code wont work:

java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
    at org.eclipse.persistence.jaxb.JAXBBeanValidator.isConstrainedObject(JAXBBeanValidator.java:257)
    at org.eclipse.persistence.jaxb.JAXBBeanValidator.shouldValidate(JAXBBeanValidator.java:208)
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.validateAndBuildJAXBElement(JAXBUnmarshaller.java:235)
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:339)
    at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.readFrom(MOXyJsonProvider.java:660)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:256)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:235)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1085)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:852)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:786)
    at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:326)
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:803)
    at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:700)
    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:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:696)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:316)
    at masterticket.controllers.login.doPost(login.java:115)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    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:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:748)

API is working good because i tested it using postman and all calls work as expected. In fact im able to retrieve the response into a String but when I try to do the same with the Usuario class provided above, code breaks..

This is an example of the json im trying to parse:

[{"id":1,"nombre":"admin1","apellidos":"admin1","tipo":"admin","email":"admin1@correo.es","password":"81dc9bdb52d04dc20036dbd8313ed055","created":1510500279000}]

Answer:

This might be a bug in Glassfish at least there seems to have been one like this in 4.1.1 and I'm not sure if it was patched by 4.1.2

Question:

Hello everyone i have these error

  WebSocket connection to 'ws://localhost:8080/vix/hello/598/rula3cfq/websocket' failed: Error during WebSocket handshake: Unexpected response code: 500

my glassfish version is 4 , spring 4.2.4.RELEASE

This is my Controller

@Controller
public class Test
{

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception
{
    Thread.sleep(3000);
    return new Greeting("hello" + message.getName());
}

this is websocket config

 @Configuration
 @EnableWebSocketMessageBroker
 public class WebsocketConfig extends        
              AbstractWebSocketMessageBrokerConfigurer
{
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    config.enableSimpleBroker("/topic");
    config.setApplicationDestinationPrefixes("/app");
}

public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/hello")
            .setAllowedOrigins("*").withSockJS();
}

}

this security config

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/webjars/**", "/images/**", "/oauth/uncache_approvals", "/oauth/cache_approvals","/topic/**","/app/**",
            "/hello/**", "/calcApp/**");
}

this is front where i using stomp and sockjs

    var stompClient = null;

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        document.getElementById('response').innerHTML = '';
    }

    function connect() {
        var socket = new SockJS('http://localhost:8080/vix/hello');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            stompClient.subscribe('/vix/topic/greetings', function(greeting){
                showGreeting(JSON.parse(greeting.body).content);
            });
        });
    }

    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected");
    }

    function sendName() {
        var name = document.getElementById('name').value;
        stompClient.send("/vix/app/hello", {}, JSON.stringify({ 'name': name }));
    }

    function showGreeting(message) {
        var response = document.getElementById('response');
        var p = document.createElement('p');
        p.style.wordWrap = 'break-word';
        p.appendChild(document.createTextNode(message));
        response.appendChild(p);
    }

any idea how fix this ? i'm new in spring websocket


Answer:

In your connect method you can just leave

Don't use the same endpoint "hello" and MessageMapping, will be confuse

public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ws")
        .setAllowedOrigins("*").withSockJS();
}

var socket = new SockJS('/hello');

Here also remove the contextPath vix

stompClient.subscribe('/topic/greetings', function(greeting){
    showGreeting(JSON.parse(greeting.body).content);
});

Here again the same

 stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));

Basically, all problem was adding the context because the context was added by default when you add the first "/"

Question:

I've created the datasource using the persistence unit wizard in netbeans (8.0.2). But when running the project on glassfish, it cannot find my datasource.

Exception

Exception Description: Cannot acquire data source [blogdb]. Internal Exception: javax.naming.NamingException: Lookup failed for 'blogdb' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: blogdb not found]

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="BloggerPU" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>blogdb</jta-data-source>
    <properties>
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
    </properties>
  </persistence-unit>
</persistence>

glassfish-resources.xml

<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="org.postgresql.ds.PGSimpleDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="post-gre-sql_2TX33_r0457020Pool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
    <property name="serverName" value"server.domain.com"/>
    <property name="portNumber" value="51415"/>
    <property name="databaseName" value="2TX33"/>
    <property name="User" value="user"/>
    <property name="Password" value="pass"/>
    <property name="URL" value="jdbc:postgresql://server.domain.com:51415/2TX33"/>
    <property name="driverClass" value="org.postgresql.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="blogdb" object-type="user" pool-name="post-gre-sql_2TX33_r0457020Pool"/>

I'm using EclipseLink JPA 2.1


Answer:

My issue was that I had an other application deployed on the glassfish server which used the same jta-datasource.

Question:

I have a problem with using maven-embedded-glassfish-plugin (version 3.1.1) with Hibernate 4.3.5 and Spring.

My pom.xml looks like that:

<dependencies> 
    ...   
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.5.Final</version>
    </dependency>
    ...
</dependencies>

<build>
    <plugins>
        ...
        <plugin>
            <groupId>org.glassfish</groupId>
            <artifactId>maven-embedded-glassfish-plugin</artifactId>
            <version>3.1.1</version>
        </plugin>
        ...
    </plugins>
</build>

My Spring's entityManagerFactory configuration is quite standard:

<bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
    <property name="packagesToScan" value="com.example.domain"/>
    <property name="jpaProperties" ref="hibernateJpaProperties"/>
</bean>

When I invoke mvn embedded-glassfish:run, I get an exception:

SEVERE: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext-persistence.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: javax.persistence.JoinColumn.foreignKey()Ljavax/persistence/ForeignKey

I have tried to change many dependencies and many different configuration, but don't know how to handle this problem.


Answer:

As it turned out, the Hibernate 4.3.5 implements the JPA 2.1 standard, while the GlassFish 3 (and maven-embedded-glassfish-plugin) implements only JPA 2.0 and that was the reason of the problem.

GlassFish 4 implements the new JPA 2.1, so if you build the app (.war/.ear file) you can deploy it without a problem on the GlassFish 4. But the maven-embedded-glassfish-plugin does not currently support the new GlassFish 4.

The solution to this problem might be to simply degrade the Hibernate version to 4.2.15.Final, that uses the JPA 2.0:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.2.15.Final</version>
</dependency>

Or you can try to configure your glassfish-plugin as mentioned HERE:

<plugin>
   <groupId>org.glassfish.embedded</groupId>
     <artifactId>maven-embedded-glassfish-plugin</artifactId>
     <version>3.1.2.2</version>
     <dependencies>
       <dependency>
       <groupId>org.glassfish.main</groupId>
       <artifactId>simple-glassfish-api</artifactId>
       <version>4.0-b79</version>
     </dependency>
     <dependency>
       <groupId>org.glassfish.main.extras</groupId>
       <artifactId>glassfish-embedded-all</artifactId>
       <version>4.0-b83</version>
     </dependency>
   </dependencies>
 </plugin>