Search in sources :

Example 1 with HttpStatusException

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;
}
Also used : Optional(java.util.Optional) InputStream(java.io.InputStream) HttpStatusException(io.micronaut.http.exceptions.HttpStatusException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpPart(com.google.cloud.functions.HttpRequest.HttpPart) Part(io.micronaut.http.annotation.Part) HttpPart(com.google.cloud.functions.HttpRequest.HttpPart) BufferedReader(java.io.BufferedReader) MediaType(io.micronaut.http.MediaType) MediaTypeCodec(io.micronaut.http.codec.MediaTypeCodec)

Example 2 with HttpStatusException

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");
}
Also used : MediaType(io.micronaut.http.MediaType) HttpStatusException(io.micronaut.http.exceptions.HttpStatusException) Post(io.micronaut.http.annotation.Post)

Example 3 with HttpStatusException

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;
}
Also used : Project(io.micronaut.starter.application.Project) Options(io.micronaut.starter.options.Options) HttpStatusException(io.micronaut.http.exceptions.HttpStatusException) GeneratorContext(io.micronaut.starter.application.generator.GeneratorContext) HttpStatusException(io.micronaut.http.exceptions.HttpStatusException) ApplicationGeneratingEvent(io.micronaut.starter.api.event.ApplicationGeneratingEvent)

Example 4 with HttpStatusException

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);
}
Also used : Project(io.micronaut.starter.application.Project) HttpStatusException(io.micronaut.http.exceptions.HttpStatusException) ProjectGenerator(io.micronaut.starter.application.generator.ProjectGenerator) GeneratorContext(io.micronaut.starter.application.generator.GeneratorContext) Get(io.micronaut.http.annotation.Get) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse)

Example 5 with HttpStatusException

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);
}
Also used : ConsoleOutput(io.micronaut.starter.io.ConsoleOutput) HttpStatusException(io.micronaut.http.exceptions.HttpStatusException) HttpStatusException(io.micronaut.http.exceptions.HttpStatusException) IOException(java.io.IOException)

Aggregations

HttpStatusException (io.micronaut.http.exceptions.HttpStatusException)7 Project (io.micronaut.starter.application.Project)4 Get (io.micronaut.http.annotation.Get)3 GeneratorContext (io.micronaut.starter.application.generator.GeneratorContext)3 IOException (java.io.IOException)3 MediaType (io.micronaut.http.MediaType)2 ProjectGenerator (io.micronaut.starter.application.generator.ProjectGenerator)2 Options (io.micronaut.starter.options.Options)2 ApiResponse (io.swagger.v3.oas.annotations.responses.ApiResponse)2 HttpPart (com.google.cloud.functions.HttpRequest.HttpPart)1 Part (io.micronaut.http.annotation.Part)1 Post (io.micronaut.http.annotation.Post)1 MediaTypeCodec (io.micronaut.http.codec.MediaTypeCodec)1 ApplicationGeneratingEvent (io.micronaut.starter.api.event.ApplicationGeneratingEvent)1 ConsoleOutput (io.micronaut.starter.io.ConsoleOutput)1 MapOutputHandler (io.micronaut.starter.io.MapOutputHandler)1 BufferedReader (java.io.BufferedReader)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 InputStream (java.io.InputStream)1 Optional (java.util.Optional)1