Example usage for java.util Hashtable entrySet

List of usage examples for java.util Hashtable entrySet

Introduction

In this page you can find the example usage for java.util Hashtable entrySet.

Prototype

Set entrySet

To view the source code for java.util Hashtable entrySet.

Click Source Link

Usage

From source file:org.hyperic.hq.bizapp.server.session.EmailManagerImpl.java

@SuppressWarnings("unchecked")
public void sendFiltered(Integer platId) {
    Hashtable<EmailRecipient, FilterBuffer> cache;
    synchronized (_alertBuffer) {
        if (!_alertBuffer.containsKey(platId)) {
            return;
        }/* w  ww  . j a va 2 s  . c o m*/
        cache = (Hashtable<EmailRecipient, FilterBuffer>) _alertBuffer.remove(platId);
        if (cache == null || cache.size() == 0) {
            return;
        }
        // Insert key again so that we continue filtering
        _alertBuffer.put(platId, null);
    }

    AppdefEntityID platEntId = AppdefEntityID.newPlatformID(platId);
    String platName = resourceManager.getAppdefEntityName(platEntId);

    // The cache is organized by addresses
    for (Entry<EmailRecipient, FilterBuffer> ent : cache.entrySet()) {
        EmailRecipient addr = (EmailRecipient) ent.getKey();
        FilterBuffer msg = (FilterBuffer) ent.getValue();
        if (msg.getNumEnts() == 1 && addr.useHtml()) {
            sendEmail(new EmailRecipient[] { addr }, "[HQ] Filtered Notifications for " + platName,
                    new String[] { "" }, new String[] { msg.getHtml() }, null);
        } else {
            addr.setHtml(false);
            sendEmail(new EmailRecipient[] { addr }, "[HQ] Filtered Notifications for " + platName,
                    new String[] { msg.getText() }, new String[] { "" }, null);
        }
    }
}

From source file:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java

/**
 * Extracts info from message context.//from w w w. j  a v a  2 s .co  m
 * 
 * @param method
 *            Post method
 * @param httpClient
 *            The client used for posting
 * @param msgContext
 *            the message context
 * @param tmpURL
 *            the url to post to.
 * @throws Exception
 */
protected void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext,
        URL tmpURL) throws Exception {

    // optionally set a timeout for the request
    //      if (msgContext.getTimeout() != 0) {
    //         /* ISSUE: these are not the same, but MessageContext has only one
    //                   definition of timeout */
    //         // SO_TIMEOUT -- timeout for blocking reads
    //         httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
    //         // timeout for initial connection
    //         httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    //      }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; //$NON-NLS-1$

    if (action == null) {
        action = ""; //$NON-NLS-1$
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"")); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent"))); //$NON-NLS-1$
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\"); //$NON-NLS-1$
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
    }

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers. 
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            //HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            //Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                // let plug-ins using SOAP be able to set their own user-agent header (i.e. for tracking purposes)
                if (HTTPConstants.HEADER_USER_AGENT.equalsIgnoreCase(key)) {
                    method.setRequestHeader(key, value);
                } else {
                    method.addRequestHeader(key, value);
                }
            }
        }
    }
}

From source file:com.polarion.alm.ws.client.internal.connection.CommonsHTTPSender.java

/**
 * Extracts info from message context./*from  w  w w. j av  a2 s  . com*/
 * 
 * @param method
 *            Post method
 * @param httpClient
 *            The client used for posting
 * @param msgContext
 *            the message context
 * @param tmpURL
 *            the url to post to.
 * 
 * @throws Exception
 */
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /*
         * ISSUE: these are not the same, but MessageContext has only one
         * definition of timeout
         */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""));
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
    }

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            // Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addRequestHeader(key, value);
            }
        }
    }
}

From source file:org.evolizer.da4java.graph.data.EdgeGrouper.java

/**
 * Checks for all edges whether it represents an invocation or an
 * inheritance relationship. Then all edges of the same type are aggregated
 * Given lower level edges are removed and a high level edge with the
 * corresponding width representing the number of grouped/aggregated
 * lower edges is created.// w  ww. j  a va 2  s .  c om
 * 
 * @param edges The list of lower edges to aggregate.
 */
private void group(List<Edge> edges) {
    Hashtable<String, List<Edge>> typeToEdgeListMap = new Hashtable<String, List<Edge>>();

    // get list of lower level edges per edge type
    for (Edge edge : edges) {
        FamixAssociation association = fGraph.getGraphModelMapper().getAssociation(edge);
        if (association != null) {
            List<Edge> edgeList;
            if (typeToEdgeListMap.containsKey(association.getType())) {
                edgeList = typeToEdgeListMap.get(association.getType());
            } else {
                edgeList = new ArrayList<Edge>();
                typeToEdgeListMap.put(association.getType(), edgeList);
            }
            edgeList.add(edge);
        }
    }

    // create higher level edges per edge type
    for (Entry<String, List<Edge>> entry : typeToEdgeListMap.entrySet()) {
        createHighLevelEdges(aggregateEdges(entry.getValue()), entry.getKey());
    }
}

From source file:com.jaspersoft.ireport.jasperserver.ws.CommonsHTTPSender.java

/**
 * Extracts info from message context./*  ww w .  j av  a  2 s .  com*/
 *
 * @param method Post method
 * @param httpClient The client used for posting
 * @param msgContext the message context
 * @param tmpURL the url to post to.
 *
 * @throws Exception
 */
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /* ISSUE: these are not the same, but MessageContext has only one
              definition of timeout */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""));
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
    }

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers. 
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            //HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            //Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addRequestHeader(key, value);
            }
        }
    }
}

From source file:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.java

/**
* Extracts info from message context.//from w w w  .  j  a v a 2 s. com
* 
* @param method
*            Post method
* @param httpClient
*            The client used for posting
* @param msgContext
*            the message context
* @param tmpURL
*            the url to post to.
* 
* @throws Exception
*/
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /*
        * ISSUE: these are not the same, but MessageContext has only one
        * definition of timeout
        */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""));
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
    //method.setRequestHeader(
    //   new Header(HTTPConstants.HEADER_USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.5072)")
    //);

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();
    //System.out.println("ImageXChangeHttpCommonsSender setting credentials = '" + userID + ". " + passwd + "'");

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
        //System.out.println("ImageXChangeHttpCommonsSender setting credentials = '" + userID + ". " + passwd + "'");
    }

    // add compression headers if needed
    // if we accept GZIP then add the accept-encoding header
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        // accept both gzip and deflate if the gzip property is set
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING,
                HTTPConstants.COMPRESSION_GZIP + "," + COMPRESSION_DEFLATE);
        //method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, COMPRESSION_DEFLATE);
    }

    // if we will gzip the request then add the content-encoding header
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            // Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION))
                continue;
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addRequestHeader(key, value);
            }
        }
    }
}

From source file:org.mule.transport.soap.axis.extensions.MuleHttpSender.java

/**
 * Send the soap request message to the server
 *
 * @param msgContext message context//from  w  w  w.ja v  a2  s . c o m
 * @param tmpURL url to connect to
 * @param otherHeaders other headers if any
 * @param host host name
 * @param port port
 * @param useFullURL flag to indicate if the whole url needs to be sent
 * @throws IOException
 */
private InputStream writeToSocket(SocketHolder sockHolder, MessageContext msgContext, URL tmpURL,
        StringBuffer otherHeaders, String host, int port, int timeout, BooleanHolder useFullURL)
        throws Exception {

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        StringBuffer tmpBuf = new StringBuffer(64);
        tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd);
        otherHeaders.append(HTTPConstants.HEADER_AUTHORIZATION).append(": Basic ")
                .append(Base64.encode(tmpBuf.toString().getBytes())).append("\r\n");
    }

    // don't forget the cookies!
    // mmm... cookies
    if (msgContext.getMaintainSession()) {
        String cookie = msgContext.getStrProp(HTTPConstants.HEADER_COOKIE);
        String cookie2 = msgContext.getStrProp(HTTPConstants.HEADER_COOKIE2);

        if (cookie != null) {
            otherHeaders.append(HTTPConstants.HEADER_COOKIE).append(": ").append(cookie).append("\r\n");
        }
        if (cookie2 != null) {
            otherHeaders.append(HTTPConstants.HEADER_COOKIE2).append(": ").append(cookie2).append("\r\n");
        }
    }

    StringBuffer header2 = new StringBuffer(64);

    String webMethod = null;
    boolean posting = true;

    Message reqMessage = msgContext.getRequestMessage();

    boolean http10 = true; // True if this is to use HTTP 1.0 / false HTTP
    // 1.1
    boolean httpChunkStream = false; // Use HTTP chunking or not.
    boolean httpContinueExpected = false; // Under HTTP 1.1 if false you
    // *MAY* need to wait for a 100
    // rc,
    // if true the server MUST reply with 100 continue.
    String httpConnection = null;

    String httpver = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
    if (null == httpver) {
        httpver = HTTPConstants.HEADER_PROTOCOL_V10;
    }
    httpver = httpver.trim();
    if (httpver.equals(HTTPConstants.HEADER_PROTOCOL_V11)) {
        http10 = false;
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        if (null == otherHeaders) {
            otherHeaders = new StringBuffer(1024);
        }

        for (java.util.Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {

            java.util.Map.Entry me = (java.util.Map.Entry) e.next();
            Object keyObj = me.getKey();
            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING)) {
                if (!http10) {
                    String val = me.getValue().toString();
                    if (null != val
                            && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                        httpChunkStream = true;
                    }
                }
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION)) {
                if (!http10) {
                    String val = me.getValue().toString();
                    if (val.trim().equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION_CLOSE)) {
                        httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
                    }
                }
                // HTTP 1.0 will always close.
                // HTTP 1.1 will use persistent. //no need to specify
            } else {
                if (!http10 && key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)) {
                    String val = me.getValue().toString();
                    if (null != val && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                        httpContinueExpected = true;
                    }
                }

                otherHeaders.append(key).append(": ").append(me.getValue()).append("\r\n");
            }
        }
    }

    if (!http10) {
        // Force close for now.
        // TODO HTTP/1.1
        httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
    }

    header2.append(" ");
    header2.append(http10 ? HTTPConstants.HEADER_PROTOCOL_10 : HTTPConstants.HEADER_PROTOCOL_11).append("\r\n");
    MimeHeaders mimeHeaders = reqMessage.getMimeHeaders();

    if (posting) {
        String contentType;
        if (mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE) != null) {
            contentType = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE)[0];
        } else {
            contentType = reqMessage.getContentType(msgContext.getSOAPConstants());
        }
        header2.append(HTTPConstants.HEADER_CONTENT_TYPE).append(": ").append(contentType).append("\r\n");
    }

    header2.append(ACCEPT_HEADERS).append(HTTPConstants.HEADER_HOST)
            // used for virtual connections
            .append(": ").append(host).append((port == -1) ? ("") : (":" + port)).append("\r\n")
            .append(CACHE_HEADERS).append(HTTPConstants.HEADER_SOAP_ACTION)
            // The SOAP action.
            .append(": \"").append(action).append("\"\r\n");

    if (posting) {
        if (!httpChunkStream) {
            // Content length MUST be sent on HTTP 1.0 requests.
            header2.append(HTTPConstants.HEADER_CONTENT_LENGTH).append(": ")
                    .append(reqMessage.getContentLength()).append("\r\n");
        } else {
            // Do http chunking.
            header2.append(CHUNKED_HEADER);
        }
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            header2.append(mimeHeader.getName()).append(": ").append(mimeHeader.getValue()).append("\r\n");
        }
    }

    if (null != httpConnection) {
        header2.append(HTTPConstants.HEADER_CONNECTION);
        header2.append(": ");
        header2.append(httpConnection);
        header2.append("\r\n");
    }

    getSocket(sockHolder, msgContext, targetURL.getProtocol(), host, port, timeout, otherHeaders, useFullURL);

    if (null != otherHeaders) {
        // Add other headers to the end.
        // for pre java1.4 support, we have to turn the string buffer
        // argument into
        // a string before appending.
        header2.append(otherHeaders.toString());
    }

    header2.append("\r\n"); // The empty line to start the BODY.

    StringBuffer header = new StringBuffer(128);

    // If we're SOAP 1.2, allow the web method to be set from the
    // MessageContext.
    if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
        webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
    }
    if (webMethod == null) {
        webMethod = HTTPConstants.HEADER_POST;
    } else {
        posting = webMethod.equals(HTTPConstants.HEADER_POST);
    }

    header.append(webMethod).append(" ");
    if (useFullURL.value) {
        header.append(tmpURL.toExternalForm());
    } else {
        header.append(StringUtils.isEmpty(tmpURL.getFile()) ? "/" : tmpURL.getFile());
    }
    header.append(header2.toString());

    OutputStream out = sockHolder.getSocket().getOutputStream();

    if (!posting) {
        out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
        out.flush();
        return null;
    }

    InputStream inp = null;

    if (httpChunkStream || httpContinueExpected) {
        out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
    }

    if (httpContinueExpected) { // We need to get a reply from the server as
                                // to whether
                                // it wants us send anything more.
        out.flush();
        Hashtable cheaders = new Hashtable();
        inp = readHeadersFromSocket(sockHolder, msgContext, null, cheaders);
        int returnCode = -1;
        Integer Irc = (Integer) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
        if (null != Irc) {
            returnCode = Irc.intValue();
        }
        if (100 == returnCode) { // got 100 we may continue.
                                 // Need TODO a little msgContext house keeping....
            msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
            msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
        } else { // If no 100 Continue then we must not send anything!
            String statusMessage = (String) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);

            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            fault.setFaultDetailString(Messages.getMessage("return01", String.valueOf(returnCode), ""));
            throw fault;
        }
    }
    ByteArrayOutputStream baos = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("xmlSent00"));
        log.debug("---------------------------------------------------");
        baos = new ByteArrayOutputStream();
    }
    if (httpChunkStream) {
        ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(out);
        out = new BufferedOutputStream(chunkedOutputStream, Constants.HTTP_TXR_BUFFER_SIZE);
        try {
            if (baos != null) {
                out = new TeeOutputStream(out, baos);
            }
            reqMessage.writeTo(out);
        } catch (SOAPException e) {
            log.error(Messages.getMessage("exception00"), e);
        }
        out.flush();
        chunkedOutputStream.eos();
    } else {
        out = new BufferedOutputStream(out, Constants.HTTP_TXR_BUFFER_SIZE);
        try {
            if (!httpContinueExpected) {
                out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
            }
            if (baos != null) {
                out = new TeeOutputStream(out, baos);
            }
            reqMessage.writeTo(out);
        } catch (SOAPException e) {
            throw e;
        } finally {
            // Flush ONLY once.
            out.flush();
        }

    }

    if (log.isDebugEnabled() && baos != null) {
        log.debug(header + new String(baos.toByteArray()));
    }

    return inp;
}

From source file:org.alfresco.test.util.UserService.java

/**
 * Add dashlet to user dashboard//from  www.ja v a 2  s .  c  o  m
 * 
 * @param userName String identifier
 * @param password
 * @param dashlet
 * @param layout
 * @param column
 * @param position
 * @return true if the dashlet is added
 * @throws Exception if error
 */
public boolean addDashlet(final String userName, final String password, final UserDashlet dashlet,
        final DashletLayout layout, final int column, final int position) throws Exception {
    login(userName, password);
    AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject();
    String url = client.getAlfrescoUrl() + DashboardCustomization.ADD_DASHLET_URL;
    org.json.JSONObject body = new org.json.JSONObject();
    org.json.JSONArray array = new org.json.JSONArray();
    body.put("dashboardPage", "user/" + userName + "/dashboard");
    body.put("templateId", layout.id);

    // keep default dashlets
    Hashtable<String, String> defaultDashlets = new Hashtable<String, String>();
    defaultDashlets.put(UserDashlet.MY_SITES.id, "component-1-1");
    defaultDashlets.put(UserDashlet.MY_TASKS.id, "component-1-2");
    defaultDashlets.put(UserDashlet.MY_ACTIVITIES.id, "component-2-1");
    defaultDashlets.put(UserDashlet.MY_DOCUMENTS.id, "component-2-2");

    Iterator<Map.Entry<String, String>> entries = defaultDashlets.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry<String, String> entry = entries.next();
        org.json.JSONObject jDashlet = new org.json.JSONObject();
        jDashlet.put("url", entry.getKey());
        jDashlet.put("regionId", entry.getValue());
        jDashlet.put("originalRegionId", entry.getValue());
        array.put(jDashlet);
    }

    org.json.JSONObject newDashlet = new org.json.JSONObject();
    newDashlet.put("url", dashlet.id);
    String region = "component-" + column + "-" + position;
    newDashlet.put("regionId", region);
    array.put(newDashlet);
    body.put("dashlets", array);

    HttpPost post = new HttpPost(url);
    StringEntity se = new StringEntity(body.toString(), AlfrescoHttpClient.UTF_8_ENCODING);
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, AlfrescoHttpClient.MIME_TYPE_JSON));
    post.setEntity(se);
    try {
        HttpResponse response = client.executeRequest(post);
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            if (logger.isTraceEnabled()) {
                logger.trace("Dashlet " + dashlet.name + " was added on user: " + userName + " dashboard");
            }
            return true;
        } else {
            logger.error("Unable to add dashlet to user dashboard " + userName);
        }
    } finally {
        post.releaseConnection();
        client.close();
    }
    return false;
}

From source file:org.apache.axis.transport.http.HTTPSender.java

/**
 * Send the soap request message to the server
 *
 * @param msgContext message context/*from   w w w .  j av a2s  .  c  om*/
 * @param tmpURL url to connect to
 * @param otherHeaders other headers if any
 * @param host host name
 * @param port port
 * @param useFullURL flag to indicate if the whole url needs to be sent
 *
 * @throws IOException
 */
private InputStream writeToSocket(SocketHolder sockHolder, MessageContext msgContext, URL tmpURL,
        StringBuffer otherHeaders, String host, int port, int timeout, BooleanHolder useFullURL)
        throws Exception {

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        StringBuffer tmpBuf = new StringBuffer();

        tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd);
        otherHeaders.append(HTTPConstants.HEADER_AUTHORIZATION).append(": Basic ")
                .append(Base64.encode(tmpBuf.toString().getBytes())).append("\r\n");
    }

    // don't forget the cookies!
    // mmm... cookies
    if (msgContext.getMaintainSession()) {
        fillHeaders(msgContext, HTTPConstants.HEADER_COOKIE, otherHeaders);
        fillHeaders(msgContext, HTTPConstants.HEADER_COOKIE2, otherHeaders);
    }

    StringBuffer header2 = new StringBuffer();

    String webMethod = null;
    boolean posting = true;

    Message reqMessage = msgContext.getRequestMessage();

    boolean http10 = true; //True if this is to use HTTP 1.0 / false HTTP 1.1
    boolean httpChunkStream = false; //Use HTTP chunking or not.
    boolean httpContinueExpected = false; //Under HTTP 1.1 if false you *MAY* need to wait for a 100 rc,
                                          //  if true the server MUST reply with 100 continue.
    String httpConnection = null;

    String httpver = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
    if (null == httpver) {
        httpver = HTTPConstants.HEADER_PROTOCOL_V10;
    }
    httpver = httpver.trim();
    if (httpver.equals(HTTPConstants.HEADER_PROTOCOL_V11)) {
        http10 = false;
    }

    //process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        if (null == otherHeaders) {
            otherHeaders = new StringBuffer(1024);
        }

        for (java.util.Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {

            java.util.Map.Entry me = (java.util.Map.Entry) e.next();
            Object keyObj = me.getKey();
            if (null == keyObj)
                continue;
            String key = keyObj.toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING)) {
                if (!http10) {
                    String val = me.getValue().toString();
                    if (null != val
                            && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED))
                        httpChunkStream = true;
                }
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION)) {
                if (!http10) {
                    String val = me.getValue().toString();
                    if (val.trim().equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION_CLOSE))
                        httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
                }
                //HTTP 1.0 will always close.
                //HTTP 1.1 will use persistent. //no need to specify
            } else {
                if (!http10 && key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)) {
                    String val = me.getValue().toString();
                    if (null != val && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue))
                        httpContinueExpected = true;
                }

                otherHeaders.append(key).append(": ").append(me.getValue()).append("\r\n");
            }
        }
    }

    if (!http10) {
        //Force close for now.
        //TODO HTTP/1.1
        httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
    }

    header2.append(" ");
    header2.append(http10 ? HTTPConstants.HEADER_PROTOCOL_10 : HTTPConstants.HEADER_PROTOCOL_11).append("\r\n");
    MimeHeaders mimeHeaders = reqMessage.getMimeHeaders();

    if (posting) {
        String contentType;
        final String[] header = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (header != null && header.length > 0) {
            contentType = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE)[0];
        } else {
            contentType = reqMessage.getContentType(msgContext.getSOAPConstants());
        }

        //fix for AXIS-2027
        if (contentType == null || contentType.equals("")) {
            throw new Exception(Messages.getMessage("missingContentType"));
        }
        header2.append(HTTPConstants.HEADER_CONTENT_TYPE).append(": ").append(contentType).append("\r\n");
    }

    header2.append(ACCEPT_HEADERS).append(HTTPConstants.HEADER_HOST) //used for virtual connections
            .append(": ").append(host).append((port == -1) ? ("") : (":" + port)).append("\r\n")
            .append(CACHE_HEADERS).append(HTTPConstants.HEADER_SOAP_ACTION) //The SOAP action.
            .append(": \"").append(action).append("\"\r\n");

    if (posting) {
        if (!httpChunkStream) {
            //Content length MUST be sent on HTTP 1.0 requests.
            header2.append(HTTPConstants.HEADER_CONTENT_LENGTH).append(": ")
                    .append(reqMessage.getContentLength()).append("\r\n");
        } else {
            //Do http chunking.
            header2.append(CHUNKED_HEADER);
        }
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers. 
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            header2.append(mimeHeader.getName()).append(": ").append(mimeHeader.getValue()).append("\r\n");
        }
    }

    if (null != httpConnection) {
        header2.append(HTTPConstants.HEADER_CONNECTION);
        header2.append(": ");
        header2.append(httpConnection);
        header2.append("\r\n");
    }

    getSocket(sockHolder, msgContext, targetURL.getProtocol(), host, port, timeout, otherHeaders, useFullURL);

    if (null != otherHeaders) {
        //Add other headers to the end.
        //for pre java1.4 support, we have to turn the string buffer argument into
        //a string before appending.
        header2.append(otherHeaders.toString());
    }

    header2.append("\r\n"); //The empty line to start the BODY.

    StringBuffer header = new StringBuffer();

    // If we're SOAP 1.2, allow the web method to be set from the
    // MessageContext.
    if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
        webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
    }
    if (webMethod == null) {
        webMethod = HTTPConstants.HEADER_POST;
    } else {
        posting = webMethod.equals(HTTPConstants.HEADER_POST);
    }

    header.append(webMethod).append(" ");
    if (useFullURL.value) {
        header.append(tmpURL.toExternalForm());
    } else {
        header.append((((tmpURL.getFile() == null) || tmpURL.getFile().equals("")) ? "/" : tmpURL.getFile()));
    }
    header.append(header2.toString());

    OutputStream out = sockHolder.getSocket().getOutputStream();

    if (!posting) {
        out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
        out.flush();
        return null;
    }

    InputStream inp = null;

    if (httpChunkStream || httpContinueExpected) {
        out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
    }

    if (httpContinueExpected) { //We need to get a reply from the server as to whether
        // it wants us send anything more.
        out.flush();
        Hashtable cheaders = new Hashtable();
        inp = readHeadersFromSocket(sockHolder, msgContext, null, cheaders);
        int returnCode = -1;
        Integer Irc = (Integer) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
        if (null != Irc) {
            returnCode = Irc.intValue();
        }
        if (100 == returnCode) { // got 100 we may continue.
            //Need todo a little msgContext house keeping....
            msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
            msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
        } else { //If no 100 Continue then we must not send anything!
            String statusMessage = (String) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);

            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, ""));
            throw fault;
        }
    }
    ByteArrayOutputStream baos = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("xmlSent00"));
        log.debug("---------------------------------------------------");
        baos = new ByteArrayOutputStream();
    }
    if (httpChunkStream) {
        ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(out);
        out = new BufferedOutputStream(chunkedOutputStream, Constants.HTTP_TXR_BUFFER_SIZE);
        try {
            if (baos != null) {
                out = new TeeOutputStream(out, baos);
            }
            reqMessage.writeTo(out);
        } catch (SOAPException e) {
            log.error(Messages.getMessage("exception00"), e);
        }
        out.flush();
        chunkedOutputStream.eos();
    } else {
        out = new BufferedOutputStream(out, Constants.HTTP_TXR_BUFFER_SIZE);
        try {
            if (!httpContinueExpected) {
                out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
            }
            if (baos != null) {
                out = new TeeOutputStream(out, baos);
            }
            reqMessage.writeTo(out);
        } catch (SOAPException e) {
            log.error(Messages.getMessage("exception00"), e);
        }
        // Flush ONLY once.
        out.flush();
    }
    if (log.isDebugEnabled()) {
        log.debug(header + new String(baos.toByteArray()));
    }

    return inp;
}

From source file:com.hp.it.spf.wsrp.axis.transport.http.HTTPSender.java

/**
 * Send the soap request message to the server
 *
 * @param msgContext message context/*from  ww w . ja v  a2  s.c  o m*/
 * @param targetURL url to connect to
 * @param otherHeaders other headers if any
 * @param useFullURL flag to indicate if the whole url needs to be sent
 *
 * @throws IOException
 */
private InputStream writeToSocket(SocketHolder sockHolder, MessageContext msgContext, URL targetURL,
        StringBuffer otherHeaders, int timeout, BooleanHolder useFullURL) throws Exception {

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (targetURL.getUserInfo() != null)) {
        String info = targetURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        StringBuffer tmpBuf = new StringBuffer();

        tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd);
        otherHeaders.append(HTTPConstants.HEADER_AUTHORIZATION).append(": Basic ")
                .append(Base64.encode(tmpBuf.toString().getBytes())).append("\r\n");
    }

    // don't forget the cookies!
    // mmm... cookies
    if (msgContext.getMaintainSession()) {
        fillHeaders(msgContext, HTTPConstants.HEADER_COOKIE, otherHeaders);
        fillHeaders(msgContext, HTTPConstants.HEADER_COOKIE2, otherHeaders);
    }

    StringBuffer header2 = new StringBuffer();

    String webMethod = null;
    boolean posting = true;

    Message reqMessage = msgContext.getRequestMessage();

    boolean http10 = true; //True if this is to use HTTP 1.0 / false HTTP 1.1
    boolean httpChunkStream = false; //Use HTTP chunking or not.
    boolean httpContinueExpected = false; //Under HTTP 1.1 if false you *MAY* need to wait for a 100 rc,
                                          //  if true the server MUST reply with 100 continue.
    String httpConnection = null;

    String httpver = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
    if (null == httpver) {
        httpver = HTTPConstants.HEADER_PROTOCOL_V10;
    }
    httpver = httpver.trim();
    if (httpver.equals(HTTPConstants.HEADER_PROTOCOL_V11)) {
        http10 = false;
    }

    //process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        if (null == otherHeaders) {
            otherHeaders = new StringBuffer(1024);
        }

        for (java.util.Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {

            java.util.Map.Entry me = (java.util.Map.Entry) e.next();
            Object keyObj = me.getKey();
            if (null == keyObj)
                continue;
            String key = keyObj.toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING)) {
                if (!http10) {
                    String val = me.getValue().toString();
                    if (null != val
                            && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED))
                        httpChunkStream = true;
                }
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION)) {
                if (!http10) {
                    String val = me.getValue().toString();
                    if (val.trim().equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION_CLOSE))
                        httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
                }
                //HTTP 1.0 will always close.
                //HTTP 1.1 will use persistent. //no need to specify
            } else {
                if (!http10 && key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)) {
                    String val = me.getValue().toString();
                    if (null != val && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue))
                        httpContinueExpected = true;
                }

                otherHeaders.append(key).append(": ").append(me.getValue()).append("\r\n");
            }
        }
    }

    if (!http10) {
        //Force close for now.
        //TODO HTTP/1.1
        httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
    }

    header2.append(" ");
    header2.append(http10 ? HTTPConstants.HEADER_PROTOCOL_10 : HTTPConstants.HEADER_PROTOCOL_11).append("\r\n");
    MimeHeaders mimeHeaders = reqMessage.getMimeHeaders();

    if (posting) {
        String contentType;
        final String[] header = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (header != null && header.length > 0) {
            contentType = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE)[0];
        } else {
            contentType = reqMessage.getContentType(msgContext.getSOAPConstants());
        }

        //fix for AXIS-2027
        if (contentType == null || contentType.equals("")) {
            throw new Exception(Messages.getMessage("missingContentType"));
        }
        header2.append(HTTPConstants.HEADER_CONTENT_TYPE).append(": ").append(contentType).append("\r\n");
    }

    //Get host and port
    String host = targetURL.getHost();
    int port = targetURL.getPort();

    header2.append(ACCEPT_HEADERS).append(HTTPConstants.HEADER_HOST) //used for virtual connections
            .append(": ").append(host).append((port == -1) ? ("") : (":" + port)).append("\r\n")
            .append(CACHE_HEADERS).append(HTTPConstants.HEADER_SOAP_ACTION) //The SOAP action.
            .append(": \"").append(action).append("\"\r\n");

    if (posting) {
        if (!httpChunkStream) {
            //Content length MUST be sent on HTTP 1.0 requests.
            header2.append(HTTPConstants.HEADER_CONTENT_LENGTH).append(": ")
                    .append(reqMessage.getContentLength()).append("\r\n");
        } else {
            //Do http chunking.
            header2.append(CHUNKED_HEADER);
        }
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            header2.append(mimeHeader.getName()).append(": ").append(mimeHeader.getValue()).append("\r\n");
        }
    }

    if (null != httpConnection) {
        header2.append(HTTPConstants.HEADER_CONNECTION);
        header2.append(": ");
        header2.append(httpConnection);
        header2.append("\r\n");
    }

    getSocket(sockHolder, msgContext, targetURL.getProtocol(), host, port, timeout, otherHeaders, useFullURL);

    if (null != otherHeaders) {
        //Add other headers to the end.
        //for pre java1.4 support, we have to turn the string buffer argument into
        //a string before appending.
        header2.append(otherHeaders.toString());
    }

    header2.append("\r\n"); //The empty line to start the BODY.

    StringBuffer header = new StringBuffer();

    // If we're SOAP 1.2, allow the web method to be set from the
    // MessageContext.
    if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
        webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
    }
    if (webMethod == null) {
        webMethod = HTTPConstants.HEADER_POST;
    } else {
        posting = webMethod.equals(HTTPConstants.HEADER_POST);
    }

    header.append(webMethod).append(" ");
    if (useFullURL.value) {
        header.append(targetURL.toExternalForm());
    } else {
        header.append((((targetURL.getFile() == null) || targetURL.getFile().equals("")) ? "/"
                : targetURL.getFile()));
    }
    header.append(header2.toString());

    OutputStream out = sockHolder.getSocket().getOutputStream();

    if (!posting) {
        out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
        out.flush();
        return null;
    }

    InputStream inp = null;

    if (httpChunkStream || httpContinueExpected) {
        out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
    }

    if (httpContinueExpected) { //We need to get a reply from the server as to whether
        // it wants us send anything more.
        out.flush();
        Hashtable cheaders = new Hashtable();
        inp = readHeadersFromSocket(sockHolder, msgContext, null, cheaders);
        int returnCode = -1;
        Integer Irc = (Integer) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
        if (null != Irc) {
            returnCode = Irc.intValue();
        }
        if (100 == returnCode) { // got 100 we may continue.
            //Need todo a little msgContext house keeping....
            msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
            msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
        } else { //If no 100 Continue then we must not send anything!
            String statusMessage = (String) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);

            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, ""));
            throw fault;
        }
    }
    ByteArrayOutputStream baos = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("xmlSent00"));
        log.debug("---------------------------------------------------");
        baos = new ByteArrayOutputStream();
    }
    if (httpChunkStream) {
        ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(out);
        out = new BufferedOutputStream(chunkedOutputStream, Constants.HTTP_TXR_BUFFER_SIZE);
        try {
            if (baos != null) {
                out = new TeeOutputStream(out, baos);
            }
            reqMessage.writeTo(out);
        } catch (SOAPException e) {
            log.error(Messages.getMessage("exception00"), e);
        }
        out.flush();
        chunkedOutputStream.eos();
    } else {
        out = new BufferedOutputStream(out, Constants.HTTP_TXR_BUFFER_SIZE);
        try {
            if (!httpContinueExpected) {
                out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
            }
            if (baos != null) {
                out = new TeeOutputStream(out, baos);
            }
            reqMessage.writeTo(out);
        } catch (SOAPException e) {
            log.error(Messages.getMessage("exception00"), e);
        }
        // Flush ONLY once.
        out.flush();
    }
    if (log.isDebugEnabled()) {
        log.debug(header + new String(baos.toByteArray()));
    }

    return inp;
}