diff --git a/AGENTS.md b/AGENTS.md index 2e9a7a210..2cd580d14 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -178,17 +178,25 @@ The cloud examples need a resource key, which a person creates on the configuration page, so ask for one if none is set. A key with the properties most of the Device Detection examples use can be made [here](https://51degrees.com/configure/jqz435Nc?utm_source=github&utm_medium=docs&utm_campaign=51degrees-java&utm_content=agents.md&utm_term=cloud-examples). -The Device Detection cloud example takes the key as its first argument, or -from a `TestResourceKey` environment variable or system property. +The Device Detection, IP Intelligence and Location cloud examples take the +key as their first argument, or from the `_51DEGREES_RESOURCE_KEY` +environment variable or system property. The Device Detection and IP +Intelligence examples read the older `TestResourceKey` after it. The TAC and +native model examples need a key with paid properties and read it from a +variable of their own, which each names when it has no key. ``` java -cp examples/device-detection/console/target/device-detection-java-examples.console-4.5.127-SNAPSHOT-jar-with-dependencies.jar fiftyone.devicedetection.examples.console.GettingStartedCloud ``` It prints the same `Input values:` and `Results:` blocks as the on-premise -example. The IP Intelligence cloud examples read their key from -`_51DEGREES_RESOURCE_KEY` first and `TestResourceKey` second, and -`examples/ip-intelligence/README.md` gives the keys to create for them. +example. `examples/ip-intelligence/README.md` gives the keys to create for +the IP Intelligence examples. + +With no key, a cloud example does not fail. It says that it needs a resource +key, names the variable to set, gives the page where a key is created, ends +with its "Find out more" section and exits with code 0. The tests named +`WithoutKey` run each one that way. ### Pitfalls diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/GettingStartedCloud.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/GettingStartedCloud.java index 71802a2d3..1d8984f61 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/GettingStartedCloud.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/GettingStartedCloud.java @@ -63,12 +63,25 @@ public class GettingStartedCloud { private static final Logger logger = LoggerFactory.getLogger(GettingStartedCloud.class); /** - * The resource key can be supplied as an argument to this program or as an environment - * variable or as a Java system property called "TestResourceKey". + * The resource key can be supplied as an argument to this program, or + * as an environment variable or Java system property called + * "_51DEGREES_RESOURCE_KEY", or the older "TestResourceKey". With none, + * the example says how to get one and ends. */ public static void main(String[] args) throws Exception { configureLogback(getFilePath("logback.xml")); - String resourceKey = args.length > 0 ? args[0]: null; + String resourceKey = KeyHelper.findResourceKey( + args.length > 0 ? args[0] : null, + KeyHelper.RESOURCE_KEY_VARIABLE, + KeyHelper.TEST_RESOURCE_KEY); + if (resourceKey == null) { + KeyHelper.writeNoResourceKey(System.out, EXAMPLE_TAG, + KeyHelper.RESOURCE_KEY_VARIABLE, + KeyHelper.FREE_PROPERTIES_CONFIGURATION); + FindOutMore.write(System.out, EXAMPLE_TAG, + FindOutMore.CLOUD_REPOSITORIES); + return; + } // prepare 'evidence' for use in pipeline (see below) List> evidence = EvidenceHelper.setUpEvidence(); diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MetadataCloud.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MetadataCloud.java index 377cf30cf..a19946313 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MetadataCloud.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MetadataCloud.java @@ -51,9 +51,26 @@ public class MetadataCloud { private static final Logger logger = LoggerFactory.getLogger(GettingStartedOnPrem.class); + /** + * The resource key can be supplied as an argument to this program, or + * as an environment variable or Java system property called + * "_51DEGREES_RESOURCE_KEY", or the older "TestResourceKey". With none, + * the example says how to get one and ends. + */ public static void main(String[] args) throws Exception { configureLogback(getFilePath("logback.xml")); - String resourceKey = args.length > 0 ? args[0]: null; + String resourceKey = KeyHelper.findResourceKey( + args.length > 0 ? args[0] : null, + KeyHelper.RESOURCE_KEY_VARIABLE, + KeyHelper.TEST_RESOURCE_KEY); + if (resourceKey == null) { + KeyHelper.writeNoResourceKey(System.out, EXAMPLE_TAG, + KeyHelper.RESOURCE_KEY_VARIABLE, + KeyHelper.FREE_PROPERTIES_CONFIGURATION); + FindOutMore.write(System.out, EXAMPLE_TAG, + FindOutMore.CLOUD_REPOSITORIES); + return; + } run(resourceKey, System.out); FindOutMore.write(System.out, EXAMPLE_TAG, FindOutMore.CLOUD_REPOSITORIES); diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MinimalExample.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MinimalExample.java index 115e97bd4..49c73e866 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MinimalExample.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MinimalExample.java @@ -23,6 +23,7 @@ package fiftyone.devicedetection.examples.console; import fiftyone.devicedetection.examples.shared.FindOutMore; +import fiftyone.devicedetection.examples.shared.KeyHelper; import fiftyone.devicedetection.DeviceDetectionPipelineBuilder; import fiftyone.devicedetection.shared.DeviceData; import fiftyone.pipeline.core.data.FlowData; @@ -52,8 +53,19 @@ public class MinimalExample { "console-src-main-java-fiftyone-devicedetection-examples-console-minimalexample.java"; public static void main(String[] args) throws Exception { - String resource = args.length > 0 ? args[0] : null; - run(resource); + String resourceKey = KeyHelper.findResourceKey( + args.length > 0 ? args[0] : null, + KeyHelper.RESOURCE_KEY_VARIABLE, + KeyHelper.TEST_RESOURCE_KEY); + if (resourceKey == null) { + KeyHelper.writeNoResourceKey(System.out, EXAMPLE_TAG, + KeyHelper.RESOURCE_KEY_VARIABLE, + KeyHelper.FREE_PROPERTIES_CONFIGURATION); + FindOutMore.write(System.out, EXAMPLE_TAG, + FindOutMore.CLOUD_REPOSITORIES); + return; + } + run(resourceKey); FindOutMore.write(System.out, EXAMPLE_TAG, FindOutMore.CLOUD_REPOSITORIES); } diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/NativeModelCloud.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/NativeModelCloud.java index adcfd02d4..046537074 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/NativeModelCloud.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/NativeModelCloud.java @@ -23,6 +23,7 @@ package fiftyone.devicedetection.examples.console; import fiftyone.devicedetection.examples.shared.FindOutMore; +import fiftyone.devicedetection.examples.shared.KeyHelper; import fiftyone.devicedetection.cloud.data.MultiDeviceDataCloud; import fiftyone.devicedetection.cloud.flowelements.HardwareProfileCloudEngineBuilder; import fiftyone.devicedetection.shared.Constants; @@ -55,7 +56,17 @@ public class NativeModelCloud { public static void main (String[] args) throws Exception { configureLogback(getFilePath("logback.xml")); - String resourceKey = args.length > 0 ? args[0] : null; + String resourceKey = KeyHelper.findResourceKey( + args.length > 0 ? args[0] : null, + NATIVE_MODEL_EXAMPLE_RESOURCE_KEY_NAME); + if (resourceKey == null) { + KeyHelper.writeNoResourceKey(System.out, EXAMPLE_TAG, + NATIVE_MODEL_EXAMPLE_RESOURCE_KEY_NAME, + KeyHelper.PAID_PROPERTIES_CONFIGURATION); + FindOutMore.write(System.out, EXAMPLE_TAG, + FindOutMore.CLOUD_REPOSITORIES); + return; + } run(resourceKey, System.out); } diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/TacCloud.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/TacCloud.java index ed3295b99..1ffcd742b 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/TacCloud.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/TacCloud.java @@ -23,6 +23,7 @@ package fiftyone.devicedetection.examples.console; import fiftyone.devicedetection.examples.shared.FindOutMore; +import fiftyone.devicedetection.examples.shared.KeyHelper; import fiftyone.devicedetection.cloud.data.MultiDeviceDataCloud; import fiftyone.devicedetection.shared.Constants; import fiftyone.devicedetection.shared.DeviceData; @@ -69,7 +70,21 @@ public class TacCloud { public static void main (String[] args) throws Exception { configureLogback(getFilePath("logback.xml")); - String resourceKey = args.length > 0 ? args[0] : null; + String resourceKey = KeyHelper.findResourceKey( + args.length > 0 ? args[0] : null, + TAC_EXAMPLE_RESOURCE_KEY_NAME); + // A key typed into the options file is used as it is. + String fileResourceKey = PipelineOptionsFactory.getOptionsFromFile( + getFilePath("tacCloud.xml")) + .find("CloudRequestEngine", "ResourceKey"); + if (resourceKey == null && isInvalidKey(fileResourceKey)) { + KeyHelper.writeNoResourceKey(System.out, EXAMPLE_TAG, + TAC_EXAMPLE_RESOURCE_KEY_NAME, + KeyHelper.PAID_PROPERTIES_CONFIGURATION); + FindOutMore.write(System.out, EXAMPLE_TAG, + FindOutMore.CLOUD_REPOSITORIES); + return; + } run(resourceKey, System.out); } diff --git a/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/CloudExamplesWithoutKeyTest.java b/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/CloudExamplesWithoutKeyTest.java new file mode 100644 index 000000000..ec60f0ee9 --- /dev/null +++ b/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/CloudExamplesWithoutKeyTest.java @@ -0,0 +1,97 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.devicedetection.examples.console; + +import fiftyone.devicedetection.examples.shared.ExampleProcess; +import fiftyone.devicedetection.examples.shared.FindOutMore; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Runs each cloud example as it runs from a fresh clone, with no resource + * key anywhere, and checks that it ends without an error, names the + * variable to set and links to where a key is created, then ends with its + * Find out more section. + */ +public class CloudExamplesWithoutKeyTest { + + private static final String CONFIGURE = "https://51degrees.com/configure/"; + + private static final String TAGS = + "?utm_source=code&utm_medium=example&utm_campaign=51degrees-java" + + "&utm_content="; + + private static final String CONTACT_US = + "https://51degrees.com/contact-us" + TAGS; + + private static String runWithoutKey(Class example, String variable) + throws Exception { + ExampleProcess.Result result = ExampleProcess.runWithoutKeys(example); + System.out.println(result.output); + String output = result.output; + assertEquals(example.getSimpleName() + " should end with exit code 0", + 0, result.exitCode); + assertTrue("The output should name " + variable, + output.contains("Set the " + variable + " environment variable")); + int link = output.indexOf(CONFIGURE); + assertTrue("The output should link to where a key is created", + link >= 0 && output.startsWith(TAGS, + output.indexOf('?', link))); + assertTrue("The output should end with the '" + FindOutMore.HEADING + + "' section after the link", + output.lastIndexOf(FindOutMore.HEADING) > link); + return output; + } + + @Test + public void gettingStartedCloud() throws Exception { + runWithoutKey(GettingStartedCloud.class, "_51DEGREES_RESOURCE_KEY"); + } + + @Test + public void metadataCloud() throws Exception { + runWithoutKey(MetadataCloud.class, "_51DEGREES_RESOURCE_KEY"); + } + + @Test + public void minimalExample() throws Exception { + runWithoutKey(MinimalExample.class, "_51DEGREES_RESOURCE_KEY"); + } + + @Test + public void tacCloud() throws Exception { + String output = runWithoutKey(TacCloud.class, "SuperResourceKey"); + assertTrue("The output should link to the contact page", + output.contains(CONTACT_US)); + } + + @Test + public void nativeModelCloud() throws Exception { + String output = runWithoutKey(NativeModelCloud.class, + "SuperResourceKey"); + assertTrue("The output should link to the contact page", + output.contains(CONTACT_US)); + } +} diff --git a/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/ExampleProcess.java b/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/ExampleProcess.java new file mode 100644 index 000000000..b010dde43 --- /dev/null +++ b/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/ExampleProcess.java @@ -0,0 +1,127 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.devicedetection.examples.shared; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.TimeUnit; + +/** + * Runs an example's main method in a new Java process with no key in its + * environment, as someone runs it from a fresh clone, for the tests of + * what an example does with no settings. A new process is needed because + * a running Java process cannot remove a variable from its own + * environment. + */ +public final class ExampleProcess { + + /** + * How long an example may run before the test stops it. + */ + private static final long TIMEOUT_SECONDS = 120; + + /** + * What an example wrote and how it ended. + */ + public static final class Result { + /** + * The process's exit code. + */ + public final int exitCode; + + /** + * Everything the process wrote to standard output and standard + * error. + */ + public final String output; + + Result(int exitCode, String output) { + this.exitCode = exitCode; + this.output = output; + } + } + + private ExampleProcess() { + } + + /** + * Runs the example's main method with no arguments and with every + * environment variable whose name holds "KEY", in any case, left out. + * The process takes the class path of the process that starts it, and + * of its system properties only project.root, which says where the + * files the example reads are. + * @param example the class whose main method runs + * @return the exit code and the output + * @throws Exception if the process cannot start, or does not end + * within the timeout + */ + public static Result runWithoutKeys(Class example) throws Exception { + List command = new ArrayList<>(); + command.add(new File(new File(System.getProperty("java.home"), + "bin"), "java").getPath()); + command.add("-cp"); + command.add(System.getProperty("java.class.path")); + String projectRoot = System.getProperty("project.root"); + if (projectRoot != null) { + command.add("-Dproject.root=" + projectRoot); + } + command.add(example.getName()); + + ProcessBuilder builder = new ProcessBuilder(command); + builder.environment().keySet().removeIf( + name -> name.toUpperCase(Locale.ROOT).contains("KEY")); + builder.redirectErrorStream(true); + Process process = builder.start(); + + ByteArrayOutputStream output = new ByteArrayOutputStream(); + Thread reader = new Thread(() -> copy(process.getInputStream(), + output)); + reader.start(); + if (process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS) == false) { + process.destroyForcibly(); + reader.join(); + throw new AssertionError(example.getName() + + " did not end within " + TIMEOUT_SECONDS + " seconds. " + + "It wrote:\n" + output.toString("UTF-8")); + } + reader.join(); + return new Result(process.exitValue(), output.toString("UTF-8")); + } + + private static void copy(InputStream input, ByteArrayOutputStream output) { + byte[] buffer = new byte[8192]; + try { + int read; + while ((read = input.read(buffer)) >= 0) { + output.write(buffer, 0, read); + } + } catch (IOException e) { + // The process ended, so there is no more to read. + } + } +} diff --git a/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/FindOutMore.java b/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/FindOutMore.java index 2b8f918f3..e50c93d35 100644 --- a/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/FindOutMore.java +++ b/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/FindOutMore.java @@ -173,13 +173,28 @@ public static String html(String example, String... repositories) { * @throws IllegalArgumentException if the tag is not a lower case slug */ public static String link(String page, String example) { - if (example == null || SLUG.matcher(example).matches() == false) { - throw new IllegalArgumentException( - "'" + example + "' is not a lower case slug."); + return link(page, example, "find-out-more"); + } + + /** + * The address of a page on 51degrees.com, tagged with the example and + * the part of its output that gives the link. + * @param page the path of the page + * @param example the example's tag + * @param term the part of the output, a lower case slug + * @return the address + * @throws IllegalArgumentException if a tag is not a lower case slug + */ + public static String link(String page, String example, String term) { + for (String tag : new String[]{example, term}) { + if (tag == null || SLUG.matcher(tag).matches() == false) { + throw new IllegalArgumentException( + "'" + tag + "' is not a lower case slug."); + } } return "https://51degrees.com/" + page + "?utm_source=code&utm_medium=example" + "&utm_campaign=51degrees-java&utm_content=" + example + - "&utm_term=find-out-more"; + "&utm_term=" + term; } } diff --git a/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/KeyHelper.java b/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/KeyHelper.java index 9f5b6729c..f21a3a3b5 100644 --- a/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/KeyHelper.java +++ b/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/KeyHelper.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.PrintStream; import java.util.*; import java.util.function.Function; @@ -85,6 +86,78 @@ public static boolean isInvalidKey(String keyValue) { static final String CREATE_KEY_URL = "https://51degrees.com/configure/?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=shared-src-main-java-fiftyone-devicedetection-examples-shared-keyhelper.java&utm_term=no-resource-key"; + /** + * The variable a cloud example reads its resource key from first. + */ + public static final String RESOURCE_KEY_VARIABLE = + "_51DEGREES_RESOURCE_KEY"; + + /** + * The configuration page that creates a key with the free properties + * the cloud examples use. + */ + public static final String FREE_PROPERTIES_CONFIGURATION = + "configure/jqz435Nc"; + + /** + * The configuration page that creates a key with the properties the + * TAC and native model examples use, which need a paid licence. + */ + public static final String PAID_PROPERTIES_CONFIGURATION = + "configure/QKyYH5XT"; + + /** + * The resource key a cloud example runs with, being the key given as + * its argument, or else the first of the names that holds one, read as + * an environment variable, under its upper case name and as a system + * property. + * @param argument the key given on the command line, or null + * @param names the names to read, in order + * @return the key, or null when there is none + */ + public static String findResourceKey(String argument, String... names) { + if (isInvalidKey(argument) == false) { + return argument.trim(); + } + for (String name : names) { + String value = readKey(name); + if (value != null) { + return value.trim(); + } + } + return null; + } + + /** + * Writes what a cloud example needs when it has no resource key, being + * the variable to set and the page where a key is created, so that the + * example can end without an error. + * @param output where to write + * @param example the example's tag, as its Find out more section has it + * @param variable the variable the example reads its key from + * @param configuration the configuration page for the key, such as + * {@link #FREE_PROPERTIES_CONFIGURATION} + */ + public static void writeNoResourceKey(PrintStream output, String example, + String variable, + String configuration) { + output.println(); + output.println("This example calls the 51Degrees cloud service, " + + "which needs a resource key, and none is set."); + output.println("Set the " + variable + " environment variable to a " + + "resource key, or give the key as the first argument, and run " + + "the example again."); + output.println("Create a resource key with the properties this " + + "example uses at " + + FindOutMore.link(configuration, example, "no-resource-key")); + if (PAID_PROPERTIES_CONFIGURATION.equals(configuration)) { + output.println("These properties need a paid licence. Contact " + + "us about one at " + + FindOutMore.link("contact-us", example, "no-resource-key")); + } + output.flush(); + } + /** * The resource key for a test that calls the live cloud service, from * {@link #SHARED_RESOURCE_KEY_NAMES} and then {@link #TEST_RESOURCE_KEY}. diff --git a/examples/device-detection/web/getting-started.cloud/src/main/java/fiftyone/devicedetection/examples/web/GettingStartedWebCloud.java b/examples/device-detection/web/getting-started.cloud/src/main/java/fiftyone/devicedetection/examples/web/GettingStartedWebCloud.java index 9a6d881f7..93dca675f 100644 --- a/examples/device-detection/web/getting-started.cloud/src/main/java/fiftyone/devicedetection/examples/web/GettingStartedWebCloud.java +++ b/examples/device-detection/web/getting-started.cloud/src/main/java/fiftyone/devicedetection/examples/web/GettingStartedWebCloud.java @@ -22,6 +22,8 @@ package fiftyone.devicedetection.examples.web; +import fiftyone.devicedetection.examples.shared.FindOutMore; +import fiftyone.devicedetection.examples.shared.KeyHelper; import fiftyone.devicedetection.shared.DeviceData; import fiftyone.pipeline.core.data.FlowData; import fiftyone.pipeline.web.Constants; @@ -50,15 +52,33 @@ * The configuration file for the pipeline is at src/main/webapp/WEB-INF/51Degrees-Cloud.xml */ public class GettingStartedWebCloud extends HttpServlet { + /** + * This example's tag in the links it writes when it has no resource + * key. + */ + private static final String EXAMPLE_TAG = + "web-getting-started.cloud-src-main-java-fiftyone-devicedetection-examples-web-gettingstartedwebcloud.java"; + private static final long serialVersionUID = 1734154705981153540L; public static String resourceBase = "examples/device-detection/web/getting-started.cloud/src/main/webapp"; public static Logger logger = LoggerFactory.getLogger(GettingStartedWebCloud.class); public static void main(String[] args) throws Exception { configureLogback(getFilePath("logback.xml")); - String resourceKey = args.length > 0 ? args[0] : null; + String resourceKey = KeyHelper.findResourceKey( + args.length > 0 ? args[0] : null, + KeyHelper.RESOURCE_KEY_VARIABLE, + KeyHelper.TEST_RESOURCE_KEY); + if (resourceKey == null) { + KeyHelper.writeNoResourceKey(System.out, EXAMPLE_TAG, + KeyHelper.RESOURCE_KEY_VARIABLE, + KeyHelper.FREE_PROPERTIES_CONFIGURATION); + FindOutMore.write(System.out, EXAMPLE_TAG, + FindOutMore.CLOUD_REPOSITORIES); + return; + } logger.info("Running Example {}", GettingStartedWebCloud.class); - // check resource key and set as System Property + // Set the key as the system property the options file reads. getOrSetTestResourceKey(resourceKey); String portEnv = System.getenv("PORT"); diff --git a/examples/device-detection/web/getting-started.cloud/src/test/java/fiftyone/devicedetection/web/GettingStartedWebCloudWithoutKeyTest.java b/examples/device-detection/web/getting-started.cloud/src/test/java/fiftyone/devicedetection/web/GettingStartedWebCloudWithoutKeyTest.java new file mode 100644 index 000000000..3e509caac --- /dev/null +++ b/examples/device-detection/web/getting-started.cloud/src/test/java/fiftyone/devicedetection/web/GettingStartedWebCloudWithoutKeyTest.java @@ -0,0 +1,68 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.devicedetection.web; + +import fiftyone.devicedetection.examples.shared.ExampleProcess; +import fiftyone.devicedetection.examples.web.GettingStartedWebCloud; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Runs the Device Detection cloud web example as it runs from a fresh + * clone, with no resource key anywhere, and checks that it ends without an + * error, names the variable to set and links to where a key is created, + * then ends with its Find out more section. + */ +public class GettingStartedWebCloudWithoutKeyTest { + + private static final String CONFIGURE = "https://51degrees.com/configure/"; + + private static final String TAGS = + "?utm_source=code&utm_medium=example&utm_campaign=51degrees-java" + + "&utm_content="; + + private static void runWithoutKey(Class example) throws Exception { + ExampleProcess.Result result = ExampleProcess.runWithoutKeys(example); + System.out.println(result.output); + String output = result.output; + assertEquals(example.getSimpleName() + " should end with exit code 0", + 0, result.exitCode); + assertTrue("The output should name _51DEGREES_RESOURCE_KEY", + output.contains("Set the _51DEGREES_RESOURCE_KEY " + + "environment variable")); + int link = output.indexOf(CONFIGURE); + assertTrue("The output should link to where a key is created", + link >= 0 && output.startsWith(TAGS, + output.indexOf('?', link))); + assertTrue("The output should end with the Find out more section " + + "after the link", + output.lastIndexOf("Find out more") > link); + } + + @Test + public void gettingStartedWebCloud() throws Exception { + runWithoutKey(GettingStartedWebCloud.class); + } +} diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GetAllPropertiesCloud.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GetAllPropertiesCloud.java index 9d66ab330..e9dcfda0c 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GetAllPropertiesCloud.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GetAllPropertiesCloud.java @@ -95,8 +95,14 @@ public static void main(String[] args) throws Exception { // Use the resource key from the command line, environment variable or // system property. - String resourceKey = args.length > 0 ? args[0] : - KeyHelper.getOrSetTestResourceKey(); + String resourceKey = KeyHelper.findResourceKey( + args.length > 0 ? args[0] : null); + if (resourceKey == null) { + KeyHelper.writeNoResourceKey(System.out, EXAMPLE_TAG); + FindOutMore.write(System.out, EXAMPLE_TAG, + FindOutMore.CLOUD_REPOSITORIES); + return; + } // An optional custom endpoint for a self-hosted Cloud service. String endPoint = args.length > 1 ? args[1] : KeyUtils.getNamedKey(GettingStartedCloud.CLOUD_END_POINT_NAME); diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloud.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloud.java index c9c8d475c..a1c67e0eb 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloud.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloud.java @@ -105,8 +105,14 @@ public static void main(String[] args) throws Exception { // Use the resource key from the command line, environment variable or // system property. - String resourceKey = args.length > 0 ? args[0] : - KeyHelper.getOrSetTestResourceKey(); + String resourceKey = KeyHelper.findResourceKey( + args.length > 0 ? args[0] : null); + if (resourceKey == null) { + KeyHelper.writeNoResourceKey(System.out, EXAMPLE_TAG); + FindOutMore.write(System.out, EXAMPLE_TAG, + FindOutMore.CLOUD_REPOSITORIES); + return; + } // An optional custom endpoint for a self-hosted Cloud service. String endPoint = args.length > 1 ? args[1] : KeyUtils.getNamedKey(CLOUD_END_POINT_NAME); diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloudMixed.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloudMixed.java index 11628ca1c..c51558f16 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloudMixed.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloudMixed.java @@ -104,8 +104,14 @@ public static void main(String[] args) throws Exception { // Use the resource key from the command line, environment variable or // system property. - String resourceKey = args.length > 0 ? args[0] : - KeyHelper.getOrSetTestResourceKey(); + String resourceKey = KeyHelper.findResourceKey( + args.length > 0 ? args[0] : null); + if (resourceKey == null) { + KeyHelper.writeNoResourceKey(System.out, EXAMPLE_TAG); + FindOutMore.write(System.out, EXAMPLE_TAG, + FindOutMore.CLOUD_REPOSITORIES); + return; + } // An optional custom endpoint for a self-hosted Cloud service. String endPoint = args.length > 1 ? args[1] : KeyUtils.getNamedKey(GettingStartedCloud.CLOUD_END_POINT_NAME); diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetadataCloud.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetadataCloud.java index 1af46c383..b3bed2d25 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetadataCloud.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetadataCloud.java @@ -99,8 +99,14 @@ public static void main(String[] args) throws Exception { // Use the resource key from the command line, environment variable or // system property. - String resourceKey = args.length > 0 ? args[0] : - KeyHelper.getOrSetTestResourceKey(); + String resourceKey = KeyHelper.findResourceKey( + args.length > 0 ? args[0] : null); + if (resourceKey == null) { + KeyHelper.writeNoResourceKey(System.out, EXAMPLE_TAG); + FindOutMore.write(System.out, EXAMPLE_TAG, + FindOutMore.CLOUD_REPOSITORIES); + return; + } // An optional custom endpoint for a self-hosted Cloud service. String endPoint = args.length > 1 ? args[1] : KeyUtils.getNamedKey(GettingStartedCloud.CLOUD_END_POINT_NAME); diff --git a/examples/ip-intelligence/console/src/test/java/fiftyone/ipintelligence/examples/console/CloudExamplesWithoutKeyTest.java b/examples/ip-intelligence/console/src/test/java/fiftyone/ipintelligence/examples/console/CloudExamplesWithoutKeyTest.java new file mode 100644 index 000000000..d6b4e7e56 --- /dev/null +++ b/examples/ip-intelligence/console/src/test/java/fiftyone/ipintelligence/examples/console/CloudExamplesWithoutKeyTest.java @@ -0,0 +1,82 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.ipintelligence.examples.console; + +import fiftyone.ipintelligence.examples.shared.ExampleProcess; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Runs each IP Intelligence cloud console example as it runs from a fresh + * clone, with no resource key anywhere, and checks that it ends without an + * error, names the variable to set and links to where a key is created, + * then ends with its Find out more section. + */ +public class CloudExamplesWithoutKeyTest { + + private static final String CONFIGURE = "https://51degrees.com/configure/"; + + private static final String TAGS = + "?utm_source=code&utm_medium=example&utm_campaign=51degrees-java" + + "&utm_content="; + + private static void runWithoutKey(Class example) throws Exception { + ExampleProcess.Result result = ExampleProcess.runWithoutKeys(example); + System.out.println(result.output); + String output = result.output; + assertEquals(example.getSimpleName() + " should end with exit code 0", + 0, result.exitCode); + assertTrue("The output should name _51DEGREES_RESOURCE_KEY", + output.contains("Set the _51DEGREES_RESOURCE_KEY " + + "environment variable")); + int link = output.indexOf(CONFIGURE); + assertTrue("The output should link to where a key is created", + link >= 0 && output.startsWith(TAGS, + output.indexOf('?', link))); + assertTrue("The output should end with the Find out more section " + + "after the link", + output.lastIndexOf("Find out more") > link); + } + + @Test + public void gettingStartedCloud() throws Exception { + runWithoutKey(GettingStartedCloud.class); + } + + @Test + public void gettingStartedCloudMixed() throws Exception { + runWithoutKey(GettingStartedCloudMixed.class); + } + + @Test + public void getAllPropertiesCloud() throws Exception { + runWithoutKey(GetAllPropertiesCloud.class); + } + + @Test + public void metadataCloud() throws Exception { + runWithoutKey(MetadataCloud.class); + } +} diff --git a/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/ExampleProcess.java b/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/ExampleProcess.java new file mode 100644 index 000000000..e411b3e3d --- /dev/null +++ b/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/ExampleProcess.java @@ -0,0 +1,127 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.ipintelligence.examples.shared; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.TimeUnit; + +/** + * Runs an example's main method in a new Java process with no key in its + * environment, as someone runs it from a fresh clone, for the tests of + * what an example does with no settings. A new process is needed because + * a running Java process cannot remove a variable from its own + * environment. + */ +public final class ExampleProcess { + + /** + * How long an example may run before the test stops it. + */ + private static final long TIMEOUT_SECONDS = 120; + + /** + * What an example wrote and how it ended. + */ + public static final class Result { + /** + * The process's exit code. + */ + public final int exitCode; + + /** + * Everything the process wrote to standard output and standard + * error. + */ + public final String output; + + Result(int exitCode, String output) { + this.exitCode = exitCode; + this.output = output; + } + } + + private ExampleProcess() { + } + + /** + * Runs the example's main method with no arguments and with every + * environment variable whose name holds "KEY", in any case, left out. + * The process takes the class path of the process that starts it, and + * of its system properties only project.root, which says where the + * files the example reads are. + * @param example the class whose main method runs + * @return the exit code and the output + * @throws Exception if the process cannot start, or does not end + * within the timeout + */ + public static Result runWithoutKeys(Class example) throws Exception { + List command = new ArrayList<>(); + command.add(new File(new File(System.getProperty("java.home"), + "bin"), "java").getPath()); + command.add("-cp"); + command.add(System.getProperty("java.class.path")); + String projectRoot = System.getProperty("project.root"); + if (projectRoot != null) { + command.add("-Dproject.root=" + projectRoot); + } + command.add(example.getName()); + + ProcessBuilder builder = new ProcessBuilder(command); + builder.environment().keySet().removeIf( + name -> name.toUpperCase(Locale.ROOT).contains("KEY")); + builder.redirectErrorStream(true); + Process process = builder.start(); + + ByteArrayOutputStream output = new ByteArrayOutputStream(); + Thread reader = new Thread(() -> copy(process.getInputStream(), + output)); + reader.start(); + if (process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS) == false) { + process.destroyForcibly(); + reader.join(); + throw new AssertionError(example.getName() + + " did not end within " + TIMEOUT_SECONDS + " seconds. " + + "It wrote:\n" + output.toString("UTF-8")); + } + reader.join(); + return new Result(process.exitValue(), output.toString("UTF-8")); + } + + private static void copy(InputStream input, ByteArrayOutputStream output) { + byte[] buffer = new byte[8192]; + try { + int read; + while ((read = input.read(buffer)) >= 0) { + output.write(buffer, 0, read); + } + } catch (IOException e) { + // The process ended, so there is no more to read. + } + } +} diff --git a/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/FindOutMore.java b/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/FindOutMore.java index b9354f6a8..f893c41c3 100644 --- a/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/FindOutMore.java +++ b/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/FindOutMore.java @@ -173,13 +173,28 @@ public static String html(String example, String... repositories) { * @throws IllegalArgumentException if the tag is not a lower case slug */ public static String link(String page, String example) { - if (example == null || SLUG.matcher(example).matches() == false) { - throw new IllegalArgumentException( - "'" + example + "' is not a lower case slug."); + return link(page, example, "find-out-more"); + } + + /** + * The address of a page on 51degrees.com, tagged with the example and + * the part of its output that gives the link. + * @param page the path of the page + * @param example the example's tag + * @param term the part of the output, a lower case slug + * @return the address + * @throws IllegalArgumentException if a tag is not a lower case slug + */ + public static String link(String page, String example, String term) { + for (String tag : new String[]{example, term}) { + if (tag == null || SLUG.matcher(tag).matches() == false) { + throw new IllegalArgumentException( + "'" + tag + "' is not a lower case slug."); + } } return "https://51degrees.com/" + page + "?utm_source=code&utm_medium=example" + "&utm_campaign=51degrees-java&utm_content=" + example + - "&utm_term=find-out-more"; + "&utm_term=" + term; } } diff --git a/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/KeyHelper.java b/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/KeyHelper.java index 687d1573d..e7b69b0b9 100644 --- a/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/KeyHelper.java +++ b/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/KeyHelper.java @@ -26,6 +26,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.PrintStream; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; @@ -65,6 +66,57 @@ public class KeyHelper { static final String CREATE_KEY_URL = "https://51degrees.com/configure/?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=shared-src-main-java-fiftyone-ipintelligence-examples-shared-keyhelper.java&utm_term=no-resource-key"; + /** + * The configuration page that creates a key with the free properties + * the cloud examples use. + */ + public static final String FREE_PROPERTIES_CONFIGURATION = + "configure/Wkqxf3Bs"; + + /** + * The resource key a cloud example runs with, being the key given as + * its argument, or else the key in {@link #RESOURCE_KEY_VARIABLE}, its + * deprecated name {@link #RESOURCE_KEY_ENV_VAR}, or + * {@link #TEST_RESOURCE_KEY}, each read as an environment variable, + * under its upper case name and as a system property. + * @param argument the key given on the command line, or null + * @return the key, or null when there is none + */ + public static String findResourceKey(String argument) { + if (KeyUtils.isInvalidKey(argument) == false) { + return argument.trim(); + } + String value = readKey(RESOURCE_KEY_VARIABLE); + if (value == null) { + value = oldNameResourceKey(KeyHelper::readKey); + } + if (value == null) { + value = readKey(TEST_RESOURCE_KEY); + } + return value == null ? null : value.trim(); + } + + /** + * Writes what a cloud example needs when it has no resource key, being + * the variable to set and the page where a key is created, so that the + * example can end without an error. + * @param output where to write + * @param example the example's tag, as its Find out more section has it + */ + public static void writeNoResourceKey(PrintStream output, + String example) { + output.println(); + output.println("This example calls the 51Degrees cloud service, " + + "which needs a resource key, and none is set."); + output.println("Set the " + RESOURCE_KEY_VARIABLE + " environment " + + "variable to a resource key, or give the key as the first " + + "argument, and run the example again."); + output.println("Create a resource key with the properties this " + + "example uses at " + FindOutMore.link( + FREE_PROPERTIES_CONFIGURATION, example, "no-resource-key")); + output.flush(); + } + /** * The resource key for a test that calls the live cloud service, from * {@link #SHARED_RESOURCE_KEY_NAMES} and then the names diff --git a/examples/ip-intelligence/web/getting-started.cloud.mixed/src/main/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloudMixed.java b/examples/ip-intelligence/web/getting-started.cloud.mixed/src/main/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloudMixed.java index 23ed0874c..ee986156e 100644 --- a/examples/ip-intelligence/web/getting-started.cloud.mixed/src/main/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloudMixed.java +++ b/examples/ip-intelligence/web/getting-started.cloud.mixed/src/main/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloudMixed.java @@ -104,7 +104,15 @@ public static void main(String[] args) throws Exception { // Get the resource key from the command line, environment variable or // system property. This sets the "TestResourceKey" system property // which is interpolated in the pipeline configuration file. - KeyHelper.getOrSetTestResourceKey(args.length > 0 ? args[0] : null, true); + String resourceKey = KeyHelper.findResourceKey( + args.length > 0 ? args[0] : null); + if (resourceKey == null) { + KeyHelper.writeNoResourceKey(System.out, EXAMPLE_TAG); + FindOutMore.write(System.out, EXAMPLE_TAG, + FindOutMore.CLOUD_REPOSITORIES); + return; + } + KeyHelper.getOrSetTestResourceKey(resourceKey, true); // Start Jetty with this WebApp EmbedJetty.runWebApp(getResourceBase(), 8084); diff --git a/examples/ip-intelligence/web/getting-started.cloud.mixed/src/test/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloudMixedWithoutKeyTest.java b/examples/ip-intelligence/web/getting-started.cloud.mixed/src/test/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloudMixedWithoutKeyTest.java new file mode 100644 index 000000000..46b28eb04 --- /dev/null +++ b/examples/ip-intelligence/web/getting-started.cloud.mixed/src/test/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloudMixedWithoutKeyTest.java @@ -0,0 +1,67 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.ipintelligence.examples.web; + +import fiftyone.ipintelligence.examples.shared.ExampleProcess; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Runs the IP Intelligence cloud and on-premise web example as it runs from + * a fresh clone, with no resource key anywhere, and checks that it ends + * without an error, names the variable to set and links to where a key is + * created, then ends with its Find out more section. + */ +public class GettingStartedWebCloudMixedWithoutKeyTest { + + private static final String CONFIGURE = "https://51degrees.com/configure/"; + + private static final String TAGS = + "?utm_source=code&utm_medium=example&utm_campaign=51degrees-java" + + "&utm_content="; + + private static void runWithoutKey(Class example) throws Exception { + ExampleProcess.Result result = ExampleProcess.runWithoutKeys(example); + System.out.println(result.output); + String output = result.output; + assertEquals(example.getSimpleName() + " should end with exit code 0", + 0, result.exitCode); + assertTrue("The output should name _51DEGREES_RESOURCE_KEY", + output.contains("Set the _51DEGREES_RESOURCE_KEY " + + "environment variable")); + int link = output.indexOf(CONFIGURE); + assertTrue("The output should link to where a key is created", + link >= 0 && output.startsWith(TAGS, + output.indexOf('?', link))); + assertTrue("The output should end with the Find out more section " + + "after the link", + output.lastIndexOf("Find out more") > link); + } + + @Test + public void gettingStartedWebCloudMixed() throws Exception { + runWithoutKey(GettingStartedWebCloudMixed.class); + } +} diff --git a/examples/ip-intelligence/web/getting-started.cloud/src/main/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloud.java b/examples/ip-intelligence/web/getting-started.cloud/src/main/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloud.java index c849b2560..217194491 100644 --- a/examples/ip-intelligence/web/getting-started.cloud/src/main/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloud.java +++ b/examples/ip-intelligence/web/getting-started.cloud/src/main/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloud.java @@ -116,7 +116,15 @@ public static void main(String[] args) throws Exception { // Get the resource key from the command line, environment variable or // system property. This sets the "TestResourceKey" system property // which is interpolated in the pipeline configuration file. - KeyHelper.getOrSetTestResourceKey(args.length > 0 ? args[0] : null, true); + String resourceKey = KeyHelper.findResourceKey( + args.length > 0 ? args[0] : null); + if (resourceKey == null) { + KeyHelper.writeNoResourceKey(System.out, EXAMPLE_TAG); + FindOutMore.write(System.out, EXAMPLE_TAG, + FindOutMore.CLOUD_REPOSITORIES); + return; + } + KeyHelper.getOrSetTestResourceKey(resourceKey, true); // start Jetty with this WebApp EmbedJetty.runWebApp(getResourceBase(), 8083); diff --git a/examples/ip-intelligence/web/getting-started.cloud/src/test/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloudWithoutKeyTest.java b/examples/ip-intelligence/web/getting-started.cloud/src/test/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloudWithoutKeyTest.java new file mode 100644 index 000000000..32488acfc --- /dev/null +++ b/examples/ip-intelligence/web/getting-started.cloud/src/test/java/fiftyone/ipintelligence/examples/web/GettingStartedWebCloudWithoutKeyTest.java @@ -0,0 +1,67 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.ipintelligence.examples.web; + +import fiftyone.ipintelligence.examples.shared.ExampleProcess; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Runs the IP Intelligence cloud web example as it runs from a fresh clone, + * with no resource key anywhere, and checks that it ends without an error, + * names the variable to set and links to where a key is created, then ends + * with its Find out more section. + */ +public class GettingStartedWebCloudWithoutKeyTest { + + private static final String CONFIGURE = "https://51degrees.com/configure/"; + + private static final String TAGS = + "?utm_source=code&utm_medium=example&utm_campaign=51degrees-java" + + "&utm_content="; + + private static void runWithoutKey(Class example) throws Exception { + ExampleProcess.Result result = ExampleProcess.runWithoutKeys(example); + System.out.println(result.output); + String output = result.output; + assertEquals(example.getSimpleName() + " should end with exit code 0", + 0, result.exitCode); + assertTrue("The output should name _51DEGREES_RESOURCE_KEY", + output.contains("Set the _51DEGREES_RESOURCE_KEY " + + "environment variable")); + int link = output.indexOf(CONFIGURE); + assertTrue("The output should link to where a key is created", + link >= 0 && output.startsWith(TAGS, + output.indexOf('?', link))); + assertTrue("The output should end with the Find out more section " + + "after the link", + output.lastIndexOf("Find out more") > link); + } + + @Test + public void gettingStartedWebCloud() throws Exception { + runWithoutKey(GettingStartedWebCloud.class); + } +} diff --git a/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/CombiningServices.java b/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/CombiningServices.java index 05135a033..55ee3ee9b 100644 --- a/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/CombiningServices.java +++ b/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/CombiningServices.java @@ -131,11 +131,16 @@ public static void main(String[] args) throws Exception { // Obtain a resource key for free at https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=geo-location.shell.examples-src-main-java-fiftyone-geolocation-examples-combiningservices.java&utm_term=main // Make sure to include the 'Country' and 'IsMobile' properties as they // are used by this example. - String resourceKey = "!!Your resource license key!!"; + String resourceKey = ResourceKey.find(args); - if (resourceKey.startsWith("!!")) { - System.out.println("You need to create a resource key at " + - "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=geo-location.shell.examples-src-main-java-fiftyone-geolocation-examples-combiningservices.java&utm_term=resource-key-required and paste it into this example."); + if (resourceKey == null) { + System.out.println("This example calls the 51Degrees cloud " + + "service, which needs a resource key, and none is set."); + System.out.println("Set the " + ResourceKey.VARIABLE + + " environment variable to a resource key, or give the key " + + "as the first argument, and run the example again."); + System.out.println("Create a resource key at " + + "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=geo-location.shell.examples-src-main-java-fiftyone-geolocation-examples-combiningservices.java&utm_term=resource-key-required"); System.out.println("Make sure to include the 'Country' and " + "'IsMobile' properties as they are used by this example."); } diff --git a/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/ResourceKey.java b/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/ResourceKey.java new file mode 100644 index 000000000..884473091 --- /dev/null +++ b/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/ResourceKey.java @@ -0,0 +1,56 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.geolocation.examples; + +/** + * Finds the resource key a Location example runs with. + */ +public final class ResourceKey { + + /** + * The variable the examples read their resource key from. + */ + public static final String VARIABLE = "_51DEGREES_RESOURCE_KEY"; + + private ResourceKey() { + } + + /** + * The key given as the first argument, or else the key in + * {@link #VARIABLE}, read as an environment variable and then as a + * system property. + * @param args the example's arguments + * @return the key, or null when there is none + */ + public static String find(String[] args) { + for (String value : new String[]{ + args.length > 0 ? args[0] : null, + System.getenv(VARIABLE), + System.getProperty(VARIABLE)}) { + if (value != null && value.trim().isEmpty() == false) { + return value.trim(); + } + } + return null; + } +} diff --git a/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/cloud/GettingStarted.java b/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/cloud/GettingStarted.java index 8585c8960..2dd7143b2 100644 --- a/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/cloud/GettingStarted.java +++ b/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/cloud/GettingStarted.java @@ -26,6 +26,7 @@ import fiftyone.geolocation.core.Enums; import fiftyone.geolocation.core.data.GeoData; import fiftyone.geolocation.examples.FindOutMore; +import fiftyone.geolocation.examples.ResourceKey; import fiftyone.pipeline.cloudrequestengine.data.CloudRequestData; import fiftyone.pipeline.core.data.FlowData; import fiftyone.pipeline.core.flowelements.Pipeline; @@ -85,11 +86,16 @@ public class GettingStarted { public static void main(String[] args) throws Exception { // Obtain a resource key for free at https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=geo-location.shell.examples-src-main-java-fiftyone-geolocation-examples-cloud-gettingstarted.java&utm_term=main // Make sure to include the 'Country' property as it is used by this example. - String resourceKey = "!!Your resource license key!!"; + String resourceKey = ResourceKey.find(args); - if (resourceKey.startsWith("!!")) { - System.out.println("You need to create a resource key at " + - "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=geo-location.shell.examples-src-main-java-fiftyone-geolocation-examples-cloud-gettingstarted.java&utm_term=resource-key-required and paste it into this example."); + if (resourceKey == null) { + System.out.println("This example calls the 51Degrees cloud " + + "service, which needs a resource key, and none is set."); + System.out.println("Set the " + ResourceKey.VARIABLE + + " environment variable to a resource key, or give the key " + + "as the first argument, and run the example again."); + System.out.println("Create a resource key at " + + "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=geo-location.shell.examples-src-main-java-fiftyone-geolocation-examples-cloud-gettingstarted.java&utm_term=resource-key-required"); System.out.println("Make sure to include the 'Country' " + "property as it is used by this example."); } diff --git a/location/geo-location.shell.examples/src/test/java/fiftyone/geolocation/examples/CloudExamplesWithoutKeyTests.java b/location/geo-location.shell.examples/src/test/java/fiftyone/geolocation/examples/CloudExamplesWithoutKeyTests.java new file mode 100644 index 000000000..7810e84e6 --- /dev/null +++ b/location/geo-location.shell.examples/src/test/java/fiftyone/geolocation/examples/CloudExamplesWithoutKeyTests.java @@ -0,0 +1,72 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.geolocation.examples; + +import fiftyone.geolocation.examples.cloud.GettingStarted; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Runs each Location example as it runs from a fresh clone, with no + * resource key anywhere, and checks that it ends without an error, names + * the variable to set and links to where a key is created, then ends with + * its Find out more section. + */ +public class CloudExamplesWithoutKeyTests { + + private static final String CONFIGURE = "https://51degrees.com/configure"; + + private static final String TAGS = + "?utm_source=code&utm_medium=example&utm_campaign=51degrees-java" + + "&utm_content="; + + private static void runWithoutKey(Class example) throws Exception { + ExampleProcess.Result result = ExampleProcess.runWithoutKeys(example); + System.out.println(result.output); + String output = result.output; + assertEquals(example.getSimpleName() + " should end with exit code 0", + 0, result.exitCode); + assertTrue("The output should name _51DEGREES_RESOURCE_KEY", + output.contains("Set the _51DEGREES_RESOURCE_KEY " + + "environment variable")); + int link = output.indexOf(CONFIGURE); + assertTrue("The output should link to where a key is created", + link >= 0 && output.startsWith(TAGS, + output.indexOf('?', link))); + assertTrue("The output should end with the Find out more section " + + "after the link", + output.lastIndexOf("Find out more") > link); + } + + @Test + public void gettingStarted() throws Exception { + runWithoutKey(GettingStarted.class); + } + + @Test + public void combiningServices() throws Exception { + runWithoutKey(CombiningServices.class); + } +} diff --git a/location/geo-location.shell.examples/src/test/java/fiftyone/geolocation/examples/ExampleProcess.java b/location/geo-location.shell.examples/src/test/java/fiftyone/geolocation/examples/ExampleProcess.java new file mode 100644 index 000000000..1fd9df08b --- /dev/null +++ b/location/geo-location.shell.examples/src/test/java/fiftyone/geolocation/examples/ExampleProcess.java @@ -0,0 +1,127 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.geolocation.examples; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.TimeUnit; + +/** + * Runs an example's main method in a new Java process with no key in its + * environment, as someone runs it from a fresh clone, for the tests of + * what an example does with no settings. A new process is needed because + * a running Java process cannot remove a variable from its own + * environment. + */ +final class ExampleProcess { + + /** + * How long an example may run before the test stops it. + */ + private static final long TIMEOUT_SECONDS = 120; + + /** + * What an example wrote and how it ended. + */ + public static final class Result { + /** + * The process's exit code. + */ + public final int exitCode; + + /** + * Everything the process wrote to standard output and standard + * error. + */ + public final String output; + + Result(int exitCode, String output) { + this.exitCode = exitCode; + this.output = output; + } + } + + private ExampleProcess() { + } + + /** + * Runs the example's main method with no arguments and with every + * environment variable whose name holds "KEY", in any case, left out. + * The process takes the class path of the process that starts it, and + * of its system properties only project.root, which says where the + * files the example reads are. + * @param example the class whose main method runs + * @return the exit code and the output + * @throws Exception if the process cannot start, or does not end + * within the timeout + */ + public static Result runWithoutKeys(Class example) throws Exception { + List command = new ArrayList<>(); + command.add(new File(new File(System.getProperty("java.home"), + "bin"), "java").getPath()); + command.add("-cp"); + command.add(System.getProperty("java.class.path")); + String projectRoot = System.getProperty("project.root"); + if (projectRoot != null) { + command.add("-Dproject.root=" + projectRoot); + } + command.add(example.getName()); + + ProcessBuilder builder = new ProcessBuilder(command); + builder.environment().keySet().removeIf( + name -> name.toUpperCase(Locale.ROOT).contains("KEY")); + builder.redirectErrorStream(true); + Process process = builder.start(); + + ByteArrayOutputStream output = new ByteArrayOutputStream(); + Thread reader = new Thread(() -> copy(process.getInputStream(), + output)); + reader.start(); + if (process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS) == false) { + process.destroyForcibly(); + reader.join(); + throw new AssertionError(example.getName() + + " did not end within " + TIMEOUT_SECONDS + " seconds. " + + "It wrote:\n" + output.toString("UTF-8")); + } + reader.join(); + return new Result(process.exitValue(), output.toString("UTF-8")); + } + + private static void copy(InputStream input, ByteArrayOutputStream output) { + byte[] buffer = new byte[8192]; + try { + int read; + while ((read = input.read(buffer)) >= 0) { + output.write(buffer, 0, read); + } + } catch (IOException e) { + // The process ended, so there is no more to read. + } + } +} diff --git a/location/geo-location.shell.examples/src/test/java/fiftyone/geolocation/examples/FindOutMoreTests.java b/location/geo-location.shell.examples/src/test/java/fiftyone/geolocation/examples/FindOutMoreTests.java index 68b751cee..b8f3f8e9a 100644 --- a/location/geo-location.shell.examples/src/test/java/fiftyone/geolocation/examples/FindOutMoreTests.java +++ b/location/geo-location.shell.examples/src/test/java/fiftyone/geolocation/examples/FindOutMoreTests.java @@ -49,7 +49,8 @@ public class FindOutMoreTests { private static final String REPOSITORY = "https://github.com/51Degrees/51degrees-java"; - private static final String NO_KEY = "You need to create a resource key"; + private static final String NO_KEY = + "needs a resource key, and none is set"; private static final Pattern TAGGED = Pattern.compile( "https://51degrees\\.com/[^?\\s]*\\?utm_source=code" diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/main/java/pipeline/developerexamples/fodid/CreatorContextDemoServer.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/main/java/pipeline/developerexamples/fodid/CreatorContextDemoServer.java index 3eaf3c223..d55b18adf 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/main/java/pipeline/developerexamples/fodid/CreatorContextDemoServer.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/main/java/pipeline/developerexamples/fodid/CreatorContextDemoServer.java @@ -133,9 +133,15 @@ public class CreatorContextDemoServer { public static void main(String[] args) throws Exception { if (RESOURCE == null) { - System.err.println( - "Set _51DEGREES_RESOURCE_KEY to the resource key of the page."); - System.exit(1); + System.out.println("This demo calls the 51Degrees cloud " + + "service, which needs a resource key, and none is set."); + System.out.println("Set the _51DEGREES_RESOURCE_KEY environment " + + "variable to the resource key of the page, and run the demo " + + "again."); + System.out.println("Create a resource key at " + + "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=pipeline.developer-examples.fodid-creatorcontextdemoserver.java&utm_term=no-resource-key"); + Main.writeFindOutMore(System.out); + return; } if (LICENCE == null) { // Only an account that holds licence keys needs one to diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/test/java/pipeline/developerexamples/fodid/CreatorContextDemoServerWithoutKeyTests.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/test/java/pipeline/developerexamples/fodid/CreatorContextDemoServerWithoutKeyTests.java new file mode 100644 index 000000000..c8da2fb1e --- /dev/null +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/test/java/pipeline/developerexamples/fodid/CreatorContextDemoServerWithoutKeyTests.java @@ -0,0 +1,66 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package pipeline.developerexamples.fodid; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Runs the 51Did creator context demo server as it runs from a fresh clone, + * with no resource key anywhere, and checks that it ends without an error, + * names the variable to set and links to where a key is created, then ends + * with its Find out more section. + */ +class CreatorContextDemoServerWithoutKeyTests { + + private static final String CONFIGURE = "https://51degrees.com/configure"; + + private static final String TAGS = + "?utm_source=code&utm_medium=example&utm_campaign=51degrees-java" + + "&utm_content="; + + private static void runWithoutKey(Class example) throws Exception { + ExampleProcess.Result result = ExampleProcess.runWithoutKeys(example); + System.out.println(result.output); + String output = result.output; + assertEquals(0, result.exitCode, + example.getSimpleName() + " should end with exit code 0"); + assertTrue(output.contains( + "Set the _51DEGREES_RESOURCE_KEY environment variable"), + "The output should name _51DEGREES_RESOURCE_KEY"); + int link = output.indexOf(CONFIGURE); + assertTrue(link >= 0 && output.startsWith(TAGS, + output.indexOf('?', link)), + "The output should link to where a key is created"); + assertTrue(output.lastIndexOf("Find out more") > link, + "The output should end with the Find out more " + + "section after the link"); + } + + @Test + void creatorContextDemoServer() throws Exception { + runWithoutKey(CreatorContextDemoServer.class); + } +} diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/test/java/pipeline/developerexamples/fodid/ExampleProcess.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/test/java/pipeline/developerexamples/fodid/ExampleProcess.java new file mode 100644 index 000000000..330f1e554 --- /dev/null +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/test/java/pipeline/developerexamples/fodid/ExampleProcess.java @@ -0,0 +1,127 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package pipeline.developerexamples.fodid; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.TimeUnit; + +/** + * Runs an example's main method in a new Java process with no key in its + * environment, as someone runs it from a fresh clone, for the tests of + * what an example does with no settings. A new process is needed because + * a running Java process cannot remove a variable from its own + * environment. + */ +final class ExampleProcess { + + /** + * How long an example may run before the test stops it. + */ + private static final long TIMEOUT_SECONDS = 120; + + /** + * What an example wrote and how it ended. + */ + public static final class Result { + /** + * The process's exit code. + */ + public final int exitCode; + + /** + * Everything the process wrote to standard output and standard + * error. + */ + public final String output; + + Result(int exitCode, String output) { + this.exitCode = exitCode; + this.output = output; + } + } + + private ExampleProcess() { + } + + /** + * Runs the example's main method with no arguments and with every + * environment variable whose name holds "KEY", in any case, left out. + * The process takes the class path of the process that starts it, and + * of its system properties only project.root, which says where the + * files the example reads are. + * @param example the class whose main method runs + * @return the exit code and the output + * @throws Exception if the process cannot start, or does not end + * within the timeout + */ + public static Result runWithoutKeys(Class example) throws Exception { + List command = new ArrayList<>(); + command.add(new File(new File(System.getProperty("java.home"), + "bin"), "java").getPath()); + command.add("-cp"); + command.add(System.getProperty("java.class.path")); + String projectRoot = System.getProperty("project.root"); + if (projectRoot != null) { + command.add("-Dproject.root=" + projectRoot); + } + command.add(example.getName()); + + ProcessBuilder builder = new ProcessBuilder(command); + builder.environment().keySet().removeIf( + name -> name.toUpperCase(Locale.ROOT).contains("KEY")); + builder.redirectErrorStream(true); + Process process = builder.start(); + + ByteArrayOutputStream output = new ByteArrayOutputStream(); + Thread reader = new Thread(() -> copy(process.getInputStream(), + output)); + reader.start(); + if (process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS) == false) { + process.destroyForcibly(); + reader.join(); + throw new AssertionError(example.getName() + + " did not end within " + TIMEOUT_SECONDS + " seconds. " + + "It wrote:\n" + output.toString("UTF-8")); + } + reader.join(); + return new Result(process.exitValue(), output.toString("UTF-8")); + } + + private static void copy(InputStream input, ByteArrayOutputStream output) { + byte[] buffer = new byte[8192]; + try { + int read; + while ((read = input.read(buffer)) >= 0) { + output.write(buffer, 0, read); + } + } catch (IOException e) { + // The process ended, so there is no more to read. + } + } +}