use of io.gravitee.rest.api.service.exceptions.TechnicalManagementException in project gravitee-management-rest-api by gravitee-io.
the class GenericNotificationConfigServiceImpl method create.
@Override
public GenericNotificationConfigEntity create(GenericNotificationConfigEntity entity) {
if (entity.getNotifier() == null || entity.getNotifier().isEmpty() || entity.getName() == null || entity.getName().isEmpty()) {
throw new BadNotificationConfigException();
}
try {
GenericNotificationConfig notificationConfig = convert(entity);
notificationConfig.setId(UuidString.generateRandom());
notificationConfig.setCreatedAt(new Date());
notificationConfig.setUpdatedAt(notificationConfig.getCreatedAt());
return convert(genericNotificationConfigRepository.create(notificationConfig));
} catch (TechnicalException te) {
LOGGER.error("An error occurs while trying to save the generic notification settings {}", entity, te);
throw new TechnicalManagementException("An error occurs while trying to save the generic notification settings " + entity, te);
}
}
use of io.gravitee.rest.api.service.exceptions.TechnicalManagementException in project gravitee-management-rest-api by gravitee-io.
the class AuditServiceImpl method getMetadata.
private Map<String, String> getMetadata(List<AuditEntity> content) {
Map<String, String> metadata = new HashMap<>();
for (AuditEntity auditEntity : content) {
// add user's display name
String metadataKey = "USER:" + auditEntity.getUser() + ":name";
try {
UserEntity user = userService.findById(auditEntity.getUser());
metadata.put(metadataKey, user.getDisplayName());
} catch (TechnicalManagementException e) {
LOGGER.error("Error finding metadata {}", auditEntity.getUser());
} catch (UserNotFoundException unfe) {
metadata.put(metadataKey, auditEntity.getUser());
}
if (Audit.AuditReferenceType.API.name().equals(auditEntity.getReferenceType())) {
metadataKey = "API:" + auditEntity.getReferenceId() + ":name";
if (!metadata.containsKey(metadataKey)) {
try {
Optional<Api> optApi = apiRepository.findById(auditEntity.getReferenceId());
if (optApi.isPresent()) {
metadata.put(metadataKey, optApi.get().getName());
}
} catch (TechnicalException e) {
LOGGER.error("Error finding metadata {}", metadataKey);
metadata.put(metadataKey, auditEntity.getReferenceId());
}
}
} else if (Audit.AuditReferenceType.APPLICATION.name().equals(auditEntity.getReferenceType())) {
metadataKey = "APPLICATION:" + auditEntity.getReferenceId() + ":name";
if (!metadata.containsKey(metadataKey)) {
try {
Optional<Application> optApp = applicationRepository.findById(auditEntity.getReferenceId());
if (optApp.isPresent()) {
metadata.put(metadataKey, optApp.get().getName());
}
} catch (TechnicalException e) {
LOGGER.error("Error finding metadata {}", metadataKey);
metadata.put(metadataKey, auditEntity.getReferenceId());
}
}
}
// add property metadata
String name;
if (auditEntity.getProperties() != null) {
for (Map.Entry<String, String> property : auditEntity.getProperties().entrySet()) {
metadataKey = new StringJoiner(":").add(property.getKey()).add(property.getValue()).add("name").toString();
if (!metadata.containsKey(metadataKey)) {
name = property.getValue();
try {
switch(Audit.AuditProperties.valueOf(property.getKey())) {
case API:
Optional<Api> optApi = apiRepository.findById(property.getValue());
if (optApi.isPresent()) {
name = optApi.get().getName();
}
break;
case APPLICATION:
Optional<Application> optApp = applicationRepository.findById(property.getValue());
if (optApp.isPresent()) {
name = optApp.get().getName();
}
break;
case PAGE:
Optional<io.gravitee.repository.management.model.Page> optPage = pageRepository.findById(property.getValue());
if (optPage.isPresent()) {
name = optPage.get().getName();
}
break;
case PLAN:
Optional<Plan> optPlan = planRepository.findById(property.getValue());
if (optPlan.isPresent()) {
name = optPlan.get().getName();
}
break;
case METADATA:
MetadataReferenceType refType = (Audit.AuditReferenceType.API.name().equals(auditEntity.getReferenceType())) ? MetadataReferenceType.API : (Audit.AuditReferenceType.APPLICATION.name().equals(auditEntity.getReferenceType())) ? MetadataReferenceType.APPLICATION : MetadataReferenceType.DEFAULT;
String refId = refType.equals(MetadataReferenceType.DEFAULT) ? getDefaultReferenceId() : auditEntity.getReferenceId();
Optional<Metadata> optMetadata = metadataRepository.findById(property.getValue(), refId, refType);
if (optMetadata.isPresent()) {
name = optMetadata.get().getName();
}
break;
case GROUP:
Optional<Group> optGroup = groupRepository.findById(property.getValue());
if (optGroup.isPresent()) {
name = optGroup.get().getName();
}
break;
case USER:
try {
UserEntity user = userService.findById(property.getValue());
name = user.getDisplayName();
} catch (UserNotFoundException unfe) {
name = property.getValue();
}
default:
break;
}
} catch (TechnicalException e) {
LOGGER.error("Error finding metadata {}", metadataKey);
name = property.getValue();
}
metadata.put(metadataKey, name);
}
}
}
}
return metadata;
}
use of io.gravitee.rest.api.service.exceptions.TechnicalManagementException in project gravitee-management-rest-api by gravitee-io.
the class EmailServiceImpl method sendEmailNotification.
private void sendEmailNotification(final EmailNotification emailNotification, String referenceId, ParameterReferenceType referenceType) {
Map<Key, String> mailParameters = getMailSenderConfiguration(referenceId, referenceType);
if (Boolean.parseBoolean(mailParameters.get(EMAIL_ENABLED)) && emailNotification.getTo() != null && emailNotification.getTo().length > 0) {
try {
JavaMailSender mailSender = mailManager.getOrCreateMailSender(referenceId, referenceType);
final MimeMessageHelper mailMessage = new MimeMessageHelper(mailSender.createMimeMessage(), true, StandardCharsets.UTF_8.name());
String emailSubject = notificationTemplateService.resolveTemplateWithParam(emailNotification.getTemplate() + ".EMAIL.TITLE", emailNotification.getParams());
String content = notificationTemplateService.resolveTemplateWithParam(emailNotification.getTemplate() + ".EMAIL", emailNotification.getParams());
content = content.replaceAll("<br />", "<br />");
final String from = isNull(emailNotification.getFrom()) || emailNotification.getFrom().isEmpty() ? mailParameters.get(EMAIL_FROM) : emailNotification.getFrom();
InternetAddress configuredFrom = new InternetAddress(from);
if (isEmpty(configuredFrom.getPersonal())) {
if (isEmpty(emailNotification.getFromName())) {
mailMessage.setFrom(from);
} else {
mailMessage.setFrom(from, emailNotification.getFromName());
}
} else {
mailMessage.setFrom(configuredFrom);
}
String sender = emailNotification.getFrom();
if (!isEmpty(emailNotification.getReplyTo())) {
mailMessage.setReplyTo(emailNotification.getReplyTo());
sender = emailNotification.getReplyTo();
}
if (Arrays.equals(DEFAULT_MAIL_TO, emailNotification.getTo())) {
mailMessage.setTo(mailParameters.get(Key.EMAIL_FROM));
} else {
mailMessage.setTo(emailNotification.getTo());
}
if (emailNotification.isCopyToSender() && sender != null) {
mailMessage.setBcc(sender);
}
if (emailNotification.getBcc() != null && emailNotification.getBcc().length > 0) {
mailMessage.setBcc(emailNotification.getBcc());
}
mailMessage.setSubject(format(mailParameters.get(EMAIL_SUBJECT), emailSubject));
final String html = addResourcesInMessage(mailMessage, content);
LOGGER.debug("Sending an email to: {}\nSubject: {}\nMessage: {}", emailNotification.getTo(), emailSubject, html);
mailSender.send(mailMessage.getMimeMessage());
} catch (final Exception ex) {
LOGGER.error("Error while sending email notification", ex);
throw new TechnicalManagementException("Error while sending email notification", ex);
}
}
}
use of io.gravitee.rest.api.service.exceptions.TechnicalManagementException in project gravitee-management-rest-api by gravitee-io.
the class ApplicationAlertServiceImpl method createNotification.
private List<Notification> createNotification(String alertType, List<String> recipients) {
try {
Notification notification = new Notification();
notification.setType(DEFAULT_EMAIL_NOTIFIER);
ObjectNode configuration = mapper.createObjectNode();
configuration.put("from", emailFrom);
configuration.put("to", String.join(",", recipients));
generateNotificationBodyFromTemplate(configuration, alertType);
notification.setPeriods(emptyList());
notification.setConfiguration(mapper.writeValueAsString(configuration));
return singletonList(notification);
} catch (JsonProcessingException e) {
LOGGER.error("An error occurs while trying to create the Alert notification", e);
throw new TechnicalManagementException("An error occurs while trying to create the Alert notification");
}
}
use of io.gravitee.rest.api.service.exceptions.TechnicalManagementException in project gravitee-management-rest-api by gravitee-io.
the class HttpClientServiceImpl method request.
@Override
public Buffer request(HttpMethod method, String uri, Map<String, String> headers, String body, Boolean useSystemProxy) {
if (uri == null || uri.isEmpty()) {
LOGGER.error("HttpClient configuration is empty");
return null;
}
Promise<Buffer> promise = Promise.promise();
URI requestUri = URI.create(uri);
final HttpClient httpClient = this.getHttpClient(requestUri.getScheme(), useSystemProxy);
final int port = requestUri.getPort() != -1 ? requestUri.getPort() : (HTTPS_SCHEME.equals(requestUri.getScheme()) ? 443 : 80);
RequestOptions options = new RequestOptions().setMethod(io.vertx.core.http.HttpMethod.valueOf(method.name())).setHost(requestUri.getHost()).setPort(port).setURI(requestUri.getPath()).setTimeout(httpClientTimeout);
// headers
if (headers != null) {
headers.forEach(options::putHeader);
}
options.putHeader("X-Gravitee-Request-Id", UuidString.generateRandom().trim());
if (body != null) {
if (!options.getHeaders().contains(HttpHeaders.CONTENT_TYPE)) {
options.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
}
options.putHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(body.getBytes().length));
}
Future<HttpClientRequest> requestFuture = httpClient.request(options);
requestFuture.onFailure(new Handler<Throwable>() {
@Override
public void handle(Throwable throwable) {
promise.fail(throwable);
// Close client
httpClient.close();
}
}).onSuccess(new Handler<HttpClientRequest>() {
@Override
public void handle(HttpClientRequest request) {
request.response(new Handler<AsyncResult<HttpClientResponse>>() {
@Override
public void handle(AsyncResult<HttpClientResponse> asyncResponse) {
if (asyncResponse.failed()) {
promise.fail(asyncResponse.cause());
// Close client
httpClient.close();
} else {
HttpClientResponse response = asyncResponse.result();
LOGGER.debug("Web response status code : {}", response.statusCode());
if (response.statusCode() >= HttpStatusCode.OK_200 && response.statusCode() <= 299) {
response.bodyHandler(buffer -> {
promise.complete(buffer);
// Close client
httpClient.close();
});
} else {
response.bodyHandler(buffer -> promise.fail(new TechnicalManagementException(" Error on url '" + uri + "'. Status code: " + response.statusCode() + ". Message: " + buffer.toString(), null)));
}
}
}
}).exceptionHandler(new Handler<Throwable>() {
@Override
public void handle(Throwable throwable) {
promise.fail(throwable);
// Close client
httpClient.close();
}
});
if (body != null) {
request.end(body);
} else {
request.end();
}
}
});
try {
return promise.future().toCompletionStage().toCompletableFuture().get();
} catch (InterruptedException | ExecutionException e) {
throw new TechnicalManagementException(e.getMessage(), e);
}
}
Aggregations