org.apache.commons.httpclient.HttpMethodBase Java Examples

The following examples show how to use org.apache.commons.httpclient.HttpMethodBase. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HMACFilterAuthenticationProvider.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String getHeaders(HttpMethodBase method) {
	Header[] headersArray = method.getRequestHeaders();
	Map<String, String> headers = new HashMap<>(headersArray.length);
	for (int i = 0; i < headersArray.length; i++) { // only 1 value admitted for each header
		headers.put(headersArray[i].getName(), headersArray[i].getValue());
	}

	StringBuilder res = new StringBuilder();
	for (String name : HMACUtils.HEADERS_SIGNED) {
		String value = headers.get(name); // only 1 value admitted
		if (value != null) {
			res.append(name);
			res.append(value);
		}
	}
	return res.toString();
}
 
Example #2
Source File: HttpResponse.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public String getResponse()
{
	if (responseBytes != null)
	{
		if (method instanceof HttpMethodBase)
		{
			// mimic method.getResponseBodyAsString
			return EncodingUtil.getString(responseBytes, ((HttpMethodBase)method).getResponseCharSet());
		}
		else
		{
			return new String(responseBytes);
		}
	}
	else
	{
		return null;
	}
}
 
Example #3
Source File: LocalWebScriptConnectorServiceImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Builds a new Request object, using HttpClient method descriptions
 */
public RemoteConnectorRequest buildRequest(String url, Class<? extends HttpMethodBase> method)
{
    // Get the method name
    String methodName;
    try
    {
        HttpMethodBase httpMethod = method.getConstructor(String.class).newInstance(url);
        methodName = httpMethod.getName();
    }
    catch(Exception e)
    {
        throw new AlfrescoRuntimeException("Error identifying method name", e);
    }
    
    // Build and return
    return buildRequest(url, methodName);
}
 
Example #4
Source File: ApiClient.java    From engage-api-client with Apache License 2.0 6 votes vote down vote up
protected String executeMethod(HttpMethodBase method) throws ApiResultException {
	try {
           log.info("executing method:" + method);
		int responseCode = httpClient.executeMethod(method);

		String responseBody = method.getResponseBodyAsString();
		if (responseBody != null && !responseBody.isEmpty()) {
			return responseBody;
		} else {
			StringBuilder buffer = new StringBuilder();
			buffer.append("No response body was returned!\nResponse Headers-\n");
			Header[] headers = method.getResponseHeaders();
			for (Header header : headers) {
				buffer.append(header.getName()).append(": ").append(header.getValue()).append("\n");
			}
               buffer.append("HTTP-Response-Code: ").append(responseCode).append("\n");
			buffer.append("Content length reported as: ").append(method.getResponseContentLength());
               log.info(buffer.toString());
               throw new ApiResultException("Error executing API: " + buffer.toString(), new NoResponseApiErrorResult());
		}
	} catch(IOException e) {
		throw new ApiException("Error executing API: ", e);
	}
}
 
Example #5
Source File: RestUtilities.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static HttpMethodBase getMethod(HttpMethod method, String address) {
	String addr = address;
	if (method.equals(HttpMethod.Delete)) {
		return new DeleteMethod(addr);
	}
	if (method.equals(HttpMethod.Post)) {
		return new PostMethod(addr);
	}
	if (method.equals(HttpMethod.Get)) {
		return new GetMethod(addr);
	}
	if (method.equals(HttpMethod.Put)) {
		return new PutMethod(addr);
	}
	Assert.assertUnreachable("method doesn't exist");
	return null;
}
 
Example #6
Source File: BigSwitchBcfApi.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private String responseToErrorMessage(final HttpMethodBase method) {
    assert method.isRequestSent() : "no use getting an error message unless the request is sent";

    if ("text/html".equals(method.getResponseHeader(CONTENT_TYPE).getValue())) {
        // The error message is the response content
        // Safety margin of 2048 characters, anything longer is probably useless
        // and will clutter the logs
        try {
            return method.getResponseBodyAsString(2048);
        } catch (IOException e) {
            S_LOGGER.debug("Error while loading response body", e);
        }
    }

    // The default
    return method.getStatusText();
}
 
Example #7
Source File: SalesforceProvisioningConnector.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * adding OAuth authorization headers to a httpMethod
 *
 * @param httpMethod method which wants to add Authorization header
 */
private void setAuthorizationHeader(HttpMethodBase httpMethod)
        throws IdentityProvisioningException {

    boolean isDebugEnabled = log.isDebugEnabled();

    String accessToken = authenticate();
    if (StringUtils.isNotBlank(accessToken)) {
        httpMethod.setRequestHeader(SalesforceConnectorConstants.AUTHORIZATION_HEADER_NAME,
                SalesforceConnectorConstants.AUTHORIZATION_HEADER_OAUTH + " " + accessToken);

        if (isDebugEnabled) {
            log.debug("Setting authorization header for method : " + httpMethod.getName()
                    + " as follows,");
            Header authorizationHeader = httpMethod
                    .getRequestHeader(SalesforceConnectorConstants.AUTHORIZATION_HEADER_NAME);
            log.debug(authorizationHeader.getName() + ": " + authorizationHeader.getValue());
        }
    } else {
        throw new IdentityProvisioningException("Authentication failed");
    }

}
 
Example #8
Source File: Action.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private String responseToErrorMessage(final HttpMethodBase method) {
    assert method.isRequestSent() : "no use getting an error message unless the request is sent";

    final Header contentTypeHeader = method.getResponseHeader(CONTENT_TYPE);
    if (contentTypeHeader != null && TEXT_HTML_CONTENT_TYPE.equals(contentTypeHeader.getValue())) {
        // The error message is the response content
        // Safety margin of 1024 characters, anything longer is probably
        // useless and will clutter the logs
        try {
            return method.getResponseBodyAsString(BODY_RESP_MAX_LEN);
        } catch (IOException e) {
            s_logger.debug("Error while loading response body", e);
        }
    }

    // The default
    return method.getStatusText();
}
 
Example #9
Source File: RemoteConnectorRequestImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected static HttpMethodBase buildHttpClientMethod(String url, String method)
{
    if ("GET".equals(method))
    {
        return new GetMethod(url);
    }
    if ("POST".equals(method))
    {
        return new PostMethod(url);
    }
    if ("PUT".equals(method))
    {
        return new PutMethod(url);
    }
    if ("DELETE".equals(method))
    {
        return new DeleteMethod(url);
    }
    if (TestingMethod.METHOD_NAME.equals(method))
    {
        return new TestingMethod(url);
    }
    throw new UnsupportedOperationException("Method '"+method+"' not supported");
}
 
Example #10
Source File: OAuthSampler.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
private void overrideHeaders(HttpMethodBase httpMethod, String url,
                             String method) {
    String headers = getRequestHeaders();
    String[] header = headers.split(System.getProperty("line.separator"));
    for (String kvp : header) {
        int pos = kvp.indexOf(':');
        if (pos < 0) {
            pos = kvp.indexOf('=');
        }
        if (pos > 0) {
            String k = kvp.substring(0, pos).trim();
            String v = "";
            if (kvp.length() > pos + 1) {
                v = kvp.substring(pos + 1).trim();
            }
            httpMethod.addRequestHeader(k, v);
        }
    }
    String authorization = OAuthGenerator.getInstance(getConsumerKey(),
            getConsumerSecret()).getAuthorization(url, method);
    httpMethod.addRequestHeader("Authorization", authorization);
}
 
Example #11
Source File: BigSwitchBcfApi.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private void setHttpHeader(final HttpMethodBase m) {
    m.setRequestHeader(CONTENT_TYPE, CONTENT_JSON);
    m.setRequestHeader(ACCEPT, CONTENT_JSON);
    m.setRequestHeader(HTTP_HEADER_INSTANCE_ID, CLOUDSTACK_INSTANCE_ID + "-" + zoneId);
    if (StringUtils.isNotEmpty(hash)) {
        m.setRequestHeader(HASH_MATCH, hash);
    }

    String authString = username + ":" + password;
    String encodedAuthString = "Basic " + Base64.encodeBase64String(authString.getBytes(Charset.forName("UTF-8")));
    m.setRequestHeader("Authorization", encodedAuthString);
}
 
Example #12
Source File: BigSwitchBcfApi.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private String checkResponse(final HttpMethodBase m, final String errorMessageBase) throws BigSwitchBcfApiException,
IllegalArgumentException{
    String customErrorMsg = null;
    if (m.getStatusCode() == HttpStatus.SC_OK) {
        String hash = "";
        if (m.getResponseHeader(HASH_MATCH) != null) {
            hash = m.getResponseHeader(HASH_MATCH).getValue();
            set_hash(hash);
        }
        return hash;
    }
    if (m.getStatusCode() == HttpStatus.SC_CONFLICT) {
        if(m instanceof GetMethod) {
            return HASH_CONFLICT;
        }
        throw new BigSwitchBcfApiException("BCF topology sync required", true);
    }
    if (m.getStatusCode() == HttpStatus.SC_SEE_OTHER) {
        isMaster = false;
        set_hash(HASH_IGNORE);
        return HASH_IGNORE;
    }
    if (m.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
        if (m instanceof DeleteMethod){
            return "";
        }
    }
    if (m.getStatusCode() == HttpStatus.SC_BAD_REQUEST) {
        customErrorMsg = " Invalid data in BCF request";
        throw new IllegalArgumentException(customErrorMsg);
    }
    String errorMessage = responseToErrorMessage(m);
    m.releaseConnection();
    S_LOGGER.error(errorMessageBase + errorMessage);
    throw new BigSwitchBcfApiException(errorMessageBase + errorMessage + customErrorMsg);
}
 
Example #13
Source File: HMACFilterAuthenticationProvider.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param method
 * @throws HMACSecurityException
 */
public void provideAuthentication(HttpMethodBase method, String body) throws HMACSecurityException {

	String token = validator.generateToken();
	Assert.assertNotNull(token, "token");
	String signature;
	try {
		signature = getSignature(method, body, token);
	} catch (Exception e) {
		throw new HMACSecurityException("Problems while signing the request", e);
	}

	method.addRequestHeader(HMACUtils.HMAC_TOKEN_HEADER, token);
	method.addRequestHeader(HMACUtils.HMAC_SIGNATURE_HEADER, signature);
}
 
Example #14
Source File: SwiftRestClient.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Add the headers to the method, and the auth token (which must be set
 * @param method method to update
 * @param requestHeaders the list of headers
 * @throws SwiftInternalStateException not yet authenticated
 */
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
    throws SwiftInternalStateException {
    for (Header header : requestHeaders) {
      method.addRequestHeader(header);
    }
  setAuthToken(method, getToken());
}
 
Example #15
Source File: BigSwitchApiTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Test
public void testExecuteRetrieveControllerMasterStatusWithTopoConflict() throws BigSwitchBcfApiException, IOException {
    _method = mock(GetMethod.class);
    when(_method.getStatusCode()).thenReturn(HttpStatus.SC_CONFLICT);
    when(((HttpMethodBase)_method).getResponseBodyAsString(2048)).thenReturn("{'healthy': true, 'topologySyncRequested': true}");
    _api.executeRetrieveObject(new TypeToken<ControlClusterStatus>() {
    }.getType(), "/", null);
    verify(_method, times(1)).releaseConnection();
    verify(_client, times(1)).executeMethod(_method);
    assertEquals(_api.getControllerData().isMaster(), true);
}
 
Example #16
Source File: AuthUtils.java    From httpclientAuthHelper with Apache License 2.0 5 votes vote down vote up
public static Header[] printResponseHeaders(HttpMethodBase httpget) throws IOException {
    System.out.println("Printing Response Header...\n");

    Header[] headers = httpget.getResponseHeaders();
    for (Header header : headers) {
        System.out.println("Key : " + header.getName()
                + " ,Value : " + header.getValue());

    }
    return headers;
}
 
Example #17
Source File: NeutronRestApi.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
protected NeutronRestApi(final Class<? extends HttpMethodBase> httpClazz, final String protocol, final int port) {
    client = createHttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    this.httpClazz = httpClazz;

    try {
        // Cast to ProtocolSocketFactory to avoid the deprecated constructor
        // with the SecureProtocolSocketFactory parameter
        Protocol.registerProtocol(protocol, new Protocol(protocol, (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), HTTPS_PORT));
    } catch (IOException e) {
        s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
    }
}
 
Example #18
Source File: ClientEntry.java    From rome with Apache License 2.0 5 votes vote down vote up
void addAuthentication(final HttpMethodBase method) throws ProponoException {
    if (service != null) {
        service.addAuthentication(method);
    } else if (collection != null) {
        collection.addAuthentication(method);
    }
}
 
Example #19
Source File: RemoteConnectorRequestImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected static HttpMethodBase buildHttpClientMethod(String url, Class<? extends HttpMethodBase> method)
{
    HttpMethodBase request = null;
    try
    {
        request = method.getConstructor(String.class).newInstance(url);
    }
    catch(Exception e)
    {
        throw new AlfrescoRuntimeException("HttpClient broken", e);
    }
    return request;
}
 
Example #20
Source File: OldHttpClientApi.java    From javabase with Apache License 2.0 5 votes vote down vote up
private static byte[] executeMethod(HttpMethodBase method, int timeout) throws Exception {
    InputStream in = null;
    try {
        method.addRequestHeader("Connection", "close");
        HttpClient client = new HttpClient();
        HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
        //设置连接时候一些参数
        params.setConnectionTimeout(timeout);
        params.setSoTimeout(timeout);
        params.setStaleCheckingEnabled(false);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE);

        int stat =  client.executeMethod(method);
        if (stat != HttpStatus.SC_OK)
            log.error("get失败!");

        //method.getResponseBody()
        in = method.getResponseBodyAsStream();
        byte[] buffer = new byte[BUFFER_SIZE];
        int len;
        while ((len = in.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }
        return baos.toByteArray();
    }
    finally {
        if (in != null) {
            in.close();
        }
    }
}
 
Example #21
Source File: AbstractApiCommandProcessor.java    From engage-api-client with Apache License 2.0 5 votes vote down vote up
@Override
public HttpMethodBase prepareMethod(String url, ApiRequest request) {
    PostMethod postMethod = new PostMethod(url);
    postMethod = addRequestHeaders(request.getHeaders(), postMethod);
    postMethod = addRequestParameters(request.getParameters(), postMethod);

    return postMethod;
}
 
Example #22
Source File: HttpMethodCloner.java    From http4e with Apache License 2.0 5 votes vote down vote up
private static void copyHttpMethodBase(
  HttpMethodBase m, HttpMethodBase copy) {
    try {
        copy.setParams((HttpMethodParams)m.getParams().clone());
    } catch (CloneNotSupportedException e) {
        // Should never happen
    }
}
 
Example #23
Source File: ProxyFilter.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Will create the method and execute it. After this the method is sent to a
 * ResponseHandler that is returned.
 * 
 * @param httpRequest
 *            Request we are receiving from the client
 * @param url
 *            The location we are proxying to
 * @return A ResponseHandler that can be used to write the response
 * @throws MethodNotAllowedException
 *             If the method specified by the request isn't handled
 * @throws IOException
 *             When there is a problem with the streams
 * @throws HttpException
 *             The httpclient can throw HttpExcetion when executing the
 *             method
 */
ResponseHandler executeRequest(HttpServletRequest httpRequest, String url)
        throws MethodNotAllowedException, IOException, HttpException {
    RequestHandler requestHandler = RequestHandlerFactory
            .createRequestMethod(httpRequest.getMethod());

    HttpMethod method = requestHandler.process(httpRequest, url);
    method.setFollowRedirects(false);

    /*
     * Why does method.validate() return true when the method has been
     * aborted? I mean, if validate returns true the API says that means
     * that the method is ready to be executed. TODO I don't like doing type
     * casting here, see above.
     */
    if (!((HttpMethodBase) method).isAborted()) {
        httpClient.executeMethod(method);

        if (method.getStatusCode() == 405) {
            Header allow = method.getResponseHeader("allow");
            String value = allow.getValue();
            throw new MethodNotAllowedException(
                    "Status code 405 from server",
                    AllowedMethodHandler.processAllowHeader(value));
        }
    }

    return ResponseHandlerFactory.createResponseHandler(method);
}
 
Example #24
Source File: SwiftRestClient.java    From sahara-extra with Apache License 2.0 5 votes vote down vote up
/**
 * Add the headers to the method, and the auth token (which must be set
 * @param method method to update
 * @param requestHeaders the list of headers
 * @throws SwiftInternalStateException not yet authenticated
 */
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
    throws SwiftInternalStateException {
    for (Header header : requestHeaders) {
      method.addRequestHeader(header);
    }
  setAuthToken(method, getToken());
}
 
Example #25
Source File: Worker.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private void parseHtml(HttpMethodBase httpMethod, String response) {
    // parse the html of what we have found

    Header contentType = httpMethod.getResponseHeader("Content-Type");

    if (contentType != null) {
        if (contentType.getValue().startsWith("text")) {
            manager.addHTMLToParseQueue(new HTMLparseWorkUnit(response, work));
        }
    }
}
 
Example #26
Source File: ApiClient.java    From engage-api-client with Apache License 2.0 5 votes vote down vote up
private ApiResult validateSessionAndExecuteCommand(ApiCommand command, Map<String,String> requestHeaders) throws ApiResultException {
	ensureSessionIsOpen();

	REQUEST request = commandProcessor.prepareRequest(command);
       addAdditionalHeadersToRequest(request, requestHeaders);
       addAdditionalHeadersToRequest(request, getSession().getDefaultHeaders());

       HttpMethodBase method = commandProcessor.prepareMethod(getSession().getUrl(), request);
	String in = executeMethod(method);

	ApiResponse response = commandProcessor.processResponse(in, request.getResultType());
	
	return extractResult(command.getClass().getName(), response);
}
 
Example #27
Source File: Worker.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private Charset getCharsetFrom(HttpMethodBase httpMethod) {
    Charset chartSet;

    try {
        chartSet = Charset.forName(httpMethod.getRequestCharSet());
    } catch (Exception ex) {
        chartSet = Charset.forName("UTF-8");
    }
    return chartSet;
}
 
Example #28
Source File: Worker.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private String getHeadersAsString(HttpMethodBase httpMethod) {
    Header[] headers = httpMethod.getResponseHeaders();

    StringBuilder builder = new StringBuilder(20 * (headers.length + 1));

    builder.append(httpMethod.getStatusLine());
    builder.append("\r\n");

    for (Header header : headers) {
        builder.append(header.getName()).append(": ").append(header.getValue());
        builder.append("\r\n");
    }

    return builder.append("\r\n").toString();
}
 
Example #29
Source File: OAuthSampler.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
private HttpMethodBase createHttpMethod(String method, String urlStr) {
    HttpMethodBase httpMethod;
    // May generate IllegalArgumentException
    if (method.equals(HTTPConstantsInterface.POST)) {
        httpMethod = new PostMethod(urlStr);
    } else if (method.equals(HTTPConstantsInterface.PUT)) {
        httpMethod = new PutMethod(urlStr);
    } else if (method.equals(HTTPConstantsInterface.HEAD)) {
        httpMethod = new HeadMethod(urlStr);
    } else if (method.equals(HTTPConstantsInterface.TRACE)) {
        httpMethod = new TraceMethod(urlStr);
    } else if (method.equals(HTTPConstantsInterface.OPTIONS)) {
        httpMethod = new OptionsMethod(urlStr);
    } else if (method.equals(HTTPConstantsInterface.DELETE)) {
        httpMethod = new DeleteMethod(urlStr);
    } else if (method.equals(HTTPConstantsInterface.GET)) {
        httpMethod = new GetMethod(urlStr);
    } else if (method.equals(HTTPConstantsInterface.PATCH)) {
        httpMethod = new PutMethod(urlStr) {
            @Override
            public String getName() {
                return "PATCH";
            }
        };
    } else {
        log.error("Unexpected method (converted to GET): " + method);
        httpMethod = new GetMethod(urlStr);
    }
    return httpMethod;
}
 
Example #30
Source File: NeutronRestFactory.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public NeutronRestApi getNeutronApi(final Class<? extends HttpMethodBase> clazz) {
    if (!flyweight.containsKey(clazz.getName())) {
        NeutronRestApi api = new NeutronRestApi(clazz);
        addNeutronApi(api);
    }
    return flyweight.get(clazz.getName());
}