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:com.youxifan.utils.EMail.java

/**
 *   Set the message content/*from  w  w w  .  ja va2 s  . c  o  m*/
 *    @throws MessagingException
 *    @throws IOException
 */
private void setContent() throws MessagingException, IOException {
    //   Local Character Set
    String charSetName;
    if (m_encoding == null) {
        charSetName = System.getProperty("file.encoding"); //   Cp1252
        if (charSetName == null || charSetName.length() == 0)
            charSetName = "UTF-8"; // WebEnv.ENCODING - alternative iso-8859-1
    } else {
        charSetName = m_encoding;
    }
    m_msg.setSubject(getSubject(), charSetName);

    //   Simple Message
    if (m_attachments == null || m_attachments.size() == 0) {
        if (m_messageHTML == null || m_messageHTML.length() == 0)
            m_msg.setText(getMessageCRLF(), charSetName);
        else
            m_msg.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html")));
        //
        log.info("(simple) " + getSubject());
    } else //   Multi part message   ***************************************
    {
        //   First Part - Message
        MimeBodyPart mbp_1 = new MimeBodyPart();
        mbp_1.setText("");
        if (m_messageHTML == null || m_messageHTML.length() == 0)
            mbp_1.setText(getMessageCRLF(), charSetName);
        else
            mbp_1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html")));

        // Create Multipart and its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp_1);
        log.info("(multi) " + getSubject() + " - " + mbp_1);

        //   for all attachments
        for (int i = 0; i < m_attachments.size(); i++) {
            Object attachment = m_attachments.get(i);
            DataSource ds = null;
            if (attachment instanceof File) {
                File file = (File) attachment;
                if (file.exists())
                    ds = new FileDataSource(file);
                else {
                    log.warn("File does not exist: " + file);
                    continue;
                }
            } else if (attachment instanceof URL) {
                URL url = (URL) attachment;
                ds = new URLDataSource(url);
            } else if (attachment instanceof DataSource)
                ds = (DataSource) attachment;
            else {
                log.warn("Attachement type unknown: " + attachment);
                continue;
            }
            //   Attachment Part
            MimeBodyPart mbp_2 = new MimeBodyPart();
            mbp_2.setDataHandler(new DataHandler(ds));
            mbp_2.setFileName(ds.getName());
            log.info("Added Attachment " + ds.getName() + " - " + mbp_2);
            mp.addBodyPart(mbp_2);
        }

        //   Add to Message
        m_msg.setContent(mp);
    } //   multi=part
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

private void writeWholeData(DataSource data, HttpServletRequest request, HttpServletResponse response,
        String characterEncoding, String dbHint)
        throws IOException, HttpErrorException, UnsupportedEncodingException {

    Reader reader = null;//from   ww  w  .  j  a va 2  s  .  c  om
    InputStream in = data.getInputStream();
    if (in == null) {
        throw new HttpErrorException(404, "File not found: " + data.getName(), dbHint);
    }

    try {
        if (!isBinary(request, response)) {
            // this is a textual reponse
            if (characterEncoding != null && !characterEncoding.equals(response.getCharacterEncoding())) {
                reader = new InputStreamReader(in, characterEncoding);
                WGUtils.inToOut(reader, response.getWriter(), 2048);
            } else {
                WGUtils.inToOut(in, response.getOutputStream(), 2048);
            }
        } else {
            WGUtils.inToOut(in, response.getOutputStream(), 2048);
        }
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

private void writeRangesData(DataSource data, List<AcceptRange> ranges, HttpServletResponse response,
        String dbHint, long size) throws IOException, HttpErrorException, UnsupportedEncodingException {

    ServletOutputStream out = response.getOutputStream();
    for (AcceptRange range : ranges) {
        InputStream in = data.getInputStream();
        if (in == null) {
            throw new HttpErrorException(404, "File not found: " + data.getName(), dbHint);
        }// ww  w  .ja  v  a2  s  . c  o  m

        if (ranges.size() != 1) {
            out.println();
            out.println("--" + BYTERANGE_BOUNDARY);
            out.println("Content-Type: " + data.getContentType());
            out.println("Content-Range: bytes " + range.from + "-" + range.to + "/" + size);
            out.println();
        }

        if (range.from > 0) {
            in.skip(range.from);
        }

        try {
            WGUtils.inToOutLimited(in, out, (new Long(range.to - range.from + 1)).intValue(), 2048);
            out.flush();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }

    if (ranges.size() != 1) {
        out.println();
        out.print("--" + BYTERANGE_BOUNDARY + "--");
        out.flush();
    }

}

From source file:de.innovationgate.webgate.api.WGDatabase.java

/**
 * Tool method for annotating a metadata object based on the given file, using the default and optionally given additional annotators
 * @param ds The file data/*w ww.  j  ava2 s  .  c  o  m*/
 * @param meta The metadata object to annotate
 * @param additionalAnnotators Additional annotators to run.
 * @throws WGAPIException
 */
protected void annotateMetadata(DataSource ds, WGFileMetaData meta, List<WGFileAnnotator> additionalAnnotators)
        throws WGAPIException {
    List<WGFileAnnotator> annotators = new ArrayList<WGFileAnnotator>(getFileAnnotators());
    if (additionalAnnotators != null) {
        annotators.addAll(additionalAnnotators);
    }

    for (WGFileAnnotator annotator : annotators) {
        try {
            annotator.annotateFile(ds, meta);
        } catch (Throwable e) {
            WGFactory.getLogger().error("Exception running annotator " + annotator.getClass().getName()
                    + " on attaching file '" + ds.getName() + "'", e);
        }
    }

}

From source file:nl.clockwork.mule.ebms.util.EbMSMessageUtils.java

public static EbMSMessageContent EbMSMessageToEbMSMessageContent(EbMSMessage message) throws IOException {
    List<EbMSAttachment> attachments = new ArrayList<EbMSAttachment>();
    for (DataSource attachment : message.getAttachments())
        attachments.add(new EbMSAttachment(attachment.getName(), attachment.getContentType(),
                IOUtils.toByteArray(attachment.getInputStream())));

    return new EbMSMessageContent(new EbMSMessageContext(message.getMessageHeader()), attachments);
}

From source file:org.activiti5.engine.impl.bpmn.behavior.MailActivityBehavior.java

protected void attach(Email email, List<File> files, List<DataSource> dataSources) throws EmailException {
    if (!(email instanceof MultiPartEmail && attachmentsExist(files, dataSources))) {
        return;/*from   ww w.j a va 2s  .  c  om*/
    }
    MultiPartEmail mpEmail = (MultiPartEmail) email;
    for (File file : files) {
        mpEmail.attach(file);
    }
    for (DataSource ds : dataSources) {
        if (ds != null) {
            mpEmail.attach(ds, ds.getName(), null);
        }
    }
}

From source file:org.adempiere.webui.apps.FeedbackRequestWindow.java

protected void saveRequest() throws IOException {
    Trx trx = Trx.get(Trx.createTrxName("SaveNewRequest"), true);
    try {/* ww w .j  a v  a 2 s.  c  om*/
        trx.start();
        MRequest request = createMRequest(trx);

        boolean success = request.save();
        if (success) {
            MAttachment attachment = null;
            for (DataSource ds : attachments) {
                if (attachment == null) {
                    attachment = new MAttachment(Env.getCtx(), 0, request.get_TrxName());
                    attachment.setAD_Table_ID(request.get_Table_ID());
                    attachment.setRecord_ID(request.get_ID());
                }

                attachment.addEntry(ds.getName(), IOUtils.toByteArray(ds.getInputStream()));
            }
            if (attachment != null)
                success = attachment.save();

            if (success)
                success = trx.commit();

        }

        if (success) {
            FDialog.info(0, null, Msg.getMsg(Env.getCtx(), "Saved"));
        } else {
            trx.rollback();
            FDialog.error(0, this, Msg.getMsg(Env.getCtx(), "SaveError"));
        }
    } finally {
        trx.close();
    }
}

From source file:org.apache.hupa.server.utils.MessageUtils.java

/**
 * Convert a FileItem to a BodyPart/*from   w ww  .j  a va 2  s .co m*/
 *
 * @param item
 * @return message body part
 * @throws MessagingException
 */
public static BodyPart fileitemToBodypart(FileItem item) throws MessagingException {
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileItemDataStore(item);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(source.getName());
    return messageBodyPart;
}

From source file:org.apache.isis.core.runtime.services.email.EmailServiceDefault.java

@Override
public boolean send(final List<String> toList, final List<String> ccList, final List<String> bccList,
        final String subject, final String body, final DataSource... attachments) {

    try {//w  w w  .  j  a  va  2s  . c om
        final ImageHtmlEmail email = new ImageHtmlEmail();

        final String senderEmailAddress = getSenderEmailAddress();
        final String senderEmailPassword = getSenderEmailPassword();
        final String senderEmailHostName = getSenderEmailHostName();
        final Integer senderEmailPort = getSenderEmailPort();
        final Boolean senderEmailTlsEnabled = getSenderEmailTlsEnabled();
        final int socketTimeout = getSocketTimeout();
        final int socketConnectionTimeout = getSocketConnectionTimeout();

        email.setAuthenticator(new DefaultAuthenticator(senderEmailAddress, senderEmailPassword));
        email.setHostName(senderEmailHostName);
        email.setSmtpPort(senderEmailPort);
        email.setStartTLSEnabled(senderEmailTlsEnabled);
        email.setDataSourceResolver(new DataSourceClassPathResolver("/", true));

        email.setSocketTimeout(socketTimeout);
        email.setSocketConnectionTimeout(socketConnectionTimeout);

        final Properties properties = email.getMailSession().getProperties();

        properties.put("mail.smtps.auth", "true");
        properties.put("mail.debug", "true");
        properties.put("mail.smtps.port", "" + senderEmailPort);
        properties.put("mail.smtps.socketFactory.port", "" + senderEmailPort);
        properties.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtps.socketFactory.fallback", "false");
        properties.put("mail.smtp.starttls.enable", "" + senderEmailTlsEnabled);

        email.setFrom(senderEmailAddress);

        email.setSubject(subject);
        email.setHtmlMsg(body);

        if (attachments != null && attachments.length > 0) {
            for (DataSource attachment : attachments) {
                email.attach(attachment, attachment.getName(), "");
            }
        }

        final String overrideTo = getEmailOverrideTo();
        final String overrideCc = getEmailOverrideCc();
        final String overrideBcc = getEmailOverrideBcc();

        final String[] toListElseOverride = actually(toList, overrideTo);
        if (notEmpty(toListElseOverride)) {
            email.addTo(toListElseOverride);
        }
        final String[] ccListElseOverride = actually(ccList, overrideCc);
        if (notEmpty(ccListElseOverride)) {
            email.addCc(ccListElseOverride);
        }
        final String[] bccListElseOverride = actually(bccList, overrideBcc);
        if (notEmpty(bccListElseOverride)) {
            email.addBcc(bccListElseOverride);
        }

        email.send();

    } catch (EmailException ex) {
        LOG.error("An error occurred while trying to send an email", ex);
        final Boolean throwExceptionOnFail = isThrowExceptionOnFail();
        if (throwExceptionOnFail) {
            throw new EmailServiceException(ex);
        }
        return false;
    }

    return true;
}

From source file:org.apache.nifi.processors.email.ExtractEmailAttachments.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final ComponentLog logger = getLogger();
    final FlowFile originalFlowFile = session.get();
    if (originalFlowFile == null) {
        return;//from   w w w .j  av  a  2  s. co  m
    }
    final List<FlowFile> attachmentsList = new ArrayList<>();
    final List<FlowFile> invalidFlowFilesList = new ArrayList<>();
    final List<FlowFile> originalFlowFilesList = new ArrayList<>();

    session.read(originalFlowFile, new InputStreamCallback() {
        @Override
        public void process(final InputStream rawIn) throws IOException {
            try (final InputStream in = new BufferedInputStream(rawIn)) {
                Properties props = new Properties();
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage originalMessage = new MimeMessage(mailSession, in);
                MimeMessageParser parser = new MimeMessageParser(originalMessage).parse();
                // RFC-2822 determines that a message must have a "From:" header
                // if a message lacks the field, it is flagged as invalid
                Address[] from = originalMessage.getFrom();
                Date sentDate = originalMessage.getSentDate();
                if (from == null || sentDate == null) {
                    // Throws MessageException due to lack of minimum required headers
                    throw new MessagingException("Message failed RFC2822 validation");
                }
                originalFlowFilesList.add(originalFlowFile);
                if (parser.hasAttachments()) {
                    final String originalFlowFileName = originalFlowFile
                            .getAttribute(CoreAttributes.FILENAME.key());
                    try {
                        for (final DataSource data : parser.getAttachmentList()) {
                            FlowFile split = session.create(originalFlowFile);
                            final Map<String, String> attributes = new HashMap<>();
                            if (StringUtils.isNotBlank(data.getName())) {
                                attributes.put(CoreAttributes.FILENAME.key(), data.getName());
                            }
                            if (StringUtils.isNotBlank(data.getContentType())) {
                                attributes.put(CoreAttributes.MIME_TYPE.key(), data.getContentType());
                            }
                            String parentUuid = originalFlowFile.getAttribute(CoreAttributes.UUID.key());
                            attributes.put(ATTACHMENT_ORIGINAL_UUID, parentUuid);
                            attributes.put(ATTACHMENT_ORIGINAL_FILENAME, originalFlowFileName);
                            split = session.append(split, new OutputStreamCallback() {
                                @Override
                                public void process(OutputStream out) throws IOException {
                                    IOUtils.copy(data.getInputStream(), out);
                                }
                            });
                            split = session.putAllAttributes(split, attributes);
                            attachmentsList.add(split);
                        }
                    } catch (FlowFileHandlingException e) {
                        // Something went wrong
                        // Removing splits that may have been created
                        session.remove(attachmentsList);
                        // Removing the original flow from its list
                        originalFlowFilesList.remove(originalFlowFile);
                        logger.error(
                                "Flowfile {} triggered error {} while processing message removing generated FlowFiles from sessions",
                                new Object[] { originalFlowFile, e });
                        invalidFlowFilesList.add(originalFlowFile);
                    }
                }
            } catch (Exception e) {
                // Another error hit...
                // Removing the original flow from its list
                originalFlowFilesList.remove(originalFlowFile);
                logger.error("Could not parse the flowfile {} as an email, treating as failure",
                        new Object[] { originalFlowFile, e });
                // Message is invalid or triggered an error during parsing
                invalidFlowFilesList.add(originalFlowFile);
            }
        }
    });

    session.transfer(attachmentsList, REL_ATTACHMENTS);

    // As per above code, originalFlowfile may be routed to invalid or
    // original depending on RFC2822 compliance.
    session.transfer(invalidFlowFilesList, REL_FAILURE);
    session.transfer(originalFlowFilesList, REL_ORIGINAL);

    if (attachmentsList.size() > 10) {
        logger.info("Split {} into {} files", new Object[] { originalFlowFile, attachmentsList.size() });
    } else if (attachmentsList.size() > 1) {
        logger.info("Split {} into {} files: {}",
                new Object[] { originalFlowFile, attachmentsList.size(), attachmentsList });
    }
}