Search in sources :

Example 46 with TechnicalManagementException

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);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) GenericNotificationConfig(io.gravitee.repository.management.model.GenericNotificationConfig) BadNotificationConfigException(io.gravitee.rest.api.service.exceptions.BadNotificationConfigException) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Example 47 with TechnicalManagementException

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;
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Page(io.gravitee.common.data.domain.Page) MetadataPage(io.gravitee.common.data.domain.MetadataPage) UuidString(io.gravitee.rest.api.service.common.UuidString) UserEntity(io.gravitee.rest.api.model.UserEntity) AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Example 48 with TechnicalManagementException

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("&lt;br /&gt;", "<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);
        }
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) JavaMailSender(org.springframework.mail.javamail.JavaMailSender) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper) Key(io.gravitee.rest.api.model.parameters.Key) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Example 49 with TechnicalManagementException

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");
    }
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Notification(io.gravitee.notifier.api.Notification) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Example 50 with TechnicalManagementException

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);
    }
}
Also used : Buffer(io.vertx.core.buffer.Buffer) UuidString(io.gravitee.rest.api.service.common.UuidString) ProxyOptions(io.vertx.core.net.ProxyOptions) HttpHeaders(io.gravitee.common.http.HttpHeaders) Logger(org.slf4j.Logger) io.vertx.core(io.vertx.core) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) io.vertx.core.http(io.vertx.core.http) HttpStatusCode(io.gravitee.common.http.HttpStatusCode) ExecutionException(java.util.concurrent.ExecutionException) Value(org.springframework.beans.factory.annotation.Value) Component(org.springframework.stereotype.Component) MediaType(io.gravitee.common.http.MediaType) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException) HttpMethod(io.gravitee.common.http.HttpMethod) Buffer(io.vertx.core.buffer.Buffer) ProxyType(io.vertx.core.net.ProxyType) Map(java.util.Map) HttpClientService(io.gravitee.rest.api.service.HttpClientService) URI(java.net.URI) URI(java.net.URI) ExecutionException(java.util.concurrent.ExecutionException) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Aggregations

TechnicalManagementException (io.gravitee.rest.api.service.exceptions.TechnicalManagementException)149 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)120 UuidString (io.gravitee.rest.api.service.common.UuidString)26 Date (java.util.Date)23 Component (org.springframework.stereotype.Component)18 Logger (org.slf4j.Logger)17 LoggerFactory (org.slf4j.LoggerFactory)17 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)16 Collectors (java.util.stream.Collectors)13 Autowired (org.springframework.beans.factory.annotation.Autowired)13 IOException (java.io.IOException)12 JsonNode (com.fasterxml.jackson.databind.JsonNode)11 Rating (io.gravitee.repository.management.model.Rating)9 ApiRatingUnavailableException (io.gravitee.rest.api.service.exceptions.ApiRatingUnavailableException)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)8 Dictionary (io.gravitee.repository.management.model.Dictionary)8 AuditService (io.gravitee.rest.api.service.AuditService)8 java.util (java.util)8 Theme (io.gravitee.repository.management.model.Theme)6 List (java.util.List)6