Example usage for javax.mail.util ByteArrayDataSource setName

List of usage examples for javax.mail.util ByteArrayDataSource setName

Introduction

In this page you can find the example usage for javax.mail.util ByteArrayDataSource setName.

Prototype

public void setName(String name) 

Source Link

Document

Set the name of the data.

Usage

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

public static EbMSMessage ebMSMessageContentToEbMSMessage(CollaborationProtocolAgreement cpa,
        EbMSMessageContent content, String hostname) throws DatatypeConfigurationException {
    MessageHeader messageHeader = createMessageHeader(cpa, content.getContext(), hostname);

    AckRequested ackRequested = createAckRequested(cpa, content.getContext());

    Manifest manifest = createManifest();
    for (int i = 0; i < content.getAttachments().size(); i++)
        manifest.getReference().add(createReference(i + 1));

    List<DataSource> attachments = new ArrayList<DataSource>();
    for (EbMSAttachment attachment : content.getAttachments()) {
        ByteArrayDataSource ds = new ByteArrayDataSource(attachment.getContent(), attachment.getContentType());
        ds.setName(attachment.getName());
        attachments.add(ds);/*  w w w.jav  a2 s .c  o  m*/
    }

    return new EbMSMessage(messageHeader, ackRequested, manifest, attachments);
}

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

/**
 * Parses the MimePart to create a DataSource.
 *
 * @param part   the current part to be processed
 * @return the DataSource/*from w  w  w.  j ava  2 s . c o  m*/
 * @throws MessagingException creating the DataSource failed
 * @throws IOException        creating the DataSource failed
 */
private static DataSource createDataSource(final MimePart part) throws MessagingException, IOException {
    final DataHandler dataHandler = part.getDataHandler();
    final DataSource dataSource = dataHandler.getDataSource();
    final String contentType = getBaseMimeType(dataSource.getContentType());
    final byte[] content = MimeMessageParser.getContent(dataSource.getInputStream());
    final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType);
    final String dataSourceName = getDataSourceName(part, dataSource);

    result.setName(dataSourceName);
    return result;
}

From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java

/**
 * Create a MimeBodyPart./* w  ww  .j a  va2 s .  c  o m*/
 * 
 * @param item
 * @return
 * @throws MessagingException
 * @throws IOException
 */
private DataSource createDataSource(FileItemStream item) throws MessagingException, IOException {

    final String fileName = FilenameUtils.getName(item.getName());
    final String contentType = item.getContentType();
    final InputStream stream = item.openStream();

    ByteArrayDataSource source = new ByteArrayDataSource(stream, contentType);
    source.setName(fileName);

    return source;
}

From source file:com.nokia.helium.core.EmailDataSender.java

/**
 * Send xml data/*from w  ww.  j a  va2s.  co  m*/
 * 
 * @param String purpose of this email
 * @param String file to send
 * @param String mime type
 * @param String subject of email
 * @param String header of mail
 * @param boolean compress data if true
 */
public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header,
        boolean compressData) throws EmailSendException {
    try {
        log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType);
        if (fileToSend != null && fileToSend.exists()) {
            InternetAddress[] toAddresses = getToAddressList();
            Properties props = new Properties();
            if (smtpServerAddress != null) {
                log.debug("sendData:smtp address: " + smtpServerAddress);
                props.setProperty("mail.smtp.host", smtpServerAddress);
            }
            Session mailSession = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject == null ? "" : subject);
            MimeMultipart multipart = new MimeMultipart("related");
            BodyPart messageBodyPart = new MimeBodyPart();
            ByteArrayDataSource dataSrc = null;
            String fileName = fileToSend.getName();
            if (compressData) {
                log.debug("Sending compressed data");
                dataSrc = compressFile(fileToSend);
                dataSrc.setName(fileName + ".gz");
                messageBodyPart.setFileName(fileName + ".gz");
            } else {
                log.debug("Sending uncompressed data:");
                dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType);

                message.setContent(FileUtils.readFileToString(fileToSend), "text/html");
                multipart = null;
            }
            String headerToSend = null;
            if (header == null) {
                headerToSend = "";
            }
            messageBodyPart.setHeader("helium-bld-data", headerToSend);
            messageBodyPart.setDataHandler(new DataHandler(dataSrc));

            if (multipart != null) {
                multipart.addBodyPart(messageBodyPart); // add to the
                // multipart
                message.setContent(multipart);
            }
            try {
                message.setFrom(getFromAddress());
            } catch (AddressException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            } catch (LDAPException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            }
            message.addRecipients(Message.RecipientType.TO, toAddresses);
            log.info("Sending email alert: " + subject);
            Transport.send(message);
        }
    } catch (MessagingException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        throw new EmailSendException(fullErrorMessage, e);
    } catch (IOException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        // We are Ignoring the errors as no need to fail the build.
        throw new EmailSendException(fullErrorMessage, e);
    }
}

From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java

private List<DataSource> getAttachments(long messageId) throws DAOException {
    try {//from  ww  w. j a va  2  s  .c o m
        return simpleJdbcTemplate.query(
                "select name, content_type, content" + " from ebms_attachment" + " where ebms_message_id = ?",
                new ParameterizedRowMapper<DataSource>() {
                    @Override
                    public DataSource mapRow(ResultSet rs, int rowNum) throws SQLException {
                        ByteArrayDataSource result = new ByteArrayDataSource(rs.getBytes("content"),
                                rs.getString("content_type"));
                        result.setName(rs.getString("name"));
                        return result;
                    }
                }, messageId);
    } catch (DataAccessException e) {
        throw new DAOException(e);
    }
}

From source file:com.cubusmail.mail.MessageHandler.java

/**
 * @param msg/*from  w  w w  . j  a  v  a 2s .co m*/
 * @throws MessagingException
 * @throws IOException
 */
public void createForwardMessage(Message msg) throws MessagingException, IOException {

    init();
    setSubject("Fwd: " + msg.getSubject());
    setHtmlMessage(MessageUtils.isHtmlMessage(msg));
    List<MimePart> attachments = MessageUtils.attachmentsFromPart(msg);
    if (attachments != null) {
        for (MimePart part : attachments) {
            DataSource source = part.getDataHandler().getDataSource();

            ByteArrayDataSource newSource = new ByteArrayDataSource(source.getInputStream(),
                    source.getContentType());

            if (StringUtils.isEmpty(source.getName())) {
                newSource.setName(this.applicationContext.getMessage("message.unknown.attachment", null,
                        SessionManager.get().getLocale()));
            } else {
                newSource.setName(source.getName());
            }

            addComposeAttachment(newSource);
        }
    }
    Preferences prefs = SessionManager.get().getPreferences();
    MessageTextUtil.messageTextFromPart(msg, this, true, MessageTextMode.REPLY, prefs, 0);
}

From source file:com.collabnet.ccf.pi.cee.pt.v50.ProjectTrackerWriter.java

private GenericArtifact[] createProjectTrackerAttachment(GenericArtifact ga) {
    String targetArtifactId = ga.getDepParentTargetArtifactId();
    String artifactId = ptHelper.getArtifactIdFromFullyQualifiedArtifactId(targetArtifactId);
    TrackerWebServicesClient twsclient = null;
    GenericArtifact parentArtifact = null;
    byte[] data = null;
    String attachmentMimeType = null;
    String attachmentName = null;
    DataSource dataSource = null;
    File attachmentFile = null;//www .  j a va  2s.c  om
    String repositoryId = ga.getTargetRepositoryId();
    try {
        twsclient = this.getConnection(ga);
        ClientArtifactListXMLHelper currentArtifactHelper = twsclient.getArtifactById(artifactId);
        ClientArtifact currentArtifact = currentArtifactHelper.getAllArtifacts().get(0);
        String retrievedArtifactId = currentArtifact.getArtifactID();
        if (!artifactId.equals(retrievedArtifactId)) {
            log.warn("Artifact seems to have moved, old id: " + artifactId + ", new id: " + retrievedArtifactId
                    + ", so do not ship it ...");
            return new GenericArtifact[] { ga };
        }
        String retrievedProject = currentArtifact.getProject();
        if (retrievedProject != null) {
            String projectName = null;
            if (repositoryId != null) {
                String[] splitProjectName = repositoryId.split(":");
                if (splitProjectName != null) {
                    if (splitProjectName.length >= 1) {
                        projectName = splitProjectName[0];
                    } else {
                        throw new IllegalArgumentException("Repository id " + repositoryId + " is not valid."
                                + " Could not extract project name from repository id");
                    }
                }
            }
            if (projectName != null) {
                if (!retrievedProject.equals(projectName)) {
                    log.warn("PT Artifact with id " + artifactId + " has moved from project " + projectName
                            + " to artifact with id " + retrievedArtifactId + " in project " + retrievedProject
                            + ", so do not ship it ...");
                    return new GenericArtifact[] { ga };
                }
            }
        }

        String attachmentType = GenericArtifactHelper.getStringGAField(AttachmentMetaData.ATTACHMENT_TYPE, ga);
        String sourceAttachmentId = ga.getSourceArtifactId();
        String parentSourceArtifactId = ga.getDepParentSourceArtifactId();
        if (attachmentType.equals(AttachmentMetaData.AttachmentType.LINK.toString())) {
            String url = GenericArtifactHelper.getStringGAField(AttachmentMetaData.ATTACHMENT_SOURCE_URL, ga);
            url = "<html><body><a href=\"" + url + "\">" + url + "</a></body></html>";
            data = url.getBytes();
            attachmentMimeType = AttachmentMetaData.TEXT_HTML;
            attachmentName = "Link-attachment-" + parentSourceArtifactId + "-" + sourceAttachmentId + ".html";
            ByteArrayDataSource baDS = new ByteArrayDataSource(data, attachmentMimeType);
            baDS.setName(attachmentName);
            dataSource = baDS;
        } else {
            String attachmentDataFileName = GenericArtifactHelper
                    .getStringGAField(AttachmentMetaData.ATTACHMENT_DATA_FILE, ga);
            attachmentMimeType = GenericArtifactHelper.getStringGAField(AttachmentMetaData.ATTACHMENT_MIME_TYPE,
                    ga);
            attachmentName = GenericArtifactHelper.getStringGAField(AttachmentMetaData.ATTACHMENT_NAME, ga);
            if (StringUtils.isEmpty(attachmentDataFileName)) {
                data = ga.getRawAttachmentData();
                ByteArrayDataSource baDS = new ByteArrayDataSource(data, attachmentMimeType);
                baDS.setName(attachmentName);
                dataSource = baDS;
            } else {
                File attachmentDataFile = new File(attachmentDataFileName);
                String tempDir = System.getProperty("java.io.tmpdir");
                attachmentFile = new File(tempDir, attachmentName);
                if (attachmentDataFile.exists()) {
                    boolean renamingSuccessful = attachmentDataFile.renameTo(attachmentFile);
                    if (renamingSuccessful) {
                        dataSource = new FileDataSource(attachmentFile);
                    } else {
                        dataSource = new FileDataSource(attachmentDataFile);
                    }
                } else {
                    String message = "Attachment data file " + attachmentDataFileName + " does not exist.";
                    FileNotFoundException e = new FileNotFoundException(message);
                    log.error(message, e);
                    throw new CCFRuntimeException(message, e);
                }
            }
        }
        String attachmentDescription = null;
        attachmentDescription = GenericArtifactHelper
                .getStringGAField(AttachmentMetaData.ATTACHMENT_DESCRIPTION, ga);
        if (StringUtils.isEmpty(attachmentDescription)) {
            attachmentDescription = "Attachment added by Connector";
        }
        long attachmentId = -1;
        attachmentId = twsclient.postAttachment(artifactId, attachmentDescription, dataSource);
        currentArtifactHelper = twsclient.getArtifactById(artifactId);
        currentArtifact = currentArtifactHelper.getAllArtifacts().get(0);
        String modifiedOn = currentArtifact.getAttributeValue(ProjectTrackerReader.TRACKER_NAMESPACE,
                ProjectTrackerReader.MODIFIED_ON_FIELD);
        long modifiedOnMilliSeconds = Long.parseLong(modifiedOn);
        Date lastModifiedDate = new Date(modifiedOnMilliSeconds);
        ga.setTargetArtifactId(Long.toString(attachmentId));
        ga.setTargetArtifactLastModifiedDate(DateUtil.format(lastModifiedDate));
        ga.setTargetArtifactVersion(Long.toString(modifiedOnMilliSeconds));
        ga.setDepParentTargetRepositoryId(ga.getTargetRepositoryId());
        ga.setDepParentTargetRepositoryKind(ga.getTargetRepositoryKind());
        log.info("Attachment with id " + attachmentId + " is created for the PT artifact " + artifactId
                + " with the attachment " + sourceAttachmentId + " from artifact " + parentSourceArtifactId);
        parentArtifact = new GenericArtifact();
        // make sure that we do not update the synchronization status record
        // for replayed attachments
        parentArtifact.setTransactionId(ga.getTransactionId());
        parentArtifact.setArtifactType(GenericArtifact.ArtifactTypeValue.PLAINARTIFACT);
        parentArtifact.setArtifactAction(GenericArtifact.ArtifactActionValue.UPDATE);
        parentArtifact.setArtifactMode(GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY);
        parentArtifact.setConflictResolutionPriority(ga.getConflictResolutionPriority());
        parentArtifact.setSourceArtifactId(ga.getDepParentSourceArtifactId());
        parentArtifact.setSourceArtifactLastModifiedDate(ga.getSourceArtifactLastModifiedDate());
        parentArtifact.setSourceArtifactVersion(ga.getSourceArtifactVersion());
        parentArtifact.setSourceRepositoryId(ga.getSourceRepositoryId());
        parentArtifact.setSourceSystemId(ga.getSourceSystemId());
        parentArtifact.setSourceSystemKind(ga.getSourceSystemKind());
        parentArtifact.setSourceRepositoryKind(ga.getSourceRepositoryKind());
        parentArtifact.setSourceSystemTimezone(ga.getSourceSystemTimezone());

        parentArtifact.setTargetArtifactId(targetArtifactId);
        parentArtifact.setTargetArtifactLastModifiedDate(DateUtil.format(lastModifiedDate));
        parentArtifact.setTargetArtifactVersion(Long.toString(modifiedOnMilliSeconds));
        parentArtifact.setTargetRepositoryId(ga.getTargetRepositoryId());
        parentArtifact.setTargetRepositoryKind(ga.getTargetRepositoryKind());
        parentArtifact.setTargetSystemId(ga.getTargetSystemId());
        parentArtifact.setTargetSystemKind(ga.getTargetSystemKind());
        parentArtifact.setTargetSystemTimezone(ga.getTargetSystemTimezone());
    } catch (WSException e) {
        String message = "Exception while creating PT artifact attachment";
        log.error(message, e);
        throw new CCFRuntimeException(message, e);
    } catch (RemoteException e) {
        String message = "Exception while creating PT artifact attachment";
        log.error(message, e);
        throw new CCFRuntimeException(message, e);
    } catch (ServiceException e) {
        String message = "Exception while creating PT artifact attachment";
        log.error(message, e);
        throw new CCFRuntimeException(message, e);
    } catch (Exception e) {
        String message = "Exception while creating PT artifact attachment";
        log.error(message, e);
        throw new CCFRuntimeException(message, e);
    } finally {
        if (attachmentFile != null) {
            boolean fileDeleted = attachmentFile.delete();
            if (!fileDeleted) {
                log.warn("The temporary attachment file" + attachmentFile.getAbsolutePath()
                        + " could not be deleted");
            }
        }
        if (twsclient != null) {
            this.releaseConnection(twsclient);
        }
    }

    return new GenericArtifact[] { ga, parentArtifact };
}