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);
}
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;
}
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;
}
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);
}
}
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;
}
Aggregations