Skip to content

Commit

Permalink
Merge pull request #158 from kbss-cvut/550-error-message-id
Browse files Browse the repository at this point in the history
Provide messageArguments for exceptions
  • Loading branch information
blcham authored Sep 23, 2024
2 parents 2bbd821 + caa32d2 commit 4a029e5
Show file tree
Hide file tree
Showing 11 changed files with 151 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@ public ErrorInfo handleAuthenticationError(HttpServletRequest request, Throwable

@ExceptionHandler(EntityNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorInfo handleNotFoundError(HttpServletRequest request, Throwable t) {
public ErrorInfo handleNotFoundError(HttpServletRequest request, EntityNotFoundException e) {
log.warn("> handleNotFoundError - {}", request.getRequestURI());
return ErrorInfo.builder()
.message(t.getMessage())
.message(e.getMessage())
.messageId(e.getMessageId())
.requestUri(request.getRequestURI())
.messageArguments(e.getMessageArguments())
.build();
}

Expand All @@ -45,6 +47,7 @@ public ErrorInfo handleLogicViolationError(HttpServletRequest request, LogicViol
.message(e.getMessage())
.messageId(e.getMessageId())
.requestUri(request.getRequestURI())
.messageArguments(e.getMessageArguments())
.build();
}

Expand Down Expand Up @@ -78,9 +81,23 @@ public ErrorInfo handleBadRequestException(HttpServletRequest request, BadReques
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorInfo handleEvaluationException(HttpServletRequest request, CalculationException e) {
log.warn("> handleEvaluationException - {}", request.getRequestURI());
return ErrorInfo.builder()
.message(e.getMessage())
.messageId(e.getMessageId())
.requestUri(request.getRequestURI())
.messageArguments(e.getMessageArguments())
.build();
}

@ExceptionHandler(UsernameNotAvailableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorInfo handleUsernameNotAvailableException(HttpServletRequest request, UsernameNotAvailableException e) {
log.warn("> handleUsernameNotAvailableException - {}", request.getRequestURI());
return ErrorInfo.builder()
.message(e.getMessage())
.requestUri(request.getRequestURI())
.messageId(e.getMessageId())
.messageArguments(e.getMessageArguments())
.build();
}
}
4 changes: 4 additions & 0 deletions src/main/java/cz/cvut/kbss/analysis/dto/error/ErrorInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Map;

@Data
@AllArgsConstructor
@NoArgsConstructor
Expand All @@ -17,4 +19,6 @@ public class ErrorInfo {

private String requestUri;

private Map<String, String> messageArguments;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package cz.cvut.kbss.analysis.exception;

import lombok.Getter;
import lombok.Setter;

import java.util.Map;

@Getter
@Setter
public class BadCredentialsException extends org.springframework.security.authentication.BadCredentialsException {

private final String messageId;
private Map<String, String> messageArguments;

public BadCredentialsException(String message) {
super(message);
this.messageId = null;
}

public BadCredentialsException(String message, Throwable cause) {
super(message, cause);
this.messageId = null;
}

public BadCredentialsException(String messageId, String message, Map<String, String> args){
super(message);
this.messageId = messageId;
messageArguments = args;
}
}
Original file line number Diff line number Diff line change
@@ -1,25 +1,39 @@
package cz.cvut.kbss.analysis.exception;

import cz.cvut.kbss.analysis.model.FaultEvent;
import lombok.Getter;

import java.util.Map;

@Getter
public class CalculationException extends RuntimeException{
public CalculationException() {
}

private final String messageId;
private Map<String, String> messageArguments;


public CalculationException(String message) {
super(message);
messageId = null;
}

public CalculationException(String messageId, String message, Map<String, String> args){
super(message);
this.messageId = messageId;
this.messageArguments = args;
}

public CalculationException(String message, Throwable cause) {
super(message, cause);
this.messageId = null;
}

public static CalculationException childProbabilityNotSet(FaultEvent event){
return new CalculationException(childProbabilityNotSetMessage(event));
return new CalculationException("error.faultEvent.childProbabilityNotSet",childProbabilityNotSetMessage(event), Map.of("event", event.getName(), "uri", event.getUri().toString()));
}

public static CalculationException probabilityNotSet(FaultEvent event){
return new CalculationException(probabilityNotSetMessage(event));
return new CalculationException("error.faultEvent.probabilityNotSet",probabilityNotSetMessage(event), Map.of("event", event.getName(), "uri", event.getUri().toString()));
}

public static String probabilityNotSetMessage(FaultEvent event){
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
package cz.cvut.kbss.analysis.exception;

import lombok.Getter;

import java.util.HashMap;
import java.util.Map;

@Getter
public class EntityNotFoundException extends FtaFmeaException {

public EntityNotFoundException(String message) {
private final String messageId;
private Map<String, String> messageArguments;

public EntityNotFoundException(String messageId, String message, Map<String, String> args) {
super(message);
this.messageId = messageId;
this.messageArguments = args;
}

public static EntityNotFoundException create(String resourceName, Object identifier) {
return new EntityNotFoundException(resourceName + " identified by " + identifier + " not found.");
return new EntityNotFoundException("error.entityNotFound",resourceName + " identified by " + identifier + " not found.", Map.of("resourceName", resourceName, "identifier", identifier.toString()));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,37 @@

import lombok.Getter;

import java.util.HashMap;
import java.util.Map;

@Getter
public class LogicViolationException extends RuntimeException {

private final String messageId;
private final Map<String, String> messageArguments;

public LogicViolationException(String messageId, String message){
super(message);
this.messageId = messageId;
messageArguments = null;
}

public LogicViolationException(String messageId, String message, Map<String, String> args){
super(message);
this.messageId = messageId;
this.messageArguments = args;
}

public LogicViolationException(String message) {
super(message);
messageId = null;
messageArguments = null;
}

public LogicViolationException(String message, Throwable cause) {
super(message, cause);
messageId = null;
messageArguments = null;
}

}
Original file line number Diff line number Diff line change
@@ -1,7 +1,26 @@
package cz.cvut.kbss.analysis.exception;

import lombok.Getter;
import lombok.Setter;

import java.util.Map;

@Getter
@Setter
public class UsernameNotAvailableException extends RuntimeException {

private final String messageId;
private Map<String, String> messageArguments;

public UsernameNotAvailableException(String message) {
super(message);
messageId = null;
}

public UsernameNotAvailableException(String messageId, String message, Map<String, String> args){
super(message);
this.messageId = messageId;
messageArguments = args;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,13 @@ public void evaluate(FaultTree faultTree){
.filter(e -> e.getProbability() == null)
.toList();
if(!fe.isEmpty()){
String message =
String leafEvents =
fe.stream().map(e -> "'%s'".formatted(e.getName()))
.collect(Collectors.joining("\n" , "The following leaf events do not have specified probability: [\n", "]"));
.collect(Collectors.joining("\n"));

throw new CalculationException(message);
String message = String.format("The following leaf events do not have specified probability:[\n%s]", leafEvents);

throw new CalculationException("error.faultTree.leafEvents.noProbability", message, Map.of("leafEvents", leafEvents));
}
minScenarios = null;
evaluate(faultTree.getManifestingEvent());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package cz.cvut.kbss.analysis.security;

import cz.cvut.kbss.analysis.exception.BadCredentialsException;
import cz.cvut.kbss.analysis.service.security.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
Expand All @@ -12,6 +12,8 @@
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
* The class is used for local authentication instead of OAuth2.
*/
Expand All @@ -38,7 +40,7 @@ public Authentication authenticate(Authentication authentication) throws Authent
final String password = (String) authentication.getCredentials();
if (!passwordEncoder.matches(password, userDetails.getPassword())) {
log.trace("Provided password for username '{}' doesn't match.", username);
throw new BadCredentialsException("Provided password for username '" + username + "' doesn't match.");
throw new BadCredentialsException("error.user.passwordMismatch" ,"Provided password for username '" + username + "' doesn't match.", Map.of("username", username));
}
return SecurityUtils.setCurrentUser(userDetails);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
Expand Down Expand Up @@ -68,7 +69,13 @@ public System findRequired(URI id) {
}

@Transactional
public System create(System system){
public System create(System system) {
List<URI> existingSystems = systemDao.findUriByName(system.getName());
if (!existingSystems.isEmpty())
throw new LogicViolationException("error.system.nameExists",
("System with name \"%s\" already exists")
.formatted(system.getName()),
Map.of("systemName", system.getName()));
this.persist(system);
return system;
}
Expand All @@ -77,12 +84,15 @@ public System create(System system){
public void remove(@NonNull URI instanceUri) {
System system = findAllSummary(instanceUri);
List<URI> faultTrees = systemDao.findSystemsFaultTrees(instanceUri);
if(!faultTrees.isEmpty()) {

throw new LogicViolationException((
"Cannot delete system \"%s\" (<%s>), " +
"the system has fault %d trees.")
.formatted(system.getName(), instanceUri, faultTrees.size()));
if (!faultTrees.isEmpty()) {
throw new LogicViolationException("error.system.removeWithFaultTrees", (
"System \"%s\" (<%s>), " +
"has %d fault trees.")
.formatted(system.getName(), instanceUri, faultTrees.size()),
Map.of(
"systemName", system.getName(),
"instanceUri", instanceUri.toString(),
"faultTreeCount", String.valueOf(faultTrees.size())));
}
super.remove(instanceUri);
}
Expand Down Expand Up @@ -128,7 +138,7 @@ public void removeComponent(URI systemUri, URI componentUri) {
public Set<FailureMode> getAllFailureModes(URI systemUri) {
System system = findRequired(systemUri);
Set<FailureMode> failureModes = new HashSet<>();
for(Item comp: system.getComponents()) {
for (Item comp : system.getComponents()) {
failureModes.addAll(comp.getFailureModes());
}
return failureModes;
Expand All @@ -143,16 +153,16 @@ public void importDocument(URI systemURI, URI contextIRI) {
}

@Transactional(readOnly = true)
public List<System> findAllSummaries(){
List<System> systems = ((SystemDao)getPrimaryDao()).findAllSummaries();
for(System system : systems)
public List<System> findAllSummaries() {
List<System> systems = ((SystemDao) getPrimaryDao()).findAllSummaries();
for (System system : systems)
setOperationalDataFilter(system);
return systems;
}

@Transactional(readOnly = true)
public System findAllSummary(URI systemUri){
System system = ((SystemDao)getPrimaryDao()).findSummary(systemUri);
public System findAllSummary(URI systemUri) {
System system = ((SystemDao) getPrimaryDao()).findSummary(systemUri);
setOperationalDataFilter(system);
return system;
}
Expand All @@ -163,7 +173,7 @@ protected void setOperationalDataFilter(System system) {
system.setGlobalOperationalDataFilter(operationalDataFilterService.getDefaultGlobalFilter());
}

public URI getToolContextForGeneralSystem(URI uri){
public URI getToolContextForGeneralSystem(URI uri) {
return GENERAL_SYSTEM_CONTEXT;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import org.springframework.transaction.annotation.Transactional;

import java.net.URI;
import java.util.Map;
import java.util.Optional;

@Slf4j
Expand Down Expand Up @@ -47,7 +48,7 @@ protected GenericDao<User> getPrimaryDao() {
public URI register(User user) {
if (userDao.existsWithUsername(user.getUsername())) {
log.warn("User with username {} already exists", user.getUsername());
throw new UsernameNotAvailableException("Username '" + user.getUsername() + "' has already been used.");
throw new UsernameNotAvailableException( "error.user.usernameNotAvailable","Username '" + user.getUsername() + "' has already been used.", Map.of("username", user.getUsername()));
}

user.setPassword(passwordEncoder.encode(user.getPassword()));
Expand Down

0 comments on commit 4a029e5

Please sign in to comment.