List of usage examples for javax.activation FileDataSource FileDataSource
public FileDataSource(String name)
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Send an email. Also sends it as a gmail if applicable, and does password checking. * @param host host of SMTP server//from w w w .j ava2s . com * @param uName username of email account * @param pWord password of email account * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email * @param toEMailAddr the email addr of who this is going to * @param subject the Textual subject line of the email * @param bodyText the body text of the email (plain text???) * @param fileAttachment and optional file to be attached to the email * @return true if the msg was sent, false if not */ public static boolean sendMsgAsGMail(final String host, final String uName, final String pWord, final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText, final String mimeType, @SuppressWarnings("unused") final String port, @SuppressWarnings("unused") final String security, final File fileAttachment) { String userName = uName; String password = pWord; Boolean fail = false; ArrayList<String> userAndPass = new ArrayList<String>(); Properties props = System.getProperties(); props.put("mail.smtp.host", host); //$NON-NLS-1$ props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ boolean usingSSL = false; if (usingSSL) { props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ } Session session = Session.getInstance(props, null); session.setDebug(instance.isDebugging); if (instance.isDebugging) { log.debug("Host: " + host); //$NON-NLS-1$ log.debug("UserName: " + userName); //$NON-NLS-1$ log.debug("Password: " + password); //$NON-NLS-1$ log.debug("From: " + fromEMailAddr); //$NON-NLS-1$ log.debug("To: " + toEMailAddr); //$NON-NLS-1$ log.debug("Subject: " + subject); //$NON-NLS-1$ } try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromEMailAddr)); if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$ { StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$ InternetAddress[] address = new InternetAddress[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { String toStr = st.nextToken().trim(); address[i++] = new InternetAddress(toStr); } msg.setRecipients(Message.RecipientType.TO, address); } else { InternetAddress[] address = { new InternetAddress(toEMailAddr) }; msg.setRecipients(Message.RecipientType.TO, address); } msg.setSubject(subject); //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\""); // create the second message part if (fileAttachment != null) { // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\""); //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\""); MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileAttachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); } else { // add the Multipart to the message msg.setContent(bodyText, mimeType); } // set the Date: header msg.setSentDate(new Date()); // send the message int cnt = 0; do { cnt++; SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$ try { t.connect(host, userName, password); t.sendMessage(msg, msg.getAllRecipients()); fail = false; } catch (MessagingException mex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } //wrong username or password, get new one if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$ { fail = true; userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow()); if (userAndPass == null) {//the user is done return false; } // else //try again userName = userAndPass.get(0); password = userAndPass.get(1); } } finally { log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$ t.close(); } } while (fail && cnt < 6); } catch (MessagingException mex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); //mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } return false; } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex); ex.printStackTrace(); } if (fail) { return false; } //else return true; }
From source file:org.mule.DefaultMuleMessage.java
@Override public void addOutboundAttachment(String name, Object object, String contentType) throws Exception { assertAccess(WRITE);/* w ww. j av a 2s .c o m*/ DataHandler dh; if (object instanceof File) { if (contentType != null) { dh = new DataHandler(new FileInputStream((File) object), contentType); } else { dh = new DataHandler(new FileDataSource((File) object)); } } else if (object instanceof URL) { if (contentType != null) { dh = new DataHandler(((URL) object).openStream(), contentType); } else { dh = new DataHandler((URL) object); } } else { dh = new DataHandler(object, contentType); } outboundAttachments.put(name, dh); }
From source file:com.clustercontrol.monitor.factory.SelectEvent.java
/** * ??????????//from www . jav a 2 s.c om * <p> * <ol> * <li>?????????{@link com.clustercontrol.util.PropertyUtil}??????</li> * <li>?????????????</li> * <li>{@link com.clustercontrol.monitor.bean.ReportEventInfo}????</li> * <li>??????{@link ArrayList}?????<BR> * </ol> * * @param facilityId ??ID * @param property ? * @return {@link com.clustercontrol.monitor.bean.ReportEventInfo}? * @throws HinemosUnknown * @throws IOException * * @since 2.1.0 * * @see com.clustercontrol.util.PropertyUtil#getPropertyValue(com.clustercontrol.bean.Property, java.lang.String) * @see com.clustercontrol.repository.session.RepositoryControllerBean#getFacilityIdList(String, int) * @see com.clustercontrol.monitor.ejb.entity.EventLogBean#ejbFindEvent(String[], Integer, Timestamp, Timestamp, Timestamp, Timestamp, String, String, Integer, boolean, Integer) * @see com.clustercontrol.monitor.bean.ReportEventInfo */ public DataHandler getEventFile(String facilityId, EventFilterInfo filter, String filename, String username, Locale locale) throws HinemosUnknown, IOException { Integer[] priorityList = null; Long outputFromDate = null; Long outputToDate = null; Long generationFromDate = null; Long generationToDate = null; String monitorId = null; String monitorDetailId = null; int facilityType = 0; String facilityTypeStr = ""; String application = null; String message = null; Integer confirmFlg = null; String confirmStr = ""; String confirmUser = null; String comment = null; String commentUser = null; String ownerRoleId = null; Boolean collectGraphFlg = null; String collectGraphStr = ""; String exportDirectory = HinemosPropertyUtil.getHinemosPropertyStr("performance.export.dir", HinemosPropertyDefault.getString(HinemosPropertyDefault.StringKey.PERFORMANCE_EXPORT_DIR)); String filepath = exportDirectory + "/" + filename; File file = new File(filepath); boolean UTF8_BOM = HinemosPropertyUtil.getHinemosPropertyBool("monitor.common.report.event.bom", true); if (UTF8_BOM) { FileOutputStream fos = new FileOutputStream(file); fos.write(0xef); fos.write(0xbb); fos.write(0xbf); fos.close(); } FileWriter filewriter = new FileWriter(file, true); try { //??? if (filter.getPriorityList() != null && filter.getPriorityList().length > 0) { priorityList = filter.getPriorityList(); } //? if (filter.getOutputDateFrom() != null) { outputFromDate = filter.getOutputDateFrom(); outputFromDate -= (outputFromDate % 1000); //??0?? } //? if (filter.getOutputDateTo() != null) { outputToDate = filter.getOutputDateTo(); outputToDate += (999 - (outputToDate % 1000)); //??999?? } //? if (filter.getGenerationDateFrom() != null) { generationFromDate = filter.getGenerationDateFrom(); generationFromDate -= (generationFromDate % 1000); //??0?? } //? if (filter.getGenerationDateTo() != null) { generationToDate = filter.getGenerationDateTo(); generationToDate += (999 - (generationToDate % 1000)); //??999?? } //ID? if (!"".equals(filter.getMonitorId())) { monitorId = filter.getMonitorId(); } //? if (!"".equals(filter.getMonitorDetailId())) { monitorDetailId = filter.getMonitorDetailId(); } //? if (filter.getFacilityType() != null) { facilityType = filter.getFacilityType(); } facilityTypeStr = Messages.getString(FacilityTargetConstant.typeToMessageCode(facilityType), locale); //? if (!"".equals(filter.getApplication())) { application = filter.getApplication(); } //? if (!"".equals(filter.getMessage())) { message = filter.getMessage(); } // ?? int confirmFlgType = filter.getConfirmFlgType(); if (confirmFlgType != -1) { confirmFlg = confirmFlgType; } confirmStr = Messages.getString(ConfirmConstant.typeToMessageCode(confirmFlgType), locale); // ? if (!"".equals(filter.getConfirmedUser())) { confirmUser = filter.getConfirmedUser(); } // if (!"".equals(filter.getComment())) { comment = filter.getComment(); } // if (!"".equals(filter.getCommentUser())) { commentUser = filter.getCommentUser(); } // collectGraphFlg = filter.getCollectGraphFlg(); if (collectGraphFlg == null) { collectGraphStr = ""; } else { collectGraphStr = Messages.getString(CollectGraphFlgConstant.typeToMessageCode(collectGraphFlg), locale); } // ID if (!"".equals(filter.getOwnerRoleId())) { ownerRoleId = filter.getOwnerRoleId(); } // /* ,,,,,,,,,,,,, ,2012/02/08 17:20:10,,,,,,,,,,,, ,Hinemos Administrator,,,,,,,,,,,, ??,?,,ID,,ID,?,?,,,,,,, ,,,,,,,,,,,,, */ String SEPARATOR = HinemosPropertyUtil.getHinemosPropertyStr("MONITOR_COMMON_REPORT_EVENT_SEPARATOR", ","); String DATE_FORMAT = HinemosPropertyUtil.getHinemosPropertyStr("MONITOR_COMMON_REPORT_EVENT_FORMAT", "yyyy/MM/dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); sdf.setTimeZone(HinemosTime.getTimeZone()); filewriter.write(Messages.getString("REPORT_TITLE_MONITOR_EVENT", locale) + "\n"); filewriter.write(Messages.getString("REPORT_OUTPUT_DATE", locale) + SEPARATOR + sdf.format(HinemosTime.getDateInstance()) + "\n"); filewriter.write(Messages.getString("REPORT_OUTPUT_USER", locale) + SEPARATOR + username + "\n"); // () filewriter.write(Messages.getString("DEF_RESULT", locale) + SEPARATOR + // ?? Messages.getString("RECEIVE_TIME", locale) + SEPARATOR + Messages.getString("REPORT_OUTPUT_DATE", locale) + SEPARATOR + Messages.getString("MONITOR_ID", locale) + SEPARATOR + Messages.getString("MONITOR_DETAIL_ID", locale) + SEPARATOR + Messages.getString("FACILITY_ID", locale) + SEPARATOR + Messages.getString("APPLICATION", locale) + SEPARATOR + Messages.getString("CONFIRMED", locale) + SEPARATOR + Messages.getString("CONFIRM_USER", locale) + SEPARATOR + Messages.getString("MESSAGE", locale) + SEPARATOR + Messages.getString("COMMENT", locale) + SEPARATOR + Messages.getString("COMMENT_USER", locale) + SEPARATOR + Messages.getString("COLLECT_GRAPH_FLG", locale) + SEPARATOR + Messages.getString("OWNER_ROLE_ID", locale) + "\n"); // ??? StringBuilder priorityMsg = new StringBuilder(); if (priorityList != null) { for (int i = 0; i < priorityList.length; i++) { priorityMsg.append( Messages.getString(PriorityConstant.typeToMessageCode(priorityList[i]), locale) + " "); } } // filewriter.write((priorityList == null ? "" : priorityMsg) + SEPARATOR + (outputFromDate == null ? "" : sdf.format(outputFromDate)) + " - " + (outputToDate == null ? "" : sdf.format(outputToDate)) + SEPARATOR + (generationFromDate == null ? "" : sdf.format(generationFromDate)) + " - " + (generationToDate == null ? "" : sdf.format(generationToDate)) + SEPARATOR + (monitorId == null ? "" : monitorId) + SEPARATOR + (monitorDetailId == null ? "" : monitorDetailId) + SEPARATOR + facilityTypeStr + SEPARATOR + (application == null ? "" : application) + SEPARATOR + (confirmFlg == null ? "" : confirmStr) + SEPARATOR + (confirmUser == null ? "" : confirmUser) + SEPARATOR + (message == null ? "" : message) + SEPARATOR + (comment == null ? "" : comment) + SEPARATOR + (commentUser == null ? "" : commentUser) + SEPARATOR + (collectGraphFlg == null ? "" : collectGraphStr) + SEPARATOR + (ownerRoleId == null ? "" : ownerRoleId) + "\n"); // ? filewriter.write(Messages.getString("NUMBER", locale) + SEPARATOR + Messages.getString("DEF_RESULT", locale) + SEPARATOR + Messages.getString("RECEIVE_TIME", locale) + SEPARATOR + Messages.getString("REPORT_OUTPUT_DATE", locale) + SEPARATOR + Messages.getString("FACILITY_ID", locale) + SEPARATOR + Messages.getString("SCOPE", locale) + SEPARATOR + Messages.getString("MONITOR_ID", locale) + SEPARATOR + Messages.getString("MONITOR_DETAIL_ID", locale) + SEPARATOR + Messages.getString("PLUGIN_ID", locale) + SEPARATOR + Messages.getString("APPLICATION", locale) + SEPARATOR + Messages.getString("OWNER_ROLE_ID", locale) + SEPARATOR + Messages.getString("CONFIRMED", locale) + SEPARATOR + Messages.getString("CONFIRM_TIME", locale) + SEPARATOR + Messages.getString("CONFIRM_USER", locale) + SEPARATOR + Messages.getString("COMMENT", locale) + SEPARATOR + Messages.getString("COMMENT_DATE", locale) + SEPARATOR + Messages.getString("COMMENT_USER", locale) + SEPARATOR + Messages.getString("MESSAGE", locale) + SEPARATOR + Messages.getString("MESSAGE_ORG", locale) + SEPARATOR + Messages.getString("COLLECT_GRAPH_FLG", locale) + "\n"); // ?ID? String[] facilityIds = null; int level = RepositoryControllerBean.ALL; if (FacilityTargetConstant.TYPE_BENEATH == facilityType) { level = RepositoryControllerBean.ONE_LEVEL; } ArrayList<String> facilityIdList = new RepositoryControllerBean().getFacilityIdList(facilityId, level); if (facilityIdList != null && facilityIdList.size() > 0) { // ?? facilityIds = new String[facilityIdList.size()]; facilityIdList.toArray(facilityIds); } else { // ?? facilityIds = new String[1]; facilityIds[0] = facilityId; } // ?CSV?????DB?? List<EventLogEntity> ct = null; // ? ct = QueryUtil.getEventLogByFilter(facilityIds, priorityList, outputFromDate, outputToDate, generationFromDate, generationToDate, monitorId, monitorDetailId, application, message, confirmFlg, confirmUser, comment, commentUser, collectGraphFlg, ownerRoleId, true, HinemosPropertyUtil .getHinemosPropertyNum("monitor.common.report.event.count", Long.valueOf(2000)) .intValue()); // ?? collectionToFile(ct, filewriter, locale); } finally { filewriter.close(); } // ???? FileDataSource source = new FileDataSource(file); DataHandler handler = new DataHandler(source); return handler; }
From source file:com.collabnet.ccf.pi.cee.pt.v50.ProjectTrackerWriter.java
private GenericArtifact[] createProjectTrackerAttachment(GenericArtifact ga) { String targetArtifactId = ga.getDepParentTargetArtifactId(); String artifactId = ptHelper.getArtifactIdFromFullyQualifiedArtifactId(targetArtifactId); TrackerWebServicesClient twsclient = null; GenericArtifact parentArtifact = null; byte[] data = null; String attachmentMimeType = null; String attachmentName = null; DataSource dataSource = null; File attachmentFile = null;/* ww w . j a v a2s. c om*/ String repositoryId = ga.getTargetRepositoryId(); try { twsclient = this.getConnection(ga); ClientArtifactListXMLHelper currentArtifactHelper = twsclient.getArtifactById(artifactId); ClientArtifact currentArtifact = currentArtifactHelper.getAllArtifacts().get(0); String retrievedArtifactId = currentArtifact.getArtifactID(); if (!artifactId.equals(retrievedArtifactId)) { log.warn("Artifact seems to have moved, old id: " + artifactId + ", new id: " + retrievedArtifactId + ", so do not ship it ..."); return new GenericArtifact[] { ga }; } String retrievedProject = currentArtifact.getProject(); if (retrievedProject != null) { String projectName = null; if (repositoryId != null) { String[] splitProjectName = repositoryId.split(":"); if (splitProjectName != null) { if (splitProjectName.length >= 1) { projectName = splitProjectName[0]; } else { throw new IllegalArgumentException("Repository id " + repositoryId + " is not valid." + " Could not extract project name from repository id"); } } } if (projectName != null) { if (!retrievedProject.equals(projectName)) { log.warn("PT Artifact with id " + artifactId + " has moved from project " + projectName + " to artifact with id " + retrievedArtifactId + " in project " + retrievedProject + ", so do not ship it ..."); return new GenericArtifact[] { ga }; } } } String attachmentType = GenericArtifactHelper.getStringGAField(AttachmentMetaData.ATTACHMENT_TYPE, ga); String sourceAttachmentId = ga.getSourceArtifactId(); String parentSourceArtifactId = ga.getDepParentSourceArtifactId(); if (attachmentType.equals(AttachmentMetaData.AttachmentType.LINK.toString())) { String url = GenericArtifactHelper.getStringGAField(AttachmentMetaData.ATTACHMENT_SOURCE_URL, ga); url = "<html><body><a href=\"" + url + "\">" + url + "</a></body></html>"; data = url.getBytes(); attachmentMimeType = AttachmentMetaData.TEXT_HTML; attachmentName = "Link-attachment-" + parentSourceArtifactId + "-" + sourceAttachmentId + ".html"; ByteArrayDataSource baDS = new ByteArrayDataSource(data, attachmentMimeType); baDS.setName(attachmentName); dataSource = baDS; } else { String attachmentDataFileName = GenericArtifactHelper .getStringGAField(AttachmentMetaData.ATTACHMENT_DATA_FILE, ga); attachmentMimeType = GenericArtifactHelper.getStringGAField(AttachmentMetaData.ATTACHMENT_MIME_TYPE, ga); attachmentName = GenericArtifactHelper.getStringGAField(AttachmentMetaData.ATTACHMENT_NAME, ga); if (StringUtils.isEmpty(attachmentDataFileName)) { data = ga.getRawAttachmentData(); ByteArrayDataSource baDS = new ByteArrayDataSource(data, attachmentMimeType); baDS.setName(attachmentName); dataSource = baDS; } else { File attachmentDataFile = new File(attachmentDataFileName); String tempDir = System.getProperty("java.io.tmpdir"); attachmentFile = new File(tempDir, attachmentName); if (attachmentDataFile.exists()) { boolean renamingSuccessful = attachmentDataFile.renameTo(attachmentFile); if (renamingSuccessful) { dataSource = new FileDataSource(attachmentFile); } else { dataSource = new FileDataSource(attachmentDataFile); } } else { String message = "Attachment data file " + attachmentDataFileName + " does not exist."; FileNotFoundException e = new FileNotFoundException(message); log.error(message, e); throw new CCFRuntimeException(message, e); } } } String attachmentDescription = null; attachmentDescription = GenericArtifactHelper .getStringGAField(AttachmentMetaData.ATTACHMENT_DESCRIPTION, ga); if (StringUtils.isEmpty(attachmentDescription)) { attachmentDescription = "Attachment added by Connector"; } long attachmentId = -1; attachmentId = twsclient.postAttachment(artifactId, attachmentDescription, dataSource); currentArtifactHelper = twsclient.getArtifactById(artifactId); currentArtifact = currentArtifactHelper.getAllArtifacts().get(0); String modifiedOn = currentArtifact.getAttributeValue(ProjectTrackerReader.TRACKER_NAMESPACE, ProjectTrackerReader.MODIFIED_ON_FIELD); long modifiedOnMilliSeconds = Long.parseLong(modifiedOn); Date lastModifiedDate = new Date(modifiedOnMilliSeconds); ga.setTargetArtifactId(Long.toString(attachmentId)); ga.setTargetArtifactLastModifiedDate(DateUtil.format(lastModifiedDate)); ga.setTargetArtifactVersion(Long.toString(modifiedOnMilliSeconds)); ga.setDepParentTargetRepositoryId(ga.getTargetRepositoryId()); ga.setDepParentTargetRepositoryKind(ga.getTargetRepositoryKind()); log.info("Attachment with id " + attachmentId + " is created for the PT artifact " + artifactId + " with the attachment " + sourceAttachmentId + " from artifact " + parentSourceArtifactId); parentArtifact = new GenericArtifact(); // make sure that we do not update the synchronization status record // for replayed attachments parentArtifact.setTransactionId(ga.getTransactionId()); parentArtifact.setArtifactType(GenericArtifact.ArtifactTypeValue.PLAINARTIFACT); parentArtifact.setArtifactAction(GenericArtifact.ArtifactActionValue.UPDATE); parentArtifact.setArtifactMode(GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY); parentArtifact.setConflictResolutionPriority(ga.getConflictResolutionPriority()); parentArtifact.setSourceArtifactId(ga.getDepParentSourceArtifactId()); parentArtifact.setSourceArtifactLastModifiedDate(ga.getSourceArtifactLastModifiedDate()); parentArtifact.setSourceArtifactVersion(ga.getSourceArtifactVersion()); parentArtifact.setSourceRepositoryId(ga.getSourceRepositoryId()); parentArtifact.setSourceSystemId(ga.getSourceSystemId()); parentArtifact.setSourceSystemKind(ga.getSourceSystemKind()); parentArtifact.setSourceRepositoryKind(ga.getSourceRepositoryKind()); parentArtifact.setSourceSystemTimezone(ga.getSourceSystemTimezone()); parentArtifact.setTargetArtifactId(targetArtifactId); parentArtifact.setTargetArtifactLastModifiedDate(DateUtil.format(lastModifiedDate)); parentArtifact.setTargetArtifactVersion(Long.toString(modifiedOnMilliSeconds)); parentArtifact.setTargetRepositoryId(ga.getTargetRepositoryId()); parentArtifact.setTargetRepositoryKind(ga.getTargetRepositoryKind()); parentArtifact.setTargetSystemId(ga.getTargetSystemId()); parentArtifact.setTargetSystemKind(ga.getTargetSystemKind()); parentArtifact.setTargetSystemTimezone(ga.getTargetSystemTimezone()); } catch (WSException e) { String message = "Exception while creating PT artifact attachment"; log.error(message, e); throw new CCFRuntimeException(message, e); } catch (RemoteException e) { String message = "Exception while creating PT artifact attachment"; log.error(message, e); throw new CCFRuntimeException(message, e); } catch (ServiceException e) { String message = "Exception while creating PT artifact attachment"; log.error(message, e); throw new CCFRuntimeException(message, e); } catch (Exception e) { String message = "Exception while creating PT artifact attachment"; log.error(message, e); throw new CCFRuntimeException(message, e); } finally { if (attachmentFile != null) { boolean fileDeleted = attachmentFile.delete(); if (!fileDeleted) { log.warn("The temporary attachment file" + attachmentFile.getAbsolutePath() + " could not be deleted"); } } if (twsclient != null) { this.releaseConnection(twsclient); } } return new GenericArtifact[] { ga, parentArtifact }; }
From source file:org.sakaiproject.signup.logic.SignupEmailFacadeImpl.java
/** * Helper to create an ICS calendar from a list of vevents, then turn it into an attachment * @param vevents list of vevents/*from ww w .j av a 2 s . c o m*/ * @param method the ITIP method for the calendar, e.g. "REQUEST" * @return */ private Attachment formatICSAttachment(List<VEvent> vevents, String method) { String path = calendarHelper.createCalendarFile(vevents, method); // Explicitly define the Content-Type and Content-Diposition headers so the invitation appears inline String filename = StringUtils.substringAfterLast(path, File.separator); String type = String.format("text/calendar; charset=\"utf-8\"; method=%s; name=signup-invite.ics", method); File file = new File(path); DataSource dataSource = new Attachment.RenamedDataSource(new FileDataSource(file), filename); return new Attachment(dataSource, type, Attachment.ContentDisposition.INLINE); }
From source file:org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient.java
public void restore(String path, Reader reader) throws RegistryException { try {//from w ww. j a v a 2 s .c om BufferedReader bufferedReader = new BufferedReader(reader); File tempFile = new File("tempFile"); tempFile.deleteOnExit(); FileOutputStream fileOutputStream = new FileOutputStream(tempFile); Writer writer = new OutputStreamWriter(fileOutputStream); String inputLine; while ((inputLine = bufferedReader.readLine()) != null) { writer.append(inputLine); } writer.flush(); fileOutputStream.close(); writer.close(); bufferedReader.close(); DataHandler handler = new DataHandler(new FileDataSource(tempFile)); stub.wsRestore(path, handler); @SuppressWarnings("unused") boolean ignored = tempFile.delete(); } catch (Exception e) { String msg = "Failed to perform restore operation."; log.error(msg, e); throw new RegistryException(msg, e); } }
From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; message = "Some of the appliances in your house are running inefficient." + "\n" + "Kindly check or replace your appliance " + "\n" + "Check the attachment for details or visit your account"; Properties props = System.getProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", 587); props.put("mail.smtp.user", from); Session session = Session.getDefaultInstance(props); MimeMessage mimeMessage = new MimeMessage(session); try {/* w w w . j a va 2 s . c o m*/ mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Energy Board"); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(message); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(path); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(name_attach.getText() + ".png"); multipart.addBodyPart(messageBodyPart); mimeMessage.setContent(multipart); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); System.out.println("sent"); transport.close(); } catch (MessagingException me) { } }
From source file:org.wso2.carbon.registry.ws.api.WSRegistry.java
public DataHandler wsDump(String path) throws RegistryException { DataHandler dataHandler = null; try {/*from www .j av a2 s . c o m*/ FileOutputStream fileOutputStream = new FileOutputStream(tempFile); Writer writer = new OutputStreamWriter(fileOutputStream); dump(path, writer); writer.flush(); fileOutputStream.close(); return new DataHandler(new FileDataSource(tempFile)); } catch (IOException e) { String msg = "get Content failed - Unable to generate temp file"; log.error(msg, e); throw new RegistryException(msg, e); } }
From source file:com.panet.imeta.job.entries.mail.JobEntryMail.java
public Result execute(Result result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); File masterZipfile = null;//from w ww . ja v a 2s . c o m // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { log.logError(toString(), Messages.getString("JobMail.Error.HostNotSpecified")); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { if (secureConnectionType.equals("TLS")) { // Allow TLS authentication props.put("mail.smtp.starttls.enable", "true"); } else { protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version // Unknown props.put("mail.smtps.quitwait", "false"); } } props.put("mail." + protocol + ".host", environmentSubstitute(server)); if (!Const.isEmpty(port)) props.put("mail." + protocol + ".port", environmentSubstitute(port)); boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG; if (debug) props.put("mail.debug", "true"); if (usingAuthentication) { props.put("mail." + protocol + ".auth", "true"); /* * authenticator = new Authenticator() { protected * PasswordAuthentication getPasswordAuthentication() { return new * PasswordAuthentication( * StringUtil.environmentSubstitute(Const.NVL(authenticationUser, * "")), * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword * , "")) ); } }; */ } Session session = Session.getInstance(props); session.setDebug(debug); try { // create a message Message msg = new MimeMessage(session); // set message priority if (usePriority) { String priority_int = "1"; if (priority.equals("low")) { priority_int = "3"; } if (priority.equals("normal")) { priority_int = "2"; } msg.setHeader("X-Priority", priority_int); // (String)int // between 1= high // and 3 = low. msg.setHeader("Importance", importance); // seems to be needed for MS Outlook. // where it returns a string of high /normal /low. } // Set Mail sender (From) String sender_address = environmentSubstitute(replyAddress); if (!Const.isEmpty(sender_address)) { String sender_name = environmentSubstitute(replyName); if (!Const.isEmpty(sender_name)) sender_address = sender_name + '<' + sender_address + '>'; msg.setFrom(new InternetAddress(sender_address)); } else { throw new MessagingException(Messages.getString("JobMail.Error.ReplyEmailNotFilled")); } // set Reply to addresses String reply_to_address = environmentSubstitute(replyToAddresses); if (!Const.isEmpty(reply_to_address)) { // Split the mail-address: space separated String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) address[i] = new InternetAddress(reply_Address_List[i]); msg.setReplyTo(address); } // Split the mail-address: space separated String destinations[] = environmentSubstitute(destination).split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) address[i] = new InternetAddress(destinations[i]); msg.setRecipients(Message.RecipientType.TO, address); if (!Const.isEmpty(destinationCc)) { // Split the mail-address Cc: space separated String destinationsCc[] = environmentSubstitute(destinationCc).split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) addressCc[i] = new InternetAddress(destinationsCc[i]); msg.setRecipients(Message.RecipientType.CC, addressCc); } if (!Const.isEmpty(destinationBCc)) { // Split the mail-address BCc: space separated String destinationsBCc[] = environmentSubstitute(destinationBCc).split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) addressBCc[i] = new InternetAddress(destinationsBCc[i]); msg.setRecipients(Message.RecipientType.BCC, addressBCc); } String realSubject = environmentSubstitute(subject); if (!Const.isEmpty(realSubject)) { msg.setSubject(realSubject); } msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) { messageText.append(environmentSubstitute(comment)).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append(Messages.getString("JobMail.Log.Comment.Job")).append(Const.CR); messageText.append("-----").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobName") + " : ") .append(parentJob.getJobMeta().getName()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobDirectory") + " : ") .append(parentJob.getJobMeta().getDirectory()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobEntry") + " : ").append(getName()) .append(Const.CR); messageText.append(Const.CR); } if (includeDate) { messageText.append(Const.CR).append(Messages.getString("JobMail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR); } if (!onlySendComment && result != null) { messageText.append(Messages.getString("JobMail.Log.Comment.PreviousResult") + ":").append(Const.CR); messageText.append("-----------------").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobEntryNr") + " : ") .append(result.getEntryNr()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Errors") + " : ") .append(result.getNrErrors()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesRead") + " : ") .append(result.getNrLinesRead()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesWritten") + " : ") .append(result.getNrLinesWritten()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesInput") + " : ") .append(result.getNrLinesInput()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesOutput") + " : ") .append(result.getNrLinesOutput()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesUpdated") + " : ") .append(result.getNrLinesUpdated()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Status") + " : ") .append(result.getExitStatus()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Result") + " : ") .append(result.getResult()).append(Const.CR); messageText.append(Const.CR); } if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson)) || !Const.isEmpty(environmentSubstitute(contactPhone)))) { messageText.append(Messages.getString("JobMail.Log.Comment.ContactInfo") + " :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.PersonToContact") + " : ") .append(environmentSubstitute(contactPerson)).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Tel") + " : ") .append(environmentSubstitute(contactPhone)).append(Const.CR); messageText.append(Const.CR); } // Include the path to this job entry... if (!onlySendComment) { JobTracker jobTracker = parentJob.getJobTracker(); if (jobTracker != null) { messageText.append(Messages.getString("JobMail.Log.Comment.PathToJobentry") + ":") .append(Const.CR); messageText.append("------------------------").append(Const.CR); addBacktracking(jobTracker, messageText); } } Multipart parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // 1st part if (useHTML) { if (!Const.isEmpty(getEncoding())) { part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding()); } else { part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } } else part1.setText(messageText.toString()); parts.addBodyPart(part1); if (includingFiles && result != null) { List<ResultFile> resultFiles = result.getResultFilesList(); if (resultFiles != null && !resultFiles.isEmpty()) { if (!zipFiles) { // Add all files to the message... // for (ResultFile resultFile : resultFiles) { FileObject file = resultFile.getFile(); if (file != null && file.exists()) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { // create a data source MimeBodyPart files = new MimeBodyPart(); URLDataSource fds = new URLDataSource(file.getURL()); // get a data Handler to manipulate this // file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(file.getName().getBaseName()); // add the part with the file in the // BodyPart(); parts.addBodyPart(files); log.logBasic(toString(), "Added file '" + fds.getName() + "' to the mail message."); } } } } else { // create a single ZIP archive of all files masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (ResultFile resultFile : resultFiles) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { FileObject file = resultFile.getFile(); ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into // this archive... BufferedInputStream inputStream = new BufferedInputStream( KettleVFS.getInputStream(file)); int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } inputStream.close(); zipOutputStream.closeEntry(); log.logBasic(toString(), "Added file '" + file.getName().getURI() + "' to the mail message in a zip archive."); } } } catch (Exception e) { log.logError(toString(), "Error zipping attachement files into file [" + masterZipfile.getPath() + "] : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { log.logError(toString(), "Unable to close attachement zip file archive : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } } } // Now attach the master zip file to the message. if (result.getNrErrors() == 0) { // create a data source MimeBodyPart files = new MimeBodyPart(); FileDataSource fds = new FileDataSource(masterZipfile); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in th e data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); } } } } msg.setContent(parts); Transport transport = null; try { transport = session.getTransport(protocol); if (usingAuthentication) { if (!Const.isEmpty(port)) { transport.connect(environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))), environmentSubstitute(Const.NVL(authenticationUser, "")), environmentSubstitute(Const.NVL(authenticationPassword, ""))); } else { transport.connect(environmentSubstitute(Const.NVL(server, "")), environmentSubstitute(Const.NVL(authenticationUser, "")), environmentSubstitute(Const.NVL(authenticationPassword, ""))); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) transport.close(); } } catch (IOException e) { log.logError(toString(), "Problem while sending message: " + e.toString()); result.setNrErrors(1); } catch (MessagingException mex) { log.logError(toString(), "Problem while sending message: " + mex.toString()); result.setNrErrors(1); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { log.logError(toString(), " ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) { log.logError(toString(), " " + invalid[i]); result.setNrErrors(1); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { log.logError(toString(), " ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) { log.logError(toString(), " " + validUnsent[i]); result.setNrErrors(1); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { // System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) { log.logError(toString(), " " + validSent[i]); result.setNrErrors(1); } } } if (ex instanceof MessagingException) { ex = ((MessagingException) ex).getNextException(); } else { ex = null; } } while (ex != null); } finally { if (masterZipfile != null && masterZipfile.exists()) { masterZipfile.delete(); } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } return result; }
From source file:org.pentaho.di.job.entries.mail.JobEntryMail.java
public Result execute(Result result, int nr) { File masterZipfile = null;//from ww w .j a va 2 s. c o m // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { logError(BaseMessages.getString(PKG, "JobMail.Error.HostNotSpecified")); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { if (secureConnectionType.equals("TLS")) { // Allow TLS authentication props.put("mail.smtp.starttls.enable", "true"); } else { protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version Unknown props.put("mail.smtps.quitwait", "false"); } } props.put("mail." + protocol + ".host", environmentSubstitute(server)); if (!Const.isEmpty(port)) { props.put("mail." + protocol + ".port", environmentSubstitute(port)); } if (log.isDebug()) { props.put("mail.debug", "true"); } if (usingAuthentication) { props.put("mail." + protocol + ".auth", "true"); /* * authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new * PasswordAuthentication( StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")) ); } }; */ } Session session = Session.getInstance(props); session.setDebug(log.isDebug()); try { // create a message Message msg = new MimeMessage(session); // set message priority if (usePriority) { String priority_int = "1"; if (priority.equals("low")) { priority_int = "3"; } if (priority.equals("normal")) { priority_int = "2"; } msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low. msg.setHeader("Importance", importance); // seems to be needed for MS Outlook. // where it returns a string of high /normal /low. msg.setHeader("Sensitivity", sensitivity); // Possible values are normal, personal, private, company-confidential } // Set Mail sender (From) String sender_address = environmentSubstitute(replyAddress); if (!Const.isEmpty(sender_address)) { String sender_name = environmentSubstitute(replyName); if (!Const.isEmpty(sender_name)) { sender_address = sender_name + '<' + sender_address + '>'; } msg.setFrom(new InternetAddress(sender_address)); } else { throw new MessagingException(BaseMessages.getString(PKG, "JobMail.Error.ReplyEmailNotFilled")); } // set Reply to addresses String reply_to_address = environmentSubstitute(replyToAddresses); if (!Const.isEmpty(reply_to_address)) { // Split the mail-address: space separated String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) { address[i] = new InternetAddress(reply_Address_List[i]); } msg.setReplyTo(address); } // Split the mail-address: space separated String[] destinations = environmentSubstitute(destination).split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) { address[i] = new InternetAddress(destinations[i]); } msg.setRecipients(Message.RecipientType.TO, address); String realCC = environmentSubstitute(getDestinationCc()); if (!Const.isEmpty(realCC)) { // Split the mail-address Cc: space separated String[] destinationsCc = realCC.split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) { addressCc[i] = new InternetAddress(destinationsCc[i]); } msg.setRecipients(Message.RecipientType.CC, addressCc); } String realBCc = environmentSubstitute(getDestinationBCc()); if (!Const.isEmpty(realBCc)) { // Split the mail-address BCc: space separated String[] destinationsBCc = realBCc.split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) { addressBCc[i] = new InternetAddress(destinationsBCc[i]); } msg.setRecipients(Message.RecipientType.BCC, addressBCc); } String realSubject = environmentSubstitute(subject); if (!Const.isEmpty(realSubject)) { msg.setSubject(realSubject); } msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); String endRow = isUseHTML() ? "<br>" : Const.CR; String realComment = environmentSubstitute(comment); if (!Const.isEmpty(realComment)) { messageText.append(realComment).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Job")).append(endRow); messageText.append("-----").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobName") + " : ") .append(parentJob.getJobMeta().getName()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobDirectory") + " : ") .append(parentJob.getJobMeta().getRepositoryDirectory()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntry") + " : ") .append(getName()).append(endRow); messageText.append(Const.CR); } if (includeDate) { messageText.append(endRow).append(BaseMessages.getString(PKG, "JobMail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(endRow).append(endRow); } if (!onlySendComment && result != null) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PreviousResult") + ":") .append(endRow); messageText.append("-----------------").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntryNr") + " : ") .append(result.getEntryNr()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Errors") + " : ") .append(result.getNrErrors()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRead") + " : ") .append(result.getNrLinesRead()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesWritten") + " : ") .append(result.getNrLinesWritten()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesInput") + " : ") .append(result.getNrLinesInput()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesOutput") + " : ") .append(result.getNrLinesOutput()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesUpdated") + " : ") .append(result.getNrLinesUpdated()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRejected") + " : ") .append(result.getNrLinesRejected()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Status") + " : ") .append(result.getExitStatus()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Result") + " : ") .append(result.getResult()).append(endRow); messageText.append(endRow); } if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson)) || !Const.isEmpty(environmentSubstitute(contactPhone)))) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.ContactInfo") + " :") .append(endRow); messageText.append("---------------------").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PersonToContact") + " : ") .append(environmentSubstitute(contactPerson)).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Tel") + " : ") .append(environmentSubstitute(contactPhone)).append(endRow); messageText.append(endRow); } // Include the path to this job entry... if (!onlySendComment) { JobTracker jobTracker = parentJob.getJobTracker(); if (jobTracker != null) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PathToJobentry") + ":") .append(endRow); messageText.append("------------------------").append(endRow); addBacktracking(jobTracker, messageText); if (isUseHTML()) { messageText.replace(0, messageText.length(), messageText.toString().replace(Const.CR, endRow)); } } } MimeMultipart parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // Attached files counter int nrattachedFiles = 0; // 1st part if (useHTML) { if (!Const.isEmpty(getEncoding())) { part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding()); } else { part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } } else { part1.setText(messageText.toString()); } parts.addBodyPart(part1); if (includingFiles && result != null) { List<ResultFile> resultFiles = result.getResultFilesList(); if (resultFiles != null && !resultFiles.isEmpty()) { if (!zipFiles) { // Add all files to the message... // for (ResultFile resultFile : resultFiles) { FileObject file = resultFile.getFile(); if (file != null && file.exists()) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) { found = true; } } if (found) { // create a data source MimeBodyPart files = new MimeBodyPart(); URLDataSource fds = new URLDataSource(file.getURL()); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(file.getName().getBaseName()); // insist on base64 to preserve line endings files.addHeader("Content-Transfer-Encoding", "base64"); // add the part with the file in the BodyPart(); parts.addBodyPart(files); nrattachedFiles++; logBasic("Added file '" + fds.getName() + "' to the mail message."); } } } } else { // create a single ZIP archive of all files masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (ResultFile resultFile : resultFiles) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) { found = true; } } if (found) { FileObject file = resultFile.getFile(); ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into this archive... BufferedInputStream inputStream = new BufferedInputStream( KettleVFS.getInputStream(file)); try { int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } } finally { inputStream.close(); } zipOutputStream.closeEntry(); nrattachedFiles++; logBasic("Added file '" + file.getName().getURI() + "' to the mail message in a zip archive."); } } } catch (Exception e) { logError("Error zipping attachement files into file [" + masterZipfile.getPath() + "] : " + e.toString()); logError(Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { logError("Unable to close attachement zip file archive : " + e.toString()); logError(Const.getStackTracker(e)); result.setNrErrors(1); } } } // Now attach the master zip file to the message. if (result.getNrErrors() == 0) { // create a data source MimeBodyPart files = new MimeBodyPart(); FileDataSource fds = new FileDataSource(masterZipfile); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); } } } } int nrEmbeddedImages = 0; if (embeddedimages != null && embeddedimages.length > 0) { FileObject imageFile = null; for (int i = 0; i < embeddedimages.length; i++) { String realImageFile = environmentSubstitute(embeddedimages[i]); String realcontenID = environmentSubstitute(contentids[i]); if (messageText.indexOf("cid:" + realcontenID) < 0) { if (log.isDebug()) { log.logDebug("Image [" + realImageFile + "] is not used in message body!"); } } else { try { boolean found = false; imageFile = KettleVFS.getFileObject(realImageFile, this); if (imageFile.exists() && imageFile.getType() == FileType.FILE) { found = true; } else { log.logError("We can not find [" + realImageFile + "] or it is not a file"); } if (found) { // Create part for the image MimeBodyPart messageBodyPart = new MimeBodyPart(); // Load the image URLDataSource fds = new URLDataSource(imageFile.getURL()); messageBodyPart.setDataHandler(new DataHandler(fds)); // Setting the header messageBodyPart.setHeader("Content-ID", "<" + realcontenID + ">"); // Add part to multi-part parts.addBodyPart(messageBodyPart); nrEmbeddedImages++; log.logBasic("Image '" + fds.getName() + "' was embedded in message."); } } catch (Exception e) { log.logError( "Error embedding image [" + realImageFile + "] in message : " + e.toString()); log.logError(Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (imageFile != null) { try { imageFile.close(); } catch (Exception e) { /* Ignore */ } } } } } } if (nrEmbeddedImages > 0 && nrattachedFiles == 0) { // If we need to embedd images... // We need to create a "multipart/related" message. // otherwise image will appear as attached file parts.setSubType("related"); } // put all parts together msg.setContent(parts); Transport transport = null; try { transport = session.getTransport(protocol); String authPass = getPassword(authenticationPassword); if (usingAuthentication) { if (!Const.isEmpty(port)) { transport.connect(environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))), environmentSubstitute(Const.NVL(authenticationUser, "")), authPass); } else { transport.connect(environmentSubstitute(Const.NVL(server, "")), environmentSubstitute(Const.NVL(authenticationUser, "")), authPass); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) { transport.close(); } } } catch (IOException e) { logError("Problem while sending message: " + e.toString()); result.setNrErrors(1); } catch (MessagingException mex) { logError("Problem while sending message: " + mex.toString()); result.setNrErrors(1); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { logError(" ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) { logError(" " + invalid[i]); result.setNrErrors(1); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { logError(" ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) { logError(" " + validUnsent[i]); result.setNrErrors(1); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { // System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) { logError(" " + validSent[i]); result.setNrErrors(1); } } } if (ex instanceof MessagingException) { ex = ((MessagingException) ex).getNextException(); } else { ex = null; } } while (ex != null); } finally { if (masterZipfile != null && masterZipfile.exists()) { masterZipfile.delete(); } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } return result; }