Danix
Danix
JCHJava Community | Help. Code. Learn.
Created by Danix on 10/29/2024 in #java-help
Error: Could not find or load main class
i am facing this problem i dont know what to do now ! Can anyone help me upon this ?
package com.demo.journalApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement
@Configuration
@EnableAutoConfiguration
public class JournalApplication {

public static void main(String[] args) {
SpringApplication.run(JournalApplication.class, args);
}

@Bean
PlatformTransactionManager add(MongoDatabaseFactory db) {
return new MongoTransactionManager(db);
}

}
package com.demo.journalApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement
@Configuration
@EnableAutoConfiguration
public class JournalApplication {

public static void main(String[] args) {
SpringApplication.run(JournalApplication.class, args);
}

@Bean
PlatformTransactionManager add(MongoDatabaseFactory db) {
return new MongoTransactionManager(db);
}

}
9 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 10/6/2024 in #java-help
500 Internal Error
No description
6 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 10/4/2024 in #java-help
Java Devlopment Suggestion
Should i have to learn about testing as a java dev or should i have to cover my core knowledge like Orm , Spring boot , React etc and then start to learn about testing !
4 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 9/28/2024 in #java-help
Deleting Error
i am tryna delete a book from a list of books but end up with this error
16 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 8/11/2024 in #java-help
Getting 500 error instead of 400 and 409
I am tryna handle the erros in the Api and Return the Exception according to the need as u can see in the code but i am not getting proper errors as i return them !
@Override
public Optional<BooksDetails> addBooks(BooksDetailsDto booksDetailsDto, Long roll_no) {

Optional<StudentDetails> studentObj = detailsRepository.findById(roll_no);
Optional<BooksDetails> existingBook = bookDetailsRepository.findByBookId(booksDetailsDto.getBookId());

if (!studentObj.isPresent()) {
throw new StudentNotFound("No Student Has been Founded with this roll_no");
}

if (existingBook.isPresent()) {
throw new BookAlreadyExist("This Book is Already Present");
}
BooksDetails booksDetails = BookDetailsDtoMapper.toEntity(booksDetailsDto, studentObj.get(),
apiService);
BooksDetails savedBook = bookDetailsRepository.save(booksDetails);
return Optional.of(savedBook);
}
@Override
public Optional<BooksDetails> addBooks(BooksDetailsDto booksDetailsDto, Long roll_no) {

Optional<StudentDetails> studentObj = detailsRepository.findById(roll_no);
Optional<BooksDetails> existingBook = bookDetailsRepository.findByBookId(booksDetailsDto.getBookId());

if (!studentObj.isPresent()) {
throw new StudentNotFound("No Student Has been Founded with this roll_no");
}

if (existingBook.isPresent()) {
throw new BookAlreadyExist("This Book is Already Present");
}
BooksDetails booksDetails = BookDetailsDtoMapper.toEntity(booksDetailsDto, studentObj.get(),
apiService);
BooksDetails savedBook = bookDetailsRepository.save(booksDetails);
return Optional.of(savedBook);
}
@PostMapping("/addBook/{roll_no}")
public ResponseEntity<?> addBooksToStudent(@RequestBody BooksDetailsDto booksDetailsDto,
@PathVariable Long roll_no) {

Optional<BooksDetails> studentBook = detailsService.addBooks(booksDetailsDto, roll_no);
if (studentBook.isPresent()) {
return ResponseEntity.ok(studentBook.get()); // Return the added book
} else {
return ResponseEntity.badRequest().build(); // Return a 400 Bad Request if the book could not be added
}

}
@PostMapping("/addBook/{roll_no}")
public ResponseEntity<?> addBooksToStudent(@RequestBody BooksDetailsDto booksDetailsDto,
@PathVariable Long roll_no) {

Optional<BooksDetails> studentBook = detailsService.addBooks(booksDetailsDto, roll_no);
if (studentBook.isPresent()) {
return ResponseEntity.ok(studentBook.get()); // Return the added book
} else {
return ResponseEntity.badRequest().build(); // Return a 400 Bad Request if the book could not be added
}

}
46 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 7/30/2024 in #java-help
Exception Handling in Spring
Hey i am getting 500 response code instead of 404 even after handling the exception
package com.ShelfSpace.ShelfSpace.exception;

public class ResourceNotFoundException extends RuntimeException {

public ResourceNotFoundException() {
super();
}

public ResourceNotFoundException(String message) {
super(message);
}

public ResourceNotFoundException(String message, Throwable throwable) {
super(message, throwable);
}
}
package com.ShelfSpace.ShelfSpace.exception;

public class ResourceNotFoundException extends RuntimeException {

public ResourceNotFoundException() {
super();
}

public ResourceNotFoundException(String message) {
super(message);
}

public ResourceNotFoundException(String message, Throwable throwable) {
super(message, throwable);
}
}
20 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 7/21/2024 in #java-help
RestApi Access Problem
When i try to access the Rest Api from postman then i got the html of login i even permit the enpoint of api
@RestController
@RequestMapping("/api/Student")
@CrossOrigin(origins = "http://localhost:3000")
public class RestApplication {

@Autowired
private StudentDetailsService detailsService;
@Autowired
private BookDetailsRepository booksRepositrory;

//// Get All The Students

@GetMapping("/getAllStudents")
public ResponseEntity<List<StudentDetails>> getAllStudents() {
Iterable<StudentDetails> studentDetailsIt = detailsService.getAllStudent();
List<StudentDetails> studentDetails = new ArrayList<StudentDetails>();
studentDetailsIt.forEach(studentDetails::add);

if (studentDetails.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(studentDetails, HttpStatus.OK);

}
@RestController
@RequestMapping("/api/Student")
@CrossOrigin(origins = "http://localhost:3000")
public class RestApplication {

@Autowired
private StudentDetailsService detailsService;
@Autowired
private BookDetailsRepository booksRepositrory;

//// Get All The Students

@GetMapping("/getAllStudents")
public ResponseEntity<List<StudentDetails>> getAllStudents() {
Iterable<StudentDetails> studentDetailsIt = detailsService.getAllStudent();
List<StudentDetails> studentDetails = new ArrayList<StudentDetails>();
studentDetailsIt.forEach(studentDetails::add);

if (studentDetails.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(studentDetails, HttpStatus.OK);

}
Security
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/signup", "/processRegister", "/Login", "/login", "/forgot-password/**",
"/css/emailVerification.css", "/css/newpassword.css", "css/home.css",
"/css/otpchecker.css", "/css/signup.css", "/css/login.css", "/css/resetpassword.css",
"/api/Student/**")
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/signup", "/processRegister", "/Login", "/login", "/forgot-password/**",
"/css/emailVerification.css", "/css/newpassword.css", "css/home.css",
"/css/otpchecker.css", "/css/signup.css", "/css/login.css", "/css/resetpassword.css",
"/api/Student/**")
```
5 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 7/14/2024 in #java-help
Spring JPA
I am tryna Delete the forgotPassword Enetity if the Otp expired time is passed out and that is 10 sec right now but after the Otp time expired the otp entity is not deleting itself from Db . Here is the implemet
if (forgotPassword.getOtpExpireDate().before(Date.from(Instant.now()))) {

if (forgotPassword.getOtpExpireDate().before(Date.from(Instant.now()))) {

Long fId = forgotPassword.getForgotpasswordId();
System.out.println("The Password id is "+ fId);

emailService.deleteForgotPasswordById(fId);
logger.warn("The Time is expired", forgotPassword.getOtpExpireDate());
throw new OtpNotFoundExcpetion("Otp Expired");
}
}
if (forgotPassword.getOtpExpireDate().before(Date.from(Instant.now()))) {

if (forgotPassword.getOtpExpireDate().before(Date.from(Instant.now()))) {

Long fId = forgotPassword.getForgotpasswordId();
System.out.println("The Password id is "+ fId);

emailService.deleteForgotPasswordById(fId);
logger.warn("The Time is expired", forgotPassword.getOtpExpireDate());
throw new OtpNotFoundExcpetion("Otp Expired");
}
}
Can anyone help
139 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 7/13/2024 in #java-help
Java Mail Sender
I am Getting issue while try to send a email to the user after config everything and i dont know how to resolve it
Failed messages: org.eclipse.angus.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com , 587; timeout -1;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com ; message exceptions (1) are:
Failed message 1: org.eclipse.angus.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com , 587; timeout -1;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com ] with root cause

java.net.UnknownHostException: smtp.gmail.com
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:572) ~
Failed messages: org.eclipse.angus.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com , 587; timeout -1;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com ; message exceptions (1) are:
Failed message 1: org.eclipse.angus.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com , 587; timeout -1;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com ] with root cause

java.net.UnknownHostException: smtp.gmail.com
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:572) ~
4 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 7/11/2024 in #java-help
Custom AuthenticationFailureHandler
i am tryna make a Custom Authentication Failure Handler like this ->
@Component
public class CustomAuthenticationHandler implements AuthenticationFailureHandler {

@Autowired
private UserRepository userRepository;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CustomAuthenticationHandler.class);

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {

logger.info("CustomAuthenticationFailureHandler invoked");

if (exception instanceof BadCredentialsException) {

String email = request.getParameter("username");
boolean emailExists = checkEmail(email);

if (!emailExists) {
logger.warn(" User not registered with email : {}", email);
response.sendRedirect("/login?error=email");
} else {
logger.warn(" Incorrect password for email: {}", email);
response.sendRedirect("/login?error=password");
}
} else {
logger.error("Authentication failed due to: {}", exception.getMessage());
response.sendRedirect("/login?error");
}
}

private boolean checkEmail(String email) {
Optional<User> user = userRepository.findByEmail(email);
return user.isPresent();
}

}
@Component
public class CustomAuthenticationHandler implements AuthenticationFailureHandler {

@Autowired
private UserRepository userRepository;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CustomAuthenticationHandler.class);

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {

logger.info("CustomAuthenticationFailureHandler invoked");

if (exception instanceof BadCredentialsException) {

String email = request.getParameter("username");
boolean emailExists = checkEmail(email);

if (!emailExists) {
logger.warn(" User not registered with email : {}", email);
response.sendRedirect("/login?error=email");
} else {
logger.warn(" Incorrect password for email: {}", email);
response.sendRedirect("/login?error=password");
}
} else {
logger.error("Authentication failed due to: {}", exception.getMessage());
response.sendRedirect("/login?error");
}
}

private boolean checkEmail(String email) {
Optional<User> user = userRepository.findByEmail(email);
return user.isPresent();
}

}
7 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 7/9/2024 in #java-help
Oauth Authorization
Can anyone suggests how can I learn about Oauth2 theory and implementation ? I am really confused about it that what to learn and what not !
4 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 7/3/2024 in #java-help
Bean Initialization Error
I am Getting this error ->
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2024-07-03T11:11:21.350+05:30 ERROR 11748 --- [ restartedMain] o.s.boot.SpringApplication  : Application run failed

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'securityConfiguration': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:355) ~[spring-beans-6.1.10.jar:6.1.10]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:227) ~[spring-beans-6.1.10.jar:6.1.10]

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2024-07-03T11:11:21.350+05:30 ERROR 11748 --- [ restartedMain] o.s.boot.SpringApplication  : Application run failed

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'securityConfiguration': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:355) ~[spring-beans-6.1.10.jar:6.1.10]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:227) ~[spring-beans-6.1.10.jar:6.1.10]

197 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 7/2/2024 in #java-help
Ecplise Project Issue
No description
45 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 7/1/2024 in #java-help
Saving User
Can someone help me to save the user if the user dont have any roles then put it there the USER role but i dont know how to do it ..
package com.ShelfSpace.ShelfSpace.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.ShelfSpace.ShelfSpace.UserDao.UserInfoDao;
import com.ShelfSpace.ShelfSpace.model.UserEntity;
import com.ShelfSpace.ShelfSpace.model.UserRoleEntity;
import com.ShelfSpace.ShelfSpace.repository.RoleRepository;
import com.ShelfSpace.ShelfSpace.repository.UserRepository;

import jakarta.transaction.Transactional;

public class UserService implements UserInfoDao{

private UserRepository userRepository;
private RoleRepository roleRepository;

public UserService(UserRepository userRepository , RoleRepository roleRepository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}

@Transactional
@Override
public UserEntity addUser(UserEntity user) {
if (user.getRoles() == null || user.getRoles().isEmpty()) {

}
userRepository.save(user);
return null;
}

}
package com.ShelfSpace.ShelfSpace.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.ShelfSpace.ShelfSpace.UserDao.UserInfoDao;
import com.ShelfSpace.ShelfSpace.model.UserEntity;
import com.ShelfSpace.ShelfSpace.model.UserRoleEntity;
import com.ShelfSpace.ShelfSpace.repository.RoleRepository;
import com.ShelfSpace.ShelfSpace.repository.UserRepository;

import jakarta.transaction.Transactional;

public class UserService implements UserInfoDao{

private UserRepository userRepository;
private RoleRepository roleRepository;

public UserService(UserRepository userRepository , RoleRepository roleRepository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}

@Transactional
@Override
public UserEntity addUser(UserEntity user) {
if (user.getRoles() == null || user.getRoles().isEmpty()) {

}
userRepository.save(user);
return null;
}

}
4 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 7/1/2024 in #java-help
Pushing Java Code
Can someone tell me how can i push my code to my github using Ecplise IDE ? Bcz last time when i did it myself i really got into the big problem .
4 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 6/28/2024 in #java-help
DTO
Can anyone help me to create DTO for this classes and also explain me why we use DTO more
package com.ShelfSpace.ShelfSpace.model;

import java.util.List;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import jakarta.persistence.JoinColumn;

@Entity
@Table(name = "registered_user")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserEntity {


@Column(name = "name", nullable = false)
private String name;

@Id
@Column(name = "email", nullable = false, unique = true)
private String email;


@Column(name = "password", nullable = false)
private String password;

@ManyToMany
@JoinTable(
name = "user_info_user_roles",
joinColumns = @JoinColumn(name = "user_info_email", referencedColumnName = "email"),
inverseJoinColumns = @JoinColumn(name = "user_roles_id")
)
private List<UserRoleEntity> roles;

}
package com.ShelfSpace.ShelfSpace.model;

import java.util.List;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import jakarta.persistence.JoinColumn;

@Entity
@Table(name = "registered_user")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserEntity {


@Column(name = "name", nullable = false)
private String name;

@Id
@Column(name = "email", nullable = false, unique = true)
private String email;


@Column(name = "password", nullable = false)
private String password;

@ManyToMany
@JoinTable(
name = "user_info_user_roles",
joinColumns = @JoinColumn(name = "user_info_email", referencedColumnName = "email"),
inverseJoinColumns = @JoinColumn(name = "user_roles_id")
)
private List<UserRoleEntity> roles;

}
package com.ShelfSpace.ShelfSpace.model;

import java.util.List;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Table(name = "user_roles")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserRoleEntity {

@Id
@Column(name = "role_id")
private int roleId;

@Column(name = "role_name", nullable = false, unique = true)
private String roleName;

@ManyToMany(mappedBy = "roles")
private List<UserEntity> registeredUser;
}
package com.ShelfSpace.ShelfSpace.model;

import java.util.List;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Table(name = "user_roles")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserRoleEntity {

@Id
@Column(name = "role_id")
private int roleId;

@Column(name = "role_name", nullable = false, unique = true)
private String roleName;

@ManyToMany(mappedBy = "roles")
private List<UserEntity> registeredUser;
}
13 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 6/28/2024 in #java-help
Spring Security
I wanna Config The Spring Config class but due to changemnet in version i am not able to do it . Can anyone Help
package com.ShelfSpace.ShelfSpace.Config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfiguration{

public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {

httpSecurity.authorizeHttpRequests(x->{
x.requestMatchers("/").permitAll();
});

return httpSecurity.build();
}
}
package com.ShelfSpace.ShelfSpace.Config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfiguration{

public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {

httpSecurity.authorizeHttpRequests(x->{
x.requestMatchers("/").permitAll();
});

return httpSecurity.build();
}
}
i want to make a custom login page and authenticate every endpoint excpet the / this one how could i achieve it ?
52 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 6/27/2024 in #java-help
Data Structure And Algorithms
I wanna start Data Structure And Algorithms So can anyone Suggests me a good Data Structure And Algorithms Course ?
4 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 6/26/2024 in #java-help
JSON RESPONSE ERROR
I dont know why whenever i am adding data to my RestApi i am getting double json response of book class here is the response ->
80 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 6/24/2024 in #java-help
Spring Security Filters
When we need to make our own custom filter chain in spring security and what's actually it's use case ?
9 replies