Search in sources :

Example 26 with HttpPatch

use of org.apache.http.client.methods.HttpPatch in project microservice_framework by CJSCommonPlatform.

the class DefaultUsersUserIdResourceIT method patchRequestFor.

private HttpPatch patchRequestFor(final String uri, final String json, final String contentType, final String accept) throws UnsupportedEncodingException {
    final HttpPatch request = patchRequestFor(uri, json, contentType);
    request.setHeader("Accept", accept);
    return request;
}
Also used : HttpPatch(org.apache.http.client.methods.HttpPatch)

Example 27 with HttpPatch

use of org.apache.http.client.methods.HttpPatch in project carbon-apimgt by wso2.

the class SolaceAdminApis method patchClientIdForApplication.

/**
 * Patch client ID for Solace application
 *
 * @param organization name of the Organization
 * @param application  Application object to be renamed
 * @param consumerKey  Consumer key to be used when patching
 * @param consumerSecret Consumer secret to be used when patching
 * @return CloseableHttpResponse of the PATCH call
 */
public CloseableHttpResponse patchClientIdForApplication(String organization, Application application, String consumerKey, String consumerSecret) {
    URL serviceEndpointURL = new URL(baseUrl);
    HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
    HttpPatch httpPatch = new HttpPatch(baseUrl + "/" + organization + "/developers/" + developerUserName + "/apps/" + application.getUUID());
    httpPatch.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedCredentials());
    httpPatch.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    org.json.JSONObject requestBody = buildRequestBodyForClientIdPatch(application, consumerKey, consumerSecret);
    StringEntity params = null;
    try {
        params = new StringEntity(requestBody.toString());
        httpPatch.setEntity(params);
        return APIUtil.executeHTTPRequest(httpPatch, httpClient);
    } catch (IOException | APIManagementException e) {
        log.error(e.getMessage());
    }
    return null;
}
Also used : StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpClient(org.apache.http.client.HttpClient) IOException(java.io.IOException) URL(org.apache.axis2.util.URL) HttpPatch(org.apache.http.client.methods.HttpPatch)

Example 28 with HttpPatch

use of org.apache.http.client.methods.HttpPatch in project carbon-apimgt by wso2.

the class SolaceAdminApis method applicationPatchRemoveSubscription.

/**
 * Remove subscriptions to application in Solace and update the application
 *
 * @param organization        name of the Organization
 * @param application         Application to be checked in solace
 * @param apiProductsToRemove List of API products to remove from subscriptions
 * @return CloseableHttpResponse of the PATCH call
 */
public CloseableHttpResponse applicationPatchRemoveSubscription(String organization, Application application, List<String> apiProductsToRemove) {
    URL serviceEndpointURL = new URL(baseUrl);
    HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
    HttpPatch httpPatch = new HttpPatch(baseUrl + "/" + organization + "/developers/" + developerUserName + "/apps/" + application.getUUID());
    httpPatch.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedCredentials());
    httpPatch.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    // retrieve existing API products in the app
    ArrayList<String> apiProducts = new ArrayList<>();
    try {
        apiProducts = retrieveApiProductsInAnApplication(applicationGet(organization, application.getUUID(), "default"), apiProducts);
    } catch (IOException e) {
        log.error(e.getMessage());
    }
    // remove API product from arrayList
    apiProducts.removeAll(apiProductsToRemove);
    org.json.JSONObject requestBody = buildRequestBodyForApplicationPatchSubscriptions(apiProducts);
    StringEntity params = null;
    try {
        params = new StringEntity(requestBody.toString());
        httpPatch.setEntity(params);
        return APIUtil.executeHTTPRequest(httpPatch, httpClient);
    } catch (IOException | APIManagementException e) {
        log.error(e.getMessage());
    }
    return null;
}
Also used : StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpClient(org.apache.http.client.HttpClient) ArrayList(java.util.ArrayList) IOException(java.io.IOException) URL(org.apache.axis2.util.URL) HttpPatch(org.apache.http.client.methods.HttpPatch)

Example 29 with HttpPatch

use of org.apache.http.client.methods.HttpPatch in project HongsCORE by ihongs.

the class Remote method request.

/**
 * 简单请求
 *
 * @param type
 * @param kind
 * @param url
 * @param data
 * @param head
 * @param con
 * @throws HongsException
 * @throws StatusException
 * @throws SimpleException
 */
public static void request(METHOD type, FORMAT kind, String url, Map<String, Object> data, Map<String, String> head, Consumer<HttpResponse> con) throws HongsException, StatusException, SimpleException {
    if (url == null) {
        throw new NullPointerException("Request url can not be null");
    }
    HttpRequestBase http = null;
    try {
        // 构建 HTTP 请求对象
        switch(type) {
            case DELETE:
                http = new HttpDelete();
                break;
            case PATCH:
                http = new HttpPatch();
                break;
            case POST:
                http = new HttpPost();
                break;
            case PUT:
                http = new HttpPut();
                break;
            default:
                http = new HttpGet();
                break;
        }
        // 设置报文
        if (data != null) {
            if (http instanceof HttpEntityEnclosingRequest) {
                HttpEntityEnclosingRequest htte = (HttpEntityEnclosingRequest) http;
                if (null != kind)
                    switch(kind) {
                        case JSON:
                            htte.setEntity(buildJson(data));
                            break;
                        case PART:
                            htte.setEntity(buildPart(data));
                            break;
                        default:
                            htte.setEntity(buildPost(data));
                            break;
                    }
                else {
                    htte.setEntity(buildPost(data));
                }
            } else {
                String qry = EntityUtils.toString(buildPost(data), "UTF-8");
                if (url.indexOf('?') == -1) {
                    url += "?" + qry;
                } else {
                    url += "&" + qry;
                }
            }
        }
        // 设置报头
        if (head != null) {
            for (Map.Entry<String, String> et : head.entrySet()) {
                http.setHeader(et.getKey(), et.getValue());
            }
        }
        // 执行请求
        http.setURI(new URI(url));
        HttpResponse rsp = HttpClients.createDefault().execute(http);
        // 异常处理
        int sta = rsp.getStatusLine().getStatusCode();
        if (sta >= 300 && sta <= 399) {
            Header hea = rsp.getFirstHeader("Location");
            String loc = hea != null ? hea.getValue() : "";
            throw new StatusException(sta, url, loc);
        }
        if (sta >= 400 || sta <= 199) {
            HttpEntity t = rsp.getEntity();
            String txt = EntityUtils.toString(t, "UTF-8");
            throw new StatusException(sta, url, txt);
        }
        con.accept(rsp);
    } catch (URISyntaxException | IOException ex) {
        throw new SimpleException(url, ex);
    } finally {
        if (http != null) {
            http.releaseConnection();
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) HttpPatch(org.apache.http.client.methods.HttpPatch) HttpPut(org.apache.http.client.methods.HttpPut) Header(org.apache.http.Header) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) HashMap(java.util.HashMap) Map(java.util.Map)

Example 30 with HttpPatch

use of org.apache.http.client.methods.HttpPatch in project open-kilda by telstra.

the class RestClientManager method invoke.

/**
 * Invoke.
 *
 * @param apiRequestDto the api request dto
 * @return the http response
 */
public HttpResponse invoke(final ApiRequestDto apiRequestDto) {
    HttpResponse httpResponse = null;
    String url = apiRequestDto.getUrl();
    String headers = apiRequestDto.getHeader();
    HttpMethod httpMethod = apiRequestDto.getHttpMethod();
    String payload = apiRequestDto.getPayload();
    try {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509CertChain, authType) -> true).build();
        CloseableHttpClient client = HttpClientBuilder.create().setSSLContext(sslContext).setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)).build())).build();
        HttpUriRequest httpUriRequest = null;
        HttpEntityEnclosingRequestBase httpEntityEnclosingRequest = null;
        // Initializing Request
        if (HttpMethod.POST.equals(httpMethod)) {
            httpEntityEnclosingRequest = new HttpPost(url);
        } else if (HttpMethod.PUT.equals(httpMethod)) {
            httpEntityEnclosingRequest = new HttpPut(url);
        } else if (HttpMethod.DELETE.equals(httpMethod)) {
            httpUriRequest = new HttpDelete(url);
        } else if (HttpMethod.PATCH.equals(httpMethod)) {
            httpUriRequest = new HttpPatch(url);
        } else {
            httpUriRequest = new HttpGet(url);
        }
        Map<String, String> headersMap = new HashMap<String, String>();
        if (!HttpMethod.POST.equals(httpMethod) && !HttpMethod.PUT.equals(httpMethod)) {
            if (!StringUtil.isNullOrEmpty(headers)) {
                for (String header : headers.split("\n")) {
                    getHeaders(headersMap, header);
                    for (Entry<String, String> headerEntrySet : headersMap.entrySet()) {
                        httpUriRequest.setHeader(headerEntrySet.getKey(), headerEntrySet.getValue());
                    }
                }
            }
        }
        if (HttpMethod.POST.equals(httpMethod) || HttpMethod.PUT.equals(httpMethod)) {
            LOGGER.info("[invoke] Executing POST/ PUT request : httpEntityEnclosingRequest : " + httpEntityEnclosingRequest);
            if (!StringUtil.isNullOrEmpty(headers)) {
                for (String header : headers.split("\n")) {
                    getHeaders(headersMap, header);
                    for (Entry<String, String> headerEntrySet : headersMap.entrySet()) {
                        httpEntityEnclosingRequest.setHeader(headerEntrySet.getKey(), headerEntrySet.getValue());
                    }
                }
            }
            // Setting request payload
            httpEntityEnclosingRequest.setEntity(new StringEntity(payload));
            httpResponse = client.execute(httpEntityEnclosingRequest);
            LOGGER.debug("[invoke] Call executed successfully");
        } else {
            LOGGER.info("[invoke] Executing : httpUriRequest : " + httpUriRequest);
            httpResponse = client.execute(httpUriRequest);
            LOGGER.info("[invoke] Call executed successfully");
        }
    } catch (Exception e) {
        LOGGER.error("Error occurred while trying to communicate third party service provider", e);
        throw new RestCallFailedException(e);
    }
    return httpResponse;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) SSLContext(javax.net.ssl.SSLContext) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpPatch(org.apache.http.client.methods.HttpPatch) AuthPropertyService(org.openkilda.service.AuthPropertyService) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) TypeFactory(com.fasterxml.jackson.databind.type.TypeFactory) Map(java.util.Map) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ExternalSystemException(org.openkilda.exception.ExternalSystemException) IAuthConstants(org.openkilda.constants.IAuthConstants) HttpHeaders(org.springframework.http.HttpHeaders) StringEntity(org.apache.http.entity.StringEntity) List(java.util.List) StringUtil(org.openkilda.utility.StringUtil) HttpGet(org.apache.http.client.methods.HttpGet) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) Entry(java.util.Map.Entry) HttpClients(org.apache.http.impl.client.HttpClients) RequestContext(org.openkilda.auth.model.RequestContext) RegistryBuilder(org.apache.http.config.RegistryBuilder) HashMap(java.util.HashMap) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) RestCallFailedException(org.openkilda.exception.RestCallFailedException) ServerContext(org.openkilda.auth.context.ServerContext) InvalidResponseException(org.openkilda.integration.exception.InvalidResponseException) HttpDelete(org.apache.http.client.methods.HttpDelete) ErrorMessage(org.openkilda.model.response.ErrorMessage) HttpClient(org.apache.http.client.HttpClient) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Logger(org.slf4j.Logger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpMethod(org.springframework.http.HttpMethod) UnauthorizedException(org.openkilda.exception.UnauthorizedException) IOException(java.io.IOException) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) HttpError(org.openkilda.constants.HttpError) IoUtil(org.openkilda.utility.IoUtil) HttpStatus(org.springframework.http.HttpStatus) Component(org.springframework.stereotype.Component) HttpPut(org.apache.http.client.methods.HttpPut) ApiRequestDto(org.openkilda.store.common.model.ApiRequestDto) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpDelete(org.apache.http.client.methods.HttpDelete) HashMap(java.util.HashMap) HttpGet(org.apache.http.client.methods.HttpGet) RestCallFailedException(org.openkilda.exception.RestCallFailedException) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HttpPut(org.apache.http.client.methods.HttpPut) HttpPatch(org.apache.http.client.methods.HttpPatch) ExternalSystemException(org.openkilda.exception.ExternalSystemException) RestCallFailedException(org.openkilda.exception.RestCallFailedException) InvalidResponseException(org.openkilda.integration.exception.InvalidResponseException) UnauthorizedException(org.openkilda.exception.UnauthorizedException) IOException(java.io.IOException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StringEntity(org.apache.http.entity.StringEntity) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) HttpMethod(org.springframework.http.HttpMethod)

Aggregations

HttpPatch (org.apache.http.client.methods.HttpPatch)33 HttpPost (org.apache.http.client.methods.HttpPost)15 HttpPut (org.apache.http.client.methods.HttpPut)15 IOException (java.io.IOException)13 StringEntity (org.apache.http.entity.StringEntity)13 HttpGet (org.apache.http.client.methods.HttpGet)12 HttpDelete (org.apache.http.client.methods.HttpDelete)11 HttpClient (org.apache.http.client.HttpClient)7 HttpHead (org.apache.http.client.methods.HttpHead)7 URI (java.net.URI)6 HttpRequestBase (org.apache.http.client.methods.HttpRequestBase)6 HttpResponse (org.apache.http.HttpResponse)5 InputStreamEntity (org.apache.http.entity.InputStreamEntity)5 URISyntaxException (java.net.URISyntaxException)4 HashMap (java.util.HashMap)4 URL (org.apache.axis2.util.URL)4 HttpEntity (org.apache.http.HttpEntity)4 HttpOptions (org.apache.http.client.methods.HttpOptions)4 HttpTrace (org.apache.http.client.methods.HttpTrace)4 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)4