You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by lb...@apache.org on 2020/10/01 14:51:35 UTC

[camel-k-runtime] branch master updated: knative: cleanup knative environment definition leftovers

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

lburgazzoli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel-k-runtime.git


The following commit(s) were added to refs/heads/master by this push:
     new cf3f9d9  knative: cleanup knative environment definition leftovers
cf3f9d9 is described below

commit cf3f9d9348f2a5eb19af90108ce69b40cb220491
Author: Luca Burgazzoli <lb...@gmail.com>
AuthorDate: Thu Oct 1 16:00:47 2020 +0200

    knative: cleanup knative environment definition leftovers
---
 .../component/knative/spi/KnativeEnvironment.java  | 54 +++--------------
 .../knative/spi/KnativeEnvironmentTest.java        |  4 +-
 .../knative/http/KnativeHttpConsumer.java          |  7 ---
 .../knative/http/KnativeHttpProducer.java          | 67 +++++++++-------------
 .../component/knative/http/KnativeHttpTest.java    | 58 ++++++++++++++++---
 .../component/knative/KnativeComponentTest.java    |  8 +--
 6 files changed, 88 insertions(+), 110 deletions(-)

diff --git a/components/camel-knative/camel-knative-api/src/main/java/org/apache/camel/component/knative/spi/KnativeEnvironment.java b/components/camel-knative/camel-knative-api/src/main/java/org/apache/camel/component/knative/spi/KnativeEnvironment.java
index 7e88425..cebc932 100644
--- a/components/camel-knative/camel-knative-api/src/main/java/org/apache/camel/component/knative/spi/KnativeEnvironment.java
+++ b/components/camel-knative/camel-knative-api/src/main/java/org/apache/camel/component/knative/spi/KnativeEnvironment.java
@@ -20,8 +20,6 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.Reader;
 import java.io.StringReader;
-import java.net.MalformedURLException;
-import java.net.URL;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
@@ -204,32 +202,6 @@ public class KnativeEnvironment {
             return this.name;
         }
 
-        public String getHost() {
-            String urlAsString = getUrl();
-            if (urlAsString != null) {
-                try {
-                    return new URL(urlAsString).getHost();
-                } catch (MalformedURLException ignored) {
-                    // ignore
-                }
-            }
-
-            return null;
-        }
-
-        public int getPort() {
-            String urlAsString = getUrl();
-            if (urlAsString != null) {
-                try {
-                    return new URL(urlAsString).getPort();
-                } catch (MalformedURLException ignored) {
-                    // ignored
-                }
-            }
-
-            return -1;
-        }
-
         public Map<String, String> getMetadata() {
             return this.meta;
         }
@@ -239,30 +211,13 @@ public class KnativeEnvironment {
         }
 
         public String getPath() {
-            String urlAsString = getUrl();
-            if (urlAsString != null) {
-                try {
-                    return new URL(urlAsString).getPath();
-                } catch (MalformedURLException e) {
-                    throw new RuntimeException(e);
-                }
-            }
-
             return getMetadata(Knative.SERVICE_META_PATH);
         }
 
-        public String getPathOrDefault(String path) {
-            return getMetadata().getOrDefault(Knative.SERVICE_META_PATH, path);
-        }
-
         public String getEventType() {
             return getMetadata(Knative.KNATIVE_EVENT_TYPE);
         }
 
-        public int getPortOrDefault(int port) {
-            return getPort() != -1 ? getPort() : port;
-        }
-
         public String getUrl() {
             return this.url != null ? this.url : getMetadata(Knative.SERVICE_META_URL);
         }
@@ -279,5 +234,14 @@ public class KnativeEnvironment {
             return Objects.equals(type.name(), getMetadata(Knative.KNATIVE_TYPE))
                 && Objects.equals(name, getName());
         }
+
+        @Override
+        public String toString() {
+            return "KnativeResource{" +
+                "name='" + name + '\'' +
+                ", url='" + url + '\'' +
+                ", meta=" + meta +
+                '}';
+        }
     }
 }
diff --git a/components/camel-knative/camel-knative-api/src/test/java/org/apache/camel/component/knative/spi/KnativeEnvironmentTest.java b/components/camel-knative/camel-knative-api/src/test/java/org/apache/camel/component/knative/spi/KnativeEnvironmentTest.java
index 6586964..eb219c7 100644
--- a/components/camel-knative/camel-knative-api/src/test/java/org/apache/camel/component/knative/spi/KnativeEnvironmentTest.java
+++ b/components/camel-knative/camel-knative-api/src/test/java/org/apache/camel/component/knative/spi/KnativeEnvironmentTest.java
@@ -25,7 +25,6 @@ import static org.assertj.core.api.Assertions.assertThat;
 
 public class KnativeEnvironmentTest {
 
-
     @ParameterizedTest
     @ValueSource(strings = {
         "{\"services\":[{\"type\":\"endpoint\",\"name\":\"knative3\",\"metadata\":{\"camel.endpoint.kind\":\"source\",\"knative.apiVersion\":\"serving.knative.dev/v1\",\"knative.kind\":\"Service\",\"service.path\":\"/\"}}]}",
@@ -38,7 +37,6 @@ public class KnativeEnvironmentTest {
         assertThat(env.lookup(Knative.Type.endpoint, "knative3"))
             .first()
                 .hasFieldOrPropertyWithValue("url", null)
-                .hasFieldOrPropertyWithValue("port", -1)
-                .hasFieldOrPropertyWithValue("host", null);
+                .hasFieldOrProperty("metadata");
     }
 }
diff --git a/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpConsumer.java b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpConsumer.java
index 13c5c42..d29d97e 100644
--- a/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpConsumer.java
+++ b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpConsumer.java
@@ -84,13 +84,6 @@ public class KnativeHttpConsumer extends DefaultConsumer {
 
     @Override
     protected void doStart() throws Exception {
-        if (!ObjectHelper.isEmpty(serviceDefinition.getHost())) {
-            LOGGER.warn("Unsupported property `host` on definition={}", serviceDefinition.getName());
-        }
-        if (serviceDefinition.getPort() >= 0) {
-            LOGGER.warn("Unsupported property `port` on definition={}", serviceDefinition.getName());
-        }
-
         if (route == null) {
             String path = ObjectHelper.supplyIfEmpty(serviceDefinition.getPath(), () -> KnativeHttpTransport.DEFAULT_PATH);
             if (ObjectHelper.isNotEmpty(basePath)) {
diff --git a/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpProducer.java b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpProducer.java
index a4e7923..47f00eb 100644
--- a/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpProducer.java
+++ b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpProducer.java
@@ -19,7 +19,6 @@ package org.apache.camel.component.knative.http;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.Map;
-import java.util.function.Supplier;
 
 import io.vertx.core.MultiMap;
 import io.vertx.core.Vertx;
@@ -34,13 +33,13 @@ import org.apache.camel.Endpoint;
 import org.apache.camel.Exchange;
 import org.apache.camel.InvalidPayloadException;
 import org.apache.camel.Message;
+import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.component.knative.spi.KnativeEnvironment;
 import org.apache.camel.spi.HeaderFilterStrategy;
 import org.apache.camel.support.DefaultAsyncProducer;
 import org.apache.camel.support.MessageHelper;
 import org.apache.camel.util.ObjectHelper;
 import org.apache.camel.util.URISupport;
-import org.apache.camel.util.function.Suppliers;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -51,8 +50,9 @@ public class KnativeHttpProducer extends DefaultAsyncProducer {
     private final Vertx vertx;
     private final WebClientOptions clientOptions;
     private final HeaderFilterStrategy headerFilterStrategy;
-    private final Supplier<String> uri;
 
+    private String uri;
+    private String host;
     private WebClient client;
 
     public KnativeHttpProducer(
@@ -66,7 +66,6 @@ public class KnativeHttpProducer extends DefaultAsyncProducer {
         this.vertx = ObjectHelper.notNull(vertx, "vertx");
         this.clientOptions = ObjectHelper.supplyIfEmpty(clientOptions, WebClientOptions::new);
         this.headerFilterStrategy = new KnativeHttpHeaderFilterStrategy();
-        this.uri = Suppliers.memorize(() -> computeUrl(serviceDefinition));
     }
 
     @Override
@@ -89,32 +88,22 @@ public class KnativeHttpProducer extends DefaultAsyncProducer {
             return true;
         }
 
-        final Message message = exchange.getMessage();
-        final String host = getHost(serviceDefinition);
-
-        if (ObjectHelper.isEmpty(host)) {
-            exchange.setException(new CamelException("HTTP operation failed because host is not defined"));
-            callback.done(true);
-
-            return true;
-        }
-
         MultiMap headers = MultiMap.caseInsensitiveMultiMap();
         headers.add(HttpHeaders.CONTENT_LENGTH, Integer.toString(payload.length));
-        headers.add(HttpHeaders.HOST, host);
+        headers.add(HttpHeaders.HOST, this.host);
 
-        String contentType = MessageHelper.getContentType(message);
+        String contentType = MessageHelper.getContentType(exchange.getMessage());
         if (contentType != null) {
             headers.add(HttpHeaders.CONTENT_TYPE, contentType);
         }
 
-        for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
+        for (Map.Entry<String, Object> entry : exchange.getMessage().getHeaders().entrySet()) {
             if (!headerFilterStrategy.applyFilterToCamelHeaders(entry.getKey(), entry.getValue(), exchange)) {
                 headers.add(entry.getKey(), entry.getValue().toString());
             }
         }
 
-        client.postAbs(this.uri.get())
+        client.postAbs(this.uri)
             .putHeaders(headers)
             .sendBuffer(Buffer.buffer(payload), response -> {
                 if (response.succeeded()) {
@@ -138,7 +127,7 @@ public class KnativeHttpProducer extends DefaultAsyncProducer {
                     if (result.statusCode() < 200 || result.statusCode() >= 300) {
                         String exceptionMessage = String.format(
                             "HTTP operation failed invoking %s with statusCode: %d, statusMessage: %s",
-                            URISupport.sanitizeUri(this.uri.get()),
+                            URISupport.sanitizeUri(this.uri),
                             result.statusCode(),
                             result.statusMessage()
                         );
@@ -148,7 +137,7 @@ public class KnativeHttpProducer extends DefaultAsyncProducer {
 
                     answer.setHeader(Exchange.HTTP_RESPONSE_CODE, result.statusCode());
                 } else if (response.failed()) {
-                    String exceptionMessage = "HTTP operation failed invoking " + URISupport.sanitizeUri(this.uri.get());
+                    String exceptionMessage = "HTTP operation failed invoking " + URISupport.sanitizeUri(this.uri);
                     if (response.result() != null) {
                         exceptionMessage += " with statusCode: " + response.result().statusCode();
                     }
@@ -164,9 +153,11 @@ public class KnativeHttpProducer extends DefaultAsyncProducer {
 
     @Override
     protected void doInit() throws Exception {
-        super.doInit();
-
+        this.uri = getUrl(serviceDefinition);
+        this.host = getHost(serviceDefinition);
         this.client = WebClient.create(vertx, clientOptions);
+
+        super.doInit();
     }
 
     @Override
@@ -180,39 +171,35 @@ public class KnativeHttpProducer extends DefaultAsyncProducer {
         }
     }
 
-    private String computeUrl(KnativeEnvironment.KnativeResource definition) {
+    private String getUrl(KnativeEnvironment.KnativeResource definition) {
         String url = definition.getUrl();
         if (url == null) {
-            int port = definition.getPortOrDefault(KnativeHttpTransport.DEFAULT_PORT);
-            String path = definition.getPathOrDefault(KnativeHttpTransport.DEFAULT_PATH);
+            throw new RuntimeCamelException("Unable to determine the `url` for definition: " + definition);
+        }
 
+        String path = definition.getPath();
+        if (path != null) {
             if (path.charAt(0) != '/') {
                 path = "/" + path;
             }
+            if (url.endsWith("/")) {
+                url = url.substring(0, url.length() - 1);
+            }
 
-            url = String.format("http://%s:%d%s", definition.getHost(), port, path);
+            url += path;
         }
 
         return getEndpoint().getCamelContext().resolvePropertyPlaceholders(url);
     }
 
     private String getHost(KnativeEnvironment.KnativeResource definition) {
-        if (definition.getHost() != null) {
-            return serviceDefinition.getHost();
-        }
+        String url = getUrl(definition);
 
-        if (serviceDefinition.getUrl() != null) {
-            String url = serviceDefinition.getUrl();
-            url = getEndpoint().getCamelContext().resolvePropertyPlaceholders(url);
-
-            try {
-               return new URL(url).getHost();
-            } catch (MalformedURLException e) {
-                throw new RuntimeException(e);
-            }
+        try {
+           return new URL(url).getHost();
+        } catch (MalformedURLException e) {
+            throw new RuntimeCamelException("Unable to determine `host` for definition: " + definition, e);
         }
-
-        return null;
     }
 
 }
diff --git a/components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpTest.java b/components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpTest.java
index 6accb64..8b1a163 100644
--- a/components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpTest.java
+++ b/components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpTest.java
@@ -33,7 +33,9 @@ import io.vertx.core.http.HttpServerRequest;
 import org.apache.camel.CamelContext;
 import org.apache.camel.CamelException;
 import org.apache.camel.Exchange;
+import org.apache.camel.FailedToStartRouteException;
 import org.apache.camel.ProducerTemplate;
+import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.builder.RouteBuilder;
 import org.apache.camel.component.knative.KnativeComponent;
 import org.apache.camel.component.knative.spi.CloudEvent;
@@ -65,6 +67,7 @@ import static org.apache.camel.component.knative.test.KnativeEnvironmentSupport.
 import static org.apache.camel.component.knative.test.KnativeEnvironmentSupport.sourceEndpoint;
 import static org.apache.camel.component.knative.test.KnativeEnvironmentSupport.sourceEvent;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
 import static org.hamcrest.Matchers.emptyOrNullString;
 import static org.hamcrest.Matchers.is;
 
@@ -250,7 +253,6 @@ public class KnativeHttpTest {
                 "myEndpoint",
                 null,
                 Map.of(
-                    Knative.SERVICE_META_PATH, "/does/not/exist",
                     Knative.SERVICE_META_URL, String.format("http://localhost:%d/a/path", platformHttpPort),
                     Knative.KNATIVE_EVENT_TYPE, "org.apache.camel.event",
                     Knative.CONTENT_TYPE, "text/plain"
@@ -283,8 +285,49 @@ public class KnativeHttpTest {
 
     @ParameterizedTest
     @EnumSource(CloudEvents.class)
-    void testConsumeStructuredContent(CloudEvent ce) throws Exception {
+    void testInvokeEndpointByUrlAndPath(CloudEvent ce) throws Exception {
+        configureKnativeComponent(
+            context,
+            ce,
+            endpoint(
+                Knative.EndpointKind.sink,
+                "myEndpoint",
+                null,
+                Map.of(
+                    Knative.SERVICE_META_PATH, "/with/subpath",
+                    Knative.SERVICE_META_URL, String.format("http://localhost:%d/a/path", platformHttpPort),
+                    Knative.KNATIVE_EVENT_TYPE, "org.apache.camel.event",
+                    Knative.CONTENT_TYPE, "text/plain"
+                ))
+        );
 
+        RouteBuilder.addRoutes(context, b -> {
+            b.from("direct:source")
+                .to("knative:endpoint/myEndpoint");
+            b.from("platform-http:/a/path/with/subpath")
+                .to("mock:ce");
+        });
+
+        context.start();
+
+        MockEndpoint mock = context.getEndpoint("mock:ce", MockEndpoint.class);
+        mock.expectedHeaderReceived(httpAttribute(ce, CloudEvent.CAMEL_CLOUD_EVENT_VERSION), ce.version());
+        mock.expectedHeaderReceived(httpAttribute(ce, CloudEvent.CAMEL_CLOUD_EVENT_TYPE), "org.apache.camel.event");
+        mock.expectedHeaderReceived(httpAttribute(ce, CloudEvent.CAMEL_CLOUD_EVENT_SOURCE), "knative://endpoint/myEndpoint");
+        mock.expectedHeaderReceived(Exchange.CONTENT_TYPE, "text/plain");
+        mock.expectedMessagesMatches(e -> e.getMessage().getHeaders().containsKey(httpAttribute(ce, CloudEvent.CAMEL_CLOUD_EVENT_TIME)));
+        mock.expectedMessagesMatches(e -> e.getMessage().getHeaders().containsKey(httpAttribute(ce, CloudEvent.CAMEL_CLOUD_EVENT_ID)));
+        mock.expectedBodiesReceived("test");
+        mock.expectedMessageCount(1);
+
+        template.sendBody("direct:source", "test");
+
+        mock.assertIsSatisfied();
+    }
+
+    @ParameterizedTest
+    @EnumSource(CloudEvents.class)
+    void testConsumeStructuredContent(CloudEvent ce) throws Exception {
         configureKnativeComponent(
             context,
             ce,
@@ -773,7 +816,7 @@ public class KnativeHttpTest {
 
     @ParameterizedTest
     @EnumSource(CloudEvents.class)
-    void testInvokeServiceWithoutHost(CloudEvent ce) throws Exception {
+    void testInvokeServiceWithoutUrl(CloudEvent ce) throws Exception {
         configureKnativeComponent(
             context,
             ce,
@@ -794,12 +837,9 @@ public class KnativeHttpTest {
                 .to("mock:start");
         });
 
-        context.start();
-
-        Exchange exchange = template.request("direct:start", e -> e.getMessage().setBody(""));
-        assertThat(exchange.isFailed()).isTrue();
-        assertThat(exchange.getException()).isInstanceOf(CamelException.class);
-        assertThat(exchange.getException()).hasMessageStartingWith("HTTP operation failed because host is not defined");
+        assertThatExceptionOfType(FailedToStartRouteException.class)
+            .isThrownBy(context::start)
+            .withCauseExactlyInstanceOf(RuntimeCamelException.class);
     }
 
     @ParameterizedTest
diff --git a/components/camel-knative/camel-knative/src/test/java/org/apache/camel/component/knative/KnativeComponentTest.java b/components/camel-knative/camel-knative/src/test/java/org/apache/camel/component/knative/KnativeComponentTest.java
index dafe66a..5cbd7a2 100644
--- a/components/camel-knative/camel-knative/src/test/java/org/apache/camel/component/knative/KnativeComponentTest.java
+++ b/components/camel-knative/camel-knative/src/test/java/org/apache/camel/component/knative/KnativeComponentTest.java
@@ -82,9 +82,7 @@ public class KnativeComponentTest {
             assertThat(endpoint.lookupServiceDefinition("c1", Knative.EndpointKind.source)).isPresent();
             assertThat(endpoint.lookupServiceDefinition("e1", Knative.EndpointKind.source)).isNotPresent();
             assertThat(endpoint.lookupServiceDefinition("c1", Knative.EndpointKind.source)).isPresent().get()
-                .hasFieldOrPropertyWithValue("url", "http://localhost:8081")
-                .hasFieldOrPropertyWithValue("host", "localhost")
-                .hasFieldOrPropertyWithValue("port", 8081);
+                .hasFieldOrPropertyWithValue("url", "http://localhost:8081");
         }
         {
             KnativeEndpoint endpoint = context.getEndpoint("knative:channel/creg", KnativeEndpoint.class);
@@ -99,9 +97,7 @@ public class KnativeComponentTest {
             assertThat(endpoint.lookupServiceDefinition("e1", Knative.EndpointKind.source)).isPresent();
             assertThat(endpoint.lookupServiceDefinition("c1", Knative.EndpointKind.source)).isNotPresent();
             assertThat(endpoint.lookupServiceDefinition("e1", Knative.EndpointKind.source)).isPresent().get()
-                .hasFieldOrPropertyWithValue("url", "http://localhost:9001")
-                .hasFieldOrPropertyWithValue("host", "localhost")
-                .hasFieldOrPropertyWithValue("port", 9001);
+                .hasFieldOrPropertyWithValue("url", "http://localhost:9001");
         }
         {
             KnativeEndpoint endpoint = context.getEndpoint("knative:endpoint/ereg", KnativeEndpoint.class);