ResponseEntityExceptionHandler not called - spring

I'm working with Spring Boot 2.7.1 and trying to implement Exception handling. Somehow it's not working. Here're the details:
Controller Advice
#ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
#ExceptionHandler(RoomNotFoundException.class)
#ResponseBody
public final ResponseEntity<ErrorMessage> handleRoomNotFoundException(RoomNotFoundException e, WebRequest request) {
ErrorMessage errorMessage=new ErrorMessage(HttpStatus.NOT_FOUND,e.getMessage());
System.out.println("RestResponseEntityExceptionHandler.RoomNotFoundException()");
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorMessage);
}
}
RestController Implementation:
#RestController
#RequestMapping("/api")
public class WebServiceController {
#Autowired
private final ReservationService reservationService;
#Autowired
private RoomRepository roomRepository;
#Override
public String toString() {
return "WebServiceController []";
}
public WebServiceController(ReservationService reservationService) {
super();
this.reservationService = reservationService;
}
#RequestMapping(path = "/jpa/getroomId/{id}", method = RequestMethod.GET)
public Room getRooms(#PathVariable String id) throws RoomNotFoundException {
Optional<Room> optionalRoom;
try {
optionalRoom = reservationService.getRoomDetail(Integer.parseInt(id));
if (!optionalRoom.isPresent()) {
throw new RoomNotFoundException("Room Id is incorrect:" + id);
}
return optionalRoom.get();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
ErrorMessage Bean class:
public class ErrorMessage {
private HttpStatus status;
private String message;
public ErrorMessage(HttpStatus status, String message) {
super();
this.status = status;
this.message = message;
}
public ErrorMessage() {
}
public HttpStatus getStatus() {
return status;
}
public void setStatus(HttpStatus status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
On Postman when I hit:
I get no return and the Response status code is 200.
On Eclipse server, I get the below output:
022-07-28 20:55:41.571 INFO 6893 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8000 (http) with context path ''
2022-07-28 20:55:41.575 INFO 6893 --- [ restartedMain] c.k.j.l.LearningSpringApplication : Started LearningSpringApplication in 0.891 seconds (JVM running for 1266.472)
2022-07-28 20:55:41.576 INFO 6893 --- [ restartedMain] .ConditionEvaluationDeltaLoggingListener : Condition evaluation unchanged
2022-07-28 20:55:49.292 INFO 6893 --- [nio-8000-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-07-28 20:55:49.292 INFO 6893 --- [nio-8000-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-07-28 20:55:49.294 INFO 6893 --- [nio-8000-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms
Hibernate: select room0_.room_id as room_id1_2_0_, room0_.bed_info as bed_info2_2_0_, room0_.name as name3_2_0_, room0_.room_number as room_num4_2_0_ from room room0_ where room0_.room_id=?
com.khushboo.java.learningspring.exceptions.RoomNotFoundException: Room Id is incorrect:500
at com.khushboo.java.learningspring.webservice.WebServiceController.getRooms(WebServiceController.java:56)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
Thanks for taking the time and sharing any helpful insights on why the ExceptionHandler code is not getting invoked.

ResponseEntityExceptionHandler is not get called because here:
}catch (Exception e) {
e.printStackTrace();
}
return null;
you are swallowing all exceptions, including RoomNotFoundException

Related

Can not execute controller test with #SpringBootTest

I have a Spring Boot application. Version is 2.3.1.
Main Application looks like:
#AllArgsConstructor
#SpringBootApplication
public class LocalServiceApplication implements CommandLineRunner {
private final DataService dataService;
private final QrReaderServer qrReaderServer;
private final MonitoringService monitoringService;
#Override
public void run(String... args) {
dataService.fetchData();
monitoringService.launchMonitoring();
qrReaderServer.launchServer();
}
public static void main(String[] args) {
SpringApplication.run(LocalServiceApplication.class, args);
}
}
After the application is started I have to execute 3 distinct steps which have done with CommandLineRunner:
first gets remote data and store it locally (for test profile this step is skipped)
start async folder monitoring for file uploads with WatchService.
launch TCP server
I have a controller like:
#Slf4j
#RestController
#AllArgsConstructor
#RequestMapping("/v1/permissions")
public class CarParkController {
private final PermissionService permissionService;
#PostMapping
public CarParkPermission createPermission(#RequestBody #Valid CarParkPermission permission) {
return permissionService.createPermission(permission);
}
}
Ant test with Junit 5 looks like:
#ActiveProfiles("test")
#AutoConfigureMockMvc
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class CarParkControllerIntegrationTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private PermissionService permissionService;
private final Gson gson = new Gson();
#Test
void testCreatingNewPermissionSuccess() throws Exception {
CarParkPermission permission = CarParkPermission.builder()
.id(56)
.permissionCode("1234")
.build();
when(permissionService.createPermission(refEq(permission))).thenReturn(permission);
postPermission(permission).andExpect(status().isOk());
}
private <T> ResultActions postPermission(T instance) throws Exception {
return this.mockMvc.perform(post("/v1/permissions")
.contentType(MediaType.APPLICATION_JSON)
.content(gson.toJson(instance)));
}
}
Looks like it should work fine.
However, the test isn't executed:
2020-08-27 14:42:30.308 INFO 21800 --- [ main] c.s.i.CarParkControllerIntegrationTest : Started CarParkControllerIntegrationTest in 8.593 seconds (JVM running for 10.03)
2020-08-27 14:42:30.334 INFO 21800 --- [ main] c.s.s.s.DataServiceTestImpl : Fetch data for test profile is skipped
2020-08-27 14:42:30.336 DEBUG 21800 --- [ carpark-ex-1] c.s.monitoring.MonitoringServiceImpl : START_MONITORING Results from Cameras for folder: D:\results-from-camera
2020-08-27 14:42:30.751 DEBUG 21800 --- [ main] c.s.netty.TCPServer : TCP Server is STARTED : port 9090
After those lines execution hangs up forever.
UPDATE
Here are details for monitoring task:
#Async
#Override
public void launchMonitoring() {
log.debug("START_MONITORING Results from Cameras for folder: {}", properties.getFolder());
try {
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == ENTRY_CREATE) {
log.info("FILE_CREATED: {}", event.context());
// processing resource
deleteResource(zipFullPath);
} else if (kind == ENTRY_DELETE) {
log.info("RESOURCE_DELETED: {}", event.context());
}
}
key.reset();
}
} catch (InterruptedException e) {
log.error("interrupted exception for monitoring service", e);
Thread.currentThread().interrupt();
}
}
Also AsyncConfiguration is configured with TaskExecutor.
Launch method from TCPServer looks:
#Override
public void launchServer() {
try {
ChannelFuture serverChannelFuture = serverBootstrap.bind(hostAddress).sync();
log.debug("TCP Server is STARTED : port {}", hostAddress.getPort());
serverChannel = serverChannelFuture.channel().closeFuture().sync().channel();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
shutdownQuietly();
}
}
How to solve this issue?
Have understood that execution is blocked (thanks to M.Deinum).
So changed the last method for:
#Async
#Override
public void launchServer() {
// ...
}
And shifted to ObjectMapper instead of Gson for converting instance to JSON format:
#SpringBootTest
#AutoConfigureMockMvc
#ActiveProfiles("test")
class CarParkControllerIntegrationTest {
#Autowired
private MockMvc mockMvc;
#Autowired
private ObjectMapper mapper;
#Test
void testCreatingNewPermissionSuccess() throws Exception {
CarParkPermission permission = CarParkPermission.builder()
.id(444)
.permissionCode("1234")
.build();
postPermission(permission).andExpect(status().isOk());
}
private <T> ResultActions postPermission(T instance) throws Exception {
return this.mockMvc.perform(post("/v1/permissions")
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(instance)));
}
}
And finally, it works fine.

java.lang.NullPointerException error on accessing page linked to controller class

I am running a spring mvc application with classes annotated as #controller,#service,#component and for the view layer thymeleaf is used. However on navigating to the path localhost:8080/owners no owner data is displayed.Looks like even though data is getting saved in owner object but ownerservicemap is null for no reason.
Below is the error
Owner data is loaded
2019-06-26 12:39:47.237 INFO 5776 --- [ restartedMain]
.ConditionEvaluationDeltaLoggingListener : Condition evaluation
unchanged
2019-06-26 12:39:50.475 INFO 5776 --- [nio-8080-exec-1]
o.a.c.c.C.[Tomcat-1].[localhost].[/] : Initializing Spring
DispatcherServlet 'dispatcherServlet'
2019-06-26 12:39:50.475 INFO 5776 --- [nio-8080-exec-1]
o.s.web.servlet.DispatcherServlet : Initializing Servlet
'dispatcherServlet'
2019-06-26 12:39:50.483 INFO 5776 --- [nio-8080-exec-1]
o.s.web.servlet.DispatcherServlet : Completed initialization in
8 ms
2019-06-26 12:39:50.507 ERROR 5776 --- [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] with root cause
java.lang.NullPointerException: null
at com.example.Project.controllers.OwnerController.listOwners(OwnerController.java:33)
~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_211]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
~[na:1.8.0_211]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[na:1.8.0_211]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_211]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
DataLoader class to load the data
#Component public class DataLoader implements CommandLineRunner{
private final OwnerService ownerService;
public DataLoader()
{
ownerService=new OwnerServiceMap();
}
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
Owner owner1=new Owner();
owner1.setId(1L);
owner1.setFirstName("ally");
owner1.setLastName("nilson");
Owner sa1=ownerService.save(owner1);
}}
Below is the ownercontroller class
#RequestMapping("/owners") #Controller public class OwnerController {
private OwnerService ownerservice;
#Autowired
public OwnerController(OwnerService ownerservice)
{
this.ownerservice=ownerservice;
}
#RequestMapping({"","/","/index","/index.html"})
public String listOwners(Model model)
{
model.addAttribute("owner",ownerservice.findAll());// System.out.println(ownerservice.findById(1L).getLastName());
return "owner/index";
}}
OwnerService interface
public interface OwnerService extends CrudService<Owner, Long>{
Owner findByLastName(String lastname);}
AbstractmapService class
public abstract class AbstractMapService<T,ID> {
protected Map<ID,T> map=new HashMap<>();
Set<T> findAll()
{
return new HashSet<>(map.values());
}
T findById(ID id)
{
return map.get(id);
}
T save(ID id,T object)
{
map.put(id, object);
return object;
}
void deleteById(ID id)
{
map.remove(id);
}
void delete(T object)
{
map.entrySet().removeIf(entry->entry.getValue().equals(object));
}}
OwnerServiceMap class
#Service public class OwnerServiceMap extends AbstractMapService<Owner,Long>implements OwnerService{
#Override
public Set<Owner> findAll() {
// TODO Auto-generated method stub
return super.findAll();
}
#Override
public Owner findById(Long id) {
// TODO Auto-generated method stub
return super.findById(id);
}
#Override
public Owner save(Owner object) {
// TODO Auto-generated method stub
return super.save(object.getId(),object);
}
#Override
public void delete(Owner object) {
// TODO Auto-generated method stub
super.delete(object);
}
#Override
public void deleteById(Long id) {
// TODO Auto-generated method stub
super.deleteById(id);
}
#Override
public Owner findByLastName(String lastname) {
// TODO Auto-generated method stub
return null;
}
}
#Service
public class OwnerServiceMap extends AbstractMapService<Owner,Long> implements OwnerService{ ... // }
To be autowired, you must register with the bean.
EDIT1
You did to save another service's Map.
#Component public class DataLoader implements CommandLineRunner{
private final OwnerService ownerService;
public DataLoader()
{
ownerService=new OwnerServiceMap();
}
// ...
And here,
#RequestMapping("/owners") #Controller public class OwnerController {
private OwnerService ownerservice;
#Autowired
public OwnerController(OwnerService ownerservice)
{
this.ownerservice=ownerservice;
}
check this please.
EDIT2
If you register Object to bean, container has that by singleton object.
then, Using #Autowired get singleton object from container.
NOTE : it's different with GOF's singleton.
To summarize, what you use with the new keyword like ownerService=new OwnerServiceMap(); was to create a new instance, not to use the bean instance that you assigned to the Container. So, using the different instances, the above problem occurs.

Unable to pass the JobParameters Value to the tasklet in Spring Batch

I already followed link: Pass JobParameters and ExecutionContext to #Bean Tasklet?, but still facing issue while passing the jobParameters value to the tasklet.
I've developed a code like below:
JobConfiguration.java
#Component
public class JobConfiguration implements ApplicationContextAware{
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Autowired
private JobExplorer jobExplorer;
#Autowired
private JobRepository jobRepository;
#Autowired
private JobRegistry jobRegistry;
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
#Bean
#StepScope
public Tasklet tasklet(#Value("#{jobParameters['name']}") String name) {
System.out.println("NAME VALUE = "+name);
return (contribution, chunkContext) -> {
System.out.println(String.format("The job run for %s", name));
return RepeatStatus.FINISHED;
};
}
#Bean
public Job job() {
return jobBuilderFactory.get("job")
.start(stepBuilderFactory.get("step1")
.tasklet(tasklet(null))
.build())
.build();
}
}
JobLaunchingController.java
#RestController
public class JobLaunchingController {
#Autowired
private JobLauncher jobLauncher;
#Autowired
private Job job;
#PostMapping("/")
#ResponseStatus(value = HttpStatus.ACCEPTED)
public void launch(#RequestParam("name") String name) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
JobParameters jobParameters = new JobParametersBuilder()
.addString("name", name)
.toJobParameters();
JobExecution jobExecution = this.jobLauncher.run(job, jobParameters);
System.out.println("STATUS = "+jobExecution.getStatus());
}
}
Logs:
2018-12-13 23:09:35.930 INFO 20004 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2018-12-13 23:09:35.930 INFO 20004 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2018-12-13 23:09:35.938 INFO 20004 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 8 ms
2018-12-13 23:09:55.046 INFO 20004 --- [nio-8080-exec-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job]] launched with the following parameters: [{name=foo}]
2018-12-13 23:09:55.414 INFO 20004 --- [nio-8080-exec-1] o.s.batch.core.job.SimpleStepHandler : Executing step: [step1]
The job run for null
2018-12-13 23:09:55.672 INFO 20004 --- [nio-8080-exec-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job]] completed with the following parameters: [{name=foo}] and the following status: [COMPLETED]
STATUS = COMPLETED
StartingAJobApplication.java
#SpringBootApplication
#EnableBatchProcessing
public class StartingAJobApplication {
public static void main(String[] args) {
SpringApplication.run(StartingAJobApplication.class, args);
}
}
CURL:
curl --data 'name=foo' localhost:8080
it's normal because you are passing the tasklet to the job yourself and it has null param.
in order to use #StepScop feature, you need to use the bean spring created
#Bean
public Job job(Tasklet tasklet) {
return jobBuilderFactory.get("job")
.start(stepBuilderFactory.get("step1")
.tasklet(tasklet)
.build())
.build();
}
When you implement “execute” method, you have SetpContribution and ChunkContext as parameters. You have to use ChunkContext to get jobParameter.
#Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
JobParameters jobParameters = chunkContext.getStepContext().getStepExecution().getJobParameters();
...
}

Spring-Boot BeanCreatingException

My project was running but after 5 minutes there is no change and i recompile my project there is an error just enter code here like this.
2018-11-12 14:04:27.508 INFO 7904 --- [ main] c.i.IwbEmuhasebeAdapterApplication : Starting IwbEmuhasebeAdapterApplication on PRMS-ALC with PID 7904 (D:\eclipse-workspace\iwb-emuhasebe-adapter\target\classes started by Alican in D:\eclipse-workspace\iwb-emuhasebe-adapter)
2018-11-12 14:04:27.516 INFO 7904 --- [ main] c.i.IwbEmuhasebeAdapterApplication : No active profile set, falling back to default profiles: default
2018-11-12 14:04:27.626 INFO 7904 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#5a45133e: startup date [Mon Nov 12 14:04:27 EET 2018]; root of context hierarchy
2018-11-12 14:04:30.873 INFO 7904 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8083 (http)
2018-11-12 14:04:30.940 INFO 7904 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-11-12 14:04:30.940 INFO 7904 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.34
2018-11-12 14:04:30.969 INFO 7904 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_171\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files\Java\jdk1.8.0_171\jre\bin;C:/Program Files/Java/jre1.8.0_191/bin/server;C:/Program Files/Java/jre1.8.0_191/bin;C:/Program Files/Java/jre1.8.0_191/lib/amd64;C:\oracle\product\11.2.0\dbhome_1\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\Java\jdk1.8.0_171;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files\MongoDB\Server\3.6\bin;C:\Program Files\PuTTY\;C:\Program Files\Java\jdk1.8.0_171\bin\;C:\Program Files\Java\jre1.8.0_191\bin;C:\Users\Alican\AppData\Local\Microsoft\WindowsApps;;C:\Program Files (x86)\Microsoft VS Code\bin;C:\Users\Alican\AppData\Roaming\npm;C:\eclipse;;.]
2018-11-12 14:04:31.212 INFO 7904 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-11-12 14:04:31.213 INFO 7904 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3599 ms
2018-11-12 14:04:31.354 INFO 7904 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-11-12 14:04:31.359 INFO 7904 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-11-12 14:04:31.360 INFO 7904 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-11-12 14:04:31.360 INFO 7904 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-11-12 14:04:31.360 INFO 7904 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-11-12 14:04:31.800 WARN 7904 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appServlet': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.iworkbetter.controller.AppServlet] from ClassLoader [sun.misc.Launcher$AppClassLoader#18b4aac2]
2018-11-12 14:04:31.804 INFO 7904 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
Here is the my appServlet.java
#RestController
public class AppServlet {
#Autowired
private AdapterEngine engine;
public AppServlet(AdapterEngine engine) {
this.engine = engine;
}
#RequestMapping("/EFaturaSender")
public void hndEFaturaSender(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
response.setContentType("text/html; charset=UTF-8");
engine.eFaturaSender(customizationId, AdapterUtil.uInt(requestParams.get("efatura_id")));
}
/*
* #RequestMapping("/EFaturaReceiverGelen") public void
* hndEFaturaReceiverGelen(HttpServletRequest request, HttpServletResponse
* response) throws IOException { Map<String, String> requestParams =
* AdapterUtil.getParameterMap(request); int customizationId = 0;
*
* if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) { try {
* customizationId = AdapterUtil.uInt(requestParams.get("customizationId")); }
* catch (Exception e) { e.printStackTrace(); } } int insertedInvoice = 0;
* response.setContentType("text/html; charset=UTF-8"); insertedInvoice =
* engine.eFaturaGelenAra(customizationId,
* AdapterUtil.uDate(requestParams.get("start_dt")),
* AdapterUtil.uDate(requestParams.get("end_dt")));
* response.getWriter().write("{'success':true,'insertedInvoice':" +
* insertedInvoice + "}");
*
* }
*/
#RequestMapping("/EFaturaReceiverGiden") // TODO Şimdilik gerek yok
public void hndEFaturaReceiverGiden(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
int insertedInvoice = 0;
response.setContentType("text/html; charset=UTF-8");
try {
insertedInvoice = engine.eFaturaAlGiden(customizationId, requestParams);
response.getWriter().write("{'success':true,'insertedInvoice':" + insertedInvoice + "}");
} catch (Exception e) {
response.getWriter().write("{'success':false}");
e.printStackTrace();
} finally {
response.getWriter().close();
}
}
#RequestMapping("/EFaturaMukellefGuncelle") // TODO
public void hndEFaturaMukellefGuncelle(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
int insertedMukellef = 0;
response.setContentType("text/html; charset=UTF-8");
try {
insertedMukellef = engine.eFaturaMukellefGuncelle(customizationId);
response.getWriter().write("{'success':true,'insertedMukellef':" + insertedMukellef + "}");
} catch (IOException e) {
response.getWriter().write("{'success':false}");
e.printStackTrace();
} finally {
response.getWriter().close();
}
}
#RequestMapping("/EFaturaGelenFaturaDurum")
public void hndGelenEFaturaDurumGuncelle(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
response.setContentType("text/html; charset=UTF-8");
try {
engine.eFaturaGelenDurumSorgula(customizationId, AdapterUtil.uInt(requestParams.get("efatura_id")));
response.getWriter().write("{'success':true}");
} catch (Exception e) {
response.getWriter().write("{'success':false}");
e.printStackTrace();
} finally {
response.getWriter().close();
}
}
#RequestMapping("/EFaturaGidenFaturaDurum")
public void hndGidenEFaturaDurumGuncelle(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
response.setContentType("text/html; charset=UTF-8");
try {
engine.eFaturaGidenFaturaDurumSorgula(customizationId, AdapterUtil.uInt(requestParams.get("efatura_id")));
response.getWriter().write("{'success':true}");
} catch (Exception e) {
response.getWriter().write("{'success':false}");
e.printStackTrace();
} finally {
response.getWriter().close();
}
}
#RequestMapping("/EFaturaYanıtla")
public void hndEFaturaYanitla(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
response.setContentType("text/html; charset=UTF-8");
try {
engine.eFaturaYanitla(customizationId, requestParams);
response.getWriter().write("{'success':true}");
} catch (Exception e) {
response.getWriter().write("{'success':false}");
e.printStackTrace();
} finally {
response.getWriter().close();
}
}
// #Scheduled(fixedRate = 200000) // gelen fatura icin scheduled
public void scheduled4ReceiverInvoice() {
int customizationId = 0;// TODO
Date end_date = new Date();
GregorianCalendar start_date = new GregorianCalendar();
start_date.setTime(end_date);
start_date.add(Calendar.DATE, -6);// bugunle 6 gun oncesi
engine.eFaturaGelenAra(customizationId, start_date.getTime(), end_date);
}
// #Scheduled(fixedRate = 200000)
public void scheduled4MukellefUpdate() {
int customizationId = 0;
engine.eFaturaMukellefGuncelle(customizationId);
}
#RequestMapping("EFaturaReceiverGelen")
public void deserializeTest(HttpServletRequest request, HttpServletResponse response)
throws JAXBException, IOException {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
int insertedInvoice = 0;
response.setContentType("text/html; charset=UTF-8");
insertedInvoice = engine.deserializeTest(customizationId, AdapterUtil.uDate(requestParams.get("start_dt")),
AdapterUtil.uDate(requestParams.get("end_dt")));
response.getWriter().write("{'success':true,'insertedInvoice':" + insertedInvoice + "}");
}
#RequestMapping("ShowInvoice")
public void showInvoiceOnBrowser(HttpServletRequest request, HttpServletResponse response) throws IOException {
byte[] pdfBytes = engine.showInvoice();
JSONObject j = new JSONObject();
try {
j.put("data1", pdfBytes);
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// response.setContentType("application/json");
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(j);
out.flush();
try {
response.getWriter().write("{'success':true,'data':" + "}");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* response.setHeader("Content-Type", "text/plain");
* response.setHeader("success", "yes"); PrintWriter writer =
* response.getWriter(); writer.write(pdfBytes.toString()); writer.close();
*/
}
}
and this is the warning message:
2018-11-12 14:54:13.580 WARN 7784 --- [ main]
ConfigServletWebServerApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'appServlet': Lookup method resolution failed;
nested exception is java.lang.IllegalStateException: Failed to
introspect Class [com.iworkbetter.controller.AppServlet] from
ClassLoader [sun.misc.Launcher$AppClassLoader#18b4aac2]
I had the same problem. I've fixed 2 things and the problem is resolved:
I found that I made a typo at pom.xml.
I was using Java 8 to run, but compiled with Java 11.

Spring Boot JettyServerCustomizer | HTTPS port not opened | A ServletContext is required to configure default servlet handling

I am trying to use Spring Boot with embedded. I want the embedded Jetty to open a HTTPS port at 443.
After referring the answer posted here, I came up with this configuration:-
import java.io.FileNotFoundException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ssl.SslSocketConnector;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.jetty.JettyServerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.util.ResourceUtils;
import com.samsoft.expunto.service.UserService;
/**
* #author Kumar Sambhav Jain
*
*/
#Configuration
#EnableWebMvcSecurity
#EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/", "/resources/**")
.permitAll().anyRequest().authenticated().and().formLogin()
.loginPage("/").defaultSuccessUrl("/home", false).and()
.requiresChannel().anyRequest().requiresSecure().and().logout()
.invalidateHttpSession(true).logoutUrl("/logout")
.logoutSuccessUrl("/").and().userDetailsService(userService);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
}
#Bean
public JettyServerCustomizer jettyCutomizer() {
return new JettyServerCustomizer() {
#Override
public void customize(Server server) {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePassword("jetty6");
try {
sslContextFactory.setKeyStorePath(ResourceUtils.getFile(
"classpath:jetty-ssl.keystore").getAbsolutePath());
} catch (FileNotFoundException ex) {
throw new IllegalStateException("Could not load keystore",
ex);
}
SslSocketConnector sslConnector = new SslSocketConnector(
sslContextFactory);
sslConnector.setPort(443);
sslConnector.setMaxIdleTime(60000);
server.addConnector(sslConnector);
}
};
}
}
Trying to run the application using spring-boot:run, I can see in logs that port 80 is opened but no HTTPS port:-
2014-06-10 23:41:56.932 INFO 196 --- [lication.main()] /
: Initializing Spring FrameworkServlet 'dispatcherServlet' 2014-06-10
23:41:56.932 INFO 196 --- [lication.main()]
o.s.web.servlet.DispatcherServlet : FrameworkServlet
'dispatcherServlet': initialization started 2014-06-10 23:41:56.960
INFO 196 --- [lication.main()] o.s.web.servlet.DispatcherServlet
: FrameworkServlet 'dispatcherServlet': initialization completed in 26
ms 2014-06-10 23:41:57.037 INFO 196 --- [lication.main()]
o.e.jetty.server.AbstractConnector : Started
SelectChannelConnector#0.0.0.0:80 2014-06-10 23:41:57.043 INFO 196
--- [lication.main()] .s.b.c.e.j.JettyEmbeddedServletContainer : Jetty started on port: 80 2014-06-10 23:41:57.045 INFO 196 ---
[lication.main()] c.s.expunto.web.config.Application : Started
Application in 7.628 seconds (JVM running for 16.509)
UPDATE
Using this configuration:-
#Configuration
#EnableWebMvcSecurity
#EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
implements EmbeddedServletContainerCustomizer {
#Autowired
private UserService userService;
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/", "/resources/**")
.permitAll().anyRequest().authenticated().and().formLogin()
.loginPage("/").defaultSuccessUrl("/home", false).and()
.requiresChannel().anyRequest().requiresSecure().and().logout()
.invalidateHttpSession(true).logoutUrl("/logout")
.logoutSuccessUrl("/").and().userDetailsService(userService);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
}
public JettyServerCustomizer jettyServerCustomizer() {
return new JettyServerCustomizer() {
#Override
public void customize(Server server) {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePassword("jetty6");
try {
sslContextFactory.setKeyStorePath(ResourceUtils.getFile(
"classpath:jetty-ssl.keystore").getAbsolutePath());
} catch (FileNotFoundException ex) {
throw new IllegalStateException("Could not load keystore",
ex);
}
SslSocketConnector sslConnector = new SslSocketConnector(
sslContextFactory);
sslConnector.setPort(443);
sslConnector.setMaxIdleTime(60000);
server.addConnector(sslConnector);
}
};
}
public void customizeJetty(
JettyEmbeddedServletContainerFactory containerFactory) {
containerFactory.addServerCustomizers(jettyServerCustomizer());
}
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if (container instanceof JettyEmbeddedServletContainerFactory) {
customizeJetty((JettyEmbeddedServletContainerFactory) container);
}
container.setContextPath("");
}
}
I get this error:-
: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:54)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:346)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$d7014349.CGLIB$defaultServletHandlerMapping$24(<generated>)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$d7014349$$FastClassBySpringCGLIB$$ec8be680.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$d7014349.defaultServletHandlerMapping(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
As per M. Deinum advice, moving the customizers to class annotated with #EnableAutoConfiguration did the trick.
This is what worked for me:-
#Configuration
#EnableAutoConfiguration
public class Application implements EmbeddedServletContainerCustomizer {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
#Bean
public JettyServerCustomizer jettyServerCustomizer() {
return new JettyServerCustomizer() {
#Override
public void customize(Server server) {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePassword("jetty6");
try {
sslContextFactory.setKeyStorePath(ResourceUtils.getFile(
"classpath:jetty-ssl.keystore").getAbsolutePath());
} catch (FileNotFoundException ex) {
throw new IllegalStateException("Could not load keystore",
ex);
}
SslSocketConnector sslConnector = new SslSocketConnector(
sslContextFactory);
sslConnector.setPort(443);
sslConnector.setMaxIdleTime(60000);
server.addConnector(sslConnector);
}
};
}
public void customizeJetty(
JettyEmbeddedServletContainerFactory containerFactory) {
containerFactory.addServerCustomizers(jettyServerCustomizer());
}
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if (container instanceof JettyEmbeddedServletContainerFactory) {
customizeJetty((JettyEmbeddedServletContainerFactory) container);
}
}
}

Resources