Cannot get session using SessionFactory.getCurrentSession() in Hibernate5 with Spring - spring

I am completely new to Spring and Hibernate. I am having some difficulty getting Spring and Hibernate to cooperate so that my Spring configuration returns a Session object from the SessionFactory object.
In particular, I have followed the tutorial at: https://www.baeldung.com/hibernate-5-spring. This tutorial is for configuring Spring and Hibernate for the H2 database. However, I am currently configuring Spring and Hibernate for Oracle 12.2. I have reflected the changes in the configuration files.
Just like the aforementioned site suggests, I have written a Maven project with all the required dependencies. Moreover, I am configuring Hibernate 5 with an XML-based configuration.
Please find the code below:
Here is the Spring - Hibernate configuration file:
<?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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.test">
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="debug">true</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:ORCL"/>
<property name="username" value="sa"/>
<property name="password" value="sa"/>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
Here is the Java code that I am using to try and secure the Hibernate Session object:
#Autowired
private SessionFactory sessionFactory;
public Session getSession()
{
Session session = null;
try
{
session = sessionFactory.getCurrentSession();
if(session != null)
{
System.out.println("Session is VALID.");
}
else
{
System.out.println("Session is INVALID.");
}
}
catch(IllegalStateException e)
{
System.out.println("getSession: Illegal State Exception: " + e.getMessage());
}
catch(Exception e)
{
System.out.println("getSession: Exception: " + e.getMessage());
}
return session;
}
Here is the project pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>Flow</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Flow</name>
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
<org.springframework.data.version>1.10.6.RELEASE</org.springframework.data.version>
<org.springframework.security.version>4.2.1.RELEASE</org.springframework.security.version>
<hibernate.version>5.2.10.Final</hibernate.version>
<hibernatesearch.version>5.8.2.Final</hibernatesearch.version>
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
<jta.version>1.1</jta.version>
<hsqldb.version>2.3.4</hsqldb.version>
<oracle.version>12.2.0.1</oracle.version>
<commons-lang3.version>3.5</commons-lang3.version>
</properties>
<repositories>
<repository>
<id>maven.oracle.com</id>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<url>https://maven.oracle.com</url>
<layout>default</layout>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>maven.oracle.com</id>
<url>https://maven.oracle.com</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- persistence -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${org.springframework.data.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>${jta.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>${tomcat-dbcp.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>${oracle.version}</version>
</dependency>
</dependencies>
<build>
<finalName>Flows</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
What I am expecting to receive is a Session object; however, when I run my code, the variable session i returns null. Any help would be greatly appreciated. Thanks!

The hibernate property hibernate.current_session_context_class defines how SessionFactory retrieve the current Session. When using LocalSessionFactoryBean to build SessionFactory , by default it will set to SpringSessionContext which basically means Spring will mange the session for you.
So in most case , you don't need to get the session by calling sessionFactory.getCurrentSession(). Simply use #PersistenceContext to inject and use the Session:
#PersistenceContext
private Session session;

Related

Add CORSHandler to a camel-jetty component

I need to add the following CORSHandler to a camel-jetty component.
public class CORSHandler extends AbstractHandler
{
#Override
public void handle(String arg0, Request arg1, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
System.out.println("GOT REQUEST!!!!!!!");
if(request.getMethod().equals("OPTIONS")){
System.out.println("CORSFilter HTTP Request BS: " + request.getMethod());
// Authorize (allow) all domains to consume the content
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");
response.addHeader("Access-Control-Allow-Headers","Authorization");
// For HTTP OPTIONS verb/method reply with ACCEPTED status code -- per CORS handshake
if (request.getMethod().equals("OPTIONS")) {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
arg1.setHandled(true);
}
}
}
}
I'm trying the following way,
from("jetty:http://0.0.0.0:8082/proxy?disableStreamCache=true&matchOnUriPrefix=true&enableMultipartFilter=false&handlers=#corsHandler")
.to("jetty:http://localhost:8085/myWebApp/foo?bridgeEndpoint=true&throwExceptionOnFailure=false&traceEnabled=true")
.to("log:MyLogger?level=INFO&showAll=true");
Following is my camel-context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:camel="http://camel.apache.org/schema/spring"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean class="com.abccom.route.CloudServiceRoute" id="cloudServiceRoute"/>
<bean class="com.abccom.CORSHandler" id="corsHandler"/>
<camelContext id="esbConsoleCamelContext" xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="cloudServiceRoute"/>
</camelContext>
</beans>
I'm getting the following exception upon deployment.
Caused by: org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: jetty://http://0.0.0.0:8082/proxy?disableStreamCache=true&enableMultipartFilter=false&handlers=%23corsHandler&matchOnUriPrefix=true due to: No bean could be found in the registry for: corsHandler of type: java.lang.Object
at org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:723)
at org.apache.camel.util.CamelContextHelper.getMandatoryEndpoint(CamelContextHelper.java:80)
at org.apache.camel.model.RouteDefinition.resolveEndpoint(RouteDefinition.java:219)
at org.apache.camel.impl.DefaultRouteContext.resolveEndpoint(DefaultRouteContext.java:112)
at org.apache.camel.impl.DefaultRouteContext.resolveEndpoint(DefaultRouteContext.java:118)
at org.apache.camel.model.FromDefinition.resolveEndpoint(FromDefinition.java:69)
at org.apache.camel.impl.DefaultRouteContext.getEndpoint(DefaultRouteContext.java:94)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1278)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:204)
Any info on how should I configure the CORSHandler for the camel-jetty component?
Following is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.abccom</groupId>
<artifactId>console-service-esb</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<name>WildFly Camel CDI Application</name>
<url>http://www.myorganization.org</url>
<!-- Properties -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- WildFly versions -->
<version.wildfly>10.1.0.Final</version.wildfly>
<!-- Other versions -->
<version.apache.camel>2.19.3</version.apache.camel>
<version.junit>4.12</version.junit>
<!-- Plugin versions -->
<version.maven.compiler.plugin>3.1</version.maven.compiler.plugin>
<version.maven.surefire.plugin>2.18.1</version.maven.surefire.plugin>
<version.maven.war.plugin>3.0.0</version.maven.war.plugin>
<version.wildfly.maven.plugin>1.2.0.Final</version.wildfly.maven.plugin>
<!-- maven-compiler-plugin -->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- Arquillian application server properties -->
<jboss.home>${env.JBOSS_HOME}</jboss.home>
<server.config>standalone-camel.xml</server.config>
</properties>
<!-- DependencyManagement -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.wildfly.camel</groupId>
<artifactId>wildfly-camel-bom</artifactId>
<version>4.9.0</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<!-- Dependencies -->
<dependencies>
<!-- Provided -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cdi</artifactId>
<version>${version.apache.camel}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-restlet</artifactId>
<version>${version.apache.camel}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jetty</artifactId>
<version>${version.apache.camel}</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.servlet</groupId>
<artifactId>jboss-servlet-api_3.1_spec</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.ws.rs</groupId>
<artifactId>jboss-jaxrs-api_1.1_spec</artifactId>
<version>1.0.1.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-git</artifactId>
<version>${version.apache.camel}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jasypt</artifactId>
<version>${version.apache.camel}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${version.junit}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<!--HTTP camel component dependency -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-http</artifactId>
<version>${version.apache.camel}</version>
</dependency>
</dependencies>
<!-- Build-->
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${version.maven.compiler.plugin}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${version.maven.war.plugin}</version>
</plugin>
<plugin>
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>${version.wildfly.maven.plugin}</version>
<configuration>
<version>${version.wildfly}</version>
<serverConfig>${server.config}</serverConfig>
</configuration>
</plugin>
</plugins>
</build>
<!-- Profiles -->
<profiles>
<profile>
<!-- The default profile skips all tests, though you can tune it to run just unit tests based on a custom pattern -->
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${version.maven.surefire.plugin}</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<!-- Repositories -->
<repositories>
<repository>
<id>jboss-public-repository</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
</repositories>
</project>
Following is my web.xml
<web-app>
<servlet>
<display-name>Camel Http Transport Servlet</display-name>
<servlet-name>CamelServlet</servlet-name>
<servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CamelServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

I Can't run Arquillian Tests on Wildfly 8.2.0.Final

i'm trying to run arquillian tests on my project, but without sucess.
I'm looking for this error but not found questions about it.
When I try to run the arquillian test, see that RuntimeException.
java.lang.RuntimeException: java.net.MalformedURLException: Unsupported protocol: remote+http
my profile wildfly-remote-arquillian in pom.xml:
<profile>
<id>wildfly-remote-arquillian</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<dependencies>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-websockets-jsr</artifactId>
<version>1.0.0.Beta25</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.5.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>3.0.5.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-json-p-provider</artifactId>
<version>3.0.5.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-remote</artifactId>
<version>${org.wildfly}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
</plugins>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
<testResource>
<directory>src/test/resources-wildfly-remote</directory>
<filtering>true</filtering>
</testResource>
</testResources>
</build>
</profile>
my arquillian.xml:
<?xml version="1.0" encoding="UTF-8"?>
(...)
<engine>
<property name="deploymentExportPath">target/</property>
</engine>
<container qualifier="wildfly" default="true">
<protocol type="jmx-as7">
<property name="executionType">REMOTE</property>
</protocol>
<configuration>
<property name="javaVmArguments">-agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=y</property>
<property name="allowConnectingToRunningServer">true</property>
<property name="managementAddress">127.0.0.1</property>
<property name="managementPort">9990</property>
<property name="username">admin</property>
<property name="password">admin</property>
</configuration>
</container>
my Arquillian Test class:
#RunWith(Arquillian.class)
public class MemberRegistrationTest {
#Deployment
public static Archive<?> createTestArchive() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(Member.class, MemberRegistration.class,
Resources.class)
.addAsResource("META-INF/test-persistence.xml", "META- INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
// Deploy our test datasource
.addAsWebInfResource("test-ds.xml");
}
#Inject
MemberRegistration memberRegistration;
#Inject
Logger log;
#Test
public void testRegister() throws Exception {
Member newMember = new Member();
newMember.setName("Jane Doe");
newMember.setEmail("jane#mailinator.com");
newMember.setPhoneNumber("2125551234");
memberRegistration.register(newMember);
assertNotNull(newMember.getId());
(...)
Error console:
thanks for any help.

Spring autowiring not working in Vaadin 7 UI

I have a Vaadin 7 project. It's works. Now I need to implement Hibernate 4 to access Database and I want to use also Spring 4 to use its annotations.
The problem is that the autowired annotation doesn't work. The related object is always null.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>bermacorp</groupId>
<artifactId>b-sci</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>b-sci</name>
<properties>
<vaadin.version>7.6.1</vaadin.version>
<vaadin.plugin.version>${vaadin.version}</vaadin.plugin.version>
<jetty.plugin.version>9.2.3.v20140905</jetty.plugin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>4.2.3.RELEASE</spring.version>
<version.hibernate>4.3.6.Final</version.hibernate>
<version.slf4j>1.5.8</version.slf4j>
</properties>
<repositories>
<repository>
<id>vaadin-addons</id>
<url>http://maven.vaadin.com/vaadin-addons</url>
</repository>
<repository>
<id>vaadin-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>${vaadin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-server</artifactId>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-push</artifactId>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-client</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-client-compiler</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-themes</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${version.hibernate}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.0.2.GA</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${version.slf4j}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>8.4-702.jdbc4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<packagingExcludes>WEB-INF/classes/VAADIN/gwt-unitCache/**,
WEB-INF/classes/VAADIN/widgetsets/WEB-INF/**</packagingExcludes>
</configuration>
</plugin>
<plugin>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-maven-plugin</artifactId>
<version>${vaadin.plugin.version}</version>
<configuration>
<extraJvmArgs>-Xmx512M -Xss1024k</extraJvmArgs>
<webappDirectory>${basedir}/target/classes/VAADIN/widgetsets</webappDirectory>
<draftCompile>false</draftCompile>
<compileReport>false</compileReport>
<style>OBF</style>
<strict>true</strict>
</configuration>
<executions>
<execution>
<goals>
<goal>update-theme</goal>
<goal>update-widgetset</goal>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.4</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<version>2.6.1</version>
<configuration>
<filesets>
<fileset>
<directory>src/main/webapp/VAADIN/themes</directory>
<includes>
<include>**/styles.css</include>
<include>**/styles.scss.cache</include>
</includes>
</fileset>
</filesets>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty.plugin.version}</version>
<configuration>
<scanIntervalSeconds>2</scanIntervalSeconds>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>com.vaadin</groupId>
<artifactId>
vaadin-maven-plugin
</artifactId>
<versionRange>[7.1.11,)</versionRange>
<goals>
<goal>resources</goal>
<goal>update-widgetset</goal>
<goal>compile</goal>
<goal>compile-theme</goal>
<goal>update-theme</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
<profile>
<id>vaadin-prerelease</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<repositories>
<repository>
<id>vaadin-prereleases</id>
<url>http://maven.vaadin.com/vaadin-prereleases</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>vaadin-prereleases</id>
<url>http://maven.vaadin.com/vaadin-prereleases</url>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>b-sci</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>Bsci</servlet-name>
<servlet-class>bsci.BsciServlet</servlet-class>
<init-param>
<param-name>UI</param-name>
<param-value>bsci.BsciUI</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Bsci</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
applicationContext.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:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<context:property-placeholder location = "classpath:application.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>bsci.entity</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<context:annotation-config />
<tx:annotation-driven/>
<context:component-scan base-package="bsci.dao"/>
<bean class="bsci.service.impl.ServizioImpl" id="servizio"/>
</beans>
BsciServlet.java
package bsci;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.vaadin.server.ServiceException;
import com.vaadin.server.SessionInitEvent;
import com.vaadin.server.SessionInitListener;
import com.vaadin.server.VaadinServlet;
#SuppressWarnings("serial")
public class BsciServlet extends VaadinServlet implements SessionInitListener {
private WebApplicationContext webApplicationContext;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
this.webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
} catch (IllegalStateException e) {
throw new ServletException("could not locate containing WebApplicationContext");
}
AutowireCapableBeanFactory ctx = getWebApplicationContext().getAutowireCapableBeanFactory();
ctx.autowireBean(this);
}
protected final AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws ServletException {
try {
return getWebApplicationContext().getAutowireCapableBeanFactory();
} catch (IllegalStateException e) {
throw new ServletException("containing context " + getWebApplicationContext() + " is not autowire-capable", e);
}
}
protected final WebApplicationContext getWebApplicationContext() throws ServletException {
if (this.webApplicationContext == null) {
throw new ServletException("can't retrieve WebApplicationContext before init() is invoked");
}
return this.webApplicationContext;
}
#Override
public void sessionInit(SessionInitEvent event) throws ServiceException {
}
#Override
protected final void servletInitialized() throws ServletException {
super.servletInitialized();
getService().addSessionInitListener(this);
getService().addSessionInitListener(new BsciSessionInitListener());
}
}
BsciSessionInitListener.java
package bsci;
import org.jsoup.nodes.Element;
import com.vaadin.server.BootstrapFragmentResponse;
import com.vaadin.server.BootstrapListener;
import com.vaadin.server.BootstrapPageResponse;
import com.vaadin.server.ServiceException;
import com.vaadin.server.SessionInitEvent;
import com.vaadin.server.SessionInitListener;
#SuppressWarnings("serial")
public class BsciSessionInitListener implements SessionInitListener {
#Override
public final void sessionInit(final SessionInitEvent event)
throws ServiceException {
event.getSession().addBootstrapListener(new BootstrapListener() {
#Override
public void modifyBootstrapPage(final BootstrapPageResponse response) {
final Element head = response.getDocument().head();
head.appendElement("meta")
.attr("name", "viewport")
.attr("content",
"width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no");
head.appendElement("meta")
.attr("name", "apple-mobile-web-app-capable")
.attr("content", "yes");
head.appendElement("meta")
.attr("name", "apple-mobile-web-app-status-bar-style")
.attr("content", "black-translucent");
String contextPath = response.getRequest().getContextPath();
}
#Override
public void modifyBootstrapFragment(
final BootstrapFragmentResponse response) {
}
});
}
}
Now in my UI class the autowired object is always null.
package bsci;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.common.eventbus.Subscribe;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Widgetset;
import com.vaadin.server.Page;
import com.vaadin.server.Page.BrowserWindowResizeEvent;
import com.vaadin.server.Page.BrowserWindowResizeListener;
import com.vaadin.server.Responsive;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.UI;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.ValoTheme;
import bsci.data.DataProvider;
import bsci.data.DummyDataProvider;
import bsci.entity.Utente;
import bsci.event.BsciEvent.BrowserResizeEvent;
import bsci.event.BsciEvent.CloseOpenWindowsEvent;
import bsci.event.BsciEvent.UserLoggedOutEvent;
import bsci.event.BsciEvent.UserLoginRequestedEvent;
import bsci.event.BsciEventBus;
import bsci.service.Servizio;
import bsci.view.LoginView;
import bsci.view.MainView;
#Theme("bscitheme")
#Widgetset("bsci.BsciWidgetset")
public final class BsciUI extends UI {
#Autowired
Servizio servizio;
private final DataProvider dataProvider = new DummyDataProvider();
private final BsciEventBus dashboardEventbus = new BsciEventBus();
#Override
protected void init(final VaadinRequest request) {
BsciEventBus.register(this);
Responsive.makeResponsive(this);
addStyleName(ValoTheme.UI_WITH_MENU);
updateContent();
Page.getCurrent().addBrowserWindowResizeListener(new BrowserWindowResizeListener() {
#Override
public void browserWindowResized(final BrowserWindowResizeEvent event) {
BsciEventBus.post(new BrowserResizeEvent());
}
});
}
private void updateContent() {
Utente user = (Utente) VaadinSession.getCurrent().getAttribute(Utente.class.getName());
if (user != null) {
setContent(new MainView());
removeStyleName("loginview");
getNavigator().navigateTo(getNavigator().getState());
} else {
setContent(new LoginView());
addStyleName("loginview");
}
}
#Subscribe
public void userLoginRequested(final UserLoginRequestedEvent event) {
Utente user = getDataProvider().authenticate(event.getUserName(), event.getPassword());
VaadinSession.getCurrent().setAttribute(Utente.class.getName(), user);
updateContent();
}
#Subscribe
public void userLoggedOut(final UserLoggedOutEvent event) {
VaadinSession.getCurrent().close();
Page.getCurrent().reload();
}
#Subscribe
public void closeOpenWindows(final CloseOpenWindowsEvent event) {
for (Window window : getWindows()) {
window.close();
}
}
public static DataProvider getDataProvider() {
return ((BsciUI) getCurrent()).dataProvider;
}
public static BsciEventBus getDashboardEventbus() {
return ((BsciUI) getCurrent()).dashboardEventbus;
}
public Servizio getServizio() {
return servizio;
}
}
Can you help me, please?
I don't understand the reason.
The reason is that you're trying to let Spring inject something into your UI, but Spring doesn't know about your UI.
Use the Vaadin Spring integration instead of implementing it yourself. Doing it yourself is possible, but then you need some place where you manually look up some Components in the WebApplicationContext, for example the View components could be prototype scoped beans looked up in a ViewProvider used by the Navigator. But now that we have the official Vaadin Spring integration this isn't necessary anymore.
Thanks all, but I solved the problem using vaadin spring integration add-on
<dependency>
<groupId>ru.xpoft.vaadin</groupId>
<artifactId>spring-vaadin-integration</artifactId>
<version>3.2</version>
</dependency>

Cannot get some unit tests to run for a spring application

Spring newbie here. Trying to meld various online spring tutorials into a single working project. Started off with the spring mvc tutorial described in this link.
Now I'm trying to meld this online tutorial on Spring data jpa into the above project. As you may see in the attached figure, I've added all necessary project files (src, test, .xml files etc).
My issue is that when I do mvn package (which is what I've been using to build and run the tests), the new suite of tests for the second project do not get executed. I wonder why! Without giving away all the sources, I will show some of the most important configuration (.xml) files.
Picture showing new files added, existing files, and brief description of issue:
Note: Sorry, but some of the xml meta-data are being removed by stackoverflow. They are mostly header tags that import xml definitions and thus not that important.
orm.xml (added for spring-data-jpa exercise)
<?xml version="1.0" encoding="UTF-8"?>
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="org.springframework.data.jpa.domain.support.AuditingEntityListener" />
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
<named-query name="Person.findByName">
<query>select p from Person p where p.firstName = :firstName AND p.lastName = :lastName</query>
</named-query>
persistence.xml (added for spring-data-jpa exercise)
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="hsql">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="validate" />
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
<property name="jadira.usertype.autoRegisterUserTypes" value="true" />
<property name="jadira.usertype.databaseZone" value="jvm" />
</properties>
</persistence-unit>
root-context.xml (initially there for spring-mvc-tutorial)
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!--
CSRF protection. Here we only include the CsrfFilter instead of all of Spring Security.
See http://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#csrf for more information on
Spring Security's CSRF protection
-->
<bean id="csrfFilter" class="org.springframework.security.web.csrf.CsrfFilter">
<constructor-arg>
<bean class="org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository"/>
</constructor-arg>
</bean>
<!--
Provides automatic CSRF token inclusion when using Spring MVC Form tags or Thymeleaf. See
http://localhost:8080/#forms and form.jsp for examples
-->
<bean id="requestDataValueProcessor" class="org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor"/>
4.) controllers.xml, 5.)servlet-context.xml files are just standard files that map controllers to path, define and instantiate the dispatcher-servlet, and other beans which were already in the spring-mvc-tutorial code. I believe they don't really have anything to do with the issue described in this ticket.
Here is the test file that doesn't execute, and I'd like to have running:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
#TransactionConfiguration
#Transactional
public class PersonRepositoryTest {
final Logger logger = LoggerFactory.getLogger(PersonRepositoryTest.class);
private final static Integer FIRST_ID = Integer.valueOf(1);
private final static Integer SECOND_ID = Integer.valueOf(2);
private final static int EXPECTED_COUNT = 3;
private final static String FIRST_NAME = "Joe";
private final static String LAST_NAME = "Smith";
private final static int EXPECTED_ADDRESS_COUNT = 1;
private final static String ADDR = "1060 West Addison St.";
private final static String CITY = "Chicago";
private final static String STATE = "IL";
private final static String ZIP_POSTAL = "60613";
private final static String COUNTRY = "USA";
#Autowired
private PersonRepository personRepository;
#Autowired
private ProfessionalRepository professionalRepository;
#Test
public void testFindOne() {
Person person = personRepository.findOne(FIRST_ID);
testPersonOne(person);
}
...
.. //more tests
Any help is much appreciated!
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>spring-mvc-showcase</artifactId>
<name>spring-mvc-showcase</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.7</java-version>
<org.springframework-version>4.2.2.RELEASE</org.springframework-version>
<org.springframework.security-version>4.0.1.RELEASE</org.springframework.security-version>
<org.aspectj-version>1.8.1</org.aspectj-version>
<org.slf4j-version>1.7.12</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<scope>runtime</scope>
</dependency>
<!-- #Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>7.0.30</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jstl-impl</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Jackson JSON Processor -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
<!-- Rome Atom+RSS -->
<dependency>
<groupId>com.rometools</groupId>
<artifactId>rome</artifactId>
<version>1.5.0</version>
</dependency>
<!-- JSR 303 with Hibernate Validator -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.1.0.Final</version>
</dependency>
<!-- Joda Time Library -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
<!-- File Upload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
<!-- Security (used for CSRF protection only) -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${org.springframework.security-version}</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>1.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<!--Additional POM for spring-data-jpa trial -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.1.RELEASE</version>
</dependency>
</dependencies>
<repositories>
<!-- For testing against latest Spring snapshots -->
<repository>
<id>org.springframework.maven.snapshot</id>
<name>Spring Maven Snapshot Repository</name>
<url>http://repo.spring.io/snapshot</url>
<releases><enabled>false</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<!-- For developing against latest Spring milestones -->
<repository>
<id>org.springframework.maven.milestone</id>
<name>Spring Maven Milestone Repository</name>
<url>http://repo.spring.io/milestone</url>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>
<excludes>
<exclude>**/Abstract*.java</exclude>
</excludes>
<junitArtifactName>junit:junit</junitArtifactName>
<argLine>-Xmx512m</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>install</id>
<phase>install</phase>
<goals>
<goal>sources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<!-- Have to use version 1.2 since version 1.3 does not appear to work with ITDs -->
<version>1.2</version>
<dependencies>
<!-- You must use Maven 2.0.9 or above or these are ignored (see MNG-2972) -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<outxml>true</outxml>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.0.6.v20130930</version>
<configuration>
<webApp>
<contextPath>/${project.artifactId}</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
</build>
</project>
So in your pom you are having
and the class which your saying not executing ending with only test.java.
So rename PersonRepositoryTest.java to PersonRepositoryTests.java and try again.

JPA does not return any data from CloudSQL

I have project based on maven for deployment on GoogleAppEngine. I have local MySQL DB (for development) and remote CloudSQL DB (for production)
My code is based on google github
Data inside CloudSQL and MySQL are identical. I have a problem when trying to retrieve data via named query on production - list of size 0 is returned. On local MySQL DB code returns data correctly. I even tried to retrieve data from ClodSQL using standard java.sql.Connection and I was able to retrieve data. No data are returned only when requested from JPA.
Named query used:
#NamedQueries({(name = "Device.getDevices", = "SELECT d FROM Device d")
my persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="transactions-optional-device">
<class>commander.apprecorder.database.pojos.device.Device</class>
<properties>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="datanucleus.autoCreateSchema" value="true"/>
</properties>
</persistence-unit>
</persistence>
Content of pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<groupId>group</groupId>
<artifactId>art</artifactId>
<properties>
<app.id>appid</app.id>
<app.version>version</app.version>
<appengine.version>1.9.30</appengine.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<gcloud.plugin.version>2.0.9.74.v20150814</gcloud.plugin.version>
<objectify.version>5.1.5</objectify.version>
<guava.version>18.0</guava.version>
<datanucleus.jpa.version>3.1.1</datanucleus.jpa.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.showDeprecation>true</maven.compiler.showDeprecation>
<cloudsql.device.url>
jdbc:google:mysql://some:instance:name/db?user=xxx
</cloudsql.device.url>
<cloudsql.device.url.dev>jdbc:mysql://localhost/db?user=x</cloudsql.device.url.dev>
<datanucleus-core.version>4.0.0-release</datanucleus-core.version>
<datanucleus-maven-plugin.version>4.0.0-release</datanucleus-maven-plugin.version>
<datanucleus-accessplatform-jpa-rdbms.version>4.0.0-release</datanucleus-accessplatform-jpa-rdbms.version>
<javax.persistence.version>2.1.0</javax.persistence.version>
</properties>
<prerequisites>
<maven>3.1.0</maven>
</prerequisites>
<dependencies>
<!-- Compile/runtime dependencies -->
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>${appengine.version}</version>
</dependency>
<dependency>
<groupId>com.google.appengine.tools</groupId>
<artifactId>appengine-gcs-client</artifactId>
<version>0.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20151123</version>
</dependency>
<!--JPA start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-accessplatform-jpa-rdbms</artifactId>
<version>${datanucleus-accessplatform-jpa-rdbms.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>javax.persistence</artifactId>
<version>${javax.persistence.version}</version>
</dependency>
<!--JPA end -->
<!-- [START Objectify_Dependencies] -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.objectify</groupId>
<artifactId>objectify</artifactId>
<version>${objectify.version}</version>
</dependency>
<!-- [END Objectify_Dependencies] -->
<!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-testing</artifactId>
<version>${appengine.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-stubs</artifactId>
<version>${appengine.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- for hot reload of the web application-->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>display-dependency-updates</goal>
<goal>display-plugin-updates</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<version>3.2</version>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<dependencies>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>${datanucleus-core.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<archiveClasses>true</archiveClasses>
<webResources>
<!-- in order to interpolate version from pom into appengine-web.xml -->
<resource>
<directory>${basedir}/src/main/webapp/WEB-INF</directory>
<filtering>true</filtering>
<targetPath>WEB-INF</targetPath>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>${appengine.version}</version>
<configuration>
<enableJarClasses>false</enableJarClasses>
<version>${app.version}</version>
<!-- Comment in the below snippet to bind to all IPs instead of just localhost -->
<!-- address>0.0.0.0</address>
<port>8080</port -->
<!-- Comment in the below snippet to enable local debugging with a remote debugger
like those included with Eclipse or IntelliJ -->
<!-- jvmFlags>
<jvmFlag>-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n</jvmFlag>
</jvmFlags -->
</configuration>
</plugin>
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>gcloud-maven-plugin</artifactId>
<version>${gcloud.plugin.version}</version>
<configuration>
<set_default>true</set_default>
</configuration>
</plugin>
<!--DB start-->
<plugin>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-maven-plugin</artifactId>
<version>${datanucleus-maven-plugin.version}</version>
<configuration>
<api>JPA</api>
<persistenceUnitName>transactions-optional-device</persistenceUnitName>
<fork>false</fork>
<!--<persistenceUnitName>Demo</persistenceUnitName>-->
<!--<log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>-->
<verbose>true</verbose>
</configuration>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>${datanucleus-core.version}</version>
</dependency>
</dependencies>
</plugin>
<!--JPA end-->
</plugins>
</build>
And servlet for JPA
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
Map<String, String> properties = new HashMap();
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
properties.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.GoogleDriver");
properties.put("javax.persistence.jdbc.url", System.getProperty("cloudsql.device.url"));
} else {
properties.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
properties.put("javax.persistence.jdbc.url", System.getProperty("cloudsql.device.url.dev"));
}
// List all the rows.
EntityManagerFactory emf = Persistence.createEntityManagerFactory(
"transactions-optional-device", properties);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
resp.getWriter().println("performing query");
List<Device> result = em.createNamedQuery("Device.getDevices", Device.class).getResultList();
resp.getWriter().println("Starting to list devices - " + result.size());
for (Device g : result) {
resp.getWriter().println(g.getA() + "_" + g.getB());
}
em.getTransaction().commit();
em.close();
}
There is no error inside app engine log. Can you please tell me what is wrong? Thanks :)
I set log level to ALL and found out that Datanucleus was trying to access datastore. It created new table inside datastore and retrieved its content - no data.
I have no idea why it was trying to access datastore and was not using CloudSQL, but nevermind...
I replaced DataNucles for Hibernate by tutorial inside google github and it worked on first time
Migration was easy, only persistance.xml and pom.xml had to be modified.

Resources