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:org.apache.axis.attachments.MultiPartDimeInputStream.java

/**
 * This will read streams in till the one that is needed is found.
 *
 * @param id is the stream being sought// w ww  .  java  2s. c om
 * @return a <code>Part</code> matching the ids
 */
protected Part readTillFound(final String[] id) throws java.io.IOException {
    if (dimeDelimitedStream == null) {
        //The whole stream has been consumed already
        return null;
    }
    Part ret = null;

    try {

        if (soapStream != null) { //Still on the SOAP stream.
            if (!eos) { //The SOAP packet has not been fully read yet. Need to store it away.

                java.io.ByteArrayOutputStream soapdata = new java.io.ByteArrayOutputStream(1024 * 8);

                byte[] buf = new byte[1024 * 16];
                int byteread = 0;

                do {
                    byteread = soapStream.read(buf);
                    if (byteread > 0) {
                        soapdata.write(buf, 0, byteread);
                    }

                } while (byteread > -1);
                soapdata.close();
                soapStream.close();
                soapStream = new java.io.ByteArrayInputStream(soapdata.toByteArray());
            }
            dimeDelimitedStream = dimeDelimitedStream.getNextStream();
        }
        //Now start searching for the data.

        if (null != dimeDelimitedStream) {
            do {
                String contentId = dimeDelimitedStream.getContentId();
                String type = dimeDelimitedStream.getType();

                if (type != null
                        && !dimeDelimitedStream.getDimeTypeNameFormat().equals(DimeTypeNameFormat.MIME)) {
                    type = "application/uri; uri=\"" + type + "\"";
                }

                ManagedMemoryDataSource source = new ManagedMemoryDataSource(dimeDelimitedStream,
                        ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, type, true);
                DataHandler dh = new DataHandler(source);

                AttachmentPart ap = new AttachmentPart(dh);
                if (contentId != null) {
                    ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, contentId);
                }

                addPart(contentId, "", ap);

                for (int i = id.length - 1; ret == null && i > -1; --i) {
                    if (contentId != null && id[i].equals(contentId)) { //This is the part being sought
                        ret = ap;
                    }
                }

                dimeDelimitedStream = dimeDelimitedStream.getNextStream();

            } while (null == ret && null != dimeDelimitedStream);
        }
    } catch (Exception e) {
        throw org.apache.axis.AxisFault.makeFault(e);
    }

    return ret;
}

From source file:org.openehealth.ipf.platform.camel.lbs.cxf.process.LbsCxfHugeFileTest.java

@Test
@Ignore/*from ww  w.ja v a 2s. c o m*/
public void testHugeFile() throws Exception {
    TrackMemThread memTracker = new TrackMemThread();
    memTracker.start();
    try {
        DataSource dataSourceAttachInfo = new ByteArrayDataSource("Smaller content",
                "application/octet-stream");
        DataHandler dataHandlerAttachInfo = new DataHandler(dataSourceAttachInfo);
        Holder<DataHandler> handlerHolderAttachInfo = new Holder(dataHandlerAttachInfo);

        DataSource dataSourceOneWay = new InputStreamDataSource();
        DataHandler dataHandlerOneWay = new DataHandler(dataSourceOneWay);

        Holder<String> nameHolder = new Holder("Hello Camel!!");
        greeter.postMe(nameHolder, handlerHolderAttachInfo, dataHandlerOneWay);

        assertEquals("resultText", nameHolder.value);
        InputStream resultInputStream = handlerHolderAttachInfo.value.getInputStream();
        try {
            assertTrue(IOUtils.contentEquals(new HugeContentInputStream(), resultInputStream));
        } finally {
            resultInputStream.close();
        }
    } finally {
        memTracker.waitForStop();
        assertTrue("Memory consumption not constant. Difference was: " + memTracker.getDiff(),
                memTracker.getDiff() < 10000);
    }
}

From source file:org.apache.synapse.samples.framework.clients.MTOMSwASampleClient.java

public SampleClientResult sendUsingSWA(String fileName, String targetEPR) {
    clientResult = new SampleClientResult();
    try {/*from  w w w . ja v a 2  s.c  o m*/
        Options options = new Options();
        options.setTo(new EndpointReference(targetEPR));
        options.setAction("urn:uploadFileUsingSwA");
        options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);

        ConfigurationContext configContext = ConfigurationContextFactory
                .createConfigurationContextFromFileSystem(configuration.getClientRepo(),
                        configuration.getAxis2Xml());

        ServiceClient sender = new ServiceClient(configContext, null);

        sender.setOptions(options);
        OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);

        MessageContext mc = new MessageContext();

        log.info("Sending file : " + fileName + " as SwA");
        FileDataSource fileDataSource = new FileDataSource(new File(fileName));
        DataHandler dataHandler = new DataHandler(fileDataSource);
        String attachmentID = mc.addAttachment(dataHandler);

        SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
        SOAPEnvelope env = factory.getDefaultEnvelope();
        OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
        OMElement payload = factory.createOMElement("uploadFileUsingSwA", ns);
        OMElement request = factory.createOMElement("request", ns);
        OMElement imageId = factory.createOMElement("imageId", ns);
        imageId.setText(attachmentID);
        request.addChild(imageId);
        payload.addChild(request);
        env.getBody().addChild(payload);
        mc.setEnvelope(env);

        mepClient.addMessageContext(mc);
        mepClient.execute(true);
        MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);

        SOAPBody body = response.getEnvelope().getBody();
        String imageContentId = body
                .getFirstChildWithName(new QName("http://services.samples", "uploadFileUsingSwAResponse"))
                .getFirstChildWithName(new QName("http://services.samples", "response"))
                .getFirstChildWithName(new QName("http://services.samples", "imageId")).getText();

        Attachments attachment = response.getAttachmentMap();
        dataHandler = attachment.getDataHandler(imageContentId);
        File tempFile = File.createTempFile("swa-", ".gif");
        FileOutputStream fos = new FileOutputStream(tempFile);
        dataHandler.writeTo(fos);
        fos.flush();
        fos.close();

        log.info("Saved response to file : " + tempFile.getAbsolutePath());
        clientResult.incrementResponseCount();
    } catch (Exception e) {
        log.error("Error invoking service", e);
        clientResult.setException(e);
    }

    return clientResult;

}

From source file:org.apache.axis2.builder.MultipartFormDataBuilder.java

private DataHandler getFileParameter(DiskFileItem diskFileItem) throws Exception {

    DataSource dataSource = new DiskFileDataSource(diskFileItem);
    DataHandler dataHandler = new DataHandler(dataSource);

    return dataHandler;
}

From source file:com.collabnet.ccf.pi.sfee.v44.SFEEAttachmentHandler.java

/**
 * This method uploads the file and gets the new file descriptor returned
 * from the TF system. It then associates the file descriptor to the
 * artifact there by adding the attachment to the artifact.
 * //  www  .  j  a v  a  2  s  . c  o m
 * @param sessionId
 *            - The current session id
 * @param artifactId
 *            - The artifact's id to which the attachment should be added.
 * @param comment
 *            - Comment for the attachment addition
 * @param fileName
 *            - Name of the file that is attached to this artifact
 * @param mimeType
 *            - MIME type of the file that is being attached.
 * @param att
 *            - the file content
 * @param linkUrl
 * 
 * @throws RemoteException
 *             - if any SOAP api call fails
 */
public ArtifactSoapDO attachFileToArtifact(String sessionId, String artifactId, String comment, String fileName,
        String mimeType, GenericArtifact att, byte[] linkUrl) throws RemoteException {
    ArtifactSoapDO soapDo = null;
    String attachmentDataFileName = GenericArtifactHelper
            .getStringGAField(AttachmentMetaData.ATTACHMENT_DATA_FILE, att);
    boolean retryCall = true;
    while (retryCall) {
        retryCall = false;
        String fileDescriptor = null;
        try {
            byte[] data = null;
            if (StringUtils.isEmpty(attachmentDataFileName)) {
                if (linkUrl == null) {
                    data = att.getRawAttachmentData();
                } else {
                    data = linkUrl;
                }
                fileDescriptor = fileStorageApp.startFileUpload(sessionId);
                fileStorageApp.write(sessionId, fileDescriptor, data);
                fileStorageApp.endFileUpload(sessionId, fileDescriptor);
            } else {
                try {
                    DataSource dataSource = new FileDataSource(new File(attachmentDataFileName));
                    DataHandler dataHandler = new DataHandler(dataSource);
                    fileDescriptor = fileStorageSoapApp.uploadFile(sessionId, dataHandler);
                } catch (IOException e) {
                    String message = "Exception while uploading the attachment " + attachmentDataFileName;
                    log.error(message, e);
                    throw new CCFRuntimeException(message, e);
                }
            }

            soapDo = mTrackerApp.getArtifactData(sessionId, artifactId);
            boolean fileAttached = true;
            while (fileAttached) {
                try {
                    fileAttached = false;
                    mTrackerApp.setArtifactData(sessionId, soapDo, comment, fileName, mimeType, fileDescriptor);
                } catch (AxisFault e) {
                    javax.xml.namespace.QName faultCode = e.getFaultCode();
                    if (!faultCode.getLocalPart().equals("VersionMismatchFault")) {
                        throw e;
                    }
                    logConflictResolutor.warn("Stale attachment update, trying again ...:", e);
                    soapDo = mTrackerApp.getArtifactData(sessionId, artifactId);
                    fileAttached = true;
                }
            }
        } catch (AxisFault e) {
            javax.xml.namespace.QName faultCode = e.getFaultCode();
            if (!faultCode.getLocalPart().equals("InvalidSessionFault")) {
                throw e;
            }
            if (connectionManager.isEnableReloginAfterSessionTimeout()
                    && (!connectionManager.isUseStandardTimeoutHandlingCode())) {
                log.warn("While uploading an attachment, the session id became invalid, trying again", e);
                retryCall = true;
            } else {
                throw e;
            }
        }
    }
    // we have to increase the version after the update
    // TODO Find out whether this really works if last modified date differs
    // from actual last modified date
    soapDo.setVersion(soapDo.getVersion() + 1);
    return soapDo;
}

From source file:org.wso2.carbon.bpel.ui.fileupload.BPELUploadExecutor.java

public boolean execute(HttpServletRequest request, HttpServletResponse response)
        throws CarbonException, IOException {
    String errMsg;/* w w  w.  ja  v a  2 s  .  c  om*/

    response.setContentType("text/html; charset=utf-8");

    PrintWriter out = response.getWriter();
    String webContext = (String) request.getAttribute(CarbonConstants.WEB_CONTEXT);
    String serverURL = (String) request.getAttribute(CarbonConstants.SERVER_URL);
    String cookie = (String) request.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    Map<String, ArrayList<FileItemData>> fileItemsMap = getFileItemsMap();

    if (fileItemsMap == null || fileItemsMap.isEmpty()) {
        String msg = "File uploading failed.";
        log.error(msg);
        out.write("<textarea>" + "(function(){i18n.fileUplodedFailed();})();" + "</textarea>");
        return true;
    }
    BPELUploaderClient uploaderClient = new BPELUploaderClient(configurationContext, serverURL + "BPELUploader",
            cookie);

    SaveExtractReturn uploadedFiles = null;
    ArrayList<String> extractedFiles = new ArrayList<String>();
    try {
        for (FileItemData fieldData : fileItemsMap.get("bpelFileName")) {
            String fileName = getFileName(fieldData.getFileItem().getName());
            //Check filename for \ charactors. This cannot be handled at the lower stages.
            if (fileName.matches("(.*[\\\\].*[/].*|.*[/].*[\\\\].*)")) {
                log.error(
                        "BPEL Package Validation Failure: one or many of the following illegal characters are "
                                + "in " + "the package.\n ~!@#$;%^*()+={}[]| \\<>");
                throw new Exception("BPEL Package Validation Failure: one or many of the following illegal "
                        + "characters " + "are in the package. ~!@#$;%^*()+={}[]| \\<>");
            }
            //Check file extension.
            checkServiceFileExtensionValidity(fileName, ALLOWED_FILE_EXTENSIONS);

            if (fileName.lastIndexOf('\\') != -1) {
                int indexOfColon = fileName.lastIndexOf('\\') + 1;
                fileName = fileName.substring(indexOfColon, fileName.length());
            }
            if (fieldData.getFileItem().getFieldName().equals("bpelFileName")) {
                uploadedFiles = saveAndExtractUploadedFile(fieldData.getFileItem());
                extractedFiles.add(uploadedFiles.extractedFile);
                validateBPELPackage(uploadedFiles.extractedFile);
                DataSource dataSource = new FileDataSource(uploadedFiles.zipFile);
                uploaderClient.addUploadedFileItem(new DataHandler(dataSource), fileName, "zip");

            }
        }
        uploaderClient.uploadFileItems();
        String msg = "Your BPEL package been uploaded successfully. Please refresh this page in a"
                + " while to see the status of the new process.";
        CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.INFO, request, response,
                getContextRoot(request) + "/" + webContext + "/bpel/process_list.jsp");

        return true;
    } catch (Exception e) {
        errMsg = "File upload failed :" + e.getMessage();
        log.error(errMsg, e);
        CarbonUIMessage.sendCarbonUIMessage(errMsg, CarbonUIMessage.ERROR, request, response,
                getContextRoot(request) + "/" + webContext + "/bpel/upload_bpel.jsp");
    } finally {
        for (String s : extractedFiles) {
            File extractedFile = new File(s);
            if (log.isDebugEnabled()) {
                log.debug("Cleaning temporarily extracted BPEL artifacts in " + extractedFile.getParent());
            }
            try {
                FileUtils.cleanDirectory(new File(extractedFile.getParent()));
            } catch (IOException ex) {
                log.warn("Failed to clean temporary extractedFile.", ex);
            }
        }
    }

    return false;
}

From source file:org.sigmah.server.mail.MailSenderImpl.java

@Override
public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException {
    final String user = email.getAuthenticationUserName();
    final String password = email.getAuthenticationPassword();

    final Properties properties = new Properties();
    properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL);
    properties.setProperty(MAIL_SMTP_HOST, email.getHostName());
    properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort()));

    final StringBuilder toBuilder = new StringBuilder();
    for (final String to : email.getToAddresses()) {
        if (toBuilder.length() > 0) {
            toBuilder.append(',');
        }/* ww w. j a v a  2 s  .co m*/
        toBuilder.append(to);
    }

    final StringBuilder ccBuilder = new StringBuilder();
    if (email.getCcAddresses().length > 0) {
        for (final String cc : email.getCcAddresses()) {
            if (ccBuilder.length() > 0) {
                ccBuilder.append(',');
            }
            ccBuilder.append(cc);
        }
    }

    final Session session = javax.mail.Session.getInstance(properties);
    try {
        final DataSource attachment = new ByteArrayDataSource(fileStream,
                FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType());

        final Transport transport = session.getTransport();

        if (password != null) {
            transport.connect(user, password);
        } else {
            transport.connect();
        }

        final MimeMessage message = new MimeMessage(session);

        // Configures the headers.
        message.setFrom(new InternetAddress(email.getFromAddress(), false));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false));
        if (email.getCcAddresses().length > 0) {
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false));
        }

        message.setSubject(email.getSubject(), email.getEncoding());

        // Html body part.
        final MimeMultipart textMultipart = new MimeMultipart("alternative");

        final MimeBodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\"");
        textMultipart.addBodyPart(htmlBodyPart);

        final MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(textMultipart);

        // Attachment body part.
        final MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(attachment));
        attachmentPart.setFileName(fileName);
        attachmentPart.setDescription(fileName);

        // Mail multipart content.
        final MimeMultipart contentMultipart = new MimeMultipart("related");
        contentMultipart.addBodyPart(textBodyPart);
        contentMultipart.addBodyPart(attachmentPart);

        message.setContent(contentMultipart);
        message.saveChanges();

        // Sends the mail.
        transport.sendMessage(message, message.getAllRecipients());

    } catch (UnsupportedEncodingException ex) {
        throw new EmailException(
                "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex);

    } catch (IOException ex) {
        throw new EmailException("An error occured while reading the attachment of an email.", ex);

    } catch (MessagingException ex) {
        throw new EmailException("An error occured while sending an email.", ex);
    }
}

From source file:edu.mit.broad.genepattern.gp.services.GenePatternClientImpl.java

private DataHandler getFileDataHandler(ParameterInfo parameter) {
    String filePath = parameter.getValue();
    FileDataSource fileDataSource = new FileDataSource(filePath) {
        @Override//w  w w.  j  av a  2 s. com
        public String getName() {
            return getFile().getName();
        }
    };
    DataHandler handler = new DataHandler(fileDataSource);
    parameter.setValue(fileDataSource.getName());
    return handler;
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.WsdlPackagingRequestFilter.java

/**
 * Creates root BodyPart containing message
 *///from www . j  a v  a 2 s. c o  m

protected void initRootPart(WsdlRequest wsdlRequest, String requestContent, MimeMultipart mp, boolean isXOP)
        throws MessagingException {
    MimeBodyPart rootPart = new PreencodedMimeBodyPart(System.getProperty("soapui.bodypart.encoding", "8bit"));
    rootPart.setContentID(AttachmentUtils.ROOTPART_SOAPUI_ORG);
    mp.addBodyPart(rootPart, 0);

    DataHandler dataHandler = new DataHandler(new WsdlRequestDataSource(wsdlRequest, requestContent, isXOP));
    rootPart.setDataHandler(dataHandler);
}

From source file:org.eclipse.ecr.automation.core.mail.Composer.java

public Mailer.Message newMixedMessage(String templateContent, Object ctx, String textType,
        List<Blob> attachments) throws Exception {
    if (textType == null) {
        textType = "plain";
    }// www  . j  a  v  a 2s .  co m
    Mailer.Message msg = mailer.newMessage();
    MimeMultipart mp = new MimeMultipart();
    MimeBodyPart body = new MimeBodyPart();
    String result = render(templateContent, ctx);
    body.setText(result, "UTF-8", textType);
    mp.addBodyPart(body);
    for (Blob blob : attachments) {
        MimeBodyPart a = new MimeBodyPart();
        a.setDataHandler(new DataHandler(new BlobDataSource(blob)));
        a.setFileName(blob.getFilename());
        mp.addBodyPart(a);
    }
    msg.setContent(mp);
    return msg;
}