Search in sources :

Example 1 with Key

use of io.gravitee.rest.api.model.parameters.Key in project gravitee-management-rest-api by gravitee-io.

the class ParameterServiceTest method shouldFindAllKeysWithFilter.

@Test
public void shouldFindAllKeysWithFilter() throws TechnicalException {
    final Key p1key = PORTAL_TOP_APIS;
    final Key p2key = PORTAL_ANALYTICS_ENABLED;
    final Key p3key = PORTAL_ANALYTICS_TRACKINGID;
    final Parameter parameter1 = new Parameter();
    parameter1.setKey(PORTAL_TOP_APIS.key());
    parameter1.setValue("api1;api2;;api1");
    final Parameter parameter2 = new Parameter();
    parameter2.setKey(PORTAL_ANALYTICS_ENABLED.key());
    parameter2.setValue("api3;api4;;api5");
    final Parameter parameter3 = new Parameter();
    parameter3.setKey(PORTAL_ANALYTICS_TRACKINGID.key());
    when(parameterRepository.findByKeys(Arrays.asList(PORTAL_TOP_APIS.key(), PORTAL_ANALYTICS_ENABLED.key(), PORTAL_ANALYTICS_TRACKINGID.key()), "DEFAULT", ParameterReferenceType.ENVIRONMENT)).thenReturn(Arrays.asList(parameter1, parameter2, parameter3));
    final Map<String, List<String>> values = parameterService.findAll(Arrays.asList(p1key, p2key, p3key), value -> value, value -> !value.isEmpty(), io.gravitee.rest.api.model.parameters.ParameterReferenceType.ENVIRONMENT);
    assertEquals(asList("api1", "api2", "api1"), values.get(p1key.key()));
    assertEquals(asList("api3", "api4", "api5"), values.get(p2key.key()));
    assertTrue(values.get(p3key.key()).isEmpty());
}
Also used : Parameter(io.gravitee.repository.management.model.Parameter) Arrays.asList(java.util.Arrays.asList) Key(io.gravitee.rest.api.model.parameters.Key) Test(org.junit.Test)

Example 2 with Key

use of io.gravitee.rest.api.model.parameters.Key in project gravitee-management-rest-api by gravitee-io.

the class GraviteeJavaMailManagerTest method shouldInializeOnlyOnceWhenGettingMailManager.

@Test
public void shouldInializeOnlyOnceWhenGettingMailManager() {
    GraviteeContext.setCurrentEnvironment("DEFAULT");
    assertNull(graviteeJavaMailManager.getMailSenderByReference(GraviteeContext.getCurrentContext()));
    // Initialize the field only when we get the mail sender for the first time.
    JavaMailSender mailSender = graviteeJavaMailManager.getOrCreateMailSender("DEFAULT", ParameterReferenceType.ENVIRONMENT);
    assertNotNull(mailSender);
    // If we call this getter a second time, then we do not initialize anymore
    JavaMailSender mailSender2 = graviteeJavaMailManager.getOrCreateMailSender("DEFAULT", ParameterReferenceType.ENVIRONMENT);
    assertSame(mailSender, mailSender2);
    verify(parameterService, times(1)).find(Key.EMAIL_HOST, "DEFAULT", ParameterReferenceType.ENVIRONMENT);
    verify(parameterService, times(1)).find(Key.EMAIL_PORT, "DEFAULT", ParameterReferenceType.ENVIRONMENT);
    verify(parameterService, times(1)).find(Key.EMAIL_USERNAME, "DEFAULT", ParameterReferenceType.ENVIRONMENT);
    verify(parameterService, times(1)).find(Key.EMAIL_PASSWORD, "DEFAULT", ParameterReferenceType.ENVIRONMENT);
    verify(parameterService, times(1)).find(Key.EMAIL_PROTOCOL, "DEFAULT", ParameterReferenceType.ENVIRONMENT);
    verify(parameterService, times(1)).findAll(argThat((List<Key> o) -> o.contains(Key.EMAIL_PROPERTIES_AUTH_ENABLED) && o.contains(Key.EMAIL_PROPERTIES_STARTTLS_ENABLE) && o.contains(Key.EMAIL_PROPERTIES_SSL_TRUST)), eq("DEFAULT"), eq(ParameterReferenceType.ENVIRONMENT));
}
Also used : JavaMailSender(org.springframework.mail.javamail.JavaMailSender) Key(io.gravitee.rest.api.model.parameters.Key) Test(org.junit.Test)

Example 3 with Key

use of io.gravitee.rest.api.model.parameters.Key in project gravitee-management-rest-api by gravitee-io.

the class ConfigServiceImpl method loadConfigByReference.

private void loadConfigByReference(Object[] objects, AbstractCommonSettingsEntity configEntity, String referenceId, ParameterReferenceType referenceType) {
    // get values from DB
    final List<Key> parameterKeys = new ArrayList<>();
    for (Object o : objects) {
        for (Field f : o.getClass().getDeclaredFields()) {
            ParameterKey parameterKey = f.getAnnotation(ParameterKey.class);
            if (parameterKey != null) {
                parameterKeys.add(parameterKey.value());
            }
        }
    }
    Map<String, List<String>> parameterMap = parameterService.findAll(parameterKeys, value -> value == null ? null : value.trim(), referenceId, referenceType);
    // set values
    for (Object o : objects) {
        for (Field f : o.getClass().getDeclaredFields()) {
            ParameterKey parameterKey = f.getAnnotation(ParameterKey.class);
            if (parameterKey != null) {
                boolean accessible = f.isAccessible();
                f.setAccessible(true);
                try {
                    List<String> values = parameterMap.get(parameterKey.value().key());
                    if (environment.containsProperty(parameterKey.value().key())) {
                        configEntity.getMetadata().add(PortalSettingsEntity.METADATA_READONLY, parameterKey.value().key());
                    }
                    final String defaultValue = parameterKey.value().defaultValue();
                    if (Enabled.class.isAssignableFrom(f.getType())) {
                        f.set(o, Boolean.parseBoolean(getFirstValueOrDefault(values, defaultValue)) ? new Enabled(true) : new Enabled(false));
                    } else if (Boolean.class.isAssignableFrom(f.getType())) {
                        f.set(o, Boolean.valueOf(getFirstValueOrDefault(values, defaultValue)));
                    } else if (Integer.class.isAssignableFrom(f.getType())) {
                        f.set(o, Integer.valueOf(getFirstValueOrDefault(values, defaultValue)));
                    } else if (Long.class.isAssignableFrom(f.getType())) {
                        f.set(o, Long.valueOf(getFirstValueOrDefault(values, defaultValue)));
                    } else if (List.class.isAssignableFrom(f.getType())) {
                        if (values == null || values.isEmpty()) {
                            if (StringUtils.isNotEmpty(defaultValue)) {
                                f.set(o, Arrays.asList(defaultValue.split(SEPARATOR)));
                            } else {
                                f.set(o, emptyList());
                            }
                        } else {
                            f.set(o, values);
                        }
                    } else if (Map.class.isAssignableFrom(f.getType())) {
                        if (values == null || values.isEmpty()) {
                            if (defaultValue == null) {
                                f.set(o, emptyMap());
                            } else {
                                f.set(o, singletonMap(defaultValue.split(KV_SEPARATOR)[0], defaultValue.split(KV_SEPARATOR)[1]));
                            }
                        } else {
                            f.set(o, values.stream().collect(toMap(v -> v.split(KV_SEPARATOR)[0], v -> {
                                final String[] split = v.split(KV_SEPARATOR);
                                if (split.length < 2) {
                                    return "";
                                }
                                return split[1];
                            })));
                        }
                    } else {
                        // If the parameter contains a sensitive info, we return dummy value
                        if (!parameterKey.sensitive()) {
                            f.set(o, getFirstValueOrDefault(values, defaultValue));
                        } else {
                            f.set(o, SENSITIVE_VALUE);
                        }
                    }
                } catch (IllegalAccessException e) {
                    LOGGER.error("Unable to set parameter {}. Use the default value", parameterKey.value().key(), e);
                }
                f.setAccessible(accessible);
            }
        }
    }
}
Also used : ConfigService(io.gravitee.rest.api.service.ConfigService) Arrays(java.util.Arrays) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) SEPARATOR(io.gravitee.rest.api.service.impl.ParameterServiceImpl.SEPARATOR) StringUtils(org.apache.commons.lang3.StringUtils) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ArrayList(java.util.ArrayList) NewsletterService(io.gravitee.rest.api.service.NewsletterService) Collectors.toMap(java.util.stream.Collectors.toMap) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Map(java.util.Map) ParameterService(io.gravitee.rest.api.service.ParameterService) Logger(org.slf4j.Logger) ParameterReferenceType(io.gravitee.rest.api.model.parameters.ParameterReferenceType) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) io.gravitee.rest.api.model.settings(io.gravitee.rest.api.model.settings) Field(java.lang.reflect.Field) Key(io.gravitee.rest.api.model.parameters.Key) List(java.util.List) Component(org.springframework.stereotype.Component) ParameterKey(io.gravitee.rest.api.model.annotations.ParameterKey) KV_SEPARATOR(io.gravitee.rest.api.service.impl.ParameterServiceImpl.KV_SEPARATOR) Collections(java.util.Collections) ReCaptchaService(io.gravitee.rest.api.service.ReCaptchaService) ArrayList(java.util.ArrayList) ParameterKey(io.gravitee.rest.api.model.annotations.ParameterKey) Field(java.lang.reflect.Field) ArrayList(java.util.ArrayList) List(java.util.List) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) Key(io.gravitee.rest.api.model.parameters.Key) ParameterKey(io.gravitee.rest.api.model.annotations.ParameterKey)

Example 4 with Key

use of io.gravitee.rest.api.model.parameters.Key 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 5 with Key

use of io.gravitee.rest.api.model.parameters.Key in project gravitee-management-rest-api by gravitee-io.

the class ParameterServiceImpl method findAll.

@Override
public <T> Map<String, List<T>> findAll(List<Key> keys, Function<String, T> mapper, Predicate<String> filter, final String referenceId, final io.gravitee.rest.api.model.parameters.ParameterReferenceType referenceType) {
    String refIdToUse = getEffectiveReferenceId(referenceId, referenceType);
    try {
        List<Key> keysToFind = new ArrayList<>(keys);
        Map<String, List<T>> result = new HashMap<>();
        // Get System parameters
        for (Key keyToFind : keys) {
            this.getSystemParameter(keyToFind).ifPresent(p -> {
                result.put(p.getKey(), splitValue(p.getValue(), mapper, filter));
                keysToFind.remove(keyToFind);
            });
        }
        if (!keysToFind.isEmpty()) {
            switch(referenceType) {
                case ENVIRONMENT:
                    this.getEnvParameters(keysToFind, refIdToUse).forEach(p -> {
                        result.put(p.getKey(), splitValue(p.getValue(), mapper, filter));
                        keysToFind.remove(Key.findByKey(p.getKey()));
                    });
                    if (!keysToFind.isEmpty()) {
                        // String organizationId = "DEFAULT";//environmentService.findById(referenceId).getOrganizationId();
                        String organizationId = environmentService.findById(refIdToUse).getOrganizationId();
                        this.getOrgParameters(keysToFind, organizationId).forEach(p -> {
                            result.put(p.getKey(), splitValue(p.getValue(), mapper, filter));
                            keysToFind.remove(Key.findByKey(p.getKey()));
                        });
                        if (!keysToFind.isEmpty()) {
                            keysToFind.forEach(k -> result.put(k.key(), splitValue(k.defaultValue(), mapper, filter)));
                        }
                    }
                    break;
                case ORGANIZATION:
                    this.getOrgParameters(keysToFind, refIdToUse).forEach(p -> {
                        result.put(p.getKey(), splitValue(p.getValue(), mapper, filter));
                        keysToFind.remove(Key.findByKey(p.getKey()));
                    });
                    if (!keysToFind.isEmpty()) {
                        keysToFind.forEach(k -> result.put(k.key(), splitValue(k.defaultValue(), mapper, filter)));
                    }
                    break;
                default:
                    keysToFind.forEach(k -> result.put(k.key(), splitValue(k.defaultValue(), mapper, filter)));
                    break;
            }
        }
        return result;
    } catch (final TechnicalException ex) {
        final String message = "An error occurs while trying to find parameter values with keys: " + keys;
        LOGGER.error(message, ex);
        throw new TechnicalManagementException(message, ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Collections.emptyList(java.util.Collections.emptyList) Collectors.toList(java.util.stream.Collectors.toList) Key(io.gravitee.rest.api.model.parameters.Key) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Aggregations

Key (io.gravitee.rest.api.model.parameters.Key)8 Test (org.junit.Test)4 Parameter (io.gravitee.repository.management.model.Parameter)3 Arrays.asList (java.util.Arrays.asList)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)2 ParameterReferenceType (io.gravitee.rest.api.model.parameters.ParameterReferenceType)2 GraviteeContext (io.gravitee.rest.api.service.common.GraviteeContext)2 TechnicalManagementException (io.gravitee.rest.api.service.exceptions.TechnicalManagementException)2 JavaMailSender (org.springframework.mail.javamail.JavaMailSender)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)1 Page (io.gravitee.common.data.domain.Page)1 ApplicationRepository (io.gravitee.repository.management.api.ApplicationRepository)1 MembershipRepository (io.gravitee.repository.management.api.MembershipRepository)1 ApplicationCriteria (io.gravitee.repository.management.api.search.ApplicationCriteria)1 io.gravitee.repository.management.model (io.gravitee.repository.management.model)1 AuditEvent (io.gravitee.repository.management.model.Application.AuditEvent)1 io.gravitee.rest.api.model (io.gravitee.rest.api.model)1 MembershipMemberType (io.gravitee.rest.api.model.MembershipMemberType)1