Search in sources :

Example 51 with DataSource

use of javax.activation.DataSource in project oozie by apache.

the class EmailActionExecutor method email.

public void email(String[] to, String[] cc, String[] bcc, String subject, String body, String[] attachments, String contentType, String user) throws ActionExecutorException {
    // Get mailing server details.
    String smtpHost = ConfigurationService.get(EMAIL_SMTP_HOST);
    Integer smtpPortInt = ConfigurationService.getInt(EMAIL_SMTP_PORT);
    Boolean smtpAuthBool = ConfigurationService.getBoolean(EMAIL_SMTP_AUTH);
    String smtpUser = ConfigurationService.get(EMAIL_SMTP_USER);
    String smtpPassword = ConfigurationService.getPassword(EMAIL_SMTP_PASS, "");
    String fromAddr = ConfigurationService.get(EMAIL_SMTP_FROM);
    Integer timeoutMillisInt = ConfigurationService.getInt(EMAIL_SMTP_SOCKET_TIMEOUT_MS);
    Properties properties = new Properties();
    properties.setProperty("mail.smtp.host", smtpHost);
    properties.setProperty("mail.smtp.port", smtpPortInt.toString());
    properties.setProperty("mail.smtp.auth", smtpAuthBool.toString());
    // Apply sensible timeouts, as defaults are infinite. See https://s.apache.org/javax-mail-timeouts
    properties.setProperty("mail.smtp.connectiontimeout", timeoutMillisInt.toString());
    properties.setProperty("mail.smtp.timeout", timeoutMillisInt.toString());
    properties.setProperty("mail.smtp.writetimeout", timeoutMillisInt.toString());
    Session session;
    // (cause it may lead to issues when used second time).
    if (!smtpAuthBool) {
        session = Session.getInstance(properties);
    } else {
        session = Session.getInstance(properties, new JavaMailAuthenticator(smtpUser, smtpPassword));
    }
    Message message = new MimeMessage(session);
    InternetAddress from;
    List<InternetAddress> toAddrs = new ArrayList<InternetAddress>(to.length);
    List<InternetAddress> ccAddrs = new ArrayList<InternetAddress>(cc.length);
    List<InternetAddress> bccAddrs = new ArrayList<InternetAddress>(bcc.length);
    try {
        from = new InternetAddress(fromAddr);
        message.setFrom(from);
    } catch (AddressException e) {
        throw new ActionExecutorException(ErrorType.ERROR, "EM002", "Bad from address specified in ${oozie.email.from.address}.", e);
    } catch (MessagingException e) {
        throw new ActionExecutorException(ErrorType.ERROR, "EM003", "Error setting a from address in the message.", e);
    }
    try {
        // Add all <to>
        for (String toStr : to) {
            toAddrs.add(new InternetAddress(toStr.trim()));
        }
        message.addRecipients(RecipientType.TO, toAddrs.toArray(new InternetAddress[0]));
        // Add all <cc>
        for (String ccStr : cc) {
            ccAddrs.add(new InternetAddress(ccStr.trim()));
        }
        message.addRecipients(RecipientType.CC, ccAddrs.toArray(new InternetAddress[0]));
        // Add all <bcc>
        for (String bccStr : bcc) {
            bccAddrs.add(new InternetAddress(bccStr.trim()));
        }
        message.addRecipients(RecipientType.BCC, bccAddrs.toArray(new InternetAddress[0]));
        // Set subject
        message.setSubject(subject);
        // when there is attachment
        if (attachments != null && attachments.length > 0 && ConfigurationService.getBoolean(EMAIL_ATTACHMENT_ENABLED)) {
            Multipart multipart = new MimeMultipart();
            // Set body text
            MimeBodyPart bodyTextPart = new MimeBodyPart();
            bodyTextPart.setText(body);
            multipart.addBodyPart(bodyTextPart);
            for (String attachment : attachments) {
                URI attachUri = new URI(attachment);
                if (attachUri.getScheme() != null && attachUri.getScheme().equals("file")) {
                    throw new ActionExecutorException(ErrorType.ERROR, "EM008", "Encountered an error when attaching a file. A local file cannot be attached:" + attachment);
                }
                MimeBodyPart messageBodyPart = new MimeBodyPart();
                DataSource source = new URIDataSource(attachUri, user);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(new File(attachment).getName());
                multipart.addBodyPart(messageBodyPart);
            }
            message.setContent(multipart);
        } else {
            if (attachments != null && attachments.length > 0 && !ConfigurationService.getBoolean(EMAIL_ATTACHMENT_ENABLED)) {
                body = body + EMAIL_ATTACHMENT_ERROR_MSG;
            }
            message.setContent(body, contentType);
        }
    } catch (AddressException e) {
        throw new ActionExecutorException(ErrorType.ERROR, "EM004", "Bad address format in <to> or <cc> or <bcc>.", e);
    } catch (MessagingException e) {
        throw new ActionExecutorException(ErrorType.ERROR, "EM005", "An error occurred while adding recipients.", e);
    } catch (URISyntaxException e) {
        throw new ActionExecutorException(ErrorType.ERROR, "EM008", "Encountered an error when attaching a file", e);
    } catch (HadoopAccessorException e) {
        throw new ActionExecutorException(ErrorType.ERROR, "EM008", "Encountered an error when attaching a file", e);
    }
    try {
        // Send over SMTP Transport
        // (Session+Message has adequate details.)
        Transport.send(message);
    } catch (NoSuchProviderException e) {
        throw new ActionExecutorException(ErrorType.ERROR, "EM006", "Could not find an SMTP transport provider to email.", e);
    } catch (MessagingException e) {
        throw new ActionExecutorException(ErrorType.ERROR, "EM007", "Encountered an error while sending the email message over SMTP.", e);
    }
    LOG.info("Email sent to [{0}]", to);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) ArrayList(java.util.ArrayList) ActionExecutorException(org.apache.oozie.action.ActionExecutorException) DataHandler(javax.activation.DataHandler) URISyntaxException(java.net.URISyntaxException) Properties(java.util.Properties) URI(java.net.URI) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) AddressException(javax.mail.internet.AddressException) MessagingException(javax.mail.MessagingException) HadoopAccessorException(org.apache.oozie.service.HadoopAccessorException) DataSource(javax.activation.DataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) NoSuchProviderException(javax.mail.NoSuchProviderException) File(java.io.File) Session(javax.mail.Session)

Example 52 with DataSource

use of javax.activation.DataSource in project carbon-business-process by wso2.

the class BPELUploadExecutor method execute.

public boolean execute(HttpServletRequest request, HttpServletResponse response) throws CarbonException, IOException {
    String errMsg;
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();
    String webContext = (String) request.getAttribute(CarbonConstants.WEB_CONTEXT);
    String serverURL = (String) request.getAttribute(CarbonConstants.SERVER_URL);
    String cookie = (String) request.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    Map<String, ArrayList<FileItemData>> fileItemsMap = getFileItemsMap();
    if (fileItemsMap == null || fileItemsMap.isEmpty()) {
        String msg = "File uploading failed.";
        log.error(msg);
        out.write("<textarea>" + "(function(){i18n.fileUplodedFailed();})();" + "</textarea>");
        return true;
    }
    BPELUploaderClient uploaderClient = new BPELUploaderClient(configurationContext, serverURL + "BPELUploader", cookie);
    SaveExtractReturn uploadedFiles = null;
    ArrayList<String> extractedFiles = new ArrayList<String>();
    try {
        for (FileItemData fieldData : fileItemsMap.get("bpelFileName")) {
            String fileName = getFileName(fieldData.getFileItem().getName());
            // Check filename for \ charactors. This cannot be handled at the lower stages.
            if (fileName.matches("(.*[\\\\].*[/].*|.*[/].*[\\\\].*)")) {
                log.error("BPEL Package Validation Failure: one or many of the following illegal characters are " + "in " + "the package.\n ~!@#$;%^*()+={}[]| \\<>");
                throw new Exception("BPEL Package Validation Failure: one or many of the following illegal " + "characters " + "are in the package. ~!@#$;%^*()+={}[]| \\<>");
            }
            // Check file extension.
            checkServiceFileExtensionValidity(fileName, ALLOWED_FILE_EXTENSIONS);
            if (fileName.lastIndexOf('\\') != -1) {
                int indexOfColon = fileName.lastIndexOf('\\') + 1;
                fileName = fileName.substring(indexOfColon, fileName.length());
            }
            if (fieldData.getFileItem().getFieldName().equals("bpelFileName")) {
                uploadedFiles = saveAndExtractUploadedFile(fieldData.getFileItem());
                extractedFiles.add(uploadedFiles.extractedFile);
                validateBPELPackage(uploadedFiles.extractedFile);
                DataSource dataSource = new FileDataSource(uploadedFiles.zipFile);
                uploaderClient.addUploadedFileItem(new DataHandler(dataSource), fileName, "zip");
            }
        }
        uploaderClient.uploadFileItems();
        String msg = "Your BPEL package been uploaded successfully. Please refresh this page in a" + " while to see the status of the new process.";
        CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.INFO, request, response, getContextRoot(request) + "/" + webContext + "/bpel/process_list.jsp");
        return true;
    } catch (Exception e) {
        errMsg = "File upload failed :" + e.getMessage();
        log.error(errMsg, e);
        CarbonUIMessage.sendCarbonUIMessage(errMsg, CarbonUIMessage.ERROR, request, response, getContextRoot(request) + "/" + webContext + "/bpel/upload_bpel.jsp");
    } finally {
        for (String s : extractedFiles) {
            File extractedFile = new File(s);
            if (log.isDebugEnabled()) {
                log.debug("Cleaning temporarily extracted BPEL artifacts in " + extractedFile.getParent());
            }
            try {
                FileUtils.cleanDirectory(new File(extractedFile.getParent()));
            } catch (IOException ex) {
                log.warn("Failed to clean temporary extractedFile.", ex);
            }
        }
    }
    return false;
}
Also used : FileItemData(org.wso2.carbon.utils.FileItemData) ArrayList(java.util.ArrayList) DataHandler(javax.activation.DataHandler) IOException(java.io.IOException) IOException(java.io.IOException) CarbonException(org.wso2.carbon.CarbonException) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) FileDataSource(javax.activation.FileDataSource) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 53 with DataSource

use of javax.activation.DataSource in project carbon-business-process by wso2.

the class BPMNUploadExecutor method execute.

@Override
public boolean execute(HttpServletRequest request, HttpServletResponse response) throws CarbonException, IOException {
    String errMsg;
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();
    String webContext = (String) request.getAttribute(CarbonConstants.WEB_CONTEXT);
    String serverURL = (String) request.getAttribute(CarbonConstants.SERVER_URL);
    String cookie = (String) request.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    Map<String, ArrayList<FileItemData>> fileItemsMap = getFileItemsMap();
    if (fileItemsMap == null || fileItemsMap.isEmpty()) {
        String msg = "File uploading failed.";
        log.error(msg);
        out.write("<textarea>" + "(function(){i18n.fileUplodedFailed();})();" + "</textarea>");
        return true;
    }
    BPMNUploaderClient uploaderClient = new BPMNUploaderClient(configurationContext, serverURL + "BPMNUploaderService", cookie);
    File uploadedTempFile;
    try {
        for (FileItemData fileData : fileItemsMap.get("bpmnFileName")) {
            String fileName = getFileName(fileData.getFileItem().getName());
            // Check filename for \ charactors. This cannot be handled at the lower stages.
            if (fileName.matches("(.*[\\\\].*[/].*|.*[/].*[\\\\].*)")) {
                log.error("BPMN Package Validation Failure: one or more of the following illegal characters are in " + "the package.\n ~!@#$;%^*()+={}[]| \\<>");
                throw new Exception("BPMN Package Validation Failure: one or more of the following illegal characters " + "are in the package. ~!@#$;%^*()+={}[]| \\<>");
            }
            // Check file extension.
            checkServiceFileExtensionValidity(fileName, ALLOWED_FILE_EXTENSIONS);
            if (fileName.lastIndexOf('\\') != -1) {
                int indexOfColon = fileName.lastIndexOf('\\') + 1;
                fileName = fileName.substring(indexOfColon, fileName.length());
            }
            if (fileData.getFileItem().getFieldName().equals("bpmnFileName")) {
                uploadedTempFile = new File(CarbonUtils.getTmpDir(), fileName);
                fileData.getFileItem().write(uploadedTempFile);
                DataSource dataSource = new FileDataSource(uploadedTempFile);
                uploaderClient.addUploadedFileItem(new DataHandler(dataSource), fileName, "bar");
            }
        }
        uploaderClient.uploadFileItems();
        String msg = "Your BPMN package has been uploaded successfully. Please refresh this page in a" + " while to see the status of the new process.";
        CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.INFO, request, response, getContextRoot(request) + "/" + webContext + "/bpmn/process_list_view.jsp");
        return true;
    } catch (Exception e) {
        errMsg = "File upload failed :" + e.getMessage();
        log.error(errMsg, e);
        CarbonUIMessage.sendCarbonUIMessage(errMsg, CarbonUIMessage.ERROR, request, response, getContextRoot(request) + "/" + webContext + "/bpmn/process_list_view.jsp");
    }
    return false;
}
Also used : FileItemData(org.wso2.carbon.utils.FileItemData) ArrayList(java.util.ArrayList) FileDataSource(javax.activation.FileDataSource) DataHandler(javax.activation.DataHandler) File(java.io.File) IOException(java.io.IOException) CarbonException(org.wso2.carbon.CarbonException) PrintWriter(java.io.PrintWriter) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource)

Example 54 with DataSource

use of javax.activation.DataSource in project ecs-dashboard by carone1.

the class KibanaEmailer method sendFileEmail.

/*
	 * Utility method that grabs png files and send them
	 * to a list of email addresses
	 */
private static void sendFileEmail(String security) {
    final String username = smtpUsername;
    final String password = smtpPassword;
    // Get system properties
    Properties properties = System.getProperties();
    // Setup mail server
    properties.setProperty("mail.smtp.host", smtpHost);
    if (security.equals(SMTP_SECURITY_TLS)) {
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", smtpHost);
        properties.put("mail.smtp.port", smtpPort);
    } else if (security.equals(SMTP_SECURITY_SSL)) {
        properties.put("mail.smtp.socketFactory.port", smtpPort);
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.port", smtpPort);
    }
    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(sourceAddress));
        // Set To: header field of the header.
        for (String destinationAddress : destinationAddressList) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress));
        }
        // Set Subject: header field
        message.setSubject(mailTitle);
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        StringBuffer bodyBuffer = new StringBuffer(mailBody);
        if (!kibanaUrls.isEmpty()) {
            bodyBuffer.append("\n\n");
        }
        // Add urls info to e-mail
        for (Map<String, String> kibanaUrl : kibanaUrls) {
            // Add urls to e-mail
            String urlName = kibanaUrl.get(NAME_KEY);
            String reportUrl = kibanaUrl.get(URL_KEY);
            if (urlName != null && reportUrl != null) {
                bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n");
            }
        }
        // Fill the message
        messageBodyPart.setText(bodyBuffer.toString());
        // Create a multipart message
        Multipart multipart = new MimeMultipart();
        // Set text message part
        multipart.addBodyPart(messageBodyPart);
        // Part two is attachments
        for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) {
            messageBodyPart = new MimeBodyPart();
            String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY);
            String filename = kibanaScreenCapture.get(FILE_NAME_KEY);
            DataSource source = new FileDataSource(absoluteFilename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);
        }
        // Send the complete message parts
        message.setContent(multipart);
        // Send message
        Transport.send(message);
        logger.info("Sent mail message successfully");
    } catch (MessagingException mex) {
        throw new RuntimeException(mex);
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) MessagingException(javax.mail.MessagingException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 55 with DataSource

use of javax.activation.DataSource in project estatio by estatio.

the class Communication method sendByEmail.

// so can invoke via BackgroundService
@Action(hidden = Where.EVERYWHERE)
public Communication sendByEmail() {
    // body...
    final Document coverNoteDoc = findDocument(DocumentConstants.PAPERCLIP_ROLE_COVER);
    final String emailBody = coverNoteDoc.asChars();
    // (email) attachments..
    // this corresponds to the primary document and any attachments
    final List<DataSource> attachments = Lists.newArrayList();
    final Document primaryDocument = getPrimaryDocument();
    if (primaryDocument != null) {
        // should be the case
        attachments.add(primaryDocument.asDataSource());
    }
    attachments.addAll(findDocumentsInRoleAsStream(DocumentConstants.PAPERCLIP_ROLE_ATTACHMENT).map(DocumentAbstract::asDataSource).collect(Collectors.toList()));
    // cc..
    final List<String> toList = findCorrespondents(CommChannelRoleType.TO);
    final List<String> ccList = findCorrespondents(CommChannelRoleType.CC);
    final List<String> bccList = findCorrespondents(CommChannelRoleType.BCC);
    // subject ...
    final String subject = getSubject();
    // finally, we send
    final boolean send = emailService.send(toList, ccList, bccList, subject, emailBody, attachments.toArray(new DataSource[] {}));
    if (!send) {
        throw new ApplicationException("Failed to send email; see system logs for details.");
    }
    // mark this comm as having been sent.
    sent();
    return this;
}
Also used : DocumentAbstract(org.incode.module.document.dom.impl.docs.DocumentAbstract) ApplicationException(org.apache.isis.applib.ApplicationException) Document(org.incode.module.document.dom.impl.docs.Document) DataSource(javax.activation.DataSource) Action(org.apache.isis.applib.annotation.Action)

Aggregations

DataSource (javax.activation.DataSource)196 DataHandler (javax.activation.DataHandler)114 FileDataSource (javax.activation.FileDataSource)60 MimeBodyPart (javax.mail.internet.MimeBodyPart)53 MimeMultipart (javax.mail.internet.MimeMultipart)48 MimeMessage (javax.mail.internet.MimeMessage)39 InputStream (java.io.InputStream)37 IOException (java.io.IOException)36 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)35 ByteArrayInputStream (java.io.ByteArrayInputStream)33 File (java.io.File)33 ByteArrayOutputStream (java.io.ByteArrayOutputStream)30 Test (org.junit.Test)30 InternetAddress (javax.mail.internet.InternetAddress)27 Properties (java.util.Properties)26 MessagingException (javax.mail.MessagingException)25 Multipart (javax.mail.Multipart)24 Session (javax.mail.Session)21 BodyPart (javax.mail.BodyPart)19 ArrayList (java.util.ArrayList)16