Eclipselink static weaving in Java web application - Eclipse - java

Im currently working on project where I develop Java web application. I use IDE Eclipse.
As data layer I use EclipseLink(2.6) JPA. Web application runs on Tomcat webserver(7). Now I realized that I need to use LAZY fetching for my Entities because of performance issues.
After some research I figured out that I need to use "static weaving", acording to manual pages, I found that I have 3 possibilities how to do that: Ant, Maven or use command line.
Since I have no experience with Ant, Maven or command line options I dont know how to continue now. I would like to pick easiest solution, which is Ant (from my begginer point of view). Can you suggest?
My project is divided into two projects:
JPA project, with persistence entities and database operations
Java application with servlets and JSP, this project contains link to JPA project
I run that application on:
remote Tomcat server - then I generate .war file that contains both projects and then I upload it on server
localhost - then I run that application directly from Eclipse (Run As -> localhost)
Can please somebody tell me process how I should continue now?
Shall I specify two steps Ant build that firstly create .jar from my JPA project, then do static weaving and continue in building web project to .war? So far I found only Ant builds where .jar applications are generated, not sure how it differ to web applications. Any tutorials there?
Can please somebody share some hits? I am complete beginer in this area - perhaps I missed some easy ways. My main goal is to have .war file that contains entities with static weaving, secondary goal is to automate deploying on tomcat localhost server, as I do it now from Eclipse IDE.
Thank you.

I can only speak for the Maven side of things, because thats the one I have experience with.
Inside your pom.xml , under plugins you will have to add the maven staticweave plugin:
<plugin>
<groupId>de.empulse.eclipselink</groupId>
<artifactId>staticweave-maven-plugin</artifactId>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>weave</goal>
</goals>
<configuration>
<persistenceXMLLocation>META-INF/persistence.xml</persistenceXMLLocation>>
</configuration>
</execution>
</executions>
</plugin>
You may have to adjust your persistence.xml-location.
Inside your persistence.xml you will need to activate static weaving:
<properties>
<property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.H2Platform" />
<property name="eclipselink.weaving" value = "static"/>
<property name="eclipselink.weaving.internal" value="true"/>
<property name="eclipselink.weaving.lazy" value="true" />
<property name="eclipselink.weaving.changetracking" value="true" />
<property name="eclipselink.weaving.fetchgroups" value="true" />
<property name="eclipselink.weaving.eager" value="false" />
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<property name="eclipselink.logging.level" value="FINEST" />
</properties>
Again, you may have to change your platform, desired logging level and the other parameters.
If you leave all the eclipselink.weaving.*-parameters out, they will have their default values.
The static weaving happens in the process-classes phase of the maven lifecycle after the compile phase. If you have packaging set to war, you will get a single *.war-file that you can then deploy.
If you would really rather do it via ant-task, you should look at
https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Advanced_JPA_Development/Performance/Weaving/Static_Weaving#Use_the_weave_Ant_Task
I can't really answer any questions about that though.

Related

Wildfly Data Persistence

I am currently working on a Java EE project and am working with the Wildfly server.
I have a Web project and EJB project which are deployed onto the Wildfly server.
I can save a user for example, but only for as long as the server is running.
There is no data persistence between server downtimes.
I have searched through the internet but couldn't find an answer.
My persistence.xml looks like this:
<persistence-unit name="primary">
<!-- If you are running in a production environment, add a managed
data source, this example data source is just for development and testing! -->
<!-- The datasource is deployed as WEB-INF/kitchensink-quickstart-ds.xml, you
can find it in the source at src/main/webapp/WEB-INF/kitchensink-quickstart-ds.xml -->
<jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="false" />
<value="true"/>
</properties>
If I want to persist any information, do i need to reconfigure this file?
I hope you can help me :)
Your problem is this line
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
Everytime when the wildfly starts up, JPA creates a new database model with an empty database.
Adjust your code to
<property name="hibernate.hbm2ddl.auto" value="update" />
You are using "ExampleDS" which is set up as H2 in-memory database by default. It therefore does not persist data between restarts on purpose (useful for development/testing). Go to wildfly's standalone/configuration/standalone.xml configuration file and search for "ExampleDS" in the "datasources" section. It should show:
<connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
where "mem" means in-memory. You can change "mem:test" to any write path, e.g.
<connection-url>jdbc:h2:~/test;DB_CLOSE_DELAY=-1</connection-url>
to use a H2 file-based database stored as "test" in your home-folder (assuming *nix).
You can also define additional databases (Postgresql, Oracle, etc) in the datasources-section.

Debug Arquillian tests in IntelliJ

I have Java EE project in which I use Arquillian tests with JUnit on JBoss 7 (Windows). Tests are working fine however I cannot debug them.
From what I've googled (https://community.jboss.org/wiki/WhyDontBreakPointsWorkWhenDebugging) I understand that Arquillian tests are being run in separate VM therefore IntelliJ cannot debug them. I need IntelliJ to connect to that machine remotely over socket but I dont know how to do it.
I found this thread: Debugging with Arquillian in IntelliJ - Managed Container However I dont know how to get it work.
Also I stepped over this thread: http://devnet.jetbrains.com/message/5253623?tstart=0 so I filled hopefully appropriet surefire part in my pom.xml but it didnt help:
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.4.3</version>
<configuration>
<debugForkedProcess>true</debugForkedProcess>
<skip>false</skip>
</configuration>
</plugin>
Could anyone guild me please how to debug tests in such configuration?
First of all depend on the container type you are using - managed, remote or embedded. See also https://docs.jboss.org/author/display/ARQ/Containers. For the latter the tests are running in the same JVM and you can for example debug your test directly in the IDE.
The Surefire configuration is in this case not important, because you want to debug in your IDE (unless you are executing maven goals from within your IDE).
For managed and remote containers you need to debug the actual container. For this to wrok you have to pass the right JVM options to the remote container, so that you can open a remote debugging session. One way of doing this is via arquillian.xml:
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<!-- Need to set the default protocol and use resource filtering, because of https://issues.jboss.org/browse/ARQ-579 -->
<defaultProtocol type="Servlet 3.0"/>
<engine>
<property name="deploymentExportPath">target/artifacts</property>
</engine>
<container qualifier="incontainer">
<configuration>
<property name="jbossHome">${jbossTargetDir}</property>
<property name="javaVmArguments">-Xmx1024m -XX:MaxPermSize=512m -Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005</property>
<property name="allowConnectingToRunningServer">true</property>
</configuration>
</container>
The important part in the example above being the javaVmArguments.
I can run Arqullian tests by either Maven or by IntelliJ. I use embedded container. The most important thing is to configure the JBoss home at arqullian.xml nor just at the Maven configuration to IntelliJ know where the JBoss home is.
<arquillian xmlns="http://jboss.org/schema/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<engine>
<property name="deploymentExportPath">testing/target/artifacts</property>
</engine>
<container qualifier="jbossas-managed" default="true">
<configuration>
<!-- JBoss embedded does not use this property
<property name="javaVmArguments">-java.util.logging.manager=org.jboss.logmanager.LogManager -Xmx512m -XX:MaxPermSize=256m -Djava.util.logging.manager=org.jboss.logmanager.LogManager</property>
-->
<property name="jbossHome">target/wildfly-8.1.0.Final</property>
<property name="modulePath">target/wildfly-8.1.0.Final/modules</property>
<property name="allowConnectingToRunningServer">true</property>
</configuration>
</container>
IMPORTANT for debugging and running test in IntelliJ:
From some reason you must specify the logging manager to be able run embedded JBoss. For Maven it is easy and you can set it to configuration:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!-- Fork every test because it will launch a separate AS instance -->
<forkMode>always</forkMode>
<systemPropertyVariables>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
</systemPropertyVariables>
<redirectTestOutputToFile>false</redirectTestOutputToFile>
</configuration>
</plugin>
But the IntelliJ does not care about these plugin configuration at Maven and you must set it directly at the test case configuration. I did not find better solution. The embedded container does not care about Java VM configuration in arqullian.xml.
Here is always possibility to debug throught remote debugging. I like to do it at IDE. For me it is more confortable way. When you want to enable remote debugging you must set configuration to JAVA_OPT for embedded container nor at arqullian.xml.

How to instruct Maven to ignore my main/resources/persistence.xml in favor of test/...?

I have two persistence.xml files, for the sake of testing:
src/main/resources/META-INF/persistence.xml
src/test/resources/META-INF/persistence.xml
How to instruct Maven to ignore the first file during testing? Now it is not ignored since OpenEJB says:
ERROR - FAIL ... Finder: #PersistenceContext unitName has multiple matches:
unitName "abc" has 2 possible matches.
Check out the alternate descriptors functionality which is aimed at what you're trying to do.
Try this setup:
src/main/resources/META-INF/persistence.xml
src/main/resources/META-INF/test.persistence.xml
Then you can construct OpenEJB to prefer the test.persistence.xml file by setting the openejb.altdd.prefix System or InitialContext property to test
A different possible solution could be to override the persistence unit properties in the test. With that approach you could avoid the need for a second persistence.xml which can be nice as maintaining two can be a pain.
You can use the Maven approach, but be aware that per spec the persistence provider will only look (aka scan) for #Entity beans in the exact jar or directory where the persistence.xml is found. So be keenly aware that in Maven these are two different locations:
target/classes
target/test-classes
EDIT More details on the overriding capabilities
You can override any property in your test setup via either system properties or the initial context properties (this includes jndi.properties files). The format is:
<unit-name>.<property>=<value>
So for example with the following persistence.xml:
<persistence>
<persistence-unit name="movie-unit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>movieDatabase</jta-data-source>
<non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.max_fetch_depth" value="3"/>
</properties>
</persistence-unit>
</persistence>
You can override and add persistence unit properties in your test case. There are currently no facilities for removing them (if you have a need for that let us know – it hasn't really come up so far).
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");
p.put("movie-unit.hibernate.hbm2ddl.auto", "update");
p.put("movie-unit.hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
context = new InitialContext(p);
Or alternatively via a jndi.properties file
java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory
movie-unit.hibernate.hbm2ddl.auto = update
movie-unit.hibernate.dialect = org.hibernate.dialect.HSQLDialect
I think you can create two profiles in your pom.xml:
<properties>
<environment>dev</environment>
</properties>
<profiles>
<profile>
<id>prod</id>
<properties>
<environment>test</environment>
</properties>
</profile>
</profiles>
After that, in your src folder, create two folders named dev/resoruces and test/resources and copy your different resources there. After that, add something like this:
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<filtering>false</filtering>
</resource>
<resource>
<directory>${basedir}/src/main/${environment}/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
The ${basedir} depends on the command line parameter, it can be test or dev.
You run the maven command like this: mvn clean package -P test.
I have been testing these and other similar solutions without involving the pom.xml... In my opinion, the best way to solve this issue is to have two application-context.xml (one only to be used in test classes) and to add a custom persistence unit manager bean in the test's application-context.xml. Like this example:
<bean id="pum" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocation">
<value>classpath*:META-INF/test.persistence.xml</value>
</property>
<property name="defaultDataSource" ref="dataSource"/>
</bean>
This solution runs.
:)
Better add both files - in general, making test/production or debug/profile/production distinction in build makes only trouble.
Better try to use different perasistence unit name for production (say abc-production) and for tests (abc-tests).

after assembling jar - No Persistence provider for EntityManager named

im developing a standalone application and it works fine when starting it from my ide(intellij idea), but after creating an uberjar and start the application from it javax.persistence.spi.PersistenceProvider is thrown saying "No Persistence provider for EntityManager named testPU"
here is my persistence.xml which is placed under meta-inf directory:
<persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>test.model.Configuration</class>
<properties>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value="root"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
and here is how im creating the entity manager factory:
emf = Persistence.createEntityManagerFactory("testPU");
im using maven and tried the assembly plug-in with the default configuration fot it, i dont have much experience with assembling jars and i dont know if im missing something, so if u have any ideas ill be glad to hear them
You are probably having problems with your libraries.. Try doing below.
Build your application JAR File
Get all libraries that you have used for the application and put them in a folder lib.
Place your JAR file and lib folder in a new folder say MyApp.
Open your file by using 7-ZIP or WinRAR. Look for Manifest.MF in the META-INF folder.
Your manifest file should look something like..
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.0
Created-By: 1.6.0_03-b05 (Sun Microsystems Inc.)
Main-Class:
Class-Path: lib/.jar lib/.jar lib/.jar ...
I remember having that issue, and I think the problem was that you can't reference a jar in a jar. For your external libraries, they need to be expanded inside your jar or live elsewhere on the system CLASSPATH. So since you don't specify what all you're putting in your jar, I'm betting on this one.
You can NOT use the -cp command line parameter if you run your jar using the -jar parameter. One or the other.
When using the Maven Assembly Plugin with the predefined jar-with-dependencies descriptor, you get a jar archive which contains the binary output of your project, along its the unpacked dependencies. So one possible problem I can think of would be multiple JARs with persistence.xml, in which case I'm not sure which one you'll get in the final assembly.
Since you get an error message complaining about "No Persistence provider for EntityManager named testPU", I would open the megajar and:
check that the persistence.xml is present (it should)
check that it contains the expected persistence unit testPU
if it doesn't, find the origin of the conflicting file and rewrite the assembly descriptor to exclude it

How to create a development/debug and production setup

I recently deployed inadvertently a debug version of our game typrX
(typing races at www.typrx.com - try it it's fun).
It was quickly corrected but I know it may happen again. After digging
on Google I found some info how to create 2 different profiles, one
for development mode that has the debug functions and one used for
deployment. Here is what I found from a Google IO presentation. Does
anyone have this setup? Can someone explains how to run this?
MyAppCommon.gwt.xml
<module>
...
<define-property values="debug, release" name="app.config" />
<replace-with class="myapp.debug.DebugConsole">
<when-type-is class="myapp.Console" />
<when-property-is name="app.config" value="debug" />
</replace-with>
...
</module>
MyAppDebug.gwt.xml
<module>
...
<set-property name="app.config" value="debug" />
</module>
The idea of using a specific module for debugging has been floating around for some times, and was also mentioned in this Google I/O presentation (see slide 33 from PDF or at 0h31m in the video).
The basic idea is that you have a standard GWT module, and a second debug module that inherits this standard module, configures some properties, and uses GWT's deferred binding to replace some classes with specific instances when debugging.
Then, you only have to configure your Maven / ant build to compile the appropriate module depending on wether you are in development mode or in release mode.
In my project, I did not create an "app.config" deferred binding property, but I might do that later on. What I did was the following:
Created a standard module
com/example/MainModule.gwt.xml:
<module rename-to="mainModule">
<inherits name="com.smartgwt.SmartGwt" />
<!-- (other configurations) -->
<!-- gwt-log configuration -->
<define-property name="log_level" values="OFF,DEBUG" />
<inherits name="com.allen_sauer.gwt.log.gwt-log-common" />
<!-- Locales we want to compile for -->
<extend-property name="locale" values="en" />
<extend-property name="locale" values="fr_FR" />
</module>
Created a "debug" module, that inherits the standard module and configures some additional properties for development
com/example/MainModuleDebug.gwt.xml:
<module rename-to="mainModule">
<inherits name="com.example.MainModule" />
<set-property name="user.agent" value="gecko1_8" />
<set-property name="locale" value="fr_FR"/>
<set-property name="log_level" value="DEBUG" />
</module>
Note: the rename-to attribute is very important here, since you want both modules to be deployed under the exact same name. When you compile during development, you do not want to have to change all your html host pages to point to the debug module.
Configured Maven and the gwt-maven-plugin to compile the right module
<project>
(...)
<properties>
(...)
<!--
Suffix appended to the names of the GWT modules we compile in our child projects.
Empty by default, this suffix is overriden by some profiles to specify an alternative module to compile.
-->
<gwt.module.suffix></gwt.module.suffix>
<!-- We force GWT-recompilation by default (except when using the "gwtDebug" profile - see below for more info) -->
<gwt.compiler.force>true</gwt.compiler.force>
</properties>
(...)
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>gwt-maven-plugin</artifactId>
<configuration>
(...)
<module>com.example.MainModule${gwt.module.suffix}</module>
</configuration>
</plugin>
(...)
<profiles>
<!-- This profile should be used during *DEVELOPMENT* -->
<profile>
<id>gwtDebug</id>
<properties>
<gwt.module.suffix>Debug</gwt.module.suffix>
<!-- Tells gwt-maven-plugin to recompile GWT modules only when necessary -->
<gwt.compiler.force>false</gwt.compiler.force>
</properties>
<activation>
<property>
<name>gwtDebug</name>
</property>
</activation>
</profile>
</profiles>
</project>
Simply doing "maven clean install" will compile the production module. In development, you use "mvn clean install -DgwtDebug" to activate the gwtDebug profile, which in turn compiles the debug module.
Of course, you could configure your ~/.m2/settings.xml to always define the "gwtDebug" property...
The same idea would also apply to Ant. But I'm not well versed with it.
When you starts to toy with the idea of overriding your real module with a debug module, you start to envision some very cool possibilities:
You could add performance logs, which would be pruned from the code when in production.
You could configure all your toString() methods to return something useful when in debug mode, and the empty string when in production (and thus reduce the .js size).
You may reduce the number of permutations by specifying only one locale / one browser / one log level, to speed up the compilation (but do not forget to test for other locales / browsers from time to time).

Categories