Search in sources :

Example 1 with MailTransportSecurityType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.MailTransportSecurityType in project midpoint by Evolveum.

the class NotificationConfigPanel method initLayout.

@Override
protected void initLayout() {
    TextField<String> defaultFromField = WebComponentUtil.createAjaxTextField(ID_DEFAULT_FROM, new PropertyModel<String>(getModel(), "defaultFrom"));
    CheckBox debugCheck = WebComponentUtil.createAjaxCheckBox(ID_DEBUG, new PropertyModel<Boolean>(getModel(), "debug"));
    DropDownChoice mailServerConfigChooser = new DropDownChoice<>(ID_MAIL_SERVER, new PropertyModel<MailServerConfigurationTypeDto>(getModel(), NotificationConfigurationDto.F_SELECTED_SERVER), new AbstractReadOnlyModel<List<MailServerConfigurationTypeDto>>() {

        @Override
        public List<MailServerConfigurationTypeDto> getObject() {
            return getModel().getObject().getServers();
        }
    }, new ChoiceableChoiceRenderer<MailServerConfigurationTypeDto>());
    mailServerConfigChooser.setNullValid(true);
    mailServerConfigChooser.add(new AjaxFormSubmitBehavior("click") {

        @Override
        protected void onEvent(AjaxRequestTarget target) {
            getForm().onFormSubmitted();
        }
    });
    mailServerConfigChooser.add(new OnChangeAjaxBehavior() {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            preparePasswordFieldPlaceholder();
            target.add(NotificationConfigPanel.this);
        }
    });
    add(mailServerConfigChooser);
    Label serverConfigTooltip = new Label(ID_MAIL_SERVER_TOOLTIP);
    serverConfigTooltip.add(new InfoTooltipBehavior());
    add(serverConfigTooltip);
    WebMarkupContainer serverConfigContainer = new WebMarkupContainer(ID_MAIL_SERVER_CONFIG_CONTAINER);
    serverConfigContainer.setOutputMarkupId(true);
    serverConfigContainer.setOutputMarkupPlaceholderTag(true);
    serverConfigContainer.add(new VisibleEnableBehaviour() {

        @Override
        public boolean isVisible() {
            if (getModelObject() != null) {
                return getModelObject().getSelectedServer() != null;
            }
            return false;
        }
    });
    add(serverConfigContainer);
    TextField<String> hostField = WebComponentUtil.createAjaxTextField(ID_HOST, new PropertyModel<String>(getModel(), "selectedServer.host"));
    TextField<Integer> portField = WebComponentUtil.createAjaxTextField(ID_PORT, new PropertyModel<Integer>(getModel(), "selectedServer.port"));
    TextField<String> userNameField = WebComponentUtil.createAjaxTextField(ID_USERNAME, new PropertyModel<String>(getModel(), "selectedServer.username"));
    PasswordTextField passwordField = new PasswordTextField(ID_PASSWORD, new PropertyModel<String>(getModel(), "selectedServer.password"));
    passwordField.setRequired(false);
    passwordField.add(new EmptyOnChangeAjaxFormUpdatingBehavior());
    TextField<String> redirectToFileField = WebComponentUtil.createAjaxTextField(ID_REDIRECT_TO_FILE, new PropertyModel<String>(getModel(), "redirectToFile"));
    DropDownFormGroup transportSecurity = new DropDownFormGroup<>(ID_TRANSPORT_SECURITY, new PropertyModel<MailTransportSecurityType>(getModel(), "selectedServer.mailTransportSecurityType"), WebComponentUtil.createReadonlyModelFromEnum(MailTransportSecurityType.class), new EnumChoiceRenderer<MailTransportSecurityType>(this), createStringResource("SystemConfigPanel.mail.transportSecurity"), ID_LABEL_SIZE, ID_INPUT_SIZE, false);
    // transportSecurity.add(new EmptyOnChangeAjaxFormUpdatingBehavior());
    serverConfigContainer.add(hostField);
    serverConfigContainer.add(portField);
    serverConfigContainer.add(userNameField);
    serverConfigContainer.add(passwordField);
    serverConfigContainer.add(transportSecurity);
    add(defaultFromField);
    add(debugCheck);
    add(redirectToFileField);
    AjaxSubmitLink buttonAddNewMailServerConfig = new AjaxSubmitLink(ID_BUTTON_ADD_NEW_MAIL_SERVER_CONFIG) {

        @Override
        protected void onSubmit(AjaxRequestTarget target, org.apache.wicket.markup.html.form.Form<?> form) {
            MailServerConfigurationTypeDto newConfig = new MailServerConfigurationTypeDto();
            newConfig.setHost(getString("SystemConfigPanel.mail.config.placeholder"));
            if (getModelObject() != null) {
                getModelObject().getServers().add(newConfig);
                getModelObject().setSelectedServer(newConfig);
            }
            preparePasswordFieldPlaceholder();
            target.add(NotificationConfigPanel.this, getPageBase().getFeedbackPanel());
        }

        @Override
        protected void onError(AjaxRequestTarget target, org.apache.wicket.markup.html.form.Form<?> form) {
            target.add(getPageBase().getFeedbackPanel());
        }
    };
    add(buttonAddNewMailServerConfig);
    AjaxSubmitLink removeMailServerConfig = new AjaxSubmitLink(ID_BUTTON_REMOVE_MAIL_SERVER_CONFIG) {

        @Override
        protected void onSubmit(AjaxRequestTarget target, org.apache.wicket.markup.html.form.Form<?> form) {
            if (getModelObject() != null) {
                NotificationConfigurationDto notificationConfig = getModelObject();
                MailServerConfigurationTypeDto selected = notificationConfig.getSelectedServer();
                if (notificationConfig.getServers().contains(selected)) {
                    notificationConfig.getServers().remove(selected);
                    notificationConfig.setSelectedServer(null);
                } else {
                    warn(getString("SystemConfigPanel.mail.server.remove.warn"));
                }
                target.add(NotificationConfigPanel.this, getPageBase().getFeedbackPanel());
            }
        }

        @Override
        protected void onError(AjaxRequestTarget target, org.apache.wicket.markup.html.form.Form<?> form) {
            target.add(getPageBase().getFeedbackPanel());
        }
    };
    removeMailServerConfig.add(new AttributeAppender("class", new AbstractReadOnlyModel<String>() {

        @Override
        public String getObject() {
            if (getModelObject() != null && getModelObject().getSelectedServer() != null) {
                return null;
            } else {
                return " disabled";
            }
        }
    }));
    add(removeMailServerConfig);
}
Also used : AbstractReadOnlyModel(org.apache.wicket.model.AbstractReadOnlyModel) Label(org.apache.wicket.markup.html.basic.Label) AjaxSubmitLink(org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink) WebMarkupContainer(org.apache.wicket.markup.html.WebMarkupContainer) AjaxFormSubmitBehavior(org.apache.wicket.ajax.form.AjaxFormSubmitBehavior) MailServerConfigurationTypeDto(com.evolveum.midpoint.web.page.admin.configuration.dto.MailServerConfigurationTypeDto) List(java.util.List) VisibleEnableBehaviour(com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour) AttributeAppender(org.apache.wicket.behavior.AttributeAppender) NotificationConfigurationDto(com.evolveum.midpoint.web.page.admin.configuration.dto.NotificationConfigurationDto) DropDownFormGroup(com.evolveum.midpoint.web.component.form.DropDownFormGroup) PasswordTextField(org.apache.wicket.markup.html.form.PasswordTextField) OnChangeAjaxBehavior(org.apache.wicket.ajax.form.OnChangeAjaxBehavior) AjaxRequestTarget(org.apache.wicket.ajax.AjaxRequestTarget) InfoTooltipBehavior(com.evolveum.midpoint.web.util.InfoTooltipBehavior) MailTransportSecurityType(com.evolveum.midpoint.xml.ns._public.common.common_3.MailTransportSecurityType) DropDownChoice(org.apache.wicket.markup.html.form.DropDownChoice) CheckBox(org.apache.wicket.markup.html.form.CheckBox)

Example 2 with MailTransportSecurityType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.MailTransportSecurityType in project midpoint by Evolveum.

the class MailTransport method send.

@Override
public void send(Message mailMessage, String transportName, Event event, Task task, OperationResult parentResult) {
    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo());
    result.addParam("mailMessage subject", mailMessage.getSubject());
    SystemConfigurationType systemConfiguration = NotificationFunctionsImpl.getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy"));
    if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null || systemConfiguration.getNotificationConfiguration().getMail() == null) {
        String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }
    //		if (mailConfigurationType == null) {
    MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail();
    //		}
    String redirectToFile = mailConfigurationType.getRedirectToFile();
    if (redirectToFile != null) {
        try {
            TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage));
            result.recordSuccess();
        } catch (IOException e) {
            LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile);
            result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e);
        }
        return;
    }
    if (mailConfigurationType.getServer().isEmpty()) {
        String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }
    long start = System.currentTimeMillis();
    String defaultFrom = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom() : "nobody@nowhere.org";
    for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) {
        OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer");
        final String host = mailServerConfigurationType.getHost();
        resultForServer.addContext("server", host);
        resultForServer.addContext("port", mailServerConfigurationType.getPort());
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        if (mailServerConfigurationType.getPort() != null) {
            properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort()));
        }
        MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType.getTransportSecurity();
        boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false;
        if (mailTransportSecurityType != null) {
            switch(mailTransportSecurityType) {
                case STARTTLS_ENABLED:
                    starttlsEnable = true;
                    break;
                case STARTTLS_REQUIRED:
                    starttlsEnable = true;
                    starttlsRequired = true;
                    break;
                case SSL:
                    sslEnabled = true;
                    break;
            }
        }
        properties.put("mail.smtp.ssl.enable", "" + sslEnabled);
        properties.put("mail.smtp.starttls.enable", "" + starttlsEnable);
        properties.put("mail.smtp.starttls.required", "" + starttlsRequired);
        if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) {
            properties.put("mail.debug", "true");
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Using mail properties: ");
            for (Object key : properties.keySet()) {
                if (key instanceof String && ((String) key).startsWith("mail.")) {
                    LOGGER.debug(" - " + key + " = " + properties.get(key));
                }
            }
        }
        task.recordState("Sending notification mail via " + host);
        Session session = Session.getInstance(properties);
        try {
            MimeMessage mimeMessage = new MimeMessage(session);
            String from = mailMessage.getFrom() != null ? mailMessage.getFrom() : defaultFrom;
            mimeMessage.setFrom(new InternetAddress(from));
            for (String recipient : mailMessage.getTo()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
            }
            for (String recipientCc : mailMessage.getCc()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(recipientCc));
            }
            for (String recipientBcc : mailMessage.getBcc()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipientBcc));
            }
            mimeMessage.setSubject(mailMessage.getSubject(), "utf-8");
            String contentType = mailMessage.getContentType();
            if (StringUtils.isEmpty(contentType)) {
                contentType = "text/plain; charset=UTF-8";
            }
            mimeMessage.setContent(mailMessage.getBody(), contentType);
            javax.mail.Transport t = session.getTransport("smtp");
            if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) {
                ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword();
                String password = null;
                if (passwordProtected != null) {
                    try {
                        password = protector.decryptString(passwordProtected);
                    } catch (EncryptionException e) {
                        String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any.";
                        LoggingUtils.logException(LOGGER, msg, e);
                        resultForServer.recordFatalError(msg, e);
                        continue;
                    }
                }
                t.connect(mailServerConfigurationType.getUsername(), password);
            } else {
                t.connect();
            }
            t.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + ".");
            resultForServer.recordSuccess();
            result.recordSuccess();
            long duration = System.currentTimeMillis() - start;
            task.recordState("Notification mail sent successfully via " + host + ", in " + duration + " ms overall.");
            task.recordNotificationOperation(NAME, true, duration);
            return;
        } catch (MessagingException e) {
            String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", trying another mail server, if there is any";
            LoggingUtils.logException(LOGGER, msg, e);
            resultForServer.recordFatalError(msg, e);
            task.recordState("Error sending notification mail via " + host);
        }
    }
    LOGGER.warn("No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent.");
    result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent.");
    task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) MailConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.MailConfigurationType) MailServerConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.MailServerConfigurationType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) IOException(java.io.IOException) Properties(java.util.Properties) MailTransportSecurityType(com.evolveum.midpoint.xml.ns._public.common.common_3.MailTransportSecurityType) MimeMessage(javax.mail.internet.MimeMessage) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) SystemConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) Session(javax.mail.Session)

Aggregations

MailTransportSecurityType (com.evolveum.midpoint.xml.ns._public.common.common_3.MailTransportSecurityType)2 EncryptionException (com.evolveum.midpoint.prism.crypto.EncryptionException)1 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)1 DropDownFormGroup (com.evolveum.midpoint.web.component.form.DropDownFormGroup)1 VisibleEnableBehaviour (com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour)1 MailServerConfigurationTypeDto (com.evolveum.midpoint.web.page.admin.configuration.dto.MailServerConfigurationTypeDto)1 NotificationConfigurationDto (com.evolveum.midpoint.web.page.admin.configuration.dto.NotificationConfigurationDto)1 InfoTooltipBehavior (com.evolveum.midpoint.web.util.InfoTooltipBehavior)1 MailConfigurationType (com.evolveum.midpoint.xml.ns._public.common.common_3.MailConfigurationType)1 MailServerConfigurationType (com.evolveum.midpoint.xml.ns._public.common.common_3.MailServerConfigurationType)1 SystemConfigurationType (com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType)1 ProtectedStringType (com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType)1 IOException (java.io.IOException)1 List (java.util.List)1 Properties (java.util.Properties)1 MessagingException (javax.mail.MessagingException)1 Session (javax.mail.Session)1 InternetAddress (javax.mail.internet.InternetAddress)1 MimeMessage (javax.mail.internet.MimeMessage)1 AjaxRequestTarget (org.apache.wicket.ajax.AjaxRequestTarget)1