Search in sources :

Example 11 with HttpPatch

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

the class SolaceAdminApis method renameApplication.

/**
 * Rename application in Solace Broker
 *
 * @param organization name of the Organization
 * @param application  Application object to be renamed
 * @return CloseableHttpResponse of the DELETE call
 */
public CloseableHttpResponse renameApplication(String organization, Application application) {
    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 = buildRequestBodyForRenamingApp(application);
    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 12 with HttpPatch

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

the class SolaceAdminApis method applicationPatchAddSubscription.

/**
 * Add subscriptions to application in Solace and update the application
 *
 * @param organization name of the Organization
 * @param application  Application to be checked in solace
 * @param apiProducts  API products to add as subscriptions
 * @return CloseableHttpResponse of the PATCH call
 */
public CloseableHttpResponse applicationPatchAddSubscription(String organization, Application application, ArrayList<String> apiProducts) {
    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
    try {
        apiProducts = retrieveApiProductsInAnApplication(applicationGet(organization, application.getUUID(), "default"), apiProducts);
    } catch (IOException e) {
        log.error(e.getMessage());
    }
    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) IOException(java.io.IOException) URL(org.apache.axis2.util.URL) HttpPatch(org.apache.http.client.methods.HttpPatch)

Example 13 with HttpPatch

use of org.apache.http.client.methods.HttpPatch in project iaf by ibissource.

the class HttpSender method getMethod.

/**
 * Returns HttpRequestBase, with (optional) RAW or as BINAIRY content
 */
protected HttpRequestBase getMethod(URI uri, Message message, ParameterValueList parameters) throws SenderException {
    try {
        boolean queryParametersAppended = false;
        StringBuffer relativePath = new StringBuffer(uri.getRawPath());
        if (!StringUtils.isEmpty(uri.getQuery())) {
            relativePath.append("?" + uri.getQuery());
            queryParametersAppended = true;
        }
        switch(getHttpMethod()) {
            case GET:
                if (parameters != null) {
                    queryParametersAppended = appendParameters(queryParametersAppended, relativePath, parameters);
                    if (log.isDebugEnabled())
                        log.debug(getLogPrefix() + "path after appending of parameters [" + relativePath + "]");
                }
                HttpGet getMethod = new HttpGet(relativePath + (parameters == null && !Message.isEmpty(message) ? message.asString() : ""));
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "HttpSender constructed GET-method [" + getMethod.getURI().getQuery() + "]");
                if (null != getFullContentType()) {
                    // Manually set Content-Type header
                    getMethod.setHeader("Content-Type", getFullContentType().toString());
                }
                return getMethod;
            case POST:
            case PUT:
            case PATCH:
                HttpEntity entity;
                if (postType.equals(PostType.RAW)) {
                    String messageString = message.asString();
                    if (parameters != null) {
                        StringBuffer msg = new StringBuffer(messageString);
                        appendParameters(true, msg, parameters);
                        if (StringUtils.isEmpty(messageString) && msg.length() > 1) {
                            messageString = msg.substring(1);
                        } else {
                            messageString = msg.toString();
                        }
                    }
                    entity = new ByteArrayEntity(messageString.getBytes(StreamUtil.DEFAULT_INPUT_STREAM_ENCODING), getFullContentType());
                } else if (postType.equals(PostType.BINARY)) {
                    entity = new InputStreamEntity(message.asInputStream(), getFullContentType());
                } else {
                    throw new SenderException("PostType [" + postType.name() + "] not allowed!");
                }
                HttpEntityEnclosingRequestBase method;
                if (getHttpMethod() == HttpMethod.POST) {
                    method = new HttpPost(relativePath.toString());
                } else if (getHttpMethod() == HttpMethod.PATCH) {
                    method = new HttpPatch(relativePath.toString());
                } else {
                    method = new HttpPut(relativePath.toString());
                }
                method.setEntity(entity);
                return method;
            case DELETE:
                HttpDelete deleteMethod = new HttpDelete(relativePath.toString());
                if (null != getFullContentType()) {
                    // Manually set Content-Type header
                    deleteMethod.setHeader("Content-Type", getFullContentType().toString());
                }
                return deleteMethod;
            case HEAD:
                return new HttpHead(relativePath.toString());
            case REPORT:
                Element element = XmlUtils.buildElement(message.asString(), true);
                HttpReport reportMethod = new HttpReport(relativePath.toString(), element);
                if (null != getFullContentType()) {
                    // Manually set Content-Type header
                    reportMethod.setHeader("Content-Type", getFullContentType().toString());
                }
                return reportMethod;
            default:
                return null;
        }
    } catch (Exception e) {
        // Catch all exceptions and throw them as SenderException
        throw new SenderException(e);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpEntity(org.apache.http.HttpEntity) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpGet(org.apache.http.client.methods.HttpGet) Element(org.w3c.dom.Element) HttpPatch(org.apache.http.client.methods.HttpPatch) HttpPut(org.apache.http.client.methods.HttpPut) HttpHead(org.apache.http.client.methods.HttpHead) URISyntaxException(java.net.URISyntaxException) MessagingException(javax.mail.MessagingException) DomBuilderException(nl.nn.adapterframework.util.DomBuilderException) SenderException(nl.nn.adapterframework.core.SenderException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) InputStreamEntity(org.apache.http.entity.InputStreamEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) SenderException(nl.nn.adapterframework.core.SenderException)

Example 14 with HttpPatch

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

the class RestClientManager method invoke.

/**
 * Invoke.
 *
 * @param apiUrl the api url
 * @param httpMethod the http method
 * @param payload the payload
 * @param contentType the content type
 * @param basicAuth the basic auth
 * @return the http response
 */
public HttpResponse invoke(final String apiUrl, final HttpMethod httpMethod, final String payload, final String contentType, final String basicAuth) {
    HttpResponse httpResponse = null;
    try {
        RequestContext requestContext = serverContext.getRequestContext();
        HttpClient client = HttpClients.createDefault();
        HttpUriRequest httpUriRequest = null;
        HttpEntityEnclosingRequestBase httpEntityEnclosingRequest = null;
        // Initializing Request
        if (HttpMethod.POST.equals(httpMethod)) {
            httpEntityEnclosingRequest = new HttpPost(apiUrl);
        } else if (HttpMethod.PUT.equals(httpMethod)) {
            httpEntityEnclosingRequest = new HttpPut(apiUrl);
        } else if (HttpMethod.DELETE.equals(httpMethod)) {
            httpEntityEnclosingRequest = new HttpEntityEnclosingRequestBase() {

                @Override
                public String getMethod() {
                    return "DELETE";
                }
            };
        } else if (HttpMethod.PATCH.equals(httpMethod)) {
            httpEntityEnclosingRequest = new HttpPatch(apiUrl);
        } else {
            httpUriRequest = new HttpGet(apiUrl);
        }
        if (!HttpMethod.POST.equals(httpMethod) && !HttpMethod.PUT.equals(httpMethod) && !HttpMethod.PATCH.equals(httpMethod) && !HttpMethod.DELETE.equals(httpMethod)) {
            // Setting Required Headers
            if (!StringUtil.isNullOrEmpty(basicAuth)) {
                LOGGER.debug("[invoke] Setting authorization in header as " + IAuthConstants.Header.AUTHORIZATION);
                httpUriRequest.setHeader(IAuthConstants.Header.AUTHORIZATION, basicAuth);
                httpUriRequest.setHeader(IAuthConstants.Header.CORRELATION_ID, requestContext.getCorrelationId());
            }
        }
        if (HttpMethod.POST.equals(httpMethod) || HttpMethod.PUT.equals(httpMethod) || HttpMethod.PATCH.equals(httpMethod)) {
            LOGGER.info("[invoke] Executing POST/ PUT request : httpEntityEnclosingRequest : " + httpEntityEnclosingRequest + " : payload : " + payload);
            // Setting POST/PUT related headers
            httpEntityEnclosingRequest.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
            httpEntityEnclosingRequest.setHeader(IAuthConstants.Header.AUTHORIZATION, basicAuth);
            httpEntityEnclosingRequest.setHeader(IAuthConstants.Header.CORRELATION_ID, requestContext.getCorrelationId());
            // Setting request payload
            httpEntityEnclosingRequest.setEntity(new StringEntity(payload));
            httpResponse = client.execute(httpEntityEnclosingRequest);
            LOGGER.debug("[invoke] Call executed successfully");
        } else if (HttpMethod.DELETE.equals(httpMethod)) {
            httpEntityEnclosingRequest.setURI(URI.create(apiUrl));
            LOGGER.info("[invoke] Executing DELETE request : httpDeleteRequest : " + httpEntityEnclosingRequest + " : payload : " + payload);
            // Setting DELETE related headers
            httpEntityEnclosingRequest.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
            httpEntityEnclosingRequest.setHeader(IAuthConstants.Header.EXTRA_AUTH, String.valueOf(System.currentTimeMillis()));
            httpEntityEnclosingRequest.setHeader(IAuthConstants.Header.AUTHORIZATION, basicAuth);
            httpEntityEnclosingRequest.setHeader(IAuthConstants.Header.CORRELATION_ID, requestContext.getCorrelationId());
            // 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 : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpGet(org.apache.http.client.methods.HttpGet) RestCallFailedException(org.openkilda.exception.RestCallFailedException) HttpResponse(org.apache.http.HttpResponse) 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) StringEntity(org.apache.http.entity.StringEntity) HttpClient(org.apache.http.client.HttpClient) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestContext(org.openkilda.auth.model.RequestContext)

Example 15 with HttpPatch

use of org.apache.http.client.methods.HttpPatch in project iaf by ibissource.

the class HttpResponseMock method answer.

@Override
public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
    HttpHost host = (HttpHost) invocation.getArguments()[0];
    HttpRequestBase request = (HttpRequestBase) invocation.getArguments()[1];
    HttpContext context = (HttpContext) invocation.getArguments()[2];
    InputStream response = null;
    if (request instanceof HttpGet)
        response = doGet(host, (HttpGet) request, context);
    else if (request instanceof HttpPost)
        response = doPost(host, (HttpPost) request, context);
    else if (request instanceof HttpPut)
        response = doPut(host, (HttpPut) request, context);
    else if (request instanceof HttpPatch)
        response = doPatch(host, (HttpPatch) request, context);
    else if (request instanceof HttpDelete)
        response = doDelete(host, (HttpDelete) request, context);
    else
        throw new Exception("mock method not implemented");
    return buildResponse(response);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpHost(org.apache.http.HttpHost) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) HttpContext(org.apache.http.protocol.HttpContext) HttpPut(org.apache.http.client.methods.HttpPut) HttpPatch(org.apache.http.client.methods.HttpPatch) ParseException(org.apache.http.ParseException) IOException(java.io.IOException)

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