I have a springboot application that ingests an application.properties via #ConfigurationProperties and #PropertySource("classpath:application.properties"). My desire is to reload these properties on the fly for the purposes of support. When I POST to http://localhost:8080/actuator/refresh I get a 200 OK response but the body is empty, which I think implies no #RefreshScopes have been refreshed but I'm not sure. I have read and viewed most docs and SO while trying various things but haven't managed to reload a new value.
Here is my app:
application.properties:
# suppress inspection "UnusedProperty" for whole file
# the name of Camel
camel.springboot.name = IntegrationsCamel
# how often to trigger the timer (millis)
myPeriod = 2000
spring.main.allow-bean-definition-overriding=true
# to turn off Camel info in (/actuator/info)
management.info.camel.enabled=false
# to configure logging levels
logging.level.org.springframework = INFO
logging.level.org.apache.camel.spring.boot = INFO
logging.level.org.apache.camel.impl = DEBUG
logging.level.sample.camel = DEBUG
# Environment
integration.env = DEV
spring.application.name = integration
spring.config.import=aws-parameterstore:
# Client API Auth -- Set by Instance
integration.client.auth.key = tempclientkey
integration.client.auth.secret = tempclientsecret
# Client API Credentials -- Set by Instance
integration.client.endpoint = https://127.0.0.2
integration.client.port = 6060
# AWS Paramstore Config
aws.paramstore.enabled=true
aws.paramstore.prefix=/integration
aws.paramstore.defaultContext=application
aws.paramstore.profile-separator=_
# AWS OAuth
cloud.aws.credentials.instance-profile=true
cloud.aws.credentials.profile-name=default
cloud.aws.credentials.access-key=${AWS_ACCESS_KEY_ID}
cloud.aws.credentials.secret-key=${AWS_SECRET_ACCESS_KEY}
# Non EC2 vars (remove when running live)
cloud.aws.stack.auto=false
cloud.aws.region.static=eu-west-1
AWS_EC2_METADATA_DISABLED=true
logging.level.com.amazonaws.util.EC2MetadataUtils=error
logging.level.com.amazonaws.internal.InstanceMetadataServiceResourceFetcher=error
# DB Vars
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://${RDS_HOSTNAME:my-server-domain.com}:${RDS_PORT:1337};databaseName=${RDS_DB_NAME:MYDB}
spring.datasource.username=${RDS_USERNAME:readuser}
spring.datasource.password=${RDS_PASSWORD:${read_pass}}
spring.jpa.properties.hibernate.default_schema=dbo
# Actuator Management
management.endpoints.enabled-by-default=false
management.endpoint.refresh.enabled=true
management.endpoints.web.exposure.include=refresh
All of these are successfully pulled in to the bean
package com.Integration.Configuration;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.event.EventListener;
#Getter
#Setter
#RefreshScope
#Configuration
public class ApplicationProperties {
#Value("${integration.env}")
private String env;
#Value("${spring.datasource.url}")
private String DB_URL;
#Value("${rds-username}")
private String DB_USERNAME;
#Value("${rds-password}")
private String DB_ENCRYPTED_PASSWORD;
#Value("${oauth2.key}")
private String OAuth2Key;
#Value("${oauth2.secret}")
private String OAuth2Secret;
#Value("${integration.client.endpoint}")
private String ClientAPIEndpoint;
#Value("${integration.client.port}")
private String ClientAPIPort;
#Value("${integration.client.auth.key}")
private String ClientAPIKey;
#Value("${integration.client.auth.secret}")
private String ClientAPISecret;
public ApplicationProperties() {}
#SuppressWarnings("unused")
#EventListener(RefreshScopeRefreshedEvent.class)
public void onRefresh(RefreshScopeRefreshedEvent event) {
// todo: Bug-#01 #RefreshScope actuator/refresh not updating #Values
System.out.println(this.ClientAPIEndpoint);
}
}
The event listener fires without issue too and it will successfully print the value from application.properties. I have debugged main below and all values are populated without issue.
I suspect the issue is here but I'm not sure what I'm doing wrong in main()
package com.Integration;
import com.Integration.AutoLoader.RouteBuilderAutoLoader;
import com.Integration.Configuration.ApplicationProperties;
import com.Integration.Scheduler.TasksScheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import java.util.Objects;
#SpringBootApplication
#RefreshScope
#EnableScheduling
public class Integration {
public static String SERVER_ADDR;
protected static CamelContext context;
public static void main(String[] args) throws Exception {
// Spring Boot App Entry
ConfigurableApplicationContext appContext = SpringApplication.run(Integration.class, args);
// Get ApplicationProperties
ApplicationProperties properties = appContext.getBean(ApplicationProperties.class);
SERVER_ADDR = (Objects.equals(properties.getEnv(), "DEV")) ? "0.0.0.0" : "localhost";
// Start Camel Context Engine
context = new DefaultCamelContext();
// Feed Camel our defined routes & start
RouteBuilderAutoLoader.loadRoutes(context);
context.start();
}
}
The last thing I'm unsure of is if I have the necessary dependencies or if I'm missing something here.
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress MavenPackageUpdate -->
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.Integration</groupId>
<artifactId>Integration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Integration</name>
<description>Generic API Integration App</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR12</spring-cloud.version>
</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>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>9.4.1.jre8</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2021.0.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- AWS/Cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-aws</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-context</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-starter-aws-parameter-store-config</artifactId>
<version>2.4.0</version>
</dependency>
<!-- Camel 3.14.1 Latest LTS version -->
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-spring-boot-bom</artifactId>
<version>3.14.1</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>3.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core-languages</artifactId>
<version>3.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-bean</artifactId>
<version>3.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-rest</artifactId>
<version>3.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-direct</artifactId>
<version>3.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-netty-http</artifactId>
<version>3.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-platform-http</artifactId>
<version>3.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-management</artifactId>
<version>3.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-endpointdsl</artifactId>
<version>3.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-spring</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>4.3.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
Edit 12/04/2022
Completely redid my classes with #ConfigurationProperties
So when I post to refresh the values in propertySource for AWS automatically update. So eg I change cobaltdlt to cobaltdlttest below, hit refresh, and then I can see the change when I query GET http://localhost:8080/actuator/env
So the refresh is working but it's not reflective in the #Component beans even though the propertySource is updating. In fact the only beans it is working with are the AWS beans.
Have you tried a PropertiesConfiguration bean? See here: https://www.baeldung.com/spring-reloading-properties.
Once configured correctly, it should automatically read changes to your properties file and reload them. Also, there are some limitations that are mentioned in that article that you should be aware of.
#I2obiN. As you have mentioned that ApplicationProperties is getting refreshed by Refresh Scopes, therefore actuator refresh is working properly.
But I noticed that you are using RefreshScope on main application class. IMO this actuator management/refresh will not restart application. You can try to create an extra method that reinitializes Camel Context.
Hope this helps!!
https://www.baeldung.com/java-restart-spring-boot-app#actuators-restart-endpoint
You can invoke the refresh Actuator endpoint by sending an empty HTTP POST to the client's refresh endpoint: http://localhost:8080/actuator/refresh . Then you can confirm it worked by visiting the http://localhost:8080/message endpoint.
And once you refresh, try to rebind immediately by calling the POST endpoint http://localhost:8080/actuator/env
This worked on a spring boot I tried and it reloads the values and you can see it in the stack trace.
I tried doing a field in spring data source with the given payload to Rebind and it reloads Example as the value.
Payload:
{"name":"spring.datasource.userName", "value":"Example"}
In the application.properties, add the following
management.endpoint.env.post.enabled=true
management.endpoint.restart.enabled=true
endpoints.sensitive=true
endpoints.actuator.enabled=true
management.security.enabled=false
management.endpoints.web.exposure.include=*
Related
I'm new in Spring Boot, I'm trying to build a simple application with REST Api, and I'm getting this error immediately when starting the app:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-01-24 20:08:19.505 ERROR 11344 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
An attempt was made to call a method that does not exist. The attempt was made from the following location:
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration.requestMappingHandlerAdapter(WebMvcAutoConfiguration.java:369)
The following method did not exist:
'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration.requestMappingHandlerAdapter(org.springframework.web.accept.ContentNegotiationManager, org.springframework.format.support.FormattingConversionService, org.springframework.validation.Validator)'
The method's class, org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration, is available from the following locations:
jar:file:/C:/Users/user/.m2/repository/org/springframework/spring-webmvc/5.1.3.RELEASE/spring-webmvc-5.1.3.RELEASE.jar!/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class
The class hierarchy was loaded from the following locations:
org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: file:/C:/Users/user/.m2/repository/org/springframework/spring-webmvc/5.1.3.RELEASE/spring-webmvc-5.1.3.RELEASE.jar
org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport: file:/C:/Users/user/.m2/repository/org/springframework/spring-webmvc/5.1.3.RELEASE/spring-webmvc-5.1.3.RELEASE.jar
Action:
Correct the classpath of your application so that it contains a single, compatible version of org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration
Process finished with exit code 0
I did not finish yet with the development of the app, but I can't go on because of this errors.
There are my classes so far:
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>micro1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>micro1</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<!-- <version>1.4.200</version>-->
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
</plugin>
</plugins>
</build>
</project>
controller:
package com.example.micro1.controllers;
import com.example.micro1.entities.User;
import com.example.micro1.services.Service;
import lombok.Data;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping("/users")
#Data
public class Controller {
private final Service service;
#PostMapping
User addNewUser(#RequestBody User user){
return service.add(user);
}
}
service:
package com.example.micro1.services;
import com.example.micro1.entities.User;
import com.example.micro1.repositories.Repository;
import lombok.Data;
#org.springframework.stereotype.Service
#Data
public class Service {
private final Repository repository;
public User add(User user){
return repository.save(user);
}
}
repository:
package com.example.micro1.repositories;
import com.example.micro1.entities.User;
import org.springframework.data.jpa.repository.JpaRepository;
#org.springframework.stereotype.Repository
public interface Repository extends JpaRepository<User, Integer> {
#Override
<S extends User> S save(S s);
}
One entity for now:
package com.example.micro1.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String phoneNumber;
}
application.properties:
#h2
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
The application class:
package com.example.micro1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Micro1Application {
public static void main(String[] args) {
SpringApplication.run(Micro1Application.class, args);
}
}
Please tell me if there is something else that I should write here...
Thanks!
Your starter spring-boot-starter-web contains inside itself these dependencies
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.3</version>
<scope>compile</scope>
</dependency>
besides, you add in your pom.xml that:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
so, when you'll start your application you have in classpath ambiguity. I think it's cause of your problem.
Spring Boot starters save you the trouble of specifying explicitly declare dependency.
Try to remove spring-webmvc dependency.
I had this same issue when I run a Spring Boot Application of Web. But I got following error messages:
***************************
APPLICATION FAILED TO START
***************************
Description:
An attempt was made to call a method that does not exist. The attempt was made from the following location:
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration.configureHandlerExceptionResolvers(WebMvcAutoConfiguration.java:519)
The following method did not exist:
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration.addDefaultHandlerExceptionResolvers(Ljava/util/List;)V
The method's class, org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration, is available from the following locations:
jar:file:/Users/itzhouq/dev/mavne_repository/org/springframework/boot/spring-boot-autoconfigure/2.1.6.RELEASE/spring-boot-autoconfigure-2.1.6.RELEASE.jar!/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class
It was loaded from the following location:
file:/Users/itzhouq/dev/mavne_repository/org/springframework/boot/spring-boot-autoconfigure/2.1.6.RELEASE/spring-boot-autoconfigure-2.1.6.RELEASE.jar
Action:
Correct the classpath of your application so that it contains a single, compatible version of org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration
This may be spring-boot-autoconfigure's exception.So, I checked the dependency of this.
org.springframework.boot:spring-boot-web:2.2.1.RELEASE--> org.springframework.boot:spring-boot-starter:2.2.1.RELEASE -->
org.springframework.boot:spring-boot-autoconfigure:2.2.1.RELEASE(omitted for conflict with 2.1.6.RELEASE). Obviously, the autoconfigure was losing because of version conflict.For solve this problem, I added the following dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
confirm this dependency had be added in the module and reruned the application.
Add one more dependency is Spring-webMVC because spring web MVC is using for deploying your project
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.3</version>
<scope>compile</scope>
</dependency
i am trying to print the output written in the step definitions into eclipse console. but i do not see any output in the console
i have added these below dependencies into my project and i have also included "pretty" and monochrome :true in the runner class
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sampleProject</groupId>
<artifactId>sampleProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>sampleProject</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-core -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-core</artifactId>
<version>4.7.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.8</version>
<scope>system</scope>
<systemPath>${java.home}\lib\tools-1.8.0.jar</systemPath>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>4.7.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>4.7.1</version>
</dependency>
<dependency>
<groupId>net.sourceforge.cobertura</groupId>
<artifactId>cobertura</artifactId>
<version>2.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.masterthought</groupId>
<artifactId>cucumber-reporting</artifactId>
<version>4.8.0</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-jvm-deps</artifactId>
<version>1.0.6</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-jvm -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-jvm</artifactId>
<version>4.7.1</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>gherkin</artifactId>
<version>5.1.0</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-html</artifactId>
<version>0.2.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit-dep -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<version>4.11</version>
<type>pom</type>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-testng -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>4.7.1</version>
</dependency>
</dependencies>
</project>
for example if i print any thing in my step definitions like
System.out.println("2+2");
when i ran this code, only see the below lines in the console
[RemoteTestNG] detected TestNG version 6.14.3
Starting ChromeDriver 76.0.3809.68 (420c9498db8ce8fcd190a954d51297672c1515d5-refs/branch-heads/3809#{#864}) on port 9315
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Aug 02, 2019 11:54:35 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Feature: Check addition in Google calculatorcontent
In order to verify that Google calculator work correctly
As a user of Google
I should be able to get correct addition result
Scenario: Addition # src/main/java/Features/sample.feature:6
Given I open Google # SampleStepDef.I_open_google()
When I enter "2+2" in search textbox # SampleStepDef.I_enter_in_search_textbox(String)
Then I should get result as "4" # SampleStepDef.I_should_get_correct_result(String)
PASSED: runScenario("Addition", "Check addition in Google calculatorcontent")
Runs Cucumber Scenarios
===============================================
the console does not display anything else other than this.
it also does not display the number of scenarios and steps passed or failed like
1 Scenarios ([33m1 undefined[0m)
3 Steps ([33m3 undefined[0m)
0m0.000s
And here is my tesRunner code
package Runner;
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
#CucumberOptions(
features = "src/main/java/Features",
glue = {"StepDefinitions"},
// tags = "#SmokeTest",
monochrome = true,
dryRun = false,
strict = true,
plugin = {
"pretty",
"html:target/cucumber-reports/cucumber-pretty",
"json:target/cucumber-reports/CucumberTestReport.json",
"rerun:target/cucumber-reports/rerun.txt"
}
)
public class TestRunner extends AbstractTestNGCucumberTests {
}
and stepDefifnition code
package StepDefinitions;
import java.util.concurrent.TimeUnit;
import org.testng.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
public class SampleStepDef {
protected WebDriver driver;
private static Logger Log = Logger.getLogger(Logger.class.getName());
#Before
public void setup() {
System.setProperty("webdriver.chrome.driver","C:\\Users\\Admin\\Downloads\\chromedriver.exe");
driver = new ChromeDriver();
}
#Given("^I open Google$")
public void I_open_google() {
//Set implicit wait of 10 seconds and launch google
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.google.co.in");
}
#When("^I enter \"([^\"]*)\" in search textbox$")
public void I_enter_in_search_textbox(String additionTerms) {
//Write term in google textbox
WebElement googleTextBox = driver.findElement(By.id("gbqfq"));
googleTextBox.sendKeys(additionTerms);
//Click on searchButton
WebElement searchButton = driver.findElement(By.id("gbqfb"));
searchButton.click();
}
#Then("^I should get result as \"([^\"]*)\"$")
public void I_should_get_correct_result(String expectedResult) {
//Get result from calculator
WebElement calculatorTextBox = driver.findElement(By.id("cwos"));
String result = calculatorTextBox.getText();
//Verify that result of 2+2 is 4
Assert.assertEquals(result, expectedResult);
driver.close();
}
#After
public void closeBrowser() {
driver.quit();
}
}
With cucumber-jvm 4.5.0 and up, in order to see the summary statistics at the end of a run you need to explicit ask for it via the plugins you define in your runner class. If you add the "summary" (as you have already "pretty") you should be able to see again the totals of Scenarios/Steps and time it took.
This has changed via https://github.com/cucumber/cucumber-jvm/pull/1670
Is it opening the google chrome browser?.
I think your code is not reaching to the point where there are print statements, Please share your test runner and step-definition file.
This question already has answers here:
java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri
(8 answers)
Closed 3 years ago.
I am trying to build a REST webservice using an asynchronous response.
I have looked around this error on the web, however, none of the solutions have worked for me. I am not sure on how to go about it.
This is the code for the REST service, it has AsyncResponse, and #Suspended which are taken from jar file specified in the pom.xml, which I will provide below. The problem is, on deploying the war, I get an exception:
java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri(Ljava/lang/String;)Ljavax/ws/rs/core/UriBuilder;
javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:651)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.50 logs
My class is as follows:
package com.crudapp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.annotation.Generated;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
//import javax.ws.rs.core.UriBuilder;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.google.gson.Gson;
import com.mysql.jdbc.StringUtils;
import dao.User;
import dao.UserDAO;
import dao.UserDAOImpl;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
#Path("/crudpath")
public class EntityResource {
private final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/spring.xml");
UserDAO userdao = null;
private final int numOfThreads = 10;
private final ExecutorService executorService = Executors.newFixedThreadPool(numOfThreads);
// userdao.getUsers("118");
//ctx.close();
#GET
#Produces("application/json")
public Response getTupleFromDBasJSON(#QueryParam("param1") String userid, #Suspended final AsyncResponse asyncresponse ){
if(StringUtils.isNullOrEmpty(userid))
throw new ServiceException("Userid passed to the REST service /crudpath is null or empty");
userdao = (userdao==null)?
ctx.getBean("userDAO", UserDAOImpl.class)
: userdao;
Gson gson = new Gson();
Future<List<User>> futures = executorService.submit(new DAOTaskHandlerThread(userid));
List <User> users = new ArrayList<User>();
if(futures.isDone())
{
try{
users = futures.get();
if(users!= null)
return Response.status(200).entity( gson.toJson(users).toString()).build();
}
catch(Exception ex)
{
throw new ServiceException(ex);
}
}
return Response.status(200).entity(new ArrayList<User>().toString()).build();
/*// crrate a new thread.. call the DAO .. returns the result from here.
JSONObject jsonObject = new JSONObject();
jsonObject.put("key", "value");
return Response.status(200).entity( jsonObject.toString()).build();*/
}
private class DAOTaskHandlerThread implements Callable<List<User>>{
//private UserDAO userDAO;
private String userid;
private DAOTaskHandlerThread(//UserDAO userDAO,
String useridpassed){
///this.userDAO= userDAO;
userid= useridpassed;
}
#Override
public List<User> call() throws Exception {
// TODO Auto-generated method stub
return userdao.getUsers(userid);
}
}
}
My pom.xml file for maven is as follow:
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>RESTJerseyExample</groupId>
<artifactId>RESTJerseyExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<!-- spring framework just added -->
<properties>
<java-version>1.7</java-version>
<org.springframework-version>4.0.3.RELEASE</org.springframework-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- spring framework just added ends here -->
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.0</version>
</dependency>
<!-- used for httpclient library -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.2</version>
</dependency>
<!-- for async response -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0-m12</version>
</dependency>
</dependencies>
</project>
AbstractMethodError are thrown when an application tries to call an abstract method.
uri is an abstract method in UriBuilder, so you need an implementation of this. This method (with String parameter) is from version 2.0 of JAX-RS specification.
You're trying to use JAX-RS 2.0 with Jersey 1.*. Instead, you need to use Jersey 2.* that implements JAX-RS 2.0 and contains an implementation to uri method.
In your pom.xml you may remove these dependencies:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0-m12</version>
</dependency>
And use these dependencies:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.17</version>
</dependency>
Using this, uri method is implemented in JerseyUriBuilder class from jersey-common.
EDIT:
You need to change, in your web.xml, servlet com.sun.jersey.spi.container.servlet.ServletContainer to org.glassfish.jersey.servlet.ServletContainer and init-param from com.sun.jersey.config.property.packages to jersey.config.server.provider.packages
I would like to add one answer to this post. I faced a similar problem today and found the root cause to be another dependent jar which was Internally using an older version of Jersey/JAX-RS.
My POM before fix was:
<jersey.version>2.17</jersey.version>
...
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.ci.wrapper</groupId>
<artifactId>client-wrapper</artifactId>
<version>${clients-wrapper.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.api.commons</groupId>
<artifactId>transferobjects</artifactId>
<version>3.0.2</version>
</dependency>
The problem was with "com.ci.wrapper" and "com.api.commons".
They inturn included 2 different JAR's of BraveJersey and org.apache.cxf.cxf-rt-frontend-jaxrs (2.5.1) which were using Jersey and JAX-RS 1.X versions.
After excluding the nested jar's and adding the newer version's of BraveJersey2/org.apache.cxf.cxf-rt-frontend-jaxrs(3.1.5) it got resolved.
<dependency>
<groupId>com.api.commons</groupId>
<artifactId>transferobjects</artifactId>
<version>3.0.2</version>
<exclusions>
<exclusion>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<groupId>org.apache.cxf</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.1.5</version>
</dependency>
<dependency>
<groupId>com.ci.wrapper</groupId>
<artifactId>client-wrapper</artifactId>
<version>${clients-wrapper.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<artifactId>brave-jersey</artifactId>
<groupId>com.github.kristofa</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.kristofa</groupId>
<artifactId>brave-jersey2</artifactId>
<version>2.4.2</version>
</dependency>
In case you're facing a similar issue, please check if the project's or jar's included could be using an incompatible version of Jersey/Jax-RS.
In my case it's combination of both cxf-rt-frontend-jaxrs and httpclint jar needed to be removed to resolve the issue. Both of these jars have the class javax.ws.rs.core.UriBuilder, the multiple version of this class caused the issue.
My pom had a transitive dependency on both these jars, after removing it worked.
enter code here
<exclusion>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</exclusion>
I have faced this problem when I was trying to use a library (custom built) in one of my project.
So the problem was happening due to mismatch in the com.sun.jersey dependencies. My project was using jersey version 2.15 whereas the custom library was giving me com.sun.jersey transitively of version 1.17.
So how to find such problems.
Use gradle dependencies task to find out the dependencies (it gives nested level results which means all the transitive dependencies will also be shown)
Once you identify the problem causing dependencies. Exclude them while adding the required dependencies in the project.
For e.g.
httpRestClient is name of my custom library which I wanted to use in my project.
So here is how I have added the dependency and at the same time excluded the conflicting dependencies of group 'com.sun.jersey'
compile(httpRestClient) {
exclude group: 'com.sun.jersey'
}
This way you can use whatever library and exclude the conflicting libraries.
Thanks.
In our case culprit was this dependency
<dependency>
<groupId>org.apache.wink</groupId>
<artifactId>wink-common</artifactId>
<version>1.0-incubating</version>
</dependency>
I want to monitor some apps and i am using Prometheus. It works well in some apps but when i tried to implement it in another app i am facing some problems.
It says:
The constructor ServletRegistrationBean(MetricsServlet, String) is undefined
What can cause this problem and how to fix this.
This is my class.
import java.util.Collection;
import org.springframework.boot.actuate.endpoint.PublicMetrics;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.prometheus.client.exporter.MetricsServlet;
import io.prometheus.client.hotspot.DefaultExports;
import io.prometheus.client.spring.boot.SpringBootMetricsCollector;
#Configuration
public class MonitoringConfig {
#Bean
SpringBootMetricsCollector springBootMetricsCollector(Collection<PublicMetrics> publicMetrics) {
SpringBootMetricsCollector springBootMetricsCollector = new SpringBootMetricsCollector(publicMetrics);
springBootMetricsCollector.register();
return springBootMetricsCollector;
}
#Bean
public ServletRegistrationBean servletRegistrationBean() {
DefaultExports.initialize();
return new ServletRegistrationBean(new MetricsServlet(), "/prometheus");
}
}
Dependecies:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.moelholm/prometheus-spring-boot-starter -->
<dependency>
<groupId>com.moelholm</groupId>
<artifactId>prometheus-spring-boot-starter</artifactId>
<version>1.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.prometheus/simpleclient -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient</artifactId>
<version>0.0.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.prometheus/simpleclient_hotspot -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_hotspot</artifactId>
<version>0.0.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.prometheus/simpleclient_spring_boot -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_spring_boot</artifactId>
<version>0.0.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.prometheus/simpleclient_servlet -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_servlet</artifactId>
<version>0.0.25</version>
</dependency>
In some apps it works but in one i stacked with this:
The constructor ServletRegistrationBean(MetricsServlet, String) is undefined
The MetricsServlet should implement javax.servlet.Servlet . Make sure you have that class(i.e javax.servlet.Servlet) in your project/classpath.
The maven dependency for the library containing this class is:
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
I am using the H2 database in a Spring boot application. But unable to open it in the browser at http://localhost:8080/console. My pom.xml is as below:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.192</version>
</dependency>
Spring boot Configuration :
Springboot configuration file
#Configuration
public class WebConfiguration {
#Bean
ServletRegistrationBean h2servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
}
to use the H2 console you need to configure it in your .properties file
spring.h2.console.enabled=true
spring.h2.console.path=/h2console/
where /h2console/ is the path you want to use on the browser so you can change it to anything. Also if you have security enabled you might want to add it to the permitted paths
also add this to your HttpSecurity configuration http.headers().frameOptions().disable();
Edit
change your security configuration i'm pretty sure you might have spring security in your pom so use this instead, if not it should work
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
public class WebConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/").permitAll().and()
.authorizeRequests().antMatchers("/console/**").permitAll();
httpSecurity.csrf().disable();
httpSecurity.headers().frameOptions().disable();
}
}
If have included spring-boot-starter-security artifact in your pom then by default basic authentication is enabled. Hence, to access your console either you disable the basic authentication by adding security.basic.enabled=false in your application.properties or allow the access in your configure method as below:
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests().antMatchers("/").permitAll().and().authorizeRequests()
.antMatchers("/console/**").permitAll();
httpSecurity.headers().frameOptions().disable();
}
}
Thank you all for your generous help.The application class (Springboot) was in a separate package and it was not scanning other packages.Also I modified my Pom.xml a bit which finally helped me to access the console.Attached is my new 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.spring.app</groupId>
<artifactId>Demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBootApp</name>
<description>Generator of statistics </description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--WebJars -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.4</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring AOP + AspectJ -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- JavaConfig need this library -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
go the POM file and add the dependency :
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
rebuild your project
this might help folks , all the configuration above is correct
Note - if you are not using any security then adding spring security is not required
Actualy problem is - when you open this url in chrome
http://localhost:8080/h2 chrome makes it --> https://localhost:8080/h2
To get rid of this issue - Below reference will help -
Google Chrome redirecting localhost to https
You might have face 2 situation including following errors:
localhost refused to connect
Double check the URL. Chrome automatically try to change http:// to https://
Check spring.h2.console.path (Path at witch the console avilible) to get your URL:
Default: /h2-console --> URL: http://localhost:8080/h2-console/
If you running IDE (e.g. IntelliJ Idea), make sure your app is running witch means your H2 data base is running!
You face 404 Error:
In this case your H2 Data base is correctly running on Port 8080 and you already have the connection with it.
Check spring.h2.console.path (Path at witch the console avilible) to get your URL:
Default: /h2-console --> URL: http://localhost:8080/h2-console/
Enable H2 Console
spring.h2.console.enabled=true
The issue might be also be caused by adding server.servlet.context-path to properties. The new url will be composed of server.servlet.context-path plus spring.h2.console.path
If you have renamed the h2 path in the application.properties to "console" you've to add it in your antMatcher like .antMatcher("/console/**") with two asterisks after the "console" because there are much more appendings.
If none of the above solution works, try below one, this worked for me :
Add below property in your application.propertiesfollowing
spring.data.jpa.repositories.bootstrap-mode=default
Open console in browser using this URL : http://localhost:8080/h2-console
On a login page make sure that you use jdbc:h2:mem:testdb as JDBC URL.
As h2 database console is mapped to "h2-console".
Use this:
http.csrf().disable().authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated();
// disable frame options
http.headers().frameOptions().disable();
`
You don't need permit root access:
.antMatchers("/") * NOT NEEDED *