Search in sources :

Example 1 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project pinot by linkedin.

the class SchemaUtils method postSchema.

/**
   * Given host, port and schema, send a http POST request to upload the {@link Schema}.
   *
   * @return <code>true</code> on success.
   * <P><code>false</code> on failure.
   */
public static boolean postSchema(@Nonnull String host, int port, @Nonnull Schema schema) {
    Preconditions.checkNotNull(host);
    Preconditions.checkNotNull(schema);
    try {
        URL url = new URL("http", host, port, "/schemas");
        PostMethod httpPost = new PostMethod(url.toString());
        try {
            Part[] parts = { new StringPart(schema.getSchemaName(), schema.toString()) };
            MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, new HttpMethodParams());
            httpPost.setRequestEntity(requestEntity);
            int responseCode = HTTP_CLIENT.executeMethod(httpPost);
            if (responseCode >= 400) {
                String response = httpPost.getResponseBodyAsString();
                LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
                return false;
            }
            return true;
        } finally {
            httpPost.releaseConnection();
        }
    } catch (Exception e) {
        LOGGER.error("Caught exception while posting the schema: {} to host: {}, port: {}", schema.getSchemaName(), host, port, e);
        return false;
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) Part(org.apache.commons.httpclient.methods.multipart.Part) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) URL(java.net.URL) IOException(java.io.IOException)

Example 2 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project pinot by linkedin.

the class FileUploadUtils method sendFile.

public static int sendFile(final String host, final String port, final String path, final String fileName, final InputStream inputStream, final long lengthInBytes, SendFileMethod httpMethod) {
    EntityEnclosingMethod method = null;
    try {
        method = httpMethod.forUri("http://" + host + ":" + port + "/" + path);
        Part[] parts = { new FilePart(fileName, new PartSource() {

            @Override
            public long getLength() {
                return lengthInBytes;
            }

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

            @Override
            public InputStream createInputStream() throws IOException {
                return new BufferedInputStream(inputStream);
            }
        }) };
        method.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams()));
        FILE_UPLOAD_HTTP_CLIENT.executeMethod(method);
        if (method.getStatusCode() >= 400) {
            String errorString = "POST Status Code: " + method.getStatusCode() + "\n";
            if (method.getResponseHeader("Error") != null) {
                errorString += "ServletException: " + method.getResponseHeader("Error").getValue();
            }
            throw new HttpException(errorString);
        }
        return method.getStatusCode();
    } catch (Exception e) {
        LOGGER.error("Caught exception while sending file: {}", fileName, e);
        Utils.rethrowException(e);
        throw new AssertionError("Should not reach this");
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}
Also used : PartSource(org.apache.commons.httpclient.methods.multipart.PartSource) BufferedInputStream(java.io.BufferedInputStream) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) HttpException(org.apache.commons.httpclient.HttpException) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 3 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project tdi-studio-se by Talend.

the class HttpMethodBase method recycle.

/**
     * Recycles the HTTP method so that it can be used again.
     * Note that all of the instance variables will be reset
     * once this method has been called. This method will also
     * release the connection being used by this HTTP method.
     * 
     * @see #releaseConnection()
     * 
     * @deprecated no longer supported and will be removed in the future
     *             version of HttpClient
     */
public void recycle() {
    LOG.trace("enter HttpMethodBase.recycle()");
    releaseConnection();
    path = null;
    followRedirects = false;
    doAuthentication = true;
    queryString = null;
    getRequestHeaderGroup().clear();
    getResponseHeaderGroup().clear();
    getResponseTrailerHeaderGroup().clear();
    statusLine = null;
    effectiveVersion = null;
    aborted = false;
    used = false;
    params = new HttpMethodParams();
    responseBody = null;
    recoverableExceptionCount = 0;
    connectionCloseForced = false;
    hostAuthState.invalidate();
    proxyAuthState.invalidate();
    cookiespec = null;
    requestSent = false;
}
Also used : HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams)

Example 4 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project zm-mailbox by Zimbra.

the class WebDavClient method executeMethod.

protected HttpMethod executeMethod(HttpMethod m, Depth d, String bodyForLogging) throws IOException {
    HttpMethodParams p = m.getParams();
    if (p != null)
        p.setCredentialCharset("UTF-8");
    m.setDoAuthentication(true);
    m.setRequestHeader("User-Agent", mUserAgent);
    String depth = "0";
    switch(d) {
        case one:
            depth = "1";
            break;
        case infinity:
            depth = "infinity";
            break;
        case zero:
            break;
        default:
            break;
    }
    m.setRequestHeader("Depth", depth);
    logRequestInfo(m, bodyForLogging);
    HttpClientUtil.executeMethod(mClient, m);
    logResponseInfo(m);
    return m;
}
Also used : HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams)

Example 5 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project zm-mailbox by Zimbra.

the class SoapHttpTransport method invoke.

public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId, String changeToken, String tokenType, ResponseHandler respHandler) throws IOException, HttpException, ServiceException {
    PostMethod method = null;
    try {
        // Assemble post method.  Append document name, so that the request
        // type is written to the access log.
        String uri, query;
        int i = mUri.indexOf('?');
        if (i >= 0) {
            uri = mUri.substring(0, i);
            query = mUri.substring(i);
        } else {
            uri = mUri;
            query = "";
        }
        if (!uri.endsWith("/"))
            uri += '/';
        uri += getDocumentName(document);
        method = new PostMethod(uri + query);
        // Set user agent if it's specified.
        String agentName = getUserAgentName();
        if (agentName != null) {
            String agentVersion = getUserAgentVersion();
            if (agentVersion != null)
                agentName += " " + agentVersion;
            method.setRequestHeader(new Header("User-Agent", agentName));
        }
        // the content-type charset will determine encoding used
        // when we set the request body
        method.setRequestHeader("Content-Type", getRequestProtocol().getContentType());
        if (getClientIp() != null) {
            method.setRequestHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            if (ZimbraLog.misc.isDebugEnabled()) {
                ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            }
        }
        Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken, tokenType);
        String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
        HttpMethodParams params = method.getParams();
        method.setRequestEntity(new StringRequestEntity(soapMessage, null, "UTF-8"));
        if (getRequestProtocol().hasSOAPActionHeader())
            method.setRequestHeader("SOAPAction", mUri);
        if (mCustomHeaders != null) {
            for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) method.setRequestHeader(entry.getKey(), entry.getValue());
        }
        String host = method.getURI().getHost();
        HttpState state = HttpClientUtil.newHttpState(getAuthToken(), host, this.isAdmin());
        String trustedToken = getTrustedToken();
        if (trustedToken != null) {
            state.addCookie(new Cookie(host, ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken, "/", null, false));
        }
        params.setCookiePolicy(state.getCookies().length == 0 ? CookiePolicy.IGNORE_COOKIES : CookiePolicy.BROWSER_COMPATIBILITY);
        params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(mRetryCount - 1, true));
        params.setSoTimeout(mTimeout);
        params.setVersion(HttpVersion.HTTP_1_1);
        method.setRequestHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");
        if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
            state.setProxyCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword()));
        }
        if (mHttpDebugListener != null) {
            mHttpDebugListener.sendSoapMessage(method, soapReq, state);
        }
        int responseCode = mClient.executeMethod(mHostConfig, method, state);
        //   real server issues will probably be "503" or "404"
        if (responseCode != HttpServletResponse.SC_OK && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
            throw ServiceException.PROXY_ERROR(method.getStatusLine().toString(), uri);
        // Read the response body.  Use the stream API instead of the byte[]
        // version to avoid HTTPClient whining about a large response.
        InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream(), SoapProtocol.getCharset());
        String responseStr = "";
        try {
            if (respHandler != null) {
                respHandler.process(reader);
                return null;
            } else {
                responseStr = ByteUtil.getContent(reader, (int) method.getResponseContentLength(), false);
                Element soapResp = parseSoapResponse(responseStr, raw);
                if (mHttpDebugListener != null) {
                    mHttpDebugListener.receiveSoapMessage(method, soapResp);
                }
                return soapResp;
            }
        } catch (SoapFaultException x) {
            // attach request/response to the exception and rethrow
            x.setFaultRequest(soapMessage);
            x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
            throw x;
        }
    } finally {
        // Release the connection to the connection manager
        if (method != null)
            method.releaseConnection();
        // exits.  Leave it here anyway.
        if (!mKeepAlive)
            mClient.getHttpConnectionManager().closeIdleConnections(0);
    }
}
Also used : ZimbraCookie(com.zimbra.common.util.ZimbraCookie) Cookie(org.apache.commons.httpclient.Cookie) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) InputStreamReader(java.io.InputStreamReader) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpState(org.apache.commons.httpclient.HttpState) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Header(org.apache.commons.httpclient.Header) AuthScope(org.apache.commons.httpclient.auth.AuthScope) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)20 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)9 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)7 Part (org.apache.commons.httpclient.methods.multipart.Part)7 IOException (java.io.IOException)5 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 HttpMethod (org.apache.commons.httpclient.HttpMethod)4 EntityEnclosingMethod (org.apache.commons.httpclient.methods.EntityEnclosingMethod)4 PostMethod (org.apache.commons.httpclient.methods.PostMethod)4 File (java.io.File)3 Pattern (java.util.regex.Pattern)3 URI (org.apache.commons.httpclient.URI)3 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)2 URIException (org.apache.commons.httpclient.URIException)2 PostRequest (org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest)2