Can't commit JPA transaction - RollbackException: Transaction marked as rollbackOnly - java

first I want to say that I have seen all the topics here on stackoverflow for my case but wasn't able to solve my problem anyway.
I need to run scheduled task every night to check weather the task was finished or not - I'm doing like this:
#Service
#Transactional
public class CronBackGroundProcess {
#Autowired
private CronJobService cronJobService;
#Scheduled(cron = "15 01 01 ? * *")
public void StartNightJob() {
CronJobLog log = new CronJobLog();
int count = 0;
try {
log.setStartTime(new Date());
log.setStatus("Entered StartNightJob Function");
cronJobService.saveCronJobLog(log);
List<Task> Tasks = cronJobService.getActive_AND_InArreasTasks();
log.setStatus("Grabbed List of tasks to Check");
cronJobService.saveCronJobLog(log);
for (Task Task : Tasks) {
cronJobService.StartNightJobProcess(Task, true);
count++;
}
} catch (Exception e) {
CronJobLog log2 = new CronJobLog();
log2.setStatus("Error Occurred " + new Date().toString() + e.getMessage());
cronJobService.saveCronJobLog(log2);
}
log.setLoansChecked(count);
log.setStatus("Finished");
log.setEndDate(new Date());
cronJobService.saveCronJobLog(log);
}
}
CronJobService itself is #Transactional and autowires several #Transactional services
#Service
#Transactional
public class CronJobService {
#Autowired
private ProductService productService;
#Autowired
private RepaymentService repaymentService;
#Autowired
private CronJobLogDAO cronJobLogDAO;
#Autowired
private TransferService transferService;
public String StartNightJobProcess(Account account, boolean makeTransfers) {
do something....
}
}
}
the process goes without errors and when all transactions must be committed I receive such error:
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:524) ~[spring-orm-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757) ~[spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726) ~[spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:478) ~[spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:272) ~[spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) ~[spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:646) ~[spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at ge.shemo.services.core.CronBackGroundProcess$$EnhancerByCGLIB$$30cdcf31.StartNightJob(<generated>) ~[spring-core-4.0.0.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_79]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_79]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_79]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_79]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65) ~[spring-context-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81) [spring-context-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [na:1.7.0_79]
at java.util.concurrent.FutureTask.run(FutureTask.java:262) [na:1.7.0_79]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178) [na:1.7.0_79]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292) [na:1.7.0_79]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_79]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_79]
at java.lang.Thread.run(Thread.java:745) [na:1.7.0_79]
Caused by: javax.persistence.RollbackException: Transaction marked as rollbackOnly
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:58) ~[hibernate-entitymanager-5.0.1.Final.jar:5.0.1.Final]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:515) ~[spring-orm-4.0.0.RELEASE.jar:4.0.0.RELEASE]
... 22 common frames omitted
I can't figure out why.
Also If I launch same function from #Controller it works fine
#Controller
#RequestMapping("/test")
public class test {
#Autowired
private ClientService clientService;
#Autowired
private CronBackGroundProcess cronBackGroundProcess;
#RequestMapping(value = "/test")
#ResponseBody
public void test() throws Exception {
try {
cronBackGroundProcess.StartNightJob();
} catch (Exception e) {
String s = "sd";
}
}
}
So my question is why this function works from controller - commits everything as expected and not works from scheduled task(goes through all process without errors)?

If you can then, put a debug break-point in org.springframework.transaction.interceptor.TransactionAspectSupport.completeTra‌​nsactionAfterThrowing(TransactionInfo txInfo, Throwable ex) and then see what the actual exception is.

You not need mark CronBackGroundProcess as #Transactional because in StartNightJob() method you not have access to db all access to DB as I guess you execute in CronJobService.
So remove #Transactional from CronBackGroundProcess and it must help.

Related

Could not find class [de.flapdoodle.embed.process.config.IRuntimeConfig]

After upgrading to embeded MongoDB with version 3.0.0, I am getting the following exception.
I am using the following in build.gradle.
testImplementation group: 'de.flapdoodle.embed', name: 'de.flapdoodle.embed.mongo', version: '3.0.0'
The exception is given below.
Caused by: java.lang.ClassNotFoundException: de.flapdoodle.embed.process.config.IRuntimeConfig
at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[na:1.8.0_261]
at java.lang.ClassLoader.loadClass(ClassLoader.java:418) ~[na:1.8.0_261]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355) ~[na:1.8.0_261]
at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[na:1.8.0_261]
at java.lang.Class.forName0(Native Method) ~[na:1.8.0_261]
at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_261]
at org.springframework.util.ClassUtils.forName(ClassUtils.java:284) ~[spring-core-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.util.ClassUtils.resolveClassName(ClassUtils.java:324) ~[spring-core-5.2.10.RELEASE.jar:5.2.10.RELEASE]
I provide below the code. I want to use embeded mongoDB for the MongoDB transaction feature in the integration test in spring boot.
#Profile("test")
#ActiveProfiles("test")
public class TestMongoConfig1 implements InitializingBean, DisposableBean {
MongodForTestsFactory factory = null;
MongodConfig mongodConfig = MongodConfig.builder().version(Version.Main.PRODUCTION).build();
MongodStarter runtime = MongodStarter.getDefaultInstance();
MongodExecutable mongodExecutable = null;
MongodProcess mongod = null;
#Override
public void destroy() throws Exception {
mongodExecutable.stop();
}
#Override
public void afterPropertiesSet() throws Exception {
mongodExecutable = runtime.prepare(mongodConfig);
mongod = mongodExecutable.start();
}
#Bean(name = "test1")
public MongoClient mongoClient() {
MongoClient mongoClient = MongoClients.create();
System.out.println("============================================");
System.out.println(mongoClient);
System.out.println("============================================");
return mongoClient;
}
}
First you have to use the following dependencies in build.gradle apart from other dependencies if you are using #DataMongoTest.
implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
testImplementation("de.flapdoodle.embed:de.flapdoodle.embed.mongo")
To test with embeded MongoDB, you have to use the following snippet which may work.
#Profile("test")
#ActiveProfiles("test")
#Configuration
public class TestMongoConfig1 implements InitializingBean, DisposableBean {
private MongodExecutable executable;
#Override
public void afterPropertiesSet() throws Exception {
IFeatureAwareVersion version = Versions.withFeatures(new GenericVersion("4.0.0"),
Version.Main.PRODUCTION.getFeatures());
IMongoCmdOptions cmdOptions = new
MongoCmdOptionsBuilder().useNoPrealloc(false).useSmallFiles(false)
.master(false).verbose(false).useNoJournal(false).syncDelay(0).build();
int port = Network.getFreeServerPort();
IMongodConfig mongodConfig = new MongodConfigBuilder().version(version)
.net(new Net(port, Network.localhostIsIPv6())).replication(new Storage(null, "testRepSet", 5000))
.configServer(false).cmdOptions(cmdOptions).build();
MongodStarter starter = MongodStarter.getDefaultInstance();
executable = starter.prepare(mongodConfig);
executable.start();
}

How to make SlingHttpServletRequest.getParts() return the proper value in JUnit Test?

I am facing some difficulties in writing junit test to pass the for loop condition to getParts() method from SlingHttpServletRequest.getParts(). There is no problem with the implementation, I am able to process the file attachment properly. However, I am unable to do so in the junit test.
The following is my implementation:
#Model(adaptables = SlingHttpServletRequest.class)
public class Comment {
//Variables declaration
#Inject
private CommentService service;
#PostConstruct
public void setup() {
requestData = new JSONObject();
for (String item : request.getRequestParameterMap().keySet()) {
try {
requestData.put(item, request.getParameter(item));
}
} catch (Exception e) {
Throw error message
}
}
//Upload attachment to server
try {
for (Part part : request.getParts()) { <= The JUnit test stopped at this line and throw the error below
} catch (Exception e) {
Throw error message
}
I have tried using a SlingHttpServletRequestWrapper class to override the getParts method but to no avail.
The following is my junit test:
public class CommentTest {
public final AemContext context = new AemContext();
private CommentService commentService = mock(CommentService.class);
#InjectMocks
private Comment comment;
private static String PATH = "/content/testproject/en/page/sub-page";
#Before
public void setUp() throws Exception {
context.addModelsForPackage("de.com.adsl.sightly.model");
context.load().json("/components/textrte.json", PATH);
context.currentPage(PATH);
}
#Test
public void testSetup() throws IOException, ServletException {
//before
context.request().setParameterMap(getRequestCat1());
context.registerService(CommentService.class, commentService);
Resource resource = context.resourceResolver().getResource(PATH + "/jcr:content/root/responsivegrid/textrte");
assertNotNull(resource);
//when
comment = new CustomRequest(context.request()).adaptTo(Comment.class);
//then
comment.setup();
}
private class CustomRequest extends SlingHttpServletRequestWrapper {
public CustomRequest(SlingHttpServletRequest request) {
super(request);
}
#Override
public Collection<Part> getParts() {
final String mockContent =
"------WebKitFormBoundarycTqA2AimXQHBAJbZ\n" +
"Content-Disposition: form-data; name=\"key\"\n" +
"\n" +
"myvalue1\n" +
"------WebKitFormBoundarycTqA2AimXQHBAJbZ";
final List<Part> parts = MockPart.parseAll(mockContent);
assertNotNull(parts);
return parts;
}
};
}
The following is the error message that I encountered:
14:53:04.918 [main] ERROR de.com.adsl.sightly.model.Comment - Error Message: null
java.lang.UnsupportedOperationException: null
at org.apache.sling.servlethelpers.MockSlingHttpServletRequest.getParts(MockSlingHttpServletRequest.java:882) ~[org.apache.sling.servlet-helpers-1.1.10.jar:?]
at de.com.adsl.sightly.model.Comment.uploadFile(Feedback.java:137) ~[classes/:?]
at de.com.adsl.sightly.model.Comment.setup(Feedback.java:82) [classes/:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_201]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_201]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_201]
at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_201]
at org.apache.sling.models.impl.ModelAdapterFactory.invokePostConstruct(ModelAdapterFactory.java:792) [org.apache.sling.models.impl-1.3.8.jar:?]
at org.apache.sling.models.impl.ModelAdapterFactory.createObject(ModelAdapterFactory.java:607) [org.apache.sling.models.impl-1.3.8.jar:?]
at org.apache.sling.models.impl.ModelAdapterFactory.internalCreateModel(ModelAdapterFactory.java:335) [org.apache.sling.models.impl-1.3.8.jar:?]
at org.apache.sling.models.impl.ModelAdapterFactory.getAdapter(ModelAdapterFactory.java:211) [org.apache.sling.models.impl-1.3.8.jar:?]
...
I have looked up various solutions online such as writing two mockito when statements but has not been successful. I would greatly appreciate any form of help or sharing of knowledge if you have encountered the following issue previously. Thank you!
From the source code of MockSlingServletResquest it always throws that exception as it's not supported yet by the mocked class.
https://github.com/apache/sling-org-apache-sling-servlet-helpers/blob/71ef769e5564cf78e49d6679a3270ba8706ae406/src/main/java/org/apache/sling/servlethelpers/MockSlingHttpServletRequest.java#L953
Maybe you should consider writing a servlet, or another approach.

Java BeanDefinitionStoreException on Spring Boot 2

I'm trying to rewrite an application using Spring Boot 2 (specifically 2.1.5.RELEASE). Previous version used 1.5.7.RELEASE. We are switching database platforms, thus the rewrite. The startup class in both new and old are nearly identical, both attempting to create a bean from another library. It works in 1.5.7, but in 2.1.5, it fails with the following message:
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process
import candidates for configuration class [com.company.consumer.ConsumerRecoveryConfiguration];
nested exception is java.lang.IllegalStateException: Failed to introspect
annotated methods on class com.company.consumer.RecordRecovery
Here's what the startup class looks like in old and new:
Old:
#SpringBootApplication
#ComponentScan(basePackages = {
"com.company.core",
"com.company.something",
"com.company.platform",
"com.company.config"},
excludeFilters = #ComponentScan.Filter(type =
FilterType.REGEX, pattern = "com.company.common.diag.*"))
#Import({SomeClass.class, ConsumerRecoveryConfiguration.class,
ConsumerRetryConfiguration.class})
#PropertySource("classpath:build.properties")
public class SomeApplication {
public static void main(String[] args) {
SpringApplication.run(SomeApplication.class, args);
}
#Bean(name = "someDbTimingLogger")
public TimingLogger getSomeDbTimingLogger() {
return new TimingLogger(LoggerFactory.getLogger("timing.someDb"));
}
#Bean(name = "timingLogger")
public TimingLogger getTimingLogger() {
return new TimingLogger(LoggerFactory.getLogger("timing.consumer"));
}
#Bean(name = "kafkaTimingLogger")
public TimingLogger getKafkaTimingLogger() {
return new TimingLogger(LoggerFactory.getLogger("timing.kafka"));
}
#Bean(name = "parser")
public Parser<GenericMessageModel> getSomeModelParser() {
return new Parser<>(GenericMessageModel.class);
}
}
New:
#SpringBootApplication
#ComponentScan(basePackages = {
"com.company.core",
"com.company.something",
"com.company.platform",
"com.company.config"},
excludeFilters = #ComponentScan.Filter(
type = FilterType.REGEX,
pattern = "com.company.common.diag.*"
))
#Import({ ConsumerRecoveryConfiguration.class,
ConsumerRetryConfiguration.class })
#PropertySource("classpath:build.properties")
public class SomeApplication {
public static void main(String[] args) {
SpringApplication.run(SomeApplication.class, args);
}
#Bean(name = "timingLogger")
public TimingLogger getTimingLogger() { return new TimingLogger(LoggerFactory.getLogger("timing.consumer")); }
#Bean(name = "kafkaTimingLogger")
public TimingLogger getKafkaTimingLogger() { return new TimingLogger(LoggerFactory.getLogger("timing.kafka")); }
#Bean(name = "parser")
public Parser<GenericMessageModel> getSomeModelParser() { return new Parser<>(GenericMessageModel.class, null); }
}
The Kotlin class mentioned in the nested exception is as follows (minus its numerous private methods):
#Component
class RecordRecovery(val producer: KafkaProducer<String, String>, val kafkaProducerSettings: KafkaProducerSettings,
val recoverySettings: RecoverySettings, val objectMapper: ObjectMapper) {
val random = ThreadLocalRandom.current()!!
companion object {
val LOGGER = LoggerFactory.getLogger(RecordRecovery::class.java)
}
fun recoverRecords(records: ConsumerRecords<String, String>, exception: Exception) {
recoverRecords(records.map { it.value() ?: StringUtils.EMPTY }, exception)
}
fun recoverRecords(records: List<Any>, exception: Exception) {
error(metaDataFor(records.count()), LOGGER, "Recovering {} records", records.count())
val filteredRecords = records.map { createRecoveryRecord(it) }
.filter{ it != null }
.map { recordToJson(it) }
.filter { removeNulls(it) }
.mapIndexed { index, it -> toEmergencyDataWrapper(it!!, exception, index) }
.mapNotNull {toJSONStringOrNull(it)}
.map {toProducerRecord(it)}
.map { republish(it) }
.toList()
info(metaDataFor(filteredRecords.count()), LOGGER, "After filtering, recovering {} records", filteredRecords.count())
filteredRecords.map { await(it) }
}
}
And here's the ConsumerRecoveryConfiguration class (also Kotlin) in question:
#Configuration
#Import(KafkaProducerConfig::class, RecoverySettings::class, RecordRecovery::class)
class ConsumerRecoveryConfiguration
The class has no body whatsoever. I'm assuming that importing the other classes causes Spring to basically use those as the body.
I'm still somewhat green when it comes to Spring, so I'm struggling to see why it stopped working when I changed to SB 2. Any suggestions about where I should look or what might help me figure this out?
EDIT:
Here is the full stacktrace as requested:
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.company.consumer.ConsumerRecoveryConfiguration]; nested exception is java.lang.IllegalStateException: Failed to introspect annotated methods on class com.company.consumer.RecordRecovery
at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:596)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:302)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:242)
at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:586)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:302)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:242)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:199)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:167)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:315)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:232)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:275)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:95)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:705)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
at com.company.SomeApplication.main(SomeApplication.java:35)
Caused by: java.lang.IllegalStateException: Failed to introspect annotated methods on class com.company.consumer.RecordRecovery
at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(StandardAnnotationMetadata.java:169)
at org.springframework.context.annotation.ConfigurationClassParser.retrieveBeanMethodMetadata(ConfigurationClassParser.java:392)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:317)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:242)
at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:586)
... 20 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/json/JSONObject
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.getDeclaredMethods(Class.java:1975)
at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(StandardAnnotationMetadata.java:158)
... 24 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.json.JSONObject
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 28 common frames omitted

mocking enum using powerMock

I am trying to mock enum using powerMock but got Field 'fTestClass' was not found in class error when i ran test. I found that the issue is with Junit 4.12 and powermock-module-junit4 1.5.6. so I changed to 1.6.1 now I am getting below error ...
java.lang.ExceptionInInitializerError
at sun.reflect.GeneratedSerializationConstructorAccessor9.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:45)
at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)
at org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:142)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:61)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:109)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:57)
at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:70)
at OrderEventProcessorTest.setUp(OrderEventProcessorTest.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:133)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.NullPointerException
Basically I am trying to mock enum to check the functionality of insert, update, delete operations to cassandra db. the enum gives setups the cassadra db connection. I want to mock it so I don't need to connect to the DB to test my crud functionality. Please let me know if still is there any versioning issues with Junit 4.12 and powermock 1.6.1 . I am using mockito-core 1.10.19 and maven-surefire-plugin 2.19.1
EDITED
ENUM for DB connection
public enum CassProvider {
INSTANCE;
private Map<String,ThreadLocal<PreparedStatement>> psMap;
private String[] hostnames;
private String username;
private String password;
private String keyspace;
private Cluster cluster;
private Session session;
private CassProvider() {
init();
psMap = createPreparedStatements();
}
private void init() {
//get host, port, user , pasword from properties file
cluster = Cluster.builder().addContactPoints(hostnames).withPort(port).withCredentials(username, password).build();
session = cluster.connect(keyspace);
}
private static Map<String,ThreadLocal<PreparedStatement>> createPreparedStatements() {
//code goes for mapping preparedStatements
return psMap;
}
public PreparedStatement getPreparedStatement(String id) {
//logic for preparedStatement
return preparedStatement;
}
public Session getSession() {
return session;
}
}
Code I would like to test for different conditions it executes different prepared statements
if (eventMappingType != null && processEvent) {
.......
BatchStatement batchStatement = new BatchStatement();
PreparedStatement psFieldInsert = CassProvider.INSTANCE.getPreparedStatement("INSERT_ORDERS_FV");
if (eventMappingType.getSimpleFields() != null) {
for (FieldType fieldType : eventMappingType.getSimpleFields().getField()) {
Object value = MVEL.executeExpression(fieldType.getSerializedExpr(), context);
batchStatement.add(psFieldInsert.bind(keyFields.get("orderNumber"),dateStringToDate(eventDateTime), fieldType.getValue(), value != null ? value.toString() : value));
}
}
if (eventType.compareToIgnoreCase("OrderPlaced") == 0) {
//Update the lookup table for given name 2 orders.
if (name != null && name.compareToIgnoreCase("")!=0) {
batchStatement.add(CassProvider.INSTANCE.getPreparedStatement("INSERT_ORDERS_BY_NAME").bind(name, dateStringToDate(eventDateTime), orderNumber));
}
//Update the lookup table for accIds 2 orders; not sure if we need this for now
if (accIds != null && accIds.compareToIgnoreCase("")!=0) {
batchStatement.add(CassProvider.INSTANCE.getPreparedStatement("INSERT_ORDERS_BY_ACCIDS").bind(accIds, dateStringToDate(eventDateTime), orderNumber));
}
if (SAPOrderNumber != null) {
batchStatement.add(CassProvider.INSTANCE.getPreparedStatement("INSERT_SAP_ORDER").bind(SAPOrderNumber, orderNumber));
}
}
CassProvider.INSTANCE.getSession().execute(batchStatement);
}
Not sure how your Cluster.builder() method works but I suggest you make that you configurable, i.e. to open it up for your test class to inject a mocked builder that in the end returns a mocked Cluster that in turn returns a mocked Session...

java.lang.NoClassDefFoundError: Could not initialize class DataLayer.HibernateAdapter

I have modified my Java project(Web service) into Dynamic web module. I'm using Tomcat 7.0.59 as server. While starting server it is getting started without any issues. But once if I tried to access the Web service method then I will end up with the error saying that -"Could not initialize class DataLayer.HibernateAdapter java.lang.NoClassDefFoundError: Could not initialize class DataLayer.HibernateAdapter". Anyone please help me than just marking it a "Duplicate". If code has to be modified, please provide me detail steps. Thanks!!
Console Log:
Mar 10, 2015 2:09:07 PM com.sun.xml.ws.server.sei.EndpointMethodHandler invoke
SEVERE: Could not initialize class DataLayer.HibernateAdapter
java.lang.NoClassDefFoundError: Could not initialize class DataLayer.HibernateAdapter
at DataLayer.DatabaseContext.<init>(DatabaseContext.java:12)
at DataLayer.ConsumerDetails.getConsumerdetails(ConsumerDetail.java:84)
at ManageLayer.Authenticate(AuthenticationManager.java:50)
at ManageLayer.Console.GetProductsList(Console.java:484)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.xml.ws.api.server.InstanceResolver$1.invoke(InstanceResolver.java:246)
at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:146)
DatabaseContext.java :
public class DatabaseContext
{
private final Session session;
public DatabaseContext() {
this.session = HibernateAdapter.getSessionFactory().openSession();
}
public Session delegate() {
return session;
}
public void close() {
session.flush();
session.close();
}
}
class HibernateAdapter
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try
{
return new AnnotationConfiguration()
.addAnnotatedClass(Consumer.class)
.addAnnotatedClass(Product.class)
.addAnnotatedClass(PriceTag.class)
.addAnnotatedClass(Barcode.class)
.configure().buildSessionFactory();
}
catch (Throwable e)
{
System.err.println("Exception while creating Initial SessionFactory" + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
A NoClassDefFoundError usually indicates that your class path is not correct. Check if you have the right Hibernate libraries in your class path. e.g. in the project settings, if you are using Eclipse. Right now, you are not including the DataLayer.HibernateAdapter class correctly, so Tomcat cannot find it.

Categories

Resources