You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by ac...@apache.org on 2021/03/19 06:39:40 UTC

[camel] 05/22: CAMEL-15963 Create a Google Cloud Functions component

This is an automated email from the ASF dual-hosted git repository.

acosentino pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit dfffb9ec648e95830757d1b227e1ccdd0122fae0
Author: Raffaele Marcello <ma...@gmail.com>
AuthorDate: Mon Mar 8 10:24:21 2021 +0100

    CAMEL-15963 Create a Google Cloud Functions component
---
 .../functions/GoogleCloudFunctionsProducer.java    |  65 +++++-----
 .../unit/GoogleCloudFunctionsComponentTest.java    | 132 +++++++++++++++++----
 2 files changed, 142 insertions(+), 55 deletions(-)

diff --git a/components/camel-google-functions/src/main/java/org/apache/camel/component/google/functions/GoogleCloudFunctionsProducer.java b/components/camel-google-functions/src/main/java/org/apache/camel/component/google/functions/GoogleCloudFunctionsProducer.java
index 581d6f6..d5328ce 100644
--- a/components/camel-google-functions/src/main/java/org/apache/camel/component/google/functions/GoogleCloudFunctionsProducer.java
+++ b/components/camel-google-functions/src/main/java/org/apache/camel/component/google/functions/GoogleCloudFunctionsProducer.java
@@ -20,6 +20,7 @@ import java.util.List;
 
 import com.google.api.client.util.Lists;
 import com.google.api.gax.rpc.ApiException;
+import com.google.cloud.functions.v1.CallFunctionRequest;
 import com.google.cloud.functions.v1.CallFunctionResponse;
 import com.google.cloud.functions.v1.CloudFunction;
 import com.google.cloud.functions.v1.CloudFunctionName;
@@ -50,18 +51,18 @@ public class GoogleCloudFunctionsProducer extends DefaultProducer {
     @Override
     public void process(final Exchange exchange) throws Exception {
         switch (determineOperation(exchange)) {
-            case listFunctions:
-                listFunctions(endpoint.getClient(), exchange);
-                break;
-            case getFunction:
-                getFunction(endpoint.getClient(), exchange);
-                break;
-            case callFunction:
-                callFunction(endpoint.getClient(), exchange);
-                break;
+        case listFunctions:
+            listFunctions(endpoint.getClient(), exchange);
+            break;
+        case getFunction:
+            getFunction(endpoint.getClient(), exchange);
+            break;
+        case callFunction:
+            callFunction(endpoint.getClient(), exchange);
+            break;
 
-            default:
-                throw new IllegalArgumentException("Unsupported operation");
+        default:
+            throw new IllegalArgumentException("Unsupported operation");
         }
     }
 
@@ -69,20 +70,22 @@ public class GoogleCloudFunctionsProducer extends DefaultProducer {
         if (getConfiguration().isPojoRequest()) {
             Object payload = exchange.getIn().getMandatoryBody();
             if (payload instanceof ListFunctionsRequest) {
-                ListFunctionsPagedResponse result;
+                ListFunctionsPagedResponse pagedListResponse;
                 try {
-                    result = client.listFunctions((ListFunctionsRequest) payload);
+                    pagedListResponse = client.listFunctions((ListFunctionsRequest) payload);
+                    List<CloudFunction> result = Lists.newArrayList(pagedListResponse.iterateAll());
+                    Message message = getMessageForResponse(exchange);
+                    message.setBody(result);
                 } catch (ApiException ae) {
                     LOG.trace("listFunctions command returned the error code {}", ae.getStatusCode());
                     throw ae;
                 }
-                Message message = getMessageForResponse(exchange);
-                message.setBody(result);
             }
         } else {
             ListFunctionsRequest request = ListFunctionsRequest.newBuilder()
-                    .setParent(LocationName.of(getConfiguration().getProject(), getConfiguration().getLocation()).toString())
-                    .setPageSize(883849137) //TODO check it
+                    .setParent(LocationName.of(getConfiguration().getProject(), getConfiguration().getLocation())
+                            .toString())
+                    .setPageSize(883849137) // TODO check it
                     .setPageToken("pageToken873572522").build();
             ListFunctionsPagedResponse pagedListResponse = client.listFunctions(request);
             List<CloudFunction> result = Lists.newArrayList(pagedListResponse.iterateAll());
@@ -106,8 +109,8 @@ public class GoogleCloudFunctionsProducer extends DefaultProducer {
                 message.setBody(result);
             }
         } else {
-            CloudFunctionName cfName = CloudFunctionName.of(getConfiguration().getProject(), getConfiguration().getLocation(),
-                    getConfiguration().getFunctionName());
+            CloudFunctionName cfName = CloudFunctionName.of(getConfiguration().getProject(),
+                    getConfiguration().getLocation(), getConfiguration().getFunctionName());
             CloudFunction result = client.getFunction(cfName);
             Message message = getMessageForResponse(exchange);
             message.setBody(result);
@@ -115,24 +118,27 @@ public class GoogleCloudFunctionsProducer extends DefaultProducer {
     }
 
     private void callFunction(CloudFunctionsServiceClient client, Exchange exchange) throws InvalidPayloadException {
-        String data = exchange.getIn().getBody(String.class);
         if (getConfiguration().isPojoRequest()) {
             Object payload = exchange.getIn().getMandatoryBody();
-            if (payload instanceof CloudFunctionName) {
+            if (payload instanceof CallFunctionRequest) {
                 CallFunctionResponse result;
                 try {
-                    result = client.callFunction((CloudFunctionName) payload, data);
+                    result = client.callFunction( (CallFunctionRequest) payload );
+                    Message message = getMessageForResponse(exchange);
+                    message.setBody(result);
                 } catch (ApiException ae) {
                     LOG.trace("callFunction command returned the error code {}", ae.getStatusCode());
                     throw ae;
-                }
-                Message message = getMessageForResponse(exchange);
-                message.setBody(result);
+                }                
             }
         } else {
-            CloudFunctionName cfName = CloudFunctionName.of(getConfiguration().getProject(), getConfiguration().getLocation(),
-                    getConfiguration().getFunctionName());
-            CallFunctionResponse result = client.callFunction(cfName, data);
+            String data = exchange.getIn().getBody(String.class);
+            CloudFunctionName cfName = CloudFunctionName.of(getConfiguration().getProject(), getConfiguration().getLocation(), getConfiguration().getFunctionName());
+            CallFunctionRequest request = CallFunctionRequest.newBuilder()
+                .setName(cfName.toString())
+                .setData(data)
+                .build();
+            CallFunctionResponse result = client.callFunction(request);
             Message message = getMessageForResponse(exchange);
             message.setBody(result);
         }
@@ -142,8 +148,7 @@ public class GoogleCloudFunctionsProducer extends DefaultProducer {
         GoogleCloudFunctionsOperations operation = exchange.getIn().getHeader(GoogleCloudFunctionsConstants.OPERATION,
                 GoogleCloudFunctionsOperations.class);
         if (operation == null) {
-            operation = getConfiguration().getOperation() == null
-                    ? GoogleCloudFunctionsOperations.callFunction
+            operation = getConfiguration().getOperation() == null ? GoogleCloudFunctionsOperations.callFunction
                     : getConfiguration().getOperation();
         }
         return operation;
diff --git a/components/camel-google-functions/src/test/java/org/apache/camel/component/google/functions/unit/GoogleCloudFunctionsComponentTest.java b/components/camel-google-functions/src/test/java/org/apache/camel/component/google/functions/unit/GoogleCloudFunctionsComponentTest.java
index 75af885..898684b 100644
--- a/components/camel-google-functions/src/test/java/org/apache/camel/component/google/functions/unit/GoogleCloudFunctionsComponentTest.java
+++ b/components/camel-google-functions/src/test/java/org/apache/camel/component/google/functions/unit/GoogleCloudFunctionsComponentTest.java
@@ -16,6 +16,10 @@
  */
 package org.apache.camel.component.google.functions.unit;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
@@ -28,10 +32,13 @@ import com.google.cloud.functions.v1.CloudFunction;
 import com.google.cloud.functions.v1.CloudFunctionName;
 import com.google.cloud.functions.v1.CloudFunctionStatus;
 import com.google.cloud.functions.v1.GetFunctionRequest;
+import com.google.cloud.functions.v1.ListFunctionsRequest;
 import com.google.cloud.functions.v1.ListFunctionsResponse;
+import com.google.cloud.functions.v1.LocationName;
 import com.google.protobuf.AbstractMessage;
 import com.google.protobuf.Duration;
 import com.google.protobuf.Timestamp;
+
 import org.apache.camel.EndpointInject;
 import org.apache.camel.Exchange;
 import org.apache.camel.ExchangePattern;
@@ -41,10 +48,6 @@ import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
 public class GoogleCloudFunctionsComponentTest extends GoogleCloudFunctionsBaseTest {
 
     private static final Logger log = LoggerFactory.getLogger(GoogleCloudFunctionsComponentTest.class);
@@ -60,26 +63,26 @@ public class GoogleCloudFunctionsComponentTest extends GoogleCloudFunctionsBaseT
     protected RouteBuilder createRouteBuilder() throws Exception {
         return new RouteBuilder() {
             public void configure() {
-                from("direct:listFunctions")
-                        // .to("google-functions://myCamelFunction?client=#client&operation=listFunctions")
-                        .to("google-functions://" + functionName + "?project=" + project + "&location=" + location
-                            + "&operation=listFunctions")
-                        .to("mock:result");
-                from("direct:getFunction")
-                        .to("google-functions://" + functionName + "?project=" + project + "&location=" + location
-                            + "&operation=getFunction")
-                        .to("mock:result");
-                from("direct:callFunction")
-                        .to("google-functions://" + functionName + "?project=" + project + "&location=" + location
-                            + "&operation=callFunction")
-                        .to("mock:result");
+                //simple routes
+                from("direct:listFunctions").to("google-functions://" + functionName + "?project=" + project
+                        + "&location=" + location + "&operation=listFunctions").to("mock:result");
+                from("direct:getFunction").to("google-functions://" + functionName + "?project=" + project
+                        + "&location=" + location + "&operation=getFunction").to("mock:result");
+                from("direct:callFunction").to("google-functions://" + functionName + "?project=" + project
+                        + "&location=" + location + "&operation=callFunction").to("mock:result");
+                //pojo routes
+                from("direct:listFunctionsPojo").to("google-functions://" + functionName + "?project=" + project
+                        + "&location=" + location + "&operation=listFunctions&pojoRequest=true").to("mock:result");
+                from("direct:getFunctionPojo").to("google-functions://" + functionName + "?project=" + project
+                        + "&location=" + location + "&operation=getFunction&pojoRequest=true").to("mock:result");
+                from("direct:callFunctionPojo").to("google-functions://" + functionName + "?project=" + project
+                        + "&location=" + location + "&operation=callFunction&pojoRequest=true").to("mock:result");
             }
         };
     }
 
     @Test
     public void listFunctionsTest() throws Exception {
-        log.info("list function");
         CloudFunction cf1 = CloudFunction.newBuilder().build();
         CloudFunction cf2 = CloudFunction.newBuilder().build();
         List<CloudFunction> cfList = Arrays.asList(cf1, cf2);
@@ -100,6 +103,32 @@ public class GoogleCloudFunctionsComponentTest extends GoogleCloudFunctionsBaseT
     }
 
     @Test
+    public void listFunctionsPojoTest() throws Exception {
+        CloudFunction cf1 = CloudFunction.newBuilder().build();
+        CloudFunction cf2 = CloudFunction.newBuilder().build();
+        List<CloudFunction> cfList = Arrays.asList(cf1, cf2);
+        ListFunctionsResponse expectedResponse = ListFunctionsResponse.newBuilder().setNextPageToken("")
+                .addAllFunctions(cfList).build();
+        mockCloudFunctionsService.addResponse(expectedResponse);
+
+        ListFunctionsRequest pojoRequest = ListFunctionsRequest.newBuilder()
+                .setParent(LocationName.of(project, location).toString()).setPageSize(883849137)
+                .setPageToken("pageToken873572522").build();
+
+        Exchange exchange = template.send("direct:listFunctionsPojo", ExchangePattern.InOut, exc -> {
+            exc.getIn().setBody(pojoRequest);
+        });
+        List<CloudFunction> result = exchange.getMessage().getBody(List.class);
+        assertNotNull(result);
+        assertEquals(cfList.size(), result.size());
+
+        for (int i = 0; i < result.size(); i++) {
+            assertEquals(expectedResponse.getFunctionsList().get(i), result.get(i));
+        }
+
+    }
+
+    @Test
     public void getFunctionTest() throws Exception {
         CloudFunction expectedResponse = CloudFunction.newBuilder()
                 .setName(CloudFunctionName.of(project, location, functionName).toString())
@@ -129,11 +158,39 @@ public class GoogleCloudFunctionsComponentTest extends GoogleCloudFunctionsBaseT
     }
 
     @Test
+    public void getFunctionPojoTest() throws Exception {
+        CloudFunctionName cfName = CloudFunctionName.of(project, location, functionName);
+        CloudFunction expectedResponse = CloudFunction.newBuilder()
+                .setName( cfName.toString())
+                .setDescription("description-1724546052").setStatus(CloudFunctionStatus.forNumber(0))
+                .setEntryPoint("entryPoint-1979329474").setRuntime("runtime1550962648")
+                .setTimeout(Duration.newBuilder().build()).setAvailableMemoryMb(1964533661)
+                .setServiceAccountEmail("serviceAccountEmail1825953988").setUpdateTime(Timestamp.newBuilder().build())
+                .setVersionId(-670497310).putAllLabels(new HashMap<String, String>())
+                .putAllEnvironmentVariables(new HashMap<String, String>()).setNetwork("network1843485230")
+                .setMaxInstances(-330682013).setVpcConnector("vpcConnector2101559652").setBuildId("buildId230943785")
+                .build();
+        mockCloudFunctionsService.addResponse(expectedResponse);
+        
+        Exchange exchange = template.send("direct:getFunctionPojo", ExchangePattern.InOut, exc -> {
+            exc.getIn().setBody(cfName);
+        });
+        CloudFunction actualResponse = exchange.getMessage().getBody(CloudFunction.class);
+        assertEquals(expectedResponse, actualResponse);
+
+        List<AbstractMessage> actualRequests = mockCloudFunctionsService.getRequests();
+        assertEquals(1, actualRequests.size());
+        GetFunctionRequest actualRequest = ((GetFunctionRequest) actualRequests.get(0));
+
+        assertEquals(cfName.toString(), actualRequest.getName());
+        assertTrue(channelProvider.isHeaderSent(ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
+                GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
+    }
+
+    @Test
     public void callFunctionTest() throws Exception {
         CallFunctionResponse expectedResponse = CallFunctionResponse.newBuilder()
-                .setExecutionId("executionId-454906285")
-                .setResult("result-934426595")
-                .setError("error96784904")
+                .setExecutionId("executionId-454906285").setResult("result-934426595").setError("error96784904")
                 .build();
         mockCloudFunctionsService.addResponse(expectedResponse);
 
@@ -152,10 +209,35 @@ public class GoogleCloudFunctionsComponentTest extends GoogleCloudFunctionsBaseT
 
         assertEquals(name.toString(), actualRequest.getName());
         assertEquals(data, actualRequest.getData());
-        assertTrue(
-                channelProvider.isHeaderSent(
-                        ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
-                        GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
+        assertTrue(channelProvider.isHeaderSent(ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
+                GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
+    }
+
+    @Test
+    public void callFunctionPojoTest() throws Exception {
+        CallFunctionResponse expectedResponse = CallFunctionResponse.newBuilder()
+                .setExecutionId("executionId-454906285").setResult("result-934426595").setError("error96784904")
+                .build();
+        mockCloudFunctionsService.addResponse(expectedResponse);
+
+        CloudFunctionName cfName = CloudFunctionName.of(project, location, functionName);
+        String data = "data3076010";
+        CallFunctionRequest request = CallFunctionRequest.newBuilder().setName(cfName.toString()).setData(data).build();
+
+        Exchange exchange = template.send("direct:callFunctionPojo", ExchangePattern.InOut, exc -> {
+            exc.getIn().setBody(request);
+        });
+        CallFunctionResponse actualResponse = exchange.getMessage().getBody(CallFunctionResponse.class);
+        assertEquals(expectedResponse, actualResponse);
+
+        List<AbstractMessage> actualRequests = mockCloudFunctionsService.getRequests();
+        assertEquals(1, actualRequests.size());
+        CallFunctionRequest actualRequest = ((CallFunctionRequest) actualRequests.get(0));
+
+        assertEquals(cfName.toString(), actualRequest.getName());
+        assertEquals(data, actualRequest.getData());
+        assertTrue(channelProvider.isHeaderSent(ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
+                GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
     }
 
 }