Field departmentrepositoryy in service.DepartementServiceimpl required a bean of type 'repository.DepartmentRepository' that could not be found - spring-boot

entity
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Department {
public long getDepartment_id() {
return department_id;
}
public void setDepartment_id(long department_id) {
this.department_id = department_id;
}
public String getDepartment_name() {
return department_name;
}
public Department(long department_id, String department_name, String department_address, String department_code) {
this.department_id = department_id;
this.department_name = department_name;
this.department_address = department_address;
this.department_code = department_code;
}
public void setDepartment_name(String department_name) {
this.department_name = department_name;
}
public String getDepartment_address() {
return department_address;
}
public void setDepartment_address(String department_address) {
this.department_address = department_address;
}
public String getDepartement_code() {
return department_code;
}
public void setDepartement_code(String department_code) {
this.department_code = department_code;
}
public Department() {
super();
}
#Override
public String toString() {
return "Department{" +
"departement_id=" + department_id +
", departement_name='" + department_name + '\'' +
", departement_address='" + department_address + '\'' +
", departement_code='" + department_code + '\'' +
'}';
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long department_id;
private String department_name;
private String department_address;
private String department_code;
}
department controller
import entity.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import service.DepartmentService;
#RestController
public class DepartmentController {
#Autowired
public DepartmentService departmentServicee;
#PostMapping("/departments")
public Department saveDepartment(#RequestBody Department department)
{
return departmentServicee.saveDepartment(department);
}
}
Department service
import org.springframework.stereotype.Component;
import entity.Department;
import org.springframework.stereotype.Service;
public interface DepartmentService {
public Department saveDepartment(Department department);
}
department service impl
import entity.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import repository.DepartmentRepository;
#Service
public class DepartementServiceimpl implements DepartmentService {
#Autowired
public DepartmentRepository departmentrepositoryy;
#Override
public Department saveDepartment(Department department) {
return departmentrepositoryy.save(department);
}
}
Department repository
import entity.Department;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.FluentQuery;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
#Repository
public interface DepartmentRepository extends JpaRepository<Department,Long> {
}
application.properties
server.port = 9009
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=sa
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
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.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.saketh</groupId>
<artifactId>spring_boot_Real</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring_boot_Real</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<!--<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</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>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
**
Unable to get my mistake tried most of the available solutions
what did I miss?
I did add all the files that i have used , please let me know any other required
Thanks
**
file structure

Related

Unauthorized and full authentication required to access user's resource

I am working on a resource service that uses Keycloak as the authorization server. The code below is taken from Spring Security in Action by Laurentiu Spilcă. Keycloak is provisioned with some users for testing purposes. So first a token for a user is obtained after login and the token is used to to make a request to retrieve the user's data from the resource server but I keep getting unauthorized and full authentication required. I am unable to figure out what the issue is as I am quite new to Spring.
KeycloakApplication.java
package com.chapter18.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories(basePackages = {"com.chapter18.repositories"} )
#EntityScan(basePackages = "com.chapter18.entities")
#ComponentScan(basePackages = {"com.chapter18.service", "com.chapter18.config", "com.chapter18.controller"})
public class KeycloakProjectApplication {
public static void main(String[] args) {
SpringApplication.run(KeycloakProjectApplication.class, args);
}
}
ResourceServerConfig.java
package com.chapter18.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.jwk.JwkTokenStore;
import org.springframework.security.web.FilterInvocation;
/**
* created on 21/04/2022
*/
#Configuration
#EnableResourceServer
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Value("${claim.aud}")
private String claimAud;
#Value("${jwkSetUri}")
private String urlJwk;
#Override
public void configure(ResourceServerSecurityConfigurer resources) {
System.out.println(claimAud + "\t" + urlJwk);
resources.tokenStore(tokenStore());
resources.resourceId(claimAud);
resources.expressionHandler(handler());
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().disable();
// http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests()
.mvcMatchers(HttpMethod.DELETE, "/**")
.hasAuthority("fitnessadmin")
.antMatchers("/h2-console/**").permitAll()
.anyRequest()
.authenticated();
}
#Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
#Bean
public SecurityExpressionHandler<FilterInvocation> handler() {
return new OAuth2WebSecurityExpressionHandler();
}
#Bean
public TokenStore tokenStore() {
return new JwkTokenStore(urlJwk);
}
}
WorkoutController.java
package com.chapter18.controller;
import com.chapter18.entities.Workout;
import com.chapter18.service.WorkoutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* created on 21/04/2022
*/
#RestController
#RequestMapping("/workout")
public class WorkoutController {
#Autowired
private WorkoutService workoutService;
#PostMapping("/")
public void add(#RequestBody Workout workout){
workoutService.saveWorkout(workout);
}
#GetMapping("/")
public List<Workout> findAll(){
return workoutService.findWorkouts();
}
#DeleteMapping("/{id}")
public void delete(#PathVariable Integer id){
workoutService.deleteWorkout(id);
}
}
Workout.java
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.time.LocalDateTime;
/**
* created on 21/04/2022
*/
#Getter
#Setter
#Entity
public class Workout {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String user;
private LocalDateTime start;
private LocalDateTime end;
private int diffculty;
}
WorkoutRepository.java
package com.chapter18.repositories;
import com.chapter18.entities.Workout;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
/**
* created on 21/04/2022
*/
public interface WorkoutRepository extends JpaRepository<Workout, Integer> {
#Query("SELECT w FROM Workout w WHERE w.user = ?#{authentication.name}")
List<Workout> findAllByUser();
}
WorkoutService
package com.chapter18.service;
import com.chapter18.entities.Workout;
import com.chapter18.repositories.WorkoutRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* created on 21/04/2022
*/
#Service
public class WorkoutService {
#Autowired
private WorkoutRepository workoutRepository;
#PreAuthorize("#workout.user == authentication.name and #oauth2.hasScope('fitnessapp')")
public void saveWorkout(Workout workout){
System.out.println(workout.getUser());
workoutRepository.save(workout);
}
public List<Workout> findWorkouts(){
return workoutRepository.findAll();
}
public void deleteWorkout(Integer id){
workoutRepository.deleteById(id);
}
}
application.yml
spring:
application:
name: FitnessApp
datasource:
url: jdbc:h2:mem:spring
username: sa
password: pass
driverClassName: org.h2.Driver
jpa:
spring:
jpa:
database-platform: org.hibernate.dialect.H2Dialect
defer-datasource-initialization: true
h2:
console:
enabled: true
sql:
init:
mode: ALWAYS
claim:
aud: fitnessapp
jwkSetUri: http://localhost:8080/realms/master/protocol/openid-connect/certs
server:
port: 9090
schema.sql
CREATE SCHEMA IF NOT EXISTS spring;
CREATE TABLE IF NOT EXISTS `spring`.`workout` (
`id` INT NOT NULL AUTO_INCREMENT,
`user` VARCHAR(45) NULL,
`start` DATETIME NULL,
`end` DATETIME NULL,
`difficulty` INT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `spring`.`workout` (`id`, `user`, `start`, `end`, `difficulty`) VALUES (1, 'bill', '2020-06-10 15:05:05', '2020-06-10 16:10:07', '3');
INSERT INTO `spring`.`workout` (`id`, `user`, `start`, `end`, `difficulty`) VALUES (2, 'rachel', '2020-06-10 15:05:10', '2020-06-10 16:10:20', '3');
INSERT INTO `spring`.`workout` (`id`, `user`, `start`, `end`, `difficulty`) VALUES (3, 'bill', '2020-06-12 12:00:10', '2020-06-12 13:01:10', '4');
INSERT INTO `spring`.`workout` (`id`, `user`, `start`, `end`, `difficulty`) VALUES (4, 'rachel', '2020-06-12 12:00:05', '2020-06-12 12:00:11', '4');
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.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.my</groupId>
<artifactId>KeycloakProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>KeycloakProject</name>
<description>KeycloakProject</description>
<properties>
<java.version>11</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-oauth2-resource-server</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</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>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</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>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

#Valid annotation not working on Dto class - Spring Boot

I want validate my CustomerDTO using #Valid annotation.but also being validated at the same time using the #Valid annotation but it doesn't work, please help me.
This is my controller:
import lk.navishka.loginWithSecuruty.dto.CustomerDto;
import lk.navishka.loginWithSecuruty.entity.Customer;
import lk.navishka.loginWithSecuruty.service.CustomerService;
import lk.navishka.loginWithSecuruty.util.StandradResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
#RestController
#CrossOrigin
public class CustomerController {
#Autowired
CustomerService customerService;
#RequestMapping(value = {"/register"})
public ResponseEntity saveCustomer(#Valid #RequestBody CustomerDto customer){
customerService.saveCustomer(customer);
StandradResponse success = new StandradResponse(200, "success", null);
return new ResponseEntity(success, HttpStatus.OK);
}
}
this is My CustomerDTO class
import lombok.*;
import javax.persistence.Column;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.ArrayList;
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#ToString
public class CustomerDto {
#NotNull
#Size(min = 9, message = "Nic have at least 9 characters ")
private String nic;
private String address;
#NotNull
#Size(min = 5, message = "FirstName have at least 5 characters ")
private String firstName;
#NotNull
#Size(min = 5, message = "LastName have at least 5 characters ")
private String lastName;
private ArrayList<UserDto> user = new ArrayList<>();
}
this is my ErrorDetails class
import java.util.Date;
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
this my ExceptionHandler class
import lk.navishka.loginWithSecuruty.util.ErrorDetails;
import lk.navishka.loginWithSecuruty.util.StandradResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.Date;
#ControllerAdvice
public class ExceptionHandler {
//handling custom validation error
#ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> customValidationErrorHandling(MethodArgumentNotValidException exception){
ErrorDetails errorDetails = new ErrorDetails(new Date(),"Validator Error", exception.getBindingResult().getFieldError().getDefaultMessage());
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
}
}
i use meven this is Pom.xml file
<?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>lk.navishka</groupId>
<artifactId>LoginWithSecuruty</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.2</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>
<version>2.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.4.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.1.Final</version>
</dependency>
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
This is the JSON value that i use with postman
{
"nic" : "656v",
"address" : "polpitiya",
"firstName" : "nn",
"lastName" : "",
"user": [{
"userName":"username1",
"email":"sample#gmail.com",
"password":"1234"
}]
}
Try the 6.2.0.final version of hibernate-validator, it will work.
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.0.Final</version>
</dependency>

com.mongodb.MongoSocketOpenException: Exception opening socket with spring boot and mongodb cloud

Please suggest any solution for the below exception which is occuring while running my rest api while executing springboot application with mongodb cloud db. I have created collection in mongodb as well and configured below properties.
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.1.1.jar:na]
at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:589) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:549) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:648) ~[na:na]
at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:78) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.1.1.jar:na]
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.1.1.jar:na]
... 4 common frames omitted
Model class
------------
package com.praveen.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Data;
#Document
public class Products {
#Id
private String id;
private Integer p_id;
private String p_name;
private Integer p_cost;
private Integer countInStock;
private Integer numReviews;
private String image;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getP_id() {
return p_id;
}
public void setP_id(Integer p_id) {
this.p_id = p_id;
}
public String getP_name() {
return p_name;
}
public void setP_name(String p_name) {
this.p_name = p_name;
}
public Integer getP_cost() {
return p_cost;
}
public void setP_cost(Integer p_cost) {
this.p_cost = p_cost;
}
public Integer getCountInStock() {
return countInStock;
}
public void setCountInStock(Integer countInStock) {
this.countInStock = countInStock;
}
public Integer getNumReviews() {
return numReviews;
}
public void setNumReviews(Integer numReviews) {
this.numReviews = numReviews;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#Override
public String toString() {
return "Products [id=" + id + ", p_id=" + p_id + ", p_name=" + p_name + ", p_cost=" + p_cost + ", countInStock="
+ countInStock + ", numReviews=" + numReviews + ", image=" + image + "]";
}
}
RestController class
---------------------
package com.praveen.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import com.praveen.entity.Products;
import com.praveen.service.ProductsService;
#RestController
public class ProductsRestController {
#Autowired
private ProductsService service;
#GetMapping("/products")
public ResponseEntity<List<Products>> getProducts(){
List<Products> allProducts = service.getAllProducts();
if(allProducts != null) {
return new ResponseEntity<List<Products>>(allProducts, HttpStatus.OK);
}else {
return new ResponseEntity<List<Products>>(HttpStatus.BAD_REQUEST);
}
}
}
Service class
--------------
package com.praveen.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.praveen.entity.Products;
import com.praveen.repository.ProductsRepository;
#Service
public class ProductsServiceImpl implements ProductsService {
#Autowired
private ProductsRepository prodRepo;
#Override
public List<Products> getAllProducts() {
List<Products> productsList = prodRepo.findAll();
if(productsList != null) {
System.out.println(productsList);
return productsList;
}
return null;
}
}
Repository
-----------
package com.praveen.repository;
import java.io.Serializable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.praveen.entity.Products;
#Repository
public interface ProductsRepository extends MongoRepository<Products, Serializable> {
}
application.properties
-----------------------
spring.data.mongodb.url = mongodb+srv://praveen:praveen#cluster0.qrvkm.mongodb.net/miniproject?retryWrites=true&w=majority
spring.data.mongodb.database = products
spring.data.mongodb.port = 27017
spring.data.mongodb.repositories.enabled=true
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.praveen</groupId>
<artifactId>NgRx-Products</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>05-MiniProject-NgRx-Products</name>
<description>NgRx package with Products data using springboot</description>
<properties>
<java.version>15</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<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-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Please suggest any solution for the above exception, I have given all my files in the above.
Try adding this annotation to your main class file
#EnableAutoConfiguration(exclude={MongoAutoConfiguration.class})
Search services in start.
open it.
search for mongodb there.
start/restart mongodb services from there.
It should work properly.
this exception occurs due to mongodb incorrect port in application properties. So only changing spring.data.mongodb.port=27017 in application.properties file made it work. Also make sure you started mongodb server locally.
Check the connect to MongoDB sever locally with url:portNumber mentioned in the application.properties from where your code is getting executed.

Spring config for connecting to Postgres. Need bean: 'org.flywaydb.core.internal.jdbc.JdbcTemplate'

I'm getting this error when trying to run my Spring application.
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-09-22 23:55:45.397 ERROR 36321 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.example.demo.dao.UserDataAccessService required a bean of type 'org.flywaydb.core.internal.jdbc.JdbcTemplate' that could not be found.
Action:
Consider defining a bean of type 'org.flywaydb.core.internal.jdbc.JdbcTemplate' in your configuration.
The application works when I use my fakeUserData file. It seems like there is a dependency issue, but I've double checked and it looks like the dependencies are all there.
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.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.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.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
app:
datasource:
jdbc-url: jdbc:postgresql://localhost:5432/springbootpostgresdb
username: postgres
password: password
pool-size: 30
UserDataAccessService.java
package com.example.demo.dao;
import com.example.demo.model.User;
import org.flywaydb.core.internal.jdbc.JdbcTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
#Repository("postgresql")
public class UserDataAccessService implements Userdao {
private final JdbcTemplate jdbcTemplate;
#Autowired
public UserDataAccessService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
#Override
public int insertUser(UUID id, User user) {
return 0;
}
#Override
public int deleteUserById(UUID id) {
return 0;
}
#Override
public int updateUserById(UUID id, User user) {
return 0;
}
#Override
public Optional<User> selectUserById(UUID id) {
return Optional.empty();
}
#Override
public List<User> selectAllUsers() {
final String sql = "SELECT id,name FROM userProfile";
try {
return jdbcTemplate.query(sql, (resultSet) -> {
UUID id = UUID.fromString(resultSet.getString("id"));
String name = resultSet.getString("name");
return new User(id, name);
});
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}
PostgresDataSource.java
package com.example.demo.datasource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class PostgresDataSource {
#Bean
#ConfigurationProperties("app.datasource")
public HikariDataSource hikariDataSource() {
return DataSourceBuilder
.create()
.type(HikariDataSource.class)
.build();
}
}
Hi I had directly the same problem.
Problem was That when you automatically import library, there are two options.
Flyway or Springframework.
If you import flyway, than you have this problem.
import org.flywaydb.core.internal.jdbc.JdbcTemplate;
If you import spriongwramework everything is OK
import org.springframework.jdbc.core.JdbcTemplate;
I found two problem.
as #stefic said, you should modify your import jdbcTemplate
you should modify your jdbcTemplate query
UserDataAccessService.java
#Override
public List<User> selectAllUsers() {
final String sql = "SELECT id,name FROM userProfile";
return jdbcTemplate.query(sql, (resultSet, i) -> { // <----- add second parameter `i`
UUID id = UUID.fromString(resultSet.getString("id"));
String name = resultSet.getString("name");
return new User(id, name);
});
}

There was an unexpected error (type=Not Found, status=404). No message available

I am getting below error:
There was an unexpected error (type=Not Found, status=404). No message available
While using Spring Boot + Thymeleaf
Code:
Application class:
package com.mycom.extract;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
#SpringBootApplication(scanBasePackages = "com.mycom.extract")
public class MyAppExtractionWebApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(MyAppExtractionWebApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyAppExtractionWebApplication.class);
}
}
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.mycom.extract</groupId>
<artifactId>MyApp-extraction</artifactId>
<version>1</version>
<packaging>war</packaging>
<name>MyAppExtractionWeb</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</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>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</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-security</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
SecurityConfig
package com.mycom.extract.config.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private MyAppAuthenticationProvider authProvider;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**", "/login").permitAll()
.antMatchers("/*").fullyAuthenticated()
.and()
.formLogin().loginPage("/login")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("ipn").passwordParameter("password")
.defaultSuccessUrl("/home").failureUrl("/login?error")
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login");
http.csrf().disable();
}
}
WebMvcConfiguration
package com.mycom.extract.config;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#EnableAutoConfiguration
#Configuration
#ComponentScan(basePackages = { "com.mycom.extract" })
public class MyAppConfiguration extends WebMvcConfigurerAdapter{
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/", "/login");
registry.addViewController("/login").setViewName("index");
registry.addViewController("/home").setViewName("home");
}
}
Referring all same kind of post in Stackoverflow could find solution for myself.
Please suggest.
URL http://localhost:8080/MyAppExtractionWeb/
As I am setting up login, and authentication is handled at security config side, so once it is successful it shows home page. Hence no controller mentioned.
package com.mycom.config.security;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;
import org.springframework.beans.factory.annotation.Autowired;*/
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import com.mycom.entity.User;
import com.mycom.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
#Configuration
public class MyAppAuthenticationProvider implements AuthenticationProvider {
private static final String SECURITY_DOMAIN = "MyApp-ldapdomain";
#Autowired
private UserService userService;
#Override
public Authentication authenticate(Authentication authentication) {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
try {
CallbackHandler handler = new UserPasswordHandler(name, password);
LoginContext lc = new LoginContext(SECURITY_DOMAIN, handler);
lc.login();
if(lc.getSubject() != null) {
User user = userService.loadUserByUsername(name);
Collection<? extends GrantedAuthority> roles = null;
if(!user.getAuthorities().isEmpty()) {
roles = user.getAuthorities();
}
return new UsernamePasswordAuthenticationToken(name, password,roles);
} catch (Exception e) {
return null;
}
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}

Resources