Example usage for javax.activation DataHandler DataHandler

List of usage examples for javax.activation DataHandler DataHandler

Introduction

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

Prototype

public DataHandler(URL url) 

Source Link

Document

Create a DataHandler instance referencing a URL.

Usage

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Compresses the payload using the ZLIB algorithm
 *//*from  ww  w. ja  v  a  2s  . c o m*/
private MimeBodyPart compressPayload(Partner receiver, byte[] data, String contentType)
        throws SMIMEException, MessagingException {
    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    bodyPart.addHeader("Content-Type", contentType);
    if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) {
        bodyPart.addHeader("Content-Transfer-Encoding", "base64");
    } else {
        bodyPart.addHeader("Content-Transfer-Encoding", "binary");
    }
    SMIMECompressedGenerator generator = new SMIMECompressedGenerator();
    if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) {
        generator.setContentTransferEncoding("base64");
    } else {
        generator.setContentTransferEncoding("binary");
    }
    return (generator.generate(bodyPart, SMIMECompressedGenerator.ZLIB));
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!//from   w w w.j  a va2 s  . c  o m
 *
 * @param multipart DOCUMENT ME!
 * @param file DOCUMENT ME!
 * @param charset DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, File file, String charset) throws MessagingException {
    // UNDONE how to specify the character set of the file???
    MimeBodyPart xbody = new MimeBodyPart();
    FileDataSource xds = new FileDataSource(file);
    DataHandler xdh = new DataHandler(xds);
    xbody.setDataHandler(xdh);

    //System.out.println(xdh.getContentType());
    // UNDONE
    // xbody.setContentLanguage( String ); // this could be language from Locale
    // xbody.setContentMD5( String md5 ); // don't know about this yet
    xbody.setDescription("File Attachment: " + file.getName(), charset);
    xbody.setDisposition(Part.ATTACHMENT);
    MessageUtilities.setFileName(xbody, file.getName(), charset);

    multipart.addBodyPart(xbody);
}

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;/*from w ww  .j  a  va  2  s  .co 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.jets3t.service.impl.soap.axis.SoapS3Service.java

protected S3Object putObjectImpl(String bucketName, S3Object object) throws S3ServiceException {
    if (log.isDebugEnabled()) {
        log.debug("Creating Object with key " + object.getKey() + " in bucket " + bucketName);
    }//from   www.ja va2 s.  c o  m

    Grant[] grants = null;
    if (object.getAcl() != null) {
        grants = convertACLtoGrants(object.getAcl());
    }
    MetadataEntry[] metadata = convertMetadata(object.getMetadataMap());

    try {
        AmazonS3SoapBindingStub s3SoapBinding = getSoapBinding();
        long contentLength = object.getContentLength();
        String contentType = object.getContentType();
        if (contentType == null) {
            // Set default content type.
            contentType = Mimetypes.MIMETYPE_OCTET_STREAM;
        }

        if (object.getDataInputStream() != null) {
            if (log.isDebugEnabled()) {
                log.debug("Uploading data input stream for S3Object: " + object.getKey());
            }

            if (contentLength == 0 && object.getDataInputStream().available() > 0) {

                if (log.isWarnEnabled()) {
                    log.warn("S3Object " + object.getKey()
                            + " - Content-Length was set to 0 despite having a non-empty data"
                            + " input stream. The Content-length will be determined in memory.");
                }

                // Read all data into memory to determine it's length.
                BufferedInputStream bis = new BufferedInputStream(object.getDataInputStream());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedOutputStream bos = new BufferedOutputStream(baos);
                try {
                    byte[] buffer = new byte[8192];
                    int read = -1;
                    while ((read = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, read);
                    }
                } finally {
                    if (bis != null) {
                        bis.close();
                    }
                    if (bos != null) {
                        bos.close();
                    }
                }

                contentLength = baos.size();
                object.setDataInputStream(new ByteArrayInputStream(baos.toByteArray()));

                if (log.isDebugEnabled()) {
                    log.debug("Content-Length value has been reset to " + contentLength);
                }
            }

            DataHandler dataHandler = new DataHandler(
                    new SourceDataSource(null, contentType, new StreamSource(object.getDataInputStream())));
            s3SoapBinding.addAttachment(dataHandler);
        } else {
            DataHandler dataHandler = new DataHandler(
                    new SourceDataSource(null, contentType, new StreamSource()));
            s3SoapBinding.addAttachment(dataHandler);
        }

        Calendar timestamp = getTimeStamp(System.currentTimeMillis());
        String signature = ServiceUtils.signWithHmacSha1(getAWSSecretKey(),
                Constants.SOAP_SERVICE_NAME + "PutObject" + convertDateToString(timestamp));
        PutObjectResult result = s3SoapBinding.putObject(bucketName, object.getKey(), metadata, contentLength,
                grants, null, getAWSAccessKey(), timestamp, signature, null);

        // Ensure no data was corrupted, if we have the MD5 hash available to check.
        String eTag = result.getETag().substring(1, result.getETag().length() - 1);
        String eTagAsBase64 = ServiceUtils.toBase64(ServiceUtils.fromHex(eTag));
        String md5HashAsBase64 = object.getMd5HashAsBase64();
        if (md5HashAsBase64 != null && !eTagAsBase64.equals(md5HashAsBase64)) {
            throw new S3ServiceException(
                    "Object created but ETag returned by S3 does not match MD5 hash value of object");
        }

        object.setETag(result.getETag());
        object.setContentLength(contentLength);
        object.setContentType(contentType);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new S3ServiceException("Unable to Create Object: " + object.getKey(), e);
    }
    return object;
}

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.// w w  w  . ja va2 s  . co 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:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

/**
 * Adds a simple MimeBodyPart from an attachment
 *///ww  w.j a v  a 2  s . c  o m

public static void addSingleAttachment(MimeMultipart mp, StringToStringMap contentIds, Attachment att)
        throws MessagingException {
    String contentType = att.getContentType();
    MimeBodyPart part = contentType.startsWith("text/") ? new MimeBodyPart()
            : new PreencodedMimeBodyPart("binary");

    part.setDataHandler(new DataHandler(new AttachmentDataSource(att)));
    initPartContentId(contentIds, part, att, false);

    mp.addBodyPart(part);
}

From source file:org.jlibrary.core.axis.client.AxisRepositoryDelegate.java

public List createDocuments(Ticket ticket, List properties) throws RepositoryException, SecurityException {

    try {//  w ww.  j  a  va 2s  .  co  m
        call.removeAllParameters();

        call.setTargetEndpointAddress(new java.net.URL(endpoint));
        call.setOperationName("createDocuments");

        call.addParameter("ticket", XMLType.XSD_ANY, ParameterMode.IN);
        call.addParameter("properties", XMLType.XSD_ANY, ParameterMode.IN);

        call.setReturnType(XMLType.XSD_ANY);

        // TODO: Add N attachments
        Iterator it = properties.iterator();
        while (it.hasNext()) {
            DocumentProperties props = (DocumentProperties) it.next();
            byte[] content = (byte[]) props.getProperty(DocumentProperties.DOCUMENT_CONTENT).getValue();
            if (content != null) {
                props.setProperty(DocumentProperties.DOCUMENT_CONTENT, null);
                DataHandler handler = new DataHandler(
                        new ByteArrayDataSource(content, "application/octet-stream"));
                call.addAttachmentPart(handler);
            }
        }

        Object[] o = (Object[]) call.invoke(new Object[] { ticket, properties });
        ArrayList list = new ArrayList();
        CollectionUtils.addAll(list, o);
        return list;
    } catch (Exception e) {
        // I don't know if there is a better way to do this
        AxisFault fault = (AxisFault) e;
        if (fault.getFaultString().indexOf("SecurityException") != -1) {
            throw new SecurityException(fault.getFaultString());
        } else {
            throw new RepositoryException(fault.getFaultString());
        }
    }
}

From source file:org.openhealthtools.openxds.integrationtests.XdsTest.java

protected OMElement addOneDocument(OMElement request, String document, String documentId) throws IOException {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace ns = fac.createOMNamespace("urn:ihe:iti:xds-b:2007", null);
    OMElement docElem = fac.createOMElement("Document", ns);
    docElem.addAttribute("id", documentId, null);

    // A string, turn it into an StreamSource
    DataSource ds = new ByteArrayDataSource(document, "text/xml");
    DataHandler handler = new DataHandler(ds);

    OMText binaryData = fac.createOMText(handler, true);
    docElem.addChild(binaryData);// w ww. ja  va2s .c  o  m

    Iterator iter = request.getChildrenWithLocalName("SubmitObjectsRequest");
    OMElement submitObjectsRequest = null;
    for (; iter.hasNext();) {
        submitObjectsRequest = (OMElement) iter.next();
        if (submitObjectsRequest != null)
            break;
    }
    submitObjectsRequest.insertSiblingAfter(docElem);
    return request;
}

From source file:edu.xtec.colex.client.beans.ColexRecordBean.java

/**
 * Calls the web service operation/* w  w w . ja  va2s  . co  m*/
 * <I>addRecord(User,Owner,Collection,Record) : void</I>
 *
 * @param r the Record to add
 * @param vAttachments a Vector containing the Attachments of the Record
 * @throws java.lang.Exception when an Exception error occurs
 */
protected void addRecord(Record r, Vector vAttachments) throws Exception {
    User u = new User(getUserId());
    Collection c = new Collection("");

    Vector vTempFiles = new Vector();

    c.setName(collection);

    try {
        smRequest = mf.createMessage();

        SOAPBodyElement sbeRequest = setRequestName(smRequest, "addRecord");

        addParam(sbeRequest, u);
        if (owner != null) {
            Owner oRequest = new Owner(owner);
            addParam(sbeRequest, oRequest);
        }
        addParam(sbeRequest, c);
        addParam(sbeRequest, r);

        for (int i = 0; i < vAttachments.size(); i++) {

            FileItem fi = (FileItem) vAttachments.get(i);

            String sNomFitxer = Utils.getFileName(fi.getName());

            File fTemp = File.createTempFile("attach", null);

            fi.write(fTemp);

            vTempFiles.add(fTemp);

            URL urlFile = new URL("file://" + fTemp.getPath());

            AttachmentPart ap = smRequest.createAttachmentPart(new DataHandler(urlFile));

            String fieldName = fi.getFieldName();

            ap.setContentId(fieldName + "/" + sNomFitxer);

            smRequest.addAttachmentPart(ap);
        }
        smRequest.saveChanges();

        SOAPMessage smResponse = sendMessage(smRequest,
                this.getJspProperties().getProperty("url.servlet.record"));

        SOAPBody sbResponse = smResponse.getSOAPBody();

        if (sbResponse.hasFault()) {
            checkFault(sbResponse, "add");
        } else {

        }
    } catch (Exception e) {
        throw e;
    } finally {
        File fAux;

        for (int i = 0; i < vTempFiles.size(); i++) {
            fAux = (File) vTempFiles.get(i);
            fAux.delete();
        }
    }
}

From source file:es.pode.administracion.presentacion.noticias.crear.CrearControllerImpl.java

public String tratamientoImagen(FormFile imagenFile) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("Realizamos el tratamiento de la imagen [" + imagenFile + "]");
    ImagenVO imagen = new ImagenVO();
    InternetHeaders ih = new InternetHeaders();
    MimeBodyPart mbp = new MimeBodyPart(ih, imagenFile.getFileData());

    DataSource source = new MimePartDataSource(mbp);
    DataHandler dImagen = new DataHandler(source);

    imagen.setDatos(dImagen);//from w ww  . j  av a2  s  .c o m
    imagen.setNombre(imagenFile.getFileName());
    imagen.setMimeType(imagenFile.getContentType());
    String sUrlImagen = this.getSrvNoticiasService().almacenarImagenNoticia(imagen);
    return sUrlImagen;
}