From 6a1688a53fbb56621d0c4db2b5b5d39ffcc52bb0 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Mon, 23 Nov 2026 20:09:28 +0000 Subject: [PATCH 1/2] FIX: Decide on the hardware lookup from a loaded property list in the TAC and native model examples When the cloud's accessible properties request failed as the pipeline was built, the examples ran the lookups. If processing then fetched the list for a key without the hardware lookup, they printed each heading with "No devices are associated" under it and exited with code 0, deciding from an empty lookup rather than from the list. Each example still checks the hardware engine's properties before any lookup. After processing a lookup, which fetches the accessible properties first when they are not known and throws the cloud service's error if that fails again, it checks them once more before using the result. So the decision is always made from a loaded list, a key without the lookup gets the one line and exit code 0, and a second failure ends with the cloud service's error and a non-zero exit code. The line is written by one method in each example. Two comments are corrected. TacCloud named a NativeModelLookup example, which is NativeModelCloud, and NativeModelCloud spelled pipeline wrongly. --- .../examples/console/NativeModelCloud.java | 67 ++++++++++++------ .../examples/console/TacCloud.java | 68 +++++++++++++------ 2 files changed, 91 insertions(+), 44 deletions(-) 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 c2b585df6..cc470a745 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 @@ -109,28 +109,20 @@ public static void run(String resourceKey, OutputStream os) throws Exception { .setResourceKey(resourceKey) .build()) // Create the hardware profile engine to process the response from the - // request engine - and add to the pipleine + // request engine - and add to the pipeline .addFlowElement(new HardwareProfileCloudEngineBuilder(LoggerFactory.getILoggerFactory()) .build()) // very important to ask pipeline to close the engines we added since // we are not closing them ourselves .setAutoCloseElements(true) .build()) { + // The pipeline asked the cloud for the key's accessible + // properties as it was built, so unless that request failed, + // a key without the lookup is found here, before any lookup. if (lacksHardwareLookup(pipeline)) { - output.println("The resource key does not include " + - "HardwarePlatform.Profiles, the hardware lookup " + - "this example needs, so no devices are listed. " + - "Create a resource key that includes it at " + - FindOutMore.link( - KeyHelper.PAID_PROPERTIES_CONFIGURATION, - EXAMPLE_TAG, NO_HARDWARE_LOOKUP) + - ", or contact us about it at " + - FindOutMore.link("contact-us", EXAMPLE_TAG, - NO_HARDWARE_LOOKUP) + "."); - } else { - // Pass a native model into the pipeline and list the - // matching devices. - analyseNativeModel(NATIVE_MODEL_1, pipeline, output); + writeNoHardwareLookup(output); + } else if (analyseNativeModel(NATIVE_MODEL_1, pipeline, + output)) { // Repeat for an alternative native model name. analyseNativeModel(NATIVE_MODEL_2, pipeline, output); } @@ -142,14 +134,28 @@ public static void run(String resourceKey, OutputStream os) throws Exception { } } - static void analyseNativeModel(String nativemodel, Pipeline pipeline, PrintWriter output) throws Exception { + /** + * Lists the devices associated with the native model name, or says that + * the resource key does not include the hardware lookup. + * @return false if the key does not include the lookup + */ + static boolean analyseNativeModel(String nativemodel, Pipeline pipeline, PrintWriter output) throws Exception { // Create the FlowData instance. This is wrapped in a try with resources to ensure // that resources are disposed correctly. try (FlowData data = pipeline.createFlowData()) { // Add the native model key as evidence. data.addEvidence(Constants.EVIDENCE_QUERY_NATIVE_MODEL_KEY, nativemodel); - // Process the supplied evidence. + // Process the supplied evidence. If the accessible properties + // could not be fetched as the pipeline was built, processing + // fetches them first, and throws the cloud service's error if + // that fails again. data.process(); + // So they are known now, and are checked before the result is + // used. + if (lacksHardwareLookup(pipeline)) { + writeNoHardwareLookup(output); + return false; + } // Get result data from the flow data. MultiDeviceDataCloud result = data.get(MultiDeviceDataCloud.class); // The 'MultiDeviceDataCloud' object contains one or more instances @@ -168,15 +174,32 @@ static void analyseNativeModel(String nativemodel, Pipeline pipeline, PrintWrite asString(device.getHardwareModel())); } + return true; } } /** - * Whether the resource key lacks the hardware lookup. The hardware - * engine's properties come from the cloud's accessible properties for - * the key, and hold Profiles only when the key includes the lookup. - * When the accessible properties could not be fetched nothing is known - * to be missing, so the lookups run and report what went wrong. + * Says that the resource key does not include the hardware lookup, with + * where to create a key that does. + */ + static void writeNoHardwareLookup(PrintWriter output) { + output.println("The resource key does not include " + + "HardwarePlatform.Profiles, the hardware lookup this " + + "example needs, so no devices are listed. Create a " + + "resource key that includes it at " + + FindOutMore.link(KeyHelper.PAID_PROPERTIES_CONFIGURATION, + EXAMPLE_TAG, NO_HARDWARE_LOOKUP) + + ", or contact us about it at " + + FindOutMore.link("contact-us", EXAMPLE_TAG, + NO_HARDWARE_LOOKUP) + "."); + } + + /** + * Whether the resource key is known to lack the hardware lookup. The + * hardware engine's properties come from the cloud's accessible + * properties for the key, and hold Profiles only when the key includes + * the lookup. Until the accessible properties have been fetched nothing + * is known to be missing. */ static boolean lacksHardwareLookup(Pipeline pipeline) { if (pipeline.getElement(CloudRequestEngine.class) 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 c0e253136..faaafb892 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 @@ -104,7 +104,7 @@ public static void main (String[] args) throws Exception { public static void run(String resourceKey, OutputStream os) throws Exception { // In this example, we use the FiftyOnePipelineBuilder and configure it from a file. // For a demonstration of how to do this in code instead, see the - // NativeModelLookup example. + // NativeModelCloud example. // For more information about builders in general see the documentation at // https://51degrees.com/documentation/_pipeline_api__concepts__configuration__builders__index.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=console-src-main-java-fiftyone-devicedetection-examples-console-taccloud.java&utm_term=run @@ -130,21 +130,14 @@ public static void run(String resourceKey, OutputStream os) throws Exception { // Create the pipeline using the service provider and the configured options. try (Pipeline pipeline = new FiftyOnePipelineBuilder() .buildFromConfiguration(pipelineOptions)) { + // The pipeline asked the cloud for the key's accessible + // properties as it was built, so unless that request failed, + // a key without the lookup is found here, before any lookup. if (lacksHardwareLookup(pipeline)) { - writer.println("The resource key does not include " + - "HardwarePlatform.Profiles, the hardware lookup " + - "this example needs, so no devices are listed. " + - "Create a resource key that includes it at " + - FindOutMore.link( - KeyHelper.PAID_PROPERTIES_CONFIGURATION, - EXAMPLE_TAG, NO_HARDWARE_LOOKUP) + - ", or contact us about it at " + - FindOutMore.link("contact-us", EXAMPLE_TAG, - NO_HARDWARE_LOOKUP) + "."); - } else { - // Pass a TAC into the pipeline and list the matching - // devices. - analyseTac(TAC_1, pipeline, writer); + writeNoHardwareLookup(writer); + } else if (analyseTac(TAC_1, pipeline, writer)) { + // Pass the second TAC into the pipeline and list the + // matching devices. analyseTac(TAC_2, pipeline, writer); } } @@ -155,13 +148,27 @@ public static void run(String resourceKey, OutputStream os) throws Exception { } } - static void analyseTac(String tac, Pipeline pipeline, PrintWriter output) throws Exception { + /** + * Lists the devices associated with the TAC, or says that the resource + * key does not include the hardware lookup. + * @return false if the key does not include the lookup + */ + static boolean analyseTac(String tac, Pipeline pipeline, PrintWriter output) throws Exception { // Create the FlowData instance. try (FlowData data = pipeline.createFlowData()) { // Add the TAC as evidence. data.addEvidence(Constants.EVIDENCE_QUERY_TAC_KEY, tac); - // Process the supplied evidence. + // Process the supplied evidence. If the accessible properties + // could not be fetched as the pipeline was built, processing + // fetches them first, and throws the cloud service's error if + // that fails again. data.process(); + // So they are known now, and are checked before the result is + // used. + if (lacksHardwareLookup(pipeline)) { + writeNoHardwareLookup(output); + return false; + } // Get result data from the flow data. MultiDeviceDataCloud result = data.get(MultiDeviceDataCloud.class); // The 'MultiDeviceDataCloud' object contains one or more instances @@ -179,15 +186,32 @@ static void analyseTac(String tac, Pipeline pipeline, PrintWriter output) throws // output the result, taking care to deal with "no value" cases output.format("\t%s %s (%s)%n", asString(vendor), asString(name), asString(model)); } + return true; } } /** - * Whether the resource key lacks the hardware lookup. The hardware - * engine's properties come from the cloud's accessible properties for - * the key, and hold Profiles only when the key includes the lookup. - * When the accessible properties could not be fetched nothing is known - * to be missing, so the lookups run and report what went wrong. + * Says that the resource key does not include the hardware lookup, with + * where to create a key that does. + */ + static void writeNoHardwareLookup(PrintWriter output) { + output.println("The resource key does not include " + + "HardwarePlatform.Profiles, the hardware lookup this " + + "example needs, so no devices are listed. Create a " + + "resource key that includes it at " + + FindOutMore.link(KeyHelper.PAID_PROPERTIES_CONFIGURATION, + EXAMPLE_TAG, NO_HARDWARE_LOOKUP) + + ", or contact us about it at " + + FindOutMore.link("contact-us", EXAMPLE_TAG, + NO_HARDWARE_LOOKUP) + "."); + } + + /** + * Whether the resource key is known to lack the hardware lookup. The + * hardware engine's properties come from the cloud's accessible + * properties for the key, and hold Profiles only when the key includes + * the lookup. Until the accessible properties have been fetched nothing + * is known to be missing. */ static boolean lacksHardwareLookup(Pipeline pipeline) { if (pipeline.getElement(CloudRequestEngine.class) From 1e664d3752bdb50521cee9f31ebbe44b3b975b4b Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Mon, 23 Nov 2026 20:09:29 +0000 Subject: [PATCH 2/2] TEST: Check the hardware lookup examples when the cloud fails or finds nothing HardwareLookupWithoutProfilesTest becomes HardwareLookupStandInTest, whose stand-in for the cloud service answers what each test sets. Each case runs for both examples. - Without profiles. The accessible properties have no hardware element. The test now compares the whole line, and requires that nothing is logged as an error and no stack trace is printed, as well as exit code 0, no lookup heading and no lookup request. - No devices. The accessible properties carry the hardware element and each lookup answers with an empty list of profiles. Each heading must be followed by the line saying no devices are associated with the value. - Properties fail every time. The accessible properties request answers 500 with an error. The example must end with a non-zero exit code, with the cloud service's error logged as an error, no lookup heading, no line saying the key lacks the lookup and no lookup request. - Properties fail once. The first accessible properties request answers 500 and the next gives no hardware element. The example must ask again, print the line saying the key lacks the lookup with no heading, and end with exit code 0. The log lines carry colour codes around their level, which are removed before the output is checked. The two new fixtures come from answers the staging cloud gave, with the accessible properties cut down to what the examples use, and hold no key. AGENTS.md now names the error the examples end with against the published 4.5.130 packages, and says what the examples print when a lookup matches nothing or the property list cannot be fetched. --- AGENTS.md | 19 +- .../console/HardwareLookupStandInTest.java | 407 ++++++++++++++++++ .../HardwareLookupWithoutProfilesTest.java | 193 --------- .../accessibleproperties-with-hardware.json | 50 +++ .../examples/console/json-no-devices.json | 1 + 5 files changed, 471 insertions(+), 199 deletions(-) create mode 100644 examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/HardwareLookupStandInTest.java delete mode 100644 examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/HardwareLookupWithoutProfilesTest.java create mode 100644 examples/device-detection/console/src/test/resources/fiftyone/devicedetection/examples/console/accessibleproperties-with-hardware.json create mode 100644 examples/device-detection/console/src/test/resources/fiftyone/devicedetection/examples/console/json-no-devices.json diff --git a/AGENTS.md b/AGENTS.md index 4d740e998..7f70f2de3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -204,12 +204,19 @@ HardwarePlatform.Profiles. With one, they list each device as ` ()` under the value looked up. With a key that does not include it, they say so in one line that links to where a key is created and to the contact page, make no lookup, end with their "Find out more" -section and exit with code 0. The published packages up to 4.5.130 cannot -build the pipeline for such a key, so with those the examples end with that -error instead. `TacCloudTest` and `NativeModelCloudTest` fail when the key in -`_51DEGREES_RESOURCE_KEY_BESPOKE` lacks the property, and -`HardwareLookupWithoutProfilesTest` checks the message against a stand-in for -the cloud service. +section and exit with code 0. A lookup that matches no device prints +`No devices are associated with this TAC.` or `... this native model name.` +under its heading. When the cloud's list of the key's properties cannot be +fetched, the examples end with the cloud service's error and a non-zero exit +code. The published packages up to 4.5.130 cannot build the pipeline for a +key without the lookup, so with those the examples log +`Aspect properties could not be loaded for fiftyone.devicedetection.cloud.flowelements.HardwareProfileCloudEngine`, +end with `java.lang.RuntimeException: Failed to load aspect properties for element 'hardware'` +and exit with code 1. `TacCloudTest` and `NativeModelCloudTest` fail when the +key in `_51DEGREES_RESOURCE_KEY_BESPOKE` lacks the property. +`HardwareLookupStandInTest` runs both examples against a stand-in for the +cloud service, for a key without the lookup, for lookups that match nothing, +and for a list of properties that fails once or every time. ### Pitfalls diff --git a/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/HardwareLookupStandInTest.java b/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/HardwareLookupStandInTest.java new file mode 100644 index 000000000..a8ad36f5f --- /dev/null +++ b/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/HardwareLookupStandInTest.java @@ -0,0 +1,407 @@ +/* ********************************************************************* + * 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 com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import fiftyone.devicedetection.examples.shared.ExampleProcess; +import fiftyone.devicedetection.examples.shared.FindOutMore; +import fiftyone.devicedetection.examples.shared.KeyHelper; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +/** + * Runs the TAC and native model examples against a stand-in for the cloud + * service that this test starts on this machine, so no resource key or + * network is needed. The stand-in answers the accessible properties, the + * evidence keys and the lookup with what each test sets, and anything else + * with 404, and records the path of every request. + */ +public class HardwareLookupStandInTest { + + /** + * The variable the cloud request engine reads its endpoint from. + */ + private static final String CLOUD_ENDPOINT = "_51DEGREES_CLOUD_ENDPOINT"; + + /** + * A value the examples accept as a resource key, which the stand-in + * does not check. + */ + private static final String RESOURCE_KEY = "standInResourceKey000000"; + + private static final String TAGS = + "?utm_source=code&utm_medium=example&utm_campaign=51degrees-java" + + "&utm_content="; + + private static final String MESSAGE = + "The resource key does not include HardwarePlatform.Profiles"; + + private static final String HEADING = "Which devices are associated"; + + /** + * The error the stand-in gives when it fails a request. + */ + private static final String CLOUD_ERROR = + "The stand-in cloud service failed this request."; + + /** + * A lookup answer for a resource key without the hardware element. + */ + private static final String NO_HARDWARE_ANSWER = + "{\"device\":{\"ismobile\":true},\"javascriptProperties\":[]}"; + + private final List requests = new CopyOnWriteArrayList<>(); + + /** + * How many more accessible properties requests to answer with 500. + */ + private final AtomicInteger propertiesFailures = new AtomicInteger(); + + private volatile byte[] properties; + + private volatile byte[] lookup; + + private HttpServer cloud; + + @Before + public void startCloud() throws Exception { + byte[] evidenceKeys = fixture("evidencekeys.json"); + cloud = HttpServer.create( + new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + cloud.createContext("/", exchange -> { + try (InputStream body = exchange.getRequestBody()) { + byte[] buffer = new byte[4096]; + while (body.read(buffer) >= 0) { + // Read the whole request before answering. + } + } + String path = exchange.getRequestURI().getPath(); + requests.add(path); + if (path.endsWith("accessibleproperties")) { + if (propertiesFailures.getAndUpdate( + failures -> Math.max(0, failures - 1)) > 0) { + answer(exchange, 500, ("{\"errors\":[\"" + CLOUD_ERROR + + "\"]}").getBytes(StandardCharsets.UTF_8)); + } else { + answer(exchange, 200, properties); + } + } else if (path.endsWith("evidencekeys")) { + answer(exchange, 200, evidenceKeys); + } else if (path.endsWith("json") && lookup != null) { + answer(exchange, 200, lookup); + } else { + exchange.sendResponseHeaders(404, -1); + exchange.close(); + } + }); + cloud.start(); + } + + @After + public void stopCloud() { + cloud.stop(0); + } + + private static void answer(HttpExchange exchange, int status, + byte[] body) throws IOException { + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(status, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + } + + private static byte[] fixture(String name) throws IOException { + try (InputStream input = + HardwareLookupStandInTest.class.getResourceAsStream(name)) { + if (input == null) { + throw new IOException( + "The fixture " + name + " should be a resource."); + } + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int read; + while ((read = input.read(buffer)) >= 0) { + bytes.write(buffer, 0, read); + } + return bytes.toByteArray(); + } + } + + /** + * Runs the example's main method in its own process, with a resource + * key and the stand-in as its cloud service. + */ + private ExampleProcess.Result run(Class example) throws Exception { + Map environment = new HashMap<>(); + environment.put(KeyHelper.RESOURCE_KEY_VARIABLE, RESOURCE_KEY); + environment.put(CLOUD_ENDPOINT, "http://" + + cloud.getAddress().getHostString() + ":" + + cloud.getAddress().getPort() + "/api/v4/"); + ExampleProcess.Result result = + ExampleProcess.runWith(example, environment); + System.out.println(result.output); + return result; + } + + /** + * Fails unless the example ended with exit code 0 and logged no error. + * Unless the stand-in failed a request, which the library logs as a + * warning with its stack trace, no stack trace may be printed either. + */ + private static String requireEndedNormally(Class example, + ExampleProcess.Result result, + boolean failedRequest) { + String output = plain(result.output); + assertEquals(example.getSimpleName() + + " should end with exit code 0.\n" + output, + 0, result.exitCode); + for (String line : lines(output)) { + assertFalse("Nothing should be logged as an error.\n" + output, + line.contains(" ERROR ")); + assertFalse("No stack trace should be printed.\n" + output, + failedRequest == false && ( + line.startsWith("Exception") || + line.startsWith("Caused by") || + line.startsWith("\tat "))); + } + assertTrue("The output should hold the '" + FindOutMore.HEADING + + "' section.\n" + output, + output.contains(FindOutMore.HEADING)); + return output; + } + + /** + * The output without the colour codes around the level of each log + * line. + */ + private static String plain(String output) { + return output.replaceAll("\u001B\\[[0-9;]*m", ""); + } + + private static List lines(String output) { + return Arrays.asList(output.split("\r?\n")); + } + + /** + * The line the example prints when the key lacks the lookup. + */ + private static String noHardwareLine(Class example) { + String content = "console-src-main-java-fiftyone-devicedetection-" + + "examples-console-" + + example.getSimpleName().toLowerCase(Locale.ROOT) + ".java"; + String tags = TAGS + content + "&utm_term=no-hardware-lookup"; + return MESSAGE + ", the hardware lookup this example needs, so no " + + "devices are listed. Create a resource key that includes it at " + + "https://51degrees.com/configure/QKyYH5XT" + tags + + ", or contact us about it at https://51degrees.com/contact-us" + + tags + "."; + } + + private int lookupRequests() { + int count = 0; + for (String request : requests) { + if (request.endsWith("json")) { + count++; + } + } + return count; + } + + private void requireNoHardwareLine(Class example, String output) { + assertTrue("The output should hold the line that says the key " + + "does not include HardwarePlatform.Profiles, being\n" + + noHardwareLine(example) + "\n" + output, + lines(output).contains(noHardwareLine(example))); + assertTrue("The '" + FindOutMore.HEADING + "' section should " + + "follow the line.\n" + output, + output.lastIndexOf(FindOutMore.HEADING) > + output.indexOf(MESSAGE)); + requireNoHeading(output); + } + + private static void requireNoHeading(String output) { + for (String line : lines(output)) { + assertFalse("No lookup should be listed.\n" + output, + line.startsWith(HEADING)); + } + } + + /** + * The accessible properties have no hardware element, as for a key + * without HardwarePlatform.Profiles. The example should say so in one + * line, make no lookup and end normally. + */ + private void withoutProfiles(Class example) throws Exception { + properties = fixture("accessibleproperties-no-hardware.json"); + String output = requireEndedNormally(example, run(example), false); + requireNoHardwareLine(example, output); + assertEquals("No lookup request should be made, and " + requests + + " were made.", 0, lookupRequests()); + assertTrue("The example should have asked the stand-in for the " + + "accessible properties, and asked for " + requests, + requests.stream().anyMatch( + request -> request.endsWith("accessibleproperties"))); + } + + /** + * The key includes the lookup and each lookup matches no device. The + * example should print each heading with the line that says so under + * it, and end normally. + */ + private void noDevices(Class example, String subject, String none, + String... values) throws Exception { + properties = fixture("accessibleproperties-with-hardware.json"); + lookup = fixture("json-no-devices.json"); + String output = requireEndedNormally(example, run(example), false); + List lines = lines(output); + for (String value : values) { + String heading = HEADING + " with " + subject + " '" + value + + "'?"; + int at = lines.indexOf(heading); + assertTrue("The output should hold the heading " + heading + + "\n" + output, at >= 0); + assertTrue("'" + none + "' should follow the heading " + + heading + "\n" + output, + at + 1 < lines.size() && lines.get(at + 1).equals(none)); + } + assertFalse("The output should not say the key lacks the " + + "lookup.\n" + output, output.contains(MESSAGE)); + assertEquals("A lookup request should be made for each value, and " + + requests + " were made.", values.length, lookupRequests()); + } + + /** + * The accessible properties request fails every time. The example + * should end with the cloud service's error, and not say the key lacks + * the lookup. + */ + private void propertiesFailEveryTime(Class example) throws Exception { + properties = fixture("accessibleproperties-no-hardware.json"); + propertiesFailures.set(Integer.MAX_VALUE); + ExampleProcess.Result result = run(example); + String output = plain(result.output); + assertNotEquals(example.getSimpleName() + + " should end with an error.\n" + output, + 0, result.exitCode); + // The failure as the pipeline is built is a warning, so the error + // has to follow a line logged as an error. + int error = output.indexOf(" ERROR "); + assertTrue("The cloud service's error should be logged as an " + + "error.\n" + output, + error >= 0 && output.indexOf(CLOUD_ERROR, error) >= 0); + assertFalse("The output should not say the key lacks the " + + "lookup.\n" + output, output.contains(MESSAGE)); + requireNoHeading(output); + assertEquals("No lookup request should be made, and " + requests + + " were made.", 0, lookupRequests()); + } + + /** + * The accessible properties request fails as the pipeline is built and + * then gives no hardware element. The example should fetch them again + * and decide from them, saying the key lacks the lookup and ending + * normally, rather than listing no devices. + */ + private void propertiesFailOnce(Class example) throws Exception { + properties = fixture("accessibleproperties-no-hardware.json"); + lookup = NO_HARDWARE_ANSWER.getBytes(StandardCharsets.UTF_8); + propertiesFailures.set(1); + String output = requireEndedNormally(example, run(example), true); + requireNoHardwareLine(example, output); + assertEquals("The accessible properties should be asked for " + + "twice, and " + requests + " were requested.", + 2, requests.stream().filter( + request -> request.endsWith("accessibleproperties")).count()); + // Processing the first lookup is what fetches them again, so that + // lookup is made, and no other. + assertTrue("At most one lookup request should be made, and " + + requests + " were made.", lookupRequests() <= 1); + } + + @Test + public void tacCloudWithoutProfiles() throws Exception { + withoutProfiles(TacCloud.class); + } + + @Test + public void nativeModelCloudWithoutProfiles() throws Exception { + withoutProfiles(NativeModelCloud.class); + } + + @Test + public void tacCloudNoDevices() throws Exception { + noDevices(TacCloud.class, "the TAC", + "\tNo devices are associated with this TAC.", + TacCloud.TAC_1, TacCloud.TAC_2); + } + + @Test + public void nativeModelCloudNoDevices() throws Exception { + noDevices(NativeModelCloud.class, "the native model name", + "\tNo devices are associated with this native model name.", + NativeModelCloud.NATIVE_MODEL_1, NativeModelCloud.NATIVE_MODEL_2); + } + + @Test + public void tacCloudPropertiesFailEveryTime() throws Exception { + propertiesFailEveryTime(TacCloud.class); + } + + @Test + public void nativeModelCloudPropertiesFailEveryTime() throws Exception { + propertiesFailEveryTime(NativeModelCloud.class); + } + + @Test + public void tacCloudPropertiesFailOnce() throws Exception { + propertiesFailOnce(TacCloud.class); + } + + @Test + public void nativeModelCloudPropertiesFailOnce() throws Exception { + propertiesFailOnce(NativeModelCloud.class); + } +} diff --git a/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/HardwareLookupWithoutProfilesTest.java b/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/HardwareLookupWithoutProfilesTest.java deleted file mode 100644 index 1336aad45..000000000 --- a/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/HardwareLookupWithoutProfilesTest.java +++ /dev/null @@ -1,193 +0,0 @@ -/* ********************************************************************* - * 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 com.sun.net.httpserver.HttpServer; -import fiftyone.devicedetection.examples.shared.ExampleProcess; -import fiftyone.devicedetection.examples.shared.FindOutMore; -import fiftyone.devicedetection.examples.shared.KeyHelper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - * Runs the TAC and native model examples against a stand-in for the cloud - * service that this test starts on this machine, so no resource key or - * network is needed. The stand-in gives the accessible properties the cloud - * gives a resource key that does not include HardwarePlatform.Profiles, the - * evidence keys the cloud accepts, and 404 for anything else. Each example - * should say the key lacks the lookup, link to where a key is created and - * to the contact page, make no lookup and end normally. - */ -public class HardwareLookupWithoutProfilesTest { - - /** - * The variable the cloud request engine reads its endpoint from. - */ - private static final String CLOUD_ENDPOINT = "_51DEGREES_CLOUD_ENDPOINT"; - - /** - * A value the examples accept as a resource key, which the stand-in - * does not check. - */ - private static final String RESOURCE_KEY = "standInResourceKey000000"; - - private static final String TAGS = - "?utm_source=code&utm_medium=example&utm_campaign=51degrees-java"; - - private static final String CONFIGURE = - "https://51degrees.com/configure/QKyYH5XT" + TAGS; - - private static final String CONTACT_US = - "https://51degrees.com/contact-us" + TAGS; - - private static final String MESSAGE = - "The resource key does not include HardwarePlatform.Profiles"; - - private final List requests = new CopyOnWriteArrayList<>(); - - private HttpServer cloud; - - @Before - public void startCloud() throws Exception { - byte[] properties = fixture("accessibleproperties-no-hardware.json"); - byte[] evidenceKeys = fixture("evidencekeys.json"); - cloud = HttpServer.create( - new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); - cloud.createContext("/", exchange -> { - try (InputStream body = exchange.getRequestBody()) { - byte[] buffer = new byte[4096]; - while (body.read(buffer) >= 0) { - // Read the whole request before answering. - } - } - String path = exchange.getRequestURI().getPath(); - requests.add(path); - byte[] answer = path.endsWith("accessibleproperties") ? - properties : - path.endsWith("evidencekeys") ? evidenceKeys : null; - if (answer == null) { - exchange.sendResponseHeaders(404, -1); - exchange.close(); - return; - } - exchange.getResponseHeaders().add("Content-Type", - "application/json"); - exchange.sendResponseHeaders(200, answer.length); - try (OutputStream out = exchange.getResponseBody()) { - out.write(answer); - } - }); - cloud.start(); - } - - @After - public void stopCloud() { - cloud.stop(0); - } - - private static byte[] fixture(String name) throws IOException { - try (InputStream input = - HardwareLookupWithoutProfilesTest.class - .getResourceAsStream(name)) { - assertNotNull("The fixture " + name + " should be a resource", - input); - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - byte[] buffer = new byte[4096]; - int read; - while ((read = input.read(buffer)) >= 0) { - bytes.write(buffer, 0, read); - } - return bytes.toByteArray(); - } - } - - private void runWithoutProfiles(Class example) throws Exception { - Map environment = new HashMap<>(); - environment.put(KeyHelper.RESOURCE_KEY_VARIABLE, RESOURCE_KEY); - environment.put(CLOUD_ENDPOINT, "http://" + - cloud.getAddress().getHostString() + ":" + - cloud.getAddress().getPort() + "/api/v4/"); - ExampleProcess.Result result = - ExampleProcess.runWith(example, environment); - System.out.println(result.output); - String output = result.output; - - assertEquals(example.getSimpleName() + - " should end with exit code 0.\n" + output, - 0, result.exitCode); - String message = null; - for (String line : output.split("\r?\n")) { - assertFalse("No lookup should be listed.\n" + output, - line.startsWith("Which devices are associated")); - if (line.startsWith(MESSAGE)) { - message = line; - } - } - assertNotNull("The output should say the key does not include " + - "HardwarePlatform.Profiles.\n" + output, message); - assertTrue("The message should link to where a key is created.\n" + - message, message.contains(CONFIGURE)); - assertTrue("The message should link to the contact page.\n" + - message, message.contains(CONTACT_US)); - assertTrue("The output should end with the '" + FindOutMore.HEADING + - "' section after the message.\n" + output, - output.lastIndexOf(FindOutMore.HEADING) > - output.indexOf(MESSAGE)); - for (String request : requests) { - assertFalse("No lookup request should be made, and " + - request + " was requested.", - request.endsWith("json")); - } - assertTrue("The example should have asked the stand-in for the " + - "accessible properties, and asked for " + requests, - requests.stream().anyMatch( - request -> request.endsWith("accessibleproperties"))); - } - - @Test - public void tacCloud() throws Exception { - runWithoutProfiles(TacCloud.class); - } - - @Test - public void nativeModelCloud() throws Exception { - runWithoutProfiles(NativeModelCloud.class); - } -} diff --git a/examples/device-detection/console/src/test/resources/fiftyone/devicedetection/examples/console/accessibleproperties-with-hardware.json b/examples/device-detection/console/src/test/resources/fiftyone/devicedetection/examples/console/accessibleproperties-with-hardware.json new file mode 100644 index 000000000..f5b6afb1a --- /dev/null +++ b/examples/device-detection/console/src/test/resources/fiftyone/devicedetection/examples/console/accessibleproperties-with-hardware.json @@ -0,0 +1,50 @@ +{ + "Products": { + "device": { + "DataTier": "CloudV5Bespoke", + "Properties": [ + { + "Name": "IsMobile", + "Type": "Boolean", + "Category": "Device", + "DelayExecution": false + } + ] + }, + "hardware": { + "DataTier": "CloudV5Bespoke", + "Properties": [ + { + "Name": "Profiles", + "Type": "Array", + "Category": "", + "ItemProperties": [ + { + "Name": "HardwareVendor", + "Type": "String", + "Category": "Name", + "DelayExecution": false, + "EvidenceProperties": [] + }, + { + "Name": "HardwareModel", + "Type": "String", + "Category": "Name", + "DelayExecution": false, + "EvidenceProperties": [] + }, + { + "Name": "HardwareName", + "Type": "Array", + "Category": "Name", + "DelayExecution": false, + "EvidenceProperties": [] + } + ], + "DelayExecution": false, + "EvidenceProperties": [] + } + ] + } + } +} diff --git a/examples/device-detection/console/src/test/resources/fiftyone/devicedetection/examples/console/json-no-devices.json b/examples/device-detection/console/src/test/resources/fiftyone/devicedetection/examples/console/json-no-devices.json new file mode 100644 index 000000000..a06e0a954 --- /dev/null +++ b/examples/device-detection/console/src/test/resources/fiftyone/devicedetection/examples/console/json-no-devices.json @@ -0,0 +1 @@ +{"hardware":{"profiles":[]}}