Programmatically load openjpa javaagent - runtime optimization - openjpa

I am writing unit test for testing JPA DAO and I would like to automatically load the javaagant (JPA class enhancer) without having to specify the -javaagent vm parameter.
To achieve this I implemented a #BeforeClass annotated method like this:
String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('#'));
VirtualMachine vm = VirtualMachine.attach(pid);
vm.loadAgent("openjpa-all-2.4.2.jar");
vm.detach();
emf = Persistence.createEntityManagerFactory("TEST_DB");
But I still get the error telling entity classes were not enhanced when creating the entity manager factory.
org.apache.openjpa.persistence.ArgumentException: This configuration disallows runtime optimization, but the following listed types were not enhanced at build time or at class load time with a javaagent: ")
I can live with the -javaagent parameter but I am curious and would be pleased if anybody could share a solution or idea with us.
I am running my test with JUnit and Java 8

Related

Apache Meecrowave OAuth2 JPA

I succeedeed in creating my own OAuth2 server using JCache as token store but I'm facing an issue when moving to JPA.
My configuration is :
"--users","test=test",
"--roles","test=test",
"--oauth2-provider","jpa",
"--oauth2-jpa-database-driver","org.h2.Driver",
"--oauth2-jpa-database-url","jdbc:h2:mem:oauth",
"--oauth2-jpa-database-username","sa",
"--oauth2-jpa-database-password",""
But I got exception below during OpenJPA bootstrap :
here was an error while setting up the configuration plugin option "MetaDataFactory".
The plugin was of type "org.apache.openjpa.persistence.jdbc.PersistenceMappingFactory".
Setter methods for the following plugin properties were not available in that type: [
org.apache.cxf.rs.security.oauth2.tokens.bearer.BearerAccessToken,
org.apache.cxf.rs.security.oauth2.common.OAuthPermission,
org.apache.cxf.rs.security.oauth2.tokens.refresh.RefreshToken,
org.apache.cxf.rs.security.oauth2.grants.code.ServerAuthorizationCodeGrant,
org.apache.cxf.rs.security.oauth2.common.UserSubject].
Possible plugin properties are:
[AnnotationParser, ClasspathScan, FieldOverride, Files, JAR_FILE_URLS, MAPPING_FILE_NAMES, MODE_ALL, MODE_ANN_MAPPING, MODE_MAPPING, MODE_MAPPING_INIT, MODE_META, MODE_NONE, MODE_QUERY, PERSISTENCE_UNIT_ROOT_URL, Repository, Resources, STORE_DEFAULT, STORE_PER_CLASS, STORE_VERBOSE, StoreDirectory, StoreMode, Strict, Types, URLs, XMLAnnotationParser, XMLParser].
Ensure that your plugin configuration string uses key values that correspond to setter methods in the plugin class.
I suppose I missed something in configuration...
Any help would be appreciated.
Tx
Using --oauth2-jpa-properties you can set any persistence unit properties you want, I guess you will have to override openjpa.MetaDataFactory default value which is set to jpa(Types=org.apache.cxf.rs.security.oauth2.common.Client,org.apache.cxf.rs.security.oauth2.common.OAuthPermission,org.apache.cxf.rs.security.oauth2.common.UserSubject,org.apache.cxf.rs.security.oauth2.grants.code.ServerAuthorizationCodeGrant,org.apache.cxf.rs.security.oauth2.tokens.bearer.BearerAccessToken,org.apache.cxf.rs.security.oauth2.tokens.refresh.RefreshToken).
You can also check if your configuration is properly propagated and if there is no classpath conflict (another persistence.xml with an oauth2 unit?) because I just retested and your configuration seems to work.
Romain

Spring Data Cassandra - Environment must not be null Error

I am following basic tutorial at Spring Data Cassandra reference http://docs.spring.io/spring-data/cassandra/docs/1.1.0.RC1/reference/html/ and I am running into following exception
java.lang.IllegalArgumentException: Environment must not be null!
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.data.repository.config.RepositoryConfigurationSourceSupport.<init>(RepositoryConfigurationSourceSupport.java:50)
at org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource.<init>(AnnotationRepositoryConfigurationSource.java:74)
at org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport.registerBeanDefinitions(RepositoryBeanDefinitionRegistrarSupport.java:74)
at org.springframework.context.annotation.ConfigurationClassParser.processImport(ConfigurationClassParser.java:394)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:204)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:163)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:138)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:284)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:225)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:73)
at com.strides.platform.domain.UserRepositoryDaoTest.<init>(UserRepositoryDaoTest.java:28)
I have completed steps mentioned in document,
1) Use Cassandra Properties
2) Create Java configuration
3) Create domain and repository classes
I have autowired Environment variable in Test classes. I checked couple of sample projects and not sure what needs to be done more.
I've encountered this error message and found the problem only occuring when I used Spring Framework version 3.2.8.RELEASE.
My solution was to upgrade to version 3.2.9.RELEASE.
See also java.lang.IllegalArgumentException: Environment must not be null

Memory Leak in Grails with MongoDB

I've found a strange issue when saving or updating several objects in Grails with MongoDB. Currently I'm using Grails 2.2.3 and MongoDB plugin 1.3.0.
The problem seems to be that the instances of MiUsuario are never GC neither when I manually call the GC. In our main application we don't make batch updates, but when doing load tests (with JMeter and monitoring JVM with Java VisualVM) this problem causes memory filling and Tomcat stops responding.
I've created a small new application to show the problem.
A simple domain object:
class MiUsuario {
ObjectId id
String nickName
}
My controller:
import pruebasrendimiento.Prueba
class MiUsuarioController {
def doLogin(String privateKey, String id){
MiUsuario user = MiUsuario.get(id)
user.nickName = new Random().nextInt().toString()
user.save(failOnError:true)
render 'ok'
}
}
My BuildConfig (Just the dependencies and plugins part):
dependencies {
}
plugins {
// runtime ":hibernate:$grailsVersion"
runtime ":jquery:1.8.3"
runtime ":resources:1.2"
build ":tomcat:$grailsVersion"
// runtime ":database-migration:1.3.2"
// compile ':cache:1.0.1'
runtime ":mongodb:1.3.0"
}
I've also tried something that Burt said a long time ago (http://burtbeckwith.com/blog/?p=73), but DomainClassGrailsPlugin.PROPERTY_INSTANCE_MAP.get().clear() doesn't make any difference. And the other option that's said in that page, RequestContextHolder.resetRequestAttributes(), gives me an exception.
I had similar problem and it solves upgrading to grails 2.3.1. Try it.

Code coverage on Play! project

I have a Play! project where I would like to add some code coverage information. So far I have tried JaCoCo and scct. The former has the problem that it is based on bytecode, hence it seems to give warning about missing tests for methods that are autogenerated by the Scala compiler, such as copy or canEqual. scct seems a better option, but in any case I get many errors during tests with both.
Let me stick with scct. I essentially get errors for every test that tries to connect to the database. Many of my tests load some fixtures into an H2 database in memory and then make some assertions. My Global.scala contains
override def onStart(app: Application) {
SessionFactory.concreteFactory = Some(() => connection)
def connection() = {
Session.create(DB.getConnection()(app), new MySQLInnoDBAdapter)
}
}
while the tests usually are enclosed in a block like
class MySpec extends Specification {
def app = FakeApplication(additionalConfiguration = inMemoryDatabase())
"The models" should {
"be five" in running(app) {
Fixtures.load()
MyModels.all.size should be_==(5)
}
}
}
The line running(app) allows me to run a test in the context of a working application connected to an in-memory database, at least usually. But when I run code coverage tasks, such as scct coverage:doc, I get a lot of errors related to connecting to the database.
What is even more weird is that there are at least 4 different errors, like:
ObjectExistsException: Cache play already exists
SQLException: Attempting to obtain a connection from a pool that has already been shutdown
Configuration error [Cannot connect to database [default]]
No suitable driver found for jdbc:h2:mem:play-test--410454547
Why is that launching tests in the default configuration is able to connect to the database, while running in the context of scct (or JaCoCo) fails to initialize the cache and the db?
specs2 tests run in parallel by default. Play disables parallel execution for the standard unit test configuration, but scct uses a different configuration so it doesn't know not to run in parallel.
Try adding this to your Build.scala:
.settings(parallelExecution in ScctPlugin.ScctTest := false)
Alternatively, you can add sequential to the beginning of your test classes to force all possible run configurations to run sequentially. I've got both in my files still, as I think I had some problems with the Build.scala solution at one point when I was using an early release candidate of Play.
A better option for Scala code coverage is Scoverage which gives statement line coverage.
https://github.com/scoverage/scalac-scoverage-plugin
Add to project/plugins.sbt:
addSbtPlugin("com.sksamuel.scoverage" % "sbt-scoverage" % "1.0.1")
Then run SBT with
sbt clean coverage test
You need to add sequential in the beginning of your Specification.
class MySpec extends Specification {
sequential
"MyApp" should {
//...//
}
}

grailsApplication not getting injected in a service , Grails 2.1.0

I have service in which i am accessing few configuration properties from grailsApplication
I am injecting it like this
class MyWebService{
def grailsApplication
WebService webService = new WebService()
def getProxy(url, flag){
return webService.getClient(url)
}
def getResponse(){
def proxy = getProxy(grailsApplication.config.grails.wsdlURL, true)
def response = proxy.getItem(ItemType)
return response
}
}
When i call getProxy() method, i see this in tomcat logs
No signature of method: org.example.MyWebService.getProxy() is applicable for argument types: (groovy.util.ConfigObject, java.lang.Boolean) values: [[:], true]
Possible solutions: getProxy(), getProxy(java.lang.String, boolean), setProxy(java.lang.Object)
which means grailsApplication is not getting injected into the service, is there any alternate way to access configuration object ? according to burtbeckwith's post configurationholder has been deprecated, can't think of anything else.
Interestingly the very same service works fine in my local IDE(GGTS 3.1.0), that means locally grailsApplication is getting injected, but when i create a war to deploy to a standalone tomcat, it stops getting injected.
I seem to have figured out the problem, actually grailsApplication is getting injected properly otherwise it would have thrown a null pointer exception, i feel the configuration properties are not getting added. Actually the scenario is like, i have a separate custom configuration file which holds configuration data for different environments, my application listens to the environement type(a variable which is set from tomcat) and based on that merges the corresponding config properties from my custom configuration file. i think those propreties are probably not getting added