My execution halts while implemented the Data Driven Approach - citrus-framework

I have included few lines of code for data driven, where I will fetch the details from a Excel sheet and it will pass to the script in Run Time. Here my script won't execute and it hangs after returning the message in Eclipse Console:
Returning cached instance of singleton bean 'todoClient1'
Below attached the Code and package com.consol.citrus.integration.Demo.
import java.util.Hashtable;
import org.apache.log4j.helpers.SyslogWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ImportResource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.testng.SkipException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import com.consol.citrus.TestCaseMetaInfo.Status;
import com.consol.citrus.annotations.CitrusTest;
import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;
import com.consol.citrus.http.client.HttpClient;
import com.consol.citrus.message.MessageType;
public class UnSuccessFullLogin extends TestNGCitrusTestDesigner {
#Autowired (required=true)
#Qualifier("todoClient1")
private HttpClient todoClient1;
public Xls_Reader xls=new Xls_Reader(Constants.DATA_XLS_PATH);
String testCaseName="UnSuccessFullLogin";
public String actualResult="";
#CitrusTest
#Test(dataProvider="getData")
public void TestPost(Hashtable<String, String> data) {
echo("i am entered");
variable("Uname", "admin2");
variable("Pwd", "admin");
if(!DataUtil.isTestExecutable(xls, testCaseName) || data.get(Constants.RUNMODE_COL).equals("N")){
throw new SkipException("Skipping the test as Rnumode is N");
}
http()
.client(todoClient1)
.send()
.post("/rest/api/user/login")
.contentType("application/json")
// .payload("{ \"userName\": \"${uN}\", \"password\": \"${pwd}\"}");
.payload("{ \"userName\": \"${Uname}\", \"password\": \"${Pwd}\"}");
http()
.client(todoClient1)
.receive()
.response(HttpStatus.ACCEPTED)
.validate("$.statusCode", "400");
}
#DataProvider
public Object[][] getData()
{
return DataUtil.getData(xls, testCaseName);
}
}
Log Here:
17:37:56,650 DEBUG tListableBeanFactory| Creating shared instance of singleton bean 'todoClient'
17:37:56,650 DEBUG tListableBeanFactory| Creating instance of bean 'todoClient'
17:37:56,651 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'todoClientConfiguration'
17:37:56,675 DEBUG tListableBeanFactory| Eagerly caching bean 'todoClient' to allow for resolving potential circular references
17:37:56,690 DEBUG tListableBeanFactory| Finished creating instance of bean 'todoClient'
17:37:56,690 DEBUG tListableBeanFactory| Creating shared instance of singleton bean 'todoClient1Configuration'
17:37:56,690 DEBUG tListableBeanFactory| Creating instance of bean 'todoClient1Configuration'
17:37:56,691 DEBUG tListableBeanFactory| Eagerly caching bean 'todoClient1Configuration' to allow for resolving potential circular references
17:37:56,697 DEBUG tListableBeanFactory| Finished creating instance of bean 'todoClient1Configuration'
17:37:56,697 DEBUG tListableBeanFactory| Creating shared instance of singleton bean 'todoClient1'
17:37:56,697 DEBUG tListableBeanFactory| Creating instance of bean 'todoClient1'
17:37:56,697 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'todoClient1Configuration'
17:37:56,699 DEBUG tListableBeanFactory| Eagerly caching bean 'todoClient1' to allow for resolving potential circular references
17:37:56,699 DEBUG tListableBeanFactory| Finished creating instance of bean 'todoClient1'
17:37:56,699 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'globalVariables'
17:37:56,699 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'com.consol.citrus.report.MessageTracingTestListener#1'
17:37:56,700 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
17:37:56,851 DEBUG icApplicationContext| Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor#655a5d9c]
17:37:56,852 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'lifecycleProcessor'
17:37:56,856 DEBUG rcesPropertyResolver| Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
17:37:56,866 DEBUG ontextLoaderDelegate| Storing ApplicationContext in cache under key [[MergedContextConfiguration#7bd7d6d6 testClass = UnSuccessFullLogin, locations = '{}', classes = '{class com.consol.citrus.config.CitrusSpringConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
17:37:56,866 DEBUG context.cache| Spring test ApplicationContext cache statistics: [DefaultContextCache#1a6f2363 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 0, missCount = 1]
17:37:56,939 DEBUG on.InjectionMetadata| Processing injected element of bean 'com.consol.citrus.integration.Demo.UnSuccessFullLogin': AutowiredFieldElement for private com.consol.citrus.http.client.HttpClient com.consol.citrus.integration.Demo.UnSuccessFullLogin.todoClient1
17:37:56,942 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'todoClient1'
17:37:56,942 DEBUG ionBeanPostProcessor| Autowiring by type from bean name 'com.consol.citrus.integration.Demo.UnSuccessFullLogin' to bean named 'todoClient1'
17:37:56,947 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'testSuiteListeners'
17:37:56,947 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'testContextFactory'
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus - ------------------------------------------------------------------------
5876 [main] INFO com.consol.citrus.Citrus - .__ __
5876 [main] INFO com.consol.citrus.Citrus - ____ |__|/ |________ __ __ ______
5876 [main] INFO com.consol.citrus.Citrus - _/ ___\| \ __\_ __ \ | \/ ___/
5876 [main] INFO com.consol.citrus.Citrus - \ \___| || | | | \/ | /\___ \
5876 [main] INFO com.consol.citrus.Citrus - \___ >__||__| |__| |____//____ >
5876 [main] INFO com.consol.citrus.Citrus - \/ \/
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus - C I T R U S T E S T S 2.7.2
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus - ------------------------------------------------------------------------
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus - BEFORE TEST SUITE: SUCCESS
5876 [main] INFO com.consol.citrus.Citrus - ------------------------------------------------------------------------
5876 [main] INFO com.consol.citrus.Citrus -
17:37:56,974 DEBUG estExecutionListener| Before test class: context [DefaultTestContext#740fb309 testClass = UnSuccessFullLogin, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#7bd7d6d6 testClass = UnSuccessFullLogin, locations = '{}', classes = '{class com.consol.citrus.config.CitrusSpringConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null].
17:37:56,975 DEBUG estExecutionListener| Performing dependency injection for test context [[DefaultTestContext#740fb309 testClass = UnSuccessFullLogin, testInstance = com.consol.citrus.integration.Demo.UnSuccessFullLogin#5524cca1, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#7bd7d6d6 testClass = UnSuccessFullLogin, locations = '{}', classes = '{class com.consol.citrus.config.CitrusSpringConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]].
17:37:56,975 DEBUG ontextLoaderDelegate| Retrieved ApplicationContext from cache with key [[MergedContextConfiguration#7bd7d6d6 testClass = UnSuccessFullLogin, locations = '{}', classes = '{class com.consol.citrus.config.CitrusSpringConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
17:37:56,975 DEBUG context.cache| Spring test ApplicationContext cache statistics: [DefaultContextCache#1a6f2363 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 1, missCount = 1]
17:37:56,976 DEBUG on.InjectionMetadata| Processing injected element of bean 'com.consol.citrus.integration.Demo.UnSuccessFullLogin': AutowiredFieldElement for private com.consol.citrus.http.client.HttpClient com.consol.citrus.integration.Demo.UnSuccessFullLogin.todoClient1
17:37:56,976 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'todoClient1'

Please see the following working sample how to use TestNG data provider with Citrus:
public class DataProviderJavaIT extends TestNGCitrusTestDesigner {
#CitrusTest
#CitrusParameters( {"message", "delay"} )
#Test(dataProvider = "sampleDataProvider")
public void dataProvider(String message, Long sleep) {
echo(message);
sleep(sleep);
echo("${message}");
echo("${delay}");
}
#DataProvider
public Object[][] sampleDataProvider() {
return new Object[][] {
{ "Hello World!", 300L },
{ "Hallo Welt!", 1000L },
{ "Hallo Citrus!", 500L },
};
}
}
According to the sample you are missing the #CitrusParameters annotation that translates data provider arguments to Citrus test variables.

Related

I need to run a test for my spring batch that reads from mongodb

I am new to testing. I have a completed Spring Batch job using mongodb and gradle. I need some help getting started with either a junit test or integration test to ensure my project is working correctly. I have searched through Stack and did not find anything that can help me understand what I am doing. A lot of the codes online does not pertain to my spring batch. Could someone help guide me to fully understand what I need to do to get started or point me in the right direction.
Thank you
here is a code i found, does not work, is there another way I can make this run?
#RunWith(SpringRunner.class)
#Configuration
#ComponentScan(basePackages = { "com." })
public class BatchTest {
#Autowired
private PaymentPortalRepository repository;
#Autowired
private MongoTemplate mongoTemplate;
#Test
public void testSaveAndFindRxBusiness() throws Exception {
PaymentAudit paymentAudit = new PaymentAudit(null, "1", false,
"RETAIL", null, null, 0, 0, 0, null, null, null, null, null, null, null,
null, null, null, null, 0, null, 0, null, null);
repository.save(paymentAudit);
PaymentAudit paymentAudit2 = new PaymentAudit(null, "2", false,
"RETAIL", null, null, 0, 0, 0, null, null, null, null, null, null, null,
null,
null, null, null, 0, null, 0, null, null);
repository.save(paymentAudit2);
assertEquals(paymentAudit, repository.findByRxBusiness("1"));
assertEquals(paymentAudit2, repository.findByRxBusiness("2"));
assertNull(repository.findByRxBusiness("3"));
}
}
ERROR:
14:53:20.862 [main] ERROR org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#60db1c0e] to prepare test instance [com..ecom.BatchTest#e25951c]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com..ecom.BatchTest': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com..ecom.spring_batchjob.repository.PaymentPortalRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:399)
at
org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ecom.spring_batchjob.repository.PaymentPortalRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
... 28 common frames omitted
14:53:20.871 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - After test class: context [DefaultTestContext#81d9a72 testClass = BatchTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#747f281 testClass = BatchTest, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#10feca44, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#1e683a3e, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#14555e0a, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with #DirtiesContext [false] with mode [null].
14:53:20.874 [Thread-0] INFO org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext#4f4c4b1a: startup date [Tue Jan 08 14:53:20 CST 2019]; root of context hierarchy
14:53:20.874 [Thread-0] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
14:53:20.876 [Thread-0] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#1ab06251: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,org.springframework.boot.test.mock.mockito.MockitoPostProcessor$SpyPostProcessor,org.springframework.boot.test.mock.mockito.Moc
kitoPostProcessor]; root of factory hierarchy
You are autowiring a bean of type PaymentPortalRepository in your test class but no beans of this type are found in your test context. Hence the error.
The problem is that your test class does not load any Spring application context. You need to add #ContextConfiguration and specify which Spring application context you want to load for this test (use the classes attribute if you use Java configuration and locations attribute if you use XML configuration). This application context should contain a bean of type PaymentPortalRepository and other beans used in your test.
Moreover, the #Configuration annotation means the annotated class is a source of bean definitions. This is not the case in your test so you can remove it.
You can find examples of how to test Spring Batch jobs here: https://docs.spring.io/spring-batch/4.1.x/reference/html/testing.html#endToEndTesting

How to overcome Scalatra initialization issue: NoSuchMethodError: javax.servlet.ServletContext.getFilterRegistration?

This is my first time using Scalatra, and I'm using it outside of SBT (building and running using mill). I get the following error which seems to be about a missing dependency.
2018.05.23 18:26:30 [main] INFO org.scalatra.servlet.ScalatraListener - The cycle class name from the config: ScalatraBootstrap
2018.05.23 18:26:30 [main] INFO org.scalatra.servlet.ScalatraListener - Initializing life cycle class: ScalatraBootstrap
2018.05.23 18:26:30 [main] ERROR org.scalatra.servlet.ScalatraListener - Failed to initialize scalatra application at
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getFilterRegistration(Ljava/lang/String;)Ljavax/servlet/FilterRegistration;
at org.scalatra.servlet.RichServletContext.mountFilter(RichServletContext.scala:162)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:85)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:93)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:90)
at ScalatraBootstrap.init(ScalatraBootstrap.scala:8)
at org.scalatra.servlet.ScalatraListener.configureCycleClass(ScalatraListener.scala:66)
at org.scalatra.servlet.ScalatraListener.contextInitialized(ScalatraListener.scala:22)
at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:890)
at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:558)
at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:853)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:370)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1497)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1459)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:785)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:287)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:545)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:138)
at org.eclipse.jetty.server.Server.start(Server.java:419)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:108)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
at org.eclipse.jetty.server.Server.doStart(Server.java:386)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at com.example.JettyLauncher$.main(JettyLauncher.scala:20)
at com.example.JettyLauncher.main(JettyLauncher.scala)
Here are the dependencies I'm using:
val jettyVersion = "9.4.10.v20180503"
def ivyDeps = Agg(
ivy"org.scalatra::scalatra:2.6.3",
ivy"javax.servlet:servlet-api:2.5",
ivy"org.eclipse.jetty:jetty-server:$jettyVersion",
ivy"org.eclipse.jetty:jetty-servlet:$jettyVersion",
ivy"org.eclipse.jetty:jetty-webapp:$jettyVersion",
)
My JettyLauncher is a striaght copy from the web site, so far, except I changed the resourceBase to be something that actually exists (but it didn't help):
object JettyLauncher { // this is my entry object as specified in sbt project definition
def main(args: Array[String]) {
val port = if(System.getenv("PORT") != null) System.getenv("PORT").toInt else 5001
val server = new Server(port)
val context = new WebAppContext()
context setContextPath "/"
context.setResourceBase("repeater")
context.addEventListener(new ScalatraListener)
context.addServlet(classOf[DefaultServlet], "/")
server.setHandler(context)
server.start
server.join
}
}
My LifeCycle class is also fairly minimal:
class ScalatraBootstrap extends LifeCycle {
override def init(context: ServletContext) {
context mount (new RepeatAll, "/*")
}
}
UPDATE
I changed to using ScalatraServlet instead of ScalatraServlet, but get a similar issue:
2018.05.23 18:39:24 [main] ERROR org.scalatra.servlet.ScalatraListener - Failed to initialize scalatra application at
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getServletRegistration(Ljava/lang/String;)Ljavax/servlet/ServletRegistration;
at org.scalatra.servlet.RichServletContext.mountServlet(RichServletContext.scala:127)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:84)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:93)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:90)
at ScalatraBootstrap.init(ScalatraBootstrap.scala:8)
Update 2
Another important part of the stacktrace I missed posting earlier:
2018.05.23 18:39:24 [main] WARN org.eclipse.jetty.webapp.WebAppContext - Failed startup of context o.e.j.w.WebAppContext#3d74bf60{/,file:///home/brandon/workspace/sbh/repeater,UNAVAILABLE}
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getServletRegistration(Ljava/lang/String;)Ljavax/servlet/ServletRegistration;
at org.scalatra.servlet.RichServletContext.mountServlet(RichServletContext.scala:127)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:84)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:93)
I tried putting a WEB-INF/web.xml under repeater as specified above, but same result.

Connection not releasing for StoredProcedureQuery without #Transactional

I have the following service which simply logs an error message to the database. When I do not have #Transactional on the method, the connection stays active until all the connections are used up. All the StoredProcedureQuery calls that return a result do not have this problem.
Why do I need to mark the method as #Transactional to have it release the connection?
#Service
public class SSOErrorLogServiceImpl implements SSOErrorLogService {
#PersistenceContext
private EntityManager em;
#Override
#Transactional
public void logError(String errorMessage, String request){
StoredProcedureQuery proc = em.createNamedStoredProcedureQuery("dbo.spSSOLogError");
proc.setParameter("errorMessage", errorMessage);
proc.setParameter("request", request);
proc.execute();
}
}
DataConfig
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory
= new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(reflexDataSource());
entityManagerFactory.setPackagesToScan("com.company.platform.jpa");
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
Properties additionalProperties = new Properties();
additionalProperties.put("eclipselink.weaving", "false");
entityManagerFactory.setJpaProperties(additionalProperties);
return entityManagerFactory;
}
#Bean
public HikariDataSource reflexDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setLeakDetectionThreshold(20000);
dataSource.setMaximumPoolSize(20);
dataSource.setConnectionTimeout(5000);
dataSource.setRegisterMbeans(false);
dataSource.setInitializationFailFast(false);
dataSource.setDriverClassName(driver);
dataSource.setJdbcUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
Logs without transaction (excerpt)
[EL Finer]: connection: 2016-09-30 14:33:16.955--ServerSession(317574415)--Thread(Thread[Test worker,5,main])--client acquired: 1151058631
[EL Finer]: transaction: 2016-09-30 14:33:16.962--ClientSession(1151058631)--Thread(Thread[Test worker,5,main])--acquire unit of work: 544160013
[EL Finest]: query: 2016-09-30 14:33:16.962--UnitOfWork(544160013)--Thread(Thread[Test worker,5,main])--Execute query ResultSetMappingQuery(name="dbo.spSSOLogError" )
[EL Finest]: connection: 2016-09-30 14:33:16.963--ServerSession(317574415)--Connection(1107704332)--Thread(Thread[Test worker,5,main])--Connection acquired from connection pool [read].
[EL Finest]: connection: 2016-09-30 14:33:16.963--ServerSession(317574415)--Thread(Thread[Test worker,5,main])--reconnecting to external connection pool
[EL Fine]: sql: 2016-09-30 14:33:16.963--ServerSession(317574415)--Connection(539538496)--Thread(Thread[Test worker,5,main])--EXECUTE dbo.spSSOLogError #errorMessage = ?, #request = ?
bind => [Message, Request]
2016-09-30 14:33:16,984 | TRACE | org.springframework.test.context.TestContextManager:394 - afterTestMethod(): instance [com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest#314c32e8], method [public void com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest.test_logError()], exception [null]
2016-09-30 14:33:16,985 | DEBUG | org.springframework.test.context.support.DirtiesContextTestExecutionListener:94 - After test method: context [DefaultTestContext#6cce3af3 testClass = SSOErrorLogServiceTest, testInstance = com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest#314c32e8, testMethod = test_logError#SSOErrorLogServiceTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#37770c96 testClass = SSOErrorLogServiceTest, locations = '{}', classes = '{class com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest$Config}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class dirties context [false], class mode [null], method dirties context [false].
2016-09-30 14:33:16,985 | TRACE | org.springframework.test.context.TestContextManager:437 - afterTestClass(): class [class com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest]
2016-09-30 14:33:16,986 | DEBUG | org.springframework.test.context.support.DirtiesContextTestExecutionListener:126 - After test class: context [DefaultTestContext#6cce3af3 testClass = SSOErrorLogServiceTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#37770c96 testClass = SSOErrorLogServiceTest, locations = '{}', classes = '{class com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest$Config}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], dirtiesContext [false].
Logs with #Transaction
[EL Finer]: transaction: 2016-09-30 14:30:50.747--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--begin unit of work flush
[EL Finer]: transaction: 2016-09-30 14:30:50.747--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--end unit of work flush
[EL Finest]: query: 2016-09-30 14:30:50.747--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--Execute query ResultSetMappingQuery(name="dbo.spSSOLogError" )
[EL Finest]: connection: 2016-09-30 14:30:50.748--ServerSession(1432568628)--Connection(708660831)--Thread(Thread[Test worker,5,main])--Connection acquired from connection pool [default].
[EL Finer]: transaction: 2016-09-30 14:30:50.748--ClientSession(287210054)--Connection(708660831)--Thread(Thread[Test worker,5,main])--begin transaction
[EL Finest]: connection: 2016-09-30 14:30:50.748--ClientSession(287210054)--Thread(Thread[Test worker,5,main])--reconnecting to external connection pool
[EL Fine]: sql: 2016-09-30 14:30:50.75--ClientSession(287210054)--Connection(29007067)--Thread(Thread[Test worker,5,main])--EXECUTE dbo.spSSOLogError #errorMessage = ?, #request = ?
bind => [Message, Request]
2016-09-30 14:30:50,772 | TRACE | org.springframework.transaction.interceptor.TransactionAspectSupport:519 - Completing transaction for [com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceImpl.logError]
2016-09-30 14:30:50,772 | TRACE | org.springframework.transaction.support.AbstractPlatformTransactionManager:926 - Triggering beforeCommit synchronization
2016-09-30 14:30:50,772 | TRACE | org.springframework.transaction.support.AbstractPlatformTransactionManager:939 - Triggering beforeCompletion synchronization
2016-09-30 14:30:50,772 | DEBUG | org.springframework.transaction.support.AbstractPlatformTransactionManager:755 - Initiating transaction commit
2016-09-30 14:30:50,773 | DEBUG | org.springframework.orm.jpa.JpaTransactionManager:512 - Committing JPA transaction on EntityManager [org.eclipse.persistence.internal.jpa.EntityManagerImpl#8f90fd5]
[EL Finer]: transaction: 2016-09-30 14:30:50.773--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--begin unit of work commit
[EL Finer]: transaction: 2016-09-30 14:30:50.773--ClientSession(287210054)--Connection(29007067)--Thread(Thread[Test worker,5,main])--commit transaction
[EL Finest]: connection: 2016-09-30 14:30:50.775--ServerSession(1432568628)--Connection(708660831)--Thread(Thread[Test worker,5,main])--Connection released to connection pool [default].
[EL Finer]: transaction: 2016-09-30 14:30:50.775--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--end unit of work commit
[EL Finer]: transaction: 2016-09-30 14:30:50.775--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--resume unit of work
2016-09-30 14:30:50,775 | TRACE | org.springframework.transaction.support.AbstractPlatformTransactionManager:952 - Triggering afterCommit synchronization
2016-09-30 14:30:50,775 | TRACE | org.springframework.transaction.support.AbstractPlatformTransactionManager:968 - Triggering afterCompletion synchronization
2016-09-30 14:30:50,775 | TRACE | org.springframework.transaction.support.TransactionSynchronizationManager:331 - Clearing transaction synchronization
2016-09-30 14:30:50,776 | TRACE | org.springframework.transaction.support.TransactionSynchronizationManager:243 - Removed value [org.springframework.orm.jpa.EntityManagerHolder#4569d6c9] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean#33d8b566] from thread [Test worker]
2016-09-30 14:30:50,776 | TRACE | org.springframework.transaction.support.TransactionSynchronizationManager:243 - Removed value [org.springframework.jdbc.datasource.ConnectionHolder#53d1206a] for key [JDBC URL = jdbc:sqlserver://somehost:1433;databaseName=Database, Username = test, partitions = 1, max (per partition) = 10, min (per partition) = 0, idle max age = 60 min, idle test period = 240 min, strategy = DEFAULT] from thread [Test worker]
2016-09-30 14:30:50,776 | DEBUG | org.springframework.orm.jpa.JpaTransactionManager:600 - Closing JPA EntityManager [org.eclipse.persistence.internal.jpa.EntityManagerImpl#8f90fd5] after transaction
2016-09-30 14:30:50,776 | DEBUG | org.springframework.orm.jpa.EntityManagerFactoryUtils:432 - Closing JPA EntityManager
[EL Finer]: transaction: 2016-09-30 14:30:50.776--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--release unit of work
[EL Finer]: connection: 2016-09-30 14:30:50.776--ClientSession(287210054)--Thread(Thread[Test worker,5,main])--client released
2016-09-30 14:30:50,776 | TRACE | org.springframework.test.context.TestContextManager:394 - afterTestMethod(): instance [com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest#314c32e8], method [public void com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest.test_logError()], exception [null]
2016-09-30 14:30:50,777 | DEBUG | org.springframework.test.context.support.DirtiesContextTestExecutionListener:94 - After test method: context [DefaultTestContext#6cce3af3 testClass = SSOErrorLogServiceTest, testInstance = com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest#314c32e8, testMethod = test_logError#SSOErrorLogServiceTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#37770c96 testClass = SSOErrorLogServiceTest, locations = '{}', classes = '{class com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest$Config}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class dirties context [false], class mode [null], method dirties context [false].
2016-09-30 14:30:50,777 | TRACE | org.springframework.test.context.TestContextManager:437 - afterTestClass(): class [class com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest]
2016-09-30 14:30:50,778 | DEBUG | org.springframework.test.context.support.DirtiesContextTestExecutionListener:126 - After test class: context [DefaultTestContext#6cce3af3 testClass = SSOErrorLogServiceTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#37770c96 testClass = SSOErrorLogServiceTest, locations = '{}', classes = '{class com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest$Config}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], dirtiesContext [false].
Did you try changing #PersistenceContext to #PersistanceUnit?
EntityManagers obtained via #PersistenceContext are Container Managed Entity Manager as the container will be responsible for managing "Entity Manager" while EntityManagers obtained via #PersistenceUnit / entityManagerFactory.createEntityManager() are Application Managed Entity Manager and developer has to manage certain things in code (for e.g. releasing the resources acquired by EntityManager).
Try release the query.
query.unwrap(ProcedureOutputs.class).release();
We were facing the same issue with the execute() call. The connection was not getting closed. Looking at the code made it more clear: execute()
Calling the executeUpdate() solved it.

Swagger + Jersey + Grizzly

I have been trying to generate REST API doc using Swagger.
Followed the link but couldn't make it work. Got below error's
12:54:39.859 [main] INFO org.reflections.Reflections - Reflections took 63 ms to scan 1 urls, producing 73 keys and 122 values
12:54:39.906 [main] DEBUG i.s.jaxrs.ext.SwaggerExtensions - adding extension io.swagger.jersey.SwaggerJersey2Jaxrs#18be6e8
12:54:39.906 [main] DEBUG io.swagger.jaxrs.Reader - picking up response class from method public rest.beans.UserBean rest.frontend.UserResource.opAllocateUser(rest.beans.UserBean,javax.ws.rs.core.Request)
12:54:39.921 [main] DEBUG i.s.c.ModelConverterContextImpl - resolveProperty class rest.beans.UserBean
12:54:39.921 [main] DEBUG io.swagger.jackson.ModelResolver - resolveProperty [simple type, class rest.beans.UserBean]
12:54:39.921 [main] DEBUG i.s.c.ModelConverterContextImpl - resolve [simple type, class rest.beans.UserBean]
12:54:39.921 [main] DEBUG i.s.c.ModelConverterContextImpl - trying extension io.swagger.jackson.ModelResolver#5ecce3
12:54:39.921 [main] DEBUG io.swagger.jackson.ModelResolver - Can't check class [simple type, class rest.beans.UserBean], rest.beans.UserBean
12:54:39.937 [main] DEBUG i.s.c.ModelConverterContextImpl - defineModel UserBean io.swagger.models.ModelImpl#c2b00fee
12:54:39.937 [main] DEBUG i.s.c.ModelConverterContextImpl - resolveProperty [simple type, class java.lang.String]
12:54:39.937 [main] DEBUG io.swagger.jackson.ModelResolver - Can't check class [simple type, class java.lang.String], java.lang.String
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG i.s.c.ModelConverterContextImpl - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - Can't check class [simple type, class java.lang.String], java.lang.String
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG io.swagger.converter.ModelConverters - ModelConverters readAll from class rest.beans.UserBean
12:54:39.952 [main] DEBUG i.s.c.ModelConverterContextImpl - resolve class rest.beans.UserBean
12:54:39.952 [main] DEBUG i.s.c.ModelConverterContextImpl - trying extension io.swagger.jackson.ModelResolver#5ecce3
12:54:39.952 [main] DEBUG i.s.c.ModelConverterContextImpl - defineModel UserBean io.swagger.models.ModelImpl#c2b00fee
12:54:39.952 [main] DEBUG i.s.c.ModelConverterContextImpl - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - Can't check class [simple type, class java.lang.String], java.lang.String
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG i.s.c.ModelConverterContextImpl - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - Can't check class [simple type, class java.lang.String], java.lang.String
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG io.swagger.jaxrs.Reader - getParameters for [simple type, class rest.beans.UserBean]
12:54:39.952 [main] DEBUG io.swagger.jaxrs.Reader - trying extension io.swagger.jersey.SwaggerJersey2Jaxrs#18be6e8
Next searched and found link closest to my issue. Again followed it but still getting the above error. I can't see swagger.json getting generated.
Versions info
Jersey : 2.22.1
Jackson : 2.6.3
Swagger : 1.5.6
Grizzly : 2.3.23
Am I missing some configuration which is needed to make it work? Or Do I need more libraries?
Thanks
Statement : Generate Swagger UI for the listing of all the REST APIs through Grizzly and Jersey Application.
1. Add following dependency in pom.xml –
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jersey2-jaxrs</artifactId>
<version>1.5.9</version>
</dependency>
2. Bundle Swagger UI and docs folder through you main application class using the below code –
package com.main;
import java.io.IOException;
import java.net.URI;
import org.glassfish.grizzly.http.server.CLStaticHttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.ServerConfiguration;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import io.swagger.jaxrs.config.BeanConfig;
public class MainApp {
// Base URI the Grizzly HTTP server will listen on
public static final URI BASE_URI = URI.create(“http://0.0.0.0:8080”);
public static HttpServer getLookupServer() {
String resources = “com.main”;
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion(“1.0.1”);
beanConfig.setSchemes(new String[] { “http” });
beanConfig.setBasePath(“”);
beanConfig.setResourcePackage(resources);
beanConfig.setScan(true);
final ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.packages(resources);
resourceConfig.register(io.swagger.jaxrs.listing.ApiListingResource.class);
resourceConfig.register(io.swagger.jaxrs.listing.SwaggerSerializers.class);
resourceConfig.register(JacksonFeature.class);
resourceConfig.register(JacksonJsonProvider.class);
return GrizzlyHttpServerFactory.createHttpServer(BASE_URI, resourceConfig);
}
public static void main(String[] args) throws IOException {
final HttpServer server = getLookupServer();
server.start();
ClassLoader loader = MainApp.class.getClassLoader();
CLStaticHttpHandler docsHandler = new CLStaticHttpHandler(loader, “swagger-ui/”);
docsHandler.setFileCacheEnabled(false);
ServerConfiguration cfg = server.getServerConfiguration();
cfg.addHttpHandler(docsHandler, “/docs/”);
}
}
3. Take the latest code of swagger-ui. Copy all the content of the dist folder and create a folder named swagger-ui inside src/main/resources and paste all the copied contents. Now change the url in index.file which is inside the copied folder like below –
url: http://0.0.0.0:8080/swagger.json
4. Lastly, annotate your controller with #Api and #ApiOperation.
Hope it works. Now to run your Grizzly Jersey Application, go to browser and type localhost:8080/docs/. You will see Swagger UI having all the details of your REST APIs.
Happy coding and sharing as well. 🙂 You can find the [git](https://guptakumartanuj.wordpress.com/2017/07/24/generate-swagger-ui-through-grizzly-and-jersey-application/) repo for the above implementation.

Problems connecting to Postgres from Grails

I have verified that I can connect to the postgres database using a Java test program. I have also verified that I can connect using a little Grails testDB project. But when I try to run my larger project, which the same BuildConfig.groovy, it fails.
I've tried different jdbc versions (e.g., 4 rather than 41) in the postgres jar, but it didn't help.
I've been searching stackoverflow and anything else I can find to no avail (e.g., "help me stackoverflow, your my only hope").
My BuildConfig.groovy file is shown below:
grails.servlet.version = "3.0" // Change depending on target container compliance (2.5 or 3.0)
grails.project.class.dir = "target/classes"
grails.project.test.class.dir = "target/test-classes"
grails.project.test.reports.dir = "target/test-reports"
grails.project.work.dir = "target/work"
grails.project.target.level = 1.6
grails.project.source.level = 1.6
//grails.project.war.file = "target/${appName}-${appVersion}.war"
grails.project.fork = [
// configure settings for compilation JVM, note that if you alter the Groovy version forked compilation is required
// compile: [maxMemory: 256, minMemory: 64, debug: false, maxPerm: 256, daemon:true],
// configure settings for the test-app JVM, uses the daemon by default
test: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, daemon:true],
// configure settings for the run-app JVM
run: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
// configure settings for the run-war JVM
war: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
// configure settings for the Console UI JVM
console: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256]
]
grails.project.dependency.resolver = "maven" // or ivy
grails.project.dependency.resolution = {
// inherit Grails' default dependencies
inherits("global") {
// specify dependency exclusions here; for example, uncomment this to disable ehcache:
// excludes 'ehcache'
}
log "error" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
checksums true // Whether to verify checksums on resolve
legacyResolve false // whether to do a secondary resolve on plugin installation, not advised and here for backwards compatibility
repositories {
inherits true // Whether to inherit repository definitions from plugins
grailsPlugins()
grailsHome()
mavenLocal()
grailsCentral()
mavenCentral()
// uncomment these (or add new ones) to enable remote dependency resolution from public Maven repositories
//mavenRepo "http://repository.codehaus.org"
//mavenRepo "http://download.java.net/maven/2/"
//mavenRepo "http://repository.jboss.com/maven2/"
}
dependencies {
// specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes e.g.
// runtime 'mysql:mysql-connector-java:5.1.29'
compile 'org.postgresql:postgresql:9.3-1101-jdbc41'
runtime 'org.postgresql:postgresql:9.3-1101-jdbc41'
test "org.grails:grails-datastore-test-support:1.0-grails-2.4"
}
plugins {
// plugins for the build system only
build ":tomcat:7.0.55"
// plugins for the compile step
compile ":scaffolding:2.1.2"
compile ':cache:1.1.7'
compile ":asset-pipeline:1.9.6"
compile ":twitter-bootstrap:3.2.1"
// compile ":jquery-dialog:2.0.3"
// plugins needed at runtime but not for compilation
runtime ":hibernate4:4.3.5.5" // or ":hibernate:3.6.10.15"
runtime ":database-migration:1.4.0"
runtime ":jquery:1.11.1"
runtime ":twitter-bootstrap:3.2.1"
}
}
My DataSource.groovy file contains
dataSource {
pooled = true
jmxExport = true
url = "jdbc:postgresql://150.18.178.9:5432/myDB"
driverClassName = "org.postgresql.Driver"
dbCreate = "update"
username = "user"
password = "password"
dialect = net.sf.hibernate.dialect.PostgreSQLDialect
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
// cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' // Hibernate 3
cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
singleSession = true // configure OSIV singleSession mode
}
// environment specific settings
environments {
development {
dataSource { // database dev
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
url="jdbc:postgresql://150.18.178.9:5432/dev"
username = "user"
password = "password"
}
}
test {
dataSource {
dbCreate = "update"
url="jdbc:postgresql://150.18.178.9:5432/test"
username = "user"
password = "password"
}
}
production {
dataSource {
dbCreate = "update"
url="jdbc:postgresql://150.18.178.9:5432/myDB"
username = "user"
password = "password"
properties {
// See http://grails.org/doc/latest/guide/conf.html#dataSource for documentation
jmxEnabled = true
initialSize = 5
maxActive = 50
minIdle = 5
maxIdle = 25
maxWait = 10000
maxAge = 10 * 60000
timeBetweenEvictionRunsMillis = 5000
minEvictableIdleTimeMillis = 60000
validationQuery = "SELECT 1"
validationQueryTimeout = 3
validationInterval = 15000
testOnBorrow = true
testWhileIdle = true
testOnReturn = false
jdbcInterceptors = "ConnectionState"
defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
}
}
}
}
When I try to run my application I get:
/usr/java/latest/bin/java -Dgrails.home=/home/iank/software/grails/latest -Dbase.dir=/home/iank/IdeaProjects/nderground -Dtools.jar=/usr/java/latest/lib/tools.jar -Dgroovy.starter.conf=/home/iank/software/grails/latest/conf/groovy-starter.conf -Xmx768M -Xms768M -XX:MaxPermSize=256m -XX:PermSize=256m -javaagent:/home/iank/software/grails/latest/lib/org.springframework/springloaded/jars/springloaded-1.2.0.RELEASE.jar -noverify -Dspringloaded=profile=grails -Didea.launcher.port=7535 -Didea.launcher.bin.path=/home/iank/software/idea-IU-135.909/bin -Dfile.encoding=UTF-8 -classpath /home/iank/software/grails/latest/lib/org.codehaus.groovy/groovy-all/jars/groovy-all-2.3.6.jar:/home/iank/software/grails/latest/dist/grails-bootstrap-2.4.3.jar:/home/iank/software/idea-IU-135.909/lib/idea_rt.jar com.intellij.rt.execution.application.AppMain org.codehaus.groovy.grails.cli.support.GrailsStarter --main org.codehaus.groovy.grails.cli.GrailsScriptRunner --conf /home/iank/software/grails/latest/conf/groovy-starter.conf "run-app -plain-output"
|Loading Grails 2.4.3
|Configuring classpath
.
|Environment set to development
.................................
|Packaging Grails application
...........
|Compiling 1 source files
............................
|Running Grails application
| Error 2014-09-27 17:16:38,021 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error initializing the application: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
Message: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
Line | Method
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by IllegalArgumentException: object is not an instance of declaring class
->> 22 | doCall in nderground.User$__clinit__closure1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 262 | run in java.util.concurrent.FutureTask
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . in java.lang.Thread
Error |
Forked Grails VM exited with error
|Server running. Browse to http://localhost:8080/nderground
Process finished with exit code 1
Any help would be deeply appreciated. My progress has completely stalled and I'm not sure what to do other than to try rebuilding the project piece by piece.
Many thanks...
By creating a Grails project that worked and slowly adding code I was able to find the problem. I had an improperly specified constraint.
class User {
String handle
String emailAddr
String salt
String password
boolean isAdmin
String toString()
{
String rslt = "$handle"
return rslt
}
static constraints = {
handle blank : false, nullable : false, unique : true
emailAddr blank : false, nullable : false, unique : true, email : true
salt blank: false, nullable: false
password blank: false, nullable: false
isAdmin false <<======= This is the problem!
}
static mapping = {
table 'users'
handle index : 'handle_Ix'
emailAddr index: 'email_ix'
isAdmin defaultValue: false
}
}
This should have been in the static mapping section:
static mapping = {
table 'users'
handle index : 'handle_Ix'
emailAddr index: 'email_ix'
isAdmin defaultValue: false <<== This is the right way to set the default
}
To put it mildly, its annoying that the error shows up as a thread creation error, without any other indication of other errors.
As #EElke points out in the comments, there's no indication at all that Postgres is the problem; the error that you should be looking at says Error creating bean with name 'sessionFactory' ... object is not an instance of declaring class.
My guess is that net.sf.hibernate.dialect.PostgreSQLDialect is the problem - replace that with org.hibernate.dialect.PostgreSQLDialect.
Also, delete this:
runtime 'org.postgresql:postgresql:9.3-1101-jdbc41'
since you already have
compile 'org.postgresql:postgresql:9.3-1101-jdbc41'
and runtime scope includes dependencies from compile scope.