List of usage examples for javax.activation FileDataSource FileDataSource
public FileDataSource(String name)
From source file:org.apache.synapse.samples.framework.clients.MTOMSwASampleClient.java
public SampleClientResult sendUsingSWA(String fileName, String targetEPR) { clientResult = new SampleClientResult(); try {//from ww w . ja v a2 s . c o m Options options = new Options(); options.setTo(new EndpointReference(targetEPR)); options.setAction("urn:uploadFileUsingSwA"); options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE); ConfigurationContext configContext = ConfigurationContextFactory .createConfigurationContextFromFileSystem(configuration.getClientRepo(), configuration.getAxis2Xml()); ServiceClient sender = new ServiceClient(configContext, null); sender.setOptions(options); OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP); MessageContext mc = new MessageContext(); log.info("Sending file : " + fileName + " as SwA"); FileDataSource fileDataSource = new FileDataSource(new File(fileName)); DataHandler dataHandler = new DataHandler(fileDataSource); String attachmentID = mc.addAttachment(dataHandler); SOAPFactory factory = OMAbstractFactory.getSOAP11Factory(); SOAPEnvelope env = factory.getDefaultEnvelope(); OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0"); OMElement payload = factory.createOMElement("uploadFileUsingSwA", ns); OMElement request = factory.createOMElement("request", ns); OMElement imageId = factory.createOMElement("imageId", ns); imageId.setText(attachmentID); request.addChild(imageId); payload.addChild(request); env.getBody().addChild(payload); mc.setEnvelope(env); mepClient.addMessageContext(mc); mepClient.execute(true); MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); SOAPBody body = response.getEnvelope().getBody(); String imageContentId = body .getFirstChildWithName(new QName("http://services.samples", "uploadFileUsingSwAResponse")) .getFirstChildWithName(new QName("http://services.samples", "response")) .getFirstChildWithName(new QName("http://services.samples", "imageId")).getText(); Attachments attachment = response.getAttachmentMap(); dataHandler = attachment.getDataHandler(imageContentId); File tempFile = File.createTempFile("swa-", ".gif"); FileOutputStream fos = new FileOutputStream(tempFile); dataHandler.writeTo(fos); fos.flush(); fos.close(); log.info("Saved response to file : " + tempFile.getAbsolutePath()); clientResult.incrementResponseCount(); } catch (Exception e) { log.error("Error invoking service", e); clientResult.setException(e); } return clientResult; }
From source file:edu.mit.broad.genepattern.gp.services.GenePatternClientImpl.java
private DataHandler getFileDataHandler(ParameterInfo parameter) { String filePath = parameter.getValue(); FileDataSource fileDataSource = new FileDataSource(filePath) { @Override//from w w w . j a va 2 s . c o m public String getName() { return getFile().getName(); } }; DataHandler handler = new DataHandler(fileDataSource); parameter.setValue(fileDataSource.getName()); return handler; }
From source file:com.collabnet.ccf.pi.sfee.v44.SFEEAttachmentHandler.java
/** * This method uploads the file and gets the new file descriptor returned * from the TF system. It then associates the file descriptor to the * artifact there by adding the attachment to the artifact. * /*from ww w . j av a 2 s .c o m*/ * @param sessionId * - The current session id * @param artifactId * - The artifact's id to which the attachment should be added. * @param comment * - Comment for the attachment addition * @param fileName * - Name of the file that is attached to this artifact * @param mimeType * - MIME type of the file that is being attached. * @param att * - the file content * @param linkUrl * * @throws RemoteException * - if any SOAP api call fails */ public ArtifactSoapDO attachFileToArtifact(String sessionId, String artifactId, String comment, String fileName, String mimeType, GenericArtifact att, byte[] linkUrl) throws RemoteException { ArtifactSoapDO soapDo = null; String attachmentDataFileName = GenericArtifactHelper .getStringGAField(AttachmentMetaData.ATTACHMENT_DATA_FILE, att); boolean retryCall = true; while (retryCall) { retryCall = false; String fileDescriptor = null; try { byte[] data = null; if (StringUtils.isEmpty(attachmentDataFileName)) { if (linkUrl == null) { data = att.getRawAttachmentData(); } else { data = linkUrl; } fileDescriptor = fileStorageApp.startFileUpload(sessionId); fileStorageApp.write(sessionId, fileDescriptor, data); fileStorageApp.endFileUpload(sessionId, fileDescriptor); } else { try { DataSource dataSource = new FileDataSource(new File(attachmentDataFileName)); DataHandler dataHandler = new DataHandler(dataSource); fileDescriptor = fileStorageSoapApp.uploadFile(sessionId, dataHandler); } catch (IOException e) { String message = "Exception while uploading the attachment " + attachmentDataFileName; log.error(message, e); throw new CCFRuntimeException(message, e); } } soapDo = mTrackerApp.getArtifactData(sessionId, artifactId); boolean fileAttached = true; while (fileAttached) { try { fileAttached = false; mTrackerApp.setArtifactData(sessionId, soapDo, comment, fileName, mimeType, fileDescriptor); } catch (AxisFault e) { javax.xml.namespace.QName faultCode = e.getFaultCode(); if (!faultCode.getLocalPart().equals("VersionMismatchFault")) { throw e; } logConflictResolutor.warn("Stale attachment update, trying again ...:", e); soapDo = mTrackerApp.getArtifactData(sessionId, artifactId); fileAttached = true; } } } catch (AxisFault e) { javax.xml.namespace.QName faultCode = e.getFaultCode(); if (!faultCode.getLocalPart().equals("InvalidSessionFault")) { throw e; } if (connectionManager.isEnableReloginAfterSessionTimeout() && (!connectionManager.isUseStandardTimeoutHandlingCode())) { log.warn("While uploading an attachment, the session id became invalid, trying again", e); retryCall = true; } else { throw e; } } } // we have to increase the version after the update // TODO Find out whether this really works if last modified date differs // from actual last modified date soapDo.setVersion(soapDo.getVersion() + 1); return soapDo; }
From source file:org.wso2.carbon.bpel.ui.fileupload.BPELUploadExecutor.java
public boolean execute(HttpServletRequest request, HttpServletResponse response) throws CarbonException, IOException { String errMsg;/* ww w .ja v a 2 s .com*/ 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; }
From source file:org.latticesoft.util.resource.MessageUtil.java
/** * Sends the email.// w w w . j a va 2 s . co m * @param info the EmailInfo containing the message and other details * @param p the properties to set in the environment when instantiating the session * @param auth the authenticator */ public static void sendMail(EmailInfo info, Properties p, Authenticator auth) { try { if (p == null) { if (log.isErrorEnabled()) { log.error("Null properties!"); } return; } Session session = Session.getInstance(p, auth); session.setDebug(true); if (log.isInfoEnabled()) { log.info(p); log.info(session); } MimeMessage mimeMessage = new MimeMessage(session); if (log.isInfoEnabled()) { log.info(mimeMessage); log.info(info.getFromAddress()); } mimeMessage.setFrom(info.getFromAddress()); mimeMessage.setSentDate(new Date()); List l = info.getToList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); if (log.isInfoEnabled()) { log.info(addr); } mimeMessage.addRecipients(Message.RecipientType.TO, addr); } } l = info.getCcList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); mimeMessage.addRecipients(Message.RecipientType.CC, addr); } } l = info.getBccList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); mimeMessage.addRecipients(Message.RecipientType.BCC, addr); } } if (info.getAttachment().size() == 0) { if (info.getCharSet() != null) { mimeMessage.setSubject(info.getSubject(), info.getCharSet()); mimeMessage.setText(info.getContent(), info.getCharSet()); } else { mimeMessage.setSubject(info.getSubject()); mimeMessage.setText(info.getContent()); } mimeMessage.setContent(info.getContent(), info.getContentType()); } else { if (info.getCharSet() != null) { mimeMessage.setSubject(info.getSubject(), info.getCharSet()); } else { mimeMessage.setSubject(info.getSubject()); } Multipart mp = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); if (info.getCharSet() != null) { body.setText(info.getContent(), info.getCharSet()); body.setContent(info.getContent(), info.getContentType()); } else { body.setText(info.getContent()); body.setContent(info.getContent(), info.getContentType()); } mp.addBodyPart(body); for (int i = 0; i < info.getAttachment().size(); i++) { String filename = (String) info.getAttachment().get(i); MimeBodyPart attachment = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filename); attachment.setDataHandler(new DataHandler(fds)); attachment.setFileName(MimeUtility.encodeWord(fds.getName())); mp.addBodyPart(attachment); } mimeMessage.setContent(mp); } Transport.send(mimeMessage); } catch (Exception e) { if (log.isErrorEnabled()) { log.error("Error in sending email", e); } } }
From source file:edu.harvard.med.screensaver.service.SmtpEmailService.java
private static void setFileAsAttachment(Message msg, String message, File file) throws MessagingException { MimeBodyPart p1 = new MimeBodyPart(); p1.setText(message);/*from w w w . j a va 2 s.c om*/ // Create second part MimeBodyPart p2 = new MimeBodyPart(); // Put a file in the second part FileDataSource fds = new FileDataSource(file); p2.setDataHandler(new DataHandler(fds)); p2.setFileName(fds.getName()); // Create the Multipart. Add BodyParts to it. Multipart mp = new MimeMultipart(); mp.addBodyPart(p1); mp.addBodyPart(p2); // Set Multipart as the message's content msg.setContent(mp); }
From source file:com.aurel.track.util.emailHandling.MailBuilder.java
private void includeAttachments(MimeMultipart mimeMultipart, List<LabelValueBean> attachments) throws MessagingException { for (int i = 0; i < attachments.size(); i++) { LabelValueBean lvb = attachments.get(i); File f = new File(lvb.getValue()); if (f != null && f.exists()) { LOGGER.debug("Use attachment file:" + f.getAbsolutePath()); MimeBodyPart mbpFile = new MimeBodyPart(); FileDataSource fds = new FileDataSource(f); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(lvb.getLabel()); mimeMultipart.addBodyPart(mbpFile); } else {//from w w w.j a v a2 s . c o m LOGGER.debug("Attachment file:\"" + lvb.getValue() + "\" not exits!"); } } }
From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java
public void sendMail(Mail mail) { LOG.debug("sendEmail() to: " + mail.getRecipient()); try {/* w w w . j ava 2 s. co m*/ Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator); session.setDebug(false); MimeMessage msg = new MimeMessage(session); msg.setFrom(m_bag.m_fromAddress); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient())); msg.setSubject(mail.getSubject()); msg.setSentDate(new Date()); Multipart mp = new MimeMultipart(); MimeBodyPart txtmbp = new MimeBodyPart(); txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE); mp.addBodyPart(txtmbp); List<String> attachments = mail.getAttachments(); for (Iterator<String> it = attachments.iterator(); it.hasNext();) { MimeBodyPart mbp = new MimeBodyPart(); String filename = it.next(); FileDataSource fds = new FileDataSource(filename); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(MimeUtility.encodeText(fds.getName())); mp.addBodyPart(mbp); } msg.setContent(mp); if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null) && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) { cheat(msg, m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@"))); } Transport.send(msg); LOG.info("Successfully send the mail to " + mail.getRecipient()); } catch (Throwable e) { LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e); LOG.debug("Details:", e); } }
From source file:org.unitime.commons.Email.java
public void addAttachement(File file, String name) throws MessagingException { BodyPart attachement = new MimeBodyPart(); attachement.setDataHandler(new DataHandler(new FileDataSource(file))); attachement.setFileName(name == null ? file.getName() : name); iBody.addBodyPart(attachement);/*from ww w . j a va2s .c om*/ }
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }// w ww . j a v a 2 s . c o m if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }