I have something very similar to the code below (I had to do some obfiscation). I am getting an Application Failed to Start error. Code not shown are datasource bean and spring boot application class. When I put breakpoints in and all run in debug, all beans appear to be created except the Job and Step bean, which seem to be skipped over entirely. I am not sure how to diagnose further. Seems to be some Spring Magic issues. Any ideas are greatly appreciated.
Here is the exception:
2020-08-23 11:26:50.264 INFO 12195 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-23 11:26:50.265 INFO 12195 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-08-23 11:26:50.382 INFO 12195 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-23 11:26:50.383 INFO 12195 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2276 ms
2020-08-23 11:26:57.552 WARN 12195 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'databaseCursorStep' defined in class path resource [/com/configuration/BatchConfig.class]: Unsatisfied dependency expressed through method 'databaseCursorStep' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.batch.item.ItemReader<com.dto.StuffDto>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=databaseCursorItemReader)}
2020-08-23 11:26:57.572 INFO 12195 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-08-23 11:26:57.603 INFO 12195 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-08-23 11:26:57.908 ERROR 12195 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Parameter 0 of method databaseCursorStep in com.configuration.BatchConfig required a bean of type 'org.springframework.batch.item.ItemReader' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Qualifier(value=databaseCursorItemReader)
Action:
Consider defining a bean of type 'org.springframework.batch.item.ItemReader' in your configuration.
Disconnected from the target VM, address: '127.0.0.1:46088', transport: 'socket'
Process finished with exit code 1
Here is the code:
#Configuration
#EnableBatchProcessing
public class BatchConfig {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
private static final String GET_DATA =
"SELECT " +
"stuffA, " +
"stuffB, " +
"FROM STUFF_TABLE " +
"ORDER BY stuffA ASC";
#Bean
public ItemReader<StuffDto> itemReader(DataSource dataSource) {
return new JdbcCursorItemReaderBuilder<StuffDto>()
.name("cursorItemReader")
.dataSource(dataSource)
.sql(GET_DATA)
.rowMapper(new BeanPropertyRowMapper<>(StuffDto.class))
.build();
}
#Bean
ItemProcessor<StuffDto, StuffDto> databaseXmlItemProcessor() {
return new QueryLoggingProcessor();
}
#Bean
public ItemWriter<StuffDto> databaseCursorItemWriter() {
return new LoggingItemWriter();
}
#Bean
public Step databaseCursorStep(#Qualifier("databaseCursorItemReader") ItemReader<StuffDto> reader,
#Qualifier("databaseCursorItemWriter") ItemWriter<StuffDto> writer,
StepBuilderFactory stepBuilderFactory) {
return stepBuilderFactory.get("databaseCursorStep")
.<StuffDto, StuffDto>chunk(1)
.reader(reader)
.writer(writer)
.build();
}
#Bean
public Job databaseCursorJob(#Qualifier("databaseCursorStep") Step exampleJobStep,
JobBuilderFactory jobBuilderFactory) {
return jobBuilderFactory.get("databaseCursorJob")
.incrementer(new RunIdIncrementer())
.flow(exampleJobStep)
.end()
.build();
}
}
Your Qualifier Bean name is itemReader not databaseCursorItemReader. Either change the method name or change to databaseCursorStep(#Qualifier("itemReader")
#Bean
public Step databaseCursorStep(#Qualifier("itemReader") ItemReader<StuffDto> reader,
#Qualifier("databaseCursorItemWriter") ItemWriter<StuffDto> writer,
StepBuilderFactory stepBuilderFactory) {
return stepBuilderFactory.get("databaseCursorStep")
.<StuffDto, StuffDto>chunk(1)
.reader(reader)
.writer(writer)
.build();
}
#Bean
public ItemReader<StuffDto> itemReader(DataSource dataSource) {
return new JdbcCursorItemReaderBuilder<StuffDto>()
.name("cursorItemReader")
.dataSource(dataSource)
.sql(GET_DATA)
.rowMapper(new BeanPropertyRowMapper<>(StuffDto.class))
.build();
}
Related
I train with springboot and a mariadb database. When I test for data recovery, I get this message in postman:
{
"timestamp": "2022-03-03T13:53:18.609+00:00",
"status": 404,
"error": "Not Found",
"path": "/user/all"
}
. I tried several tutorials in copy paste and I always have the same message. I will also put the message that is in the console. Thank you in advance for your help.
controller
package controller;
import model.Users;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import service.UsersService;
import java.util.List;
#RestController
#RequestMapping("/user")
public class UsersController {
private UsersService usersService;
public UsersController(UsersService usersService) {
this.usersService = usersService;
}
#GetMapping("/all")
public ResponseEntity<List<Users>> getUsers() {
List<Users> users = usersService.getUsers();
return new ResponseEntity<>(users, HttpStatus.OK);
}
}
Service
package service;
import model.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import repository.UsersRepository;
import java.util.List;
#Service
public class UsersService {
private UsersRepository usersRepository;
#Autowired
public UsersService(UsersRepository usersRepository) {
this.usersRepository = usersRepository;
}
public List<Users> saveUsers(List<Users>users){
return usersRepository.saveAll(users);
}
public Users saveUsers(Users users){
return usersRepository.save(users);
}
public List<Users> getUsers(){
return usersRepository.findAll();
}
public Users getUserById(int id_user){
return usersRepository.findById(id_user).orElse(null);
}
}
Respository
package repository;
import model.Users;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UsersRepository extends JpaRepository<Users, Integer> {
}
Model
package model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "users")
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id_user;
#Column(name="lastname")
private String lastname;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
#Column(name="phone")
private String phone;
#Column(name="adress")
private String adress;
#Column(name="city")
private String city;
#Column(name="country")
private String country;
}
Application properties
spring.jpa.hibernate.ddl-auto = update
spring.datasource.url = jdbc:mysql://localhost:3306/database
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5Dialect
Console
2022-03-03 14:52:57.479 INFO 24188 --- [ main] c.p.database.databaseApplication : No active profile set, falling back to 1 default profile: "default"
2022-03-03 14:52:58.412 INFO 24188 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-03-03 14:52:58.435 INFO 24188 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 8 ms. Found 0 JPA repository interfaces.
2022-03-03 14:52:59.190 INFO 24188 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-03-03 14:52:59.204 INFO 24188 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-03-03 14:52:59.204 INFO 24188 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.58]
2022-03-03 14:52:59.370 INFO 24188 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-03-03 14:52:59.370 INFO 24188 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1816 ms
2022-03-03 14:52:59.627 INFO 24188 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-03-03 14:52:59.696 INFO 24188 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.5.Final
2022-03-03 14:52:59.892 INFO 24188 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-03-03 14:53:00.046 INFO 24188 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-03-03 14:53:00.252 INFO 24188 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-03-03 14:53:00.272 INFO 24188 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2022-03-03 14:53:00.652 INFO 24188 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-03-03 14:53:00.666 INFO 24188 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-03-03 14:53:00.722 WARN 24188 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-03-03 14:53:01.296 INFO 24188 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-03-03 14:53:01.317 INFO 24188 --- [ main] c.p.database.databaseApplication : Started dataBaseApplication in 4.589 seconds (JVM running for 5.786)
2022-03-03 14:53:18.493 INFO 24188 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-03-03 14:53:18.493 INFO 24188 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-03-03 14:53:18.495 INFO 24188 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Every thing on the controller class is implemented properly and there is definitely no need for other layers implementation to share, you probably use SpringBootServletInitializer, in the main class add the #EnableWebMvc annotation and override SpringApplicationBuilder method as
#SpringBootApplication
#EnableWebMvc
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
Otherwise if you use SpringApplication to sun the project make sure the main class annotated with #SpringBootApplication and be some thing like
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
And final thing check the presence of spring boot starter web dependency in you pom file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
If you do not use spring boot parent do not forget to add the proper version to web starter artifact.
I'm actually defining login with websecurity enabled, and i don't really know what is wring with my annotations that don't allow me to continue testing...
Here is the trace:
2021-10-29 13:58:09.436 INFO 10044 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-10-29 13:58:09.447 INFO 10044 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-10-29 13:58:09.447 INFO 10044 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.52]
2021-10-29 13:58:09.534 INFO 10044 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-10-29 13:58:09.534 INFO 10044 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1188 ms
2021-10-29 13:58:09.682 INFO 10044 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-10-29 13:58:09.731 INFO 10044 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-10-29 13:58:09.845 INFO 10044 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-10-29 13:58:09.933 INFO 10044 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-10-29 13:58:10.065 INFO 10044 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-10-29 13:58:10.089 INFO 10044 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL55Dialect
2021-10-29 13:58:10.628 INFO 10044 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-10-29 13:58:10.636 INFO 10044 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-10-29 13:58:10.670 WARN 10044 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2021-10-29 13:58:10.687 WARN 10044 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'personaDetails'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.taxig10.demo.service.PersonaDetailsImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2021-10-29 13:58:10.687 INFO 10044 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-10-29 13:58:10.689 INFO 10044 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-10-29 13:58:10.695 INFO 10044 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2021-10-29 13:58:10.696 INFO 10044 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-10-29 13:58:10.706 INFO 10044 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-10-29 13:58:10.720 ERROR 10044 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field personaDetails in com.taxig10.demo.config.WebSecurityConfig required a bean of type 'com.taxig10.demo.service.PersonaDetailsImpl' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.taxig10.demo.service.PersonaDetailsImpl' in your configuration.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
And my classes:
// app class
package com.taxig10.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TaxiG10Application {
public static void main(String[] args) {
SpringApplication.run(TaxiG10Application.class, args);
}
}
// config class
package com.taxig10.demo.config;
import org.springframework.beans.factory.annotation.Autowired;
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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.taxig10.demo.service.PersonaDetailsImpl;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
private PersonaDetailsImpl personaDetails;
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(personaDetails).passwordEncoder(passwordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/","/auth/**","public/**","/css/**","/js/**")
.permitAll().anyRequest().authenticated()
.and()
.formLogin().loginPage("/auth/index/").defaultSuccessUrl("/private/index",true).failureUrl("/auth/login?error=true")
.loginProcessingUrl("/auth/login-post").permitAll()
.and()
.logout().logoutUrl("/logout/").logoutSuccessUrl("public/index");
}
}
// IPersona class
package com.taxig10.demo.interfaces;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.taxig10.demo.modelo.Persona;
#Repository
public interface Ipersona extends CrudRepository<Persona, Integer> {
}
// IpersonaService class
package com.taxig10.demo.interfaceService;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Optional;
import javax.mail.MessagingException;
import com.taxig10.demo.modelo.Persona;
public interface IpersonaService {
public List<Persona> listar();
public Optional<Persona> listarId(int id);
public Persona save(Persona p) throws UnsupportedEncodingException, MessagingException;
public void delete(int id);
boolean login(Persona persona);
int confirm(Persona p);
boolean isAdmin(String name);
void logout(Persona persona);
// ---
public Persona getPersonaFromBD(String name);
public Persona registrar(Persona p);
}
// PersonaService class
package com.taxig10.demo.service;
#Service
public class PersonaService implements IpersonaService {
#Autowired
private Ipersona data;
#Autowired
private BCryptPasswordEncoder passwordEncoder;
#Override
public List<Persona> listar() {
return (List<Persona>)data.findAll();
}
#Override
public Persona getPersonaFromBD(String name) {
Iterator<Persona> personas = data.findAll().iterator();
while(personas.hasNext()) {
Persona cont = personas.next();
if(cont.getName().equals(name)) {
return cont;
}
}
return null;
}
}
// PersonaDetailsImpl class
package com.taxig10.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.User.UserBuilder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.taxig10.demo.interfaceService.IpersonaService;
import com.taxig10.demo.modelo.Persona;
public class PersonaDetailsImpl implements UserDetailsService{
#Autowired
private IpersonaService personaService;
#Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
Persona persona = personaService.getPersonaFromBD(name);
UserBuilder builder = null;
if(persona != null) {
builder = User.withUsername(name);
builder.disabled(false);
builder.password(persona.getPwd());
builder.authorities(new SimpleGrantedAuthority("ROLE_USER"));
} else {
throw new UsernameNotFoundException("Usuario no encontrado");
}
return builder.build();
}
}
Thank you in advance <3
I have simple application that is trying consume Rest service:
#SpringBootApplication
public class ConsumingRestApplication
{
private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);
public static void main(String[] args)
{
SpringApplication.run(ConsumingRestApplication.class, args);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder)
{
return builder.build();
}
#Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception
{
return args -> {
try
{
restTemplate.getForObject("https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
} catch (RestClientException e)
{
e.printStackTrace();
}
};
}
}
Quote class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
#Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
Got error :
org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.consumingrest.Quote] and content type [application/json;charset=UTF-8]
Whole exception trace:
2020-10-19 12:39:04.984 INFO 8328 --- [ restartedMain] c.e.c.ConsumingRestApplication : Starting ConsumingRestApplication on GM with PID 8328 (C:\gdrive\java_test\consumingrest\build\classes\java\main started by g in C:\gdrive\java_test\consumingrest)
2020-10-19 12:39:04.987 INFO 8328 --- [ restartedMain] c.e.c.ConsumingRestApplication : No active profile set, falling back to default profiles: default
2020-10-19 12:39:05.070 INFO 8328 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-10-19 12:39:05.070 INFO 8328 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-10-19 12:39:06.843 INFO 8328 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-10-19 12:39:06.856 INFO 8328 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-10-19 12:39:06.857 INFO 8328 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.38]
2020-10-19 12:39:06.957 INFO 8328 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-10-19 12:39:06.957 INFO 8328 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1887 ms
2020-10-19 12:39:07.204 INFO 8328 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-10-19 12:39:07.395 INFO 8328 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-10-19 12:39:07.603 INFO 8328 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-10-19 12:39:07.617 INFO 8328 --- [ restartedMain] c.e.c.ConsumingRestApplication : Started ConsumingRestApplication in 3.076 seconds (JVM running for 3.545)
2020-10-19 12:39:07.786 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:07.786 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:08.541 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:08.542 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:08.544 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:08.545 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.consumingrest.Quote] and content type [application/json;charset=UTF-8]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:126)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:741)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:315)
at com.example.consumingrest.ConsumingRestApplication.lambda$run$0(ConsumingRestApplication.java:37)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
at com.example.consumingrest.ConsumingRestApplication.main(ConsumingRestApplication.java:21)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
What is starting point o solving this problem? What logic I should go to find problem?
I believe you are missing Value object or must be a wrong import. Along with that you need to add getter methods for the field if they are private, when you are returning that object directly in the response, here is how i have done it:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
#RestController
public static class Test {
#Autowired
private RestTemplate restTemplate;
#GetMapping
public Quote test() {
return restTemplate.getForObject("https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
}
}
public static class Quote {
private String type;
private Value value;
public String getType() {
return type;
}
public Value getValue() {
return value;
}
}
public static class Value {
private Long id;
private String quote;
public Long getId() {
return id;
}
public String getQuote() {
return quote;
}
}
}
When I give domain name in accessTokenUri it doesn't work and reports error but when I provide localhost it works. Why?
Authorization Server Config.java
#Configuration
#EnableAuthorizationServer
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient("QWE123")
.secret("abc")
.authorizedGrantTypes("password")
.scopes("user_info").accessTokenValiditySeconds(0)
.autoApprove(true);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
#EnableResourceServer
#Configuration
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Autowired
private UserDetailsService customUserDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.permitAll();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/user/**","/swagger-ui.html", "/v2/api-docs", "/swagger-resources/**");
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
App.properties
security:
basic:
enabled: false
oauth2:
resource:
filter-order: 3
ResourceServerConfig.java
#EnableOAuth2Sso
#Configuration
public class OauthConfig extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/")
.permitAll()
.anyRequest()
.authenticated();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/swagger-ui.html", "/v2/api-docs", "/swagger-resources/**");
}
}
#Configuration
#EnableResourceServer
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class Oauth2ResourceServerConfig extends GlobalMethodSecurityConfiguration {
#Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
App.properties
security:
basic:
enabled: false
oauth2:
client:
clientId: QWE123
clientSecret: abc
accessTokenUri: https://example.net/auth/oauth/token
userAuthorizationUri: https://example.net/auth/oauth/authorize
resource:
userInfoUri: https://example.net/auth/logged-in/principal
filter-order: 3
Error:
2018-09-14 12:00:13.083 INFO 25836 --- [ main]
o.s.j.e.a.AnnotationMBeanExporter : Located managed bean
'environmentManager': registering with JMX server as MBean
[org.springframework.cloud.context.environment:name=environmentManager,type=EnvironmentManager]
2018-09-14 12:00:13.095 INFO 25836 --- [ main]
o.s.j.e.a.AnnotationMBeanExporter : Located managed bean
'restartEndpoint': registering with JMX server as MBean
[org.springframework.cloud.context.restart:name=restartEndpoint,type=RestartEndpoint]
2018-09-14 12:00:13.106 INFO 25836 --- [ main]
o.s.j.e.a.AnnotationMBeanExporter : Located managed bean
'refreshScope': registering with JMX server as MBean
[org.springframework.cloud.context.scope.refresh:name=refreshScope,type=RefreshScope]
2018-09-14 12:00:13.116 INFO 25836 --- [ main]
o.s.j.e.a.AnnotationMBeanExporter : Located managed bean
'configurationPropertiesRebinder': registering with JMX server as
MBean
[org.springframework.cloud.context.properties:name=configurationPropertiesRebinder,context=35d08e6c,type=ConfigurationPropertiesRebinder]
2018-09-14 12:00:13.123 INFO 25836 --- [ main]
o.s.j.e.a.AnnotationMBeanExporter : Located managed bean
'refreshEndpoint': registering with JMX server as MBean
[org.springframework.cloud.endpoint:name=refreshEndpoint,type=RefreshEndpoint]
2018-09-14 12:00:13.424 INFO 25836 --- [ main]
o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2018-09-14 12:00:13.482 INFO 25836 --- [ main]
o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase
2147483647 2018-09-14 12:00:13.483 INFO 25836 --- [ main]
d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2018-09-14 12:00:13.509 INFO 25836 --- [ main]
d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom
documentation plugin(s) 2018-09-14 12:00:13.530 INFO 25836 --- [
main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api
listing references 2018-09-14 12:00:13.870 INFO 25836 --- [
main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on
port(s): 8080 (http) 2018-09-14 12:00:13.882 INFO 25836 --- [
main] c.h.dfsc.DfscServiceApplication : Started
DfscServiceApplication in 44.8 seconds (JVM running for 45.324)
2018-09-14 12:01:52.271 INFO 25836 --- [nio-8080-exec-1]
o.a.c.c.C.[Tomcat].[localhost].[/api] : Initializing Spring
FrameworkServlet 'dispatcherServlet' 2018-09-14 12:01:52.271 INFO
25836 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet :
FrameworkServlet 'dispatcherServlet': initialization started
2018-09-14 12:01:52.292 INFO 25836 --- [nio-8080-exec-1]
o.s.web.servlet.DispatcherServlet : FrameworkServlet
'dispatcherServlet': initialization completed in 21 ms 2018-09-14
12:01:52.990 WARN 25836 --- [nio-8080-exec-1]
o.s.b.a.s.o.r.UserInfoTokenServices : Could not fetch user details: class
org.springframework.security.oauth2.client.resource.UserRedirectRequiredException,
A redirect is required to get the users approval
I have find a lot on this but no success, could you please help me out?
I have found a solution for this.
It was occurring due to clustering. There were multiple servers instances which authenticate and authorise for token. When request for token generation occurs it stores token on one instance but when authorisation request came, it hits on another instances. Where it does not found the token and generates exception.
on localhost I was having one server only, thus working fine.
I am trying to route a view when I request a specific URL without any Model, so i am using the URLFileNameController to do that, below is my main class and bean declaration for the same.
#SpringBootApplication
public class WebMvcApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CpiWebMvcApplication.class);
}
public static void main(String[] args)
{
ApplicationContext ctx =SpringApplication.run(CpiWebMvcApplication.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames)
{
System.out.println(beanName);
}
}
}
//Bean Declaration -- declared in a separate class
#Configuration
//#ImportResource("*/**/Controller-Beans.xml")
public class BeanConfig {
#Bean
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
#Bean(name = "urlViewController")
public UrlFilenameViewController getUrlViewController() {
UrlFilenameViewController urlViewController = new UrlFilenameViewController();
urlViewController.setSuffix(".jsp");
urlViewController.setPrefix("/WEB-INF/");
urlViewController.setAlwaysUseFullPath(true);
return urlViewController;
}
#Bean
public SimpleUrlHandlerMapping getUrlHandlerMapping() {
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
Properties mappings = new Properties();
mappings.put("*.do", getUrlViewController());
handlerMapping.setMappings(mappings);
return handlerMapping;
}
#Bean
public DispatcherServlet dispatcherServlet() {
return new DispatcherServlet();
}
/**
* Register dispatcherServlet programmatically
*
* #return ServletRegistrationBean
*/
#Bean
public ServletRegistrationBean dispatcherServletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(
dispatcherServlet());
registration.addUrlMappings("*.do");
registration
.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
registration.setLoadOnStartup(-1);
return registration;
}
When I run my spring boot app, I get the following:
2017-01-04 10:43:04.806 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing servlet 'dispatcherServletRegistration'
2017-01-04 10:43:04.807 INFO 24728 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServletRegistration'
2017-01-04 10:43:04.807 INFO 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServletRegistration': initialization started
2017-01-04 10:43:04.807 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Using MultipartResolver [org.springframework.web.multipart.support.StandardServletMultipartResolver#7f1abac0]
2017-01-04 10:43:04.817 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver#621cf3e7]
2017-01-04 10:43:04.830 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.servlet.theme.FixedThemeResolver#41e31325]
2017-01-04 10:43:04.837 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#46a1a74]
2017-01-04 10:43:04.852 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager#56cd7abe]
2017-01-04 10:43:04.852 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Published WebApplicationContext of servlet 'dispatcherServletRegistration' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServletRegistration]
2017-01-04 10:43:04.852 INFO 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServletRegistration': initialization completed in 45 ms
2017-01-04 10:43:04.852 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Servlet 'dispatcherServletRegistration' configured successfully
2017-01-04 10:43:04.879 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServletRegistration' processing GET request for [/logout.do]
2017-01-04 10:43:04.894 DEBUG 24728 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /logout.do
2017-01-04 10:43:04.909 DEBUG 24728 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/logout.do]
2017-01-04 10:43:04.909 DEBUG 24728 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/logout.do] are [/**]
2017-01-04 10:43:04.912 DEBUG 24728 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/logout.do] are {}
2017-01-04 10:43:04.912 DEBUG 24728 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/logout.do] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#720653c2]]] and 1 interceptor
2017-01-04 10:43:04.912 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/logout.do] is: -1
2017-01-04 10:43:04.917 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServletRegistration': assuming HandlerAdapter completed request handling
2017-01-04 10:43:04.917 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Successfully completed request
The logs clearly states that my app is not able to find the view, but I am not able to understand where i am doing wrong, as when i declared a controller with a mapping, i am able to get the view.
#Controller
public class LoginPageController {
#RequestMapping("/secure/main")
//#ResponseBody
public String getLoginpage(Model model, #RequestParam(value="name", required=false, defaultValue="Uttik") String name)
{
model.addAttribute("name", name);
return "unauth";
}
}
I tried even declaring the beans in xml, still it didnt worked. Any idea where i am doing wrong?
Thanks in advance!!