Search in sources :

Example 1 with HttpMethod

use of com.okta.commons.http.HttpMethod in project okta-commons-java by okta.

the class HttpClientRequestFactory method createHttpClientRequest.

/**
 * Creates an HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the original request.
 *
 * @param request        The request to convert to an HttpClient method object.
 * @param previousEntity The optional, previous HTTP entity to reuse in the new request.
 * @return The converted HttpClient method object with any parameters,
 *         headers, etc. from the original request set.
 */
HttpRequestBase createHttpClientRequest(Request request, HttpEntity previousEntity) {
    HttpMethod method = request.getMethod();
    URI uri = getFullyQualifiedUri(request);
    InputStream body = request.getBody();
    long contentLength = request.getHeaders().getContentLength();
    boolean isMultipartFormDataForFileUploading = false;
    String xContentType = RequestUtils.fetchHeaderValueAndRemoveIfPresent(request, "x-contentType");
    if (!Strings.isEmpty(xContentType)) {
        isMultipartFormDataForFileUploading = xContentType.equals(MediaType.MULTIPART_FORM_DATA_VALUE);
    }
    HttpRequestBase base;
    switch(method) {
        case DELETE:
            base = new HttpDelete(uri);
            break;
        case GET:
            base = new HttpGet(uri);
            break;
        case HEAD:
            base = new HttpHead(uri);
            break;
        case POST:
            base = new HttpPost(uri);
            if (isMultipartFormDataForFileUploading) {
                String fileLocation = RequestUtils.fetchHeaderValueAndRemoveIfPresent(request, "x-fileLocation");
                String formDataPartName = RequestUtils.fetchHeaderValueAndRemoveIfPresent(request, "x-fileFormDataName");
                File file = new File(fileLocation);
                HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody(formDataPartName, file).build();
                // remove default Content-Type header
                request.getHeaders().remove("Content-Type");
                ((HttpEntityEnclosingRequestBase) base).setEntity(entity);
            } else {
                ((HttpEntityEnclosingRequestBase) base).setEntity(new RepeatableInputStreamEntity(request));
            }
            break;
        case PUT:
            base = new HttpPut(uri);
            // Enable 100-continue support for PUT operations, since this is  where we're potentially uploading
            // large amounts of data and want to find out as early as possible if an operation will fail. We
            // don't want to do this for all operations since it will cause extra latency in the network
            // interaction.
            base.setConfig(RequestConfig.copy(defaultRequestConfig).setExpectContinueEnabled(true).build());
            if (previousEntity != null) {
                ((HttpEntityEnclosingRequestBase) base).setEntity(previousEntity);
            } else if (body != null) {
                HttpEntity entity = new RepeatableInputStreamEntity(request);
                if (contentLength < 0) {
                    entity = newBufferedHttpEntity(entity);
                }
                ((HttpEntityEnclosingRequestBase) base).setEntity(entity);
            }
            break;
        default:
            throw new IllegalArgumentException("Unrecognized HttpMethod: " + method);
    }
    base.setProtocolVersion(HttpVersion.HTTP_1_1);
    applyHeaders(base, request);
    return base;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) QueryString(com.okta.commons.http.QueryString) URI(java.net.URI) HttpHead(org.apache.http.client.methods.HttpHead) HttpPut(org.apache.http.client.methods.HttpPut) File(java.io.File) HttpMethod(com.okta.commons.http.HttpMethod)

Example 2 with HttpMethod

use of com.okta.commons.http.HttpMethod in project okta-commons-java by okta.

the class OkHttpRequestExecutor method executeRequest.

@Override
public Response executeRequest(Request request) throws HttpException {
    // Sign the request
    this.requestAuthenticator.authenticate(request);
    HttpUrl.Builder urlBuilder = HttpUrl.get(request.getResourceUrl()).newBuilder();
    // query params
    request.getQueryString().forEach(urlBuilder::addQueryParameter);
    okhttp3.Request.Builder okRequestBuilder = new okhttp3.Request.Builder().url(urlBuilder.build());
    // headers
    request.getHeaders().toSingleValueMap().forEach(okRequestBuilder::addHeader);
    boolean isMultipartFormDataForFileUploading = false;
    String xContentType = RequestUtils.fetchHeaderValueAndRemoveIfPresent(request, "x-contentType");
    if (!Strings.isEmpty(xContentType)) {
        isMultipartFormDataForFileUploading = xContentType.equals(MediaType.MULTIPART_FORM_DATA_VALUE);
    }
    HttpMethod method = request.getMethod();
    switch(method) {
        case DELETE:
            okRequestBuilder.delete();
            break;
        case GET:
            okRequestBuilder.get();
            break;
        case HEAD:
            okRequestBuilder.head();
            break;
        case POST:
            if (isMultipartFormDataForFileUploading) {
                String fileLocation = RequestUtils.fetchHeaderValueAndRemoveIfPresent(request, "x-fileLocation");
                String formDataPartName = RequestUtils.fetchHeaderValueAndRemoveIfPresent(request, "x-fileFormDataName");
                File file = new File(fileLocation);
                RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart(formDataPartName, file.getName(), RequestBody.create(null, file)).build();
                okRequestBuilder.post(requestBody);
            } else {
                okRequestBuilder.post(new InputStreamRequestBody(request.getBody(), request.getHeaders().getContentType()));
            }
            break;
        case PUT:
            // TODO support 100-continue ?
            okRequestBuilder.put(new InputStreamRequestBody(request.getBody(), request.getHeaders().getContentType()));
            break;
        default:
            throw new IllegalArgumentException("Unrecognized HttpMethod: " + method);
    }
    try {
        okhttp3.Response okResponse = client.newCall(okRequestBuilder.build()).execute();
        return toSdkResponse(okResponse);
    } catch (SocketException | SocketTimeoutException e) {
        throw new HttpException("Unable to execute HTTP request - retryable exception: " + e.getMessage(), e, true);
    } catch (IOException e) {
        throw new HttpException(e.getMessage(), e);
    }
}
Also used : SocketException(java.net.SocketException) Request(com.okta.commons.http.Request) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) SocketTimeoutException(java.net.SocketTimeoutException) MultipartBody(okhttp3.MultipartBody) HttpException(com.okta.commons.http.HttpException) File(java.io.File) HttpMethod(com.okta.commons.http.HttpMethod) RequestBody(okhttp3.RequestBody)

Example 3 with HttpMethod

use of com.okta.commons.http.HttpMethod in project okta-sdk-java by okta.

the class DefaultDataStore method save.

@SuppressWarnings("unchecked")
private <T extends Resource, R extends Resource> R save(String href, final T resource, final T parentResource, HttpHeaders requestHeaders, final Class<? extends R> returnType, final QueryString qs, final boolean create) {
    Assert.hasText(href, "href argument cannot be null or empty.");
    Assert.notNull(resource, "resource argument cannot be null.");
    Assert.notNull(returnType, "returnType class cannot be null.");
    Assert.isInstanceOf(AbstractResource.class, resource);
    Assert.isTrue(!CollectionResource.class.isAssignableFrom(resource.getClass()), "Collections cannot be persisted.");
    final CanonicalUri uri = canonicalize(href, qs);
    final AbstractResource abstractResource = (AbstractResource) resource;
    // Most Okta endpoints do not support partial update, we can revisit in the future.
    final Map<String, Object> props = resourceConverter.convert(abstractResource, false);
    FilterChain chain = new DefaultFilterChain(this.filters, req -> {
        CanonicalUri uri1 = req.getUri();
        String href1 = uri1.getAbsolutePath();
        QueryString qs1 = uri1.getQuery();
        HttpHeaders httpHeaders = req.getHttpHeaders();
        // create == POST
        HttpMethod method = HttpMethod.POST;
        if (!create) {
            method = HttpMethod.PUT;
        }
        InputStream body;
        long length = 0;
        if (resource instanceof VoidResource) {
            body = new ByteArrayInputStream(new byte[0]);
        } else if (resource instanceof FileResource) {
            body = new ByteArrayInputStream(new byte[0]);
            httpHeaders.add("x-fileLocation", ((FileResource) resource).getLocation());
            httpHeaders.add("x-fileFormDataName", ((FileResource) resource).getFormDataName());
        } else {
            ByteArrayOutputStream bodyOut = new ByteArrayOutputStream();
            mapMarshaller.marshal(bodyOut, req.getData());
            body = new ByteArrayInputStream(bodyOut.toByteArray());
            length = bodyOut.size();
        }
        Request request = new DefaultRequest(method, href1, qs1, httpHeaders, body, length);
        Response response = execute(request);
        Map<String, Object> responseBody = getBody(response);
        if (Collections.isEmpty(responseBody)) {
            // Okta response with 200 for deactivate requests (i.e. /api/v1/apps/<id>/lifecycle/deactivate)
            if (response.getHttpStatus() == 202 || response.getHttpStatus() == 200 || response.getHttpStatus() == 201 || response.getHttpStatus() == 204) {
                // 202 means that the request has been accepted for processing, but the processing has not been completed. Therefore we do not have a response setBody.
                responseBody = java.util.Collections.emptyMap();
            } else {
                throw new IllegalStateException("Unable to obtain resource data from the API server.");
            }
        }
        ResourceAction responseAction = getPostAction(req, response);
        return new DefaultResourceDataResult(responseAction, uri1, returnType, responseBody);
    });
    ResourceAction action = create ? ResourceAction.CREATE : ResourceAction.UPDATE;
    ResourceDataRequest request = new DefaultResourceDataRequest(action, uri, canonicalizeParent(parentResource), returnType, getResourceClass(parentResource), props, requestHeaders);
    DefaultResourceDataResult result = (DefaultResourceDataResult) chain.filter(request);
    Map<String, Object> data = result.getData();
    // ensure the caller's argument is updated with what is returned from the server if the types are the same:
    if (returnType.isAssignableFrom(abstractResource.getClass())) {
        abstractResource.setInternalProperties(data);
    }
    return resourceFactory.instantiate(returnType, data);
}
Also used : HttpHeaders(com.okta.commons.http.HttpHeaders) DefaultRequest(com.okta.commons.http.DefaultRequest) QueryString(com.okta.commons.http.QueryString) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) FileResource(com.okta.sdk.resource.FileResource) Request(com.okta.commons.http.Request) DefaultRequest(com.okta.commons.http.DefaultRequest) AbstractResource(com.okta.sdk.impl.resource.AbstractResource) QueryString(com.okta.commons.http.QueryString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Response(com.okta.commons.http.Response) DefaultCanonicalUri(com.okta.sdk.impl.http.support.DefaultCanonicalUri) CanonicalUri(com.okta.sdk.impl.http.CanonicalUri) VoidResource(com.okta.sdk.resource.VoidResource) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpMethod(com.okta.commons.http.HttpMethod)

Aggregations

HttpMethod (com.okta.commons.http.HttpMethod)3 QueryString (com.okta.commons.http.QueryString)2 Request (com.okta.commons.http.Request)2 File (java.io.File)2 InputStream (java.io.InputStream)2 DefaultRequest (com.okta.commons.http.DefaultRequest)1 HttpException (com.okta.commons.http.HttpException)1 HttpHeaders (com.okta.commons.http.HttpHeaders)1 Response (com.okta.commons.http.Response)1 CanonicalUri (com.okta.sdk.impl.http.CanonicalUri)1 DefaultCanonicalUri (com.okta.sdk.impl.http.support.DefaultCanonicalUri)1 AbstractResource (com.okta.sdk.impl.resource.AbstractResource)1 FileResource (com.okta.sdk.resource.FileResource)1 VoidResource (com.okta.sdk.resource.VoidResource)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 SocketException (java.net.SocketException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 URI (java.net.URI)1