Search in sources :

Example 1 with HttpRequest

use of com.google.cloud.functions.HttpRequest in project spring-cloud-function by spring-cloud.

the class FunctionInvokerHttpTests method testHttpFunction.

private <I, O> void testHttpFunction(Class<?> configurationClass, I input, O expectedOutput) throws Exception {
    try (FunctionInvoker handler = new FunctionInvoker(configurationClass)) {
        HttpRequest request = Mockito.mock(HttpRequest.class);
        if (input != null) {
            when(request.getReader()).thenReturn(new BufferedReader(new StringReader(gson.toJson(input))));
        }
        HttpResponse response = Mockito.mock(HttpResponse.class);
        StringWriter writer = new StringWriter();
        BufferedWriter bufferedWriter = new BufferedWriter(writer);
        when(response.getWriter()).thenReturn(bufferedWriter);
        handler.service(request, response);
        // Closing the writer is done by the Framework/caller.
        bufferedWriter.close();
        if (expectedOutput != null) {
            assertThat(writer.toString()).isEqualTo(gson.toJson(expectedOutput));
        }
    }
}
Also used : HttpRequest(com.google.cloud.functions.HttpRequest) StringWriter(java.io.StringWriter) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) HttpResponse(com.google.cloud.functions.HttpResponse) BufferedWriter(java.io.BufferedWriter)

Example 2 with HttpRequest

use of com.google.cloud.functions.HttpRequest in project java-docs-samples by GoogleCloudPlatform.

the class HttpFormData method service.

@Override
public void service(HttpRequest request, HttpResponse response) throws IOException {
    if (!"POST".equals(request.getMethod())) {
        response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD);
        return;
    }
    // This code will process each file uploaded.
    String tempDirectory = System.getProperty("java.io.tmpdir");
    for (HttpRequest.HttpPart httpPart : request.getParts().values()) {
        String filename = httpPart.getFileName().orElse(null);
        if (filename == null) {
            continue;
        }
        logger.info("Processed file: " + filename);
        // Note: GCF's temp directory is an in-memory file system
        // Thus, any files in it must fit in the instance's memory.
        Path filePath = Paths.get(tempDirectory, filename).toAbsolutePath();
        // Note: files saved to a GCF instance itself may not persist across executions.
        // Persistent files should be stored elsewhere, e.g. a Cloud Storage bucket.
        Files.copy(httpPart.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        // TODO(developer): process saved files here
        Files.delete(filePath);
    }
    // This code will process other form fields.
    request.getQueryParameters().forEach((fieldName, fieldValues) -> {
        String firstFieldValue = fieldValues.get(0);
        // TODO(developer): process field values here
        logger.info(String.format("Processed field: %s (value: %s)", fieldName, firstFieldValue));
    });
}
Also used : HttpRequest(com.google.cloud.functions.HttpRequest) Path(java.nio.file.Path)

Example 3 with HttpRequest

use of com.google.cloud.functions.HttpRequest in project micronaut-gcp by micronaut-projects.

the class HttpFunction method toGoogleRequest.

private HttpRequest toGoogleRequest(io.micronaut.http.HttpRequest<?> request) {
    Map<String, List<String>> headers = new LinkedHashMap<>();
    Map<String, List<String>> parameters = new LinkedHashMap<>();
    request.getHeaders().forEach(headers::put);
    request.getParameters().forEach(parameters::put);
    Object body = request.getBody().orElse(null);
    try {
        Cookies cookies = request.getCookies();
        cookies.forEach((s, cookie) -> {
            if (cookie instanceof NettyCookie) {
                headers.computeIfAbsent(HttpHeaders.COOKIE, s1 -> new ArrayList<>()).add(ClientCookieEncoder.STRICT.encode(((NettyCookie) cookie).getNettyCookie()));
            }
        });
    } catch (UnsupportedOperationException e) {
    // not all request types support retrieving cookies
    }
    return new HttpRequest() {

        @Override
        public String getMethod() {
            return request.getMethodName();
        }

        @Override
        public String getUri() {
            return request.getUri().toString();
        }

        @Override
        public String getPath() {
            return request.getPath();
        }

        @Override
        public Optional<String> getQuery() {
            return Optional.of(request.getUri().getQuery());
        }

        @Override
        public Map<String, List<String>> getQueryParameters() {
            return parameters;
        }

        @Override
        public Map<String, HttpPart> getParts() {
            return Collections.emptyMap();
        }

        @Override
        public Optional<String> getContentType() {
            List<String> values = headers.get(HttpHeaders.CONTENT_TYPE);
            if (values != null) {
                Iterator<String> i = values.iterator();
                if (i.hasNext()) {
                    return Optional.ofNullable(i.next());
                }
            }
            return Optional.empty();
        }

        @Override
        public long getContentLength() {
            List<String> values = headers.get(HttpHeaders.CONTENT_LENGTH);
            if (values != null) {
                Iterator<String> i = values.iterator();
                if (i.hasNext()) {
                    return Long.parseLong(i.next());
                }
            }
            return 0;
        }

        @Override
        public Optional<String> getCharacterEncoding() {
            List<String> values = headers.get(HttpHeaders.CONTENT_ENCODING);
            if (values != null) {
                Iterator<String> i = values.iterator();
                if (i.hasNext()) {
                    return Optional.ofNullable(i.next());
                }
            }
            return Optional.empty();
        }

        @Override
        public InputStream getInputStream() {
            if (body != null) {
                if (body instanceof byte[]) {
                    return new ByteArrayInputStream((byte[]) body);
                } else {
                    MediaType mediaType = getContentType().map(MediaType::new).orElse(null);
                    if (mediaType != null) {
                        MediaTypeCodec codec = httpHandler.getMediaTypeCodecRegistry().findCodec(mediaType).orElse(null);
                        if (codec != null) {
                            byte[] bytes = codec.encode(body);
                            return new ByteArrayInputStream(bytes);
                        }
                    } else {
                        return new ByteArrayInputStream(body.toString().getBytes(StandardCharsets.UTF_8));
                    }
                }
            }
            return new ByteArrayInputStream(new byte[0]);
        }

        @Override
        public BufferedReader getReader() {
            return new BufferedReader(new InputStreamReader(getInputStream(), StandardCharsets.UTF_8));
        }

        @Override
        public Map<String, List<String>> getHeaders() {
            return headers;
        }
    };
}
Also used : ServletExchange(io.micronaut.servlet.http.ServletExchange) Environment(io.micronaut.context.env.Environment) MediaTypeCodec(io.micronaut.http.codec.MediaTypeCodec) java.util(java.util) Logger(org.slf4j.Logger) ApplicationContextBuilder(io.micronaut.context.ApplicationContextBuilder) DefaultServletExchange(io.micronaut.servlet.http.DefaultServletExchange) HttpRequest(com.google.cloud.functions.HttpRequest) LoggerFactory(org.slf4j.LoggerFactory) HttpResponse(com.google.cloud.functions.HttpResponse) FunctionInitializer(io.micronaut.function.executor.FunctionInitializer) io.micronaut.http(io.micronaut.http) MacAddressUtil(io.netty.util.internal.MacAddressUtil) StandardCharsets(java.nio.charset.StandardCharsets) ServletHttpHandler(io.micronaut.servlet.http.ServletHttpHandler) NonNull(io.micronaut.core.annotation.NonNull) ApplicationContext(io.micronaut.context.ApplicationContext) PlatformDependent(io.netty.util.internal.PlatformDependent) java.io(java.io) NettyCookie(io.micronaut.http.netty.cookies.NettyCookie) ClientCookieEncoder(io.netty.handler.codec.http.cookie.ClientCookieEncoder) Argument(io.micronaut.core.type.Argument) ConversionService(io.micronaut.core.convert.ConversionService) Cookies(io.micronaut.http.cookie.Cookies) HttpRequest(com.google.cloud.functions.HttpRequest) NettyCookie(io.micronaut.http.netty.cookies.NettyCookie) Cookies(io.micronaut.http.cookie.Cookies) MediaTypeCodec(io.micronaut.http.codec.MediaTypeCodec)

Aggregations

HttpRequest (com.google.cloud.functions.HttpRequest)3 HttpResponse (com.google.cloud.functions.HttpResponse)2 ApplicationContext (io.micronaut.context.ApplicationContext)1 ApplicationContextBuilder (io.micronaut.context.ApplicationContextBuilder)1 Environment (io.micronaut.context.env.Environment)1 NonNull (io.micronaut.core.annotation.NonNull)1 ConversionService (io.micronaut.core.convert.ConversionService)1 Argument (io.micronaut.core.type.Argument)1 FunctionInitializer (io.micronaut.function.executor.FunctionInitializer)1 io.micronaut.http (io.micronaut.http)1 MediaTypeCodec (io.micronaut.http.codec.MediaTypeCodec)1 Cookies (io.micronaut.http.cookie.Cookies)1 NettyCookie (io.micronaut.http.netty.cookies.NettyCookie)1 DefaultServletExchange (io.micronaut.servlet.http.DefaultServletExchange)1 ServletExchange (io.micronaut.servlet.http.ServletExchange)1 ServletHttpHandler (io.micronaut.servlet.http.ServletHttpHandler)1 ClientCookieEncoder (io.netty.handler.codec.http.cookie.ClientCookieEncoder)1 MacAddressUtil (io.netty.util.internal.MacAddressUtil)1 PlatformDependent (io.netty.util.internal.PlatformDependent)1 java.io (java.io)1