use of io.micronaut.http.exceptions.HttpStatusException 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;
}
use of io.micronaut.http.exceptions.HttpStatusException in project micronaut-graphql by micronaut-projects.
the class GraphQLController method post.
/**
* Handles GraphQL {@code POST} requests.
*
* @param query the GraphQL query
* @param operationName the GraphQL operation name
* @param variables the GraphQL variables
* @param body the GraphQL request body
* @param httpRequest the HTTP request
* @return the GraphQL response
*/
@Post(consumes = ALL, produces = APPLICATION_JSON, single = true)
public Publisher<MutableHttpResponse<String>> post(@Nullable @QueryValue("query") String query, @Nullable @QueryValue("operationName") String operationName, @Nullable @QueryValue("variables") String variables, @Nullable @Body String body, HttpRequest httpRequest) {
Optional<MediaType> opt = httpRequest.getContentType();
MediaType contentType = opt.orElse(null);
if (body == null) {
body = "";
}
if (APPLICATION_JSON_TYPE.equals(contentType)) {
GraphQLRequestBody request = graphQLJsonSerializer.deserialize(body, GraphQLRequestBody.class);
if (request.getQuery() == null) {
request.setQuery("");
}
return executeRequest(request.getQuery(), request.getOperationName(), request.getVariables(), httpRequest);
}
if (query != null) {
return executeRequest(query, operationName, convertVariablesJson(variables), httpRequest);
}
if (APPLICATION_GRAPHQL_TYPE.equals(contentType)) {
return executeRequest(body, null, null, httpRequest);
}
throw new HttpStatusException(UNPROCESSABLE_ENTITY, "Could not process GraphQL request");
}
use of io.micronaut.http.exceptions.HttpStatusException in project micronaut-starter by micronaut-projects.
the class AbstractCreateController method createProjectGeneratorContext.
public GeneratorContext createProjectGeneratorContext(ApplicationType type, @Pattern(regexp = "[\\w\\d-_\\.]+") String name, @Nullable List<String> features, @Nullable BuildTool buildTool, @Nullable TestFramework testFramework, @Nullable Language lang, @Nullable JdkVersion javaVersion, @Nullable @Header(HttpHeaders.USER_AGENT) String userAgent) {
Project project;
try {
project = NameUtils.parse(name);
} catch (IllegalArgumentException e) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Invalid project name: " + e.getMessage());
}
GeneratorContext generatorContext;
try {
generatorContext = projectGenerator.createGeneratorContext(type, project, new Options(lang, testFramework != null ? testFramework.toTestFramework() : null, buildTool == null ? BuildTool.GRADLE : buildTool, javaVersion != null ? javaVersion : JdkVersion.JDK_8), getOperatingSystem(userAgent), features != null ? features : Collections.emptyList(), ConsoleOutput.NOOP);
try {
eventPublisher.publishEvent(new ApplicationGeneratingEvent(generatorContext));
} catch (Exception e) {
LOG.warn("Error firing application generated event: " + e.getMessage(), e);
}
} catch (IllegalArgumentException e) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
return generatorContext;
}
use of io.micronaut.http.exceptions.HttpStatusException in project micronaut-starter by micronaut-projects.
the class DiffController method diffFeature.
/**
* Returns a diff for the given application type and feature.
*
* @param type The application type
* @param feature The feature
* @param build The build tool
* @param test The test framework
* @param lang The lang
* @param javaVersion The java version
* @param requestInfo The request info
* @return A string representing the difference
*/
@Get(uri = "/{type}/feature/{feature}{?lang,build,test,javaVersion,name}", produces = MediaType.TEXT_PLAIN)
@Override
@ApiResponse(responseCode = "404", description = "If no difference is found")
@ApiResponse(responseCode = "400", description = "If the supplied parameters are invalid")
@ApiResponse(responseCode = "200", description = "A textual diff", content = @Content(mediaType = "text/plain"))
public Flowable<String> diffFeature(@NotNull ApplicationType type, @Nullable String name, @NonNull @NotBlank String feature, @Nullable BuildTool build, @Nullable TestFramework test, @Nullable Language lang, @Nullable JdkVersion javaVersion, @Parameter(hidden = true) RequestInfo requestInfo) {
ProjectGenerator projectGenerator;
GeneratorContext generatorContext;
try {
Project project = name != null ? NameUtils.parse(name) : this.project;
Options options = new Options(lang != null ? lang : Language.JAVA, test != null ? test : TestFramework.JUNIT, build != null ? build : BuildTool.GRADLE);
projectGenerator = this.projectGenerator;
generatorContext = projectGenerator.createGeneratorContext(type, project, options, UserAgentParser.getOperatingSystem(requestInfo.getUserAgent()), Collections.singletonList(feature), ConsoleOutput.NOOP);
} catch (IllegalArgumentException e) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
return diffFlowable(projectGenerator, generatorContext);
}
use of io.micronaut.http.exceptions.HttpStatusException in project micronaut-starter by micronaut-projects.
the class DiffController method diffFlowable.
private Flowable<String> diffFlowable(ProjectGenerator projectGenerator, GeneratorContext generatorContext) {
return Flowable.create(emitter -> {
try {
// empty string so there is at least some content
// if there is no difference
emitter.onNext("");
featureDiffer.produceDiff(projectGenerator, generatorContext, new ConsoleOutput() {
@Override
public void out(String message) {
emitter.onNext(message + LINE_SEPARATOR);
}
@Override
public void err(String message) {
// will never be called
}
@Override
public void warning(String message) {
// will never be called
}
@Override
public boolean showStacktrace() {
return false;
}
@Override
public boolean verbose() {
return false;
}
});
emitter.onComplete();
} catch (Exception e) {
emitter.onError(new HttpStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Could not produce diff: " + e.getMessage()));
}
}, BackpressureStrategy.BUFFER);
}
Aggregations