List of usage examples for javax.activation DataHandler DataHandler
public DataHandler(URL url)
DataHandler
instance referencing a URL. From source file:com.threewks.thundr.gmail.GmailMailer.java
private MimeMessage createMime(String bodyText, String subject, Map<String, String> to, List<Attachment> pdfs) throws MessagingException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); Set<InternetAddress> toAddresses = getInternetAddresses(to); if (!toAddresses.isEmpty()) { email.addRecipients(javax.mail.Message.RecipientType.TO, toAddresses.toArray(new InternetAddress[to.size()])); }/*ww w . ja v a 2 s. c om*/ email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/html"); mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); for (Attachment attachmentPdf : pdfs) { MimeBodyPart attachment = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(attachmentPdf.getData(), "application/pdf"); attachment.setDataHandler(new DataHandler(source)); attachment.setFileName(attachmentPdf.getFileName()); multipart.addBodyPart(mimeBodyPart); multipart.addBodyPart(attachment); } email.setContent(multipart); return email; }
From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java
public static void SendEmailSephoraFailed(String adresaSephora, String from, String to1, String to2, String grupSephora, String subject, String filename) throws FileNotFoundException, IOException { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); //get Session Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, "anda.cristea"); }//ww w . j a v a2s . c o m }); //compose message try { MimeMessage message = new MimeMessage(session); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1)); message.setSubject(subject); // message.setText(msg); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Raport teste automate"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); //send message Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:com.szmslab.quickjavamail.send.MailSender.java
/** * MimeBodyPart????Content-Disposition: attachment * * @param file//from w w w . j a v a 2 s .co m * * @return MimeBodyPartContent-Disposition: attachment? * @throws MessagingException * @throws UnsupportedEncodingException */ private MimeBodyPart createAttachmentPart(AttachmentFile file) throws MessagingException, UnsupportedEncodingException { MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null)); attachmentPart.setDataHandler(new DataHandler(file.getDataSource())); attachmentPart.setDisposition(MimeBodyPart.ATTACHMENT); return attachmentPart; }
From source file:com.clustercontrol.infra.util.InfraEndpointWrapper.java
public void modifyInfraFile(InfraFileInfo info, String filePath) throws HinemosUnknown_Exception, InfraFileTooLarge_Exception, InvalidRole_Exception, InvalidUserPass_Exception { WebServiceException wse = null; for (EndpointSetting<InfraEndpoint> endpointSetting : getInfraEndpoint(endpointUnit)) { try {//from w ww. j a va2 s . c o m InfraEndpoint endpoint = endpointSetting.getEndpoint(); if (filePath != null) { endpoint.modifyInfraFile(info, new DataHandler(new FileDataSource(filePath))); } else { endpoint.modifyInfraFile(info, null); } return; } catch (WebServiceException e) { wse = e; m_log.warn("modifyInfraFile(), " + e.getMessage()); endpointUnit.changeEndpoint(); } } throw wse; }
From source file:it.cnr.icar.eric.server.repository.hibernate.HibernateRepositoryManager.java
/** * Returns the RepositoryItem associated with the ExtrinsicObject specified by id. * * @param id Unique id for ExtrinsicObject whose repository item is desired. * @return RepositoryItem instance/*from www .ja v a 2s .co m*/ * @exception RegistryException */ @SuppressWarnings("unused") public RepositoryItem getRepositoryItem(String id) throws RegistryException { RepositoryItem repositoryItem = null; /* ** Following code must duplicate that in getRepositoryItemKey() ** because we need the eo variable later. Keep the two in sync ** manually. */ ServerRequestContext context = null; try { context = new ServerRequestContext("HibernateRepositoryManager:getRepositoryItem", null); //Access control is check in qm.getRepositoryItem using actual request context //This internal request context has total access. context.setUser(AuthenticationServiceImpl.getInstance().registryOperator); RegistryObjectType ro = qm.getRegistryObject(context, id, "ExtrinsicObject"); if (!(ro instanceof ExtrinsicObjectType)) { throw new ObjectNotFoundException(id); } ExtrinsicObjectType ebExtrinsicObjectType = (ExtrinsicObjectType) ro; if (ebExtrinsicObjectType == null) { throw new ObjectNotFoundException(id); } VersionInfoType ebVersionInfoType = ebExtrinsicObjectType.getContentVersionInfo(); if (ebVersionInfoType == null) { // no Repository Item to find for this EO throw new RepositoryItemNotFoundException(id, ebExtrinsicObjectType.getVersionInfo().getVersionName()); } RepositoryItemKey key = new RepositoryItemKey(ebExtrinsicObjectType.getLid(), ebVersionInfoType.getVersionName()); Transaction tx = null; String lid = key.getLid(); String versionName = key.getVersionName(); try { SessionContext sc = hu.getSessionContext(); Session s = sc.getSession(); //Need to call clear otherwise we get a cached ReposiytoryItemBean where the txn has committed //and Blob cannot be read any more. This will be better fixed when we pass ServerRequestContext //to each rm interface method and leverage leave txn management to ServerRequestContext. //See patch submitted for Sun Bug 6444810 on 6/28/2006 s.clear(); tx = s.beginTransaction(); // if item does not exist, error String findByID = "from RepositoryItemBean as rib where rib.key.lid = ? AND rib.key.versionName = ? "; Object[] params = { lid, versionName }; Type[] types = { Hibernate.STRING, Hibernate.STRING }; List<?> results = s.find(findByID, params, types); if (results.isEmpty()) { String errmsg = ServerResourceBundle.getInstance().getString( "message.RepositoryItemWithIdAndVersionDoesNotExist", new Object[] { lid, versionName }); log.error(errmsg); throw new RepositoryItemNotFoundException(lid, versionName); } RepositoryItemBean bean = (RepositoryItemBean) results.get(0); if (log.isDebugEnabled()) { String message = "Getting repository item:" + "lid='" + lid + "', " + "versionName='" + versionName + "', "; if (isBlobSupported) { message += "content size=" + bean.getBlobContent().length(); } else { message += "content size=" + bean.getBinaryContent().length; } log.debug(message); } String contentType = ebExtrinsicObjectType.getMimeType(); DataHandler contentDataHandler; if (isBlobSupported) { contentDataHandler = new DataHandler(new ByteArrayDataSource( readBytes(bean.getBlobContent().getBinaryStream()), contentType)); } else { contentDataHandler = new DataHandler( new ByteArrayDataSource(bean.getBinaryContent(), contentType)); } repositoryItem = new RepositoryItemImpl(id, contentDataHandler); tx.commit(); } catch (RegistryException e) { tryRollback(tx); throw e; } catch (Exception e) { String msg = ServerResourceBundle.getInstance().getString("message.FailedToGetRepositoryItem", new Object[] { lid, versionName }); log.error(e, e); tryRollback(tx); throw new RegistryException(ServerResourceBundle.getInstance() .getString("message.seeLogsForDetails", new Object[] { msg })); } finally { tryClose(); } } finally { context.rollback(); } return repositoryItem; }
From source file:org.codehaus.enunciate.modules.rest.RESTResourceExporter.java
/** * Handles a specific REST operation./*from www .j a v a2 s .co m*/ * * @param operation The operation. * @param handler The handler for the operation. * @param request The request. * @param response The response. * @return The model and view. */ protected ModelAndView handleRESTOperation(RESTOperation operation, RESTRequestContentTypeHandler handler, HttpServletRequest request, HttpServletResponse response) throws Exception { if (!this.endpoints.containsKey(operation.getVerb())) { throw new MethodNotAllowedException("Method not allowed."); } if ((this.multipartRequestHandler != null) && (this.multipartRequestHandler.isMultipart(request))) { request = this.multipartRequestHandler.handleMultipartRequest(request); } String requestContext = request.getRequestURI().substring(request.getContextPath().length()); Map<String, String> contextParameters; try { contextParameters = resource.getContextParameterAndProperNounValues(requestContext); } catch (IllegalArgumentException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); return null; } Object properNounValue = null; HashMap<String, Object> contextParameterValues = new HashMap<String, Object>(); for (Map.Entry<String, String> entry : contextParameters.entrySet()) { String parameterName = entry.getKey(); String parameterValue = entry.getValue(); if (parameterName == null) { Class nounType = operation.getProperNounType(); if (nounType != null) { //todo: provide a hook to some other conversion mechanism? try { properNounValue = converter.convert(parameterValue, nounType); } catch (Exception e) { throw new ParameterConversionException(parameterValue); } } } else { Class contextParameterType = operation.getContextParameterTypes().get(parameterName); if (contextParameterType != null) { //todo: provide a hook to some other conversion mechanism? try { contextParameterValues.put(parameterName, converter.convert(parameterValue, contextParameterType)); } catch (Exception e) { throw new ParameterConversionException(parameterValue); } } } } if ((properNounValue == null) && (operation.isProperNounOptional() != null) && (!operation.isProperNounOptional())) { throw new MissingParameterException( "A specific '" + resource.getNoun() + "' must be specified on the URL."); } HashMap<String, Object> adjectives = new HashMap<String, Object>(); for (String adjective : operation.getAdjectiveTypes().keySet()) { Object adjectiveValue = null; if (!operation.getComplexAdjectives().contains(adjective)) { //not complex, map it. String[] parameterValues = request.getParameterValues(adjective); if ((parameterValues != null) && (parameterValues.length > 0)) { //todo: provide a hook to some other conversion mechanism? final Class adjectiveType = operation.getAdjectiveTypes().get(adjective); Class componentType = adjectiveType.isArray() ? adjectiveType.getComponentType() : adjectiveType; Object adjectiveValues = Array.newInstance(componentType, parameterValues.length); for (int i = 0; i < parameterValues.length; i++) { try { Array.set(adjectiveValues, i, converter.convert(parameterValues[i], componentType)); } catch (Exception e) { throw new KeyParameterConversionException(adjective, parameterValues[i]); } } if (adjectiveType.isArray()) { adjectiveValue = adjectiveValues; } else { adjectiveValue = Array.get(adjectiveValues, 0); } } if ((adjectiveValue == null) && (!operation.getAdjectivesOptional().get(adjective))) { throw new MissingParameterException("Missing request parameter: " + adjective); } } else { //use spring's binding to map the complex adjective to the request parameters. try { adjectiveValue = operation.getAdjectiveTypes().get(adjective).newInstance(); } catch (Throwable e) { throw new IllegalArgumentException( "A complex adjective must have a simple, no-arg constructor. Invalid type: " + operation.getAdjectiveTypes().get(adjective)); } ServletRequestDataBinder binder = new ServletRequestDataBinder(adjectiveValue, adjective); binder.setIgnoreUnknownFields(true); binder.bind(request); BindException errors = binder.getErrors(); if ((errors != null) && (errors.getAllErrors() != null) && (!errors.getAllErrors().isEmpty())) { ObjectError firstError = (ObjectError) errors.getAllErrors().get(0); String message = "Invalid parameter."; if (firstError instanceof FieldError) { throw new ParameterConversionException( ((FieldError) firstError).getRejectedValue().toString()); } response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); } } adjectives.put(adjective, adjectiveValue); } Object nounValue = null; if (operation.getNounValueType() != null) { Class nounValueType = operation.getNounValueType(); if ((nounValueType.equals(DataHandler.class)) || ((nounValueType.isArray() && nounValueType.getComponentType().equals(DataHandler.class)))) { Collection<DataHandler> dataHandlers; if (this.multipartRequestHandler != null) { dataHandlers = this.multipartRequestHandler.parseParts(request); } else { dataHandlers = new ArrayList<DataHandler>(); dataHandlers.add(new DataHandler( new RESTRequestDataSource(request, resource.getNounContext() + resource.getNoun()))); } nounValue = dataHandlers; if (operation.getNounValueType().equals(DataHandler.class)) { nounValue = dataHandlers.iterator().next(); } else if (mustConvertNounValueToArray(operation)) { Class type = operation.getNounValueType(); if ((type.isArray() && type.getComponentType().equals(DataHandler.class))) { nounValue = dataHandlers.toArray(new DataHandler[dataHandlers.size()]); } } } else { try { //if the operation has a noun value type, unmarshall it from the body.... nounValue = handler.read(request); } catch (Exception e) { //if we can't unmarshal the noun value, continue if the noun value is optional. if (!operation.isNounValueOptional()) { throw e; } } } } Object result = operation.invoke(properNounValue, contextParameterValues, adjectives, nounValue, this.endpoints.get(operation.getVerb())); //successful invocation, set up the response... if (result instanceof DataHandler) { response.setContentType(((DataHandler) result).getContentType()); ((DataHandler) result).writeTo(response.getOutputStream()); } else { response.setContentType( String.format("%s; charset=%s", operation.getContentType(), operation.getCharset())); handler.write(result, request, response); } return null; }
From source file:org.apache.nifi.processors.standard.PutEmail.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final FlowFile flowFile = session.get(); if (flowFile == null) { return;/* w ww .java 2 s . c o m*/ } final Properties properties = this.getMailPropertiesFromFlowFile(context, flowFile); final Session mailSession = this.createMailSession(properties); final Message message = new MimeMessage(mailSession); final ComponentLog logger = getLogger(); try { message.addFrom(toInetAddresses(context, flowFile, FROM)); message.setRecipients(RecipientType.TO, toInetAddresses(context, flowFile, TO)); message.setRecipients(RecipientType.CC, toInetAddresses(context, flowFile, CC)); message.setRecipients(RecipientType.BCC, toInetAddresses(context, flowFile, BCC)); message.setHeader("X-Mailer", context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions(flowFile).getValue()); message.setSubject(context.getProperty(SUBJECT).evaluateAttributeExpressions(flowFile).getValue()); String messageText = context.getProperty(MESSAGE).evaluateAttributeExpressions(flowFile).getValue(); if (context.getProperty(INCLUDE_ALL_ATTRIBUTES).asBoolean()) { messageText = formatAttributes(flowFile, messageText); } String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions(flowFile) .getValue(); message.setContent(messageText, contentType); message.setSentDate(new Date()); if (context.getProperty(ATTACH_FILE).asBoolean()) { final MimeBodyPart mimeText = new PreencodedMimeBodyPart("base64"); mimeText.setDataHandler(new DataHandler(new ByteArrayDataSource( Base64.encodeBase64(messageText.getBytes("UTF-8")), contentType + "; charset=\"utf-8\""))); final MimeBodyPart mimeFile = new MimeBodyPart(); session.read(flowFile, new InputStreamCallback() { @Override public void process(final InputStream stream) throws IOException { try { mimeFile.setDataHandler( new DataHandler(new ByteArrayDataSource(stream, "application/octet-stream"))); } catch (final Exception e) { throw new IOException(e); } } }); mimeFile.setFileName(flowFile.getAttribute(CoreAttributes.FILENAME.key())); MimeMultipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeText); multipart.addBodyPart(mimeFile); message.setContent(multipart); } send(message); session.getProvenanceReporter().send(flowFile, "mailto:" + message.getAllRecipients()[0].toString()); session.transfer(flowFile, REL_SUCCESS); logger.info("Sent email as a result of receiving {}", new Object[] { flowFile }); } catch (final ProcessException | MessagingException | IOException e) { context.yield(); logger.error("Failed to send email for {}: {}; routing to failure", new Object[] { flowFile, e.getMessage() }, e); session.transfer(flowFile, REL_FAILURE); } }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java
private MimeBodyPart zipAttachment(byte[] attach, String containedFileName, String zipFileName, String nameSuffix, String fileExtension) { MimeBodyPart messageBodyPart = null; try {/*from ww w. j a v a 2 s . c om*/ ByteArrayOutputStream bout = new ByteArrayOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(bout); String entryName = containedFileName + nameSuffix + fileExtension; zipOut.putNextEntry(new ZipEntry(entryName)); zipOut.write(attach); zipOut.closeEntry(); zipOut.close(); messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(zipFileName + nameSuffix + ".zip"); } catch (Exception e) { // TODO: handle exception } return messageBodyPart; }
From source file:org.apache.axis.attachments.AttachmentPart.java
/** * Sets the content of this attachment part to that of the * given <CODE>Object</CODE> and sets the value of the <CODE> * Content-Type</CODE> header to the given type. The type of the * <CODE>Object</CODE> should correspond to the value given for * the <CODE>Content-Type</CODE>. This depends on the particular * set of <CODE>DataContentHandler</CODE> objects in use. * @param object the Java object that makes up * the content for this attachment part * @param contentType the MIME string that * specifies the type of the content * @throws java.lang.IllegalArgumentException if * the contentType does not match the type of the content * object, or if there was no <CODE> * DataContentHandler</CODE> object for this content * object/*from w w w. ja v a 2 s . c o m*/ * @see #getContent() getContent() */ public void setContent(Object object, String contentType) { ManagedMemoryDataSource source = null; setMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE, contentType); if (object instanceof String) { try { String s = (String) object; java.io.ByteArrayInputStream bais = new java.io.ByteArrayInputStream(s.getBytes()); source = new ManagedMemoryDataSource(bais, ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, contentType, true); extractFilename(source); datahandler = new DataHandler(source); contentObject = object; return; } catch (java.io.IOException io) { log.error(Messages.getMessage("javaIOException00"), io); throw new java.lang.IllegalArgumentException(Messages.getMessage("illegalArgumentException00")); } } else if (object instanceof java.io.InputStream) { try { source = new ManagedMemoryDataSource((java.io.InputStream) object, ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, contentType, true); extractFilename(source); datahandler = new DataHandler(source); contentObject = null; // the stream has been consumed return; } catch (java.io.IOException io) { log.error(Messages.getMessage("javaIOException00"), io); throw new java.lang.IllegalArgumentException(Messages.getMessage("illegalArgumentException00")); } } else if (object instanceof StreamSource) { try { source = new ManagedMemoryDataSource(((StreamSource) object).getInputStream(), ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, contentType, true); extractFilename(source); datahandler = new DataHandler(source); contentObject = null; // the stream has been consumed return; } catch (java.io.IOException io) { log.error(Messages.getMessage("javaIOException00"), io); throw new java.lang.IllegalArgumentException(Messages.getMessage("illegalArgumentException00")); } } else { throw new java.lang.IllegalArgumentException(Messages.getMessage("illegalArgumentException00")); } }