use of io.micronaut.http.annotation.Part in project micronaut-gcp by micronaut-projects.
the class GooglePartBinder method bind.
@Override
public BindingResult<T> bind(ArgumentConversionContext<T> context, HttpRequest<?> source) {
if (source instanceof GoogleFunctionHttpRequest) {
GoogleFunctionHttpRequest<?> googleRequest = (GoogleFunctionHttpRequest<?>) source;
final com.google.cloud.functions.HttpRequest nativeRequest = googleRequest.getNativeRequest();
final Argument<T> argument = context.getArgument();
final String partName = context.getAnnotationMetadata().stringValue(Part.class).orElse(argument.getName());
final HttpPart part = nativeRequest.getParts().get(partName);
if (part != null) {
final Class<T> type = argument.getType();
if (HttpPart.class.isAssignableFrom(type)) {
// noinspection unchecked
return () -> (Optional<T>) Optional.of(part);
} else if (String.class.isAssignableFrom(type)) {
try (BufferedReader reader = part.getReader()) {
final String content = IOUtils.readText(reader);
return () -> (Optional<T>) Optional.of(content);
} catch (IOException e) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Unable to read part [" + partName + "]: " + e.getMessage());
}
} else if (byte[].class.isAssignableFrom(type)) {
try (InputStream is = part.getInputStream()) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
final byte[] content = buffer.toByteArray();
return () -> (Optional<T>) Optional.of(content);
} catch (IOException e) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Unable to read part [" + partName + "]: " + e.getMessage());
}
} else {
final MediaType contentType = part.getContentType().map(MediaType::new).orElse(null);
if (contentType != null) {
final MediaTypeCodec codec = codecRegistry.findCodec(contentType, type).orElse(null);
if (codec != null) {
try (InputStream inputStream = part.getInputStream()) {
final T content = codec.decode(argument, inputStream);
return () -> (Optional<T>) Optional.of(content);
} catch (IOException e) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Unable to read part [" + partName + "]: " + e.getMessage());
}
}
}
}
}
}
return BindingResult.UNSATISFIED;
}
Aggregations