Example usage for javax.activation FileDataSource FileDataSource

List of usage examples for javax.activation FileDataSource FileDataSource

Introduction

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

Prototype

public FileDataSource(String name) 

Source Link

Document

Creates a FileDataSource from the specified path name.

Usage

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Send a SOAP request via a MEPClient without attachments.
 * //  w  w w .  ja v  a  2  s .  c o  m
 * @deprecated Please use {@link #sendSOAPRequest(String, String, Map, Map, String, String, String)}
 *             instead.
 * @param endpoint The URL of the end point to send the request to.
 * @param soapRequestFileName Path to the SOAP request file
 * @param parametersMap A map containing key value pairs to be parameterized in the request.
 * @param attachmentMap A map containing content IDs and paths to files which needed to be added to the
 *        SOAP request as attachments.
 * @return The SOAP Envelope that is returned as a result of the request.
 * @throws XMLStreamException Thrown on failure to build OM Element from the file's contents.
 * @throws IOException Thrown on failure to send the request.
 */
@Deprecated
protected SOAPEnvelope sendSOAPRequest(String endpoint, String soapRequestFileName,
        Map<String, String> parametersMap, Map<String, String> attachmentMap)
        throws XMLStreamException, IOException {

    OMElement requestEnvelope = AXIOMUtil.stringToOM(loadRequestFromFile(soapRequestFileName, parametersMap));
    Map<String, DataHandler> dataHandlerMap = new HashMap<String, DataHandler>();
    for (String contentId : attachmentMap.keySet()) {
        dataHandlerMap.put(contentId, new DataHandler(
                new FileDataSource(new File(pathToRequestsDirectory + attachmentMap.get(contentId)))));
    }
    OperationClient mepClient = buildMEPClient(new EndpointReference(endpoint), requestEnvelope,
            dataHandlerMap);

    mepClient.execute(true);
    return mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE).getEnvelope();
}

From source file:com.nridge.core.app.mail.MailManager.java

/**
 * If the property "delivery_enabled" is <i>true</i>, then this method
 * will generate an email message that includes subject, message and
 * attachments to the recipient list.  You can use the convenience
 * methods <i>lookupFromAddress()</i>, <i>createRecipientList()</i>
 * and <i>createAttachmentList()</i> for parameter building assistance.
 *
 * @param aFromAddress Source email address.
 * @param aRecipientList List of recipient email addresses.
 * @param aSubject Subject of the email message.
 * @param aMessage Messsage./*from w w w. j  a  v  a 2s.c  o  m*/
 * @param anAttachmentFiles List of file attachments or <i>null</i> for none.
 *
 * @see <a href="https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm">JavaMail API Attachments</a>
 * @see <a href="https://stackoverflow.com/questions/6756162/how-do-i-send-mail-with-both-plain-text-as-well-as-html-text-so-that-each-mail-r">JavaMail API MIME Types</a>
 *
 * @throws IOException I/O related error condition.
 * @throws NSException Missing configuration properties.
 * @throws MessagingException Message subsystem error condition.
 */
public void sendMessage(String aFromAddress, ArrayList<String> aRecipientList, String aSubject, String aMessage,
        ArrayList<String> anAttachmentFiles)

        throws IOException, NSException, MessagingException {
    InternetAddress internetAddressFrom, internetAddressTo;
    Logger appLogger = mAppMgr.getLogger(this, "sendMessage");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (isCfgStringTrue("delivery_enabled")) {
        if ((StringUtils.isNotEmpty(aFromAddress)) && (aRecipientList.size() > 0)
                && (StringUtils.isNotEmpty(aSubject)) && (StringUtils.isNotEmpty(aMessage))) {
            initialize();

            Message mimeMessage = new MimeMessage(mMailSession);
            internetAddressFrom = new InternetAddress(aFromAddress);
            mimeMessage.addFrom(new InternetAddress[] { internetAddressFrom });
            for (String mailAddressTo : aRecipientList) {
                internetAddressTo = new InternetAddress(mailAddressTo);
                mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo);
            }
            mimeMessage.setSubject(aSubject);

            // The following logic create a multi-part message and adds the attachment to it.

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(aMessage);
            //                messageBodyPart.setContent(aMessage, "text/html");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            if ((anAttachmentFiles != null) && (anAttachmentFiles.size() > 0)) {
                for (String pathFileName : anAttachmentFiles) {
                    File attachmentFile = new File(pathFileName);
                    if (attachmentFile.exists()) {
                        messageBodyPart = new MimeBodyPart();
                        DataSource fileDataSource = new FileDataSource(pathFileName);
                        messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
                        messageBodyPart.setFileName(attachmentFile.getName());
                        multipart.addBodyPart(messageBodyPart);
                    }
                }
                appLogger.debug(String.format("Mail Message (%s): %s - with attachments", aSubject, aMessage));
            } else
                appLogger.debug(String.format("Mail Message (%s): %s", aSubject, aMessage));

            mimeMessage.setContent(multipart);
            Transport.send(mimeMessage);
        } else
            throw new NSException("Valid from, recipient, subject and message are required parameters.");
    } else
        appLogger.warn("Email delivery is not enabled - no message will be sent.");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:org.olat.modules.vitero.manager.ViteroManager.java

protected boolean storePortrait(Identity identity, int userId) throws VmsNotAvailableException {
    try {/*from  w ww  .j  a va  2s . c o  m*/
        File portrait = DisplayPortraitManager.getInstance().getBigPortrait(identity.getName());
        if (portrait != null && portrait.exists()) {
            Mtom mtomWs = getMtomWebService();

            CompleteAvatarWrapper avatar = new CompleteAvatarWrapper();

            avatar.setType(BigInteger.ZERO);
            avatar.setUserid(BigInteger.valueOf(userId));
            avatar.setFilename(portrait.getName());

            DataHandler portraitHandler = new DataHandler(new FileDataSource(portrait));
            avatar.setFile(portraitHandler);

            mtomWs.storeAvatar(avatar);
            return true;
        }
        return false;
    } catch (SOAPFaultException f) {
        ErrorCode code = handleAxisFault(f);
        switch (code) {
        default:
            logAxisError("Cannot store the portrait of " + userId, f);
        }
        return false;
    } catch (WebServiceException e) {
        if (e.getCause() instanceof ConnectException) {
            throw new VmsNotAvailableException();
        }
        logError("Cannot store the portrait of " + userId, e);
        return false;
    }
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.SessionServiceImpl.java

private BlackboardMultimediaResponse createSessionMultimedia(Session session, ConferenceUser conferenceUser,
        MultipartFile file) {/*ww  w.j a va  2s  . com*/
    final String filename = FilenameUtils.getName(file.getOriginalFilename());

    File multimediaFile = null;
    try {
        //Transfer the uploaded file to our own temp file so we can use a FileDataSource
        multimediaFile = File.createTempFile(filename, ".tmp", this.tempDir);
        file.transferTo(multimediaFile);

        //Upload the file to BB
        return this.multimediaWSDao.createSessionMultimedia(session.getBbSessionId(),
                conferenceUser.getUniqueId(), filename, "",
                new DataHandler(new FileDataSource(multimediaFile)));
    } catch (IOException e) {
        throw new RuntimeException("Failed to upload multimedia file '" + filename + "'", e);
    } finally {
        FileUtils.deleteQuietly(multimediaFile);
    }
}

From source file:com.youxifan.utils.EMail.java

/**
 *   Set the message content/*from w ww .ja v a 2 s.c  om*/
 *    @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:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Send a SOAP request via a MEPClient with attachments, taking a SOAP action. This method also takes
 * XPath expressions to evaluate the header and body sections of the request envelope.
 * //from w w  w. ja va2 s.c o  m
 * @param endpoint The URL of the end point to send the request to.
 * @param soapRequestFileName Path to the SOAP request file
 * @param parametersMap A map containing key value pairs to be parameterized in the request.
 * @param attachmentMap A map containing content IDs and paths to files which needed to be added to the
 *        SOAP request as attachments.
 * @param action The SOAP Action as a string.
 * @param xpathHeaderExp XPath expression to evaluate the SOAP header.
 * @param xpathBodyExp XPath expression to evaluate the SOAP body.
 * @return The SOAP Envelope that is returned as a result of the request.
 * @throws XMLStreamException Thrown on failure to build OM Element from the file's contents.
 * @throws IOException Thrown on failure to send the request.
 * @throws JaxenException Thrown on failure to evaluate XPath expression.
 */
protected SOAPEnvelope sendSOAPRequest(final String endpoint, final String soapRequestFileName,
        final Map<String, String> parametersMap, final Map<String, String> attachmentMap, final String action,
        final String xpathHeaderExp, final String xpathBodyExp)
        throws XMLStreamException, IOException, JaxenException {

    OMElement requestEnvelope = AXIOMUtil.stringToOM(loadRequestFromFile(soapRequestFileName, parametersMap));
    Map<String, DataHandler> dataHandlerMap = new HashMap<String, DataHandler>();
    for (String contentId : attachmentMap.keySet()) {
        dataHandlerMap.put(contentId, new DataHandler(
                new FileDataSource(new File(pathToRequestsDirectory + attachmentMap.get(contentId)))));
    }
    OperationClient mepClient = buildMEPClient(new EndpointReference(endpoint), requestEnvelope, dataHandlerMap,
            action, xpathHeaderExp, xpathBodyExp);

    mepClient.execute(true);
    return mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE).getEnvelope();
}

From source file:be.ibridge.kettle.job.entry.mail.JobEntryMail.java

public Result execute(Result result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();

    File masterZipfile = null;/*  w  w  w  . ja  va  2s.  c  o m*/

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        log.logError(toString(),
                "Unable to send the mail because the mail-server (SMTP host) is not specified");
        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        protocol = "smtps";
    }

    props.put("mail." + protocol + ".host", StringUtil.environmentSubstitute(server));
    if (!Const.isEmpty(port))
        props.put("mail." + protocol + ".port", StringUtil.environmentSubstitute(port));
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        props.put("mail.debug", "true");

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
        authenticator = new Authenticator()
        {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(
                        StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), 
                        StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, ""))
                    );
        }
        };
        */
    }

    Session session = Session.getInstance(props);
    session.setDebug(debug);

    try {
        // create a message
        Message msg = new MimeMessage(session);

        String email_address = StringUtil.environmentSubstitute(replyAddress);
        if (!Const.isEmpty(email_address)) {
            msg.setFrom(new InternetAddress(email_address));
        } else {
            throw new MessagingException("reply e-mail address is not filled in");
        }

        // Split the mail-address: space separated
        String destinations[] = StringUtil.environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++)
            address[i] = new InternetAddress(destinations[i]);

        msg.setRecipients(Message.RecipientType.TO, address);

        if (!Const.isEmpty(destinationCc)) {
            // Split the mail-address Cc: space separated
            String destinationsCc[] = StringUtil.environmentSubstitute(destinationCc).split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++)
                addressCc[i] = new InternetAddress(destinationsCc[i]);

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        if (!Const.isEmpty(destinationBCc)) {
            // Split the mail-address BCc: space separated
            String destinationsBCc[] = StringUtil.environmentSubstitute(destinationBCc).split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++)
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }

        msg.setSubject(StringUtil.environmentSubstitute(subject));
        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();

        if (comment != null) {
            messageText.append(StringUtil.environmentSubstitute(comment)).append(Const.CR).append(Const.CR);
        }

        if (!onlySendComment) {
            messageText.append("Job:").append(Const.CR);
            messageText.append("-----").append(Const.CR);
            messageText.append("Name       : ").append(parentJob.getJobMeta().getName()).append(Const.CR);
            messageText.append("Directory  : ").append(parentJob.getJobMeta().getDirectory()).append(Const.CR);
            messageText.append("JobEntry   : ").append(getName()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            Value date = new Value("date", new Date());
            messageText.append("Message date: ").append(date.toString()).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment && result != null) {
            messageText.append("Previous result:").append(Const.CR);
            messageText.append("-----------------").append(Const.CR);
            messageText.append("Job entry nr         : ").append(result.getEntryNr()).append(Const.CR);
            messageText.append("Errors               : ").append(result.getNrErrors()).append(Const.CR);
            messageText.append("Lines read           : ").append(result.getNrLinesRead()).append(Const.CR);
            messageText.append("Lines written        : ").append(result.getNrLinesWritten()).append(Const.CR);
            messageText.append("Lines input          : ").append(result.getNrLinesInput()).append(Const.CR);
            messageText.append("Lines output         : ").append(result.getNrLinesOutput()).append(Const.CR);
            messageText.append("Lines updated        : ").append(result.getNrLinesUpdated()).append(Const.CR);
            messageText.append("Script exit status   : ").append(result.getExitStatus()).append(Const.CR);
            messageText.append("Result               : ").append(result.getResult()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (!onlySendComment && (!Const.isEmpty(StringUtil.environmentSubstitute(contactPerson))
                || !Const.isEmpty(StringUtil.environmentSubstitute(contactPhone)))) {
            messageText.append("Contact information :").append(Const.CR);
            messageText.append("---------------------").append(Const.CR);
            messageText.append("Person to contact : ").append(StringUtil.environmentSubstitute(contactPerson))
                    .append(Const.CR);
            messageText.append("Telephone number  : ").append(StringUtil.environmentSubstitute(contactPhone))
                    .append(Const.CR);
            messageText.append(Const.CR);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append("Path to this job entry:").append(Const.CR);
                messageText.append("------------------------").append(Const.CR);

                addBacktracking(jobTracker, messageText);
            }
        }

        Multipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // 1st part
        part1.setText(messageText.toString());
        parts.addBodyPart(part1);
        if (includingFiles && result != null) {
            List resultFiles = result.getResultFilesList();
            if (resultFiles != null && resultFiles.size() > 0) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (Iterator iter = resultFiles.iterator(); iter.hasNext();) {
                        ResultFile resultFile = (ResultFile) iter.next();
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                URLDataSource fds = new URLDataSource(file.getURL());

                                // get a data Handler to manipulate this file type;
                                files.setDataHandler(new DataHandler(fds));
                                // include the file in the data source
                                files.setFileName(fds.getName());
                                // add the part with the file in the BodyPart();
                                parts.addBodyPart(files);

                                log.logBasic(toString(),
                                        "Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + StringUtil.environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (Iterator iter = resultFiles.iterator(); iter.hasNext();) {
                            ResultFile resultFile = (ResultFile) iter.next();

                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getURI());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        file.getContent().getInputStream());
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                                log.logBasic(toString(), "Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        log.logError(toString(), "Error zipping attachement files into file ["
                                + masterZipfile.getPath() + "] : " + e.toString());
                        log.logError(toString(), Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                log.logError(toString(),
                                        "Unable to close attachement zip file archive : " + e.toString());
                                log.logError(toString(), Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in th e data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(StringUtil.environmentSubstitute(Const.NVL(port, ""))),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")));
                } else {
                    transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")));
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null)
                transport.close();
        }
    } catch (IOException e) {
        log.logError(toString(), "Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        log.logError(toString(), "Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    log.logError(toString(), "    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        log.logError(toString(), "         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    log.logError(toString(), "    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        log.logError(toString(), "         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    //System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        log.logError(toString(), "         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.SessionServiceImpl.java

private BlackboardPresentationResponse createSessionPresentation(Session session, ConferenceUser conferenceUser,
        MultipartFile file) {//from ww w .j  av  a 2  s .  c  o  m
    final String filename = FilenameUtils.getName(file.getOriginalFilename());

    File multimediaFile = null;
    try {
        //Transfer the uploaded file to our own temp file so we can use a FileDataSource
        multimediaFile = File.createTempFile(filename, ".tmp", this.tempDir);
        file.transferTo(multimediaFile);

        //Upload the file to BB
        return this.presentationWSDao.uploadPresentation(session.getBbSessionId(), conferenceUser.getUniqueId(),
                filename, "", new DataHandler(new FileDataSource(multimediaFile)));
    } catch (IOException e) {
        throw new RuntimeException("Failed to upload multimedia file '" + filename + "'", e);
    } finally {
        FileUtils.deleteQuietly(multimediaFile);
    }
}

From source file:edu.sdsc.nbcr.opal.OpalClient.java

/**
 * this function returns an array of InputFileType containing all the files
 * selected by the user/* ww w . j  a  va  2 s  .  c  om*/
  *
  * If the server is Opal2 the file are sent using attachment...
 */
private InputFileType[] _getInputFiles() throws IllegalActionException {
    InputFileType inputFile = null;
    ArrayList files = new ArrayList();
    // complex submission form
    Attribute[] opalAttrs = _getOpalAttributes();
    for (int i = 0; i < opalAttrs.length; i++) {
        if (opalAttrs[i] instanceof FilePortParameter) {
            // simple case
            File file = ((FilePortParameter) opalAttrs[i]).asFile();
            if (file == null)
                continue;
            if (file.exists()) {
                inputFile = new InputFileType();
                if (_appMetadata.isOpal2()) {
                    //use attachment to sent the file
                    DataHandler dh = new DataHandler(new FileDataSource(file));
                    inputFile.setName(file.getName());
                    inputFile.setAttachment(dh);
                    log.info("Uploading file using attahcment: " + inputFile.getName());
                } else {
                    //use inline to sent the file
                    byte[] fileByte = new byte[(int) file.length()];// this is nasty
                    inputFile.setName(file.getName());
                    try {
                        (new FileInputStream(file)).read(fileByte);
                    } catch (Exception e) {
                        throw new IllegalActionException("Unable to read input file: " + file.getName());
                    }
                    inputFile.setContents(fileByte);
                    log.info("Uploading file using base64 encoding: " + inputFile.getName());
                }
                files.add(inputFile);
            } else {
                // the file does not exist
                throw new IllegalActionException("Unable to read input file: " + file.getName());
            }
        }
    }
    log.info("we are returning " + files.size() + " file(s)");
    return (InputFileType[]) files.toArray(new InputFileType[files.size()]);
}

From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java

public DataSource downloadPlugin(RemoteSession session, PluginInfo pluginInfo) throws WGAServiceException {
    if (!isAdminServiceEnabled()) {
        throw new WGAServiceException("Administrative services are disabled");
    }//from  w ww  .j  a v  a  2  s . c  om

    if (!isAdminSession(session)) {
        throw new WGAServiceException("You need an administrative login to access this service.");
    }

    try {
        WGAPluginSet pluginSet = _core.getPluginSet();
        WGAPlugin plugin = pluginSet.getPluginByUniqueName(pluginInfo.getUniqueName());
        if (plugin != null) {
            File file = plugin.getPluginFile();
            if (file != null && file.isFile()) {
                return new FileDataSource(file);
            }
        }
    } catch (Exception e) {
        throw new WGAServiceException("Plugin download failed.", e);
    }

    return null;
}