My Spring boot mvc project runs on STS but not running after building jar/war - spring-boot

The pom.xml
4.0.0
<groupId>com.birol</groupId>
<artifactId>EMS_WEB</artifactId>
<version>1.0.1-SNAPSHOT</version>
<name>EMS_WEB</name>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- 2fa -->
<dependency>
<groupId>org.jboss.aerogear</groupId>
<artifactId>aerogear-otp-java</artifactId>
<version>${aerogear.version}</version>
<scope>compile</scope>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>${javax.el.version}</version>
</dependency>
<!-- Password Validation -->
<dependency>
<groupId>org.passay</groupId>
<artifactId>passay</artifactId>
<version>${passay.version}</version>
</dependency>
<!-- Spring Data JPA dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- DB dependencies -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- User Agent parser -->
<dependency>
<groupId>com.github.ua-parser</groupId>
<artifactId>uap-java</artifactId>
<version>${uap-java.version}</version>
</dependency>
<!-- maxmind dependency -->
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>${geoip2.version}</version>
</dependency>
<!-- test -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>${logstash-logback-encoder.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.1-GA</version>
</dependency>
</dependencies>
<build>
<finalName>EMS_WEB</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<java-version>1.8</java-version>
<javax.servlet.jsp-api.version>2.3.2-b01</javax.servlet.jsp-api.version>
<javax.el.version>2.2</javax.el.version>
<jstl.version>1.2</jstl.version>
<guava.version>20.0</guava.version>
<passay.version>1.0</passay.version>
<logstash-logback-encoder.version>4.8</logstash-logback-encoder.version>
<aerogear.version>1.0.0</aerogear.version>
<uap-java.version>1.4.0</uap-java.version>
<geoip2.version>2.15.0</geoip2.version>
</properties>
The error i am getting. this does not happen when i run it on STS as a spring boot project. But after building war , the war wont run
web - 2022-04-30 00:59:20,572 [main] WARN o.s.b.w.s.c.GbHi8bXd2f26Vj8NqmcnHFztp53C1pSdpVjsf9ANBCtpYHvWau - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'registrationListener': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'passwordEncoder'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'secSecurityConfig': Unsatisfied dependency expressed through field 'myAuthenticationSuccessHandler';
Main class. should i add component scanner to this?
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public RequestContextListener requestContextListener() {
return new RequestContextListener();
}
}
RegistrationListener.java . Am i missing any tags/annotations?
#Component
public class RegistrationListener implements
ApplicationListener<OnRegistrationCompleteEvent> {
#Autowired
private IUserService service;
#Autowired
private MessageSource messages;
#Autowired
private JavaMailSender mailSender;
#Autowired
private Environment env;
// API
#Override
public void onApplicationEvent(final OnRegistrationCompleteEvent event) {
this.confirmRegistration(event);
}
private void confirmRegistration(final OnRegistrationCompleteEvent event) {
final User user = event.getUser();
final String token = UUID.randomUUID().toString();
service.createVerificationTokenForUser(user, token);
final SimpleMailMessage email = constructEmailMessage(event, user, token);
mailSender.send(email);
}
//
private SimpleMailMessage constructEmailMessage(final OnRegistrationCompleteEvent event, final User user, final String token) {
final String recipientAddress = user.getEmail();
final String subject = "Registration Confirmation";
final String confirmationUrl = event.getAppUrl() + "/registrationConfirm?token=" + token;
String message= "Your SECRET for Google Authenticator: "+user.getSecret()+"\n";
message+= messages.getMessage("message.regSuccLink", null, "You registered successfully. To confirm your registration, please click on the below link.", event.getLocale());
final SimpleMailMessage email = new SimpleMailMessage();
email.setTo(recipientAddress);
email.setSubject(subject);
email.setText(message + " \r\n" + confirmationUrl);
email.setFrom(env.getProperty("support.email"));
return email;
}
}
IUserService.java Tried both with and without the #Service annotation
#Service
public interface IUserService {
User registerNewUserAccount(UserDto accountDto);
User getUser(String verificationToken);
void saveRegisteredUser(User user);
void deleteUser(User user);
void createVerificationTokenForUser(User user, String token);
VerificationToken getVerificationToken(String VerificationToken);
VerificationToken generateNewVerificationToken(String token);
void createPasswordResetTokenForUser(User user, String token);
User findUserByEmail(String email);
PasswordResetToken getPasswordResetToken(String token);
Optional<User> getUserByPasswordResetToken(String token);
Optional<User> getUserByID(long id);
void changeUserPassword(User user, String password);
boolean checkIfValidOldPassword(User user, String password);
String validateVerificationToken(String token);
String generateQRUrl(User user) throws UnsupportedEncodingException;
User updateUser2FA(boolean use2FA);
List<String> getUsersFromSessionRegistry();
NewLocationToken isNewLoginLocation(String username, String ip);
String isValidNewLocationToken(String token);
void addUserLocation(User user, String ip);
}

Related

Asciidoctor "Snippets" is missing in Maven

When I run the test case then requests and responses of adoc type will be created and displayed in JSON format under the generated-snippets directory. when I run this mvn command mvn clean package to create jar and HTML type of index under the generated-docs then following warning has occurred
when I open the index.html via browser then Unresolved directive in index.adoc is displayed instead of JSON result as a response.
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.oracle/ojdbc6 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4</version>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-asciidoctor</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<finalName>config-demo</finalName>
</configuration>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.6</version>
<executions>
<execution>
<id>generate-docs</id>
<phase>package</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html</backend>
<doctype>product</doctype>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
index.adoc
= Nafaz Benzema Getting Started With Spring REST Docs
This is an example output for a service running at http://localhost:9090:
==GET API Example
.request
include::{snippets}/getAllProduct/http-request.adoc[]
.response
include::{snippets}/getAllProduct/http-response.adoc[]
As you can see the format is very simple, and in fact you always get the same message.
Controller Test class
#ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
#WebMvcTest
#AutoConfigureRestDocs(outputDir = "/target/generated-snippets")
public class ProductControllerTest {
#Autowired
private WebApplicationContext webApplicationContext;
#MockBean
private ProductService productService;
private MockMvc mockMvc;
List<Product> products =null;
#BeforeEach
public void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider documentationContextProvider) {
this.mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(MockMvcRestDocumentation.documentationConfiguration(documentationContextProvider))
.build();
products=getProducts();
}
#Test
public void getAllProduct() throws Exception {
String expectedProduct=new ObjectMapper().writeValueAsString(products);
Mockito.when(productService.getAllProduct()).thenReturn(products);
MvcResult result= mockMvc.perform(get("/products")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andExpect(content().json(expectedProduct))
.andDo(document("{methodName}",preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint())))
.andReturn();
String actualProduct=result.getResponse().getContentAsString();
Assertions.assertEquals(expectedProduct,actualProduct);
}
private List<Product> getProducts()
{
Product product_1=new Product();
product_1.setProductId(1001);
product_1.setProductName("Penguin-ears");
product_1.setNumberOfUnitInCartoon(20);
product_1.setPriceOfCartoon(175.00);
product_1.setUrlOfImage("https://i.ibb.co/pLdM7FL/shutterstock-306427430-scaled.jpg");
Product product_2=new Product();
product_2.setProductId(1002);
product_2.setProductName("Horseshoe");
product_2.setNumberOfUnitInCartoon(5);
product_2.setPriceOfCartoon(825);
product_2.setUrlOfImage("https://i.ibb.co/MRDwnqj/horseshoe.jpg");
return new ArrayList<>(Arrays.asList(product_1,product_2));
}
}
The solution has been found. We have to add spring-restdocs-asciidoctor dependency inside the plugin which it belongs.
Remove spring-restdocs-asciidoctor dependency from the global dependency management space and add it inside the plugin
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.6</version>
<executions>
<execution>
<id>generate-docs</id>
<phase>package</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html</backend>
<doctype>product</doctype>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-asciidoctor</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>
</dependencies>
</plugin>

Could not resolve placeholder for JavaFX application with Spring Boot

I have a problem using Spring boot with JavaFX. I have the following error when starting my new application:
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.application.ui.title' in value "${spring.application.ui.title}"
I follow this tutorial: https://blog.jetbrains.com/idea/2019/11/tutorial-reactive-spring-boot-a-javafx-spring-boot-application/ to create it.
So here are my classes:
#SpringBootApplication
public class AgricultureApplication {
public static void main(String[] args) {
Application.launch(ApplicationStartUp.class,args);
}
}
public class ApplicationStartUp extends Application {
private ConfigurableApplicationContext applicationContext;
#Override
public void init() {
applicationContext = new SpringApplicationBuilder(AgricultureApplication.class).run();
}
#Override
public void stop(){
applicationContext.close();
Platform.exit();
}
#Override
public void start(Stage primaryStage){
applicationContext.publishEvent(new StageReadyEvent(primaryStage));
}
public static void main(String[] args) {
launch(args);
}
}
#Component
public class StageInitializer implements ApplicationListener<StageReadyEvent> {
private final String applicationTitle;
private ApplicationContext applicationContext;
public StageInitializer(#Value("${spring.application.ui.title}") String applicationTitle, ApplicationContext applicationContext){
super();
this.applicationTitle = applicationTitle;
this.applicationContext = applicationContext;
}
#Override
public void onApplicationEvent(StageReadyEvent stageReadyEvent) {
final Stage primaryStage = stageReadyEvent.getStage();
try {
FXMLLoader fxmlLoader = new FXMLLoader(new ClassPathResource("/main.fxml").getURL());
fxmlLoader.setControllerFactory(aClass -> applicationContext.getBean(aClass));
Parent parent = fxmlLoader.load();
Scene scene = new Scene(parent);
primaryStage.setResizable(false);
primaryStage.setScene(scene);
primaryStage.setTitle(applicationTitle);
primaryStage.show();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
public class StageReadyEvent extends ApplicationEvent {
public StageReadyEvent(Stage stage) {
super(stage);
}
public Stage getStage() {
return (Stage) this.getSource();
}
}
This is application.properties file:
spring.datasource.url=jdbc:h2:file:./AgricultureRentDb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.main.web-application-type=none
spring.application.ui.title = "Test"
spring.h2.console.enabled=true
And my POM.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>gtech</groupId>
<artifactId>agriculturerent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.20.Final</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>29.0-jre</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>16-ea+1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Here is my project strucutre:
I think spring doesn't recognize application.properties file and i do not why, i've tried to add even the #PropertySource annotation and put absolute path to the application.properties file or to put it as classpath.
Just for notice that when i follow the tutorial i am using java 8 instead of java 11, but i do not think that's making the problem.
EDITED:
Here is my github link for the project: https://github.com/Dilyan-Galabov/Agriculture
Can you please help me to provide the problem, thank you in advance :)!
Firstly #James_D found there is a problem copying the resources files to the target folder. Actually they are not copied anyway even if i add this to my pom.xml:
<resources>
<resource>
<directory>src/main/resources</directory>
<targetPath>${project.build.outputDirectory}</targetPath>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
Even if i try to set different targetPath the problem occurs(doesn't copying the files to targetPath) and actually i think that maven does not read that code in the pom and i do not know why this is happening.

Springboot app deployed in CloudFoundry - Get and Post operation on db fail

I am building a sample Spring application that will expose a REST
API to get and post data to a table in a database. Building the basic stuff.
I am using PostgreSQL for the data source in Cloud Foundry.
The GET API which returns a string works fine. The API which does POST returns 404 Not Found. The API which returns the entries in the table throws an exception.
Type Exception Report
Message Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DatabaseException
Description:
The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax error at or near "GROUP"
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#Configuration
#EnableJpaRepositories(basePackageClasses =
CustomerFeedbackRepository.class)
#Profile("cloud")
public class CloudDatabaseConfig extends AbstractCloudConfig {
#Bean
public DataSource dataSource() {
List<String> dataSourceNames =
Arrays.asList("BasicDbcpPooledDataSourceCreator","TomcatJdbcPooledDataSourceCreator","HikariCpPooledDataSourceCreator","TomcatDbcpPooledDataSourceCreator");
DataSourceConfig dbConfig = new DataSourceConfig(dataSourceNames);
return connectionFactory().dataSource(dbConfig);
}
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
return EntityManagerFactoryProvider.get(dataSource, CustomerFeedback.class.getPackage().getName());
}
#Bean(name = "transactionManager")
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
#PostMapping("/capturecf")
#RequestMapping(value ="CustomerFeedback", method = RequestMethod.POST)
public CustomerFeedback addFeedback(#RequestBody CustomerFeedback custfeedback)
{
return customerfeedbackrepo.save(custfeedback);
}
#PostMapping("/captureua")
#RequestMapping(value = "UsageActivity", method = RequestMethod.POST)
public UsageActivity addUsageTracking(#Valid #RequestBody UsageActivity usageActivity)
{
return usageactivityrepository.save(usageActivity);
}
#GetMapping("/usageactivity")
public List<UsageActivity> getAllNotes() {
return usageactivityrepository.findAll();`enter code here`
}
<dependencies>
<!-- APIs for servlets and injection -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Spring Framework and Spring WebMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Logging library -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>com.sap.hcp.cf.logging</groupId>
<artifactId>cf-java-logging-support-logback</artifactId>
<version>${sap.logging.version}</version>
</dependency>
<dependency>
<groupId>com.sap.hcp.cf.logging</groupId>
<artifactId>cf-java-logging-support-servlet</artifactId>
<version>${sap.logging.version}</version>
</dependency>
<!-- JSON conversion -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<!-- Actuator for adding management endpoints -->
<dependency>
<groupId> org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
<!-- Bean validation (#NotNull etc.) -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency>
<!-- MethodValidationPostProcessor relies on Expression Language -->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.1-b04</version>
</dependency>
<!-- Spring Cloud Connector -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-spring-service-connector</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-cloudfoundry-connector</artifactId>
<version>1.2.1.RELEASE</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.2.RELEASE</version>
<exclusions>
<exclusion>
<!-- We need spring-core 4.2 or later, but spring-data includes 4.1.9 -->
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- EclipseLink as JPA implementation -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.6.2</version>
</dependency>
<!-- PostgreSQL database implementations -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1206-jdbc41</version>
<scope>runtime</scope>
</dependency>
<!-- connection pooling -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
<scope>runtime</scope>
</dependency>
<!-- Testing -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- Use MockMvcResultMatchers.jsonPath to assert the JSON body -->
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
<scope>test</scope>
</dependency>
<!-- H2 (in-memory) database implementation -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.184</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>customerconnect</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<!-- Provides the application at http://localhost:8080/ using an embedded
Tomcat server with a pre-configured environment referencing the SAP proxy -->
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>${maven.tomcat.port}</port>
<path>/</path>
<systemProperties>
<http.proxyHost>${http.proxyHost}</http.proxyHost>
<http.proxyPort>${http.proxyPort}</http.proxyPort>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>3.0.2</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>findbugs</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.5</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>pmd</goal>
<goal>cpd</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.5.201505241946</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<version>2.5</version>
</plugin>
</plugins>
</reporting>
</project>
package com.sap.customerconnect.ads.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.sap.customerconnect.ads.models.UsageActivity;
import com.sap.customerconnect.ads.models.UsageActivityPK;
#Component
#Repository
public interface UsageActivityRepository extends JpaRepository<UsageActivity, UsageActivityPK> {
}
package com.sap.customerconnect.ads.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.sap.customerconnect.ads.models.CustomerFeedback;
import com.sap.customerconnect.ads.models.CustomerFeedbackPK;
#Component
#Repository
public interface CustomerFeedbackRepository extends JpaRepository<CustomerFeedback, CustomerFeedbackPK>{
}
package com.sap.customerconnect.ads.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
#IdClass(UsageActivityPK.class)
#Entity
#Table(name = "UsageActivity")
public class UsageActivity {
#Id
#Column(name = "PRODUCT_ID")
private String ProductId;
#Id
#Column(name = "CUSTOMER_ID")
private String CustomerId;
#Id
#Column(name = "SCREEN_ID")
private String ScreenId;
#Column(name = "GROUP")
private String Group;
#Column(name = "ACTION")
private String Action;
#Column(name = "DESCRIPTION")
private String Description;
#Column(name = "COUNT")
private Integer Count;
public UsageActivity() {
}
public String getProductId() {
return ProductId;
}
public void setProductId(String productId) {
ProductId = productId;
}
public String getCustomerId() {
return CustomerId;
}
public void setCustomerId(String customerId) {
CustomerId = customerId;
}
public String getScreenId() {
return ScreenId;
}
public void setScreenId(String screenId) {
ScreenId = screenId;
}
public String getGroup() {
return Group;
}
public void setGroup(String group) {
Group = group;
}
public String getAction() {
return Action;
}
public void setAction(String action) {
Action = action;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public Integer getCount() {
return Count;
}
public void setCount(Integer count) {
Count = count;
}
public UsageActivity(String productId, String customerId, String screenId, String group, String action,
String description, Integer count) {
super();
ProductId = productId;
CustomerId = customerId;
ScreenId = screenId;
Group = group;
Action = action;
Description = description;
Count = count;
}
}
package com.sap.customerconnect.ads.models;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class UsageActivityPK implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "PRODUCT_ID")
private String ProductId;
#Column(name = "CUSTOMER_ID")
private String CustomerId;
#Column(name = "SCREEN_ID")
private String ScreenId;
}
The POST and GET operations on the repository does not work.

CAS Maven Overlay And Spring Boot do not work together

I create a spring boot application from spring.io, then add CAS dependecy to pom file of project as below.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.apereo.cas</groupId>
<artifactId>cas-server-webapp</artifactId>
<version>${cas.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<overlays>
<overlay>
<groupId>org.apereo.cas</groupId>
<artifactId>cas-server-webapp</artifactId>
</overlay>
</overlays>
</configuration>
</plugin>
</plugins>
</build>
after that start spring boot application, but CAS does not start in spring boot application.
what is the main problem in this usage of CAS?
Is the method of using the CAS at this way wrong?
_____________________________________________________________
finaly I solve my problem. I change the pom file as below
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<javaparser-core.version>3.12.0</javaparser-core.version>
<start.class>org.apereo.cas.web.CasWebApplication</start.class>
<start.class2>x.y.sso.SingleSignOnApplication</start.class2>
<h2.version>1.4.197</h2.version>
<cas.version>6.0.1</cas.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apereo.cas</groupId>
<artifactId>cas-server-webapp-tomcat</artifactId>
<version>${cas.version}</version>
<type>war</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>
<version>${javaparser-core.version}</version>
</dependency>
<dependency>
<groupId>org.apereo.cas</groupId>
<artifactId>cas-server-core-configuration</artifactId>
<version>${cas.version}</version>
</dependency>
<dependency>
<groupId>org.apereo.cas</groupId>
<artifactId>cas-server-core-configuration</artifactId>
<version>${cas.version}</version>
</dependency>
</dependencies>
<build>
<finalName>cas</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>${start.class2}</mainClass>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<!--<recompressZippedFiles>false</recompressZippedFiles>-->
<archive>
<compress>false</compress>
<manifestFile>
${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp-tomcat/META-INF/MANIFEST.MF
</manifestFile>
</archive>
<overlays>
<overlay>
<groupId>org.apereo.cas</groupId>
<artifactId>cas-server-webapp-tomcat</artifactId>
</overlay>
</overlays>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
then I create a Application class
#EnableDiscoveryClient
#SpringBootApplication(exclude = {
HibernateJpaAutoConfiguration.class,
JerseyAutoConfiguration.class,
JmxAutoConfiguration.class,
DataSourceAutoConfiguration.class,
DataSourceHealthIndicatorAutoConfiguration.class,
RedisAutoConfiguration.class,
MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class,
CassandraAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
RedisRepositoriesAutoConfiguration.class})
#EnableConfigurationProperties({CasConfigurationProperties.class})
#EnableAsync
#EnableTransactionManagement(proxyTargetClass = true)
#EnableScheduling
public class SingleSignOnApplication {
public static void main(String[] args) {
SpringApplication.run(SingleSignOnApplication.class, args);
}
}
by this configuration, build maven goal and execution project by spring boot work correctly.
CAS is already a spring boot web application. Therefor have a look into cas-server-webapp-init-6.0.1.jar and look CasWebApplication.java.
#EnableDiscoveryClient
#SpringBootApplication(exclude={HibernateJpaAutoConfiguration.class, JerseyAutoConfiguration.class, GroovyTemplateAutoConfiguration.class, JmxAutoConfiguration.class, DataSourceAutoConfiguration.class, DataSourceHealthIndicatorAutoConfiguration.class, RedisAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, CassandraAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class})
#EnableConfigurationProperties({CasConfigurationProperties.class})
#EnableAsync
#EnableTransactionManagement(proxyTargetClass=true)
#EnableScheduling
public class CasWebApplication
{
public static void main(String[] args)
{
Map<String, Object> properties = CasEmbeddedContainerUtils.getRuntimeProperties(Boolean.TRUE);
Banner banner = CasEmbeddedContainerUtils.getCasBannerInstance();
new SpringApplicationBuilder(new Class[] { CasWebApplication.class })
.banner(banner)
.web(WebApplicationType.SERVLET)
.properties(properties)
.logStartupInfo(true)
.contextClass(CasWebApplicationContext.class)
.run(args);
}
}
Remove the spring-boot-starter dependencies and CAS should start itself as a web application.
For further investigation I would recommend you to download the war from https://search.maven.org/artifact/org.apereo.cas/cas-server-webapp/6.0.1/war and inspect it with a tool like jd-gui.

configure security for Spring Boot 2.0 acuator framework when upgraded from spring boot 1.5

I migrated my spring boot rest service to use spring boot 2.0.2 and facing problems with actuator endpoints. I know spring boot removed the auto config security to the actuator framework in spring 2.0.2. So I think i had to specify the security in order to access those endpoints but i already had a security configured for my web service to use JWT. please suggest me how i can enable actuator endpoint in spring boot 2.0.2 and also have security configured for actuator enpoints with out impacting Jwt
pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<properties>
<jacoco.version>0.7.8</jacoco.version>
<java.version>1.8</java.version>
<mockito.version>2.7.22</mockito.version>
<mybatis.version>3.4.4</mybatis.version>
<mybatis.spring.version>1.3.1</mybatis.spring.version>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Uncomment this plugin after you have initialized the git repo. -->
<!--
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
</plugin>
-->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
<goal>check</goal>
<goal>report</goal>
</goals>
</execution>
</executions>
<configuration>
<rules>
<rule>
<element>CLASS</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>1.00</minimum>
</limit>
<limit>
<counter>BRANCH</counter>
<value>COVEREDRATIO</value>
<minimum>1.00</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<reportSets>
<reportSet>
<reports>
<report>report</report>
</reports>
</reportSet>
</reportSets>
</plugin>
</plugins>
</reporting>
<dependencies>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.ibm.db2.jcc</groupId>
<artifactId>db2jcc_license_cisuz</artifactId>
<version>DB2V11</version>
</dependency>
<dependency>
<groupId>com.ibm.db2.jcc</groupId>
<artifactId>db2jcc4</artifactId>
<version>4.19.26</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-properties-migrator</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
Integration test yaml
mybatis:
configuration-properties:
schema: abcd
spring:
datasource:
url:
username:
password:
management:
endpoints:
web:
exposure:
include: "*"
The security config is below
#Configuration
#EnableResourceServer
public class SecurityConfiguration implements
JwtAccessTokenConverterConfigurer {
#Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws
Exception {
auth.inMemoryAuthentication().withUser("management").password("cfh5r64r
bvc54r").roles("ACTUATOR");
}
#Bean
public FilterRegistrationBean corsFilter() {
// Set CORS configuration to allow cross-origin requests by default.
// Addtionally add the HTTP OPTIONS method for pre-flight requests.
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.applyPermitDefaultValues();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedMethod(HttpMethod.GET);
corsConfiguration.addAllowedMethod(HttpMethod.POST);
corsConfiguration.addAllowedMethod(HttpMethod.PUT);
corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS);
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(
new CorsFilter(urlBasedCorsConfigurationSource));
filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return filterRegistrationBean;
}
#Override
public void configure(JwtAccessTokenConverter converter) {
converter.setAccessTokenConverter(new DefaultAccessTokenConverter() {
#Override
public OAuth2Authentication extractAuthentication(Map<String, ?>
map) {
Object i = map.get();
Object e = map.get();
if (issuerClaim == null || !issuer.equals(issuerClaim) || expirationClaim == null) {
throw new InvalidTokenException("");
}
return super.extractAuthentication(map);
}
});
}
}
I'm trying to write integration tests as below
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.MOCK)
#AutoConfigureMockMvc
#ActiveProfiles("it")
#DirtiesContext
public class SecurityConfigurationIT {
#Test
#WithMockUser(roles = VALID_ACTUATOR_ROLE)
public void should_be_authorized_for_actuator() throws Exception {
mockMvc.perform(get(LOGGERS).header(HttpHeaders.ORIGIN,
ORIGIN)).andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN,
ORIGIN));
}
#Test
#WithMockUser(roles = INVALID_ACTUATOR_ROLE)
public void should_fail_as_forbidden_for_actuator() throws Exception {
mockMvc.perform(get(LOGGERS).header(HttpHeaders.ORIGIN,
ORIGIN)).andExpect(status().isForbidden())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN,
ORIGIN));
}
}
When I'm trying to run it getting 401 but this is working in spring boot 1.5.x
MockHttpServletRequest:
HTTP Method = GET
Request URI = /actuator/info
Parameters = {}
Headers = {Origin=[test.com]}
Body = null
Session Attrs = {}
Handler:
Type = null
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 401
Error message = null
Headers = {Vary=[Origin, Access-Control-Request-Method, Access-
Control-Request-Headers], Access-Control-Allow-Origin=[test.com],
Access-Control-Allow-Credentials=[true], Cache-Control=[no-store],
Pragma=[no-cache], WWW-Authenticate=[Bearer realm=",
error="unauthorized", error_description="Full
authentication is required to access this resource"], Content-Type=
[application/json;charset=UTF-8], X-Content-Type-Options=[nosniff], X-
XSS-Protection=[1; mode=block], X-Frame-Options=[DENY]}
Content type = application/json;charset=UTF-8
Body = {"error":"**unauthorized","error_description":"Full
authentication is required to access this resource"**}
Forwarded URL = null
Redirected URL = null
If you have http security in your pom, you have to override configure otheriwse default it will required authentication and will throw 401 for all end points.
So you should have below config and handle according to your end points and roles, you might have to also call jwtAccessTokenConverterConfiguration for end points which required to check Authentication. (I don't think, this jwtAccessTokenConverterConfiguration is even called, did you debug?)
Below is sample which will pass all your end points from authentication, modify as per your need.
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").permitAll();
}
}

Resources