Example usage for javax.activation DataSource getName

List of usage examples for javax.activation DataSource getName

Introduction

In this page you can find the example usage for javax.activation DataSource getName.

Prototype

public String getName();

Source Link

Document

Return the name of this object where the name of the object is dependant on the nature of the underlying objects.

Usage

From source file:org.bimserver.servlets.DownloadServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from   w ww .  j  a v  a 2 s .c o  m
        String acceptEncoding = request.getHeader("Accept-Encoding");
        boolean useGzip = false;
        if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
            useGzip = true;
        }
        OutputStream outputStream = response.getOutputStream();
        boolean zip = request.getParameter("zip") != null && request.getParameter("zip").equals("on");
        if (useGzip && !zip) {
            response.setHeader("Content-Encoding", "gzip");
            outputStream = new GZIPOutputStream(response.getOutputStream());
        }
        String token = (String) request.getSession().getAttribute("token");

        if (token == null) {
            token = request.getParameter("token");
        }
        long topicId = -1;
        if (request.getParameter("topicId") != null) {
            topicId = Long.parseLong(request.getParameter("topicId"));
        }
        ServiceMap serviceMap = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL);

        String action = request.getParameter("action");
        if (action != null) {
            if (action.equals("extendeddata")) {
                SExtendedData sExtendedData = serviceMap.getServiceInterface()
                        .getExtendedData(Long.parseLong(request.getParameter("edid")));
                SFile file = serviceMap.getServiceInterface().getFile(sExtendedData.getFileId());
                if (file.getMime() != null) {
                    response.setContentType(file.getMime());
                }
                if (file.getFilename() != null) {
                    response.setHeader("Content-Disposition",
                            "inline; filename=\"" + file.getFilename() + "\"");
                }
                outputStream.write(file.getData());
                if (outputStream instanceof GZIPOutputStream) {
                    ((GZIPOutputStream) outputStream).finish();
                }
                outputStream.flush();
                return;
            } else if (action.equals("getfile")) {
                String type = request.getParameter("type");
                if (type.equals("proto")) {
                    try {
                        String protocolBuffersFile = serviceMap.getAdminInterface()
                                .getProtocolBuffersFile(request.getParameter("name"));
                        outputStream.write(protocolBuffersFile.getBytes(Charsets.UTF_8));
                        outputStream.flush();
                    } catch (ServiceException e) {
                        LOGGER.error("", e);
                    }
                } else if (type.equals("serverlog")) {
                    try {
                        OutputStreamWriter writer = new OutputStreamWriter(outputStream);
                        writer.write(serviceMap.getAdminInterface().getServerLog());
                        writer.flush();
                    } catch (ServerException e) {
                        LOGGER.error("", e);
                    } catch (UserException e) {
                        LOGGER.error("", e);
                    }
                }
            } else if (action.equals("getBcfImage")) {
                long extendedDataId = Long.parseLong(request.getParameter("extendedDataId"));
                String topicGuid = request.getParameter("topicGuid");
                String imageGuid = request.getParameter("imageGuid");
                String name = request.getParameter("name");
                BcfFile bcfFile = BcfCache.INSTANCE.get(extendedDataId);
                if (bcfFile == null) {
                    SExtendedData extendedData = serviceMap.getServiceInterface()
                            .getExtendedData(extendedDataId);
                    long fileId = extendedData.getFileId();
                    SFile file = serviceMap.getServiceInterface().getFile(fileId);
                    try {
                        bcfFile = BcfFile.read(new ByteArrayInputStream(file.getData()),
                                new ReadOptions(false));
                        BcfCache.INSTANCE.put(extendedDataId, bcfFile);
                    } catch (BcfException e) {
                        e.printStackTrace();
                    }
                }
                TopicFolder topicFolder = bcfFile.getTopicFolder(topicGuid);
                if (topicFolder != null) {
                    byte[] data = topicFolder.getSnapshot(topicGuid + "/" + name);
                    if (data != null) {
                        response.setContentType("image/png");
                        IOUtils.write(data, outputStream);
                        if (outputStream instanceof GZIPOutputStream) {
                            ((GZIPOutputStream) outputStream).finish();
                        }
                        outputStream.flush();
                        return;
                    }
                }
            }
        } else {
            SSerializerPluginConfiguration serializer = null;
            if (request.getParameter("serializerOid") != null) {
                long serializerOid = Long.parseLong(request.getParameter("serializerOid"));
                serializer = serviceMap.getServiceInterface().getSerializerById(serializerOid);
            } else {
                serializer = serviceMap.getServiceInterface()
                        .getSerializerByName(request.getParameter("serializerName"));
            }
            if (request.getParameter("topicId") != null) {
                topicId = Long.parseLong(request.getParameter("topicId"));
            }
            if (topicId == -1) {
                response.getWriter().println("No valid topicId");
                return;
            }
            SDownloadResult checkoutResult = serviceMap.getServiceInterface().getDownloadData(topicId);
            if (checkoutResult == null) {
                LOGGER.error("Invalid topicId: " + topicId);
            } else {
                DataSource dataSource = checkoutResult.getFile().getDataSource();
                PluginConfiguration pluginConfiguration = new PluginConfiguration(
                        serviceMap.getPluginInterface().getPluginSettings(serializer.getOid()));

                final ProgressTopic progressTopic = getBimServer().getNotificationsManager()
                        .getProgressTopic(topicId);

                ProgressReporter progressReporter = new ProgressReporter() {
                    private long lastMax;
                    private long lastProgress;
                    private int stage = 3;
                    private Date start = new Date();
                    private String title = "Downloading...";

                    @Override
                    public void update(long progress, long max) {
                        if (progressTopic != null) {
                            LongActionState ds = StoreFactory.eINSTANCE.createLongActionState();
                            ds.setStart(start);
                            ds.setState(progress == max ? ActionState.FINISHED : ActionState.STARTED);
                            ds.setTitle(title);
                            ds.setStage(stage);
                            ds.setProgress((int) Math.round(100.0 * progress / max));

                            progressTopic.stageProgressUpdate(ds);

                            this.lastMax = max;
                            this.lastProgress = progress;
                        }
                    }

                    @Override
                    public void setTitle(String title) {
                        if (progressTopic != null) {
                            stage++;
                            this.title = title;
                            LongActionState ds = StoreFactory.eINSTANCE.createLongActionState();
                            ds.setStart(new Date());
                            ds.setState(lastProgress == lastMax ? ActionState.FINISHED : ActionState.STARTED);
                            ds.setTitle(title);
                            ds.setStage(stage);
                            ds.setProgress((int) Math.round(100.0 * lastProgress / lastMax));

                            progressTopic.stageProgressUpdate(ds);
                        }
                    }
                };

                try {
                    if (zip) {
                        if (pluginConfiguration.getString("ZipExtension") != null) {
                            response.setHeader("Content-Disposition",
                                    "inline; filename=\"" + dataSource.getName() + "."
                                            + pluginConfiguration.getString(SerializerPlugin.ZIP_EXTENSION)
                                            + "\"");
                        } else {
                            response.setHeader("Content-Disposition",
                                    "inline; filename=\"" + dataSource.getName() + ".zip" + "\"");
                        }
                        response.setContentType("application/zip");

                        String nameInZip = dataSource.getName() + "."
                                + pluginConfiguration.getString(SerializerPlugin.EXTENSION);
                        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
                        zipOutputStream.putNextEntry(new ZipEntry(nameInZip));

                        processDataSource(zipOutputStream, dataSource, progressReporter);
                        try {
                            zipOutputStream.finish();
                        } catch (IOException e) {
                            // Sometimes it's already closed, that's no problem
                        }
                    } else {
                        if (request.getParameter("mime") == null) {
                            response.setContentType(
                                    pluginConfiguration.getString(SerializerPlugin.CONTENT_TYPE));
                            response.setHeader("Content-Disposition",
                                    "inline; filename=\"" + dataSource.getName() + "."
                                            + pluginConfiguration.getString(SerializerPlugin.EXTENSION) + "\"");
                        } else {
                            response.setContentType(request.getParameter("mime"));
                        }
                        processDataSource(outputStream, dataSource, progressReporter);
                    }
                } catch (SerializerException s) {
                    if (s.getCause() != null && s.getCause() instanceof IOException) {

                    } else {
                        LOGGER.error("", s);
                    }

                    LongActionState ds = StoreFactory.eINSTANCE.createLongActionState();
                    ds.setStart(new Date());
                    ds.setState(ActionState.AS_ERROR);
                    ds.setTitle("Serialization Error");
                    ds.setProgress(-1);
                    ds.setStage(3);
                    ds.getErrors().add(s.getMessage());

                    progressTopic.stageProgressUpdate(ds);
                }
            }
        }
        if (outputStream instanceof GZIPOutputStream) {
            ((GZIPOutputStream) outputStream).finish();
        }
        outputStream.flush();
    } catch (NumberFormatException e) {
        LOGGER.error("", e);
        response.getWriter().println("Some number was incorrectly formatted");
    } catch (ServiceException e) {
        LOGGER.error("", e);
        response.getWriter().println(e.getUserMessage());
    } catch (EOFException e) {
    } catch (Exception e) {
        LOGGER.error("", e);
    }
}

From source file:org.chenillekit.mail.services.impl.MailServiceImpl.java

/**
 * send a HTML message./*from w  ww. j a  v  a 2 s  .  c o  m*/
 *
 * @param headers    the mail headers
 * @param htmlBody   the mail body (HTML based)
 * @param dataSources array of data sources to attach at this mail
 *
 * @return true if mail successfull send
 */
public boolean sendHtmlMail(MailMessageHeaders headers, String htmlBody, DataSource... dataSources) {
    try {
        HtmlEmail email = new HtmlEmail();

        setEmailStandardData(email);

        setMailMessageHeaders(email, headers);

        if (dataSources != null) {
            for (DataSource dataSource : dataSources)
                email.attach(dataSource, dataSource.getName(), dataSource.getName());
        }

        email.setCharset(headers.getCharset());
        email.setHtmlMsg(htmlBody);

        String msgId = email.send();

        return true;
    } catch (EmailException e) {
        // FIXME Handle gracefully
        throw new RuntimeException(e);
    }
}

From source file:org.chenillekit.mail.services.impl.MailServiceImpl.java

/**
 * send a plain text message.//w w w.j a v a  2  s. c om
 *
 * @param headers    the mail headers
 * @param body      the mail body (text based)
 * @param dataSources array of data sources to attach at this mail
 *
 * @return true if mail successfull send
 */
public boolean sendPlainTextMail(MailMessageHeaders headers, String body, DataSource... dataSources) {
    try {
        Email email = new SimpleEmail();

        if (dataSources != null && dataSources.length > 0) {
            MultiPartEmail multiPart = new MultiPartEmail();

            for (DataSource dataSource : dataSources)
                multiPart.attach(dataSource, dataSource.getName(), dataSource.getName());

            email = multiPart;
        }

        setEmailStandardData(email);

        setMailMessageHeaders(email, headers);

        email.setCharset(headers.getCharset());
        try {
            email.setMsg(new String(body.getBytes(), headers.getCharset()));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        String msgId = email.send();

        return true;
    } catch (EmailException e) {
        // FIXME Handle gracefully
        throw new RuntimeException(e);
    }
}

From source file:org.igov.io.mail.Mail.java

public Mail _Attach(URL oURL, String sName) {
    try {//  www.jav  a2 s.c  o m
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();//javax.activation
        oMimeBodyPart.setHeader("Content-Type", "multipart/mixed");
        DataSource oDataSource = new URLDataSource(oURL);
        oMimeBodyPart.setDataHandler(new DataHandler(oDataSource));
        //oPart.setFileName(MimeUtility.encodeText(source.getName()));
        oMimeBodyPart.setFileName(
                MimeUtility.encodeText(sName == null || "".equals(sName) ? oDataSource.getName() : sName));
        oMultiparts.addBodyPart(oMimeBodyPart);
        LOG.info("(sName={})", sName);
    } catch (Exception oException) {
        LOG.error("FAIL: {} (sName={})", oException.getMessage(), sName);
        LOG.trace("FAIL:", oException);
    }
    return this;
}

From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java

protected void addAttachments(MailTemplate template, WorkItem workItem, Multipart multipart,
        JCRSessionWrapper session) throws Exception {
    for (AttachmentTemplate attachmentTemplate : template.getAttachmentTemplates()) {
        BodyPart attachmentPart = new MimeBodyPart();

        // resolve description
        String description = attachmentTemplate.getDescription();
        if (description != null) {
            attachmentPart.setDescription(evaluateExpression(workItem, description, session));
        }/*from   www.  j av  a 2 s  .c  o m*/

        // obtain interface to data
        DataHandler dataHandler = createDataHandler(attachmentTemplate, workItem, session);
        attachmentPart.setDataHandler(dataHandler);

        // resolve file name
        String name = attachmentTemplate.getName();
        if (name != null) {
            attachmentPart.setFileName(evaluateExpression(workItem, name, session));
        } else {
            // fall back on data source
            DataSource dataSource = dataHandler.getDataSource();
            if (dataSource instanceof URLDataSource) {
                name = extractResourceName(((URLDataSource) dataSource).getURL());
            } else {
                name = dataSource.getName();
            }
            if (name != null) {
                attachmentPart.setFileName(name);
            }
        }

        multipart.addBodyPart(attachmentPart);
    }
}

From source file:org.mule.ibeans.flickr.FlickrSignatureFactory.java

public Object create(String paramName, boolean optional, InvocationContext invocationContext) {
    String secretKey = (String) invocationContext.getIBeanConfig().getPropertyParams().get("secret_key");
    if (secretKey == null) {
        throw new IllegalArgumentException(
                "A Flickr secret key must be set using one of the init methods on this iBeans");
    }//from w  w  w  . j  ava2 s  . com
    String sig;

    StringBuffer buf = new StringBuffer();
    buf.append(secretKey);

    try {
        //Need to find a cleaner way of doing this for users
        if ("GET".equals(invocationContext.getIBeanConfig().getPropertyParams().get("http.method"))
                || invocationContext.isTemplateMethod()) {
            Map<String, String> params;
            if (invocationContext.isTemplateMethod()) {
                params = invocationContext.getTemplateSpecificUriParams();
            } else {
                params = invocationContext.getCallSpecificUriParams();
            }
            for (Map.Entry<String, String> entry : params.entrySet()) {
                //Always delete the param for this factory. Also photo should be removed
                if (entry.getKey().equals(paramName) || entry.getKey().equals("photo")) {
                    continue;
                } else {
                    buf.append(entry.getKey()).append(entry.getValue());
                }
            }
        } else {
            for (DataSource ds : invocationContext.getIBeanConfig().getAttachments()) {
                if (ds.getName().equals("photo") || ds.getName().equals("api_sig")) {
                    continue;
                }
                buf.append(ds.getName()).append(IOUtils.toCharArray(ds.getInputStream()));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    sig = buf.toString();

    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] bytes = md5.digest(buf.toString().getBytes("UTF-8"));
        sig = StringUtils.toHexString(bytes);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sig;
}

From source file:org.paxle.core.doc.impl.jaxb.JaxbFileAdapter.java

/**
 * Converts the {@link DataHandler} into a {@link File}.
 * The file is created via the {@link ITempFileManager}.
 *///  ww w. j av  a  2 s. co m
@Override
public File unmarshal(DataHandler dataHandler) throws Exception {
    if (dataHandler == null)
        return null;

    final DataSource dataSource = dataHandler.getDataSource();
    if (dataSource != null) {
        String cid = null;

        // avoid deserializing a file twice
        for (Entry<String, DataHandler> attachment : attachments.entrySet()) {
            if (attachment.getValue().equals(dataHandler)) {
                cid = attachment.getKey();
                break;
            }
        }

        if (cid != null && this.cidFileMap.containsKey(cid)) {
            return this.cidFileMap.get(cid);
        }

        File tempFile = null;
        InputStream input = null;
        OutputStream output = null;

        try {
            // getting the input stream
            input = dataSource.getInputStream();

            // getting the output stream
            tempFile = this.tempFileManager.createTempFile();
            output = new BufferedOutputStream(new FileOutputStream(tempFile));

            // copy data
            long byteCount = IOUtils.copy(input, output);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug(String.format("%d bytes copied from the data-source into the temp-file '%s'.",
                        Long.valueOf(byteCount), tempFile.getName()));
            }

            if (cid != null) {
                this.cidFileMap.put(cid, tempFile);
            }
            return tempFile;
        } catch (IOException e) {
            this.logger.error(String.format("Unexpected '%s' while loading datasource '%s' (CID=%s).",
                    e.getClass().getName(), dataSource.getName(), cid), e);

            // delete the temp file on errors
            if (tempFile != null && this.tempFileManager.isKnown(tempFile)) {
                this.tempFileManager.releaseTempFile(tempFile);
            }

            // re-throw exception
            throw e;
        } finally {
            // closing streams
            if (input != null)
                input.close();
            if (output != null)
                output.close();
        }
    }
    return null;
}

From source file:org.pentaho.platform.plugin.action.builtin.EmailComponent.java

@Override
public boolean executeAction() {
    EmailAction emailAction = (EmailAction) getActionDefinition();

    String messagePlain = emailAction.getMessagePlain().getStringValue();
    String messageHtml = emailAction.getMessageHtml().getStringValue();
    String subject = emailAction.getSubject().getStringValue();
    String to = emailAction.getTo().getStringValue();
    String cc = emailAction.getCc().getStringValue();
    String bcc = emailAction.getBcc().getStringValue();
    String from = emailAction.getFrom().getStringValue(defaultFrom);
    if (from.trim().length() == 0) {
        from = defaultFrom;/*from  w  w w .  j  a  v  a2s.  com*/
    }

    /*
     * if( context.getInputNames().contains( "attach" ) ) { //$NON-NLS-1$ Object attachParameter =
     * context.getInputParameter( "attach" ).getValue(); //$NON-NLS-1$ // We have a list of attachments, each element of
     * the list is the name of the parameter containing the attachment // Use the parameter filename portion as the
     * attachment name. if ( attachParameter instanceof String ) { String attachName = context.getInputParameter(
     * "attach-name" ).getStringValue(); //$NON-NLS-1$ AttachStruct attachData = getAttachData( context,
     * (String)attachParameter, attachName ); if ( attachData != null ) { attachments.add( attachData ); } } else if (
     * attachParameter instanceof List ) { for ( int i = 0; i < ((List)attachParameter).size(); ++i ) { AttachStruct
     * attachData = getAttachData( context, ((List)attachParameter).get( i ).toString(), null ); if ( attachData != null
     * ) { attachments.add( attachData ); } } } else if ( attachParameter instanceof Map ) { for ( Iterator it =
     * ((Map)attachParameter).entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next();
     * AttachStruct attachData = getAttachData( context, (String)entry.getValue(), (String)entry.getKey() ); if (
     * attachData != null ) { attachments.add( attachData ); } } } }
     * 
     * int maxSize = Integer.MAX_VALUE; try { maxSize = new Integer( props.getProperty( "mail.max.attach.size" )
     * ).intValue(); } catch( Throwable t ) { //ignore if not set to a valid value }
     * 
     * if ( totalAttachLength > maxSize ) { // Sort them in order TreeMap tm = new TreeMap(); for( int idx=0;
     * idx<attachments.size(); idx++ ) { // tm.put( new Integer( )) } }
     */

    if (ComponentBase.debug) {
        debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml)); //$NON-NLS-1$
    }

    if ((to == null) || (to.trim().length() == 0)) {

        // Get the output stream that the feedback is going into
        OutputStream feedbackStream = getFeedbackOutputStream();
        if (feedbackStream != null) {
            createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), //$NON-NLS-1$//$NON-NLS-2$
                    "", "", true); //$NON-NLS-1$ //$NON-NLS-2$
            setFeedbackMimeType("text/html"); //$NON-NLS-1$
            return true;
        } else {
            return false;
        }
    }
    if (subject == null) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName())); //$NON-NLS-1$
        return false;
    }
    if ((messagePlain == null) && (messageHtml == null)) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName())); //$NON-NLS-1$
        return false;
    }

    if (getRuntimeContext().isPromptPending()) {
        return true;
    }

    try {
        Properties props = new Properties();
        final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService",
                PentahoSessionHolder.getSession());
        props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
        props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
        props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
        props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
        props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
        props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
        props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
        props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
        String fromName = service.getEmailConfig().getFromName();
        if (StringUtils.isEmpty(fromName)) {
            fromName = Messages.getInstance().getString("schedulerEmailFromName");
        }
        props.put("mail.from.name", fromName);
        props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));

        Session session;
        if (service.getEmailConfig().isAuthenticate()) {
            props.put("mail.userid", service.getEmailConfig().getUserId());
            props.put("mail.password", service.getEmailConfig().getPassword());
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // debugging is on if either component (xaction) or email config debug is on
        if (service.getEmailConfig().isDebug() || ComponentBase.debug) {
            session.setDebug(true);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED")); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        EmailAttachment[] emailAttachments = emailAction.getAttachments();
        if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
            msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
        } else if (emailAttachments.length == 0) {
            if (messagePlain != null) {
                msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$          
            }
            if (messageHtml != null) {
                msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            }
        } else {
            // need to create a multi-part message...
            // create the Multipart and add its parts to it
            Multipart multipart = new MimeMultipart();
            // create and fill the first message part
            if (messageHtml != null) {
                // create and fill the first message part
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(htmlBodyPart);
            }

            if (messagePlain != null) {
                MimeBodyPart textBodyPart = new MimeBodyPart();
                textBodyPart.setContent(messagePlain,
                        "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(textBodyPart);
            }

            for (EmailAttachment element : emailAttachments) {
                IPentahoStreamSource source = element.getContent();
                if (source == null) {
                    error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED")); //$NON-NLS-1$
                    return false;
                }
                DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
                String attachmentName = element.getName();
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName)); //$NON-NLS-1$
                }

                // create the second message part
                MimeBodyPart attachmentBodyPart = new MimeBodyPart();

                // attach the file to the message
                attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                attachmentBodyPart.setFileName(attachmentName);
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", //$NON-NLS-1$
                            dataSource.getName()));
                }
                multipart.addBodyPart(attachmentBodyPart);
            }

            // add the Multipart to the message
            msg.setContent(multipart);
        }

        msg.setHeader("X-Mailer", EmailComponent.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        if (ComponentBase.debug) {
            debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS")); //$NON-NLS-1$
        }
        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
        /*
         * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof
         * MessagingException) { sfe = (MessagingException) ne;
         * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe);
         * //$NON-NLS-1$ }
         */

    } catch (AuthenticationFailedException e) {
        error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e); //$NON-NLS-1$
    } catch (Throwable e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
    }
    return false;
}

From source file:org.simplejavamail.internal.util.MimeMessageParser.java

/**
 * Determines the name of the data source if it is not already set.
 *
 * @param part       the mail part/* w w w  .j a  v  a  2  s. c o  m*/
 * @param dataSource the data source
 * @return the name of the data source or {@code null} if no name can be determined
 * @throws MessagingException           accessing the part failed
 * @throws UnsupportedEncodingException decoding the text failed
 */
private static String getDataSourceName(final Part part, final DataSource dataSource)
        throws MessagingException, UnsupportedEncodingException {
    String result = dataSource.getName();

    if (result == null || result.length() == 0) {
        result = part.getFileName();
    }

    if (result != null && result.length() > 0) {
        result = MimeUtility.decodeText(result);
    } else {
        result = null;
    }

    return result;
}

From source file:org.unitime.commons.Email.java

public void addAttachement(DataSource source) throws MessagingException {
    BodyPart attachement = new MimeBodyPart();
    attachement.setDataHandler(new DataHandler(source));
    attachement.setFileName(source.getName());
    attachement.setHeader("Content-ID", source.getName());
    iBody.addBodyPart(attachement);/*from w  ww .j a  v a 2  s .  co  m*/
}