Search in sources :

Example 1 with HttpHeaders

use of com.okta.commons.http.HttpHeaders in project okta-commons-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.commons.http.HttpHeaders) Header(org.apache.http.Header)

Example 2 with HttpHeaders

use of com.okta.commons.http.HttpHeaders in project okta-commons-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;
    // ensure that the content has been fully acquired before closing the http stream
    if (body != null) {
        byte[] bytes = toBytes(entity);
        contentLength = entity.getContentLength();
        if (bytes != null) {
            body = new ByteArrayInputStream(bytes);
        } else {
            body = null;
        }
    } else {
        // force 0 content length when there is no body
        contentLength = 0;
    }
    Response response = new DefaultResponse(httpStatus, mediaType, body, contentLength);
    response.getHeaders().putAll(headers);
    return response;
}
Also used : DefaultResponse(com.okta.commons.http.DefaultResponse) Response(com.okta.commons.http.Response) HttpResponse(org.apache.http.HttpResponse) DefaultResponse(com.okta.commons.http.DefaultResponse) HttpHeaders(com.okta.commons.http.HttpHeaders) HttpEntity(org.apache.http.HttpEntity) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) MediaType(com.okta.commons.http.MediaType)

Example 3 with HttpHeaders

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

the class OkHttpRequestExecutor method toSdkResponse.

private Response toSdkResponse(okhttp3.Response okResponse) throws IOException {
    int httpStatus = okResponse.code();
    HttpHeaders headers = new HttpHeaders();
    headers.putAll(okResponse.headers().toMultimap());
    MediaType mediaType = headers.getContentType();
    ResponseBody body = okResponse.body();
    InputStream bodyInputStream = null;
    long contentLength;
    // ensure that the content has been fully acquired before closing the http stream
    if (body != null) {
        contentLength = body.contentLength();
        bodyInputStream = new ByteArrayInputStream(body.bytes());
    } else {
        // force 0 content length when there is no body
        contentLength = 0;
    }
    Response response = new DefaultResponse(httpStatus, mediaType, bodyInputStream, contentLength);
    response.getHeaders().putAll(headers);
    return response;
}
Also used : DefaultResponse(com.okta.commons.http.DefaultResponse) Response(com.okta.commons.http.Response) DefaultResponse(com.okta.commons.http.DefaultResponse) HttpHeaders(com.okta.commons.http.HttpHeaders) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) MediaType(com.okta.commons.http.MediaType) ResponseBody(okhttp3.ResponseBody)

Example 4 with HttpHeaders

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

the class BaseIDXClient method interact.

@Override
public IDXClientContext interact(String token, EmailTokenType tokenType) throws ProcessingException {
    InteractResponse interactResponse;
    String codeVerifier, codeChallenge, state;
    try {
        codeVerifier = PkceUtil.generateCodeVerifier();
        codeChallenge = PkceUtil.generateCodeChallenge(codeVerifier);
        state = UUID.randomUUID().toString();
        StringBuilder urlParameters = new StringBuilder().append("client_id=").append(clientConfiguration.getClientId()).append("&client_secret=").append(clientConfiguration.getClientSecret()).append("&scope=").append(clientConfiguration.getScopes().stream().map(Object::toString).collect(Collectors.joining(" "))).append("&code_challenge=").append(codeChallenge).append("&code_challenge_method=").append(PkceUtil.CODE_CHALLENGE_METHOD).append("&redirect_uri=").append(clientConfiguration.getRedirectUri()).append("&state=").append(state);
        if (Strings.hasText(token) && !Strings.isEmpty(tokenType)) {
            if (tokenType == EmailTokenType.ACTIVATION_TOKEN) {
                urlParameters.append("&activation_token=").append(token);
            } else if (tokenType == EmailTokenType.RECOVERY_TOKEN) {
                urlParameters.append("&recovery_token=").append(token);
            }
        }
        HttpHeaders httpHeaders = getHttpHeaders(true);
        if (clientConfiguration.getDeviceContext() != null) {
            httpHeaders.setAll(clientConfiguration.getDeviceContext().getAll());
        }
        Request request = new DefaultRequest(HttpMethod.POST, normalizedIssuerUri(clientConfiguration.getIssuer(), "/v1/interact"), null, httpHeaders, new ByteArrayInputStream(urlParameters.toString().getBytes(StandardCharsets.UTF_8)), -1L);
        Response response = requestExecutor.executeRequest(request);
        if (response.getHttpStatus() != 200) {
            handleErrorResponse(request, response);
        }
        JsonNode responseJsonNode = objectMapper.readTree(response.getBody());
        interactResponse = objectMapper.convertValue(responseJsonNode, InteractResponse.class);
        Assert.notNull(interactResponse, "interact response cannot be null");
        Assert.notNull(interactResponse.getInteractionHandle(), "interactionHandle cannot be null");
    } catch (IOException | IllegalArgumentException | HttpException | NoSuchAlgorithmException e) {
        throw new ProcessingException(e);
    }
    return new IDXClientContext(codeVerifier, codeChallenge, interactResponse.getInteractionHandle(), state);
}
Also used : HttpHeaders(com.okta.commons.http.HttpHeaders) DefaultRequest(com.okta.commons.http.DefaultRequest) IDXClientContext(com.okta.idx.sdk.api.model.IDXClientContext) SkipAuthenticatorEnrollmentRequest(com.okta.idx.sdk.api.request.SkipAuthenticatorEnrollmentRequest) Request(com.okta.commons.http.Request) IdentifyRequest(com.okta.idx.sdk.api.request.IdentifyRequest) EnrollUserProfileUpdateRequest(com.okta.idx.sdk.api.request.EnrollUserProfileUpdateRequest) DefaultRequest(com.okta.commons.http.DefaultRequest) EnrollRequest(com.okta.idx.sdk.api.request.EnrollRequest) ChallengeRequest(com.okta.idx.sdk.api.request.ChallengeRequest) CancelRequest(com.okta.idx.sdk.api.request.CancelRequest) RecoverRequest(com.okta.idx.sdk.api.request.RecoverRequest) IntrospectRequest(com.okta.idx.sdk.api.request.IntrospectRequest) AnswerChallengeRequest(com.okta.idx.sdk.api.request.AnswerChallengeRequest) PollRequest(com.okta.idx.sdk.api.request.PollRequest) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ErrorResponse(com.okta.idx.sdk.api.response.ErrorResponse) IDXResponse(com.okta.idx.sdk.api.response.IDXResponse) InteractResponse(com.okta.idx.sdk.api.response.InteractResponse) Response(com.okta.commons.http.Response) TokenResponse(com.okta.idx.sdk.api.response.TokenResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) InteractResponse(com.okta.idx.sdk.api.response.InteractResponse) HttpException(com.okta.commons.http.HttpException) ProcessingException(com.okta.idx.sdk.api.exception.ProcessingException)

Example 5 with HttpHeaders

use of com.okta.commons.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();
        // 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

HttpHeaders (com.okta.commons.http.HttpHeaders)7 Response (com.okta.commons.http.Response)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 InputStream (java.io.InputStream)3 DefaultRequest (com.okta.commons.http.DefaultRequest)2 DefaultResponse (com.okta.commons.http.DefaultResponse)2 MediaType (com.okta.commons.http.MediaType)2 Request (com.okta.commons.http.Request)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 HttpException (com.okta.commons.http.HttpException)1 HttpMethod (com.okta.commons.http.HttpMethod)1 QueryString (com.okta.commons.http.QueryString)1 ProcessingException (com.okta.idx.sdk.api.exception.ProcessingException)1 IDXClientContext (com.okta.idx.sdk.api.model.IDXClientContext)1 AnswerChallengeRequest (com.okta.idx.sdk.api.request.AnswerChallengeRequest)1 CancelRequest (com.okta.idx.sdk.api.request.CancelRequest)1 ChallengeRequest (com.okta.idx.sdk.api.request.ChallengeRequest)1 EnrollRequest (com.okta.idx.sdk.api.request.EnrollRequest)1 EnrollUserProfileUpdateRequest (com.okta.idx.sdk.api.request.EnrollUserProfileUpdateRequest)1 IdentifyRequest (com.okta.idx.sdk.api.request.IdentifyRequest)1