java.lang.NullPointerException while calling from controller - java

My Spring Boot program is compiling without any issues, but whenever I click the registration link it throws NullPointerException error. I am really at a loss as to what may be causing this. Given below is the error:-
java.lang.NullPointerException: null
at com.concretepage.controller.UserInfoController.registration(UserInfoController.java:32) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_171]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_171]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_171]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_171]
The UserinfoController class is given below:-
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.concretepage.entity.ProjectLevel;
import com.concretepage.service.LevelService;
import com.concretepage.service.UserInfoService;
#Controller
#RequestMapping("app")
public class UserInfoController {
#Autowired
private UserInfoService userInfoService;
private LevelService levelService;
#GetMapping("login")
public ModelAndView login() {
ModelAndView mav = new ModelAndView();
mav.setViewName("custom-login");
return mav;
}
#GetMapping("registration")
public ModelAndView registration() {
ModelAndView mav = new ModelAndView();
List<ProjectLevel> levels = levelService.getAllLevels();
mav.addObject("Levels", levels);
mav.setViewName("registration");
return mav;
}
#GetMapping("secure/project-details")
public ModelAndView getAllUserProjects() {
ModelAndView mav = new ModelAndView();
mav.addObject("userProjects", userInfoService.getAllUserProjects());
mav.setViewName("projects");
return mav;
}
Error is at the line -
List<ProjectLevel> levels = levelService.getAllLevels();
The LevelServiceImpl class is as below:-
package com.concretepage.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.concretepage.entity.ProjectLevel;
import com.concretepage.repositories.LevelRepository;
#Service
public class LevelServiceImpl implements LevelService {
#Autowired
private LevelRepository levelRepository;
#Override
public List<ProjectLevel> getAllLevels() {
List<ProjectLevel> levelList = levelRepository.findAll();
return levelList;
}
}

Just change this piece of code:
#Autowired
private UserInfoService userInfoService;
private LevelService levelService;
to
#Autowired
private UserInfoService userInfoService;
#Autowired
private LevelService levelService;

You must use separate #Autowired for private LevelService levelService;

Related

NullPointer with #Autowire HttpServletRequest

I have the following code:
package com.example.helloworld;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.annotation.RequestScope;
#RestController
public class HelloWorldController {
#GetMapping("/")
public ResponseEntity<String> getGet(
#Autowired Foo foo) {
foo.sayHi();
return new ResponseEntity<>("OK", HttpStatus.OK);
}
}
#Component
#RequestScope
class Foo {
private #Autowired HttpServletRequest request;
public void sayHi() {
var name = this.request.getHeader("x-user-name");
System.out.println("Hi " + name);
}
}
When I try to curl with curl -H x-user-name:capybara http://localhost:8080, the following error is produced:
2022-09-09 17:07:28.623 ERROR 26350 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException: Cannot invoke "javax.servlet.http.HttpServletRequest.getHeader(String)" because "this.request" is null] with root cause
java.lang.NullPointerException: Cannot invoke "javax.servlet.http.HttpServletRequest.getHeader(String)" because "this.request" is null
at com.example.helloworld.Foo.sayHi(HelloWorldController.java:32) ~[classes!/:0.0.1-SNAPSHOT]
at com.example.helloworld.HelloWorldController.getGet(HelloWorldController.java:19) ~[classes!/:0.0.1-SNAPSHOT]
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]
at
...
Why is this.request null? Giving the popularity of https://stackoverflow.com/a/3324233/2287586, seems like this should work, what am I missing?
It doesn't work becuse it needs to be a Singleton bean and you have #RequestScope.
Maybe try this:
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

Swagger is not showing any controllers or endpoints

Swagger Api Docs Image
I am working on adding / integrating swagger in my springboot project. I have tried different things but its not got fixed. All that is showing now is white page without any endpoints or controllers and just an empty page with swagger logo.
Swagger URL is : http://localhost:8080/swagger-ui.html
My swagger configurations are given below:
package com.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#SpringBootApplication(scanBasePackages = {"com.app.controller"})
public class StoreApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
try {
SpringApplication.run(StoreApplication.class, args);
}catch (Throwable throwable){
System.out.println(throwable.toString());
throwable.printStackTrace();
}
}
}
Here is my controller code.
My Controller
package com.app.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#CrossOrigin
#RestController
public class CustomersController {
#RequestMapping(value = "/customers", method = RequestMethod.GET)
ResponseEntity<?> getAllCustomers(){
return ResponseEntity.status(HttpStatus.OK).body(null);
}
#RequestMapping(value = "/customer", method = RequestMethod.POST)
ResponseEntity<?> createCustomer(){
return ResponseEntity.status(HttpStatus.OK).body(null);
}
}
Here is the main class
Main Class
package com.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#SpringBootApplication(scanBasePackages = {"com.app.controller"})
public class StoreApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
try {
SpringApplication.run(StoreApplication.class, args);
}catch (Throwable throwable){
System.out.println(throwable.toString());
throwable.printStackTrace();
}
}
}
This is my app config file
AppConfig
package com.app.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class AppConfig implements WebMvcConfigurer {
#Override
public void addViewControllers(ViewControllerRegistry registry){
// registry.addRedirectViewController("/docApi/v2/api-docs","/v2/api-docs");
registry.addViewController("/welcome").setViewName("Welcome");
}
}
First, try to add swagger config like this:
#EnableSwagger2
#Configuration
public class SwaggerConfig {
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.app"))
.paths(PathSelectors.any())
.build();
}
}
then add some annotation in your controller like this:
package com.app.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#CrossOrigin
#RestController
#Api
public class CustomersController {
#RequestMapping(value = "/customers", method = RequestMethod.GET)
#ApiOperation(value = "get all", tags = "customer")
ResponseEntity<?> getAllCustomers(){
return ResponseEntity.status(HttpStatus.OK).body(null);
}
#RequestMapping(value = "/customer", method = RequestMethod.POST)
#ApiOperation(value = "create", tags = "customer")
ResponseEntity<?> createCustomer(){
return ResponseEntity.status(HttpStatus.OK).body(null);
}
}
hope this would fix your problem. Then try to access the url: http://127.0.0.1:8080/swagger-ui/index.html, pay attention not the url http://localhost:8080/swagger-ui.html.

Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]

I am getting the error
"Resolved[org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]"
I tried all the options provided on previous posts it didn't work please tell me what I am doing wrong this is my first spring-boot application.
My controller
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.io.File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
#RestController
public class SpringBootJdbcController {
#Autowired
JdbcTemplate jdbc;
#Autowired
private SpringBootJdbcService springBootJdbcService;
#RequestMapping("/insert")
public String index() {
jdbc.execute("insert into user(name,email)values('javatpoint','java#javatpoint.com')");
return "data inserted Successfully";
}
#CrossOrigin(origins = "http://localhost:4200")
#ResponseStatus(HttpStatus.OK)
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = "multipart/form-data")
public void uploadFiles(#RequestParam("file") MultipartFile file) throws Exception {
System.out.println("hello hello hello");
System.out.println("file---------" + file);
springBootJdbcService.readConfigData(file);
}
}
My Application.properties
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=11MB
api call postman image :-
I don't understand what is the problem. Its my first spring-boot application please help.

Multiple entity managers (using different data sources for multiple db connections) in a single processor under a particular step: Spring Batch

I am trying to use 2 entity managers in my Spring Batch project in the processor, one for reading and another for persisting data in the db.
The code is as follows
#StepScope
#ComponentScan("com.airtel.billreminder.model")
#Transactional
#Slf4j
public class MyItemProcessor implements ItemProcessor<VoltSiMaster,VoltSiMaster>{
#PersistenceContext(unitName="voltuser")
EntityManager emvoltUser;
#PersistenceContext(unitName="voltreporting")
EntityManager emvoltUserReporting;
#Value("#{jobParameters['notificationNumber']}")
public Long notificationNumber;
#Value("#{jobParameters['dayBeforeNotificationValue']}")
public Long dayBeforeNotificationValue;
#Value("#{jobParameters['firstReminderBeforeDueDate']}")
public Long firstReminderBeforeDueDate;
private ReminderHistory reminderHistory;
#Transactional
#Override
public VoltSiMaster process(VoltSiMaster voltSiMaster) throws Exception {
log.info("Inside Processor");
perpareNotifications(voltSiMaster,notificationNumber,dayBeforeNotificationValue);
return voltSiMaster;
}
#Transactional
private void perpareNotifications(VoltSiMaster siMaster, long notificationNumber,long dayBeforeNotificationValue) {
try {
/*business logic*/
if(notificationNumber>0)
{
txnDone = checkIsTxnAlreadyDone(siMaster);
}
if (!txnDone) {
String[] communincationTypesArray = communincationTypes.split(Pattern.quote("|"));
for (String communincationType : communincationTypesArray) {
log.info("Before sending notification");
if(siMaster.getAmount()>0)
sendNotification(notificationNumber,siMaster,
customerResponse, communincationType);
else
log.info("Amount is "+ siMaster.getBillerName() +" "+siMaster.getAmount()+"so not sending notification");
}
}
else
{
log.info("User has Already Paid Bill so no need to send notification");
}
}
}
private boolean checkIsTxnAlreadyDone(VoltSiMaster siMaster) {
String sqlString = "select * from "+Schemas.VOLT_USER_REPORTING+".volt_txn_log where txn_date_time >= (?1-"+firstReminderBeforeDueDate+") and CUSTOM_COL_3=?2 and uc_id=?3";
try {
Query txnCheckQuery = emvoltUserReporting.createNativeQuery(sqlString, VoltTxnLog.class);
txnCheckQuery.setParameter(1, siMaster.getBillDueDate());
txnCheckQuery.setParameter(2, siMaster.getReference1());
txnCheckQuery.setParameter(3, siMaster.getUcId());
log.info("Query to fire : {} " + txnCheckQuery.toString());
#SuppressWarnings("unchecked")
List<VoltTxnLog> resultList = txnCheckQuery.getResultList();
if (resultList != null) {
if (resultList.size() > 0)
{
for(VoltTxnLog vtxnlog: resultList)
{
if(vtxnlog.getTxnStatus().equals("0") || vtxnlog.getTxnStatus().equals("2"))
return true;
}
}
else
return false;
} else
return false;
} catch (Exception e) {
log.info("Error: "+e.getMessage());
}
return false;
}
#Transactional
private void sendNotification(long notificationNumber,VoltSiMaster siMaster,CusDetResponse customerResponse, String communincationType) {
/*business logic*/
emvoltUser.persist(reminderHistory);
emvoltUser.flush();
}
}
Config file for first entity manager:
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "voltEntityManagerFactory",
transactionManagerRef = "voltTransactionManager", basePackages = {"com.airtel.billreminder.model.voltUser"})
public class VoltUserDbConfig {
#Primary
#Bean(name = "voltDataSource")
#ConfigurationProperties(prefix = "volt.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#PersistenceContext(unitName="voltuser")
#Bean(name = "voltEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean barEntityManagerFactory(
EntityManagerFactoryBuilder builder, #Qualifier("voltDataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("com.airtel.billreminder.model.voltUser").persistenceUnit("voltuser")
.build();
}
#Primary
#ConditionalOnMissingBean(name = "transactionManager")
#ConditionalOnBean(DataSource.class)
#Bean(name = "voltTransactionManager")
public PlatformTransactionManager barTransactionManager(
#Qualifier("voltEntityManagerFactory") EntityManagerFactory barEntityManagerFactory) {
return new JpaTransactionManager(barEntityManagerFactory);
}
}
Config file for second entity manager:
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "voltReportingEntityManagerFactory",
transactionManagerRef = "voltReportingTransactionManager", basePackages = {"com.airtel.billreminder.model.voltUserReporting"})
public class VoltUserReportingDbConfig {
#Bean(name = "voltReportingDataSource")
#ConfigurationProperties(prefix = "voltreporting.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#PersistenceContext(unitName="voltreporting")
#Bean(name = "voltReportingEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean barEntityManagerFactory(
EntityManagerFactoryBuilder builder, #Qualifier("voltReportingDataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("com.airtel.billreminder.model.voltUserReporting").persistenceUnit("voltreporting")
.build();
}
#ConditionalOnMissingBean(name = "transactionManager")
#ConditionalOnBean(DataSource.class)
#Bean(name = "voltReportingTransactionManager")
public PlatformTransactionManager barTransactionManager(
#Qualifier("voltReportingEntityManagerFactory") EntityManagerFactory barEntityManagerFactory) {
return new JpaTransactionManager(barEntityManagerFactory);
}
}
Spring batch initializes its own transaction manager which i handled using #ConditionalOnMissingBean annotation because it was not creating my custom entity manager previously
Now running this code gives me following exception at emvoltUser.flush() even when i m using #Transactional which should handle the transaction by itself
javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.internal.SessionImpl.checkTransactionNeeded(SessionImpl.java:3505)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1427)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1423)
at sun.reflect.GeneratedMethodAccessor56.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350)
at com.sun.proxy.$Proxy109.flush(Unknown Source)
at sun.reflect.GeneratedMethodAccessor56.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:305)
at com.sun.proxy.$Proxy109.flush(Unknown Source)
at com.airtel.billreminder.notificationStep.MyItemProcessor.sendNotification(MyItemProcessor.java:233)
at com.airtel.billreminder.notificationStep.MyItemProcessor.perpareNotifications(MyItemProcessor.java:135)
at com.airtel.billreminder.notificationStep.MyItemProcessor.process(MyItemProcessor.java:112)
at com.airtel.billreminder.notificationStep.MyItemProcessor.process(MyItemProcessor.java:58)
at com.airtel.billreminder.notificationStep.MyItemProcessor$$FastClassBySpringCGLIB$$29bbf641.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
at com.airtel.billreminder.notificationStep.MyItemProcessor$$EnhancerBySpringCGLIB$$7ddd0f69.process(<generated>)
at com.airtel.billreminder.notificationStep.MyItemProcessor$$FastClassBySpringCGLIB$$29bbf641.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:136)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:124)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
at com.airtel.billreminder.notificationStep.MyItemProcessor$$EnhancerBySpringCGLIB$$ab91a70.process(<generated>)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.doProcess(SimpleChunkProcessor.java:126)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.transform(SimpleChunkProcessor.java:303)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.process(SimpleChunkProcessor.java:202)
at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:75)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:272)
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:81)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:375)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:145)
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148)
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:66)
at
org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:169)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:144)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:136)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:308)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:141)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:134)
at sun.reflect.GeneratedMethodAccessor66.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy112.run(Unknown Source)
at com.airtel.billreminder.config.BatchConfig.notificationJobLauncher(BatchConfig.java:343)
at sun.reflect.GeneratedMethodAccessor75.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
I have been stuck at this problem for 2 days now and I searched every possible article or previous answers but none could give me the hint to handle 2 entity managers under single processor pointing to different db connections.
Any help would be appreciated...
You are using #Transactional on your processor which will already be executed in the scope of a transaction driven by Spring Batch. Spring Batch handles the transaction management for you so you don't need to make the processor or writer transactional. I recommend to remove this annotation from your processor and let it participate in the transaction driven by the framework.
The error javax.persistence.TransactionRequiredException: no transaction is in progress means your JpaTransactionManager is not being used. You need to either:
make one of your batch configuration classes extend DefaultBatchConfigurer and override getTransactionManager by returning the JPA transaction manager
or add a bean of type BatchConfigurer in your context and make it return the JpaTransactionManager
Here is an example:
#Bean
public BatchConfigurer batchConfigurer(EntityManagerFactory entityManagerFactory) {
return new DefaultBatchConfigurer() {
#Override
public PlatformTransactionManager getTransactionManager() {
return new JpaTransactionManager(entityManagerFactory);
}
};
}
Note that this requires Spring Batch v4.1+ to work properly.

I am not able to invoke a simple rest controller

This is my controller code, and I am trying to invoke it using a url http://localhost:8089/webservroj/UserInfo?UserId=123 but it gives an error 404.
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.cas.models.UserInformationModel;
#RestController
#RequestMapping("/")
public class UserInformationController {
UserInformationModel jon =new UserInformationModel(19, "jon", "LA");
#RequestMapping(value="UserInfo", method=RequestMethod.GET)
public UserInformationModel getUserInformation(#RequestParam int UserId){
return jon;
}}

Categories