Search in sources :

Example 11 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project forest by dromara.

the class OkHttp3LogBodyMessage method getBodyString.

@Override
public String getBodyString() {
    if (requestBody == null) {
        return null;
    }
    MediaType mediaType = requestBody.contentType();
    if (mediaType == null) {
        return getLogContentForStringBody(this.requestBody);
    }
    ContentType contentType = new ContentType(mediaType.toString());
    if (contentType.isMultipart()) {
        MultipartBody multipartBody = (MultipartBody) requestBody;
        String boundary = multipartBody.boundary();
        Long contentLength = null;
        try {
            contentLength = multipartBody.contentLength();
        } catch (IOException e) {
        }
        StringBuilder builder = new StringBuilder();
        builder.append("[").append("boundary=").append(boundary);
        if (contentLength != null) {
            builder.append("; length=").append(contentLength);
        }
        builder.append("] parts:");
        List<MultipartBody.Part> parts = multipartBody.parts();
        for (MultipartBody.Part part : parts) {
            RequestBody partBody = part.body();
            List<String> disposition = part.headers().values("Content-Disposition");
            builder.append("\n             -- [").append(disposition.get(0));
            MediaType partMediaType = partBody.contentType();
            if (partMediaType == null) {
                builder.append("; content-type=\"").append(partBody.contentType()).append("\"");
                builder.append("; value=\"").append(getLogContentForStringBody(partBody)).append("\"]");
            } else {
                Long length = null;
                try {
                    length = partBody.contentLength();
                } catch (IOException e) {
                }
                if (length != null) {
                    builder.append("; length=").append(length);
                }
                builder.append("; content-type=\"").append(partBody.contentType()).append("\"");
                builder.append("]");
            }
        }
        return builder.toString();
    } else if (contentType.isBinary()) {
        try {
            return "[Binary length=" + requestBody.contentLength() + "]";
        } catch (IOException e) {
            throw new ForestRuntimeException(e);
        }
    }
    return getLogContentForStringBody(this.requestBody);
}
Also used : ContentType(com.dtflys.forest.backend.ContentType) ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) IOException(java.io.IOException) MultipartBody(okhttp3.MultipartBody) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 12 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project java-sdk by dapr.

the class DaprHttp method doInvokeApi.

/**
 * Invokes an API that returns a text payload.
 *
 * @param method        HTTP method.
 * @param pathSegments  Array of path segments (/a/b/c -> ["a", "b", "c"]).
 * @param urlParameters Parameters in the URL
 * @param content       payload to be posted.
 * @param headers       HTTP headers.
 * @param context       OpenTelemetry's Context.
 * @return CompletableFuture for Response.
 */
private CompletableFuture<Response> doInvokeApi(String method, String[] pathSegments, Map<String, List<String>> urlParameters, byte[] content, Map<String, String> headers, Context context) {
    final String requestId = UUID.randomUUID().toString();
    RequestBody body;
    String contentType = headers != null ? headers.get(Metadata.CONTENT_TYPE) : null;
    MediaType mediaType = contentType == null ? MEDIA_TYPE_APPLICATION_JSON : MediaType.get(contentType);
    if (content == null) {
        body = mediaType.equals(MEDIA_TYPE_APPLICATION_JSON) ? REQUEST_BODY_EMPTY_JSON : RequestBody.Companion.create(new byte[0], mediaType);
    } else {
        body = RequestBody.Companion.create(content, mediaType);
    }
    HttpUrl.Builder urlBuilder = new HttpUrl.Builder();
    urlBuilder.scheme(DEFAULT_HTTP_SCHEME).host(this.hostname).port(this.port);
    for (String pathSegment : pathSegments) {
        urlBuilder.addPathSegment(pathSegment);
    }
    Optional.ofNullable(urlParameters).orElse(Collections.emptyMap()).entrySet().stream().forEach(urlParameter -> Optional.ofNullable(urlParameter.getValue()).orElse(Collections.emptyList()).stream().forEach(urlParameterValue -> urlBuilder.addQueryParameter(urlParameter.getKey(), urlParameterValue)));
    Request.Builder requestBuilder = new Request.Builder().url(urlBuilder.build()).addHeader(HEADER_DAPR_REQUEST_ID, requestId);
    if (context != null) {
        context.stream().filter(entry -> ALLOWED_CONTEXT_IN_HEADERS.contains(entry.getKey().toString().toLowerCase())).forEach(entry -> requestBuilder.addHeader(entry.getKey().toString(), entry.getValue().toString()));
    }
    if (HttpMethods.GET.name().equals(method)) {
        requestBuilder.get();
    } else if (HttpMethods.DELETE.name().equals(method)) {
        requestBuilder.delete();
    } else {
        requestBuilder.method(method, body);
    }
    String daprApiToken = Properties.API_TOKEN.get();
    if (daprApiToken != null) {
        requestBuilder.addHeader(Headers.DAPR_API_TOKEN, daprApiToken);
    }
    if (headers != null) {
        Optional.ofNullable(headers.entrySet()).orElse(Collections.emptySet()).stream().forEach(header -> {
            requestBuilder.addHeader(header.getKey(), header.getValue());
        });
    }
    Request request = requestBuilder.build();
    CompletableFuture<Response> future = new CompletableFuture<>();
    this.httpClient.newCall(request).enqueue(new ResponseFutureCallback(future));
    return future;
}
Also used : Arrays(java.util.Arrays) Array(java.lang.reflect.Array) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) RequestBody(okhttp3.RequestBody) HashSet(java.util.HashSet) DaprError(io.dapr.exceptions.DaprError) Map(java.util.Map) Properties(io.dapr.config.Properties) Call(okhttp3.Call) Callback(okhttp3.Callback) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) Request(okhttp3.Request) Context(reactor.util.context.Context) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Set(java.util.Set) Mono(reactor.core.publisher.Mono) IOException(java.io.IOException) UUID(java.util.UUID) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) OkHttpClient(okhttp3.OkHttpClient) DaprException(io.dapr.exceptions.DaprException) Metadata(io.dapr.client.domain.Metadata) Optional(java.util.Optional) HttpUrl(okhttp3.HttpUrl) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl) CompletableFuture(java.util.concurrent.CompletableFuture) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 13 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project recurly-client-java by recurly.

the class BaseClientTest method testNonJsonError0.

@Test
public void testNonJsonError0() throws IOException {
    final Call mCall = mock(Call.class);
    Answer answer = (i) -> {
        return mCall;
    };
    Headers headers = new Headers.Builder().build();
    MediaType contentType = MediaType.get("text/html; charset=UTF-8");
    when(mCall.execute()).thenReturn(MockClient.buildResponse(0, "Not A Real Status", "<html>badness</html>", headers, contentType));
    OkHttpClient mockOkHttpClient = MockClient.getMockOkHttpClient(answer);
    final MockClient client = new MockClient("apiKey", mockOkHttpClient);
    assertThrows(ApiException.class, () -> {
        client.getResource("code-aaron");
    });
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) NotFoundException(com.recurly.v3.exception.NotFoundException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FixtureConstants(com.recurly.v3.fixtures.FixtureConstants) HashMap(java.util.HashMap) Headers(okhttp3.Headers) MockQueryParams(com.recurly.v3.fixtures.MockQueryParams) ArrayList(java.util.ArrayList) Answer(org.mockito.stubbing.Answer) MockClient(com.recurly.v3.fixtures.MockClient) ApiException(com.recurly.v3.ApiException) Map(java.util.Map) Response(okhttp3.Response) Call(okhttp3.Call) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) MediaType(okhttp3.MediaType) Request(okhttp3.Request) TransactionException(com.recurly.v3.exception.TransactionException) InvalidApiKeyException(com.recurly.v3.exception.InvalidApiKeyException) MyResource(com.recurly.v3.fixtures.MyResource) DateTime(org.joda.time.DateTime) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Field(java.lang.reflect.Field) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) IOUtils(org.apache.commons.io.IOUtils) OkHttpClient(okhttp3.OkHttpClient) ValidationException(com.recurly.v3.exception.ValidationException) MyRequest(com.recurly.v3.fixtures.MyRequest) HttpUrl(okhttp3.HttpUrl) Assert(org.junit.Assert) InternalServerException(com.recurly.v3.exception.InternalServerException) Collections(java.util.Collections) ExceptionFactory(com.recurly.v3.exception.ExceptionFactory) InputStream(java.io.InputStream) Mockito.mock(org.mockito.Mockito.mock) Call(okhttp3.Call) Answer(org.mockito.stubbing.Answer) OkHttpClient(okhttp3.OkHttpClient) Headers(okhttp3.Headers) MediaType(okhttp3.MediaType) MockClient(com.recurly.v3.fixtures.MockClient) Test(org.junit.jupiter.api.Test)

Example 14 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project msgraph-sdk-java-core by microsoftgraph.

the class CoreHttpProvider method processResponse.

@SuppressWarnings("unchecked")
private <Result, Body, DeserializeType> Result processResponse(final Response response, final IHttpRequest request, final Class<Result> resultClass, final Body serializable, final IStatefulResponseHandler<Result, DeserializeType> handler) {
    if (response == null)
        return null;
    final ResponseBody body = response.body();
    try {
        InputStream in = null;
        boolean isBinaryStreamInput = false;
        try {
            // Call being executed
            logger.logDebug(String.format(Locale.ROOT, "Response code %d, %s", response.code(), response.message()));
            if (handler != null) {
                logger.logDebug("StatefulResponse is handling the HTTP response.");
                return handler.generateResult(request, response, this.serializer, this.logger);
            }
            if (response.code() >= HttpResponseCode.HTTP_CLIENT_ERROR && body != null) {
                logger.logDebug("Handling error response");
                in = body.byteStream();
                handleErrorResponse(request, serializable, response);
            }
            final Map<String, List<String>> responseHeaders = response.headers().toMultimap();
            if (response.code() == HttpResponseCode.HTTP_NOBODY || response.code() == HttpResponseCode.HTTP_NOT_MODIFIED) {
                logger.logDebug("Handling response with no body");
                return handleEmptyResponse(responseHeaders, resultClass);
            }
            if (response.code() == HttpResponseCode.HTTP_ACCEPTED) {
                logger.logDebug("Handling accepted response");
                return handleEmptyResponse(responseHeaders, resultClass);
            }
            if (body == null || body.contentLength() == 0)
                return null;
            in = new BufferedInputStream(body.byteStream());
            final MediaType contentType = body.contentType();
            if (contentType != null && contentType.subtype().contains("json") && resultClass != InputStream.class) {
                logger.logDebug("Response json");
                return handleJsonResponse(in, responseHeaders, resultClass);
            } else if (resultClass == InputStream.class) {
                logger.logDebug("Response binary");
                isBinaryStreamInput = true;
                return (Result) handleBinaryStream(in);
            } else if (contentType != null && resultClass != InputStream.class && contentType.type().contains("text") && contentType.subtype().contains("plain")) {
                return handleRawResponse(in, resultClass);
            } else {
                return null;
            }
        } finally {
            if (!isBinaryStreamInput) {
                try {
                    if (in != null)
                        in.close();
                    if (body != null)
                        body.close();
                } catch (IOException e) {
                    logger.logError(e.getMessage(), e);
                }
                response.close();
            }
        }
    } catch (final GraphServiceException ex) {
        final boolean shouldLogVerbosely = logger.getLoggingLevel() == LoggerLevel.DEBUG;
        logger.logError("Graph service exception " + ex.getMessage(shouldLogVerbosely), ex);
        throw ex;
    } catch (final Exception ex) {
        final ClientException clientException = new ClientException("Error during http request", ex);
        logger.logError("Error during http request", clientException);
        throw clientException;
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) MediaType(okhttp3.MediaType) List(java.util.List) IOException(java.io.IOException) ClientException(com.microsoft.graph.core.ClientException) ClientException(com.microsoft.graph.core.ClientException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ResponseBody(okhttp3.ResponseBody)

Example 15 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project msgraph-sdk-java-core by microsoftgraph.

the class LargeFileUploadResponseHandler method generateResult.

@Override
@Nullable
public <ResponseType> LargeFileUploadResponse<UploadType> generateResult(@Nonnull final IHttpRequest request, @Nonnull final ResponseType response, @Nonnull final ISerializer serializer, @Nonnull final ILogger logger) throws Exception {
    Objects.requireNonNull(request, "parameter request cannot be null");
    Objects.requireNonNull(response, "parameter response cannot be null");
    Objects.requireNonNull(serializer, "parameter serializer cannot be null");
    Objects.requireNonNull(logger, "parameter logger cannot be null");
    if (!(response instanceof Response)) {
        throw new ClientException("unsupported response type", null);
    }
    final Response nativeResponse = (Response) response;
    if (nativeResponse.code() >= HttpResponseCode.HTTP_CLIENT_ERROR) {
        logger.logDebug("Receiving error during upload, see detail on result error");
        return new LargeFileUploadResponse<>(GraphServiceException.createFromResponse(request, null, serializer, nativeResponse, logger));
    } else if (nativeResponse.code() >= HTTP_OK && nativeResponse.code() < HttpResponseCode.HTTP_MULTIPLE_CHOICES) {
        try (final ResponseBody body = nativeResponse.body()) {
            final String location = nativeResponse.headers().get("Location");
            final MediaType contentType = body.contentType();
            final String subType = contentType == null ? null : contentType.subtype();
            if (subType != null && subType.contains("json")) {
                return parseJsonUploadResult(body, serializer, logger);
            } else if (location != null) {
                logger.logDebug("Upload session is completed (Outlook), uploaded item returned.");
                return new LargeFileUploadResponse<>(location);
            } else {
                logger.logDebug("Upload session returned an unexpected response");
            }
        }
    }
    return new LargeFileUploadResponse<>(new ClientException("Received an unexpected response from the service, response code: " + nativeResponse.code(), null));
}
Also used : Response(okhttp3.Response) MediaType(okhttp3.MediaType) ClientException(com.microsoft.graph.core.ClientException) ResponseBody(okhttp3.ResponseBody) Nullable(javax.annotation.Nullable)

Aggregations

MediaType (okhttp3.MediaType)297 RequestBody (okhttp3.RequestBody)186 Request (okhttp3.Request)179 Response (okhttp3.Response)158 IOException (java.io.IOException)137 ResponseBody (okhttp3.ResponseBody)71 OkHttpClient (okhttp3.OkHttpClient)68 Charset (java.nio.charset.Charset)50 Buffer (okio.Buffer)50 Headers (okhttp3.Headers)48 JSONObject (org.json.JSONObject)38 BufferedSource (okio.BufferedSource)36 MultipartBody (okhttp3.MultipartBody)34 HttpUrl (okhttp3.HttpUrl)30 Map (java.util.Map)24 BufferedSink (okio.BufferedSink)23 File (java.io.File)22 InputStream (java.io.InputStream)21 ArrayList (java.util.ArrayList)21 Test (org.junit.Test)21