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/02/18 10:01:11 UTC
[camel] branch master updated: Add a PropertiesFunction to reserve
network ports
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.git
The following commit(s) were added to refs/heads/master by this push:
new a439c92 Add a PropertiesFunction to reserve network ports
a439c92 is described below
commit a439c92076ee741f46e6b4cee8ead635d418fa64
Author: lburgazzoli <lb...@gmail.com>
AuthorDate: Mon Feb 17 16:49:39 2020 +0100
Add a PropertiesFunction to reserve network ports
---
components/camel-test/pom.xml | 6 +-
.../org/apache/camel/test/AvailablePortFinder.java | 23 +++++
.../AvailablePortFinderPropertiesFunction.java | 106 +++++++++++++++++++++
.../apache/camel/test/AvailablePortFinderTest.java | 31 ++++++
4 files changed, 165 insertions(+), 1 deletion(-)
diff --git a/components/camel-test/pom.xml b/components/camel-test/pom.xml
index 9a4577a..7133d87 100644
--- a/components/camel-test/pom.xml
+++ b/components/camel-test/pom.xml
@@ -146,7 +146,11 @@
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
-
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ </dependency>
+
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
diff --git a/components/camel-test/src/main/java/org/apache/camel/test/AvailablePortFinder.java b/components/camel-test/src/main/java/org/apache/camel/test/AvailablePortFinder.java
index 9861ce7..53b6054 100644
--- a/components/camel-test/src/main/java/org/apache/camel/test/AvailablePortFinder.java
+++ b/components/camel-test/src/main/java/org/apache/camel/test/AvailablePortFinder.java
@@ -55,4 +55,27 @@ public final class AvailablePortFinder {
throw new IllegalStateException("Cannot find free port", e);
}
}
+
+
+ /**
+ * Gets the next available port in the given range.
+ *
+ * @throws IllegalStateException if there are no ports available
+ * @return the available port
+ */
+ public static int getNextAvailable(int fromPort, int toPort) {
+ for (int i = fromPort; i <= toPort; i++) {
+ try (ServerSocket ss = new ServerSocket()) {
+ ss.setReuseAddress(true);
+ ss.bind(new InetSocketAddress((InetAddress) null, i), 1);
+ int port = ss.getLocalPort();
+ LOG.info("getNextAvailable() -> {}", port);
+ return port;
+ } catch (IOException e) {
+ throw new IllegalStateException("Cannot find free port", e);
+ }
+ }
+
+ throw new IllegalStateException("Cannot find free port");
+ }
}
\ No newline at end of file
diff --git a/components/camel-test/src/main/java/org/apache/camel/test/AvailablePortFinderPropertiesFunction.java b/components/camel-test/src/main/java/org/apache/camel/test/AvailablePortFinderPropertiesFunction.java
new file mode 100644
index 0000000..accc5e6
--- /dev/null
+++ b/components/camel-test/src/main/java/org/apache/camel/test/AvailablePortFinderPropertiesFunction.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.test;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.camel.component.properties.PropertiesFunction;
+import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.StringHelper;
+
+
+/**
+ * A {@link PropertiesFunction} that reserves network ports and place them in a cache for reuse.
+ * <p/>
+ * The first time the function is invoked for a given name, an unused network port is determined and cached
+ * in an hash map with the given name as key so each time this function is invoked for the same name, the
+ * previously discovered port will be returned.
+ * <p/>
+ * This is useful for testing purpose where you can write a route like:
+ * <pre>{@code
+ * from("undertow:http://0.0.0.0:{{available-port:server-port}}")
+ * .to("mock:result");
+ * }</pre>
+ * And then you can invoke with {@link org.apache.camel.ProducerTemplate} like:
+ * <pre>{@code
+ * template.sendBody("undertow:http://0.0.0.0:{{available-port:server-port}}", "the body");
+ * }</pre>
+ * Doing so avoid the need to compute the port and pass it to the various method or store it as a global
+ * variable in the test class.
+ *
+ * @see AvailablePortFinder
+ */
+public class AvailablePortFinderPropertiesFunction implements PropertiesFunction {
+ private final Map<String, String> portMapping;
+
+ public AvailablePortFinderPropertiesFunction() {
+ this.portMapping = new ConcurrentHashMap<>();
+ }
+
+ @Override
+ public String getName() {
+ return "available-port";
+ }
+
+ @Override
+ public String apply(String remainder) {
+ if (ObjectHelper.isEmpty(remainder)) {
+ return remainder;
+ }
+
+ String name = StringHelper.before(remainder, ":");
+ String range = StringHelper.after(remainder, ":");
+
+ if (name == null) {
+ name = remainder;
+ }
+
+ final Integer from;
+ final Integer to;
+
+ if (range != null) {
+ String f = StringHelper.before(range, "-");
+ if (ObjectHelper.isEmpty(f)) {
+ throw new IllegalArgumentException("Unable to parse from range, range should be defined in the as from-to, got: " + range);
+ }
+
+ String t = StringHelper.after(range, "-");
+ if (ObjectHelper.isEmpty(t)) {
+ throw new IllegalArgumentException("Unable to parse to range, range should be defined in the as from-to, got: " + range);
+ }
+
+ from = Integer.parseInt(f);
+ to = Integer.parseInt(t);
+ } else {
+ from = null;
+ to = null;
+ }
+
+ return this.portMapping.computeIfAbsent(name, n -> {
+ final int port;
+
+ if (from != null && to != null) {
+ port = AvailablePortFinder.getNextAvailable(from, to);
+ } else {
+ port = AvailablePortFinder.getNextAvailable();
+ }
+
+ return Integer.toString(port);
+ });
+ }
+}
diff --git a/components/camel-test/src/test/java/org/apache/camel/test/AvailablePortFinderTest.java b/components/camel-test/src/test/java/org/apache/camel/test/AvailablePortFinderTest.java
index 75b6010..478232b 100644
--- a/components/camel-test/src/test/java/org/apache/camel/test/AvailablePortFinderTest.java
+++ b/components/camel-test/src/test/java/org/apache/camel/test/AvailablePortFinderTest.java
@@ -25,6 +25,10 @@ import java.net.ServerSocket;
import org.junit.Assert;
import org.junit.Test;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+
public class AvailablePortFinderTest {
@Test
@@ -56,4 +60,31 @@ public class AvailablePortFinderTest {
socket.close();
}
+ @Test
+ public void testAvailablePortFinderPropertiesFunction() throws Exception {
+ AvailablePortFinderPropertiesFunction function = new AvailablePortFinderPropertiesFunction();
+
+ assertThat(function.apply("test")).isSameAs(function.apply("test"));
+ assertThat(function.apply("")).isEqualTo("");
+ assertThat(function.apply(null)).isNull();
+
+ // range
+ assertThat(Integer.parseInt(function.apply("test:1024-49151"))).isBetween(1024, 49150);
+
+ // validation
+ assertThatThrownBy(() -> function.apply("test:")).isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> function.apply("test:-")).isInstanceOf(IllegalArgumentException.class);
+
+ assertThatThrownBy(() -> function.apply("test:1024"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Unable to parse from range");
+
+ assertThatThrownBy(() -> function.apply("test:1024-"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Unable to parse to range");
+
+ assertThatThrownBy(() -> function.apply("test:-1234"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Unable to parse from range");
+ }
}