Example usage for java.net URL getUserInfo

List of usage examples for java.net URL getUserInfo

Introduction

In this page you can find the example usage for java.net URL getUserInfo.

Prototype

public String getUserInfo() 

Source Link

Document

Gets the userInfo part of this URL .

Usage

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

/**
 * Send the soap request message to the server
 *
 * @param msgContext message context/*from www.  ja va2s .  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();

        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 w ww . ja v  a 2s .co  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;
}

From source file:fi.laverca.util.CommonsHTTPSender.java

/**
 * Extracts info from message context.//from w w w  .  j  ava 2 s .  c  om
 *
 * @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 if any error occurred
 */
private void addContextInfo(final HttpPost method, final HttpClient httpClient, final MessageContext msgContext,
        final URL tmpURL) throws Exception {
    HttpParams params = method.getParams();

    if (msgContext.getTimeout() != 0) {
        // optionally set a timeout for response waits
        HttpConnectionParams.setSoTimeout(params, msgContext.getTimeout());
    }

    // Always set the 30 second timeout on establishing the connection
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()));
    }

    if (msgContext.useSOAPAction()) {
        // define SOAPAction header
        String action = msgContext.getSOAPActionURI();
        if (action != null && !"".equals(action))
            method.setHeader(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"");
    }

    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);
            }
        }
        ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY, proxyCred);
    }

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addHeader(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.addHeader(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)) {
                HttpProtocolParams.setUseExpectContinue(params, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addHeader(key, value);
            }
        }
    }
}

From source file:org.jivesoftware.community.http.impl.HttpClientManagerImpl.java

public HttpClient getClient(URL url,
        com.sun.syndication.fetcher.impl.HttpClientFeedFetcher.CredentialSupplier credentialSupplier,
        int timeout) {
    HttpClient client = new HttpClient();
    HttpConnectionManager conManager = client.getHttpConnectionManager();

    if (JiveGlobals.getProperty("http.proxyHost") != null
            && JiveGlobals.getProperty("http.proxyPort") != null) {
        client.getHostConfiguration().setProxy(JiveGlobals.getProperty("http.proxyHost"),
                Integer.parseInt(JiveGlobals.getProperty("http.proxyPort")));
        if (JiveGlobals.getProperty("http.proxyUsername") != null
                && JiveGlobals.getProperty("http.proxyPassword") != null) {
            HttpState state = new HttpState();
            state.setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(JiveGlobals.getProperty("http.proxyUserName"),
                            JiveGlobals.getProperty("http.proxyPassword")));
            client.setState(state);//from  w w w  .  j a  v a 2s.  com
        }
    }
    if (timeout > 0) {
        conManager.getParams().setParameter("http.connection.timeout", Integer.valueOf(timeout));
        conManager.getParams().setParameter("http.socket.timeout", Integer.valueOf(timeout));
    }
    if (isHTTPS(url)) {
        int port = url.getPort() <= -1 ? 443 : url.getPort();
        Protocol myhttps = new Protocol("https", new DummySSLSocketFactory(), port);
        Protocol.registerProtocol("https", myhttps);
        client.getHostConfiguration().setHost(url.getHost(), port, myhttps);
    } else {
        int port = url.getPort() <= -1 ? 80 : url.getPort();
        client.getHostConfiguration().setHost(url.getHost(), port);
    }
    if (url.getUserInfo() != null && credentialSupplier == null)
        credentialSupplier = new BasicAuthCredentials(url.getUserInfo());

    if (credentialSupplier != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(new AuthScope(url.getHost(), -1, AuthScope.ANY_REALM),
                credentialSupplier.getCredentials(null, url.getHost()));
    }
    return client;
}

From source file:com.ehsy.solr.util.SimplePostTool.java

/**
 * Reads data from the data stream and posts it to solr,
 * writes to the response to output//from   ww  w  . j  a  va 2s .  c om
 * @return true if success
 */
public boolean postData(InputStream data, Integer length, OutputStream output, String type, URL url) {
    if (mockMode)
        return true;
    boolean success = true;
    if (type == null)
        type = DEFAULT_CONTENT_TYPE;
    HttpURLConnection urlc = null;
    try {
        try {
            urlc = (HttpURLConnection) url.openConnection();
            try {
                urlc.setRequestMethod("POST");
            } catch (ProtocolException e) {
                fatal("Shouldn't happen: HttpURLConnection doesn't support POST??" + e);
            }
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            urlc.setRequestProperty("Content-type", type);
            if (url.getUserInfo() != null) {
                String encoding = DatatypeConverter
                        .printBase64Binary(url.getUserInfo().getBytes(StandardCharsets.US_ASCII));
                urlc.setRequestProperty("Authorization", "Basic " + encoding);
            }
            if (null != length)
                urlc.setFixedLengthStreamingMode(length);
            urlc.connect();
        } catch (IOException e) {
            fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e);
            success = false;
        }

        try (final OutputStream out = urlc.getOutputStream()) {
            pipe(data, out);
        } catch (IOException e) {
            fatal("IOException while posting data: " + e);
            success = false;
        }

        try {
            success &= checkResponseCode(urlc);
            try (final InputStream in = urlc.getInputStream()) {
                pipe(in, output);
            }
        } catch (IOException e) {
            warn("IOException while reading response: " + e);
            success = false;
        }
    } finally {
        if (urlc != null)
            urlc.disconnect();
    }
    return success;
}

From source file:com.jobaline.uiautomation.framework.selenium.phantomJsThreeHourTimeoutFix.HttpCommandExecutor.java

public HttpCommandExecutor(Map<String, CommandInfo> additionalCommands, URL addressOfRemoteServer) {
    try {//from  w w w. ja  va 2  s .  c om
        remoteServer = addressOfRemoteServer == null
                ? new URL(System.getProperty("webdriver.remote.server", "http://localhost:4444/wd/hub"))
                : addressOfRemoteServer;
    } catch (MalformedURLException e) {
        throw new WebDriverException(e);
    }

    HttpParams params = new BasicHttpParams();
    // Use the JRE default for the socket linger timeout.
    params.setParameter(CoreConnectionPNames.SO_LINGER, -1);
    HttpClientParams.setRedirecting(params, false);

    synchronized (HttpCommandExecutor.class) {
        if (httpClientFactory == null) {
            httpClientFactory = new HttpClientFactory();
        }
    }
    client = httpClientFactory.getHttpClient();

    // PATCH start
    // HttpClientFactory has a hardcoded timeout of three hours.
    // This class is intended to be used only for phantomjs which runs locally so the timeouts will be set to a low value

    BasicHttpParams paramsPatched = (BasicHttpParams) client.getParams();
    paramsPatched.setIntParameter("http.connection.timeout", 90000); //  1 minute an a half
    paramsPatched.setIntParameter("http.socket.timeout", 90000); // 1 minute an a half
    ((DefaultHttpClient) client).setParams(params);

    // PATCH end

    if (addressOfRemoteServer != null && addressOfRemoteServer.getUserInfo() != null) {
        // Use HTTP Basic auth
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                addressOfRemoteServer.getUserInfo());
        ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    }

    // Some machines claim "localhost.localdomain" is the same as "localhost".
    // This assumption is not always true.

    String host = remoteServer.getHost().replace(".localdomain", "");

    targetHost = new HttpHost(host, remoteServer.getPort(), remoteServer.getProtocol());

    ImmutableMap.Builder<String, CommandInfo> builder = ImmutableMap.builder();
    for (Map.Entry<String, CommandInfo> entry : additionalCommands.entrySet()) {
        builder.put(entry.getKey(), entry.getValue());
    }

    builder.put(GET_ALL_SESSIONS, get("/sessions")).put(NEW_SESSION, post("/session"))
            .put(GET_CAPABILITIES, get("/session/:sessionId")).put(QUIT, delete("/session/:sessionId"))
            .put(GET_CURRENT_WINDOW_HANDLE, get("/session/:sessionId/window_handle"))
            .put(GET_WINDOW_HANDLES, get("/session/:sessionId/window_handles"))
            .put(GET, post("/session/:sessionId/url"))

            // The Alert API is still experimental and should not be used.
            .put(GET_ALERT, get("/session/:sessionId/alert"))
            .put(DISMISS_ALERT, post("/session/:sessionId/dismiss_alert"))
            .put(ACCEPT_ALERT, post("/session/:sessionId/accept_alert"))
            .put(GET_ALERT_TEXT, get("/session/:sessionId/alert_text"))
            .put(SET_ALERT_VALUE, post("/session/:sessionId/alert_text"))

            .put(GO_FORWARD, post("/session/:sessionId/forward")).put(GO_BACK, post("/session/:sessionId/back"))
            .put(REFRESH, post("/session/:sessionId/refresh"))
            .put(EXECUTE_SCRIPT, post("/session/:sessionId/execute"))
            .put(EXECUTE_ASYNC_SCRIPT, post("/session/:sessionId/execute_async"))
            .put(GET_CURRENT_URL, get("/session/:sessionId/url"))
            .put(GET_TITLE, get("/session/:sessionId/title"))
            .put(GET_PAGE_SOURCE, get("/session/:sessionId/source"))
            .put(SCREENSHOT, get("/session/:sessionId/screenshot"))
            .put(FIND_ELEMENT, post("/session/:sessionId/element"))
            .put(FIND_ELEMENTS, post("/session/:sessionId/elements"))
            .put(GET_ACTIVE_ELEMENT, post("/session/:sessionId/element/active"))
            .put(FIND_CHILD_ELEMENT, post("/session/:sessionId/element/:id/element"))
            .put(FIND_CHILD_ELEMENTS, post("/session/:sessionId/element/:id/elements"))
            .put(CLICK_ELEMENT, post("/session/:sessionId/element/:id/click"))
            .put(CLEAR_ELEMENT, post("/session/:sessionId/element/:id/clear"))
            .put(SUBMIT_ELEMENT, post("/session/:sessionId/element/:id/submit"))
            .put(GET_ELEMENT_TEXT, get("/session/:sessionId/element/:id/text"))
            .put(SEND_KEYS_TO_ELEMENT, post("/session/:sessionId/element/:id/value"))
            .put(UPLOAD_FILE, post("/session/:sessionId/file"))
            .put(GET_ELEMENT_VALUE, get("/session/:sessionId/element/:id/value"))
            .put(GET_ELEMENT_TAG_NAME, get("/session/:sessionId/element/:id/name"))
            .put(IS_ELEMENT_SELECTED, get("/session/:sessionId/element/:id/selected"))
            .put(IS_ELEMENT_ENABLED, get("/session/:sessionId/element/:id/enabled"))
            .put(IS_ELEMENT_DISPLAYED, get("/session/:sessionId/element/:id/displayed"))
            .put(HOVER_OVER_ELEMENT, post("/session/:sessionId/element/:id/hover"))
            .put(GET_ELEMENT_LOCATION, get("/session/:sessionId/element/:id/location"))
            .put(GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW,
                    get("/session/:sessionId/element/:id/location_in_view"))
            .put(GET_ELEMENT_SIZE, get("/session/:sessionId/element/:id/size"))
            .put(GET_ELEMENT_ATTRIBUTE, get("/session/:sessionId/element/:id/attribute/:name"))
            .put(ELEMENT_EQUALS, get("/session/:sessionId/element/:id/equals/:other"))
            .put(GET_ALL_COOKIES, get("/session/:sessionId/cookie"))
            .put(ADD_COOKIE, post("/session/:sessionId/cookie"))
            .put(DELETE_ALL_COOKIES, delete("/session/:sessionId/cookie"))
            .put(DELETE_COOKIE, delete("/session/:sessionId/cookie/:name"))
            .put(SWITCH_TO_FRAME, post("/session/:sessionId/frame"))
            .put(SWITCH_TO_PARENT_FRAME, post("/session/:sessionId/frame/parent"))
            .put(SWITCH_TO_WINDOW, post("/session/:sessionId/window"))
            .put(GET_WINDOW_SIZE, get("/session/:sessionId/window/:windowHandle/size"))
            .put(GET_WINDOW_POSITION, get("/session/:sessionId/window/:windowHandle/position"))
            .put(SET_WINDOW_SIZE, post("/session/:sessionId/window/:windowHandle/size"))
            .put(SET_WINDOW_POSITION, post("/session/:sessionId/window/:windowHandle/position"))
            .put(MAXIMIZE_WINDOW, post("/session/:sessionId/window/:windowHandle/maximize"))
            .put(CLOSE, delete("/session/:sessionId/window"))
            .put(DRAG_ELEMENT, post("/session/:sessionId/element/:id/drag"))
            .put(GET_ELEMENT_VALUE_OF_CSS_PROPERTY, get("/session/:sessionId/element/:id/css/:propertyName"))
            .put(IMPLICITLY_WAIT, post("/session/:sessionId/timeouts/implicit_wait"))
            .put(SET_SCRIPT_TIMEOUT, post("/session/:sessionId/timeouts/async_script"))
            .put(SET_TIMEOUT, post("/session/:sessionId/timeouts"))
            .put(EXECUTE_SQL, post("/session/:sessionId/execute_sql"))
            .put(GET_LOCATION, get("/session/:sessionId/location"))
            .put(SET_LOCATION, post("/session/:sessionId/location"))
            .put(GET_APP_CACHE_STATUS, get("/session/:sessionId/application_cache/status"))
            .put(IS_BROWSER_ONLINE, get("/session/:sessionId/browser_connection"))
            .put(SET_BROWSER_ONLINE, post("/session/:sessionId/browser_connection"))

            .put(SWITCH_TO_CONTEXT, post("/session/:sessionId/context"))
            .put(GET_CURRENT_CONTEXT_HANDLE, get("/session/:sessionId/context"))
            .put(GET_CONTEXT_HANDLES, get("/session/:sessionId/contexts"))

            // TODO (user): Would it be better to combine this command with
            // GET_LOCAL_STORAGE_SIZE?
            .put(GET_LOCAL_STORAGE_ITEM, get("/session/:sessionId/local_storage/key/:key"))
            .put(REMOVE_LOCAL_STORAGE_ITEM, delete("/session/:sessionId/local_storage/key/:key"))
            .put(GET_LOCAL_STORAGE_KEYS, get("/session/:sessionId/local_storage"))
            .put(SET_LOCAL_STORAGE_ITEM, post("/session/:sessionId/local_storage"))
            .put(CLEAR_LOCAL_STORAGE, delete("/session/:sessionId/local_storage"))
            .put(GET_LOCAL_STORAGE_SIZE, get("/session/:sessionId/local_storage/size"))

            // TODO (user): Would it be better to combine this command with
            // GET_SESSION_STORAGE_SIZE?
            .put(GET_SESSION_STORAGE_ITEM, get("/session/:sessionId/session_storage/key/:key"))
            .put(REMOVE_SESSION_STORAGE_ITEM, delete("/session/:sessionId/session_storage/key/:key"))
            .put(GET_SESSION_STORAGE_KEYS, get("/session/:sessionId/session_storage"))
            .put(SET_SESSION_STORAGE_ITEM, post("/session/:sessionId/session_storage"))
            .put(CLEAR_SESSION_STORAGE, delete("/session/:sessionId/session_storage"))
            .put(GET_SESSION_STORAGE_SIZE, get("/session/:sessionId/session_storage/size"))

            .put(GET_SCREEN_ORIENTATION, get("/session/:sessionId/orientation"))
            .put(SET_SCREEN_ORIENTATION, post("/session/:sessionId/orientation"))

            // Interactions-related commands.
            .put(CLICK, post("/session/:sessionId/click"))
            .put(DOUBLE_CLICK, post("/session/:sessionId/doubleclick"))
            .put(MOUSE_DOWN, post("/session/:sessionId/buttondown"))
            .put(MOUSE_UP, post("/session/:sessionId/buttonup"))
            .put(MOVE_TO, post("/session/:sessionId/moveto"))
            .put(SEND_KEYS_TO_ACTIVE_ELEMENT, post("/session/:sessionId/keys"))

            // IME related commands.
            .put(IME_GET_AVAILABLE_ENGINES, get("/session/:sessionId/ime/available_engines"))
            .put(IME_GET_ACTIVE_ENGINE, get("/session/:sessionId/ime/active_engine"))
            .put(IME_IS_ACTIVATED, get("/session/:sessionId/ime/activated"))
            .put(IME_DEACTIVATE, post("/session/:sessionId/ime/deactivate"))
            .put(IME_ACTIVATE_ENGINE, post("/session/:sessionId/ime/activate"))

            // Advanced Touch API commands
            // TODO(berrada): Refactor single tap with mouse click.
            .put(TOUCH_SINGLE_TAP, post("/session/:sessionId/touch/click"))
            .put(TOUCH_DOWN, post("/session/:sessionId/touch/down"))
            .put(TOUCH_UP, post("/session/:sessionId/touch/up"))
            .put(TOUCH_MOVE, post("/session/:sessionId/touch/move"))
            .put(TOUCH_SCROLL, post("/session/:sessionId/touch/scroll"))
            .put(TOUCH_DOUBLE_TAP, post("/session/:sessionId/touch/doubleclick"))
            .put(TOUCH_LONG_PRESS, post("/session/:sessionId/touch/longclick"))
            .put(TOUCH_FLICK, post("/session/:sessionId/touch/flick"))

            .put(GET_LOG, post("/session/:sessionId/log"))
            .put(GET_AVAILABLE_LOG_TYPES, get("/session/:sessionId/log/types"))

            .put(STATUS, get("/status"));

    nameToUrl = builder.build();
}

From source file:org.activebpel.rt.axis.bpel.handlers.AeHTTPSender.java

/**
 * Extracts info from message context./* w w  w  .j ava 2s . c  o 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
 * @deprecated
 */
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.setTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.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$
    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 cred = new UsernamePasswordCredentials(userID, passwd);
        httpClient.getState().setCredentials(null, null, cred);

        // Change #2
        //
        // Comment out the lines below since they force all authentication
        // to be Basic. This is a problem if the web service you're invoking 
        // is expecting Digest.

        // The following 3 lines should NOT be required. But Our SimpleAxisServer fails
        // during all-tests if this is missing.
        //            StringBuffer tmpBuf = new StringBuffer();
        //            tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd);
        //            method.addRequestHeader(HTTPConstants.HEADER_AUTHORIZATION, "Basic " + Base64.encode(tmpBuf.toString().getBytes()));
    }

    // 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();
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

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

    if (userHeaderTable != null) {
        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();
            String value = me.getValue().toString().trim();

            method.addRequestHeader(key, value);
        }
    }
}

From source file:org.sakaiproject.content.tool.ResourcesHelperAction.java

public void doContinue(RunData data) {
    logger.debug(this + ".doContinue()");
    SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
    ParameterParser params = data.getParameters();

    int requestStateId = params.getInt("requestStateId", 0);
    ResourcesAction.restoreRequestState(state,
            new String[] { ResourcesAction.PREFIX + ResourcesAction.REQUEST }, requestStateId);

    String content = params.getString("content");
    if (content == null) {
        addAlert(state, rb.getString("text.notext"));
        return;// w  ww  .  ja v  a2  s .c o m
    }
    ToolSession toolSession = SessionManager.getCurrentToolSession();

    //      Tool tool = ToolManager.getCurrentTool();
    //      String url = (String) toolSession.getAttribute(tool.getId() + Tool.HELPER_DONE_URL);
    //      toolSession.removeAttribute(tool.getId() + Tool.HELPER_DONE_URL);

    ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession
            .getAttribute(ResourceToolAction.ACTION_PIPE);
    if (pipe == null) {
        return;
    }

    if (pipe != null) {
        String pipe_init_id = pipe.getInitializationId();
        String response_init_id = params.getString(ResourcesAction.PIPE_INIT_ID);
        if (pipe_init_id == null || response_init_id == null
                || !response_init_id.equalsIgnoreCase(pipe_init_id)) {
            // in this case, prevent upload to wrong folder
            pipe.setErrorMessage(rb.getString("alert.try-again"));
            pipe.setActionCanceled(false);
            pipe.setErrorEncountered(true);
            pipe.setActionCompleted(false);
            return;
        }

        toolSession.setAttribute(ResourceToolAction.ACTION_PIPE, pipe);

    }

    String resourceType = pipe.getAction().getTypeId();
    String mimetype = pipe.getMimeType();

    ListItem item = new ListItem(pipe.getContentEntity());
    // notification
    int noti = determineNotificationPriority(params, item.isDropbox, item.userIsMaintainer());

    pipe.setRevisedMimeType(pipe.getMimeType());
    if (ResourceType.TYPE_TEXT.equals(resourceType) || ResourceType.MIME_TYPE_TEXT.equals(mimetype)) {
        pipe.setRevisedMimeType(ResourceType.MIME_TYPE_TEXT);
        pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_ENCODING,
                ResourcesAction.UTF_8_ENCODING);
        pipe.setNotification(noti);

    } else if (ResourceType.TYPE_HTML.equals(resourceType) || ResourceType.MIME_TYPE_HTML.equals(mimetype)) {
        StringBuilder alertMsg = new StringBuilder();
        content = FormattedText.processHtmlDocument(content, alertMsg);
        pipe.setRevisedMimeType(ResourceType.MIME_TYPE_HTML);
        pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_ENCODING,
                ResourcesAction.UTF_8_ENCODING);
        pipe.setNotification(noti);
        if (alertMsg.length() > 0) {
            addAlert(state, alertMsg.toString());
            return;
        }
    } else if (ResourceType.TYPE_URL.equals(resourceType)) {

        // SAK-23587 - properly escape the URL where required
        try {
            URL url = new URL(content);
            URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                    url.getQuery(), url.getRef());
            content = uri.toString();
        } catch (Exception e) {
            //ok to ignore, just use the original url
            logger.debug("URL can not be encoded: " + e.getClass() + ":" + e.getCause());
        }

        pipe.setRevisedMimeType(ResourceType.MIME_TYPE_URL);
        pipe.setNotification(noti);
    } else if (ResourceType.TYPE_FOLDER.equals(resourceType)) {
        MultiFileUploadPipe mfp = (MultiFileUploadPipe) pipe;
        int count = params.getInt("folderCount");
        mfp.setFileCount(count);

        List<ResourceToolActionPipe> pipes = mfp.getPipes();
        for (int i = 0; i < pipes.size(); i++) {
            ResourceToolActionPipe fp = pipes.get(i);
            String folderName = params.getString("folder" + (i + 1));
            fp.setFileName(folderName);
            fp.setNotification(noti);
        }
    }

    try {
        pipe.setRevisedContent(content.getBytes(ResourcesAction.UTF_8_ENCODING));
        pipe.setActionCanceled(false);
        pipe.setErrorEncountered(false);
        pipe.setActionCompleted(true);
    } catch (UnsupportedEncodingException e) {
        logger.warn(this + ": " + e.toString());
        addAlert(state, rb.getString("alert.utf8encoding"));
        pipe.setActionCanceled(false);
        pipe.setErrorEncountered(true);
        pipe.setActionCompleted(false);
    }

    toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE);

}

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

/**
 * Extracts info from message context./*  w  w  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:com.jaspersoft.ireport.jasperserver.ws.CommonsHTTPSender.java

/**
 * Extracts info from message context./*ww  w . j av a2s .c om*/
 *
 * @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);
            }
        }
    }
}