Example usage for javax.mail Header getName

List of usage examples for javax.mail Header getName

Introduction

In this page you can find the example usage for javax.mail Header getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of this header.

Usage

From source file:org.apache.axis.attachments.MultiPartRelatedInputStream.java

/**
 * This will read streams in till the one that is needed is found.
 *
 * @param id id is the stream being sought.
 *
 * @return the part for the id/* w  ww.  j  ava  2  s .co m*/
 *
 * @throws org.apache.axis.AxisFault
 */
protected Part readTillFound(final String[] id) throws org.apache.axis.AxisFault {

    if (boundaryDelimitedStream == null) {
        return null; // The whole stream has been consumed already
    }

    Part ret = null;

    try {
        if (soapStreamBDS == boundaryDelimitedStream) { // 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 = new java.io.ByteArrayInputStream(soapdata.toByteArray());
            }

            boundaryDelimitedStream = boundaryDelimitedStream.getNextStream();
        }

        // Now start searching for the data.
        if (null != boundaryDelimitedStream) {
            do {
                String contentType = null;
                String contentId = null;
                String contentTransferEncoding = null;
                String contentLocation = null;

                // Read this attachments headers from the stream.
                javax.mail.internet.InternetHeaders headers = new javax.mail.internet.InternetHeaders(
                        boundaryDelimitedStream);

                contentId = headers.getHeader("Content-Id", null);

                if (contentId != null) {
                    contentId = contentId.trim();

                    if (contentId.startsWith("<")) {
                        contentId = contentId.substring(1);
                    }

                    if (contentId.endsWith(">")) {
                        contentId = contentId.substring(0, contentId.length() - 1);
                    }

                    //   if (!contentId.startsWith("cid:")) {
                    //       contentId = "cid:" + contentId;
                    //   }

                    contentId = contentId.trim();
                }

                contentType = headers.getHeader(HTTPConstants.HEADER_CONTENT_TYPE, null);

                if (contentType != null) {
                    contentType = contentType.trim();
                }

                contentLocation = headers.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION, null);

                if (contentLocation != null) {
                    contentLocation = contentLocation.trim();
                }

                contentTransferEncoding = headers.getHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING,
                        null);

                if (contentTransferEncoding != null) {
                    contentTransferEncoding = contentTransferEncoding.trim();
                }

                java.io.InputStream decodedStream = boundaryDelimitedStream;

                if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) {
                    decodedStream = MimeUtility.decode(decodedStream, contentTransferEncoding);
                }

                ManagedMemoryDataSource source = new ManagedMemoryDataSource(decodedStream,
                        ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, contentType, true);
                DataHandler dh = new DataHandler(source);
                AttachmentPart ap = new AttachmentPart(dh);

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

                if (contentLocation != null) {
                    ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, contentLocation);
                }

                for (java.util.Enumeration en = headers.getNonMatchingHeaders(
                        new String[] { HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_LOCATION,
                                HTTPConstants.HEADER_CONTENT_TYPE }); en.hasMoreElements();) {
                    javax.mail.Header header = (javax.mail.Header) en.nextElement();
                    String name = header.getName();
                    String value = header.getValue();

                    if ((name != null) && (value != null)) {
                        name = name.trim();

                        if (name.length() != 0) {
                            ap.addMimeHeader(name, value);
                        }
                    }
                }

                addPart(contentId, contentLocation, 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;
                    } else if ((contentLocation != null) && id[i].equals(contentLocation)) {
                        ret = ap;
                    }
                }

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

    return ret;
}

From source file:org.apache.camel.component.james.smtp.SMTPTest.java

/**
 * Test send matching message.//from  w  w  w.  ja v  a2 s  .  co m
 * 
 * @throws Exception
 *             the exception
 */
@SuppressWarnings("unchecked")
@Test
public void testSendMatchingMessage() throws Exception {
    String sender = "sender@localhost";
    String rcpt = "rcpt@localhost";
    String body = "Subject: test\r\n\r\nTestmail";
    SMTPClient client = new SMTPClient();
    client.connect("localhost", port);
    client.helo("localhost");
    client.setSender(sender);
    client.addRecipient(rcpt);

    client.sendShortMessageData(body);
    client.quit();
    client.disconnect();
    resultEndpoint.expectedMessageCount(1);
    resultEndpoint.expectedBodyReceived().body(InputStream.class);
    Exchange ex = resultEndpoint.getReceivedExchanges().get(0);
    Map<String, Object> headers = ex.getIn().getHeaders();
    assertEquals(sender, headers.get(MailEnvelopeMessage.SMTP_SENDER_ADRRESS));
    assertEquals(rcpt, headers.get(MailEnvelopeMessage.SMTP_RCPT_ADRRESS_LIST));

    // check type converter
    MimeMessage message = ex.getIn().getBody(MimeMessage.class);
    Enumeration<Header> mHeaders = message.getAllHeaders();
    Header header = null;
    while (mHeaders.hasMoreElements()) {
        header = mHeaders.nextElement();
        if (header.getName().equals("Subject")) {
            break;
        }
    }
    assertNotNull(header);
    assertEquals("Subject", header.getName());
    assertEquals(header.getValue(), "test");

    resultEndpoint.assertIsSatisfied();
}

From source file:org.apache.camel.component.mail.MailBinding.java

protected Map<String, Object> extractHeadersFromMail(Message mailMessage, Exchange exchange)
        throws MessagingException {
    Map<String, Object> answer = new HashMap<String, Object>();
    Enumeration names = mailMessage.getAllHeaders();

    while (names.hasMoreElements()) {
        Header header = (Header) names.nextElement();
        String value = header.getValue();
        if (headerFilterStrategy != null
                && !headerFilterStrategy.applyFilterToExternalHeaders(header.getName(), value, exchange)) {
            CollectionHelper.appendValue(answer, header.getName(), value);
        }/*from   ww w  .  j  av  a 2s . c o m*/
    }

    return answer;
}

From source file:org.apache.james.jdkim.mailets.DKIMSign.java

@SuppressWarnings("unchecked")
private void prependHeader(MimeMessage message, String signatureHeader) throws MessagingException {
    List<String> prevHeader = new LinkedList<String>();
    // read all the headers
    for (Enumeration<String> e = message.getAllHeaderLines(); e.hasMoreElements();) {
        String headerLine = e.nextElement();
        prevHeader.add(headerLine);// w w  w. ja  v  a  2  s .c  om
    }
    // remove all the headers
    for (Enumeration<Header> e = message.getAllHeaders(); e.hasMoreElements();) {
        Header header = e.nextElement();
        message.removeHeader(header.getName());
    }
    // add our header
    message.addHeaderLine(signatureHeader);
    // add the remaining headers using "addHeaderLine" that won't alter the
    // insertion order.
    for (Iterator<String> i = prevHeader.iterator(); i.hasNext();) {
        String header = i.next();
        message.addHeaderLine(header);
    }
}

From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java

/**
 * {@inheritDoc}//ww  w  . ja  v  a 2 s .  c om
 */
@Override
public SampleResult sample(Entry e) {
    SampleResult parent = new SampleResult();
    boolean isOK = false; // Did sample succeed?
    final boolean deleteMessages = getDeleteMessages();
    final String serverProtocol = getServerType();

    parent.setSampleLabel(getName());

    String samplerString = toString();
    parent.setSamplerData(samplerString);

    /*
     * Perform the sampling
     */
    parent.sampleStart(); // Start timing
    try {
        // Create empty properties
        Properties props = new Properties();

        if (isUseStartTLS()) {
            props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$
            if (isEnforceStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$
            }
        }

        if (isTrustAllCerts()) {
            if (isUseSSL()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        } else if (isUseLocalTrustStore()) {
            File truststore = new File(getTrustStoreToUse());
            log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                log.info("load local truststore -Failed to load truststore from: "
                        + truststore.getAbsolutePath());
                truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse());
                log.info("load local truststore -Attempting to read truststore from:  "
                        + truststore.getAbsolutePath());
                if (!truststore.exists()) {
                    log.info("load local truststore -Failed to load truststore from: "
                            + truststore.getAbsolutePath()
                            + ". Local truststore not available, aborting execution.");
                    throw new IOException("Local truststore file not found. Also not available under : "
                            + truststore.getAbsolutePath());
                }
            }
            if (isUseSSL()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ 
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        }

        // Get session
        Session session = Session.getInstance(props, null);

        // Get the store
        Store store = session.getStore(serverProtocol);
        store.connect(getServer(), getPortAsInt(), getUserName(), getPassword());

        // Get folder
        Folder folder = store.getFolder(getFolder());
        if (deleteMessages) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        final int messageTotal = folder.getMessageCount();
        int n = getNumMessages();
        if (n == ALL_MESSAGES || n > messageTotal) {
            n = messageTotal;
        }

        // Get directory
        Message[] messages = folder.getMessages(1, n);
        StringBuilder pdata = new StringBuilder();
        pdata.append(messages.length);
        pdata.append(" messages found\n");
        parent.setResponseData(pdata.toString(), null);
        parent.setDataType(SampleResult.TEXT);
        parent.setContentType("text/plain"); // $NON-NLS-1$

        final boolean headerOnly = getHeaderOnly();
        busy = true;
        for (Message message : messages) {
            StringBuilder cdata = new StringBuilder();
            SampleResult child = new SampleResult();
            child.sampleStart();

            cdata.append("Message "); // $NON-NLS-1$
            cdata.append(message.getMessageNumber());
            child.setSampleLabel(cdata.toString());
            child.setSamplerData(cdata.toString());
            cdata.setLength(0);

            final String contentType = message.getContentType();
            child.setContentType(contentType);// Store the content-type
            child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default
            child.setEncodingAndType(contentType);// Parse the content-type

            if (isStoreMimeMessage()) {
                // Don't save headers - they are already in the raw message
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                message.writeTo(bout);
                child.setResponseData(bout.toByteArray()); // Save raw message
                child.setDataType(SampleResult.TEXT);
            } else {
                @SuppressWarnings("unchecked") // Javadoc for the API says this is OK
                Enumeration<Header> hdrs = message.getAllHeaders();
                while (hdrs.hasMoreElements()) {
                    Header hdr = hdrs.nextElement();
                    String value = hdr.getValue();
                    try {
                        value = MimeUtility.decodeText(value);
                    } catch (UnsupportedEncodingException uce) {
                        // ignored
                    }
                    cdata.append(hdr.getName()).append(": ").append(value).append("\n");
                }
                child.setResponseHeaders(cdata.toString());
                cdata.setLength(0);
                if (!headerOnly) {
                    appendMessageData(child, message);
                }
            }

            if (deleteMessages) {
                message.setFlag(Flags.Flag.DELETED, true);
            }
            child.setResponseOK();
            if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called.
                child.sampleEnd();
            }
            parent.addSubResult(child);
        }

        // Close connection
        folder.close(true);
        store.close();

        parent.setResponseCodeOK();
        parent.setResponseMessageOK();
        isOK = true;
    } catch (NoClassDefFoundError | IOException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString());
    } catch (MessagingException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$
    } finally {
        busy = false;
    }

    if (parent.getEndTime() == 0) {// not been set by any child samples
        parent.sampleEnd();
    }
    parent.setSuccessful(isOK);
    return parent;
}

From source file:org.apache.jsieve.mailet.SieveMailboxMailet.java

/**
 * Delivers a mail to a local mailbox./*  www. jav a 2s.c om*/
 * 
 * @param mail
 *            the mail being processed
 * 
 * @throws MessagingException
 *             if an error occurs while storing the mail
 */
@SuppressWarnings("unchecked")
@Override
public void service(Mail mail) throws MessagingException {
    Collection<MailAddress> recipients = mail.getRecipients();
    Collection<MailAddress> errors = new Vector<MailAddress>();

    MimeMessage message = null;
    if (deliveryHeader != null || resetReturnPath) {
        message = mail.getMessage();
    }

    if (resetReturnPath) {
        // Set Return-Path and remove all other Return-Path headers from the
        // message
        // This only works because there is a placeholder inserted by
        // MimeMessageWrapper
        message.setHeader(RFC2822Headers.RETURN_PATH,
                (mail.getSender() == null ? "<>" : "<" + mail.getSender() + ">"));
    }

    Enumeration headers;
    InternetHeaders deliveredTo = new InternetHeaders();
    if (deliveryHeader != null) {
        // Copy any Delivered-To headers from the message
        headers = message.getMatchingHeaders(new String[] { deliveryHeader });
        while (headers.hasMoreElements()) {
            Header header = (Header) headers.nextElement();
            deliveredTo.addHeader(header.getName(), header.getValue());
        }
    }

    for (Iterator<MailAddress> i = recipients.iterator(); i.hasNext();) {
        MailAddress recipient = i.next();
        try {
            if (deliveryHeader != null) {
                // Add qmail's de facto standard Delivered-To header
                message.addHeader(deliveryHeader, recipient.toString());
            }

            storeMail(mail.getSender(), recipient, mail);

            if (deliveryHeader != null) {
                if (i.hasNext()) {
                    // Remove headers but leave all placeholders
                    message.removeHeader(deliveryHeader);
                    headers = deliveredTo.getAllHeaders();
                    // And restore any original Delivered-To headers
                    while (headers.hasMoreElements()) {
                        Header header = (Header) headers.nextElement();
                        message.addHeader(header.getName(), header.getValue());
                    }
                }
            }
        } catch (Exception ex) {
            log("Error while storing mail.", ex);
            errors.add(recipient);
        }
    }

    if (!errors.isEmpty()) {
        // If there were errors, we redirect the email to the ERROR
        // processor.
        // In order for this server to meet the requirements of the SMTP
        // specification, mails on the ERROR processor must be returned to
        // the sender. Note that this email doesn't include any details
        // regarding the details of the failure(s).
        // In the future we may wish to address this.
        getMailetContext().sendMail(mail.getSender(), errors, mail.getMessage(), Mail.ERROR);
    }
    if (consume) {
        // Consume this message
        mail.setState(Mail.GHOST);
    }
}

From source file:org.apache.jsieve.utils.SieveMailAdapter.java

/**
 * Parses the value from the given message into addresses.
 * //from   w  w  w . j a  v a2 s. co  m
 * @param headerName
 *            header name, to be matched case insensitively
 * @param message
 *            <code>Message</code>, not null
 * @return <code>Address</code> array, not null possibly empty
 * @throws SieveMailException
 */
public Address[] parseAddresses(final String headerName, final Message message) throws SieveMailException {
    try {
        final SieveAddressBuilder builder = new SieveAddressBuilder();

        for (Enumeration en = message.getAllHeaders(); en.hasMoreElements();) {
            final Header header = (Header) en.nextElement();
            final String name = header.getName();
            if (name.trim().equalsIgnoreCase(headerName)) {
                builder.addAddresses(header.getValue());
            }
        }

        final Address[] results = builder.getAddresses();
        return results;

    } catch (MessagingException ex) {
        throw new SieveMailException(ex);
    } catch (org.apache.jsieve.parser.generated.address.ParseException ex) {
        throw new SieveMailException(ex);
    }
}

From source file:org.apache.nifi.processors.email.ExtractEmailHeaders.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final ComponentLog logger = getLogger();

    final List<FlowFile> invalidFlowFilesList = new ArrayList<>();
    final List<FlowFile> processedFlowFilesList = new ArrayList<>();

    final FlowFile originalFlowFile = session.get();
    if (originalFlowFile == null) {
        return;//from ww w  . j a  va  2 s. co  m
    }

    final List<String> capturedHeadersList = Arrays
            .asList(context.getProperty(CAPTURED_HEADERS).getValue().toLowerCase().split(":"));

    final Map<String, String> attributes = new HashMap<>();
    session.read(originalFlowFile, new InputStreamCallback() {
        @Override
        public void process(final InputStream rawIn) throws IOException {
            try (final InputStream in = new BufferedInputStream(rawIn)) {
                Properties props = new Properties();
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage originalMessage = new MimeMessage(mailSession, in);
                MimeMessageParser parser = new MimeMessageParser(originalMessage).parse();
                // RFC-2822 determines that a message must have a "From:" header
                // if a message lacks the field, it is flagged as invalid
                Address[] from = originalMessage.getFrom();
                Date sentDate = originalMessage.getSentDate();
                if (from == null || sentDate == null) {
                    // Throws MessageException due to lack of minimum required headers
                    throw new MessagingException("Message failed RFC2822 validation");
                } else if (capturedHeadersList.size() > 0) {
                    Enumeration headers = originalMessage.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header header = (Header) headers.nextElement();
                        if (StringUtils.isNotEmpty(header.getValue())
                                && capturedHeadersList.contains(header.getName().toLowerCase())) {
                            attributes.put("email.headers." + header.getName().toLowerCase(),
                                    header.getValue());
                        }
                    }
                }
                if (Array.getLength(originalMessage.getAllRecipients()) > 0) {
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.TO)); toCount++) {
                        attributes.put(EMAIL_HEADER_TO + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.TO)[toCount].toString());
                    }
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.BCC)); toCount++) {
                        attributes.put(EMAIL_HEADER_BCC + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.BCC)[toCount].toString());
                    }
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.CC)); toCount++) {
                        attributes.put(EMAIL_HEADER_CC + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.CC)[toCount].toString());
                    }
                }
                // Incredibly enough RFC-2822 specified From as a "mailbox-list" so an array I returned by getFrom
                for (int toCount = 0; toCount < ArrayUtils.getLength(originalMessage.getFrom()); toCount++) {
                    attributes.put(EMAIL_HEADER_FROM + "." + toCount,
                            originalMessage.getFrom()[toCount].toString());
                }
                if (StringUtils.isNotEmpty(originalMessage.getMessageID())) {
                    attributes.put(EMAIL_HEADER_MESSAGE_ID, originalMessage.getMessageID());
                }
                if (originalMessage.getReceivedDate() != null) {
                    attributes.put(EMAIL_HEADER_RECV_DATE, originalMessage.getReceivedDate().toString());
                }
                if (originalMessage.getSentDate() != null) {
                    attributes.put(EMAIL_HEADER_SENT_DATE, originalMessage.getSentDate().toString());
                }
                if (StringUtils.isNotEmpty(originalMessage.getSubject())) {
                    attributes.put(EMAIL_HEADER_SUBJECT, originalMessage.getSubject());
                }
                // Zeroes EMAIL_ATTACHMENT_COUNT
                attributes.put(EMAIL_ATTACHMENT_COUNT, "0");
                // But insert correct value if attachments are present
                if (parser.hasAttachments()) {
                    attributes.put(EMAIL_ATTACHMENT_COUNT, String.valueOf(parser.getAttachmentList().size()));
                }

            } catch (Exception e) {
                // Message is invalid or triggered an error during parsing
                attributes.clear();
                logger.error("Could not parse the flowfile {} as an email, treating as failure",
                        new Object[] { originalFlowFile, e });
                invalidFlowFilesList.add(originalFlowFile);
            }
        }
    });

    if (attributes.size() > 0) {
        FlowFile updatedFlowFile = session.putAllAttributes(originalFlowFile, attributes);
        logger.info("Extracted {} headers into {} file", new Object[] { attributes.size(), updatedFlowFile });
        processedFlowFilesList.add(updatedFlowFile);
    }

    session.transfer(processedFlowFilesList, REL_SUCCESS);
    session.transfer(invalidFlowFilesList, REL_FAILURE);

}

From source file:org.apache.olingo.fit.AbstractServices.java

protected Response bodyPartRequest(final MimeBodyPart body, final Map<String, String> references)
        throws Exception {
    @SuppressWarnings("unchecked")
    final Enumeration<Header> en = body.getAllHeaders();

    Header header = en.nextElement();
    final String request = header.getName()
            + (StringUtils.isNotBlank(header.getValue()) ? ":" + header.getValue() : "");

    final Matcher matcher = REQUEST_PATTERN.matcher(request);
    final Matcher matcherRef = BATCH_REQUEST_REF_PATTERN.matcher(request);

    final MultivaluedMap<String, String> headers = new MultivaluedHashMap<String, String>();

    while (en.hasMoreElements()) {
        header = en.nextElement();/*from w  w w  .ja  v a 2s. c om*/
        headers.putSingle(header.getName(), header.getValue());
    }

    final Response res;
    final String url;
    final String method;

    if (matcher.find()) {
        url = matcher.group(2);
        method = matcher.group(1);
    } else if (matcherRef.find()) {
        url = references.get(matcherRef.group(2)) + matcherRef.group(3);
        method = matcherRef.group(1);
    } else {
        url = null;
        method = null;
    }

    if (url == null) {
        res = null;
    } else {
        final WebClient client = WebClient.create(url, "odatajclient", "odatajclient", null);
        client.headers(headers);

        if ("DELETE".equals(method)) {
            res = client.delete();
        } else {
            final InputStream is = body.getDataHandler().getInputStream();
            String content = IOUtils.toString(is);
            IOUtils.closeQuietly(is);

            final Matcher refs = REF_PATTERN.matcher(content);

            while (refs.find()) {
                content = content.replace(refs.group(1), references.get(refs.group(1)));
            }

            if ("PATCH".equals(method) || "MERGE".equals(method)) {
                client.header("X-HTTP-METHOD", method);
                res = client.invoke("POST", IOUtils.toInputStream(content));
            } else {
                res = client.invoke(method, IOUtils.toInputStream(content));
            }
        }

        // When updating to CXF 3.0.1, uncomment the following line, see CXF-5865
        //client.close();
    }

    return res;
}

From source file:org.apache.olingo.fit.Services.java

private Response bodyPartRequest(final MimeBodyPart body, final Map<String, String> references)
        throws Exception {
    @SuppressWarnings("unchecked")
    final Enumeration<Header> en = body.getAllHeaders();

    Header header = en.nextElement();
    final String request = header.getName()
            + (StringUtils.isNotBlank(header.getValue()) ? ":" + header.getValue() : "");

    final Matcher matcher = REQUEST_PATTERN.matcher(request);
    final Matcher matcherRef = BATCH_REQUEST_REF_PATTERN.matcher(request);

    final MultivaluedMap<String, String> headers = new MultivaluedHashMap<String, String>();

    while (en.hasMoreElements()) {
        header = en.nextElement();/*from   w  w w .j  a v a  2s . co  m*/
        headers.putSingle(header.getName(), header.getValue());
    }

    final Response res;
    final String url;
    final String method;

    if (matcher.find()) {
        url = matcher.group(2);
        method = matcher.group(1);
    } else if (matcherRef.find()) {
        url = references.get(matcherRef.group(2)) + matcherRef.group(3);
        method = matcherRef.group(1);
    } else {
        url = null;
        method = null;
    }

    if (url == null) {
        res = null;
    } else {
        final WebClient client = WebClient.create(url, "odatajclient", "odatajclient", null);
        client.headers(headers);

        if ("DELETE".equals(method)) {
            res = client.delete();
        } else {
            final InputStream is = body.getDataHandler().getInputStream();
            String content = IOUtils.toString(is);
            IOUtils.closeQuietly(is);

            final Matcher refs = REF_PATTERN.matcher(content);

            while (refs.find()) {
                content = content.replace(refs.group(1), references.get(refs.group(1)));
            }

            if ("PATCH".equals(method) || "MERGE".equals(method)) {
                client.header("X-HTTP-METHOD", method);
                res = client.invoke("POST", IOUtils.toInputStream(content));
            } else {
                res = client.invoke(method, IOUtils.toInputStream(content));
            }
        }

        // When updating to CXF 3.0.1, uncomment the following line, see CXF-5865
        // client.close();
    }

    return res;
}