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);
}
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;
}
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");
});
}
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;
}
}
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));
}
Aggregations