Java Examples for javax.activation.DataSource

The following java examples will help you to understand the usage of javax.activation.DataSource. These source code samples are taken from different open source projects.

Example 1
Project: jentrata-msh-master  File: EbxmlMessage.java View source code
/**
     * Gets the messageFromDataSource attribute of the MessageServer class
     * 
     * @param dataSource
     *            Description of the Parameter
     * @param withAttachments
     *            Description of the Parameter
     * @return The messageFromDataSource value
     * @throws SOAPException
     *             Description of the Exception
     */
private static Object getMessageFromDataSource(DataSource dataSource, boolean withAttachments, EbxmlMessage ebxmlMessage) throws SOAPException, IOException {
    InputStream fis = null;
    PushbackInputStream fileStream = null;
    try {
        fis = dataSource.getInputStream();
        MessageSemiParsedOutput parsedOutput = parseSoapEnvelopeOnly(fis);
        fileStream = parsedOutput.getInputStream();
        byte[] soapMessageBytes = parsedOutput.getSoapMessageBytes();
        soapMessageBytes = getSoapEnvelopeBytesFromParsedOutput(parsedOutput);
        int soapMessageFileOffset = 0;
        int soapMessageLength = soapMessageBytes.length;
        int lastIndex = parsedOutput.getLastIndex();
        String boundary = parsedOutput.getBoundary();
        /*
             * final MimeHeaders headers = new MimeHeaders();
             * headers.addHeader(Constants.CONTENT_TYPE,
             * Constants.TEXT_XML_TYPE);
             */
        final MimeHeaders headers = parsedOutput.getMimeHeaders();
        /**
             * added for parsing message without payload. For such case,
             */
        if (headers.getHeader(Constants.CONTENT_TYPE) == null) {
            headers.addHeader(Constants.CONTENT_TYPE, Constants.TEXT_XML_TYPE);
        }
        final SOAPMessage soapMessage;
        soapMessage = MessageFactory.newInstance().createMessage(headers, new ByteArrayInputStream(soapMessageBytes, 0, lastIndex + 1));
        ArrayList payloads = new ArrayList();
        if (boundary != null && withAttachments) {
            byte[] line = parsedOutput.getLastLine();
            long offset = parsedOutput.getOffset();
            lastIndex = line.length - 1;
            for (; lastIndex >= 0; lastIndex--) {
                if (line[lastIndex] != 0xA && line[lastIndex] != 0xD) {
                    break;
                }
            }
            String s = new String(line, 0, lastIndex + 1);
            while (!s.endsWith(boundary + Constants.MIME_BOUNDARY_PREFIX)) {
                /*
                     * Find the empty line delimiter separating the MIME header
                     * and the attachment content
                     */
                final MimeHeaders attachmentHeaders = new MimeHeaders();
                line = readLine(fileStream);
                offset += line.length;
                while (line.length > 0 && line[0] != 0xA && line[0] != 0xD) {
                    String lineString = new String(line).trim(), name;
                    int colonIndex = lineString.indexOf(':');
                    if (colonIndex >= 0) {
                        name = lineString.substring(0, colonIndex).trim();
                        String value = lineString.substring(colonIndex + 1).trim();
                        /*
                             * final StringTokenizer t = new StringTokenizer
                             * (new String(line), "\t\n\r\f: "); if
                             * (t.hasMoreTokens()) { final String name =
                             * t.nextToken(); String value = t.nextToken();
                             */
                        if (name.equalsIgnoreCase(Constants.CONTENT_ID)) {
                            if (value.startsWith("<") && !EbxmlMessage.needPatch) {
                                value = value.substring(1);
                                if (value.endsWith(">")) {
                                    value = value.substring(0, value.length() - 1);
                                }
                            }
                        }
                        attachmentHeaders.addHeader(name, value);
                    }
                    line = readLine(fileStream);
                    offset += line.length;
                }
                if (line.length == 0) {
                    throw new SOAPException("missing empty line delimiter of MIME header");
                }
                long length = 0;
                byte[] previousLine = null;
                line = readLine(fileStream);
                s = new String(line);
                while (line.length > 0 && !(s.startsWith(Constants.MIME_BOUNDARY_PREFIX + boundary))) {
                    length += line.length;
                    previousLine = line;
                    line = readLine(fileStream);
                    s = new String(line);
                }
                if (line.length == 0) {
                    throw new SOAPException("missing ending MIME boundary");
                }
                lastIndex = previousLine.length - 1;
                for (; lastIndex >= 0; lastIndex--) {
                    if (previousLine[lastIndex] != 0xA && previousLine[lastIndex] != 0xD) {
                        break;
                    }
                }
                String[] ahs = attachmentHeaders.getHeader(Constants.CONTENT_TYPE);
                String contentType = null;
                if (ahs == null || ahs.length == 0) {
                    throw new SOAPException("missing " + Constants.CONTENT_TYPE + " attachment");
                } else if (ahs.length == 1) {
                    contentType = ahs[0];
                } else {
                    throw new SOAPException("more than one " + Constants.CONTENT_TYPE + " in attachment");
                }
                ahs = attachmentHeaders.getHeader(Constants.CONTENT_TRANSFER_ENCODING);
                String encoding = null;
                if (ahs != null) {
                    if (ahs.length == 1) {
                        encoding = ahs[0];
                    } else if (ahs.length > 1) {
                        throw new SOAPException("more than one " + Constants.CONTENT_TRANSFER_ENCODING + " in attachment");
                    }
                }
                final AttachmentDataSource ads = new AttachmentDataSource(dataSource, offset, length - (previousLine.length - 1 - lastIndex), contentType, encoding, false);
                final DataHandler dh = new DataHandler(ads);
                String contentId = null;
                ahs = attachmentHeaders.getHeader(Constants.CONTENT_ID);
                if (ahs != null) {
                    contentId = ahs[0];
                }
                PayloadContainer attachment = new PayloadContainer(dh, contentId, null);
                for (Iterator i = attachmentHeaders.getAllHeaders(); i.hasNext(); ) {
                    final MimeHeader header = (MimeHeader) i.next();
                    final String name = header.getName();
                    if (!name.equals(Constants.CONTENT_TYPE) && !name.equals(Constants.CONTENT_ID)) {
                        attachment.setMimeHeader(name, header.getValue());
                    }
                }
                payloads.add(attachment);
                // add the attachment to soap message                    
                AttachmentPart attachmentPart = soapMessage.createAttachmentPart();
                attachmentPart.setContentId(needPatch ? " <" + contentId + ">" : contentId);
                attachmentPart.setDataHandler(dh);
                soapMessage.addAttachmentPart(attachmentPart);
                offset += (length + line.length);
                lastIndex = line.length - 1;
                for (; lastIndex >= 0; lastIndex--) {
                    if (line[lastIndex] != 0xA && line[lastIndex] != 0xD) {
                        break;
                    }
                }
                s = new String(line, 0, lastIndex + 1);
            }
        }
        if (withAttachments) {
            EbxmlMessage message;
            if (ebxmlMessage == null) {
                message = new EbxmlMessage(soapMessage);
            } else {
                ebxmlMessage.init(soapMessage);
                message = ebxmlMessage;
            }
            message.setPayloadContainers(payloads);
            message.setSoapEnvelopeBytes(soapMessageBytes);
            return message;
        }
        return soapMessage;
    } catch (IOException e) {
        throw new SOAPException(e.toString());
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                throw new SOAPException(e.toString());
            }
        }
        if (fileStream != null) {
            try {
                fileStream.close();
            } catch (IOException e) {
                throw new SOAPException(e.toString());
            }
        }
    }
}
Example 2
Project: openjdk-master  File: MimeUtility.java View source code
/**
     * Get the content-transfer-encoding that should be applied
     * to the input stream of this datasource, to make it mailsafe. <p>
     *
     * The algorithm used here is: <br>
     * <ul>
     * <li>
     * If the primary type of this datasource is "text" and if all
     * the bytes in its input stream are US-ASCII, then the encoding
     * is "7bit". If more than half of the bytes are non-US-ASCII, then
     * the encoding is "base64". If less than half of the bytes are
     * non-US-ASCII, then the encoding is "quoted-printable".
     * <li>
     * If the primary type of this datasource is not "text", then if
     * all the bytes of its input stream are US-ASCII, the encoding
     * is "7bit". If there is even one non-US-ASCII character, the
     * encoding is "base64".
     * </ul>
     *
     * @param   ds      DataSource
     * @return          the encoding. This is either "7bit",
     *                  "quoted-printable" or "base64"
     */
public static String getEncoding(DataSource ds) {
    ContentType cType = null;
    InputStream is = null;
    String encoding = null;
    try {
        cType = new ContentType(ds.getContentType());
        is = ds.getInputStream();
    } catch (Exception ex) {
        return "base64";
    }
    boolean isText = cType.match("text/*");
    // if not text, stop processing when we see non-ASCII
    int i = checkAscii(is, ALL, !isText);
    switch(i) {
        case ALL_ASCII:
            // all ascii
            encoding = "7bit";
            break;
        case MOSTLY_ASCII:
            // mostly ascii
            encoding = "quoted-printable";
            break;
        default:
            // mostly binary
            encoding = "base64";
            break;
    }
    // Close the input stream
    try {
        is.close();
    } catch (IOException ioex) {
    }
    return encoding;
}
Example 3
Project: jaxws-master  File: Issue671Test.java View source code
protected void setUp() throws Exception {
    mtom_proxy = new HelloService().getHelloPort(new MTOMFeature());
    no_mtom_proxy = new HelloService().getHelloPort();
    provider_proxy = new HelloService().getHelloProviderPort(new MTOMFeature());
    String helloPortAddress = (String) ((BindingProvider) mtom_proxy).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
    QName serviceName = new QName("http://example.org/mtom", "Hello");
    QName portName = new QName("http://example.org/mtom", "HelloPort");
    Service service = Service.create(serviceName);
    service.addPort(portName, HTTPBinding.HTTP_BINDING, helloPortAddress);
    dispatch = service.createDispatch(portName, DataSource.class, Service.Mode.MESSAGE);
}
Example 4
Project: VaadinUtils-master  File: JasperManager.java View source code
@Override
public void run() {
    JRSwapFileVirtualizer fileVirtualizer = null;
    CleanupCallback cleanupCallback = null;
    boolean initialized = false;
    try {
        logger.warn("{} permits are available", concurrentLimit.availablePermits());
        concurrentLimit.acquire();
        initialized = true;
        inQueue = false;
        queueEntry.setStatus("Gathering report data phase 1");
        reportProperties.initDBConnection();
        cleanupCallback = reportProperties.getCleanupCallback();
        List<ReportParameter<?>> extraParams = reportProperties.prepareData(params, reportProperties.getReportFileName(), cleanupCallback);
        compileReport();
        if (reportProperties.getCustomReportParameterMap() != null) {
            boundParams.putAll(reportProperties.getCustomReportParameterMap());
        }
        if (extraParams != null) {
            params.removeAll(extraParams);
            params.addAll(extraParams);
        }
        logger.info("Running report " + reportProperties.getReportFileName());
        for (ReportParameter<?> param : params) {
            for (String parameterName : param.getParameterNames()) {
                bindParameter(param, parameterName);
                if (param.displayInreport()) {
                    // populate dynamically added parameters to display user
                    // friendly parameters on the report
                    boundParams.put("ParamDisplay-" + parameterName, param.getDisplayValue(parameterName));
                }
                logger.info(parameterName + " " + param.getValue(parameterName));
            }
        }
        reportProperties.prepareForOutputFormat(exportMethod);
        CustomJRHyperlinkProducerFactory.setUseCustomHyperLinks(true);
        @SuppressWarnings("rawtypes") JRAbstractExporter exporter = null;
        queueEntry.setStatus("Gathering report data phase 2");
        // use file virtualizer to prevent out of heap
        String fileName = "/tmp";
        JRSwapFile file = new JRSwapFile(fileName, 100, 10);
        fileVirtualizer = new JRSwapFileVirtualizer(500, file);
        boundParams.put(JRParameter.REPORT_VIRTUALIZER, fileVirtualizer);
        if (stop) {
            return;
        }
        if (exportMethod == OutputFormat.CSV) {
            boundParams.put(JRParameter.IS_IGNORE_PAGINATION, true);
        }
        JasperPrint jasper_print = fillReport(exportMethod);
        switch(exportMethod) {
            case HTML:
                {
                    exporter = new JRHtmlExporter();
                    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasper_print);
                    exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, images);
                    if (VaadinServlet.getCurrent() != null) {
                        String context = VaadinServlet.getCurrent().getServletContext().getContextPath();
                        int contextIndex = Page.getCurrent().getLocation().toString().lastIndexOf(context);
                        String baseurl = Page.getCurrent().getLocation().toString().substring(0, contextIndex + context.length() + 1);
                        String imageUrl = baseurl + "VaadinJasperPrintServlet?image=";
                        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl);
                    } else {
                        logger.warn("Vaadin Servlet doens't have a current context");
                    }
                    break;
                }
            case PDF:
                {
                    exporter = new JRPdfExporter();
                    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasper_print);
                    break;
                }
            case CSV:
                {
                    exporter = new JRCsvExporter();
                    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasper_print);
                    break;
                }
            default:
                {
                    throw new RuntimeException("Unsupported export option " + exportMethod);
                }
        }
        imagesrcs = (images.size() <= 0) ? null : new DataSource[images.size()];
        if (imagesrcs != null) {
            int xi = 0;
            for (Map.Entry<String, byte[]> entry : images.entrySet()) {
                ByteArrayDataSource image = new ByteArrayDataSource(entry.getValue(), "image/gif");
                image.setName(entry.getKey());
                imagesrcs[xi++] = image;
            }
        }
        if (stop) {
            return;
        }
        createPageProgressMonitor(exporter);
        queueEntry.setStatus("Waiting for browser to start streaming");
        progressListener.outputStreamReady();
        if (readerReady.await(10, TimeUnit.SECONDS)) {
            outputStream = new PipedOutputStream(inputStream);
            writerReady.countDown();
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
            exporter.exportReport();
        } else {
            logger.error("Couldn't attach to reader stream");
        }
        Thread.sleep(750);
        queueEntry.setStatus("Cleaning up");
    } catch (Exception e) {
        logger.error(e, e);
    } finally {
        if (queueEntry != null) {
            jobQueue.remove(queueEntry);
            queueEntry = null;
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            logger.error(e, e);
        }
        if (cleanupCallback != null) {
            try {
                cleanupCallback.cleanup();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
        if (fileVirtualizer != null) {
            try {
                fileVirtualizer.cleanup();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
        CustomJRHyperlinkProducerFactory.setUseCustomHyperLinks(false);
        if (initialized) {
            concurrentLimit.release();
            try {
                reportProperties.closeDBConnection();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
        completeBarrier.countDown();
        if (progressListener != null) {
            progressListener.completed();
        }
    }
}
Example 5
Project: milton2-master  File: StandardMessageFactoryImpl.java View source code
private void addHtmlToMime(Part part, StandardMessage sm) throws MessagingException {
    // need to use a javax.activation.DataSource (!) to set a text
    // with content type "text/html"
    //			part.setDataHandler(new DataHandler(
    //			    new DataSource() {
    //						public InputStream getInputStream() throws IOException {
    //							return new ByteArrayInputStream(encoding != null ? text.getBytes(encoding) : text.getBytes());
    //						}
    //						public OutputStream getOutputStream() throws IOException {
    //							throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
    //						}
    //						public String getContentType() {
    //							return "text/html";
    //						}
    //						public String getName() {
    //							return "text";
    //						}
    //			    }
    //			));
    List<Attachment> htmlInline = findInlineAttachments(sm);
    if (htmlInline == null || htmlInline.isEmpty()) {
        part.setContent(sm.getHtml(), "text/html; charset=\"utf-8\"");
    } else {
        MimeMultipart related = new MimeMultipart("related");
        part.setContent(related);
        BodyPart bpHtml = new MimeBodyPart();
        bpHtml.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
        bpHtml.setContent(sm.getHtml(), "text/plain; charset=\"utf-8\"");
        related.addBodyPart(bpHtml);
        for (Attachment att : htmlInline) {
            addAttachmentToMime(related, att);
        }
    }
}
Example 6
Project: spring-framework-2.5.x-master  File: MimeMessageHelper.java View source code
/**
	 * Add an inline element to the MimeMessage, taking the content from a
	 * <code>javax.activation.DataSource</code>.
	 * <p>Note that the InputStream returned by the DataSource implementation
	 * needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
	 * <code>getInputStream()</code> multiple times.
	 * <p><b>NOTE:</b> Invoke <code>addInline</code> <i>after</i> [email protected] #setText};
	 * else, mail readers might not be able to resolve inline references correctly.
	 * @param contentId the content ID to use. Will end up as "Content-ID" header
	 * in the body part, surrounded by angle brackets: e.g. "myId" -> "<myId>".
	 * Can be referenced in HTML source via src="cid:myId" expressions.
	 * @param dataSource the <code>javax.activation.DataSource</code> to take
	 * the content from, determining the InputStream and the content type
	 * @throws MessagingException in case of errors
	 * @see #addInline(String, java.io.File)
	 * @see #addInline(String, org.springframework.core.io.Resource)
	 */
public void addInline(String contentId, DataSource dataSource) throws MessagingException {
    Assert.notNull(contentId, "Content ID must not be null");
    Assert.notNull(dataSource, "DataSource must not be null");
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setDisposition(MimeBodyPart.INLINE);
    // We're using setHeader here to remain compatible with JavaMail 1.2,
    // rather than JavaMail 1.3's setContentID.
    mimeBodyPart.setHeader(HEADER_CONTENT_ID, "<" + contentId + ">");
    mimeBodyPart.setDataHandler(new DataHandler(dataSource));
    getMimeMultipart().addBodyPart(mimeBodyPart);
}
Example 7
Project: wso2-synapse-master  File: FIXUtils.java View source code
/**
     * FIX messages are non-XML. So convert them into XML using the AXIOM API.
     * Put the FIX message into an Axis2 MessageContext.The basic format of the
     * generated SOAP envelope;
     * <p/>
     * <soapEnvelope>
     * <soapBody>
     * <message>
     * <header> ....</header>
     * <body> .... </body>
     * <trailer> .... </trailer>
     * </message>
     * </soapBody>
     * </soapEnvelope>
     *
     * @param message   the FIX message
     * @param counter   application level sequence number of the message
     * @param sessionID the incoming session
     * @param msgCtx    the Axis2 MessageContext to hold the FIX message
     * @throws AxisFault the exception thrown when invalid soap envelopes are set to the msgCtx
     */
public void setSOAPEnvelope(Message message, int counter, String sessionID, MessageContext msgCtx) throws AxisFault {
    if (log.isDebugEnabled()) {
        log.debug("Creating SOAP envelope for FIX message...");
    }
    SOAPFactory soapFactory = new SOAP11Factory();
    OMElement msg = soapFactory.createOMElement(FIXConstants.FIX_MESSAGE, null);
    msg.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_MESSAGE_INCOMING_SESSION, null, sessionID));
    msg.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_MESSAGE_COUNTER, null, String.valueOf(counter)));
    OMElement header = soapFactory.createOMElement(FIXConstants.FIX_HEADER, null);
    OMElement body = soapFactory.createOMElement(FIXConstants.FIX_BODY, null);
    OMElement trailer = soapFactory.createOMElement(FIXConstants.FIX_TRAILER, null);
    //process FIX header
    Iterator<Field<?>> iter = message.getHeader().iterator();
    if (iter != null) {
        while (iter.hasNext()) {
            Field<?> field = iter.next();
            OMElement msgField = soapFactory.createOMElement(FIXConstants.FIX_FIELD, null);
            msgField.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_FIELD_ID, null, String.valueOf(field.getTag())));
            Object value = field.getObject();
            if (value instanceof byte[]) {
                DataSource dataSource = new ByteArrayDataSource((byte[]) value);
                DataHandler dataHandler = new DataHandler(dataSource);
                String contentID = msgCtx.addAttachment(dataHandler);
                OMElement binaryData = soapFactory.createOMElement(FIXConstants.FIX_BINARY_FIELD, null);
                String binaryCID = "cid:" + contentID;
                binaryData.addAttribute(FIXConstants.FIX_MESSAGE_REFERENCE, binaryCID, null);
                msgField.addChild(binaryData);
            } else {
                createOMText(soapFactory, msgField, value.toString());
            }
            header.addChild(msgField);
        }
    }
    //process FIX body
    convertFIXBodyToXML(message, body, soapFactory, msgCtx);
    //process FIX trailer
    iter = message.getTrailer().iterator();
    if (iter != null) {
        while (iter.hasNext()) {
            Field<?> field = iter.next();
            OMElement msgField = soapFactory.createOMElement(FIXConstants.FIX_FIELD, null);
            msgField.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_FIELD_ID, null, String.valueOf(field.getTag())));
            Object value = field.getObject();
            if (value instanceof byte[]) {
                DataSource dataSource = new ByteArrayDataSource((byte[]) value);
                DataHandler dataHandler = new DataHandler(dataSource);
                String contentID = msgCtx.addAttachment(dataHandler);
                OMElement binaryData = soapFactory.createOMElement(FIXConstants.FIX_BINARY_FIELD, null);
                String binaryCID = "cid:" + contentID;
                binaryData.addAttribute(FIXConstants.FIX_MESSAGE_REFERENCE, binaryCID, null);
                msgField.addChild(binaryData);
            } else {
                createOMText(soapFactory, msgField, value.toString());
            }
            trailer.addChild(msgField);
        }
    }
    msg.addChild(header);
    msg.addChild(body);
    msg.addChild(trailer);
    SOAPEnvelope envelope = soapFactory.getDefaultEnvelope();
    envelope.getBody().addChild(msg);
    msgCtx.setEnvelope(envelope);
}
Example 8
Project: HR-WebServices-Examples-Java-master  File: SWAClient.java View source code
public static void transferFile(File file, String destinationFile) throws Exception {
    Options options = new Options();
    options.setTo(targetEPR);
    options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
    options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    // Increase the time out when sending large attachments
    options.setTimeOutInMilliSeconds(10000);
    options.setTo(targetEPR);
    options.setAction("urn:uploadFile");
    // assume the use runs this sample at
    // <axis2home>/samples/soapwithattachments/ dir
    ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem("../../repository", null);
    ServiceClient sender = new ServiceClient(configContext, null);
    sender.setOptions(options);
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);
    MessageContext mc = new MessageContext();
    FileDataSource fileDataSource = new FileDataSource(file);
    // Create a dataHandler using the fileDataSource. Any implementation of
    // javax.activation.DataSource interface can fit here.
    DataHandler dataHandler = new DataHandler(fileDataSource);
    String attachmentID = mc.addAttachment(dataHandler);
    SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
    SOAPEnvelope env = fac.getDefaultEnvelope();
    OMNamespace omNs = fac.createOMNamespace("http://service.soapwithattachments.sample", "swa");
    OMElement uploadFile = fac.createOMElement("uploadFile", omNs);
    OMElement nameEle = fac.createOMElement("name", omNs);
    nameEle.setText(destinationFile);
    OMElement idEle = fac.createOMElement("attchmentID", omNs);
    idEle.setText(attachmentID);
    uploadFile.addChild(nameEle);
    uploadFile.addChild(idEle);
    env.getBody().addChild(uploadFile);
    mc.setEnvelope(env);
    mepClient.addMessageContext(mc);
    mepClient.execute(true);
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
    SOAPBody body = response.getEnvelope().getBody();
    OMElement element = body.getFirstElement().getFirstChildWithName(new QName("http://service.soapwithattachments.sample", "return"));
    System.out.println(element.getText());
}
Example 9
Project: dk-master  File: MailNotifyServiceImpl.java View source code
protected void sendContext(MimeMessage msg, NotifyDo message) throws MessagingException {
    // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
    Multipart multipart = new MimeMultipart();
    // 设置邮件的文本内容
    BodyPart contentPart = new MimeBodyPart();
    contentPart.setText(message.MESSAGE_CONTEXT);
    multipart.addBodyPart(contentPart);
    // 添加附件
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(message.getFilePath());
    // 添加附件的内容
    messageBodyPart.setDataHandler(new DataHandler(source));
    // 添加附件的标题
    // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
    sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
    messageBodyPart.setFileName("=?UTF-8?B?" + enc.encode((message.getFileName() + ".xls").getBytes()) + "?=");
    multipart.addBodyPart(messageBodyPart);
    msg.setContent(multipart);
    msg.saveChanges();
}
Example 10
Project: gcontact-excel-sync-master  File: GDataContentHandler.java View source code
@SuppressWarnings("unchecked")
public Object getContent(DataSource ds) throws IOException {
    // Get the input properties to use when parsing content
    InputProperties inputProperties = getThreadInputProperties();
    // Find the parser to handle the input content type
    ContentType contentType = new ContentType(ds.getContentType());
    AltRegistry altRegistry = inputProperties.getAltRegistry();
    AltFormat altFormat = altRegistry.lookupType(contentType);
    InputParser<?> parser = altRegistry.getParser(altFormat);
    if (parser == null) {
        throw new IOException("Invalid multipart content: " + contentType);
    }
    try {
        return parseAtom(parser, ds.getInputStream(), contentType, inputProperties, inputProperties.getRootType());
    } catch (ServiceException se) {
        IOException ioe = new IOException("Error parsing content");
        ioe.initCause(se);
        throw ioe;
    }
}
Example 11
Project: resin-master  File: ServiceDelegateImpl.java View source code
public <T> Dispatch<T> createDispatch(QName portName, Class<T> type, Service.Mode mode) throws WebServiceException {
    PortInfoImpl port = _portMap.get(portName);
    String bindingId = SOAPBinding.SOAP11HTTP_BINDING;
    String endpointAddress = null;
    if (port != null) {
        bindingId = port.getBindingID();
        endpointAddress = port.getEndpointAddress();
    }
    if (endpointAddress == null)
        endpointAddress = findEndpointAddress();
    Dispatch<T> dispatch = null;
    Binding binding = getBinding(bindingId);
    if (_handlerResolver != null)
        binding.setHandlerChain(_handlerResolver.getHandlerChain(port));
    if (Source.class.equals(type)) {
        dispatch = (Dispatch<T>) new SourceDispatch(bindingId, binding, mode, _executor);
    } else if (SOAPMessage.class.equals(type)) {
        dispatch = (Dispatch<T>) new SOAPMessageDispatch(bindingId, binding, mode, _executor);
    } else if (DataSource.class.equals(type)) {
        dispatch = (Dispatch<T>) new DataSourceDispatch(bindingId, binding, mode, _executor);
    }
    if (dispatch == null) {
        throw new WebServiceException(L.l("{0} is an unsupported Dispatch type", type));
    }
    if (endpointAddress != null) {
        Map<String, Object> requestContext = dispatch.getRequestContext();
        requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointAddress);
    }
    return dispatch;
}
Example 12
Project: classlib6-master  File: MessageImpl.java View source code
private void init(MimeHeaders headers, int stat, final ContentType contentType, final InputStream in) throws SOAPExceptionImpl {
    this.headers = headers;
    try {
        // Set isFastInfoset/acceptFastInfoset flag based on MIME type
        if ((stat & FI_ENCODED_FLAG) > 0) {
            isFastInfoset = acceptFastInfoset = true;
        }
        // If necessary, inspect Accept header to set acceptFastInfoset
        if (!isFastInfoset) {
            String[] values = headers.getHeader("Accept");
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    StringTokenizer st = new StringTokenizer(values[i], ",");
                    while (st.hasMoreTokens()) {
                        final String token = st.nextToken().trim();
                        if (token.equalsIgnoreCase("application/fastinfoset") || token.equalsIgnoreCase("application/soap+fastinfoset")) {
                            acceptFastInfoset = true;
                            break;
                        }
                    }
                }
            }
        }
        if (!isCorrectSoapVersion(stat)) {
            log.log(Level.SEVERE, "SAAJ0533.soap.incorrect.Content-Type", new String[] { contentType.toString(), getExpectedContentType() });
            throw new SOAPVersionMismatchException("Cannot create message: incorrect content-type for SOAP version. Got: " + contentType + " Expected: " + getExpectedContentType());
        }
        if ((stat & PLAIN_XML_FLAG) != 0) {
            if (isFastInfoset) {
                getSOAPPart().setContent(FastInfosetReflection.FastInfosetSource_new(in));
            } else {
                initCharsetProperty(contentType);
                getSOAPPart().setContent(new StreamSource(in));
            }
        } else if ((stat & MIME_MULTIPART_FLAG) != 0) {
            DataSource ds = new DataSource() {

                public InputStream getInputStream() {
                    return in;
                }

                public OutputStream getOutputStream() {
                    return null;
                }

                public String getContentType() {
                    return contentType.toString();
                }

                public String getName() {
                    return "";
                }
            };
            multiPart = null;
            if (switchOffBM) {
                multiPart = new MimeMultipart(ds, contentType);
            } else {
                multiPart = new BMMimeMultipart(ds, contentType);
            }
            String startParam = contentType.getParameter("start");
            MimeBodyPart soapMessagePart = null;
            String contentID = null;
            if (switchOffBM || switchOffLazyAttachment) {
                if (startParam == null) {
                    soapMessagePart = multiPart.getBodyPart(0);
                    for (int i = 1; i < multiPart.getCount(); i++) {
                        initializeAttachment(multiPart, i);
                    }
                } else {
                    soapMessagePart = multiPart.getBodyPart(startParam);
                    for (int i = 0; i < multiPart.getCount(); i++) {
                        contentID = multiPart.getBodyPart(i).getContentID();
                        if (!contentID.equals(startParam))
                            initializeAttachment(multiPart, i);
                    }
                }
            } else {
                BMMimeMultipart bmMultipart = (BMMimeMultipart) multiPart;
                InputStream stream = bmMultipart.initStream();
                SharedInputStream sin = null;
                if (stream instanceof SharedInputStream) {
                    sin = (SharedInputStream) stream;
                }
                String boundary = "--" + contentType.getParameter("boundary");
                byte[] bndbytes = ASCIIUtility.getBytes(boundary);
                if (startParam == null) {
                    soapMessagePart = bmMultipart.getNextPart(stream, bndbytes, sin);
                    bmMultipart.removeBodyPart(soapMessagePart);
                } else {
                    MimeBodyPart bp = null;
                    try {
                        while (!startParam.equals(contentID)) {
                            bp = bmMultipart.getNextPart(stream, bndbytes, sin);
                            contentID = bp.getContentID();
                        }
                        soapMessagePart = bp;
                        bmMultipart.removeBodyPart(bp);
                    } catch (Exception e) {
                        throw new SOAPExceptionImpl(e);
                    }
                }
            }
            ContentType soapPartCType = new ContentType(soapMessagePart.getContentType());
            initCharsetProperty(soapPartCType);
            String baseType = soapPartCType.getBaseType().toLowerCase();
            if (!(isEqualToSoap1_1Type(baseType) || isEqualToSoap1_2Type(baseType) || isSOAPBodyXOPPackage(soapPartCType))) {
                log.log(Level.SEVERE, "SAAJ0549.soap.part.invalid.Content-Type", new Object[] { baseType });
                throw new SOAPExceptionImpl("Bad Content-Type for SOAP Part : " + baseType);
            }
            SOAPPart soapPart = getSOAPPart();
            setMimeHeaders(soapPart, soapMessagePart);
            soapPart.setContent(isFastInfoset ? (Source) FastInfosetReflection.FastInfosetSource_new(soapMessagePart.getInputStream()) : (Source) new StreamSource(soapMessagePart.getInputStream()));
        } else {
            log.severe("SAAJ0534.soap.unknown.Content-Type");
            throw new SOAPExceptionImpl("Unrecognized Content-Type");
        }
    } catch (Throwable ex) {
        log.severe("SAAJ0535.soap.cannot.internalize.message");
        throw new SOAPExceptionImpl("Unable to internalize message", ex);
    }
    needsSave();
}
Example 13
Project: aipo-master  File: ALSmtpMailSender.java View source code
/**
   * 新規作成のメールを取得します。
   * 
   * @param mcontext
   * @return
   */
private ALLocalMailMessage createMessage(ALSmtpMailContext mcontext) {
    System.setProperty("mail.mime.charset", "ISO-2022-JP");
    System.setProperty("mail.mime.decodetext.strict", "false");
    ALLocalMailMessage msg = null;
    smtpServerProp = new Properties();
    smtpServerProp.setProperty(MAIL_SMTP_HOST, scontext.getSmtpHost());
    smtpServerProp.setProperty(MAIL_SMTP_PORT, scontext.getSmtpPort());
    smtpServerProp.put(MAIL_SMTP_CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
    smtpServerProp.put(MAIL_SMTP_TIMEOUT, TIMEOUT);
    smtpServerProp.setProperty("mail.mime.address.strict", "false");
    smtpServerProp.put("mail.smtp.localhost", "localhost");
    if (scontext.getEncryptionFlag() == ENCRYPTION_SEND_SSL) {
        /** SSL 暗号化 */
        smtpServerProp.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        smtpServerProp.setProperty("mail.smtp.socketFactory.fallback", "false");
        smtpServerProp.setProperty("mail.smtp.socketFactory.port", scontext.getSmtpPort());
    }
    // SMTP サーバのアドレスをセット
    if (scontext.getAuthSendFlag() == AUTH_SEND_SMTP_AUTH && scontext.getAuthSendUserId() != null && !"".equals(scontext.getAuthSendUserId()) && scontext.getAuthSendUserPassword() != null && !"".equals(scontext.getAuthSendUserPassword())) {
        /** SMTP AUTH */
        smtpServerProp.put("mail.smtp.auth", "true");
        session = Session.getInstance(smtpServerProp, new ALSmtpAuth(scontext.getAuthSendUserId(), scontext.getAuthSendUserPassword()));
    } else {
        session = Session.getInstance(smtpServerProp, null);
    }
    try {
        // メッセージを生成
        msg = new ALLocalMailMessage(session);
        // 送信元メールアドレスと送信者名をセット
        msg.setFrom(new InternetAddress(mcontext.getFrom(), ALMailUtils.encodeWordJIS(mcontext.getName())));
        // メールのあて先(to)をセット
        if (mcontext.getTo() == null) {
            throw new MessagingException();
        }
        setRecipient(msg, Message.RecipientType.TO, mcontext.getTo());
        // メールのあて先(cc)をセット
        if (mcontext.getCc() != null) {
            setRecipient(msg, Message.RecipientType.CC, mcontext.getCc());
        }
        // メールのあて先(bcc)をセット
        if (mcontext.getBcc() != null) {
            setRecipient(msg, Message.RecipientType.BCC, mcontext.getBcc());
        }
        // メールの件名をセット
        msg.setSubject(ALMailUtils.encodeWordJIS(mcontext.getSubject()));
        // メールの送信日時をセット
        msg.setSentDate(new Date());
        if (mcontext.getFilePaths() == null) {
            // メールの本文をセット
            msg.setText(mcontext.getMsgText() + "\r\n", CHARSET_ISO2022JP);
            setHeader(msg, mcontext);
        } else {
            String[] checkedFilePaths = mcontext.getFilePaths();
            int checkedFilePathsLength = checkedFilePaths.length;
            if (checkedFilePathsLength <= 0) {
                // MultiPart にせず,メールの本文をセット
                msg.setText(mcontext.getMsgText() + "\r\n", CHARSET_ISO2022JP);
                setHeader(msg, mcontext);
            } else {
                setHeader(msg, mcontext);
                // 複数のボディを格納するマルチパートオブジェクトを生成
                Multipart multiPart = new MimeMultipart();
                // テキストのボディパートを作成
                MimeBodyPart mimeText = new MimeBodyPart();
                // メールの内容を指定
                mimeText.setText(mcontext.getMsgText(), CHARSET_ISO2022JP);
                // 1つ目のボディパートを追加
                multiPart.addBodyPart(mimeText);
                // 添付ファイルのボディパートを作成
                MimeBodyPart mimeFile = null;
                for (int i = 0; i < checkedFilePathsLength; i++) {
                    final String filePath = checkedFilePaths[i];
                    final String fileName = ALMailUtils.getFileNameFromText(checkedFilePaths[i]);
                    mimeFile = new MimeBodyPart();
                    mimeFile.setDataHandler(new DataHandler(new DataSource() {

                        @Override
                        public String getContentType() {
                            return FileTypeMap.getDefaultFileTypeMap().getContentType(fileName);
                        }

                        @Override
                        public InputStream getInputStream() throws IOException {
                            return ALStorageService.getFile(filePath);
                        }

                        @Override
                        public String getName() {
                            return fileName;
                        }

                        @Override
                        public OutputStream getOutputStream() throws IOException {
                            throw new UnsupportedOperationException("getOutputStream");
                        }
                    }));
                    MailUtility.setFileName(mimeFile, ALMailUtils.getFileNameFromText(checkedFilePaths[i]), "ISO-2022-JP", null);
                    // 添付ファイルをボディパートに追加
                    multiPart.addBodyPart(mimeFile);
                }
                // マルチパートオブジェクトをメッセージに設定
                msg.setContent(multiPart);
            }
        }
    } catch (Exception e) {
        logger.error("ALSmtpMailSender.createMessage", e);
        return null;
    }
    return msg;
}
Example 14
Project: eclipselink.runtime-master  File: MOXyJsonProvider.java View source code
/**
     * @return true indicating that <i>MOXyJsonProvider</i> will
     * be used for the JSON binding if the media type is of the following
     * patterns */json or */*+json, and the type is not assignable from
     * any of (or a Collection or JAXBElement of) the following:
     * <ul>
     * <li>byte[]</li>
     * <li>java.io.File</li>
     * <li>java.io.InputStream</li>
     * <li>java.io.Reader</li>
     * <li>java.lang.Object</li>
     * <li>java.lang.String</li>
     * <li>javax.activation.DataSource</li>
     * </ul>
     */
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    if (!supportsMediaType(mediaType)) {
        return false;
    } else if (CoreClassConstants.APBYTE == type || CoreClassConstants.STRING == type) {
        return false;
    } else if (Map.class.isAssignableFrom(type)) {
        return false;
    } else if (File.class.isAssignableFrom(type)) {
        return false;
    } else if (DataSource.class.isAssignableFrom(type)) {
        return false;
    } else if (InputStream.class.isAssignableFrom(type)) {
        return false;
    } else if (Reader.class.isAssignableFrom(type)) {
        return false;
    } else if (Object.class == type) {
        return false;
    } else if (type.isPrimitive()) {
        return false;
    } else if (type.isArray() && (type.getComponentType().isArray() || type.getComponentType().isPrimitive() || type.getComponentType().getPackage().getName().startsWith("java."))) {
        return false;
    } else if (JAXBElement.class.isAssignableFrom(type)) {
        Set<Class<?>> domainClasses = getDomainClasses(genericType);
        for (Class<?> domainClass : domainClasses) {
            if (isReadable(domainClass, null, annotations, mediaType) || String.class == domainClass) {
                return true;
            }
        }
        return false;
    } else if (Collection.class.isAssignableFrom(type)) {
        Set<Class<?>> domainClasses = getDomainClasses(genericType);
        for (Class<?> domainClass : domainClasses) {
            if (isReadable(domainClass, null, annotations, mediaType) || String.class == domainClass) {
                return true;
            }
        }
        return false;
    } else {
        return null != getJAXBContext(type, genericType, annotations, mediaType);
    }
}
Example 15
Project: iaf-master  File: MailSender.java View source code
protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType, String messageBase64, String charset, Collection recipients, Collection attachments) throws SenderException {
    StringBuffer sb = new StringBuffer();
    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject + "] to #recipients [" + recipients.size() + "]");
    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }
    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }
    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }
        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }
        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Element recipientElement = (Element) iter.next();
            String recipient = XmlUtils.getStringValue(recipientElement);
            if (StringUtils.isNotEmpty(recipient)) {
                String typeAttr = recipientElement.getAttribute("type");
                Message.RecipientType recipientType = Message.RecipientType.TO;
                if ("cc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.CC;
                }
                if ("bcc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.BCC;
                }
                msg.addRecipient(recipientType, new InternetAddress(recipient));
                recipientsFound = true;
                if (log.isDebugEnabled()) {
                    sb.append("[recipient(" + typeAttr + ")=" + recipient + "]");
                }
            } else {
                log.debug("empty recipient found, ignoring");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }
        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");
        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);
            iter = attachments.iterator();
            while (iter.hasNext()) {
                Element attachmentElement = (Element) iter.next();
                String attachmentText = XmlUtils.getStringValue(attachmentElement);
                String attachmentName = attachmentElement.getAttribute("name");
                String attachmentUrl = attachmentElement.getAttribute("url");
                String attachmentType = attachmentElement.getAttribute("type");
                String attachmentBase64 = attachmentElement.getAttribute("base64");
                if (StringUtils.isEmpty(attachmentType)) {
                    attachmentType = getDefaultAttachmentType();
                }
                if (StringUtils.isEmpty(attachmentName)) {
                    attachmentName = getDefaultAttachmentName();
                }
                log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url [" + attachmentUrl + "]contents [" + attachmentText + "]");
                messageBodyPart = new MimeBodyPart();
                DataSource attachmentDataSource;
                if (!StringUtils.isEmpty(attachmentUrl)) {
                    attachmentDataSource = new URLDataSource(new URL(attachmentUrl));
                    messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource));
                }
                messageBodyPart.setFileName(attachmentName);
                if ("true".equalsIgnoreCase(attachmentBase64)) {
                    messageBodyPart.setDataHandler(decodeBase64(attachmentText));
                } else {
                    messageBodyPart.setText(attachmentText);
                }
                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }
        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}