Spring Boot app that uses Groovy for JDBC - spring

I have spring-boot application that exposes ReST APIs. I am considering offloading all SQL reads to Groovy SQL. The DataSource is configured in Spring. I would like Groovy to use this DataSource. Btw, there will be multiple DataSource objects (connecting to different datbases).
What is the best approach for this - I want best of both worlds (DI and groovy simplicity). The App has to be in Spring (for project reasons) and will be deployed in WebLogic server utilizing WebLogic defined Data sources.
My idea is to call a Groovy method as shown below from the ReST controller method of Spring-boot:
/student/id
Student getStudentDetails(int id){
#Autowired
#Qualifier("someDataSource");
DataSource myDs;
Student student = GroovySqlUtil.findStudentById(id, myDs); // pass the DS to Groovy sothat GrooySQL can use the DS for executing queries.
return student;
}
Is there a better way? Can Groovy directly handle Data sources (multiple DDs)? In that case I won't initialize DataSource in Spring configuration.
There's no requirement for transactions, JPA etc. It's pure SQL read operations.

In fact Groovy, Java, Gradle and Spring-boot can be mixed without any issues. I create a new ReST service in Groovy class and utilized groovy.Sql. Everything works fine.
Just that the Gradle build file need below configuration:
sourceSets {
main {
groovy {
// override the default locations, rather than adding additional ones
srcDirs = ['src/main/groovy', 'src/main/java']
}
java {
srcDirs = [] // don't compile Java code twice
}
}
}
And also have the groovy package in component scan of main Spring configuration class.

Related

How do I create a CLI utility that shares code with the my Spring Boot application without pulling in everything?

I have a Kotlin Spring Boot application and want to add a little command line utility. The utility is not needed to build the application, it's just an internal tool that shares code with the application. In particular, it uses s a Client class which in turn depends on a Configuration (initialized with values from application.yml) and some external dependencies.
How can I run this utility app without pulling in all of Spring Boot? For example, I don't want the JDBC driver and any web service clients.
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
fun main(vararg args: String) {
runApplication<TheUtility>(*args)
}
#SpringBootApplication
class TheUtility(private val client: TheClient) {
fun run(args: Array<String>) {
// code goes here
}
}
TheClient.kt uses some external libraries defined as project dependencies, plus a configuration:
#Component
#Configuration
class TheClient(
private val config: TheConfig,
#Value("classpath:more-config.json") private val json: Resource
) {
// ...
}
TheConfig.kt:
#ConfigurationProperties(prefix = "my-settings")
data class TheConfig(
var fromApplicationYml: String = ""
}
When I run this, I see messages about bootstrapping Spring Data JPA repositories, Kubernetes, Tomcat, and Hibernate... all of which I don't need in my utility.
(I currently have this in the regular src/main/kotlin/... folders. Is there a better place to put the CLI utility, like in an additional source folder? I really only need to have the external dependencies plus the Spring dependency injection for my configuration.)
How do I create a CLI utility that shares code with the my Spring Boot and uses dependency injection, application without pulling in everything?

Launch spring boot mvc test from custom testng framework

Where I'm working one of our customer required to use a custom test framework written using testng that allows to handle different parameters and test iterations using excel files.
This framework uses a main class to handle all the tests, lets call it TestManager.
This TestManager defines all the #Before and #After operations and has a method called exec() which is annotated as #Test.
This method is used to call the different components required from the test, these components are java classes that implements a single method exec() containing the logic of the single component.
public class TestManager {
// ... Before, After methods
#Test(
dataProvider = "..."
)
public void exec(Parameter[] inParameter) {
// load parameters...
foreach component:
component.exec()
}
}
public class ComponentXYZ {
public void exec() {
// load input params
// Call a microservice and get results, find value on db, selenium operations...
// unload output params for next components
}
}
This framework was designed to be used with selenium, or to test microservices using some http request library and is contained in a standalone module.
So my project has:
A spring boot module
A test module which (in my idea) should have a dependency over the spring boot module
Given this situation do you think it could be possible to use WebMvcTest to perform integration tests while using this custom framework?
I've been trying for a while but I'm always getting errors or I'm not able to #Autowire MockMvc, I can't seem to start a minimal spring boot instance directly from this test framework...
I don't think running my spring boot app and calling the microservices using http is the correct way to test but at this moment is the only thing it's working.

How to statically weave JPA entities using EclipseLink when there is no persistence.xml as the entities are managed by Spring

I've got a project that is Spring based, so the entity manager is set up progammatically, with no need for persistence.xml files to list all the entities.
I'm currently using load time weaving but am trying to get static weaving working using Eclipselink and Gradle. I want to replicate what is performed by the maven eclipselink plugin:
https://github.com/ethlo/eclipselink-maven-plugin
I have the following gradle set up (note that it's Kotlin DSL not groovy):
task<JavaExec>("performJPAWeaving") {
val compileJava: JavaCompile = tasks.getByName("compileJava") as JavaCompile
dependsOn(compileJava)
val destinationDir = compileJava.destinationDir
println("Statically weaving classes in $destinationDir")
inputs.dir(destinationDir)
outputs.dir(destinationDir)
main = "org.eclipse.persistence.tools.weaving.jpa.StaticWeave"
args = listOf("-persistenceinfo", "src/main/resources", destinationDir.getAbsolutePath(), destinationDir.getAbsolutePath())
classpath = configurations.getByName("compile")
}
When I try and run the task the weaving tasks fails as it's looking for a non-existent persistence.xml.
Is there any way you can statically weave JPA entities in a Spring based JPA project ?
Exception Description: An exception was thrown while processing persistence.xml from URL: file:/home/blabla/trunk/my-module/src/main/resources/
Internal Exception: java.net.MalformedURLException
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionProcessingPersistenceXML(PersistenceUnitLoadingException.java:117)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceXML(PersistenceUnitProcessor.java:579)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceArchive(PersistenceUnitProcessor.java:536)
... 6 more
Caused by: java.net.MalformedURLException
at java.net.URL.<init>(URL.java:627)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:620)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:148)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:806)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceXML(PersistenceUnitProcessor.java:577)
... 7 more
Caused by: java.lang.NullPointerException
at java.net.URL.<init>(URL.java:532)
... 17 more
According to org.eclipse.persistence.tools.weaving.jpa.StaticWeave documentation, it requires the persistence.xml in place to generate the static weaving sources.
Usage:
StaticWeave [options] source target
Options:
-classpath
Set the user class path, use ";" as the delimiter in Window system and
":" in Unix system.
-log
The path of log file, the standard output will be the default.
-loglevel
Specify a literal value for eclipselink log level(OFF,SEVERE,WARNING,INFO,CONFIG,FINE,FINER,FINEST). The default
value is OFF.
-persistenceinfo
The path contains META-INF/persistence.xml. This is ONLY required when the source does not include it. The classpath must contain all
the classes necessary in order to perform weaving.
I run a maven build using eclipselink maven plugin, it works without the persistence.xml as you mentioned, because it generates the persistence.xml
before invoking the StaticWeave.class when It is not located in the CLASSPATH, using this method.
private void processPersistenceXml(ClassLoader classLoader, Set<String> entityClasses)
{
final File targetFile = new File(this.persistenceInfoLocation + "/META-INF/persistence.xml");
getLog().info("persistence.xml location: " + targetFile);
final String name = project.getArtifactId();
final Document doc = targetFile.exists() ? PersistenceXmlHelper.parseXml(targetFile) : PersistenceXmlHelper.createXml(name);
checkExisting(targetFile, classLoader, doc, entityClasses);
PersistenceXmlHelper.appendClasses(doc, entityClasses);
PersistenceXmlHelper.outputXml(doc, targetFile);
}
The complete source code is here
I believe you could follow the same approach in your gradle build.
Kinda late to the party but this is definitely possible with Gradle.
There are 3 steps to do in order to make this work:
Copy the persistence.xml file into the source folder next to the classes
Do the weaving
Remove the persistence.xml file from the classes source folder to avoid duplicate persistence.xml conflicts on the classpath
Also, it's very important to hook the weaving process into the compileJava task's last step in order to not break Gradle's up-to-date check, otherwise Gradle will just recompile everything all the time which can be quite inconvenient when developing.
For a more detailed explanation, check out my article on it: EclipseLink static weaving with Gradle.
I admit, I do not completely understand what you mean by weaving. My answer might help if you need to create dynamically PersistenceUnits which provide JPA-Entitymanagers, and if these units should be able to create a Db-Schema (for example in H2) and manage Entities based dynamically on the classes you provide at runtime.
The code-example I am mentioning later, does not work with JPA in Spring but in Weld. I think the answer to your question is related to how EntityManagers are created and what classes the PersistenceUnit, which creates the EntityManager, does manage. There is no difference between those two. Instead of using the EntityManagerFactory as CDI-Producer you might Autowire it or register it using an old fashioned application-context. Therefore I think the answer to your question lies in the following official sources:
PersistenceProviderResolverHolder and
PersistenceProvider#createEntityManagerFactory(getPersistenceUnitName(), properties)
properties is the replacement for the persistence.xml, where a SEPersistenceUnitInfo-Object can be registered in.
To start look at: PersistenceProviderResolverHolder
Later: PersistenceProvider
or you can try to understand how my code (see below) is doing that. But I have to admit, I am not very proud of this part of that software, sorry.
Those classes and objects are used by me to create a module that enables the simulation of a server deployed JPA-WAR-File.
To do that, it scans some classes and identifies Entities.
Later in the Testcode a so called PersistenceFactory creates EntityManager and Datasources. If eclipselink is used this factory weaves those classes together. You need no persistence.xml. The working there might be help to answer your question.
If you look at:
ioc-unit-ejb:TestPersistencefactory
search for the creation of SEPersistenceUnitInfo. That Interface got fed by a list of classes which it returns as
#Override
public List<String> getManagedClassNames() {
return TestPersistenceFactory.this.getManagedClassNames();
}
This object is used to create a Persistencefactory with the help of a PersistenceProvider. This can be discovered as soon as eclipselink is available in the classpath.
The code is not easy to be understood because it allows both Hibernate or Eclipselink to be used for JPA, that depends on the availability of the jars in the classpath.

Using Spring DSL in a Grails Plugin

I'm trying to use the Spring DSL functionality in a Grails plugin. However, it doesn't work. Here's what I have in my plugin's conf/spring/resources.groovy file:
import org.springframework.aop.scope.ScopedProxyFactoryBean
// Place your Spring DSL code here
beans = {
baseSvcProxy(ScopedProxyFactoryBean) {
targetBeanName = 'baseService'
proxyTargetClass = true
}
}
However, it seems to be completely ignored. If I move the exact same code to the application's conf/spring/resources.groovy file everything works perfectly. Is there something that needs to be done differently for plugins for this to work?
In order to modify the spring context from a Grails plugin you need to use the doWithSpring section of your plugin by hooking into the runtime configuration. Resources.groovy is ignored in plugins.

Unit testing with Spring and the Jersey Test Framework

I'm writing some JUnit-based integration tests for a RESTful web service using JerseyTest. The JAX-RS resource classes use Spring and I'm currently wiring everything together with a test case like the following code example:
public class HelloResourceTest extends JerseyTest
{
#Override
protected AppDescriptor configure()
{
return new WebAppDescriptor.Builder("com.helloworld")
.contextParam( "contextConfigLocation", "classpath:helloContext.xml")
.servletClass(SpringServlet.class)
.contextListenerClass(ContextLoaderListener.class)
.requestListenerClass(RequestContextListener.class)
.build();
}
#Test
public void test()
{
// test goes here
}
}
This works for wiring the servlet, however, I'd like to be able to share the same context in my test case so that my tests can have access to mock objects, DAOs, etc., which seems to call for SpringJUnit4ClassRunner. Unfortunately, SpringJUnit4ClassRunner creates a separate, parallel application context.
So, anyone know how can I create an application context that is shared between the SpringServlet and my test case?
Thanks!
Override JerseyTest.configure like so:
#Override
protected Application configure() {
ResourceConfig rc = new JerseyConfig();
rc.register(SpringLifecycleListener.class);
rc.register(RequestContextFilter.class);
rc.property("contextConfigLocation", "classpath:helloContext.xml");
return rc;
}
For me the SpringServlet was not required, but if you need that you may be able to call rc.register for that too.
I found a couple of ways to resolve this problem.
First up, over at the geek#riffpie blog there is an excellent description of this problem along with an elegant extension of JerseyTest to solve it:
Unit-testing RESTful Jersey services glued together with Spring
Unfortunately, I'm using a newer version of Spring and/or Jersey (forget which) and couldn't quite get it to work.
In my case, I ended up avoiding the problem by dropping the Jersey Test Framework and using embedded Jetty along with the Jersey Client. This actually made better sense in my situation anyway since I was already using embedded Jetty in my application. yves amsellem has a nice example of unit testing with the Jersey Client and embedded Jetty. For Spring integration, I used a variation of Trimbo's Jersey Tests with Embedded Jetty and Spring

Resources