Example usage for org.apache.commons.httpclient.methods EntityEnclosingMethod getRequestEntity

List of usage examples for org.apache.commons.httpclient.methods EntityEnclosingMethod getRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods EntityEnclosingMethod getRequestEntity.

Prototype

public RequestEntity getRequestEntity() 

Source Link

Usage

From source file:lucee.commons.net.http.httpclient3.HttpMethodCloner.java

private static void copyEntityEnclosingMethod(EntityEnclosingMethod m, EntityEnclosingMethod copy) {
    copy.setRequestEntity(m.getRequestEntity());
}

From source file:com.navercorp.pinpoint.plugin.httpclient3.HttpClient3EntityExtractor.java

@Override
public String getEntity(HttpMethod httpMethod) {
    if (httpMethod instanceof EntityEnclosingMethod) {
        final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;
        final RequestEntity entity = entityEnclosingMethod.getRequestEntity();
        if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
            try {
                String entityValue;
                String charSet = entityEnclosingMethod.getRequestCharSet();
                if (StringUtils.isEmpty(charSet)) {
                    charSet = HttpConstants.DEFAULT_CONTENT_CHARSET;
                }//  w w w.  j  a  va 2 s  . com
                if (entity instanceof ByteArrayRequestEntity || entity instanceof StringRequestEntity) {
                    entityValue = entityUtilsToString(entity, charSet);
                } else {
                    entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")";
                }
                return entityValue;
            } catch (Exception e) {
                if (isDebug) {
                    logger.debug("Failed to get entity. httpMethod={}", httpMethod, e);
                }
            }
        }
    }
    return null;
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.PostPackagingRequestFilter.java

@Override
public void filterAbstractHttpRequest(SubmitContext context, AbstractHttpRequest<?> request) {
    ExtendedHttpMethod httpMethod = (ExtendedHttpMethod) context
            .getProperty(BaseHttpRequestTransport.HTTP_METHOD);
    Settings settings = request.getSettings();

    // chunking?/*from   ww  w.ja v  a  2  s . c om*/
    if (httpMethod.getParams().getVersion().equals(HttpVersion.HTTP_1_1)
            && httpMethod instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod entityEnclosingMethod = ((EntityEnclosingMethod) httpMethod);
        long limit = settings.getLong(HttpSettings.CHUNKING_THRESHOLD, -1);
        RequestEntity requestEntity = entityEnclosingMethod.getRequestEntity();
        entityEnclosingMethod.setContentChunked(
                limit >= 0 && requestEntity != null ? requestEntity.getContentLength() > limit : false);
    }
}

From source file:com.zimbra.cs.index.elasticsearch.ElasticSearchConnector.java

public int executeMethod(HttpMethod method) throws IndexStoreException, IOException {
    String reqBody = "";
    if (ZimbraLog.elasticsearch.isTraceEnabled() && method instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod eem = (EntityEnclosingMethod) method;
        RequestEntity re = eem.getRequestEntity();
        if (re instanceof StringRequestEntity) {
            StringRequestEntity sre = (StringRequestEntity) re;
            reqBody = Strings.nullToEmpty(sre.getContent());
            if (reqBody.length() > 0) {
                reqBody = String.format("\nREQUEST BODY=%s", reqBody);
            }/*from  w ww. j a  va  2  s . co m*/
        }
    }
    try {
        HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
        statusCode = client.executeMethod(method);
    } catch (ConnectException ce) {
        throw new ZimbraElasticSearchDownException(ce);
    } catch (NoHttpResponseException nhre) {
        // managed to connect to the ElasticSearch service but it either crashed or timed out before
        // we got sent back the response.
        // Could be a temporary problem or a problem with this particular request.
        // In the longer term we need to track failures related to particular items at a higher level and discard
        // them after retrying a number of times.
        throw new ZimbraElasticSearchNoResponseException(nhre);
    }
    body = method.getResponseBodyAsString();
    ZimbraLog.elasticsearch.trace("ElasticSearch request:%s %s - statusCode=%d%s\nRESPONSE BODY=%s",
            method.getName(), method.getURI(), statusCode, reqBody, body);
    return statusCode;
}

From source file:com.google.jstestdriver.server.gateway.GatewayEntityMethodTest.java

License:asdf

public void testGetNameGetUriAndGetRequestEntity() throws Exception {
    ByteArrayInputStream in = new ByteArrayInputStream("ASDF".getBytes());
    EntityEnclosingMethod method = new GatewayEntityMethod("POST", "http://www.google.com/search", in);
    assertEquals("POST", method.getName());
    assertEquals("http://www.google.com/search", method.getURI().toString());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    method.getRequestEntity().writeRequest(out);
    assertEquals("ASDF", out.toString());
}

From source file:com.navercorp.pinpoint.plugin.httpclient3.HttpClient3RequestTrace.java

@Override
public String getEntityValue() {
    if (httpMethod instanceof EntityEnclosingMethod) {
        final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;
        final RequestEntity entity = entityEnclosingMethod.getRequestEntity();
        if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
            try {
                String entityValue;
                String charSet = entityEnclosingMethod.getRequestCharSet();
                if (StringUtils.isEmpty(charSet)) {
                    charSet = HttpConstants.DEFAULT_CONTENT_CHARSET;
                }/*w w w.  j a  v a 2s. c o  m*/
                if (entity instanceof ByteArrayRequestEntity || entity instanceof StringRequestEntity) {
                    entityValue = entityUtilsToString(entity, charSet);
                } else {
                    entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")";
                }
                return entityValue;
            } catch (Exception e) {
                if (isDebug) {
                    logger.debug("Failed to get entity. httpMethod={}", this.httpMethod, e);
                }
            }
        }
    }
    return null;
}

From source file:com.baidu.oped.apm.profiler.modifier.connector.httpclient3.interceptor.ExecuteInterceptor.java

private void recordEntity(HttpMethod httpMethod, Trace trace) {
    if (httpMethod instanceof EntityEnclosingMethod) {
        final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;
        final RequestEntity entity = entityEnclosingMethod.getRequestEntity();

        if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
            if (entitySampler.isSampling()) {
                try {
                    String entityValue;
                    String charSet = entityEnclosingMethod.getRequestCharSet();

                    if (charSet == null || charSet.isEmpty()) {
                        charSet = HttpConstants.DEFAULT_CONTENT_CHARSET;
                    }/*  w w w.  j  ava 2s . co m*/
                    if (entity instanceof ByteArrayRequestEntity) {
                        entityValue = readByteArray((ByteArrayRequestEntity) entity, charSet);
                    } else if (entity instanceof StringRequestEntity) {
                        entityValue = readString((StringRequestEntity) entity);
                    } else {
                        entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")";
                    }

                    trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, entityValue);
                } catch (Exception e) {
                    logger.debug("HttpEntityEnclosingRequest entity record fail. Caused:{}", e.getMessage(), e);
                }
            }
        }
    }

}

From source file:org.apache.cloudstack.network.element.SspClient.java

private String executeMethod(HttpMethod method) {
    String apiCallPath = null;/*from   ww w .  ja  va 2s  . co  m*/
    try {
        apiCallPath = method.getName() + " " + method.getURI().toString();
    } catch (URIException e) {
        s_logger.error("method getURI failed", e);
    }

    String response = null;
    try {
        client.executeMethod(method);
        response = method.getResponseBodyAsString();
    } catch (HttpException e) {
        s_logger.error("ssp api call failed " + apiCallPath, e);
        return null;
    } catch (IOException e) {
        s_logger.error("ssp api call failed " + apiCallPath, e);
        return null;
    } finally {
        method.releaseConnection();
    }

    if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        if (!login()) {
            return null;
        }

        try {
            client.executeMethod(method);
            response = method.getResponseBodyAsString();
        } catch (HttpException e) {
            s_logger.error("ssp api call failed " + apiCallPath, e);
            return null;
        } catch (IOException e) {
            s_logger.error("ssp api call failed " + apiCallPath, e);
            return null;
        } finally {
            method.releaseConnection();
        }
    }
    s_logger.info("ssp api call:" + apiCallPath + " user=" + username + " status=" + method.getStatusLine());
    if (method instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod emethod = (EntityEnclosingMethod) method;
        RequestEntity reqEntity = emethod.getRequestEntity();
        if (reqEntity instanceof StringRequestEntity) {
            StringRequestEntity strReqEntity = (StringRequestEntity) reqEntity;
            s_logger.debug("ssp api request body:" + strReqEntity.getContent());
        } else {
            s_logger.debug("ssp api request body:" + emethod.getRequestEntity());
        }
    }
    s_logger.debug("ssp api response body:" + response);
    return response;
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * Set up the PUT/PATCH/DELETE data/*from w  w w  . jav  a  2s . c  o  m*/
 */
private String sendEntityData(EntityEnclosingMethod put) throws IOException {
    // Buffer to hold the put body, except file content
    StringBuilder putBody = new StringBuilder(1000);
    boolean hasPutBody = false;

    // Check if the header manager had a content type header
    // This allows the user to specify his own content-type for a POST request
    Header contentTypeHeader = put.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE);
    boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null
            && contentTypeHeader.getValue().length() > 0;
    HTTPFileArg[] files = getHTTPFiles();

    // If there are no arguments, we can send a file as the body of the request

    if (!hasArguments() && getSendFileAsPostBody()) {
        hasPutBody = true;

        // If getSendFileAsPostBody returned true, it's sure that file is not null
        File reservedFile = FileServer.getFileServer().getResolvedFile(files[0].getPath());
        FileRequestEntity fileRequestEntity = new FileRequestEntity(reservedFile, null);
        put.setRequestEntity(fileRequestEntity);
    }
    // If none of the arguments have a name specified, we
    // just send all the values as the put body
    else if (getSendParameterValuesAsPostBody()) {
        hasPutBody = true;

        // If a content encoding is specified, we set it as http parameter, so that
        // the post body will be encoded in the specified content encoding
        String contentEncoding = getContentEncoding();
        boolean haveContentEncoding = false;
        if (isNullOrEmptyTrimmed(contentEncoding)) {
            contentEncoding = null;
        } else {
            put.getParams().setContentCharset(contentEncoding);
            haveContentEncoding = true;
        }

        // Just append all the parameter values, and use that as the post body
        StringBuilder putBodyContent = new StringBuilder();
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String value = null;
            if (haveContentEncoding) {
                value = arg.getEncodedValue(contentEncoding);
            } else {
                value = arg.getEncodedValue();
            }
            putBodyContent.append(value);
        }
        String contentTypeValue = null;
        if (hasContentTypeHeader) {
            contentTypeValue = put.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue();
        }
        StringRequestEntity requestEntity = new StringRequestEntity(putBodyContent.toString(), contentTypeValue,
                put.getRequestCharSet());
        put.setRequestEntity(requestEntity);
    }
    // Check if we have any content to send for body
    if (hasPutBody) {
        // If the request entity is repeatable, we can send it first to
        // our own stream, so we can return it
        if (put.getRequestEntity().isRepeatable()) {
            putBody.append("<actual file content, not shown here>");
        } else {
            putBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
        }
        if (!hasContentTypeHeader) {
            // Allow the mimetype of the file to control the content type
            // This is not obvious in GUI if you are not uploading any files,
            // but just sending the content of nameless parameters
            // TODO: needs a multiple file upload scenerio
            HTTPFileArg file = files.length > 0 ? files[0] : null;
            if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                put.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
            }
        }
        // Set the content length
        put.setRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH,
                Long.toString(put.getRequestEntity().getContentLength()));
    }
    return putBody.toString();
}

From source file:org.apache.ode.axis2.httpbinding.HttpHelper.java

public static String requestToString(HttpMethod m) {
    StringBuilder sb = new StringBuilder(256);
    try {//www . j  a  v  a 2  s  .  co m
        sb.append("HTTP Request Details: \n").append(m.getName()).append(" ").append(m.getURI());
    } catch (URIException e) {
        // not that important
        if (log.isDebugEnabled())
            log.debug(e);
    }
    sb.append("\nRequest Headers:");
    Header[] headers = m.getRequestHeaders();
    if (headers.length == 0)
        sb.append(" n/a");
    for (int i = 0; i < headers.length; i++) {
        Header h = headers[i];
        sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue());
    }
    if (m instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod eem = (EntityEnclosingMethod) m;
        if (eem.getRequestEntity() != null) {
            sb.append("\nRequest Entity:");
            sb.append("\n\tContent-Type:").append(eem.getRequestEntity().getContentType());
            sb.append("\n\tContent-Length:").append(eem.getRequestEntity().getContentLength());
            if (eem.getRequestEntity() instanceof StringRequestEntity) {
                StringRequestEntity sre = (StringRequestEntity) eem.getRequestEntity();
                sb.append("\n\tContent-Charset:").append(sre.getCharset());
                sb.append("\n\tRequest Entity:\n").append(sre.getContent());
            }
        }
    }
    return sb.toString();
}