Search in sources :

Example 1 with HttpHeaders

use of com.okta.sdk.impl.http.HttpHeaders in project okta-sdk-java by okta.

the class HttpClientRequestExecutor method toSdkResponse.

protected Response toSdkResponse(HttpResponse httpResponse) throws IOException {
    int httpStatus = httpResponse.getStatusLine().getStatusCode();
    HttpHeaders headers = getHeaders(httpResponse);
    MediaType mediaType = headers.getContentType();
    HttpEntity entity = getHttpEntity(httpResponse);
    InputStream body = entity != null ? entity.getContent() : null;
    long contentLength = entity != null ? entity.getContentLength() : -1;
    // ensure that the content has been fully acquired before closing the http stream
    if (body != null) {
        byte[] bytes = toBytes(entity);
        if (bytes != null) {
            body = new ByteArrayInputStream(bytes);
        } else {
            body = null;
        }
    }
    Response response = new DefaultResponse(httpStatus, mediaType, body, contentLength);
    response.getHeaders().add(HttpHeaders.OKTA_REQUEST_ID, headers.getOktaRequestId());
    response.getHeaders().put(HttpHeaders.LINK, headers.getLinkHeaders());
    return response;
}
Also used : DefaultResponse(com.okta.sdk.impl.http.support.DefaultResponse) Response(com.okta.sdk.impl.http.Response) HttpResponse(org.apache.http.HttpResponse) DefaultResponse(com.okta.sdk.impl.http.support.DefaultResponse) HttpHeaders(com.okta.sdk.impl.http.HttpHeaders) HttpEntity(org.apache.http.HttpEntity) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) MediaType(com.okta.sdk.impl.http.MediaType)

Example 2 with HttpHeaders

use of com.okta.sdk.impl.http.HttpHeaders 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();
        // if this is an Okta user, we must use a PUT and not a 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 {
            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() == 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 body.
                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);
    ResourceDataResult result = 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.sdk.impl.http.HttpHeaders) DefaultRequest(com.okta.sdk.impl.http.support.DefaultRequest) QueryString(com.okta.sdk.impl.http.QueryString) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) DefaultRequest(com.okta.sdk.impl.http.support.DefaultRequest) Request(com.okta.sdk.impl.http.Request) AbstractResource(com.okta.sdk.impl.resource.AbstractResource) QueryString(com.okta.sdk.impl.http.QueryString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Response(com.okta.sdk.impl.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.sdk.http.HttpMethod)

Example 3 with HttpHeaders

use of com.okta.sdk.impl.http.HttpHeaders in project okta-sdk-java by okta.

the class HttpClientRequestExecutor method executeRequest.

@Override
public Response executeRequest(Request request) throws RestException {
    Assert.notNull(request, "Request argument cannot be null.");
    int retryCount = 0;
    URI redirectUri = null;
    HttpEntity entity = null;
    RestException exception = null;
    // Make a copy of the original request params and headers so that we can
    // permute them in the loop and start over with the original every time.
    QueryString originalQuery = new QueryString();
    originalQuery.putAll(request.getQueryString());
    HttpHeaders originalHeaders = new HttpHeaders();
    originalHeaders.putAll(request.getHeaders());
    while (true) {
        if (redirectUri != null) {
            request = new DefaultRequest(request.getMethod(), redirectUri.toString(), null, null, request.getBody(), request.getHeaders().getContentLength());
        }
        if (retryCount > 0) {
            request.setQueryString(originalQuery);
            request.setHeaders(originalHeaders);
        }
        // Sign the request
        this.requestAuthenticator.authenticate(request);
        HttpRequestBase httpRequest = this.httpClientRequestFactory.createHttpClientRequest(request, entity);
        if (httpRequest instanceof HttpEntityEnclosingRequest) {
            entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity();
        }
        HttpResponse httpResponse = null;
        try {
            // before executing the request below.
            if (retryCount > 0 && redirectUri == null) {
                pauseExponentially(retryCount, exception);
                if (entity != null) {
                    InputStream content = entity.getContent();
                    if (content.markSupported()) {
                        content.reset();
                    }
                }
            }
            // reset redirectUri so that if there is an exception, we will pause on retry
            redirectUri = null;
            exception = null;
            retryCount++;
            httpResponse = httpClient.execute(httpRequest);
            if (isRedirect(httpResponse)) {
                Header[] locationHeaders = httpResponse.getHeaders("Location");
                String location = locationHeaders[0].getValue();
                log.debug("Redirecting to: {}", location);
                redirectUri = URI.create(location);
                httpRequest.setURI(redirectUri);
            } else {
                Response response = toSdkResponse(httpResponse);
                int httpStatus = response.getHttpStatus();
                if (httpStatus == 429) {
                    throw new RestException("HTTP 429: Too Many Requests.  Exceeded request rate limit in the allotted amount of time.");
                }
                if ((httpStatus == 503 || httpStatus == 504) && retryCount <= this.numRetries) {
                    // allow the loop to continue to execute a retry request
                    continue;
                }
                return response;
            }
        } catch (Throwable t) {
            log.warn("Unable to execute HTTP request: ", t.getMessage(), t);
            if (t instanceof RestException) {
                exception = (RestException) t;
            }
            if (!shouldRetry(httpRequest, t, retryCount)) {
                throw new RestException("Unable to execute HTTP request: " + t.getMessage(), t);
            }
        } finally {
            try {
                httpResponse.getEntity().getContent().close();
            } catch (Throwable ignored) {
            // NOPMD
            }
        }
    }
}
Also used : HttpHeaders(com.okta.sdk.impl.http.HttpHeaders) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntity(org.apache.http.HttpEntity) DefaultRequest(com.okta.sdk.impl.http.support.DefaultRequest) QueryString(com.okta.sdk.impl.http.QueryString) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) RestException(com.okta.sdk.impl.http.RestException) HttpResponse(org.apache.http.HttpResponse) QueryString(com.okta.sdk.impl.http.QueryString) URI(java.net.URI) DefaultResponse(com.okta.sdk.impl.http.support.DefaultResponse) Response(com.okta.sdk.impl.http.Response) HttpResponse(org.apache.http.HttpResponse) Header(org.apache.http.Header) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest)

Example 4 with HttpHeaders

use of com.okta.sdk.impl.http.HttpHeaders in project okta-sdk-java by okta.

the class HttpClientRequestExecutor method getHeaders.

private HttpHeaders getHeaders(HttpResponse response) {
    HttpHeaders headers = new HttpHeaders();
    Header[] httpHeaders = response.getAllHeaders();
    if (httpHeaders != null) {
        for (Header httpHeader : httpHeaders) {
            headers.add(httpHeader.getName(), httpHeader.getValue());
        }
    }
    return headers;
}
Also used : HttpHeaders(com.okta.sdk.impl.http.HttpHeaders) Header(org.apache.http.Header)

Aggregations

HttpHeaders (com.okta.sdk.impl.http.HttpHeaders)4 Response (com.okta.sdk.impl.http.Response)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 InputStream (java.io.InputStream)3 QueryString (com.okta.sdk.impl.http.QueryString)2 DefaultRequest (com.okta.sdk.impl.http.support.DefaultRequest)2 DefaultResponse (com.okta.sdk.impl.http.support.DefaultResponse)2 Header (org.apache.http.Header)2 HttpEntity (org.apache.http.HttpEntity)2 HttpResponse (org.apache.http.HttpResponse)2 HttpMethod (com.okta.sdk.http.HttpMethod)1 CanonicalUri (com.okta.sdk.impl.http.CanonicalUri)1 MediaType (com.okta.sdk.impl.http.MediaType)1 Request (com.okta.sdk.impl.http.Request)1 RestException (com.okta.sdk.impl.http.RestException)1 DefaultCanonicalUri (com.okta.sdk.impl.http.support.DefaultCanonicalUri)1 AbstractResource (com.okta.sdk.impl.resource.AbstractResource)1 VoidResource (com.okta.sdk.resource.VoidResource)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 URI (java.net.URI)1