use of org.eclipse.vorto.repository.web.api.v1.dto.OperationResult in project vorto by eclipse.
the class NamespaceController method requestAccessToNamespace.
@PostMapping("/requestAccess")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<OperationResult> requestAccessToNamespace(@RequestBody @ApiParam(value = "The request body specifying who initiates the request, the namespace, whom the request is intended for, and an optional collection of suggested roles", required = true) NamespaceAccessRequestDTO request) {
Optional<OperationResult> validationError = NamespaceValidator.validateAccessRequest(request);
if (validationError.isPresent()) {
return new ResponseEntity<>(validationError.get(), HttpStatus.BAD_REQUEST);
}
// checks namespace exists
// should only occur if namespace was deleted after user search, but before sending request
Namespace target;
try {
target = namespaceService.getByName(request.getNamespaceName());
} catch (DoesNotExistException dnee) {
return new ResponseEntity<>(OperationResult.failure("Namespace not found."), HttpStatus.NOT_FOUND);
}
// checks any admin with an e-mail address set
Set<User> adminsWithEmail = userNamespaceRoleRepository.findAllByNamespace(target).stream().map(UserNamespaceRoles::getUser).filter(u -> !Strings.nullToEmpty(u.getEmailAddress()).trim().isEmpty()).collect(Collectors.toSet());
if (adminsWithEmail.isEmpty()) {
return new ResponseEntity<>(OperationResult.failure(String.format("None of the users administrating namespace %s has set their own e-mail. Please contact them directly. ", request.getNamespaceName())), HttpStatus.PRECONDITION_FAILED);
}
int successCount = adminsWithEmail.size();
// attempts to send the e-mails
// ugly exception handling here, due to the way this was designed in the service
Collection<IMessage> messages = adminsWithEmail.stream().map(u -> new RequestAccessToNamespaceMessage(request, u, host)).collect(Collectors.toList());
for (IMessage message : messages) {
try {
emailNotificationService.sendNotification(message);
} catch (NotificationProblem np) {
successCount--;
}
}
// worked for all recipients
if (successCount == adminsWithEmail.size()) {
return new ResponseEntity<>(OperationResult.success(), HttpStatus.OK);
} else // worked for some recipients
if (successCount > 0) {
return new ResponseEntity<>(OperationResult.success("The message could not be sent to all administrators."), HttpStatus.OK);
} else // did not work for any recipient
{
return new ResponseEntity<>(OperationResult.failure("The message could not be sent to any administrator."), HttpStatus.SERVICE_UNAVAILABLE);
}
}
Aggregations