List of usage examples for javax.activation FileDataSource FileDataSource
public FileDataSource(String name)
From source file:com.clustercontrol.ws.agent.AgentEndpoint.java
/** * [Update] ?/*from www. j av a 2s . co m*/ * * HinemosAgentAccess??? * * @throws HinemosUnknown * @throws InvalidRole * @throws InvalidUserPass */ @XmlMimeType("application/octet-stream") public DataHandler downloadModule(String filename) throws InvalidUserPass, InvalidRole, HinemosUnknown { ArrayList<SystemPrivilegeInfo> systemPrivilegeList = new ArrayList<SystemPrivilegeInfo>(); systemPrivilegeList .add(new SystemPrivilegeInfo(FunctionConstant.HINEMOS_AGENT, SystemPrivilegeMode.MODIFY)); HttpAuthenticator.authCheck(wsctx, systemPrivilegeList); String homeDir = System.getProperty("hinemos.manager.home.dir"); String filepath = homeDir + "/lib/agent/" + filename; File file = new File(filepath); if (!file.exists()) { m_log.info("file not found : " + filepath); return null; } FileDataSource source = new FileDataSource(file); DataHandler dataHandler = new DataHandler(source); return dataHandler; }
From source file:org.wso2.carbon.application.mgt.ApplicationAdmin.java
/** * Used to download a carbon application archive. * @param fileName the name of the application archive (.car) to be downloaded * @return datahandler corresponding to the .car file to be downloaded * @throws Exception for invalid scenarios *//*from www. jav a 2 s. com*/ public DataHandler downloadCappArchive(String fileName) throws Exception { CarbonApplication currentApp = null; // Iterate all applications for this tenant and find the application to delete String tenantId = AppDeployerUtils.getTenantIdString(getAxisConfig()); ArrayList<CarbonApplication> appList = AppManagementServiceComponent.getAppManager() .getCarbonApps(tenantId); for (CarbonApplication carbonApp : appList) { if (fileName.equals(carbonApp.getAppNameWithVersion())) { currentApp = carbonApp; } } FileDataSource datasource = new FileDataSource(new File(currentApp.getAppFilePath())); DataHandler handler = new DataHandler(datasource); return handler; }
From source file:com.emc.kibana.emailer.KibanaEmailer.java
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); }//from w w w.ja v a2 s. c o m 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); } }
From source file:com.liferay.mail.imap.IMAPAccessor.java
protected Message createMessage(String personalName, String sender, Address[] to, Address[] cc, Address[] bcc, String subject, String body, List<MailFile> mailFiles) throws MessagingException, UnsupportedEncodingException { Message jxMessage = new MimeMessage(_imapConnection.getSession()); jxMessage.setFrom(new InternetAddress(sender, personalName)); jxMessage.addRecipients(Message.RecipientType.TO, to); jxMessage.addRecipients(Message.RecipientType.CC, cc); jxMessage.addRecipients(Message.RecipientType.BCC, bcc); jxMessage.setSentDate(new Date()); jxMessage.setSubject(subject);//from w ww . j a v a 2s . c o m MimeMultipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(body, ContentTypes.TEXT_HTML_UTF8); multipart.addBodyPart(messageBodyPart); if (mailFiles != null) { for (MailFile mailFile : mailFiles) { File file = mailFile.getFile(); if (!file.exists()) { continue; } DataSource dataSource = new FileDataSource(file); BodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(mailFile.getFileName()); multipart.addBodyPart(attachmentBodyPart); } } jxMessage.setContent(multipart); return jxMessage; }
From source file:it.cnr.icar.eric.server.profile.ws.wsdl.cataloger.WSDLCatalogerEngine.java
private void processZipFile(ExtrinsicObjectType zipEO, InputSource inputSource) throws JAXRException, JAXBException, IOException, CatalogingException { // This method unzips the zip file and places all files in the idToFileMap // This method also places all files from a zip file in a Map. This is done so // that a file can be looked up at any time during the processing of any other file Collection<File> files = addZipEntriesToMap(zipEO, inputSource); //Now iterate and create ExtrinsicObject - Repository Item pair for each unzipped file Iterator<File> iter = files.iterator(); while (iter.hasNext()) { File file = iter.next();/*from w w w . j a v a2s . c om*/ @SuppressWarnings("unused") String fileName = file.getName(); String fileNameAbsolute = file.getAbsolutePath(); String tmp_dir = TMP_DIR; if (!tmp_dir.endsWith(File.separator)) { tmp_dir = tmp_dir + File.separator; } String fileNameRelative = fileNameAbsolute.substring(tmp_dir.length(), fileNameAbsolute.length()); // TODO: the id below is a temporary id. Create final id using // namespace of the wsdl:service // Assign repository item to idToRepositoryItemMap idToRepositoryItemMap.put(fileNameRelative, new RepositoryItemImpl(fileNameRelative, new DataHandler(new FileDataSource(file)))); // Get the ExtrinsicObjectType instance for this file using the // relative file name as the key currentRelativeFilename = fileNameRelative; ExtrinsicObjectType eo = createExtrinsicObject(fileNameRelative); // Create the InputSource String urlStr = fileNameAbsolute; urlStr = Utility.absolutize(Utility.getFileOrURLName(urlStr)); inputSource = new InputSource(urlStr); if (eo.getObjectType().equals(CanonicalConstants.CANONICAL_OBJECT_TYPE_ID_WSDL)) { catalogWSDLExtrinsicObject(eo, inputSource); } else if (eo.getObjectType().equals(CanonicalConstants.CANONICAL_OBJECT_TYPE_ID_XMLSchema)) { catalogXMLSchemaExtrinsicObject(eo, inputSource); } } }
From source file:com.clustercontrol.ws.collect.CollectEndpoint.java
/** * ?DL?//from w w w . j a va 2 s. c o m * * CollectRead??? * * @param filepath * @return * @throws InvalidRole * @throws InvalidUserPass * @throws HinemosUnknown */ @XmlMimeType("application/octet-stream") public DataHandler downloadPerfFile(String fileName) throws InvalidUserPass, InvalidRole, HinemosUnknown { m_log.debug("downloadPerfFile() fileName = " + fileName); ArrayList<SystemPrivilegeInfo> systemPrivilegeList = new ArrayList<SystemPrivilegeInfo>(); systemPrivilegeList.add(new SystemPrivilegeInfo(FunctionConstant.COLLECT, SystemPrivilegeMode.READ)); HttpAuthenticator.authCheck(wsctx, systemPrivilegeList); // ??? StringBuffer msg = new StringBuffer(); msg.append(", FileName="); msg.append(fileName); String exportDirectory = HinemosPropertyUtil.getHinemosPropertyStr("performance.export.dir", HinemosPropertyDefault.getString(HinemosPropertyDefault.StringKey.PERFORMANCE_EXPORT_DIR)); File file = new File(exportDirectory + fileName); if (!file.exists()) { m_log.info("file is not found : " + exportDirectory + fileName); m_opelog.warn(HinemosModuleConstant.LOG_PREFIX_PERFORMANCE + " Download Failed, Method=downloadPerfFile, User=" + HttpAuthenticator.getUserAccountString(wsctx) + msg.toString()); return null; } m_log.info("file is found : " + exportDirectory + fileName); m_opelog.info(HinemosModuleConstant.LOG_PREFIX_PERFORMANCE + " Download, Method=downloadPerfFile, User=" + HttpAuthenticator.getUserAccountString(wsctx) + msg.toString()); FileDataSource source = new FileDataSource(file); DataHandler dataHandler = new DataHandler(source); return dataHandler; }
From source file:com.clustercontrol.infra.session.InfraControllerBean.java
public DataHandler downloadTransferFile(String fileName) { m_log.info("downloadTransferFile fileName=" + fileName); String infraDirectory = HinemosPropertyUtil.getHinemosPropertyStr("infra.transfer.dir", HinemosPropertyDefault.getString(HinemosPropertyDefault.StringKey.INFRA_TRANSFER_DIR)) + File.separator + "send" + File.separator; FileDataSource fileData = new FileDataSource(infraDirectory + fileName); return new DataHandler(fileData); }
From source file:org.sakaiproject.tool.mailtool.Mailtool.java
public String processSendEmail() { /* EmailUser */ selected = m_recipientSelector.getSelectedUsers(); if (m_selectByTree) { selectedGroupAwareRoleUsers = m_recipientSelector1.getSelectedUsers(); selectedGroupUsers = m_recipientSelector2.getSelectedUsers(); selectedSectionUsers = m_recipientSelector3.getSelectedUsers(); selected.addAll(selectedGroupAwareRoleUsers); selected.addAll(selectedGroupUsers); selected.addAll(selectedSectionUsers); }/*from www. j ava 2 s .c om*/ // Put everyone in a set so the same person doesn't get multiple emails. Set emailusers = new TreeSet(); if (isAllUsersSelected()) { // the button for this is inactivated ... leave for future for (Iterator i = getEmailGroups().iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); emailusers.addAll(group.getEmailusers()); } } if (isAllGroupSelected()) { for (Iterator i = getEmailGroupsByType("section").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("section")) { selected.addAll(group.getEmailusers()); } } } if (isAllSectionSelected()) { for (Iterator i = getEmailGroupsByType("group").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("group")) { selected.addAll(group.getEmailusers()); } } } if (isAllGroupAwareRoleSelected()) { for (Iterator i = getEmailGroupsByType("role_groupaware").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("role_groupaware")) { selected.addAll(group.getEmailusers()); } } } emailusers = new TreeSet(selected); // convert List to Set (remove duplicates) m_subjectprefix = getSubjectPrefixFromConfig(); EmailUser curUser = getCurrentUser(); String fromEmail = ""; String fromDisplay = ""; if (curUser != null) { fromEmail = curUser.getEmail(); fromDisplay = curUser.getDisplayname(); } String fromString = fromDisplay + " <" + fromEmail + ">"; m_results = "Message sent to: <br>"; String subject = m_subject; //Should we append this to the archive? String emailarchive = "/mailarchive/channel/" + m_siteid + "/main"; if (m_archiveMessage && isEmailArchiveInSite()) { String attachment_info = "<br/>"; Attachment a = null; Iterator iter = attachedFiles.iterator(); int i = 0; while (iter.hasNext()) { a = (Attachment) iter.next(); attachment_info += "<br/>"; attachment_info += "Attachment #" + (i + 1) + ": " + a.getFilename() + "(" + a.getSize() + " Bytes)"; i++; } this.appendToArchive(emailarchive, fromString, subject, m_body + attachment_info); } List headers = new ArrayList(); if (getTextFormat().equals("htmltext")) headers.add("content-type: text/html"); else headers.add("content-type: text/plain"); String smtp_server = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); //String smtp_port = ServerConfigurationService.getString("smtp.port"); try { Properties props = new Properties(); props.put("mail.smtp.host", smtp_server); //props.put("mail.smtp.port", smtp_port); Session s = Session.getInstance(props, null); MimeMessage message = new MimeMessage(s); InternetAddress from = new InternetAddress(fromString); message.setFrom(from); String reply = getReplyToSelected().trim().toLowerCase(); if (reply.equals("yes")) { // "reply to sender" is default. So do nothing } else if (reply.equals("no")) { String noreply = getSiteTitle() + " <noreply@" + smtp_server + ">"; InternetAddress noreplyemail = new InternetAddress(noreply); message.setFrom(noreplyemail); } else if (reply.equals("otheremail") && getReplyToOtherEmail().equals("") != true) { // need input(email) validation InternetAddress replytoList[] = { new InternetAddress(getConfigParam("replyto").trim()) }; message.setReplyTo(replytoList); } message.setSubject(subject); String text = m_body; String attachmentdirectory = getUploadDirectory(); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message String messagetype = ""; if (getTextFormat().equals("htmltext")) { messagetype = "text/html"; } else { messagetype = "text/plain"; } messageBodyPart.setContent(text, messagetype); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment Attachment a = null; Iterator iter = attachedFiles.iterator(); while (iter.hasNext()) { a = (Attachment) iter.next(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource( attachmentdirectory + this.getCurrentUser().getUserid() + "-" + a.getFilename()); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(a.getFilename()); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); //Send the emails String recipientsString = ""; for (Iterator i = emailusers.iterator(); i.hasNext(); recipientsString += ",") { EmailUser euser = (EmailUser) i.next(); String toEmail = euser.getEmail(); // u.getEmail(); String toDisplay = euser.getDisplayname(); // u.getDisplayName(); // if AllUsers are selected, do not add current user's email to recipients if (isAllUsersSelected() && getCurrentUser().getEmail().equals(toEmail)) { // don't add sender to recipients } else { recipientsString += toEmail; m_results += toDisplay + (i.hasNext() ? "<br/>" : ""); } // InternetAddress to[] = {new InternetAddress(toEmail) }; // Transport.send(message,to); } if (m_otheremails.trim().equals("") != true) { // // multiple email validation is needed here // String refinedOtherEmailAddresses = m_otheremails.trim().replace(';', ','); recipientsString += refinedOtherEmailAddresses; m_results += "<br/>" + refinedOtherEmailAddresses; // InternetAddress to[] = {new InternetAddress(refinedOtherEmailAddresses) }; // Transport.send(message, to); } if (m_sendmecopy) { message.addRecipients(Message.RecipientType.CC, fromEmail); // trying to solve SAK-7410 // recipientsString+=fromEmail; // InternetAddress to[] = {new InternetAddress(fromEmail) }; // Transport.send(message, to); } // message.addRecipients(Message.RecipientType.TO, recipientsString); message.addRecipients(Message.RecipientType.BCC, recipientsString); Transport.send(message); } catch (Exception e) { log.debug("Mailtool Exception while trying to send the email: " + e.getMessage()); } // Clear the Subject and Body of the Message m_subject = getSubjectPrefix().equals("") ? getSubjectPrefixFromConfig() : getSubjectPrefix(); m_otheremails = ""; m_body = ""; num_files = 0; attachedFiles.clear(); m_recipientSelector = null; m_recipientSelector1 = null; m_recipientSelector2 = null; m_recipientSelector3 = null; setAllUsersSelected(false); setAllGroupSelected(false); setAllSectionSelected(false); // Display Users with Bad Emails if the option is turned on. boolean showBadEmails = getDisplayInvalidEmailAddr(); if (showBadEmails == true) { m_results += "<br/><br/>"; List /* String */ badnames = new ArrayList(); for (Iterator i = selected.iterator(); i.hasNext();) { EmailUser user = (EmailUser) i.next(); /* This check should maybe be some sort of regular expression */ if (user.getEmail().equals("")) { badnames.add(user.getDisplayname()); } } if (badnames.size() > 0) { m_results += "The following users do not have valid email addresses:<br/>"; for (Iterator i = badnames.iterator(); i.hasNext();) { String name = (String) i.next(); if (i.hasNext() == true) m_results += name + "/ "; else m_results += name; } } } return "results"; }
From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java
protected DataHandler createDataHandler(AttachmentTemplate attachmentTemplate, WorkItem workItem, JCRSessionWrapper session) throws Exception { // evaluate expression String expression = attachmentTemplate.getExpression(); if (expression != null) { Object object = evaluateExpression(workItem, expression, session); return new DataHandler(object, attachmentTemplate.getMimeType()); }/* w ww. j a v a2 s . c om*/ // resolve local file String file = attachmentTemplate.getFile(); if (file != null) { File targetFile = new File(evaluateExpression(workItem, file, session)); if (!targetFile.isFile()) { throw new Exception("could not read attachment content, file not found: " + targetFile); } // set content from file return new DataHandler(new FileDataSource(targetFile)); } // resolve external url URL targetUrl; String url = attachmentTemplate.getUrl(); if (url != null) { url = evaluateExpression(workItem, url, session); targetUrl = new URL(url); } // resolve classpath resource else { String resource = evaluateExpression(workItem, attachmentTemplate.getResource(), session); targetUrl = Thread.currentThread().getContextClassLoader().getResource(resource); if (targetUrl == null) { throw new Exception("could not read attachment content, resource not found: " + resource); } } // set content from url return new DataHandler(targetUrl); }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//w w w . j a va 2 s .c om * * @param multipart DOCUMENT ME! * @param file DOCUMENT ME! * @param charset DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static void attach(MimeMultipart multipart, File file, String charset) throws MessagingException { // UNDONE how to specify the character set of the file??? MimeBodyPart xbody = new MimeBodyPart(); FileDataSource xds = new FileDataSource(file); DataHandler xdh = new DataHandler(xds); xbody.setDataHandler(xdh); //System.out.println(xdh.getContentType()); // UNDONE // xbody.setContentLanguage( String ); // this could be language from Locale // xbody.setContentMD5( String md5 ); // don't know about this yet xbody.setDescription("File Attachment: " + file.getName(), charset); xbody.setDisposition(Part.ATTACHMENT); MessageUtilities.setFileName(xbody, file.getName(), charset); multipart.addBodyPart(xbody); }