diff --git a/README.rst b/README.rst index facb047..28148d6 100644 --- a/README.rst +++ b/README.rst @@ -1,14 +1,14 @@ JSON-RPC-Java =============== -RANDOM.ORG JSON-RPC API (Release 1) implementation. +RANDOM.ORG JSON-RPC API (Release 4) implementation. -This is a Java implementation of the RANDOM.ORG JSON-RPC API (R1). It provides either serialized or unserialized access to both the signed and unsigned methods of the API through the RandomOrgClient class. It also provides a convenience class through the RandomOrgClient class, the RandomOrgCache, for precaching requests. In the context of this module, a serialized client is one for which the sequence of requests matches the sequence of responses. +This is a Java implementation of the RANDOM.ORG JSON-RPC API (R4). It provides either serialized or unserialized access to both the signed and unsigned methods of the API through the RandomOrgClient class. It also provides a convenience class through the RandomOrgClient class, the RandomOrgCache, for precaching requests. In the context of this module, a serialized client is one for which the sequence of requests matches the sequence of responses. Installation ------------ -Requires the `gson `_ lib and `Commons Codec `_ lib for normal operation, and the `junit `_ lib to run tests. +Requires the `gson `_ lib and `Commons Codec `_ lib for normal operation, and the `junit `_ lib and `hamcrest `_ lib to run tests. Usage ----- @@ -83,10 +83,14 @@ This library now also includes a RANDOM.ORG implementation of the `java.util.Ran 6 +Signature Verification +---------------------- +There are two additional methods to generate signature verification URLs and HTML forms (*createURL* and *createHTML*) using the random object and signature returned from any of the signed (value generating) methods. The generated URLs and HTML forms link to the same web page that is also shown when a result is verified using the online `Signature Verification Form `_. + Documentation ------------- -For a full list of available randomness generation functions and other features see RandomOrgClient.java documentation and https://api.random.org/json-rpc/1/ +For a full list of available randomness generation functions and other features see RandomOrgClient.java documentation and https://api.random.org/json-rpc/4 Tests ----- diff --git a/RandomJSONRPC/src/org/random/api/RandomOrgCache.java b/RandomJSONRPC/src/org/random/api/RandomOrgCache.java index 9fd3b4e..d2458de 100644 --- a/RandomJSONRPC/src/org/random/api/RandomOrgCache.java +++ b/RandomJSONRPC/src/org/random/api/RandomOrgCache.java @@ -10,19 +10,20 @@ import com.google.gson.JsonObject; -/** Precache class for frequently used requests. - ** - ** ** WARNING ** - ** Instances of this class should only be obtained using a RandomOrgClient's - ** createCache() methods. - ** - ** This class strives to keep a Queue of response results populated for instant - ** access via its public get() method. Work is done by a background Thread, which - ** issues the appropriate request at suitable intervals. - ** - ** @param return array type, e.g., int[] - ** - **/ +/** + * Precache class for frequently used requests. + * + * ** WARNING ** + * Instances of this class should only be obtained using a RandomOrgClient's + * createCache() methods. + * + * This class strives to keep a Queue of response results populated for instant + * access via its public get() method. Work is done by a background Thread, which + * issues the appropriate request at suitable intervals. + * + * @param return array type, e.g., int[] + * + */ public class RandomOrgCache { private JsonObjectInputCallable requestFunction; @@ -48,19 +49,20 @@ public class RandomOrgCache { private static final Logger LOGGER = Logger.getLogger(RandomOrgClient.class.getPackage().getName()); - /** Initialize class and start Queue population Thread running as a daemon. - ** - ** ** WARNING ** - ** Should only be called by RandomOrgClient's createCache() methods. - ** - ** @param requestFunction function used to send supplied request to server. - ** @param processFunction function to process result of requestFunction into expected output. - ** @param request request to send to server via requestFunction. - ** @param cacheSize number of request responses to try maintain. - ** @param bulkRequestNumber if request is set to be issued in bulk, number of result sets in a bulk request, else 0. - ** @param requestNumber if request is set to be issued in bulk, number of results in a single request, else 0. - ** @param singleRequestSize in bits for adjusting bulk requests if bits are in short supply on the server. - **/ + /** + * Initialize class and start Queue population Thread running as a daemon. + * + * ** WARNING ** + * Should only be called by RandomOrgClient's createCache() methods. + * + * @param requestFunction function used to send supplied request to server. + * @param processFunction function to process result of requestFunction into expected output. + * @param request request to send to server via requestFunction. + * @param cacheSize number of request responses to try maintain. + * @param bulkRequestNumber if request is set to be issued in bulk, number of result sets in a bulk request, else 0. + * @param requestNumber if request is set to be issued in bulk, number of results in a single request, else 0. + * @param singleRequestSize in bits for adjusting bulk requests if bits are in short supply on the server. + */ protected RandomOrgCache(JsonObjectInputCallable requestFunction, JsonObjectInputCallable processFunction, JsonObject request, int cacheSize, int bulkRequestNumber, int requestNumber, int singleRequestSize) { @@ -86,14 +88,15 @@ public void run() { t.start(); } - /** Keep issuing requests to server until Queue is full. When Queue is full if requests - ** are being issued in bulk, wait until Queue has enough space to accommodate all of a - ** bulk request before issuing a new request, otherwise issue a new request every time - ** an item in the Queue has been consumed. - ** - ** Note that requests to the server are blocking, i.e., only one request will be issued by - ** the cache at any given time. - **/ + /** + * Keep issuing requests to server until Queue is full. When Queue is full if requests + * are being issued in bulk, wait until Queue has enough space to accommodate all of a + * bulk request before issuing a new request, otherwise issue a new request every time + * an item in the Queue has been consumed. + * + * Note that requests to the server are blocking, i.e., only one request will be issued by + * the cache at any given time. + */ @SuppressWarnings("unchecked") protected void populateQueue() { while (true) { @@ -219,27 +222,29 @@ public void resume() { } } - /** Return true if cache is currently not re-populating itself. - **

- ** Values currently cached may still be retrieved with get(), - ** but no new values are being fetched from the server. - **

- ** This state can be changed with stop() and resume(). - ** - ** @see #stop() - ** @see #resume() - ** - ** @return true if cache is currently not re-populating itself. - **/ + /** + * Return {@code true} if cache is currently not re-populating itself. + *

+ * Values currently cached may still be retrieved with {@code get()}, + * but no new values are being fetched from the server. + *

+ * This state can be changed with {@code stop()} and {@code resume()}. + * + * @see #stop() + * @see #resume() + * + * @return {@code true} if cache is currently not re-populating itself. + */ public boolean isPaused() { return this.paused; } - /** Get next response. - ** - ** @return next appropriate response for the request this RandomOrgCache represents - ** or if Queue is empty throws a NoSuchElementException. - **/ + /** + * Get next response. + * + * @return next appropriate response for the request this RandomOrgCache represents + * or if Queue is empty throws a NoSuchElementException. + */ public T get() { synchronized (this.lock) { T result = this.queue.remove(); @@ -248,19 +253,20 @@ public T get() { } } - /** Get next response or wait until the next value is available. - **

- ** This method will block until a value is available. - **

- ** Note: if the cache is paused or no more randomness is available from the server this call can result in a dead lock. - ** - ** @see #isPaused() - ** - ** @return next appropriate response for the request this RandomOrgCache represents - ** - ** @throws InterruptedException if any thread interrupted the current thread before or - ** while the current thread was waiting for a notification. The interrupted status of - ** the current thread is cleared when this exception is thrown. + /** + * Get next response or wait until the next value is available. + *

+ * This method will block until a value is available. + *

+ * Note: if the cache is paused or no more randomness is available from the server this call can result in a dead lock. + * + * @see #isPaused() + * + * @return next appropriate response for the request this RandomOrgCache represents + * + * @throws InterruptedException if any thread interrupted the current thread before or + * while the current thread was waiting for a notification. The interrupted status of + * the current thread is cleared when this exception is thrown. */ public T getOrWait() throws InterruptedException { @@ -275,29 +281,32 @@ public T getOrWait() throws InterruptedException { return result; } - /** Get number of results of type {@link #T} remaining in the cache. - **

- ** This essentially returns how often get() may be called without a cache refill, - ** or getOrWait() may be called without blocking. - ** - ** @return current number of cached results - **/ + /** + * Get number of results of type {@link #T} remaining in the cache. + *

+ * This essentially returns how often {@code get()} may be called without a cache refill, + * or {@code getOrWait()} may be called without blocking. + * + * @return current number of cached results + */ public int getCachedValues() { return this.queue.size(); } - /** Get number of bits used by this cache. - ** - ** @return number of used bits - **/ + /** + * Get number of bits used by this cache. + * + * @return number of used bits + */ public long getUsedBits() { return this.usedBits; } - /** Get number of requests used by this cache. - ** - ** @return number of used requests - **/ + /** + * Get number of requests used by this cache. + * + * @return number of used requests + */ public long getUsedRequests() { return this.usedRequests; } diff --git a/RandomJSONRPC/src/org/random/api/RandomOrgClient.java b/RandomJSONRPC/src/org/random/api/RandomOrgClient.java index 7f448a4..faa0c05 100644 --- a/RandomJSONRPC/src/org/random/api/RandomOrgClient.java +++ b/RandomJSONRPC/src/org/random/api/RandomOrgClient.java @@ -6,6 +6,8 @@ import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; +import java.util.Arrays; +import java.util.Base64; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; @@ -14,6 +16,7 @@ import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; +import java.util.regex.Pattern; import javax.net.ssl.HttpsURLConnection; @@ -25,40 +28,41 @@ import org.random.api.exception.RandomOrgRANDOMORGError; import org.random.api.exception.RandomOrgSendTimeoutException; +import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -/** RandomOrgClient main class through which API functions are accessed. - ** - ** This class provides either serialized or unserialized (determined on class creation) - ** access to both the signed and unsigned methods of the RANDOM.ORG API. These are - ** threadsafe and implemented as blocking remote procedure calls. - ** - ** If requests are to be issued serially a background Thread will maintain a Queue of - ** requests to process in sequence. - ** - ** The class also provides access to creation of a convenience class, RandomOrgCache, - ** for precaching API responses when the request is known in advance. - ** - ** This class will only allow the creation of one instance per API key. If an instance - ** of this class already exists for a given key, that instance will be returned instead - ** of a new instance. - ** - ** This class obeys most of the guidelines set forth in https://api.random.org/guidelines - ** All requests respect the server's advisoryDelay returned in any responses, or use - ** DEFAULT_DELAY if no advisoryDelay is returned. If the supplied API key is paused, i.e., - ** has exceeded its daily bit/request allowance, this implementation will back off until - ** midnight UTC. - ** - ** @see https://api.random.org/ - ** @see http://code.google.com/p/google-gson/ - ** @author Anders Haahr - **/ +/** + * RandomOrgClient main class through which API functions are accessed. + * + * This class provides either serialized or unserialized (determined on class creation) access + * to both the signed and unsigned methods of the RANDOM.ORG API. These are threadsafe and + * implemented as blocking remote procedure calls. + * + * If requests are to be issued serially a background Thread will maintain a Queue of requests + * to process in sequence. + * + * The class also provides access to creation of a convenience class, RandomOrgCache, for precaching + * API responses when the request is known in advance. + * + * This class will only allow the creation of one instance per API key. If an instance of this class + * already exists for a given key, that instance will be returned instead of a new instance. + * + * This class obeys most of the guidelines set forth in https://api.random.org/json-rpc/4 + * All requests respect the server's advisoryDelay returned in any responses, or use DEFAULT_DELAY + * if no advisoryDelay is returned. If the supplied API key is paused, i.e., has exceeded its daily + * bit/request allowance, this implementation will back off until midnight UTC. + * + * @see https://api.random.org/ + * @see http://code.google.com/p/google-gson/ + * @author Anders Haahr + */ public class RandomOrgClient { - // Basic RANDOM.ORG API functions https://api.random.org/json-rpc/1/ + // Basic RANDOM.ORG API functions https://api.random.org/json-rpc/4/basic private static final String INTEGER_METHOD = "generateIntegers"; + private static final String INTEGER_SEQUENCE_METHOD = "generateIntegerSequences"; private static final String DECIMAL_FRACTION_METHOD = "generateDecimalFractions"; private static final String GAUSSIAN_METHOD = "generateGaussians"; private static final String STRING_METHOD = "generateStrings"; @@ -66,13 +70,19 @@ public class RandomOrgClient { private static final String BLOB_METHOD = "generateBlobs"; private static final String GET_USAGE_METHOD = "getUsage"; - // Signed RANDOM.ORG API functions https://api.random.org/json-rpc/1/signing + // Signed RANDOM.ORG API functions https://api.random.org/json-rpc/4/signed private static final String SIGNED_INTEGER_METHOD = "generateSignedIntegers"; + private static final String SIGNED_INTEGER_SEQUENCE_METHOD = "generateSignedIntegerSequences"; private static final String SIGNED_DECIMAL_FRACTION_METHOD = "generateSignedDecimalFractions"; private static final String SIGNED_GAUSSIAN_METHOD = "generateSignedGaussians"; private static final String SIGNED_STRING_METHOD = "generateSignedStrings"; private static final String SIGNED_UUID_METHOD = "generateSignedUUIDs"; private static final String SIGNED_BLOB_METHOD = "generateSignedBlobs"; + private static final String GET_RESULT_METHOD = "getResult"; + private static final String CREATE_TICKET_METHOD = "createTickets"; + private static final String REVEAL_TICKETS_METHOD = "revealTickets"; + private static final String LIST_TICKET_METHOD = "listTickets"; + private static final String GET_TICKET_METHOD = "getTicket"; private static final String VERIFY_SIGNATURE_METHOD = "verifySignature"; // Blob format literals @@ -85,15 +95,29 @@ public class RandomOrgClient { // On request fetch fresh allowance state if current state data is older than this value (1 hour) private static final int ALLOWANCE_STATE_REFRESH_SECONDS = 3600*1000; - // default data sizes in bits + // Default data sizes in bits private static final int UUID_SIZE = 122; + // Default values + public static final boolean DEFAULT_REPLACEMENT = true; + public static final int DEFAULT_INT_BASE = 10; + public static final JsonObject DEFAULT_USER_DATA = null; + public static final String DEFAULT_TICKET_ID = null; + public static final JsonObject DEFAULT_PREGENERATED_RANDOMIZATION = null; + public static final JsonObject DEFAULT_LICENSE_DATA = null; + public static final int DEFAULT_CACHE_SIZE = 20; + public static final int DEFAULT_CACHE_SIZE_SMALL = 10; //UUID and BLOB caches + public static final long DEFAULT_BLOCKING_TIMEOUT = 24 * 60 * 60 * 1000; + public static final int DEFAULT_HTTP_TIMEOUT = 120 * 1000; + public static final int MAX_URL_LENGTH = 2046; + // Maintain a dictionary of API keys and their instances. private static HashMap keyIndexedInstances = new HashMap(); private static HashSet randomOrgErrors = new HashSet(); static { - int[] ints = {100, 101, 200, 201, 202, 203, 204, 300, 301, 302, 303, 304, 400, 401, 402, 403, 500, 32000}; + int[] ints = {100, 101, 200, 201, 202, 203, 204, 300, 301, 302, 303, 304, 305, 306, 307, + 400, 401, 402, 403, 404, 405, 420, 421, 422, 423, 424, 425, 426, 500, 32000}; for (int i : ints) { RandomOrgClient.randomOrgErrors.add(i); } @@ -106,12 +130,12 @@ public class RandomOrgClient { private int httpTimeout; private boolean serialized; - // maintain info to obey server advisory delay + // Maintain info to obey server advisory delay private Object advisoryDelayLock = new Object(); private int advisoryDelay = 0; private long lastResponseReceivedTime = 0; - // maintain usage statistics from server + // Maintain usage statistics from server private int requestsLeft = -1; private int bitsLeft = -1; @@ -121,33 +145,45 @@ public class RandomOrgClient { private String backoffError; private LinkedList> serializedQueue; + + // Gson instance for handling certain Json operations + private Gson gson = new Gson(); - /** Ensure only one instance of RandomOrgClient exists per API key. Create a new instance if the - ** supplied key isn't already known, otherwise return the previously instantiated one. - ** New instance will have a blockingTimeout of 24*60*60*1000 milliseconds, i.e., 1 day, a httpTimeout of - ** 120*1000 milliseconds, and will issue serialized requests. - ** - ** @param apiKey of instance to create/find, obtained from RANDOM.ORG, see: https://api.random.org/api-keys - ** - ** @return new instance if instance doesn't already exist for this key, else existing instance. - **/ + /** + * Ensure only one instance of RandomOrgClient exists per API key. Create a new instance + * if the supplied key isn't already known, otherwise return the previously instantiated one. + * + * New instance will have a blockingTimeout of 24*60*60*1000 milliseconds, i.e., 1 day, + * a httpTimeout of 120*1000 milliseconds, and will issue serialized requests. + * + * @param apiKey of instance to create/find, obtained from RANDOM.ORG, see here. + * + * @return new instance if instance doesn't already exist for this key, else existing instance. + */ public static RandomOrgClient getRandomOrgClient(String apiKey) { - return RandomOrgClient.getRandomOrgClient(apiKey, 24*60*60*1000, 120*1000, true); - } - - /** Ensure only one instance of RandomOrgClient exists per API key. Create a new instance if the - ** supplied key isn't already known, otherwise return the previously instantiated one. - ** - ** @param apiKey of instance to create/find, obtained from RANDOM.ORG, see: https://api.random.org/api-keys - ** @param blockingTimeout maximum time in milliseconds to wait before being allowed to send a request. - ** Note this is a hint not a guarantee. Be advised advisory delay from server must always be obeyed. - ** Supply a value of -1 to allow blocking forever. (default 24*60*60*1000, i.e., 1 day). - ** @param httpTimeout maximum time in milliseconds to wait for the server response to a request. (default 120*1000). - ** @param serialized determines whether or not requests from this instance will be added to a Queue and - ** issued serially or sent when received, obeying any advisory delay (default true). - ** - ** @return new instance if instance doesn't already exist for this key, else existing instance. - **/ + return RandomOrgClient.getRandomOrgClient(apiKey, DEFAULT_BLOCKING_TIMEOUT, + DEFAULT_HTTP_TIMEOUT, true); + } + + /** + * Ensure only one instance of RandomOrgClient exists per API key. Create a new instance + * if the supplied key isn't already known, otherwise return the previously instantiated one. + * + * @param apiKey of instance to create/find, obtained from RANDOM.ORG, see here. + * @param blockingTimeout maximum time in milliseconds to wait before being allowed to send + * a request. Note this is a hint not a guarantee. Be advised advisory delay from server + * must always be obeyed. Supply a value of -1 to allow blocking forever + * (default 24*60*60*1000, i.e., 1 day). + * @param httpTimeout maximum time in milliseconds to wait for the server response to a + * request (default 120*1000). + * @param serialized determines whether or not requests from this instance will be added to + * a Queue and issued serially or sent when received, obeying any advisory delay + * (default true). + * + * @return new instance if instance doesn't already exist for this key, else existing instance. + */ public static RandomOrgClient getRandomOrgClient(String apiKey, long blockingTimeout, int httpTimeout, boolean serialized) { RandomOrgClient instance = RandomOrgClient.keyIndexedInstances.get(apiKey); @@ -159,18 +195,23 @@ public static RandomOrgClient getRandomOrgClient(String apiKey, long blockingTim return instance; } - /** Constructor. Initialize class and start serialized request sending Thread running as a daemon if applicable. - ** - ** @param apiKey of instance to create/find, obtained from RANDOM.ORG, see: https://api.random.org/api-keys - ** @param blockingTimeout maximum time in milliseconds to wait before being allowed to send a request. - ** Note this is a hint not a guarantee. Be advised advisory delay from server must always be obeyed. - ** Supply a value of -1 to allow blocking forever. (default 24*60*60*1000, i.e., 1 day). - ** @param httpTimeout maximum time in milliseconds to wait for the server response to a request. (default 120*1000). - ** @param serialized determines whether or not requests from this instance will be added to a Queue and - ** issued serially or sent when received, obeying any advisory delay (default true). - **/ - private RandomOrgClient(String apiKey, long blockingTimeout, int httpTimeout, boolean serialized) { - + /** + * Constructor. Initialize class and start serialized request sending Thread running as + * a daemon if applicable. + * + * @param apiKey of instance to create/find, obtained from RANDOM.ORG, see here. + * @param blockingTimeout maximum time in milliseconds to wait before being allowed to + * send a request. Note this is a hint not a guarantee. Be advised advisory delay + * from server must always be obeyed. Supply a value of -1 to allow blocking forever + * (default 24*60*60*1000, i.e., 1 day). + * @param httpTimeout maximum time in milliseconds to wait for the server response to a + * request. (default 120*1000). + * @param serialized determines whether or not requests from this instance will be added to + * a Queue and issued serially or sent when received, obeying any advisory delay + * (default true). + */ + private RandomOrgClient(String apiKey, long blockingTimeout, int httpTimeout, boolean serialized) { if (serialized) { // set up the serialized request Queue and Thread this.serializedQueue = new LinkedList>(); @@ -190,153 +231,927 @@ public void run() { this.apiKey = apiKey; this.blockingTimeout = blockingTimeout; this.httpTimeout = httpTimeout; + + try { + this.getUsage(); + } catch (Exception e) { + LOGGER.log(Level.INFO, e.getMessage()); + } + } + + // Basic methods for generating randomness, see: https://api.random.org/json-rpc/4/basic + + /** + * Request and return an array of true random integers within a user-defined range from the server. + * + * @param n the number of random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * + * @return int[] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegers + */ + public int[] generateIntegers(int n, int min, int max) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateIntegers(n, min, max, DEFAULT_REPLACEMENT); } - // Basic methods for generating randomness, see: https://api.random.org/json-rpc/1/basic - - /** Request and return an array of true random integers within a user-defined range from the server. - ** See: https://api.random.org/json-rpc/1/basic#generateIntegers - ** - ** @param n how many random integers you need. Must be within the [1,1e4] range. - ** @param min the lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range. - ** @param max the upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range. - ** - ** @return array of random integers. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public int[] generateIntegers(int n, int min, int max) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - return generateIntegers(n, min, max, true); - } - - /** Request and return an array of true random integers within a user-defined range from the server. - ** See: https://api.random.org/json-rpc/1/basic#generateIntegers - ** - ** @param n how many random integers you need. Must be within the [1,1e4] range. - ** @param min the lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range. - ** @param max the upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range. - ** @param replacement specifies whether the random numbers should be picked with replacement. - ** If True the resulting numbers may contain duplicate values, otherwise the numbers will all be unique (default True). - ** - ** @return array of random integers. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public int[] generateIntegers(int n, int min, int max, boolean replacement) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { + /** + * Request and return an array of true random integers within a user-defined range from the server. + * + * @param n the number of random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * + * @return int[] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegers + */ + public int[] generateIntegers(int n, int min, int max, boolean replacement) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateIntegers(n, min, max, replacement, DEFAULT_PREGENERATED_RANDOMIZATION); + } + + /** + * Request and return an array of true random integers within a user-defined range from the server. + * + * @param n the number of random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, 8, 10 + * and 16 (default 10). For base 10, if you would prefer an int[] to be returned instead + * of a String[], please use the {@link #generateIntegers(int n, int min, int max, + * boolean replacement) generateIntegers} method without the base parameter. + * + * @return String[] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegers + */ + public String[] generateIntegers(int n, int min, int max, boolean replacement, int base) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateIntegers(n, min, max, replacement, base, DEFAULT_PREGENERATED_RANDOMIZATION); + } + + /** + * Request and return an array of true random integers within a user-defined range from the server. + * + * @param n the number of random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *

    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * + * @return int[] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegers + */ + public int[] generateIntegers(int n, int min, int max, boolean replacement, JsonObject pregeneratedRandomization) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.extractInts(this.integerMethod(n, min, max, replacement, DEFAULT_INT_BASE, + pregeneratedRandomization, DEFAULT_LICENSE_DATA, DEFAULT_USER_DATA, DEFAULT_TICKET_ID, false)); + } + + /** + * Request and return an array of true random integers within a user-defined range from the server. + * + * @param n the number of random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, 8, 10 + * and 16 (default 10). For base 10, if you would prefer an int[] to be returned instead + * of a String[], please use the {@link #generateIntegers(int n, int min, int max, + * boolean replacement) generateIntegers} method without the base parameter. + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * + * @return String[] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegers + */ + public String[] generateIntegers(int n, int min, int max, boolean replacement, int base, JsonObject pregeneratedRandomization) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.extractStrings(this.integerMethod(n, min, max, replacement, base, + pregeneratedRandomization, DEFAULT_LICENSE_DATA, DEFAULT_USER_DATA, + DEFAULT_TICKET_ID, false)); + } + + /** + * Request and return uniform sequences of true random integers within user-defined ranges + * from the server. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length the length of each array of random integers requested. Must be within the + * [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * + * @return int[][] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegerSequences + */ + public int[][] generateIntegerSequences(int n, int length, int min, int max) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateIntegerSequences(n, length, min, max, DEFAULT_REPLACEMENT); + } + + /** + * Request and return uniform sequences of true random integers within user-defined ranges + * from the server. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length the length of each array of random integers requested. Must be within the + * [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * + * @return int[][] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegerSequences + */ + public int[][] generateIntegerSequences(int n, int length, int min, int max, boolean replacement) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateIntegerSequences(n, length, min, max, replacement, + DEFAULT_PREGENERATED_RANDOMIZATION); + } + + /** + * Request and return uniform sequences of true random integers within user-defined ranges + * from the server. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length the length of each array of random integers requested. Must be within the + * [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, 8, 10 + * and 16 (default 10). For base 10, if you would prefer an int[][] to be returned + * instead of a String[][] please use the {@link #generateIntegerSequences(int n, int length, + * int min, int max, boolean replacement) generateIntegerSequences} method without + * the base parameter. + * + * @return String[][] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegerSequences + */ + public String[][] generateIntegerSequences(int n, int length, int min, int max, boolean replacement, int base) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateIntegerSequences(n, length, min, max, replacement, base, + DEFAULT_PREGENERATED_RANDOMIZATION); + } + + /** + * Request and return uniform sequences of true random integers within user-defined ranges + * from the server. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length the length of each array of random integers requested. Must be within the + * [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * + * @return int[][] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegerSequences + */ + public int[][] generateIntegerSequences(int n, int length, int min, int max, boolean replacement, JsonObject pregeneratedRandomization) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.extractIntSequences(this.integerSequencesMethod(n, length, min, max, replacement, + DEFAULT_INT_BASE, pregeneratedRandomization, DEFAULT_LICENSE_DATA, DEFAULT_USER_DATA, + DEFAULT_TICKET_ID, false)); + } + + /** + * Request and return uniform sequences of true random integers within user-defined ranges + * from the server. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length the length of each array of random integers requested. Must be within the + * [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, 8, 10 + * and 16 (default 10). For base 10, if you would prefer an int[][] to be returned + * instead of a String[][] please use the {@link #generateIntegerSequences(int n, int length, + * int min, int max, boolean replacement) generateIntegerSequences} method without + * the base parameter. + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * + * @return String[][] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegerSequences + */ + public String[][] generateIntegerSequences(int n, int length, int min, int max, boolean replacement, int base, JsonObject pregeneratedRandomization) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.extractIntSequencesString(this.integerSequencesMethod(n, length, + min, max, replacement, base, pregeneratedRandomization, DEFAULT_LICENSE_DATA, + DEFAULT_USER_DATA, DEFAULT_TICKET_ID, false)); + } + + /** + * Request and return uniform or multiform sequences of true random integers within user-defined + * ranges from the server. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length an array with n integers each specifying the length of the sequence + * identified by its index. Each value in the array must be within the [1,1e4] range. + * @param min an array with n integers, each specifying the lower boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param max an array with n integers, each specifying the upper boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * + * @return int[][] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegerSequences + */ + public int[][] generateIntegerSequences(int n, int[] length, int[] min, int[] max) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + boolean[] replacement = new boolean[n]; + Arrays.fill(replacement, DEFAULT_REPLACEMENT); + + return this.generateIntegerSequences(n, length, min, max, replacement); + } + + /** + * Request and return uniform or multiform sequences of true random integers within user-defined + * ranges from the server. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length an array with n integers each specifying the length of the sequence + * identified by its index. Each value in the array must be within the [1,1e4] range. + * @param min an array with n integers, each specifying the lower boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param max an array with n integers, each specifying the upper boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param replacement an array with n Boolean values, each specifying whether the sequence + * identified by its index will be created with or without replacement. If true, the + * resulting numbers may contain duplicate values, otherwise the numbers will all be + * unique within each sequence (default true). + * + * @return int[][] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegerSequences + */ + public int[][] generateIntegerSequences(int n, int[] length, int[] min, int[] max, boolean[] replacement) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateIntegerSequences(n, length, min, max, replacement, + DEFAULT_PREGENERATED_RANDOMIZATION); + } + + /** + * Request and return uniform or multiform sequences of true random integers within user-defined + * ranges from the server. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length an array with n integers each specifying the length of the sequence + * identified by its index. Each value in the array must be within the [1,1e4] range. + * @param min an array with n integers, each specifying the lower boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param max an array with n integers, each specifying the upper boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param replacement an array with n Boolean values, each specifying whether the sequence + * identified by its index will be created with or without replacement. If true, the + * resulting numbers may contain duplicate values, otherwise the numbers will all be + * unique within each sequence (default true). + * @param base an array with n integer values, each specifying the base that will be used to + * display the sequence identified by its index. Values allowed are 2, 8, 10 and 16 + * (default 10). For base 10, if you require an int[][] instead of a String[][], please + * use the {@link #generateIntegerSequences(int n, int[] length, int[] min, int[] max, + * boolean[] replacement) generateIntegerSequences} method without the base parameter. + * + * @return String[][] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegerSequences + */ + public String[][] generateIntegerSequences(int n, int[] length, int[] min, int[] max, boolean[] replacement, int[] base) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateIntegerSequences(n, length, min, max, + replacement, base, DEFAULT_PREGENERATED_RANDOMIZATION); + } + + /** + * Request and return uniform or multiform sequences of true random integers within user-defined + * ranges from the server. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length an array with n integers each specifying the length of the sequence + * identified by its index. Each value in the array must be within the [1,1e4] range. + * @param min an array with n integers, each specifying the lower boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param max an array with n integers, each specifying the upper boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param replacement an array with n Boolean values, each specifying whether the sequence + * identified by its index will be created with or without replacement. If true, the + * resulting numbers may contain duplicate values, otherwise the numbers will all be + * unique within each sequence (default true). + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * + * @return int[][] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegerSequences + */ + public int[][] generateIntegerSequences(int n, int[] length, int[] min, int[] max, boolean[] replacement, JsonObject pregeneratedRandomization) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + int[] base = new int[n]; + Arrays.fill(base, DEFAULT_INT_BASE); + + return this.extractIntSequences(this.integerSequencesMethod(n, length, min, max, replacement, + base, pregeneratedRandomization, DEFAULT_LICENSE_DATA, DEFAULT_USER_DATA, + DEFAULT_TICKET_ID, false)); + } - JsonObject request = new JsonObject(); + /** + * Request and return uniform or multiform sequences of true random integers within user-defined + * ranges from the server. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length an array with n integers each specifying the length of the sequence + * identified by its index. Each value in the array must be within the [1,1e4] range. + * @param min an array with n integers, each specifying the lower boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param max an array with n integers, each specifying the upper boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param replacement an array with n Boolean values, each specifying whether the sequence + * identified by its index will be created with or without replacement. If true, the + * resulting numbers may contain duplicate values, otherwise the numbers will all be + * unique within each sequence (default true). + * @param base an array with n integer values, each specifying the base that will be used to + * display the sequence identified by its index. Values allowed are 2, 8, 10 and 16 + * (default 10). For base 10, if you require an int[][] instead of a String[][], please + * use the {@link #generateIntegerSequences(int n, int[] length, int[] min, int[] max, + * boolean[] replacement) generateIntegerSequences} method without the base parameter. + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * + * @return String[][] of true random integers. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateIntegerSequences + */ + public String[][] generateIntegerSequences(int n, int[] length, int[] min, int[] max, boolean[] replacement, int[] base, JsonObject pregeneratedRandomization) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.extractIntSequencesString(this.integerSequencesMethod(n, length, min, max, + replacement, base, pregeneratedRandomization, DEFAULT_LICENSE_DATA, DEFAULT_USER_DATA, + DEFAULT_TICKET_ID, false)); + } + + /** + * Request and return a list (size n) of true random decimal fractions, from a uniform + * distribution across the [0,1] interval with a user-defined number of decimal places + * from the server. + * + * @param n how many random decimal fractions you need. Must be within the [1,1e4] range. + * @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. + * + * @return double[] of true random decimal fractions. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateDecimalFractions + */ + public double[] generateDecimalFractions(int n, int decimalPlaces) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateDecimalFractions(n, decimalPlaces, DEFAULT_REPLACEMENT); + } - request.addProperty("n", n); - request.addProperty("min", min); - request.addProperty("max", max); - request.addProperty("replacement", replacement); - - request = this.generateKeyedRequest(request, INTEGER_METHOD); - - JsonObject response = this.sendRequest(request); - - return this.extractInts(response); - } - - /** Request and return a list (size n) of true random decimal fractions, from a uniform distribution across - ** the [0,1] interval with a user-defined number of decimal places from the server. - ** See: https://api.random.org/json-rpc/1/basic#generateDecimalFractions - ** - ** @param n how many random decimal fractions you need. Must be within the [1,1e4] range. - ** @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. - ** - ** @return array of random doubles. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public double[] generateDecimalFractions(int n, int decimalPlaces) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - return this.generateDecimalFractions(n, decimalPlaces, true); - } - - /** Request and return a list (size n) of true random decimal fractions, from a uniform distribution across - ** the [0,1] interval with a user-defined number of decimal places from the server. - ** See: https://api.random.org/json-rpc/1/basic#generateDecimalFractions - ** - ** @param n how many random decimal fractions you need. Must be within the [1,1e4] range. - ** @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. - ** @param replacement specifies whether the random numbers should be picked with replacement. - ** If True the resulting numbers may contain duplicate values, otherwise the numbers will all be unique (default True). - ** - ** @return array of random doubles. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public double[] generateDecimalFractions(int n, int decimalPlaces, boolean replacement) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - + /** + * Request and return a list (size n) of true random decimal fractions, from a uniform + * distribution across the [0,1] interval with a user-defined number of decimal places + * from the server. + * + * @param n how many random decimal fractions you need. Must be within the [1,1e4] range. + * @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * + * @return double[] of true random decimal fractions. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateDecimalFractions + */ + public double[] generateDecimalFractions(int n, int decimalPlaces, boolean replacement) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateDecimalFractions(n, decimalPlaces, replacement, DEFAULT_PREGENERATED_RANDOMIZATION); + } + + /** + * Request and return a list (size n) of true random decimal fractions, from a uniform + * distribution across the [0,1] interval with a user-defined number of decimal places + * from the server. + * + * @param n how many random decimal fractions you need. Must be within the [1,1e4] range. + * @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * + * @return double[] of true random decimal fractions. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateDecimalFractions + */ + public double[] generateDecimalFractions(int n, int decimalPlaces, boolean replacement, JsonObject pregeneratedRandomization) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { JsonObject request = new JsonObject(); request.addProperty("n", n); request.addProperty("decimalPlaces", decimalPlaces); request.addProperty("replacement", replacement); + request.add("pregeneratedRandomization", pregeneratedRandomization); request = this.generateKeyedRequest(request, DECIMAL_FRACTION_METHOD); @@ -345,43 +1160,107 @@ public double[] generateDecimalFractions(int n, int decimalPlaces, boolean repla return this.extractDoubles(response); } - /** Request and return a list (size n) of true random numbers from a Gaussian distribution (also known as a - ** normal distribution). The form uses a Box-Muller Transform to generate the Gaussian distribution from - ** uniformly distributed numbers. See: https://api.random.org/json-rpc/1/basic#generateGaussians - ** - ** @param n how many random numbers you need. Must be within the [1,1e4] range. - ** @param mean the distribution's mean. Must be within the [-1e6,1e6] range. - ** @param standardDeviation the distribution's standard deviation. Must be within the [-1e6,1e6] range. - ** @param significantDigits the number of significant digits to use. Must be within the [2,20] range. - ** - ** @return array of true random doubles from a Gaussian distribution. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public double[] generateGaussians(int n, double mean, double standardDeviation, int significantDigits) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - + /** + * Request and return a list (size n) of true random numbers from a Gaussian distribution + * (also known as a normal distribution). The form uses a Box-Muller Transform to generate + * the Gaussian distribution from uniformly distributed numbers. + * + * @param n how many random numbers you need. Must be within the [1,1e4] range. + * @param mean the distribution's mean. Must be within the [-1e6,1e6] range. + * @param standardDeviation the distribution's standard deviation. Must be within the + * [-1e6,1e6] range. + * @param significantDigits the number of significant digits to use. Must be within the + * [2,20] range. + * + * @return double[] of true random doubles from a Gaussian distribution. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateDecimalGaussians + */ + public double[] generateGaussians(int n, double mean, double standardDeviation, int significantDigits) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateGaussians(n, mean, standardDeviation, significantDigits, + DEFAULT_PREGENERATED_RANDOMIZATION); + } + + /** + * Request and return a list (size n) of true random numbers from a Gaussian distribution + * (also known as a normal distribution). The form uses a Box-Muller Transform to generate + * the Gaussian distribution from uniformly distributed numbers. + * + * @param n how many random numbers you need. Must be within the [1,1e4] range. + * @param mean the distribution's mean. Must be within the [-1e6,1e6] range. + * @param standardDeviation the distribution's standard deviation. Must be within the + * [-1e6,1e6] range. + * @param significantDigits the number of significant digits to use. Must be within the + * [2,20] range. + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * + * @return double[] of true random doubles from a Gaussian distribution. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateDecimalGaussians + */ + public double[] generateGaussians(int n, double mean, double standardDeviation, int significantDigits, JsonObject pregeneratedRandomization) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { JsonObject request = new JsonObject(); request.addProperty("n", n); request.addProperty("mean", mean); request.addProperty("standardDeviation", standardDeviation); request.addProperty("significantDigits", significantDigits); + request.add("pregeneratedRandomization", pregeneratedRandomization); request = this.generateKeyedRequest(request, GAUSSIAN_METHOD); @@ -390,76 +1269,145 @@ public double[] generateGaussians(int n, double mean, double standardDeviation, return this.extractDoubles(response); } - /** Request and return a list (size n) of true random unicode strings from the server. - ** See: https://api.random.org/json-rpc/1/basic#generateStrings - ** - ** @param n how many random strings you need. Must be within the [1,1e4] range. - ** @param length the length of each string. Must be within the [1,20] range. All strings will be of the same length. - ** @param characters a string that contains the set of characters that are allowed to occur in the random strings. - ** The maximum number of characters is 80. - ** - ** @return array of random Strings. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public String[] generateStrings(int n, int length, String characters) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - return this.generateStrings(n, length, characters, true); - } - - /** Request and return a list (size n) of true random unicode strings from the server. - ** See: https://api.random.org/json-rpc/1/basic#generateStrings - ** - ** @param n how many random strings you need. Must be within the [1,1e4] range. - ** @param length the length of each string. Must be within the [1,20] range. All strings will be of the same length. - ** @param characters a string that contains the set of characters that are allowed to occur in the random strings. - ** The maximum number of characters is 80. - ** @param replacement specifies whether the random strings should be picked with replacement. If True the resulting - ** list of strings may contain duplicates, otherwise the strings will all be unique (default True). - ** - ** @return array of random Strings. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public String[] generateStrings(int n, int length, String characters, boolean replacement) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - + /** + * Request and return a list (size n) of true random unicode strings from the server. + * + * @param n how many random strings you need. Must be within the [1,1e4] range. + * @param length the length of each string. Must be within the [1,20] range. All strings + * will be of the same length. + * @param characters a string that contains the set of characters that are allowed to occur + * in the random strings. The maximum number of characters is 80. + * + * @return String[] of true random Strings. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateStrings + */ + public String[] generateStrings(int n, int length, String characters) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateStrings(n, length, characters, DEFAULT_REPLACEMENT); + } + + /** + * Request and return a list (size n) of true random unicode strings from the server. + * + * @param n how many random strings you need. Must be within the [1,1e4] range. + * @param length the length of each string. Must be within the [1,20] range. All strings + * will be of the same length. + * @param characters a string that contains the set of characters that are allowed to occur + * in the random strings. The maximum number of characters is 80. + * @param replacement specifies whether the random strings should be picked with replacement. + * If true, the resulting list of strings may contain duplicates, otherwise the strings + * will all be unique (default true). + * + * @return String[] of true random Strings. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateStrings + */ + public String[] generateStrings(int n, int length, String characters, boolean replacement) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateStrings(n, length, characters, replacement, DEFAULT_PREGENERATED_RANDOMIZATION); + } + + /** + * Request and return a list (size n) of true random unicode strings from the server. + * + * @param n how many random strings you need. Must be within the [1,1e4] range. + * @param length the length of each string. Must be within the [1,20] range. All strings + * will be of the same length. + * @param characters a string that contains the set of characters that are allowed to occur + * in the random strings. The maximum number of characters is 80. + * @param replacement specifies whether the random strings should be picked with replacement. + * If true, the resulting list of strings may contain duplicates, otherwise the strings + * will all be unique (default true). + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * + * @return String[] of true random Strings. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateStrings + */ + public String[] generateStrings(int n, int length, String characters, boolean replacement, JsonObject pregeneratedRandomization) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { JsonObject request = new JsonObject(); request.addProperty("n", n); request.addProperty("length", length); request.addProperty("characters", characters); request.addProperty("replacement", replacement); + request.add("pregeneratedRandomization", pregeneratedRandomization); request = this.generateKeyedRequest(request, STRING_METHOD); @@ -468,36 +1416,91 @@ public String[] generateStrings(int n, int length, String characters, boolean re return this.extractStrings(response); } - /** Request and return a list (size n) of version 4 true random Universally Unique IDentifiers (UUIDs) in accordance - ** with section 4.4 of RFC 4122, from the server. See: https://api.random.org/json-rpc/1/basic#generateUUIDs - ** - ** @param n how many random UUIDs you need. Must be within the [1,1e3] range. - ** - ** @return array of random UUIDs. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public UUID[] generateUUIDs(int n) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - + /** + * Request and return a list (size n) of version 4 true random Universally Unique IDentifiers + * (UUIDs) in accordance with section 4.4 of RFC 4122, from the server. + * + * @param n how many random UUIDs you need. Must be within the [1,1e3] range. + * + * @return UUID[] of true random UUIDs. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateUUIDs + */ + public UUID[] generateUUIDs(int n) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateUUIDs(n, DEFAULT_PREGENERATED_RANDOMIZATION); + } + + /** + * Request and return a list (size n) of version 4 true random Universally Unique IDentifiers + * (UUIDs) in accordance with section 4.4 of RFC 4122, from the server. + * + * @param n how many random UUIDs you need. Must be within the [1,1e3] range. + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * + * @return UUID[] of true random UUIDs. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateUUIDs + */ + public UUID[] generateUUIDs(int n, JsonObject pregeneratedRandomization) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { JsonObject request = new JsonObject(); request.addProperty("n", n); + request.add("pregeneratedRandomization", pregeneratedRandomization); request = this.generateKeyedRequest(request, UUID_METHOD); @@ -506,72 +1509,139 @@ public UUID[] generateUUIDs(int n) throws RandomOrgSendTimeoutException, return this.extractUUIDs(response); } - /** Request and return a list (size n) of Binary Large OBjects (BLOBs) as unicode strings - ** containing true random data from the server. See: https://api.random.org/json-rpc/1/basic#generateBlobs - ** - ** @param n how many random blobs you need. Must be within the [1,100] range. - ** @param size the size of each blob, measured in bits. Must be within the [1,1048576] range and must be divisible by 8. - ** - ** @return array of random blobs as Strings. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public String[] generateBlobs(int n, int size) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - - return this.generateBlobs(n, size, RandomOrgClient.BLOB_FORMAT_BASE64); - } - - /** Request and return a list (size n) of Binary Large OBjects (BLOBs) as unicode strings - ** containing true random data from the server. See: https://api.random.org/json-rpc/1/basic#generateBlobs - ** - ** @param n how many random blobs you need. Must be within the [1,100] range. - ** @param size the size of each blob, measured in bits. Must be within the [1,1048576] range and must be divisible by 8. - ** @param format specifies the format in which the blobs will be returned. Values allowed are - ** BLOB_FORMAT_BASE64 and BLOB_FORMAT_HEX (default BLOB_FORMAT_BASE64). - ** - ** @return array of random blobs as Strings. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public String[] generateBlobs(int n, int size, String format) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - + /** + * Request and return a list (size n) of Binary Large OBjects (BLOBs) as unicode strings + * containing true random data from the server. + * + * @param n how many random blobs you need. Must be within the [1,100] range. + * @param size the size of each blob, measured in bits. Must be within the [1,1048576] range + * and must be divisible by 8. + * + * @return String[] of true random blobs as Strings. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateBlobs + */ + public String[] generateBlobs(int n, int size) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateBlobs(n, size, BLOB_FORMAT_BASE64); + } + + /** + * Request and return a list (size n) of Binary Large OBjects (BLOBs) as unicode strings + * containing true random data from the server. + * + * @param n how many random blobs you need. Must be within the [1,100] range. + * @param size the size of each blob, measured in bits. Must be within the [1,1048576] range + * and must be divisible by 8. + * @param format specifies the format in which the blobs will be returned. Values allowed + * are BLOB_FORMAT_BASE64 and BLOB_FORMAT_HEX (default BLOB_FORMAT_BASE64). + * + * @return String[] of true random blobs as Strings. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateBlobs + */ + public String[] generateBlobs(int n, int size, String format) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateBlobs(n, size, format, DEFAULT_PREGENERATED_RANDOMIZATION); + } + + /** + * Request and return a list (size n) of Binary Large OBjects (BLOBs) as unicode strings + * containing true random data from the server. + * + * @param n how many random blobs you need. Must be within the [1,100] range. + * @param size the size of each blob, measured in bits. Must be within the [1,1048576] range + * and must be divisible by 8. + * @param format specifies the format in which the blobs will be returned. Values allowed + * are BLOB_FORMAT_BASE64 and BLOB_FORMAT_HEX (default BLOB_FORMAT_BASE64). + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * + * @return String[] of true random blobs as Strings. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/basic#generateBlobs + */ + public String[] generateBlobs(int n, int size, String format, JsonObject pregeneratedRandomization) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { JsonObject request = new JsonObject(); request.addProperty("n", n); request.addProperty("size", size); request.addProperty("format", format); + request.add("pregeneratedRandomization", pregeneratedRandomization); request = this.generateKeyedRequest(request, BLOB_METHOD); @@ -580,159 +1650,1061 @@ public String[] generateBlobs(int n, int size, String format) throws RandomOrgSe return this.extractStrings(response); } - // Signed methods for generating randomness, see: https://api.random.org/json-rpc/1/signing - - /** Request a list (size n) of true random integers within a user-defined range from the server. Returns a - ** dictionary object with the parsed integer list mapped to 'data', the original response mapped to 'random', - ** and the response's signature mapped to 'signature'. See: https://api.random.org/json-rpc/1/signing#generateSignedIntegers - ** - ** @param n how many random integers you need. Must be within the [1,1e4] range. - ** @param min the lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range. - ** @param max the upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range. - ** - ** @return HashMap with "random": random JsonObject, "signature": signature String, "data": random int[] - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public HashMap generateSignedIntegers(int n, int min, int max) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - return generateSignedIntegers(n, min, max, true); - } - - /** Request a list (size n) of true random integers within a user-defined range from the server. Returns a - ** dictionary object with the parsed integer list mapped to 'data', the original response mapped to 'random', - ** and the response's signature mapped to 'signature'. See: https://api.random.org/json-rpc/1/signing#generateSignedIntegers - ** - ** @param n how many random integers you need. Must be within the [1,1e4] range. - ** @param min the lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range. - ** @param max the upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range. - ** @param replacement specifies whether the random numbers should be picked with replacement. - ** If True the resulting numbers may contain duplicate values, otherwise the numbers will all be unique (default True). - ** - ** @return HashMap with "random": random JsonObject, "signature": signature String, "data": random int[] - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public HashMap generateSignedIntegers(int n, int min, int max, boolean replacement) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - - JsonObject request = new JsonObject(); - - request.addProperty("n", n); - request.addProperty("min", min); - request.addProperty("max", max); - request.addProperty("replacement", replacement); + // Signed methods for generating randomness, see: https://api.random.org/json-rpc/4/signed + + /** + * Request a list (size n) of true random integers within a user-defined range from the server. + * Returns a dictionary object with the parsed integer list mapped to 'data', the original + * response mapped to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegers + */ + public HashMap generateSignedIntegers(int n, int min, int max) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedIntegers(n, min, max, DEFAULT_REPLACEMENT); + } + + /** + * Request a list (size n) of true random integers within a user-defined range from the server. + * Returns a dictionary object with the parsed integer list mapped to 'data', the original + * response mapped to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegers + */ + public HashMap generateSignedIntegers(int n, int min, int max, boolean replacement) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedIntegers(n, min, max, replacement, DEFAULT_INT_BASE, DEFAULT_USER_DATA); + } + + /** + * Request a list (size n) of true random integers within a user-defined range from the server. + * Returns a dictionary object with the parsed integer list mapped to 'data', the original + * response mapped to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, + * 8, 10 and 16 (default 10). + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[] if decimal (base 10) + * or random String[] if non-decimal (any other base value) + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegers + */ + public HashMap generateSignedIntegers(int n, int min, int max, boolean replacement, int base, JsonObject userData) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedIntegers(n, min, max, replacement, base, userData, DEFAULT_TICKET_ID); + } + + /** + * Request a list (size n) of true random integers within a user-defined range from the server. + * Returns a dictionary object with the parsed integer list mapped to 'data', the original + * response mapped to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, + * 8, 10 and 16 (default 10). + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[] if decimal (base 10) + * or random String[] if non-decimal (any other base value) + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegers + */ + public HashMap generateSignedIntegers(int n, int min, int max, boolean replacement, int base, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedIntegers(n, min, max, replacement, base, DEFAULT_PREGENERATED_RANDOMIZATION, + DEFAULT_LICENSE_DATA, userData, ticketId); + } + + /** + * Request a list (size n) of true random integers within a user-defined range from the server. + * Returns a dictionary object with the parsed integer list mapped to 'data', the original + * response mapped to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, + * 8, 10 and 16 (default 10). + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * @param licenseData A JsonObject which allows the caller to include data of relevance to the + * license that is associated with the API Key. This is mandatory for API Keys with the + * license type "Flexible Gambling" and follows the format { "maxPayout": { "currency": + * "XTS", "amount": 0.0 } }. This information is used in licensing requested random values + * and in billing. The currently supported currencies are: "USD", "EUR", "GBP", "BTC", "ETH". + * Please check the official documentation for the most up-to-date information on this parameter: + * https://api.random.org/json-rpc/4/signed + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[] if decimal (base 10) + * or random String[] if non-decimal (any other base value) + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegers + */ + public HashMap generateSignedIntegers(int n, int min, int max, boolean replacement, int base, JsonObject pregeneratedRandomization, JsonObject licenseData, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + JsonObject response = this.integerMethod(n, min, max, replacement, base, pregeneratedRandomization, + licenseData, userData, ticketId, true); - request = this.generateKeyedRequest(request, SIGNED_INTEGER_METHOD); + HashMap result = new HashMap(); + if (base == 10) { + result.put("data", this.extractInts(response)); + } else { + result.put("data", this.extractStrings(response)); + } + return this.extractSignedResponse(response, result); + } + + /** + * Request and return uniform sequences of true random integers within user-defined + * ranges from the server. Returns a dictionary object with the parsed 2D integer array + * mapped to 'data', the original response mapped to 'random', and the response's + * signature mapped to 'signature'. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length the length of each array of random integers requested. Must be within the + * [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[][] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegerSequences + */ + public HashMap generateSignedIntegerSequences(int n, int length, int min, int max) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedIntegerSequences(n, length, min, max, DEFAULT_REPLACEMENT, + DEFAULT_INT_BASE, DEFAULT_USER_DATA); + } + + /** + * Request and return uniform sequences of true random integers within user-defined + * ranges from the server. Returns a dictionary object with the parsed 2D integer array + * mapped to 'data', the original response mapped to 'random', and the response's + * signature mapped to 'signature'. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length the length of each array of random integers requested. Must be within the + * [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, 8, + * 10 and 16 (default 10). + * @param userData JsonObject that will be included in unmodified form. Its maximum size in + * encoded (String) form is 1,000 characters (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[][] if decimal (base 10) + * or random String[][] if non-decimal (any other base value) + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegerSequences + */ + public HashMap generateSignedIntegerSequences(int n, int length, int min, int max, boolean replacement, int base, JsonObject userData) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedIntegerSequences(n, length, min, max, replacement, base, + userData, DEFAULT_TICKET_ID); + } + + /** + * Request and return uniform sequences of true random integers within user-defined + * ranges from the server. Returns a dictionary object with the parsed 2D integer array + * mapped to 'data', the original response mapped to 'random', and the response's + * signature mapped to 'signature'. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length the length of each array of random integers requested. Must be within the + * [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, 8, + * 10 and 16 (default 10). + * @param userData JsonObject that will be included in unmodified form. Its maximum size in + * encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[][] if decimal (base 10) + * or random String[][] if non-decimal (any other base value) + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegerSequences + */ + public HashMap generateSignedIntegerSequences(int n, int length, int min, int max, boolean replacement, int base, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedIntegerSequences(n, length, min, max, replacement, base, + DEFAULT_PREGENERATED_RANDOMIZATION, DEFAULT_LICENSE_DATA, userData, ticketId); + } + + /** + * Request and return uniform sequences of true random integers within user-defined + * ranges from the server. Returns a dictionary object with the parsed 2D integer array + * mapped to 'data', the original response mapped to 'random', and the response's + * signature mapped to 'signature'. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length the length of each array of random integers requested. Must be within the + * [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, 8, + * 10 and 16 (default 10). + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * @param licenseData A JsonObject which allows the caller to include data of relevance to the + * license that is associated with the API Key. This is mandatory for API Keys with the + * license type "Flexible Gambling" and follows the format { "maxPayout": { "currency": + * "XTS", "amount": 0.0 } }. This information is used in licensing requested random values + * and in billing. The currently supported currencies are: "USD", "EUR", "GBP", "BTC", "ETH". + * Please check the official documentation for the most up-to-date information on this parameter: + * https://api.random.org/json-rpc/4/signed + * @param userData JsonObject that will be included in unmodified form. Its maximum size in + * encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[][] if decimal (base 10) + * or random String[][] if non-decimal (any other base value) + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegerSequences + */ + public HashMap generateSignedIntegerSequences(int n, int length, int min, int max, boolean replacement, int base, JsonObject pregeneratedRandomization, JsonObject licenseData, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + JsonObject response = this.integerSequencesMethod(n, length, min, max, + replacement, base, pregeneratedRandomization, licenseData, userData, ticketId, true); - JsonObject response = this.sendRequest(request); + HashMap result = new HashMap(); + if (base == 10) { + result.put("data", this.extractIntSequences(response)); + } else { + result.put("data", this.extractIntSequencesString(response)); + } + + return this.extractSignedResponse(response, result); + } + + /** + * Request and return uniform or multiform sequences of true random integers within + * user-defined ranges from the server. Returns a dictionary object with the parsed + * 2D integer array mapped to 'data', the original response mapped to 'random', and + * the response's signature mapped to 'signature'. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length the length of each array of random integers requested. Must be within the + * [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[][] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegerSequences + */ + public HashMap generateSignedIntegerSequences(int n, int[] length, int[] min, int[] max) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + boolean[] replacement = new boolean[n]; + Arrays.fill(replacement, DEFAULT_REPLACEMENT); + int[] base = new int[n]; + Arrays.fill(base, DEFAULT_INT_BASE); + + return this.generateSignedIntegerSequences(n, length, min, max, replacement, + base, DEFAULT_USER_DATA); + } + + /** + * Request and return uniform or multiform sequences of true random integers within + * user-defined ranges from the server. Returns a dictionary object with the parsed + * 2D integer array mapped to 'data', the original response mapped to 'random', and + * the response's signature mapped to 'signature'. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length an array with n integers each specifying the length of the + * sequence identified by its index. Each value in the array must + * be within the [1,1e4] range. + * @param min an array with n integers, each specifying the lower boundary of + * the sequence identified by its index. Each value in the array must + * be within the [-1e9,1e9] range. + * @param max an array with n integers, each specifying the upper boundary of + * the sequence identified by its index. Each value in the array must + * be within the [-1e9,1e9] range. + * @param replacement an array with n Boolean values, each specifying whether + * the sequence identified by its index will be created with or without + * replacement. If true, the resulting numbers may contain + * duplicate values, otherwise the numbers will all be unique within + * each sequence (default true). + * @param base an array with n integer values, each specifying the base + * that will be used to display the sequence identified by its index. + * Values allowed are 2, 8, 10 and 16 (default 10). + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[][] if decimal (all base values are 10) + * or random String[][] if non-decimal (any other mix of base values) + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegerSequences + */ + public HashMap generateSignedIntegerSequences(int n, int[] length, int[] min, int[] max, boolean[] replacement, int[] base, JsonObject userData) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedIntegerSequences(n, length, min, max, replacement, base, userData, + DEFAULT_TICKET_ID); + } + + /** + * Request and return uniform or multiform sequences of true random integers within + * user-defined ranges from the server. Returns a dictionary object with the parsed + * 2D integer array mapped to 'data', the original response mapped to 'random', and + * the response's signature mapped to 'signature'. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length an array with n integers each specifying the length of the + * sequence identified by its index. Each value in the array must + * be within the [1,1e4] range. + * @param min an array with n integers, each specifying the lower boundary of + * the sequence identified by its index. Each value in the array must + * be within the [-1e9,1e9] range. + * @param max an array with n integers, each specifying the upper boundary of + * the sequence identified by its index. Each value in the array must + * be within the [-1e9,1e9] range. + * @param replacement an array with n Boolean values, each specifying whether + * the sequence identified by its index will be created with or without + * replacement. If true, the resulting numbers may contain + * duplicate values, otherwise the numbers will all be unique within + * each sequence (default true). + * @param base an array with n integer values, each specifying the base + * that will be used to display the sequence identified by its index. + * Values allowed are 2, 8, 10 and 16 (default 10). + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[][] if decimal (all base values are 10) + * or random String[][] if non-decimal (any other mix of base values) + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegerSequences + */ + public HashMap generateSignedIntegerSequences(int n, int[] length, int[] min, int[] max, boolean[] replacement, int[] base, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedIntegerSequences(n, length, min, max, replacement, base, + DEFAULT_PREGENERATED_RANDOMIZATION, DEFAULT_LICENSE_DATA, userData, ticketId); + } + + /** + * Request and return uniform or multiform sequences of true random integers within + * user-defined ranges from the server. Returns a dictionary object with the parsed + * 2D integer array mapped to 'data', the original response mapped to 'random', and + * the response's signature mapped to 'signature'. + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length an array with n integers each specifying the length of the + * sequence identified by its index. Each value in the array must + * be within the [1,1e4] range. + * @param min an array with n integers, each specifying the lower boundary of + * the sequence identified by its index. Each value in the array must + * be within the [-1e9,1e9] range. + * @param max an array with n integers, each specifying the upper boundary of + * the sequence identified by its index. Each value in the array must + * be within the [-1e9,1e9] range. + * @param replacement an array with n Boolean values, each specifying whether + * the sequence identified by its index will be created with or without + * replacement. If true, the resulting numbers may contain + * duplicate values, otherwise the numbers will all be unique within + * each sequence (default true). + * @param base an array with n integer values, each specifying the base + * that will be used to display the sequence identified by its index. + * Values allowed are 2, 8, 10 and 16 (default 10). + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * @param licenseData A JsonObject which allows the caller to include data of relevance to the + * license that is associated with the API Key. This is mandatory for API Keys with the + * license type "Flexible Gambling" and follows the format { "maxPayout": { "currency": + * "XTS", "amount": 0.0 } }. This information is used in licensing requested random values + * and in billing. The currently supported currencies are: "USD", "EUR", "GBP", "BTC", "ETH". + * Please check the official documentation for the most up-to-date information on this parameter: + * https://api.random.org/json-rpc/4/signed + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, + * "data": random int[][] if decimal (all base values are 10) + * or random String[][] if non-decimal (any other mix of base values) + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedIntegerSequences + */ + public HashMap generateSignedIntegerSequences(int n, int[] length, int[] min, int[] max, boolean[] replacement, int[] base, JsonObject pregeneratedRandomization, JsonObject licenseData, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + int[] defaultBase = new int[n]; + Arrays.fill(defaultBase, DEFAULT_INT_BASE); + + JsonObject response = this.integerSequencesMethod(n, length, min, max, + replacement, base, pregeneratedRandomization, licenseData, userData, ticketId, true); HashMap result = new HashMap(); - result.put("data", this.extractInts(response)); + if (Arrays.equals(base, defaultBase)) { + result.put("data", this.extractIntSequences(response)); + } else { + result.put("data", this.extractIntSequencesString(response)); + } return this.extractSignedResponse(response, result); } - /** Request a list (size n) of true random decimal fractions, from a uniform distribution across the [0,1] interval - ** with a user-defined number of decimal places from the server. Returns a dictionary object with the parsed decimal - ** fraction list mapped to 'data', the original response mapped to 'random', and the response's signature mapped to - ** 'signature'. See: https://api.random.org/json-rpc/1/signing#generateSignedDecimalFractions - ** - ** @param n how many random decimal fractions you need. Must be within the [1,1e4] range. - ** @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. - ** - ** @return HashMap with "random": random JsonObject, "signature": signature String, "data": random double[] - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public HashMap generateSignedDecimalFractions(int n, int decimalPlaces) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - - return this.generateSignedDecimalFractions(n, decimalPlaces, true); - } - - /** Request a list (size n) of true random decimal fractions, from a uniform distribution across the [0,1] interval - ** with a user-defined number of decimal places from the server. Returns a dictionary object with the parsed decimal - ** fraction list mapped to 'data', the original response mapped to 'random', and the response's signature mapped to - ** 'signature'. See: https://api.random.org/json-rpc/1/signing#generateSignedDecimalFractions - ** - ** @param n how many random decimal fractions you need. Must be within the [1,1e4] range. - ** @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. - ** @param replacement specifies whether the random numbers should be picked with replacement. - ** If True the resulting numbers may contain duplicate values, otherwise the numbers will all be unique (default True). - ** - ** @return HashMap with "random": random JsonObject, "signature": signature String, "data": random double[] - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public HashMap generateSignedDecimalFractions(int n, int decimalPlaces, boolean replacement) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - + /** + * Request a list (size n) of true random decimal fractions, from a uniform distribution + * across the [0,1] interval with a user-defined number of decimal places from the server. + * Returns a dictionary object with the parsed decimal fraction list mapped to 'data', the + * original response mapped to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random decimal fractions you need. Must be within the [1,1e4] range. + * @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random double[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedDecimalFractions + */ + public HashMap generateSignedDecimalFractions(int n, int decimalPlaces) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedDecimalFractions(n, decimalPlaces, DEFAULT_REPLACEMENT); + } + + /** + * Request a list (size n) of true random decimal fractions, from a uniform distribution + * across the [0,1] interval with a user-defined number of decimal places from the server. + * Returns a dictionary object with the parsed decimal fraction list mapped to 'data', the + * original response mapped to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random decimal fractions you need. Must be within the [1,1e4] range. + * @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random double[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedDecimalFractions + */ + public HashMap generateSignedDecimalFractions(int n, int decimalPlaces, boolean replacement) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedDecimalFractions(n, decimalPlaces, replacement, DEFAULT_USER_DATA); + } + + /** + * Request a list (size n) of true random decimal fractions, from a uniform distribution + * across the [0,1] interval with a user-defined number of decimal places from the server. + * Returns a dictionary object with the parsed decimal fraction list mapped to 'data', the + * original response mapped to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random decimal fractions you need. Must be within the [1,1e4] range. + * @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param userData JsonObject that will be included in unmodified form. Its maximum size in + * encoded (String) form is 1,000 characters (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random double[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedDecimalFractions + */ + public HashMap generateSignedDecimalFractions(int n, int decimalPlaces, boolean replacement, JsonObject userData) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedDecimalFractions(n, decimalPlaces, replacement, userData, DEFAULT_TICKET_ID); + } + + /** + * Request a list (size n) of true random decimal fractions, from a uniform distribution + * across the [0,1] interval with a user-defined number of decimal places from the server. + * Returns a dictionary object with the parsed decimal fraction list mapped to 'data', the + * original response mapped to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random decimal fractions you need. Must be within the [1,1e4] range. + * @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param userData JsonObject that will be included in unmodified form. Its maximum size in + * encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random double[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedDecimalFractions + */ + public HashMap generateSignedDecimalFractions(int n, int decimalPlaces, boolean replacement, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedDecimalFractions(n, decimalPlaces, replacement, DEFAULT_PREGENERATED_RANDOMIZATION, + DEFAULT_LICENSE_DATA, userData, ticketId); + } + + /** + * Request a list (size n) of true random decimal fractions, from a uniform distribution + * across the [0,1] interval with a user-defined number of decimal places from the server. + * Returns a dictionary object with the parsed decimal fraction list mapped to 'data', the + * original response mapped to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random decimal fractions you need. Must be within the [1,1e4] range. + * @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * @param licenseData A JsonObject which allows the caller to include data of relevance to the + * license that is associated with the API Key. This is mandatory for API Keys with the + * license type "Flexible Gambling" and follows the format { "maxPayout": { "currency": + * "XTS", "amount": 0.0 } }. This information is used in licensing requested random values + * and in billing. The currently supported currencies are: "USD", "EUR", "GBP", "BTC", "ETH". + * Please check the official documentation for the most up-to-date information on this parameter: + * https://api.random.org/json-rpc/4/signed + * @param userData JsonObject that will be included in unmodified form. Its maximum size in + * encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random double[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedDecimalFractions + */ + public HashMap generateSignedDecimalFractions(int n, int decimalPlaces, boolean replacement, JsonObject pregeneratedRandomization, JsonObject licenseData, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { JsonObject request = new JsonObject(); request.addProperty("n", n); request.addProperty("decimalPlaces", decimalPlaces); request.addProperty("replacement", replacement); + request.add("pregeneratedRandomization", pregeneratedRandomization); + request.add("licenseData", licenseData); + request.add("userData", userData); + request.addProperty("ticketId", ticketId); request = this.generateKeyedRequest(request, SIGNED_DECIMAL_FRACTION_METHOD); @@ -744,44 +2716,229 @@ public HashMap generateSignedDecimalFractions(int n, int decimal return this.extractSignedResponse(response, result); } - /** Request a list (size n) of true random numbers from a Gaussian distribution (also known as a normal distribution). - ** The form uses a Box-Muller Transform to generate the Gaussian distribution from uniformly distributed numbers. - ** Returns a dictionary object with the parsed random number list mapped to 'data', the original response mapped to 'random', - ** and the response's signature mapped to 'signature'. See: https://api.random.org/json-rpc/1/signing#generateSignedGaussians - ** - ** @param n how many random numbers you need. Must be within the [1,1e4] range. - ** @param mean the distribution's mean. Must be within the [-1e6,1e6] range. - ** @param standardDeviation the distribution's standard deviation. Must be within the [-1e6,1e6] range. - ** @param significantDigits the number of significant digits to use. Must be within the [2,20] range. - ** - ** @return HashMap with "random": random JsonObject, "signature": signature String, "data": random double[] - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public HashMap generateSignedGaussians(int n, double mean, double standardDeviation, int significantDigits) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - + /** + * Request a list (size n) of true random numbers from a Gaussian distribution (also known + * as a normal distribution). The form uses a Box-Muller Transform to generate the Gaussian + * distribution from uniformly distributed numbers. Returns a dictionary object with the + * parsed random number list mapped to 'data', the original response mapped to 'random', + * and the response's signature mapped to 'signature'. + * + * @param n how many random numbers you need. Must be within the [1,1e4] range. + * @param mean the distribution's mean. Must be within the [-1e6,1e6] range. + * @param standardDeviation the distribution's standard deviation. Must be within the + * [-1e6,1e6] range. + * @param significantDigits the number of significant digits to use. Must be within the + * [2,20] range. + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random double[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedGaussians + */ + public HashMap generateSignedGaussians(int n, double mean, double standardDeviation, int significantDigits) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedGaussians(n, mean, standardDeviation, + significantDigits, DEFAULT_USER_DATA); + } + + /** + * Request a list (size n) of true random numbers from a Gaussian distribution (also known + * as a normal distribution). The form uses a Box-Muller Transform to generate the Gaussian + * distribution from uniformly distributed numbers. Returns a dictionary object with the + * parsed random number list mapped to 'data', the original response mapped to 'random', + * and the response's signature mapped to 'signature'. + * + * @param n how many random numbers you need. Must be within the [1,1e4] range. + * @param mean the distribution's mean. Must be within the [-1e6,1e6] range. + * @param standardDeviation the distribution's standard deviation. Must be within the + * [-1e6,1e6] range. + * @param significantDigits the number of significant digits to use. Must be within the + * [2,20] range. + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random double[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedGaussians + */ + public HashMap generateSignedGaussians(int n, double mean, double standardDeviation, int significantDigits, JsonObject userData) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedGaussians(n, mean, standardDeviation, significantDigits, userData, + DEFAULT_TICKET_ID); + } + + /** + * Request a list (size n) of true random numbers from a Gaussian distribution (also known + * as a normal distribution). The form uses a Box-Muller Transform to generate the Gaussian + * distribution from uniformly distributed numbers. Returns a dictionary object with the + * parsed random number list mapped to 'data', the original response mapped to 'random', + * and the response's signature mapped to 'signature'. + * + * @param n how many random numbers you need. Must be within the [1,1e4] range. + * @param mean the distribution's mean. Must be within the [-1e6,1e6] range. + * @param standardDeviation the distribution's standard deviation. Must be within the + * [-1e6,1e6] range. + * @param significantDigits the number of significant digits to use. Must be within the + * [2,20] range. + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random double[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedGaussians + */ + public HashMap generateSignedGaussians(int n, double mean, double standardDeviation, int significantDigits, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedGaussians(n, mean, standardDeviation, significantDigits, + DEFAULT_PREGENERATED_RANDOMIZATION, DEFAULT_LICENSE_DATA, userData, ticketId); + } + + /** + * Request a list (size n) of true random numbers from a Gaussian distribution (also known + * as a normal distribution). The form uses a Box-Muller Transform to generate the Gaussian + * distribution from uniformly distributed numbers. Returns a dictionary object with the + * parsed random number list mapped to 'data', the original response mapped to 'random', + * and the response's signature mapped to 'signature'. + * + * @param n how many random numbers you need. Must be within the [1,1e4] range. + * @param mean the distribution's mean. Must be within the [-1e6,1e6] range. + * @param standardDeviation the distribution's standard deviation. Must be within the + * [-1e6,1e6] range. + * @param significantDigits the number of significant digits to use. Must be within the + * [2,20] range. + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * @param licenseData A JsonObject which allows the caller to include data of relevance to the + * license that is associated with the API Key. This is mandatory for API Keys with the + * license type "Flexible Gambling" and follows the format { "maxPayout": { "currency": + * "XTS", "amount": 0.0 } }. This information is used in licensing requested random values + * and in billing. The currently supported currencies are: "USD", "EUR", "GBP", "BTC", "ETH". + * Please check the official documentation for the most up-to-date information on this parameter: + * https://api.random.org/json-rpc/4/signed + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random double[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedGaussians + */ + public HashMap generateSignedGaussians(int n, double mean, double standardDeviation, int significantDigits, JsonObject pregeneratedRandomization, JsonObject licenseData, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { JsonObject request = new JsonObject(); request.addProperty("n", n); request.addProperty("mean", mean); request.addProperty("standardDeviation", standardDeviation); request.addProperty("significantDigits", significantDigits); + request.add("pregeneratedRandomization", pregeneratedRandomization); + request.add("licenseData", licenseData); + request.add("userData", userData); + request.addProperty("ticketId", ticketId); request = this.generateKeyedRequest(request, SIGNED_GAUSSIAN_METHOD); @@ -793,78 +2950,269 @@ public HashMap generateSignedGaussians(int n, double mean, doubl return this.extractSignedResponse(response, result); } - /** Request a list (size n) of true random strings from the server. Returns a dictionary object with the parsed random - ** string list mapped to 'data', the original response mapped to 'random', and the response's signature mapped to 'signature'. - ** See: https://api.random.org/json-rpc/1/signing#generateSignedStrings - ** - ** @param n how many random strings you need. Must be within the [1,1e4] range. - ** @param length the length of each string. Must be within the [1,20] range. All strings will be of the same length. - ** @param characters a string that contains the set of characters that are allowed to occur in the random strings. - ** The maximum number of characters is 80. - ** - ** @return HashMap with "random": random JsonObject, "signature": signature String, "data": random String[] - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public HashMap generateSignedStrings(int n, int length, String characters) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - return this.generateSignedStrings(n, length, characters, true); - } - - /** Request a list (size n) of true random strings from the server. Returns a dictionary object with the parsed random - ** string list mapped to 'data', the original response mapped to 'random', and the response's signature mapped to 'signature'. - ** See: https://api.random.org/json-rpc/1/signing#generateSignedStrings - ** - ** @param n how many random strings you need. Must be within the [1,1e4] range. - ** @param length the length of each string. Must be within the [1,20] range. All strings will be of the same length. - ** @param characters a string that contains the set of characters that are allowed to occur in the random strings. - ** The maximum number of characters is 80. - ** @param replacement specifies whether the random strings should be picked with replacement. If True the resulting - ** list of strings may contain duplicates, otherwise the strings will all be unique (default True). - ** - ** @return HashMap with "random": random JsonObject, "signature": signature String, "data": random String[] - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public HashMap generateSignedStrings(int n, int length, String characters, boolean replacement) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - + /** + * Request a list (size n) of true random strings from the server. Returns a dictionary + * object with the parsed random string list mapped to 'data', the original response mapped + * to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random strings you need. Must be within the [1,1e4] range. + * @param length the length of each string. Must be within the [1,20] range. All strings + * will be of the same length. + * @param characters a string that contains the set of characters that are allowed to + * occur in the random strings. The maximum number of characters is 80. + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random String[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedStrings + */ + public HashMap generateSignedStrings(int n, int length, String characters) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedStrings(n, length, characters, DEFAULT_REPLACEMENT); + } + + /** + * Request a list (size n) of true random strings from the server. Returns a dictionary + * object with the parsed random string list mapped to 'data',the original response mapped + * to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random strings you need. Must be within the [1,1e4] range. + * @param length the length of each string. Must be within the [1,20] range. All strings + * will be of the same length. + * @param characters a string that contains the set of characters that are allowed to + * occur in the random strings. The maximum number of characters is 80. + * @param replacement specifies whether the random strings should be picked with replacement. + * If true, the resulting list of strings may contain duplicates, otherwise the strings + * will all be unique (default true). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random String[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedStrings + */ + public HashMap generateSignedStrings(int n, int length, String characters, boolean replacement) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedStrings(n, length, characters, replacement, DEFAULT_USER_DATA); + } + + /** + * Request a list (size n) of true random strings from the server. Returns a dictionary + * object with the parsed random string list mapped to 'data', the original response mapped + * to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random strings you need. Must be within the [1,1e4] range. + * @param length the length of each string. Must be within the [1,20] range. All strings + * will be of the same length. + * @param characters a string that contains the set of characters that are allowed to + * occur in the random strings. The maximum number of characters is 80. + * @param replacement specifies whether the random strings should be picked with replacement. + * If true, the resulting list of strings may contain duplicates, otherwise the strings + * will all be unique (default true). + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random String[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedStrings + */ + public HashMap generateSignedStrings(int n, int length, String characters, boolean replacement, JsonObject userData) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedStrings(n, length, characters, replacement, userData, DEFAULT_TICKET_ID); + } + + /** + * Request a list (size n) of true random strings from the server. Returns a dictionary + * object with the parsed random string list mapped to 'data', the original response mapped + * to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random strings you need. Must be within the [1,1e4] range. + * @param length the length of each string. Must be within the [1,20] range. All strings + * will be of the same length. + * @param characters a string that contains the set of characters that are allowed to + * occur in the random strings. The maximum number of characters is 80. + * @param replacement specifies whether the random strings should be picked with replacement. + * If true, the resulting list of strings may contain duplicates, otherwise the strings + * will all be unique (default true). + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random String[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedStrings + */ + public HashMap generateSignedStrings(int n, int length, String characters, boolean replacement, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedStrings(n, length, characters, replacement, DEFAULT_PREGENERATED_RANDOMIZATION, + DEFAULT_LICENSE_DATA, userData, ticketId); + } + + /** + * Request a list (size n) of true random strings from the server. Returns a dictionary + * object with the parsed random string list mapped to 'data', the original response mapped + * to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random strings you need. Must be within the [1,1e4] range. + * @param length the length of each string. Must be within the [1,20] range. All strings + * will be of the same length. + * @param characters a string that contains the set of characters that are allowed to + * occur in the random strings. The maximum number of characters is 80. + * @param replacement specifies whether the random strings should be picked with replacement. + * If true, the resulting list of strings may contain duplicates, otherwise the strings + * will all be unique (default true). + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * @param licenseData A JsonObject which allows the caller to include data of relevance to the + * license that is associated with the API Key. This is mandatory for API Keys with the + * license type "Flexible Gambling" and follows the format { "maxPayout": { "currency": + * "XTS", "amount": 0.0 } }. This information is used in licensing requested random values + * and in billing. The currently supported currencies are: "USD", "EUR", "GBP", "BTC", "ETH". + * Please check the official documentation for the most up-to-date information on this parameter: + * https://api.random.org/json-rpc/4/signed + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random String[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedStrings + */ + public HashMap generateSignedStrings(int n, int length, String characters, boolean replacement, JsonObject pregeneratedRandomization, JsonObject licenseData, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { JsonObject request = new JsonObject(); request.addProperty("n", n); request.addProperty("length", length); request.addProperty("characters", characters); request.addProperty("replacement", replacement); + request.add("pregeneratedRandomization", pregeneratedRandomization); + request.add("licenseData", licenseData); + request.add("userData", userData); + request.addProperty("ticketId", ticketId); request = this.generateKeyedRequest(request, SIGNED_STRING_METHOD); @@ -873,269 +3221,1499 @@ public HashMap generateSignedStrings(int n, int length, String c HashMap result = new HashMap(); result.put("data", this.extractStrings(response)); - return this.extractSignedResponse(response, result); + return this.extractSignedResponse(response, result); + } + + /** + * Request a list (size n) of version 4 true random Universally Unique IDentifiers (UUIDs) + * in accordance with section 4.4 of RFC 4122, from the server. Returns a dictionary + * object with the parsed random UUID list mapped to 'data', the original response mapped + * to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random UUIDs you need. Must be within the [1,1e3] range. + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random UUID[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedUUIDs + */ + public HashMap generateSignedUUIDs(int n) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedUUIDs(n, DEFAULT_USER_DATA); + } + + /** + * Request a list (size n) of version 4 true random Universally Unique IDentifiers (UUIDs) + * in accordance with section 4.4 of RFC 4122, from the server. Returns a dictionary + * object with the parsed random UUID list mapped to 'data', the original response mapped + * to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random UUIDs you need. Must be within the [1,1e3] range. + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random UUID[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedUUIDs + */ + public HashMap generateSignedUUIDs(int n, JsonObject userData) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedUUIDs(n, userData, DEFAULT_TICKET_ID); + } + + /** + * Request a list (size n) of version 4 true random Universally Unique IDentifiers (UUIDs) + * in accordance with section 4.4 of RFC 4122, from the server. Returns a dictionary + * object with the parsed random UUID list mapped to 'data', the original response mapped + * to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random UUIDs you need. Must be within the [1,1e3] range. + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random UUID[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedUUIDs + */ + public HashMap generateSignedUUIDs(int n, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedUUIDs(n, DEFAULT_PREGENERATED_RANDOMIZATION, DEFAULT_LICENSE_DATA, + userData, ticketId); + } + + /** + * Request a list (size n) of version 4 true random Universally Unique IDentifiers (UUIDs) + * in accordance with section 4.4 of RFC 4122, from the server. Returns a dictionary + * object with the parsed random UUID list mapped to 'data', the original response mapped + * to 'random', and the response's signature mapped to 'signature'. + * + * @param n how many random UUIDs you need. Must be within the [1,1e3] range. + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * @param licenseData A JsonObject which allows the caller to include data of relevance to the + * license that is associated with the API Key. This is mandatory for API Keys with the + * license type "Flexible Gambling" and follows the format { "maxPayout": { "currency": + * "XTS", "amount": 0.0 } }. This information is used in licensing requested random values + * and in billing. The currently supported currencies are: "USD", "EUR", "GBP", "BTC", "ETH". + * Please check the official documentation for the most up-to-date information on this parameter: + * https://api.random.org/json-rpc/4/signed + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random UUID[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedUUIDs + */ + public HashMap generateSignedUUIDs(int n, JsonObject pregeneratedRandomization, JsonObject licenseData, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + JsonObject request = new JsonObject(); + + request.addProperty("n", n); + request.add("pregeneratedRandomization", pregeneratedRandomization); + request.add("licenseData", licenseData); + request.add("userData", userData); + request.addProperty("ticketId", ticketId); + + request = this.generateKeyedRequest(request, SIGNED_UUID_METHOD); + + JsonObject response = this.sendRequest(request); + + HashMap result = new HashMap(); + result.put("data", this.extractUUIDs(response)); + + return this.extractSignedResponse(response, result); + } + + /** + * Request a list (size n) of Binary Large OBjects (BLOBs) containing true random data + * from the server. Returns a dictionary object with the parsed random BLOB list mapped + * to 'data', the original response mapped to 'random', and the response's signature + * mapped to 'signature'. + * + * @param n how many random blobs you need. Must be within the [1,100] range. + * @param size the size of each blob, measured in bits. Must be within the [1,1048576] + * range and must be divisible by 8. + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random String[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedBlobs + */ + public HashMap generateSignedBlobs(int n, int size) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedBlobs(n, size, BLOB_FORMAT_BASE64); + } + + /** + * Request a list (size n) of Binary Large OBjects (BLOBs) containing true random data + * from the server. Returns a dictionary object with the parsed random BLOB list mapped + * to 'data', the original response mapped to 'random', and the response's signature + * mapped to 'signature'. + * + * @param n how many random blobs you need. Must be within the [1,100] range. + * @param size the size of each blob, measured in bits. Must be within the [1,1048576] + * range and must be divisible by 8. + * @param format specifies the format in which the blobs will be returned. Values allowed + * are BLOB_FORMAT_BASE64 and BLOB_FORMAT_HEX (default BLOB_FORMAT_BASE64). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random String[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedBlobs + */ + public HashMap generateSignedBlobs(int n, int size, String format) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedBlobs(n, size, format, DEFAULT_USER_DATA); + } + + /** + * Request a list (size n) of Binary Large OBjects (BLOBs) containing true random data + * from the server. Returns a dictionary object with the parsed random BLOB list mapped + * to 'data', the original response mapped to 'random', and the response's signature + * mapped to 'signature'. + * + * @param n how many random blobs you need. Must be within the [1,100] range. + * @param size the size of each blob, measured in bits. Must be within the [1,1048576] + * range and must be divisible by 8. + * @param format specifies the format in which the blobs will be returned. Values allowed + * are BLOB_FORMAT_BASE64 and BLOB_FORMAT_HEX (default BLOB_FORMAT_BASE64). + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random String[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedBlobs + */ + public HashMap generateSignedBlobs(int n, int size, String format, JsonObject userData) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedBlobs(n, size, format, userData, DEFAULT_TICKET_ID); + } + + /** + * Request a list (size n) of Binary Large OBjects (BLOBs) containing true random data + * from the server. Returns a dictionary object with the parsed random BLOB list mapped + * to 'data', the original response mapped to 'random', and the response's signature + * mapped to 'signature'. + * + * @param n how many random blobs you need. Must be within the [1,100] range. + * @param size the size of each blob, measured in bits. Must be within the [1,1048576] + * range and must be divisible by 8. + * @param format specifies the format in which the blobs will be returned. Values allowed + * are BLOB_FORMAT_BASE64 and BLOB_FORMAT_HEX (default BLOB_FORMAT_BASE64). + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random String[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedBlobs + */ + public HashMap generateSignedBlobs(int n, int size, String format, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return this.generateSignedBlobs(n, size, format, DEFAULT_PREGENERATED_RANDOMIZATION, + DEFAULT_LICENSE_DATA, userData, ticketId); + } + + /** + * Request a list (size n) of Binary Large OBjects (BLOBs) containing true random data + * from the server. Returns a dictionary object with the parsed random BLOB list mapped + * to 'data', the original response mapped to 'random', and the response's signature + * mapped to 'signature'. + * + * @param n how many random blobs you need. Must be within the [1,100] range. + * @param size the size of each blob, measured in bits. Must be within the [1,1048576] + * range and must be divisible by 8. + * @param format specifies the format in which the blobs will be returned. Values allowed + * are BLOB_FORMAT_BASE64 and BLOB_FORMAT_HEX (default BLOB_FORMAT_BASE64). + * @param pregeneratedRandomization A JsonObject which allows the client to specify that the + * random values should be generated from a pregenerated, historical randomization instead + * of a one-time on-the-fly randomization. There are three possible cases: + *
    + *
  • null: the standard way of calling for random values, i.e.true randomness is + * generated and discarded afterwards + *
  • date: RANDOM.ORG uses historical true randomness generated on the corresponding + * date (past or present, key "date" and value "YYYY-MM-DD") + *
  • id: RANDOM.ORG uses historical true randomness derived from the corresponding + * identifier in a deterministic manner. Key "id" and value is a string with length + * in the [1,64] range + *
+ * @param licenseData A JsonObject which allows the caller to include data of relevance to the + * license that is associated with the API Key. This is mandatory for API Keys with the + * license type "Flexible Gambling" and follows the format { "maxPayout": { "currency": + * "XTS", "amount": 0.0 } }. This information is used in licensing requested random values + * and in billing. The currently supported currencies are: "USD", "EUR", "GBP", "BTC", "ETH". + * Please check the official documentation for the most up-to-date information on this parameter: + * https://api.random.org/json-rpc/4/signed + * @param userData JsonObject that will be included in unmodified form. Its maximum size + * in encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * + * @return HashMap with "random": random JsonObject, + * "signature": signature String, "data": random String[] + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#generateSignedBlobs + */ + public HashMap generateSignedBlobs(int n, int size, String format, JsonObject pregeneratedRandomization, JsonObject licenseData, JsonObject userData, String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + JsonObject request = new JsonObject(); + + request.addProperty("n", n); + request.addProperty("size", size); + request.addProperty("format", format); + request.add("pregeneratedRandomization", pregeneratedRandomization); + request.add("licenseData", licenseData); + request.add("userData", userData); + request.addProperty("ticketId", ticketId); + + request = this.generateKeyedRequest(request, SIGNED_BLOB_METHOD); + + JsonObject response = this.sendRequest(request); + + HashMap result = new HashMap(); + result.put("data", this.extractStrings(response)); + + return this.extractSignedResponse(response, result); + } + + // Retrieve a signed result generated within the last 24h, + // see https://api.random.org/json-rpc/4/signed#getResult + + /** + * Retrieve signed random values generated within the last 24h, using a serial number. + * If the historical response was found, a response with the result property containing + * the same values that were returned by the method that was used to generate the values. + * + * @param serialNumber an integer containing the serial number associated with the response + * you wish to retrieve. + * + * @return HashMap with "random": random JsonObject, "signature": signature String + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#getResult + */ + public HashMap getResult(int serialNumber) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + JsonObject request = new JsonObject(); + + request.addProperty("serialNumber", serialNumber); + + request = this.generateKeyedRequest(request, GET_RESULT_METHOD); + + JsonObject response = this.sendRequest(request); + + HashMap result = new HashMap(); + + return this.extractSignedResponse(response, result); + } + + // Ticket methods + + /** + * Create n tickets to be used in signed value-generating methods. + * + * @param n The number of tickets requested. This must be a number in the [1, 50] range. + * @param showResult A boolean value that determines how much information calls to {@link + * #getTicket(String ticketId) getTicket} will return. If {@code showResult} is {@code false}, + * {@code getTicket} will return only the basic ticket information. If {@code showResult} is + * {@code true}, the full random and signature objects from the response that was used to satisfy + * the ticket is returned. + * + * @return JsonObject[] of ticket objects + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#createTickets + */ + public JsonObject[] createTickets(int n, boolean showResult) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + + JsonObject request = new JsonObject(); + + request.addProperty("n", n); + request.addProperty("showResult", showResult); + + request = this.generateKeyedRequest(request, CREATE_TICKET_METHOD); + + JsonObject response = this.sendRequest(request); + + return this.extractTickets(response); + } + + /** + * This method marks a specific ticket and all its predecessors in its chain as + * being revealed, meaning that subsequent calls to {@link #getTicket(String ticketId) + * getTicket} will return the full details of the tickets, including the random + * values produced when the tickets were used. Using this method effectively + * changes the value of {@code showResult} (which was specified when the first + * ticket in the chain was created using {@link #createTickets(int n, boolean showResult) + * createTicket}) from {@code false} to {@code true}. The reason that not only + * the ticket specified (but also its predecessors in its chain) are revealed + * is to ensure maximum transparency. This method does not affect any successors + * to the ticket in the chain. + *

+ * If this method is used on a ticket that has not yet been used, a RandomOrgRANDOMORGError + * (426) will be thrown. + * + * @param ticketId A string value that uniquely identifies the ticket. + * + * @return int A number value that specifies how many tickets were revealed. This + * will include the ticket specified as well as all its predecessors. If + * this method is invoked on a ticket that is already revealed (or which + * was created with {@code howResult} set to {@code true}), then the value + * returned will be zero. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#revealTickets + */ + public int revealTickets(String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + JsonObject request = new JsonObject(); + + request.addProperty("ticketId", ticketId); + + request = this.generateKeyedRequest(request, REVEAL_TICKETS_METHOD); + + JsonObject response = this.sendRequest(request); + + return this.extractTicketCount(response); + } + + /** + * Obtain information about tickets linked with your API key. The maximum number of tickets + * that can be returned by this method is 2000. + * + * @param ticketType A string describing the type of tickets you want to obtain information + * about. Possible values are {@code singleton, head} and {@code tail}. + *

    + *
  • {@code singleton} returns tickets that have no previous or next tickets. + *
  • {@code head} returns tickets hat do not have a previous ticket but that + * do have a next ticket. + *
  • {@code tail} returns tickets that have a previous ticket but do not have + * a next ticket. + *
+ * + * @return JsonObject[] of tickets of the type requested + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#listTickets + */ + public JsonObject[] listTickets(String ticketType) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + + JsonObject request = new JsonObject(); + + request.addProperty("ticketType", ticketType); + + request = this.generateKeyedRequest(request, LIST_TICKET_METHOD); + + JsonObject response = this.sendRequest(request); + + return this.extractTickets(response); + } + + /** + * Obtain information about a single ticket using the {@code ticketId} associated with it. + * If the ticket has {@code showResult} set to true and has been used, this method will return the + * values generated. + * + * @param ticketId A string containing a ticket identifier returned by a prior call to the + * {@link #createTickets(int n, boolean showResult) createTicket} method. + * + * @return HashMap with the following data: + *

If the ticket was created with {@code showResult true} and has been used in a + * signed value-generating method: + *

    + *
  • "random": random JsonObject as returned from the server + *
  • "signature": signature String + *
  • "data": an array of random values of the type corresponding to the method that + * the ticket was used on + *
+ * If the ticket was created with {@code showResult false} or has not yet been used: + *
    + *
  • "result": JsonObject returned from the server + *
+ * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#getTicket + */ + public HashMap getTicket(String ticketId) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + + JsonObject request = new JsonObject(); + + request.addProperty("ticketId", ticketId); + + request = this.generateRequest(request, GET_TICKET_METHOD); + + JsonObject response = this.sendRequest(request); + + HashMap result = new HashMap(); + + response = response.get("result").getAsJsonObject(); + + if (response.has("result") && !response.get("result").isJsonNull()) { + String method = response.get("result").getAsJsonObject() + .get("random").getAsJsonObject() + .get("method").getAsString(); + + if (method.equals(SIGNED_INTEGER_METHOD)) { + if (response.get("result").getAsJsonObject() + .get("random").getAsJsonObject() + .get("base").getAsInt() == 10) { + // decimal base + result.put("data", this.extractInts(response)); + } else { + // non-decimal base + result.put("data", this.extractStrings(response)); + } + } else if (method.equals(SIGNED_INTEGER_SEQUENCE_METHOD)) { + boolean decimal = false; + JsonObject random = response.get("result").getAsJsonObject() + .get("random").getAsJsonObject(); + + if (random.get("base").isJsonArray()) { + // Integer sequence method with array parameters + int[] defaultBase = new int[random.get("n").getAsInt()]; + Arrays.fill(defaultBase, DEFAULT_INT_BASE); + + if (Arrays.equals(defaultBase, gson.fromJson(random.get("base"), int[].class))) { + // Decimal base for all sequences requested + decimal = true; + } + } else if (random.get("base").getAsInt() == 10) { + // Integer sequence method with single value parameters and decimal base + decimal = true; + } + + if (decimal) { + result.put("data", this.extractIntSequences(response)); + } else { + result.put("data", this.extractIntSequencesString(response)); + } + } else if (method.equals(SIGNED_DECIMAL_FRACTION_METHOD) + || method.equals(SIGNED_GAUSSIAN_METHOD)) { + result.put("data", this.extractDoubles(response)); + } else if (method.equals(SIGNED_STRING_METHOD) + || method.equals(SIGNED_BLOB_METHOD)) { + result.put("data", this.extractStrings(response)); + } else if (method.equals(SIGNED_UUID_METHOD)) { + result.put("data", this.extractUUIDs(response)); + } + return this.extractSignedResponse(response, result); + } else { + /* + * Returns the information for a ticket with showResult == false OR + * a ticket with showResult == true, but which has not yet been used + */ + result.put("result", response); + return result; + } + } + + // Signature verification for signed methods, see: https://api.random.org/json-rpc/4/signed + + /** + * Verify the signature of a response previously received from one of the methods in + * the Signed API with the server. This is used to examine the authenticity of numbers. + * Return True on verification success. + * + * @param random the random field from a response returned by RANDOM.ORG through one of + * the Signed API methods. + * @param signature the signature field from the same response that the random field + * originates from. + * + * @return verification success. + * + *@throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + * @see + * https://api.random.org/json-rpc/4/signed#verifySignature + */ + public boolean verifySignature(JsonObject random, String signature) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + JsonObject request = new JsonObject(); + + request.add("random", random); + request.addProperty("signature", signature); + + request = this.generateRequest(request, VERIFY_SIGNATURE_METHOD); + + JsonObject response = this.sendRequest(request); + + return this.extractVerificationResponse(response); + } + + /** + * Create the URL for the signature verification page of a response previously + * received from one of the methods in the Signed API with the server. The web-page + * accessible from this URL will contain the details of the response used in this + * method, provided that the signature can be verified. This URL is also shown + * under "Show Technical Details" when the online Signature Verification Form is + * used to validate a signature. + * + * @param random the random field from a response returned by RANDOM.ORG through one of + * the Signed API methods. + * @param signature the signature field from the same response that the random field + * originates from. + * @return String containing the signature verification URL + * @throws RandomOrgRANDOMORGError when the URL is too long (max. 2,046 characters) + * @see + * https://api.random.org/signatures/form + */ + public String createURL(JsonObject random, String signature) throws RandomOrgRANDOMORGError { + String formattedRandom = formatURL(random.toString()); + String formattedSignature = formatURL(signature); + + String url = "https://api.random.org/signatures/form?format=json"; + url += "&random=" + formattedRandom; + url += "&signature=" + formattedSignature; + + if (url.length() > MAX_URL_LENGTH) { + throw new RandomOrgRANDOMORGError("Error: URL exceeds maximum length" + + "(" + MAX_URL_LENGTH + " characters)."); + } + + return url; + } + + /** + * Create the HTML form for the signature verification page of a response previously + * received from one of the methods in the Signed API with the server. The web-page + * accessible from the "Validate" button created will contain the details of the + * response used in this method, provided that the signature can be verified. The + * same HTML form is also shown under "Show Technical Details" when the online + * Signature Verification Form is used to validate a signature. + * + * @param random the random field from a response returned by RANDOM.ORG through + * one of the Signed API methods. + * @param signature the signature field from the same response that the random + * field originates from. + * @return string containing the code for the HTML form + * @see + * https://api.random.org/signatures/form + */ + public String createHTML(JsonObject random, String signature) { + String s = "
\n"; + s += " " + inputHTML("hidden", "format", "json") + "\n"; + s += " " + inputHTML("hidden", "random", random.toString()) + "\n"; + s += " " + inputHTML("hidden", "signature", signature) + "\n"; + s += " \n
"; + return s; + } + + // Methods used to create a cache for any given randomness request. + + /** + * Get a RandomOrgCache to obtain random integers. The RandomOrgCache can be polled for + * new results conforming to the output format of the input request. RandomOrgCache type + * is same as expected return value. + * + * @param n how many random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * + * @return {@code RandomOrgCache} + */ + public RandomOrgCache createIntegerCache(int n, int min, int max) { + return this.createIntegerCache(n, min, max, DEFAULT_REPLACEMENT, DEFAULT_CACHE_SIZE); + } + + /** + * Get a RandomOrgCache to obtain random integers. The RandomOrgCache can be polled for + * new results conforming to the output format of the input request. RandomOrgCache type + * is same as expected return value. + * + * @param n how many random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param cacheSize number of result-sets for the cache to try to maintain at any given time + * (default 20, minimum 2). + * + * @return {@code RandomOrgCache} + */ + public RandomOrgCache createIntegerCache(int n, int min, int max, boolean replacement, int cacheSize) { + if (cacheSize < 2) { + cacheSize = 2; + } + + JsonObject request = new JsonObject(); + + request.addProperty("min", min); + request.addProperty("max", max); + request.addProperty("replacement", replacement); + + int bulkN = 0; + + // If possible, make requests more efficient by bulk-ordering from the server. + // initially set at cache_size/2, but cache will auto-shrink bulk request size if requests can't be fulfilled. + if (replacement) { + bulkN = cacheSize/2; + request.addProperty("n", bulkN*n); + + // not possible to make the request more efficient + } else { + request.addProperty("n", n); + } + + // get the request object for use in all requests from this cache + request = this.generateKeyedRequest(request, INTEGER_METHOD); + + // max single request size, in bits, for adjusting bulk requests later + int maxRequestSize = (int) Math.ceil(Math.log(max - min + 1)/Math.log(2) * n); + + return new RandomOrgCache( + new JsonObjectInputCallable() { + @Override + public JsonObject call() throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return RandomOrgClient.this.sendRequest(this.input); + } + }, new JsonObjectInputCallable() { + @Override + public int[] call() { + return RandomOrgClient.this.extractInts(this.input); + } + }, + request, cacheSize, bulkN, n, maxRequestSize); + } + + /** + * Get a RandomOrgCache to obtain random integers. The RandomOrgCache can be polled for + * new results conforming to the output format of the input request. RandomOrgCache type + * is same as expected return value. + * + * @param n how many random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, 8, 10 + * and 16 (default 10). For base 10, if you would prefer a {@code RandomOrgCache} + * to be returned instead of a {@code RandomOrgCache}, please use the {@link + * #createIntegerCache(int n, int min, int max, boolean replacement, int cacheSize) + * createIntegerCache} method without the base parameter. + * @param cacheSize number of result-sets for the cache to try to maintain at any given time + * (default 20, minimum 2). + * + * @return {@code RandomOrgCache} + */ + public RandomOrgCache createIntegerCache(int n, int min, int max, boolean replacement, int base, int cacheSize) { + if (cacheSize < 2) { + cacheSize = 2; + } + + JsonObject request = new JsonObject(); + + request.addProperty("min", min); + request.addProperty("max", max); + request.addProperty("replacement", replacement); + request.addProperty("base", base); + + int bulkN = 0; + + // If possible, make requests more efficient by bulk-ordering from the server. + // initially set at cache_size/2, but cache will auto-shrink bulk request size + // if requests can't be fulfilled. + if (replacement) { + bulkN = cacheSize/2; + request.addProperty("n", bulkN*n); + + // not possible to make the request more efficient + } else { + request.addProperty("n", n); + } + + // get the request object for use in all requests from this cache + request = this.generateKeyedRequest(request, INTEGER_METHOD); + + // max single request size, in bits, for adjusting bulk requests later + int maxRequestSize = (int) Math.ceil(Math.log(max - min + 1)/Math.log(2) * n); + + return new RandomOrgCache( + new JsonObjectInputCallable() { + @Override + public JsonObject call() throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return RandomOrgClient.this.sendRequest(this.input); + } + }, new JsonObjectInputCallable() { + @Override + public String[] call() { + return RandomOrgClient.this.extractStrings(this.input); + } + }, + request, cacheSize, bulkN, n, maxRequestSize); + } + + /** + * Get a RandomOrgCache to obtain random integer sequences. The RandomOrgCache can be polled + * for new results conforming to the output format of the input request. RandomOrgCache + * type is same as expected return value. + * + * @param n how many random integers you need. Must be within the [1,1e4] range. + * @param length the length of each array of random integers requested. Must be within + * the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * + * @return {@code RandomOrgCache} + */ + public RandomOrgCache createIntegerSequenceCache(int n, int length, int min, int max) { + return this.createIntegerSequenceCache(n, length, min, max, DEFAULT_REPLACEMENT, DEFAULT_CACHE_SIZE_SMALL); + } + + /** + * Get a RandomOrgCache to obtain random integer sequences. The RandomOrgCache can be polled + * for new results conforming to the output format of the input request. RandomOrgCache + * type is same as expected return value. + * + * @param n how many random integers you need. Must be within the [1,1e4] range. + * @param length the length of each array of random integers requested. Must be within + * the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default True). + * @param cacheSize number of result-sets for the cache to try to maintain at any given + * time (default 10, minimum 2). + * + * @return {@code RandomOrgCache} + */ + public RandomOrgCache createIntegerSequenceCache(int n, int length, int min, int max, boolean replacement, int cacheSize) { + if (cacheSize < 2) { + cacheSize = 2; + } + + JsonObject request = new JsonObject(); + + request.addProperty("length", length); + request.addProperty("min", min); + request.addProperty("max", max); + request.addProperty("replacement", replacement); + + int bulkN = 0; + + // If possible, make requests more efficient by bulk-ordering from the server. + // initially set at cache_size/2, but cache will auto-shrink bulk request size + // if requests can't be fulfilled. + if (replacement) { + bulkN = cacheSize/2; + request.addProperty("n", bulkN*n); + + // not possible to make the request more efficient + } else { + request.addProperty("n", n); + } + + // get the request object for use in all requests from this cache + request = this.generateKeyedRequest(request, INTEGER_SEQUENCE_METHOD); + + // max single request size, in bits, for adjusting bulk requests later + int maxRequestSize = (int) Math.ceil(Math.log(max - min + 1)/Math.log(2) * n); + + return new RandomOrgCache( + new JsonObjectInputCallable() { + @Override + public JsonObject call() throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return RandomOrgClient.this.sendRequest(this.input); + } + }, new JsonObjectInputCallable() { + @Override + public int[][] call() { + return RandomOrgClient.this.extractIntSequences(this.input); + } + }, + request, cacheSize, bulkN, n, maxRequestSize); } + + /** + * Get a RandomOrgCache to obtain random integer sequences. The RandomOrgCache can be polled + * for new results conforming to the output format of the input request. RandomOrgCache + * type is same as expected return value. + * + * @param n how many random integers you need. Must be within the [1,1e4] range. + * @param length the length of each array of random integers requested. Must be within + * the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default True). + * @param base the base that will be used to display the numbers. Values allowed are 2, + * 8, 10 and 16 (default 10). For base 10, if you would prefer a {@code + * RandomOrgCache} to be returned instead of a {@code RandomOrgCache}, + * please use the {@link #createIntegerSequenceCache(int n, int length, int min, + * int max, boolean replacement, int cacheSize) createIntegerSequenceCache} method + * without the base parameter. + * @param cacheSize number of result-sets for the cache to try to maintain at any given + * time (default 10, minimum 2). + * + * @return {@code RandomOrgCache} + */ + public RandomOrgCache createIntegerSequenceCache(int n, int length, int min, int max, boolean replacement, int base, int cacheSize) { + if (cacheSize < 2) { + cacheSize = 2; + } - /** Request a list (size n) of version 4 true random Universally Unique IDentifiers (UUIDs) in accordance with - ** section 4.4 of RFC 4122, from the server. Returns a dictionary object with the parsed random UUID list mapped - ** to 'data', the original response mapped to 'random', and the response's signature mapped to 'signature'. - ** See: https://api.random.org/json-rpc/1/signing#generateSignedUUIDs - ** - ** @param n how many random UUIDs you need. Must be within the [1,1e3] range. - ** - ** @return HashMap with "random": random JsonObject, "signature": signature String, "data": random UUID[] - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public HashMap generateSignedUUIDs(int n) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - JsonObject request = new JsonObject(); - request.addProperty("n", n); - - request = this.generateKeyedRequest(request, SIGNED_UUID_METHOD); - - JsonObject response = this.sendRequest(request); + request.addProperty("length", length); + request.addProperty("min", min); + request.addProperty("max", max); + request.addProperty("replacement", replacement); + request.addProperty("base", base); + + int bulkN = 0; + + // If possible, make requests more efficient by bulk-ordering from the server. + // initially set at cache_size/2, but cache will auto-shrink bulk request size if requests can't be fulfilled. + if (replacement) { + bulkN = cacheSize/2; + request.addProperty("n", bulkN*n); + + // not possible to make the request more efficient + } else { + request.addProperty("n", n); + } + + // get the request object for use in all requests from this cache + request = this.generateKeyedRequest(request, INTEGER_SEQUENCE_METHOD); - HashMap result = new HashMap(); - result.put("data", this.extractUUIDs(response)); + // max single request size, in bits, for adjusting bulk requests later + int maxRequestSize = (int) Math.ceil(Math.log(max - min + 1)/Math.log(2) * n); - return this.extractSignedResponse(response, result); + return new RandomOrgCache( + new JsonObjectInputCallable() { + @Override + public JsonObject call() throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return RandomOrgClient.this.sendRequest(this.input); + } + }, new JsonObjectInputCallable() { + @Override + public String[][] call() { + return RandomOrgClient.this.extractIntSequencesString(this.input); + } + }, + request, cacheSize, bulkN, n, maxRequestSize); + } + + /** + * Get a RandomOrgCache to obtain random integer sequences. The RandomOrgCache can be + * polled for new results conforming to the output format of the input request. RandomOrgCache + * type is same as expected return value. + * + * @param n how many random integers you need. Must be within the + * [1,1e4] range. + * @param length an array with n integers each specifying the length of the sequence + * identified by its index. Each value in the array must be within the [1,1e4] range. + * @param min an array with n integers, each specifying the lower boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param max an array with n integers, each specifying the upper boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * + * @return {@code RandomOrgCache} + */ + public RandomOrgCache createIntegerSequenceCache(int n, int[] length, int[] min, int[] max) { + boolean[] replacement = new boolean[n]; + Arrays.fill(replacement, DEFAULT_REPLACEMENT); + return createIntegerSequenceCache(n, length, min, max, replacement, DEFAULT_CACHE_SIZE_SMALL); } - /** Request a list (size n) of Binary Large OBjects (BLOBs) containing true random data from the server. Returns a - ** dictionary object with the parsed random BLOB list mapped to 'data', the original response mapped to 'random', - ** and the response's signature mapped to 'signature'. See: https://api.random.org/json-rpc/1/signing#generateSignedBlobs - ** - ** @param n how many random blobs you need. Must be within the [1,100] range. - ** @param size the size of each blob, measured in bits. Must be within the [1,1048576] range and must be divisible by 8. - ** - ** @return HashMap with "random": random JsonObject, "signature": signature String, "data": random String[] - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public HashMap generateSignedBlobs(int n, int size) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - - return this.generateSignedBlobs(n, size, RandomOrgClient.BLOB_FORMAT_BASE64); - } - - /** Request a list (size n) of Binary Large OBjects (BLOBs) containing true random data from the server. Returns a - ** dictionary object with the parsed random BLOB list mapped to 'data', the original response mapped to 'random', - ** and the response's signature mapped to 'signature'. See: https://api.random.org/json-rpc/1/signing#generateSignedBlobs - ** - ** @param n how many random blobs you need. Must be within the [1,100] range. - ** @param size the size of each blob, measured in bits. Must be within the [1,1048576] range and must be divisible by 8. - ** @param format specifies the format in which the blobs will be returned. Values allowed are - ** BLOB_FORMAT_BASE64 and BLOB_FORMAT_HEX (default BLOB_FORMAT_BASE64). - ** - ** @return HashMap with "random": random JsonObject, "signature": signature String, "data": random String[] - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public HashMap generateSignedBlobs(int n, int size, String format) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { + /** + * Get a RandomOrgCache to obtain random integer sequences. The RandomOrgCache can be polled + * for new results conforming to the output format of the input request. RandomOrgCache + * type is same as expected return value. + * + * @param n how many random integers you need. Must be within the + * [1,1e4] range. + * @param length an array with n integers each specifying the length of the sequence + * identified by its index. Each value in the array must be within the [1,1e4] range. + * @param min an array with n integers, each specifying the lower boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param max an array with n integers, each specifying the upper boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param replacement an array with n boolean values, each specifying whether the sequence + * identified by its index will be created with or without replacement. If true, the + * resulting numbers may contain duplicate values, otherwise the numbers will all be + * unique within each sequence (default boolean[n] with all values set to true). + * @param cacheSize number of result-sets for the cache to try to maintain + * at any given time (default 10, minimum 2). + * + * @return {@code RandomOrgCache} + */ + public RandomOrgCache createIntegerSequenceCache(int n, int[] length, int[] min, int[] max, boolean[] replacement, int cacheSize) { + if (cacheSize < 2) { + cacheSize = 2; + } + + boolean[] defaultReplacement = new boolean[replacement.length]; + Arrays.fill(defaultReplacement, true); JsonObject request = new JsonObject(); - - request.addProperty("n", n); - request.addProperty("size", size); - request.addProperty("format", format); - - request = this.generateKeyedRequest(request, SIGNED_BLOB_METHOD); - - JsonObject response = this.sendRequest(request); - - HashMap result = new HashMap(); - result.put("data", this.extractStrings(response)); - - return this.extractSignedResponse(response, result); - } - // Signature verification for signed methods, see: https://api.random.org/json-rpc/1/signing - - /** Verify the signature of a response previously received from one of the methods in the Signed API with the - ** server. This is used to examine the authenticity of numbers. Return True on verification success. - ** See: https://api.random.org/json-rpc/1/signing#verifySignature - ** - ** @param random the random field from a response returned by RANDOM.ORG through one of the Signed API methods. - ** @param signature the signature field from the same response that the random field originates from. - ** - ** @return verification success. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - public boolean verifySignature(JsonObject random, String signature) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { + int bulkN = 0; + + // If possible, make requests more efficient by bulk-ordering from the server. + // initially set at cache_size/2, but cache will auto-shrink bulk request size + // if requests can't be fulfilled. + if (Arrays.equals(replacement, defaultReplacement)) { + bulkN = cacheSize/2; + + request.addProperty("n", bulkN*n); + + length = adjust(length, bulkN*n); + min = adjust(min, bulkN*n); + max = adjust(max, bulkN*n); + replacement = adjust(replacement, bulkN*n); + + // not possible to make the request more efficient + } else { + request.addProperty("n", n); + } - JsonObject request = new JsonObject(); + request.add("length", gson.toJsonTree(length)); + request.add("min", gson.toJsonTree(min)); + request.add("max", gson.toJsonTree(max)); + request.add("replacement", gson.toJsonTree(replacement)); + + // get the request object for use in all requests from this cache + request = this.generateKeyedRequest(request, INTEGER_SEQUENCE_METHOD); - request.add("random", random); - request.addProperty("signature", signature); + // max single request size, in bits, for adjusting bulk requests later - request = this.generateRequest(request, VERIFY_SIGNATURE_METHOD); - JsonObject response = this.sendRequest(request); + int maxRequestSize = (int) Math.ceil(Math.log(max(max) - min(min) + 1)/Math.log(2) * n * max(length)); - return this.extractVerificationResponse(response); + return new RandomOrgCache( + new JsonObjectInputCallable() { + @Override + public JsonObject call() throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + return RandomOrgClient.this.sendRequest(this.input); + } + }, new JsonObjectInputCallable() { + @Override + public int[][] call() { + return RandomOrgClient.this.extractIntSequences(this.input); + } + }, + request, cacheSize, bulkN, n, maxRequestSize); } - - // Methods used to create a cache for any given randomness request. - - /** Get a RandomOrgCache to obtain random integers. The RandomOrgCache can be polled for new results conforming to - ** the output format of the input request. RandomOrgCache type is same as expected return value. - ** - ** @param n how many random integers you need. Must be within the [1,1e4] range. - ** @param min the lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range. - ** @param max the upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range. - ** - ** @return RandomOrgCache - **/ - public RandomOrgCache createIntegerCache(int n, int min, int max) { - return this.createIntegerCache(n, min, max, true, 20); - } - - /** Get a RandomOrgCache to obtain random integers. The RandomOrgCache can be polled for new results conforming to - ** the output format of the input request. RandomOrgCache type is same as expected return value. - ** - ** @param n how many random integers you need. Must be within the [1,1e4] range. - ** @param min the lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range. - ** @param max the upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range. - ** @param replacement specifies whether the random numbers should be picked with replacement. - ** If True the resulting numbers may contain duplicate values, otherwise the numbers will all be unique (default True). - ** @param cacheSize number of result-sets for the cache to try to maintain at any given time (default 20, minimum 2). - ** - ** @return RandomOrgCache - **/ - public RandomOrgCache createIntegerCache(int n, int min, int max, boolean replacement, int cacheSize) { + + /** + * Get a RandomOrgCache to obtain random integer sequences. The RandomOrgCache can be polled + * for new results conforming to the output format of the input request. RandomOrgCache + * type is same as expected return value. + * + * @param n how many random integers you need. Must be within the + * [1,1e4] range. + * @param length an array with n integers each specifying the length of the sequence + * identified by its index. Each value in the array must be within the [1,1e4] range. + * @param min an array with n integers, each specifying the lower boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param max an array with n integers, each specifying the upper boundary of the sequence + * identified by its index. Each value in the array must be within the [-1e9,1e9] range. + * @param replacement an array with n boolean values, each specifying whether the sequence + * identified by its index will be created with or without replacement. If true, the + * resulting numbers may contain duplicate values, otherwise the numbers will all be + * unique within each sequence (default boolean[n] with all values set to true). + * @param base an array with n integer values, each specifying the base that will be used to + * display the sequence identified by its index. Values allowed are 2, 8, 10 and 16 + * (default 10). For base 10, if you require an {@code RandomOrgCache} instead of + * a {@code RandomOrgCache}, please use the {@link #createIntegerSequenceCache( + * int n, int[] length, int[] min, int[] max, boolean[] replacement, int cacheSize) + * createIntegerSequenceCache} method without the base parameter. + * @param cacheSize number of result-sets for the cache to try to maintain + * at any given time (default 10, minimum 2). + * + * @return {@code RandomOrgCache} + */ + public RandomOrgCache createIntegerSequenceCache(int n, int[] length, int[] min, int[] max, boolean[] replacement, int[] base, int cacheSize) { if (cacheSize < 2) { cacheSize = 2; } - JsonObject request = new JsonObject(); + boolean[] defaultReplacement = new boolean[replacement.length]; + Arrays.fill(defaultReplacement, true); - request.addProperty("min", min); - request.addProperty("max", max); - request.addProperty("replacement", replacement); - + JsonObject request = new JsonObject(); + int bulkN = 0; // If possible, make requests more efficient by bulk-ordering from the server. - // initially set at cache_size/2, but cache will auto-shrink bulk request size if requests can't be fulfilled. - if (replacement) { + // initially set at cache_size/2, but cache will auto-shrink bulk request size + // if requests can't be fulfilled. + if (Arrays.equals(replacement, defaultReplacement)) { bulkN = cacheSize/2; + request.addProperty("n", bulkN*n); + + length = adjust(length, bulkN*n); + min = adjust(min, bulkN*n); + max = adjust(max, bulkN*n); + replacement = adjust(replacement, bulkN*n); + base = adjust(base, bulkN*n); // not possible to make the request more efficient } else { request.addProperty("n", n); - } + } + + request.add("length", gson.toJsonTree(length)); + request.add("min", gson.toJsonTree(min)); + request.add("max", gson.toJsonTree(max)); + request.add("replacement", gson.toJsonTree(replacement)); + request.add("base", gson.toJsonTree(base)); // get the request object for use in all requests from this cache - request = this.generateKeyedRequest(request, INTEGER_METHOD); + request = this.generateKeyedRequest(request, INTEGER_SEQUENCE_METHOD); // max single request size, in bits, for adjusting bulk requests later - int maxRequestSize = (int) Math.ceil(Math.log(max - min + 1)/Math.log(2) * n); - return new RandomOrgCache( + + int maxRequestSize = (int) Math.ceil(Math.log(max(max) - min(min) + 1)/Math.log(2) * n * max(length)); + + return new RandomOrgCache( new JsonObjectInputCallable() { @Override - public JsonObject call() throws RandomOrgSendTimeoutException, RandomOrgKeyNotRunningError, RandomOrgInsufficientRequestsError, RandomOrgInsufficientBitsError, RandomOrgBadHTTPResponseException, RandomOrgRANDOMORGError, RandomOrgJSONRPCError, MalformedURLException, IOException { + public JsonObject call() throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { return RandomOrgClient.this.sendRequest(this.input); } - }, new JsonObjectInputCallable() { + }, new JsonObjectInputCallable() { @Override - public int[] call() { - return RandomOrgClient.this.extractInts(this.input); + public String[][] call() { + return RandomOrgClient.this.extractIntSequencesString(this.input); } }, request, cacheSize, bulkN, n, maxRequestSize); } - - /** Get a RandomOrgCache to obtain random decimal fractions. The RandomOrgCache can be polled for new results - ** conforming to the output format of the input request. RandomOrgCache type is same as expected return value. - ** - ** @param n how many random decimal fractions you need. Must be within the [1,1e4] range. - ** @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. - ** - ** @return RandomOrgCache - **/ + + /** + * Get a RandomOrgCache to obtain random decimal fractions. The RandomOrgCache can be polled + * for new results conforming to the output format of the input request. RandomOrgCache type + * is same as expected return value. + * + * @param n how many random decimal fractions you need. Must be within the [1,1e4] range. + * @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. + * + * @return {@code RandomOrgCache} + */ public RandomOrgCache createDecimalFractionCache(int n, int decimalPlaces) { - return this.createDecimalFractionCache(n, decimalPlaces, true, 20); - } - - /** Get a RandomOrgCache to obtain random decimal fractions. The RandomOrgCache can be polled for new results - ** conforming to the output format of the input request. RandomOrgCache type is same as expected return value. - ** - ** @param n how many random decimal fractions you need. Must be within the [1,1e4] range. - ** @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. - ** @param replacement specifies whether the random numbers should be picked with replacement. - ** If True the resulting numbers may contain duplicate values, otherwise the numbers will all be unique (default True). - ** @param cacheSize number of result-sets for the cache to try to maintain at any given time (default 20, minimum 2). - ** - ** @return RandomOrgCache - **/ + return this.createDecimalFractionCache(n, decimalPlaces, DEFAULT_REPLACEMENT, DEFAULT_CACHE_SIZE); + } + + /** + * Get a RandomOrgCache to obtain random decimal fractions. The RandomOrgCache can be polled + * for new results conforming to the output format of the input request. RandomOrgCache type + * is same as expected return value. + * + * @param n how many random decimal fractions you need. Must be within the [1,1e4] range. + * @param decimalPlaces the number of decimal places to use. Must be within the [1,20] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param cacheSize number of result-sets for the cache to try to maintain at any given time + * (default 20, minimum 2). + * + * @return {@code RandomOrgCache} + */ public RandomOrgCache createDecimalFractionCache(int n, int decimalPlaces, boolean replacement, int cacheSize) { if (cacheSize < 2) { cacheSize = 2; @@ -1149,7 +4727,8 @@ public RandomOrgCache createDecimalFractionCache(int n, int decimalPla int bulkN = 0; // If possible, make requests more efficient by bulk-ordering from the server. - // initially set at cache_size/2, but cache will auto-shrink bulk request size if requests can't be fulfilled. + // initially set at cache_size/2, but cache will auto-shrink bulk request size + // if requests can't be fulfilled. if (replacement) { bulkN = cacheSize/2; request.addProperty("n", bulkN*n); @@ -1168,7 +4747,15 @@ public RandomOrgCache createDecimalFractionCache(int n, int decimalPla return new RandomOrgCache( new JsonObjectInputCallable() { @Override - public JsonObject call() throws RandomOrgSendTimeoutException, RandomOrgKeyNotRunningError, RandomOrgInsufficientRequestsError, RandomOrgInsufficientBitsError, RandomOrgBadHTTPResponseException, RandomOrgRANDOMORGError, RandomOrgJSONRPCError, MalformedURLException, IOException { + public JsonObject call() throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { return RandomOrgClient.this.sendRequest(this.input); } }, new JsonObjectInputCallable() { @@ -1180,31 +4767,40 @@ public double[] call() { request, cacheSize, bulkN, n, maxRequestSize); } - /** Get a RandomOrgCache to obtain random numbers. The RandomOrgCache can be polled for new results - ** conforming to the output format of the input request. RandomOrgCache type is same as expected return value. - ** - ** @param n how many random numbers you need. Must be within the [1,1e4] range. - ** @param mean the distribution's mean. Must be within the [-1e6,1e6] range. - ** @param standardDeviation the distribution's standard deviation. Must be within the [-1e6,1e6] range. - ** @param significantDigits the number of significant digits to use. Must be within the [2,20] range. - ** - ** @return RandomOrgCache - **/ + /** + * Get a RandomOrgCache to obtain random numbers. The RandomOrgCache can be polled for new + * results conforming to the output format of the input request. RandomOrgCache type is same + * as expected return value. + * + * @param n how many random numbers you need. Must be within the [1,1e4] range. + * @param mean the distribution's mean. Must be within the [-1e6,1e6] range. + * @param standardDeviation the distribution's standard deviation. Must be within the + * [-1e6,1e6] range. + * @param significantDigits the number of significant digits to use. Must be within the + * [2,20] range. + * + * @return {@code RandomOrgCache} + */ public RandomOrgCache createGaussianCache(int n, double mean, double standardDeviation, int significantDigits) { - return this.createGaussianCache(n, mean, standardDeviation, significantDigits, 20); - } - - /** Get a RandomOrgCache to obtain random numbers. The RandomOrgCache can be polled for new results - ** conforming to the output format of the input request. RandomOrgCache type is same as expected return value. - ** - ** @param n how many random numbers you need. Must be within the [1,1e4] range. - ** @param mean the distribution's mean. Must be within the [-1e6,1e6] range. - ** @param standardDeviation the distribution's standard deviation. Must be within the [-1e6,1e6] range. - ** @param significantDigits the number of significant digits to use. Must be within the [2,20] range. - ** @param cacheSize number of result-sets for the cache to try to maintain at any given time (default 20, minimum 2). - ** - ** @return RandomOrgCache - **/ + return this.createGaussianCache(n, mean, standardDeviation, significantDigits, DEFAULT_CACHE_SIZE); + } + + /** + * Get a RandomOrgCache to obtain random numbers. The RandomOrgCache can be polled for new + * results conforming to the output format of the input request. RandomOrgCache type is + * same as expected return value. + * + * @param n how many random numbers you need. Must be within the [1,1e4] range. + * @param mean the distribution's mean. Must be within the [-1e6,1e6] range. + * @param standardDeviation the distribution's standard deviation. Must be within the + * [-1e6,1e6] range. + * @param significantDigits the number of significant digits to use. Must be within the + * [2,20] range. + * @param cacheSize number of result-sets for the cache to try to maintain at any given time + * (default 20, minimum 2). + * + * @return {@code RandomOrgCache} + */ public RandomOrgCache createGaussianCache(int n, double mean, double standardDeviation, int significantDigits, int cacheSize) { if (cacheSize < 2) { cacheSize = 2; @@ -1219,7 +4815,8 @@ public RandomOrgCache createGaussianCache(int n, double mean, double s int bulkN = 0; // make requests more efficient by bulk-ordering from the server. - // initially set at cache_size/2, but cache will auto-shrink bulk request size if requests can't be fulfilled. + // initially set at cache_size/2, but cache will auto-shrink bulk request size if + // requests can't be fulfilled. bulkN = cacheSize/2; request.addProperty("n", bulkN*n); @@ -1232,7 +4829,15 @@ public RandomOrgCache createGaussianCache(int n, double mean, double s return new RandomOrgCache( new JsonObjectInputCallable() { @Override - public JsonObject call() throws RandomOrgSendTimeoutException, RandomOrgKeyNotRunningError, RandomOrgInsufficientRequestsError, RandomOrgInsufficientBitsError, RandomOrgBadHTTPResponseException, RandomOrgRANDOMORGError, RandomOrgJSONRPCError, MalformedURLException, IOException { + public JsonObject call() throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { return RandomOrgClient.this.sendRequest(this.input); } }, new JsonObjectInputCallable() { @@ -1244,33 +4849,41 @@ public double[] call() { request, cacheSize, bulkN, n, maxRequestSize); } - /** Get a RandomOrgCache to obtain random strings. The RandomOrgCache can be polled for new results - ** conforming to the output format of the input request. RandomOrgCache type is same as expected return value. - ** - ** @param n how many random strings you need. Must be within the [1,1e4] range. - ** @param length the length of each string. Must be within the [1,20] range. All strings will be of the same length. - ** @param characters a string that contains the set of characters that are allowed to occur in the random strings. - ** The maximum number of characters is 80. - ** - ** @return RandomOrgCache - **/ + /** + * Get a RandomOrgCache to obtain random strings. The RandomOrgCache can be polled for new + * results conforming to the output format of the input request. RandomOrgCache type is + * same as expected return value. + * + * @param n how many random strings you need. Must be within the [1,1e4] range. + * @param length the length of each string. Must be within the [1,20] range. All strings will + * be of the same length. + * @param characters a string that contains the set of characters that are allowed to occur + * in the random strings. The maximum number of characters is 80. + * + * @return {@code RandomOrgCache} + */ public RandomOrgCache createStringCache(int n, int length, String characters) { - return this.createStringCache(n, length, characters, true, 20); - } - - /** Get a RandomOrgCache to obtain random strings. The RandomOrgCache can be polled for new results - ** conforming to the output format of the input request. RandomOrgCache type is same as expected return value. - ** - ** @param n how many random strings you need. Must be within the [1,1e4] range. - ** @param length the length of each string. Must be within the [1,20] range. All strings will be of the same length. - ** @param characters a string that contains the set of characters that are allowed to occur in the random strings. - ** The maximum number of characters is 80. - ** @param replacement specifies whether the random strings should be picked with replacement. If True the resulting - ** list of strings may contain duplicates, otherwise the strings will all be unique (default True). - ** @param cacheSize number of result-sets for the cache to try to maintain at any given time (default 20, minimum 2). - ** - ** @return RandomOrgCache - **/ + return this.createStringCache(n, length, characters, DEFAULT_REPLACEMENT, DEFAULT_CACHE_SIZE); + } + + /** + * Get a RandomOrgCache to obtain random strings. The RandomOrgCache can be polled for new + * results conforming to the output format of the input request. RandomOrgCache type is + * same as expected return value. + * + * @param n how many random strings you need. Must be within the [1,1e4] range. + * @param length the length of each string. Must be within the [1,20] range. All strings + * will be of the same length. + * @param characters a string that contains the set of characters that are allowed to occur + * in the random strings. The maximum number of characters is 80. + * @param replacement specifies whether the random strings should be picked with replacement. + * If true, the resulting list of strings may contain duplicates, otherwise the strings + * will all be unique (default true). + * @param cacheSize number of result-sets for the cache to try to maintain at any given time + * (default 20, minimum 2). + * + * @return {@code RandomOrgCache} + */ public RandomOrgCache createStringCache(int n, int length, String characters, boolean replacement, int cacheSize) { if (cacheSize < 2) { cacheSize = 2; @@ -1285,7 +4898,8 @@ public RandomOrgCache createStringCache(int n, int length, String char int bulkN = 0; // If possible, make requests more efficient by bulk-ordering from the server. - // initially set at cache_size/2, but cache will auto-shrink bulk request size if requests can't be fulfilled. + // initially set at cache_size/2, but cache will auto-shrink bulk request size + // if requests can't be fulfilled. if (replacement) { bulkN = cacheSize/2; request.addProperty("n", bulkN*n); @@ -1304,7 +4918,15 @@ public RandomOrgCache createStringCache(int n, int length, String char return new RandomOrgCache( new JsonObjectInputCallable() { @Override - public JsonObject call() throws RandomOrgSendTimeoutException, RandomOrgKeyNotRunningError, RandomOrgInsufficientRequestsError, RandomOrgInsufficientBitsError, RandomOrgBadHTTPResponseException, RandomOrgRANDOMORGError, RandomOrgJSONRPCError, MalformedURLException, IOException { + public JsonObject call() throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { return RandomOrgClient.this.sendRequest(this.input); } }, new JsonObjectInputCallable() { @@ -1316,25 +4938,30 @@ public String[] call() { request, cacheSize, bulkN, n, maxRequestSize); } - /** Get a RandomOrgCache to obtain UUIDs. The RandomOrgCache can be polled for new results conforming to the - ** output format of the input request. RandomOrgCache type is same as expected return value. - ** - ** @param n how many random UUIDs you need. Must be within the [1,1e3] range. - ** - ** @return RandomOrgCache - **/ + /** + * Get a RandomOrgCache to obtain UUIDs. The RandomOrgCache can be polled for new results + * conforming to the output format of the input request. RandomOrgCache type is same as + * expected return value. + * + * @param n how many random UUIDs you need. Must be within the [1,1e3] range. + * + * @return {@code RandomOrgCache} + */ public RandomOrgCache createUUIDCache(int n) { - return this.createUUIDCache(n, 10); + return this.createUUIDCache(n, DEFAULT_CACHE_SIZE_SMALL); } - /** Get a RandomOrgCache to obtain UUIDs. The RandomOrgCache can be polled for new results conforming to the - ** output format of the input request. RandomOrgCache type is same as expected return value. - ** - ** @param n how many random UUIDs you need. Must be within the [1,1e3] range. - ** @param cacheSize number of result-sets for the cache to try to maintain at any given time (default 10, minimum 2). - ** - ** @return RandomOrgCache - **/ + /** + * Get a RandomOrgCache to obtain UUIDs. The RandomOrgCache can be polled for new results + * conforming to the output format of the input request. RandomOrgCache type is same as + * expected return value. + * + * @param n how many random UUIDs you need. Must be within the [1,1e3] range. + * @param cacheSize number of result-sets for the cache to try to maintain at any given time + * (default 10, minimum 2). + * + * @return {@code RandomOrgCache} + */ public RandomOrgCache createUUIDCache(int n, int cacheSize) { if (cacheSize < 2) { cacheSize = 2; @@ -1345,7 +4972,8 @@ public RandomOrgCache createUUIDCache(int n, int cacheSize) { int bulkN = 0; // make requests more efficient by bulk-ordering from the server. - // initially set at cache_size/2, but cache will auto-shrink bulk request size if requests can't be fulfilled. + // initially set at cache_size/2, but cache will auto-shrink bulk request size if + // requests can't be fulfilled. bulkN = cacheSize/2; request.addProperty("n", bulkN*n); @@ -1358,7 +4986,15 @@ public RandomOrgCache createUUIDCache(int n, int cacheSize) { return new RandomOrgCache( new JsonObjectInputCallable() { @Override - public JsonObject call() throws RandomOrgSendTimeoutException, RandomOrgKeyNotRunningError, RandomOrgInsufficientRequestsError, RandomOrgInsufficientBitsError, RandomOrgBadHTTPResponseException, RandomOrgRANDOMORGError, RandomOrgJSONRPCError, MalformedURLException, IOException { + public JsonObject call() throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { return RandomOrgClient.this.sendRequest(this.input); } }, new JsonObjectInputCallable() { @@ -1370,29 +5006,36 @@ public UUID[] call() { request, cacheSize, bulkN, n, maxRequestSize); } - /** Get a RandomOrgCache to obtain random blobs. The RandomOrgCache can be polled for new results conforming - ** to the output format of the input request. RandomOrgCache type is same as expected return value. - ** - ** @param n how many random blobs you need. Must be within the [1,100] range. - ** @param size the size of each blob, measured in bits. Must be within the [1,1048576] range and must be divisible by 8. - ** - ** @return RandomOrgCache - **/ + /** + * Get a RandomOrgCache to obtain random blobs. The RandomOrgCache can be polled for new + * results conforming to the output format of the input request. RandomOrgCache type is + * same as expected return value. + * + * @param n how many random blobs you need. Must be within the [1,20] range. + * @param size the size of each blob, measured in bits. Must be within the [1,1048576] range + * and must be divisible by 8. + * + * @return {@code RandomOrgCache} + */ public RandomOrgCache createBlobCache(int n, int size) { - return this.createBlobCache(n, size, RandomOrgClient.BLOB_FORMAT_BASE64, 10); - } - - /** Get a RandomOrgCache to obtain random blobs. The RandomOrgCache can be polled for new results conforming - ** to the output format of the input request. RandomOrgCache type is same as expected return value. - ** - ** @param n how many random blobs you need. Must be within the [1,100] range. - ** @param size the size of each blob, measured in bits. Must be within the [1,1048576] range and must be divisible by 8. - ** @param format specifies the format in which the blobs will be returned. Values allowed are - ** BLOB_FORMAT_BASE64 and BLOB_FORMAT_HEX (default BLOB_FORMAT_BASE64). - ** @param cacheSize number of result-sets for the cache to try to maintain at any given time (default 10, minimum 2). - ** - ** @return RandomOrgCache - **/ + return this.createBlobCache(n, size, BLOB_FORMAT_BASE64, DEFAULT_CACHE_SIZE_SMALL); + } + + /** + * Get a RandomOrgCache to obtain random blobs. The RandomOrgCache can be polled for new + * results conforming to the output format of the input request. RandomOrgCache type is + * same as expected return value. + * + * @param n how many random blobs you need. {@code n*(cacheSize/2)} must be within the [1,100] range. + * @param size the size of each blob, measured in bits. Must be within the [1,1048576] range + * and must be divisible by 8. + * @param format specifies the format in which the blobs will be returned. Values allowed are + * BLOB_FORMAT_BASE64 and BLOB_FORMAT_HEX (default BLOB_FORMAT_BASE64). + * @param cacheSize number of result-sets for the cache to try to maintain at any given time + * (default 10, minimum 2). + * + * @return {@code RandomOrgCache} + */ public RandomOrgCache createBlobCache(int n, int size, String format, int cacheSize) { if (cacheSize < 2) { cacheSize = 2; @@ -1406,7 +5049,8 @@ public RandomOrgCache createBlobCache(int n, int size, String format, int bulkN = 0; // make requests more efficient by bulk-ordering from the server. - // initially set at cache_size/2, but cache will auto-shrink bulk request size if requests can't be fulfilled. + // initially set at cache_size/2, but cache will auto-shrink bulk request size + // if requests can't be fulfilled. bulkN = cacheSize/2; request.addProperty("n", bulkN*n); @@ -1419,7 +5063,15 @@ public RandomOrgCache createBlobCache(int n, int size, String format, return new RandomOrgCache( new JsonObjectInputCallable() { @Override - public JsonObject call() throws RandomOrgSendTimeoutException, RandomOrgKeyNotRunningError, RandomOrgInsufficientRequestsError, RandomOrgInsufficientBitsError, RandomOrgBadHTTPResponseException, RandomOrgRANDOMORGError, RandomOrgJSONRPCError, MalformedURLException, IOException { + public JsonObject call() throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { return RandomOrgClient.this.sendRequest(this.input); } }, new JsonObjectInputCallable() { @@ -1433,22 +5085,26 @@ public String[] call() { // Methods for accessing server usage statistics. - /** Return the (estimated) number of remaining API requests available to the client. If cached - ** usage info is older than ALLOWANCE_STATE_REFRESH_SECONDS fresh info is obtained from server. - ** If fresh info has to be obtained the following exceptions can be raised. - ** - ** @return number of requests remaining. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ + /** + * Return the (estimated) number of remaining API requests available to the client. If + * cached usage info is older than ALLOWANCE_STATE_REFRESH_SECONDS fresh info is obtained + * from server. If fresh info has to be obtained the following exceptions can be raised. + * + * @return number of requests remaining. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + */ public int getRequestsLeft() throws RandomOrgSendTimeoutException, RandomOrgKeyNotRunningError, RandomOrgInsufficientRequestsError, @@ -1464,22 +5120,26 @@ public int getRequestsLeft() throws RandomOrgSendTimeoutException, return this.requestsLeft; } - /** Return the (estimated) number of remaining true random bits available to the client. If cached - ** usage info is older than ALLOWANCE_STATE_REFRESH_SECONDS fresh info is obtained from server. - ** If fresh info has to be obtained the following exceptions can be raised. - ** - ** @return number of bits remaining. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ + /** + * Return the (estimated) number of remaining true random bits available to the client. + * If cached usage info is older than ALLOWANCE_STATE_REFRESH_SECONDS fresh info is obtained + * from server. If fresh info has to be obtained the following exceptions can be raised. + * + * @return number of bits remaining. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + */ public int getBitsLeft() throws RandomOrgSendTimeoutException, RandomOrgKeyNotRunningError, RandomOrgInsufficientRequestsError, @@ -1497,18 +5157,22 @@ public int getBitsLeft() throws RandomOrgSendTimeoutException, // Server communications & helper functions. - /** Issue a getUsage request to update bits and requests left. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ + /** + * Issue a getUsage request to update bits and requests left. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + */ private void getUsage() throws RandomOrgSendTimeoutException, RandomOrgKeyNotRunningError, RandomOrgInsufficientRequestsError, @@ -1517,8 +5181,7 @@ private void getUsage() throws RandomOrgSendTimeoutException, RandomOrgRANDOMORGError, RandomOrgJSONRPCError, MalformedURLException, - IOException { - + IOException { JsonObject request = new JsonObject(); request = this.generateKeyedRequest(request, GET_USAGE_METHOD); @@ -1526,15 +5189,15 @@ private void getUsage() throws RandomOrgSendTimeoutException, this.sendRequest(request); } - /** Add generic request parameters and API key to custom request. - ** - ** @param params custom parameters to generate request around. - ** @param method to send request to. - ** - ** @return fleshed out JSON request. - **/ - private JsonObject generateKeyedRequest(JsonObject params, String method) { - + /** + * Add generic request parameters and API key to custom request. + * + * @param params custom parameters to generate request around. + * @param method to send request to. + * + * @return fleshed out JSON request. + */ + private JsonObject generateKeyedRequest(JsonObject params, String method) { params.addProperty("apiKey", this.apiKey); JsonObject request = new JsonObject(); @@ -1547,15 +5210,15 @@ private JsonObject generateKeyedRequest(JsonObject params, String method) { return request; } - /** Add generic request parameters to custom request. - ** - ** @param params custom parameters to generate request around. - ** @param method to send request to. - ** - ** @return fleshed out JSON request. - **/ + /** + * Add generic request parameters to custom request. + * + * @param params custom parameters to generate request around. + * @param method to send request to. + * + * @return fleshed out JSON request. + */ private JsonObject generateRequest(JsonObject params, String method) { - JsonObject request = new JsonObject(); request.addProperty("jsonrpc", "2.0"); @@ -1566,14 +5229,14 @@ private JsonObject generateRequest(JsonObject params, String method) { return request; } - /** Extracts int[] from JSON response. - ** - ** @param response JSON from which to extract data. - ** - ** @return extracted int[]. - **/ - protected int[] extractInts(JsonObject response) { - + /** + * Extracts int[] from JSON response. + * + * @param response JSON from which to extract data. + * + * @return extracted int[]. + */ + protected int[] extractInts(JsonObject response) { JsonArray data = this.extractResponse(response); int[] randoms = new int[data.size()]; @@ -1584,14 +5247,50 @@ protected int[] extractInts(JsonObject response) { return randoms; } - /** Extracts double[] from JSON response. - ** - ** @param response JSON from which to extract data. - ** - ** @return extracted double[]. - **/ - protected double[] extractDoubles(JsonObject response) { + /** + * Extracts int[][] from JSON response. + * + * @param response JSON from which to extract data. + * + * @return extracted int[][]. + */ + protected int[][] extractIntSequences(JsonObject response) { + JsonArray data = this.extractResponse(response); + int[][] randoms = new int[data.size()][]; + + for (int i = 0; i < randoms.length; i++) { + randoms[i] = gson.fromJson(data.get(i), int[].class); + } + + return randoms; + } + + /** + * Extracts String[][] from JSON response. + * + * @param response JSON from which to extract data. + * + * @return extracted String[][]. + */ + protected String[][] extractIntSequencesString(JsonObject response) { + JsonArray data = this.extractResponse(response); + String[][] randoms = new String[data.size()][]; + + for (int i = 0; i < randoms.length; i++) { + randoms[i] = gson.fromJson(data.get(i), String[].class); + } + return randoms; + } + + /** + * Extracts double[] from JSON response. + * + * @param response JSON from which to extract data. + * + * @return extracted double[]. + */ + protected double[] extractDoubles(JsonObject response) { JsonArray data = this.extractResponse(response); double[] randoms = new double[data.size()]; @@ -1602,14 +5301,14 @@ protected double[] extractDoubles(JsonObject response) { return randoms; } - /** Extracts String[] from JSON response. - ** - ** @param response JSON from which to extract data. - ** - ** @return extracted String[]. - **/ - protected String[] extractStrings(JsonObject response) { - + /** + * Extracts String[] from JSON response. + * + * @param response JSON from which to extract data. + * + * @return extracted String[]. + */ + protected String[] extractStrings(JsonObject response) { JsonArray data = this.extractResponse(response); String[] randoms = new String[data.size()]; @@ -1620,14 +5319,14 @@ protected String[] extractStrings(JsonObject response) { return randoms; } - /** Extracts UUID[] from JSON response. - ** - ** @param response JSON from which to extract data. - ** - ** @return extracted UUID[]. - **/ - protected UUID[] extractUUIDs(JsonObject response) { - + /** + * Extracts UUID[] from JSON response. + * + * @param response JSON from which to extract data. + * + * @return extracted UUID[]. + */ + protected UUID[] extractUUIDs(JsonObject response) { JsonArray data = this.extractResponse(response); UUID[] randoms = new UUID[data.size()]; @@ -1638,23 +5337,41 @@ protected UUID[] extractUUIDs(JsonObject response) { return randoms; } - /** Gets random data as separate from response JSON. - ** - ** @param response JSON from which to extract data. - ** - ** @return JsonArray of random data. - **/ + /** + * Gets list of ticket objects from response JSON. + * + * @param response JSON from which to extract list of ticket objects. + * + * @return JsonObject[] of tickets. + */ + protected JsonObject[] extractTickets(JsonObject response) { + JsonArray t = (JsonArray) response.get("result"); + JsonObject[] tickets = new JsonObject[t.size()]; + for (int i = 0; i < tickets.length; i++) { + tickets[i] = t.get(i).getAsJsonObject(); + } + return tickets; + } + + /** + * Gets random data as separate from response JSON. + * + * @param response JSON from which to extract data. + * + * @return JsonArray of random data. + */ private JsonArray extractResponse(JsonObject response) { return response.get("result").getAsJsonObject().get("random").getAsJsonObject().get("data").getAsJsonArray(); } - /** Gets signing data from response JSON and add to result HashMap. - ** - ** @param response JSON from which to extract data. - ** @param result to add signing data to. - ** - ** @return the passed in result HasMap. - **/ + /** + * Gets signing data from response JSON and add to result HashMap. + * + * @param response JSON from which to extract data. + * @param result to add signing data to. + * + * @return the passed in result HashMap. + */ private HashMap extractSignedResponse(JsonObject response, HashMap result) { result.put("random", response.get("result").getAsJsonObject().get("random").getAsJsonObject()); result.put("signature", response.get("result").getAsJsonObject().get("signature").getAsString()); @@ -1662,33 +5379,48 @@ private HashMap extractSignedResponse(JsonObject response, HashM return result; } - /** Gets verification response as separate from response JSON. - ** - ** @param response JSON from which to extract verification response. - ** - ** @return verification success. - **/ + /** + * Gets verification response as separate from response JSON. + * + * @param response JSON from which to extract verification response. + * + * @return verification success. + */ private boolean extractVerificationResponse(JsonObject response) { - return response.get("result").getAsJsonObject().get("authenticity").getAsBoolean(); } + + /** + * Gets the response from the revealTickets method, i.e., the number + * of tickets that were revealed. + * + * @param response JSON from which to extract the revealTicket response. + * @return the number of tickets revealed. + */ + private int extractTicketCount(JsonObject response) { + return response.get("result").getAsJsonObject().get("ticketCount").getAsInt(); + } - /** Send request as determined by serialized boolean. - ** - ** @param request JSON to send. - ** - ** @return JsonObject response. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ + /** + * Send request as determined by serialized boolean. + * + * @param request JSON to send. + * + * @return JsonObject response. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + */ protected JsonObject sendRequest(JsonObject request) throws RandomOrgSendTimeoutException, RandomOrgKeyNotRunningError, RandomOrgInsufficientRequestsError, @@ -1702,31 +5434,37 @@ protected JsonObject sendRequest(JsonObject request) throws RandomOrgSendTimeout return this.serialized ? this.sendSerializedRequest(request) : this.sendUnserializedRequest(request); } - /** Immediate call to server. Networking is run on a separate thread as Android platform disallows networking on the main thread. - ** - ** @param request JSON to send. - ** - ** @return JsonObject response. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - private JsonObject sendUnserializedRequest(JsonObject request) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { + /** + * Immediate call to server. Networking is run on a separate thread as Android platform + * disallows networking on the main thread. + * + * @param request JSON to send. + * + * @return JsonObject response. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + */ + private JsonObject sendUnserializedRequest(JsonObject request) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { // Send request immediately. UnserializedRunnable r = new UnserializedRunnable(request); @@ -1737,7 +5475,8 @@ private JsonObject sendUnserializedRequest(JsonObject request) throws RandomOrgS try { Thread.sleep(50); } catch (InterruptedException e) { - LOGGER.log(Level.INFO, "Client interrupted while waiting for server to return a response."); + LOGGER.log(Level.INFO, "Client interrupted while waiting for server to " + + "return a response."); } } @@ -1750,7 +5489,7 @@ private JsonObject sendUnserializedRequest(JsonObject request) throws RandomOrgS return (JsonObject) r.getData().get("response"); } - /** Runnable for unserialized network calls. **/ + /** Runnable for unserialized network calls. */ private class UnserializedRunnable implements Runnable { private JsonObject request; @@ -1762,7 +5501,7 @@ public UnserializedRunnable(JsonObject request) { this.request = request; } - /* @see java.lang.Runnable#run() */ + /** @see java.lang.Runnable#run() */ @Override public void run() { this.data = RandomOrgClient.this.sendRequestCore(this.request); @@ -1774,34 +5513,38 @@ public HashMap getData() { } } - /** Add request to queue to be executed by networking thread one-by-one. - ** Method blocks until this request receives a response or times out. - ** - ** @param request JSON to send. - ** - ** @return JsonObject response. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ - private JsonObject sendSerializedRequest(JsonObject request) throws RandomOrgSendTimeoutException, - RandomOrgKeyNotRunningError, - RandomOrgInsufficientRequestsError, - RandomOrgInsufficientBitsError, - RandomOrgBadHTTPResponseException, - RandomOrgRANDOMORGError, - RandomOrgJSONRPCError, - MalformedURLException, - IOException { - - // Add request to the queue with it's own lock. + /** + * Add request to queue to be executed by networking thread one-by-one. Method blocks until + * this request receives a response or times out. + * + * @param request JSON to send. + * + * @return JsonObject response. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + */ + private JsonObject sendSerializedRequest(JsonObject request) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + // Creating request to add to the queue with it's own lock. Object requestLock = new Object(); HashMap data = new HashMap(); @@ -1810,13 +5553,15 @@ private JsonObject sendSerializedRequest(JsonObject request) throws RandomOrgSen data.put("response", null); data.put("exception", null); - synchronized (this.serializedQueue) { - this.serializedQueue.offer(data); - this.serializedQueue.notify(); - } - // Wait on the lock for the specified blocking timeout. synchronized (requestLock) { + + // Adding request to the queue + synchronized (this.serializedQueue) { + this.serializedQueue.offer(data); + this.serializedQueue.notify(); + } + try { if (this.blockingTimeout == -1) { requestLock.wait(); @@ -1824,16 +5569,19 @@ private JsonObject sendSerializedRequest(JsonObject request) throws RandomOrgSen requestLock.wait(this.blockingTimeout); } } catch (InterruptedException e) { - LOGGER.log(Level.INFO, "Client interrupted while waiting for request to be sent."); + LOGGER.log(Level.INFO, "Client interrupted while waiting for request to " + + "be sent."); } - // Lock has now either been notified or timed out. Examine data to determine which and react accordingly. + // Lock has now either been notified or timed out. Examine data to determine + // which and react accordingly. // Request wasn't sent in time, cancel and raise exception. if (data.get("response") == null && data.get("exception") == null) { data.put("request", null); - throw new RandomOrgSendTimeoutException("The maximum allowed blocking time of " + this.blockingTimeout - + "millis has been exceeded while waiting for a synchronous request to send."); + throw new RandomOrgSendTimeoutException("The maximum allowed blocking time of " + + this.blockingTimeout + "millis has been exceeded while waiting " + + "for a synchronous request to send."); } // Exception on sending request. @@ -1847,20 +5595,19 @@ private JsonObject sendSerializedRequest(JsonObject request) throws RandomOrgSen } /** Thread to synchronously send requests in queue. */ - protected void threadedRequestSending() { - + protected void threadedRequestSending() { // Thread to execute queued requests. while (true) { HashMap request; - synchronized (this.serializedQueue) { // Block and wait for a request. if (this.serializedQueue.isEmpty()) { try { this.serializedQueue.wait(); } catch (InterruptedException e) { - LOGGER.log(Level.INFO, "Client thread interrupted while waiting for a request to send."); + LOGGER.log(Level.INFO, "Client thread interrupted while waiting " + + "for a request to send."); } } @@ -1891,20 +5638,24 @@ protected void threadedRequestSending() { } } - /** Throw specific Exception types. - ** - ** @param e exception to throw. - ** - ** @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request can be sent. - ** @throws RandomOrgKeyNotRunningError API key has been stopped. - ** @throws RandomOrgInsufficientRequestsError API key's server requests allowance has been exceeded. - ** @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - ** @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. - ** @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws IOException @see java.io.IOException - **/ + /** + * Throw specific Exception types. + * + * @param e exception to throw. + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + */ private void throwException(Exception e) throws RandomOrgSendTimeoutException, RandomOrgKeyNotRunningError, RandomOrgInsufficientRequestsError, @@ -1936,28 +5687,30 @@ private void throwException(Exception e) throws RandomOrgSendTimeoutException, } } - /** Core send request function. - ** - ** @param request JSON to send. - ** - ** @return info on request success/response in a HashMap with one or other of the following entries: - ** "exception" : Exception - exception thrown, possible exception types: - ** RandomOrgSendTimeoutException - ** RandomOrgKeyNotRunningError - ** RandomOrgInsufficientRequestsError - ** RandomOrgInsufficientBitsError - ** RandomOrgBadHTTPResponseException - ** RandomOrgRANDOMORGError - ** RandomOrgJSONRPCError - ** MalformedURLException - ** IOException - ** "response" : JsonObject - response - **/ + /** + * Core send request function. + * + * @param request JSON to send. + * + * @return info on request success/response in a HashMap with one or other of the following entries: + * "exception" : Exception - exception thrown, possible exception types: + * RandomOrgSendTimeoutException + * RandomOrgKeyNotRunningError + * RandomOrgInsufficientRequestsError + * RandomOrgInsufficientBitsError + * RandomOrgBadHTTPResponseException + * RandomOrgRANDOMORGError + * RandomOrgJSONRPCError + * MalformedURLException + * IOException + * "response" : JsonObject - response + */ protected HashMap sendRequestCore(JsonObject request) { HashMap ret = new HashMap(); - // If a back-off is set, no more requests can be issued until the required back-off time is up. + // If a back-off is set, no more requests can be issued until the required + // back-off time is up. if (this.backoff != -1) { // Time not yet up, throw exception. @@ -1978,17 +5731,20 @@ protected HashMap sendRequestCore(JsonObject request) { wait = this.advisoryDelay - (System.currentTimeMillis() - this.lastResponseReceivedTime); } - // Wait the specified delay if necessary and if wait time is not longer than the set blocking timeout. + // Wait the specified delay if necessary and if wait time is not longer than the + // set blocking timeout. if (wait > 0) { if (this.blockingTimeout != -1 && wait > this.blockingTimeout) { - ret.put("exception", new RandomOrgSendTimeoutException("The server advisory delay of " + wait + - "millis is greater than the defined maximum allowed blocking time of " + this.blockingTimeout + "millis.")); + ret.put("exception", new RandomOrgSendTimeoutException("The server advisory delay of " + + wait + "millis is greater than the defined maximum allowed " + + "blocking time of " + this.blockingTimeout + "millis.")); return ret; } try { Thread.sleep(wait); } catch (InterruptedException e) { - LOGGER.log(Level.INFO, "Client interrupted while waiting for server mandated blocking time."); + LOGGER.log(Level.INFO, "Client interrupted while waiting for server " + + "mandated blocking time."); } } @@ -2018,7 +5774,7 @@ protected HashMap sendRequestCore(JsonObject request) { String message = error.get("message").getAsString(); // RandomOrgAllowanceExceededError, API key not running, backoff until midnight UTC, - // from RANDOM.ORG Errors: https://api.random.org/json-rpc/1/error-codes + // from RANDOM.ORG Errors: https://api.random.org/json-rpc/4/error-codes if (code == 402) { Calendar date = new GregorianCalendar(); @@ -2033,62 +5789,81 @@ protected HashMap sendRequestCore(JsonObject request) { ret.put("exception", new RandomOrgInsufficientRequestsError(this.backoffError)); return ret; } else if (code == 401) { - ret.put("exception", new RandomOrgKeyNotRunningError("Error " + code + ": " + message)); + ret.put("exception", new RandomOrgKeyNotRunningError("Error " + code + + ": " + message)); return ret; } else if (code == 403) { - ret.put("exception", new RandomOrgInsufficientBitsError("Error " + code + ": " + message, this.bitsLeft)); + ret.put("exception", new RandomOrgInsufficientBitsError("Error " + code + + ": " + message, this.bitsLeft)); return ret; - // RandomOrgRANDOMORGError from RANDOM.ORG Errors: https://api.random.org/json-rpc/1/error-codes + // RandomOrgRANDOMORGError from RANDOM.ORG Errors: + // https://api.random.org/json-rpc/4/error-codes } else if (RandomOrgClient.randomOrgErrors.contains(code)) { - ret.put("exception", new RandomOrgRANDOMORGError("Error " + code + ": " + message)); + ret.put("exception", new RandomOrgRANDOMORGError("Error " + code + + ": " + message, code)); return ret; - // RandomOrgJSONRPCError from JSON-RPC Errors: https://api.random.org/json-rpc/1/error-codes + // RandomOrgJSONRPCError from JSON-RPC Errors: + // https://api.random.org/json-rpc/4/error-codes } else { - ret.put("exception", new RandomOrgJSONRPCError("Error " + code + ": " + message)); + ret.put("exception", new RandomOrgJSONRPCError("Error " + code + + ": " + message)); return ret; } } - JsonObject result = response.get("result").getAsJsonObject(); + String method = request.get("method").getAsString(); - // Update usage statistics - if (result.has("requestsLeft")) { - this.requestsLeft = result.get("requestsLeft").getAsInt(); - this.bitsLeft = result.get("bitsLeft").getAsInt(); - } - - // Set new server advisory delay - synchronized (this.advisoryDelayLock) { - if (result.has("advisoryDelay")) { - this.advisoryDelay = result.get("advisoryDelay").getAsInt(); - } else { - // Use default if none from server. + if (method.equals("listTickets") || method.equals("createTickets") || method.equals("getTicket") || method.equals("getResult")) { + // Set default server advisory delay + synchronized (this.advisoryDelayLock) { this.advisoryDelay = RandomOrgClient.DEFAULT_DELAY; + this.lastResponseReceivedTime = System.currentTimeMillis(); } + } else { + JsonObject result = response.get("result").getAsJsonObject(); - this.lastResponseReceivedTime = System.currentTimeMillis(); + // Update usage statistics + if (result.has("requestsLeft")) { + this.requestsLeft = result.get("requestsLeft").getAsInt(); + this.bitsLeft = result.get("bitsLeft").getAsInt(); + } + + // Set new server advisory delay + synchronized (this.advisoryDelayLock) { + if (result.has("advisoryDelay")) { + this.advisoryDelay = result.get("advisoryDelay").getAsInt(); + } else { + // Use default if none from server. + this.advisoryDelay = RandomOrgClient.DEFAULT_DELAY; + } + + this.lastResponseReceivedTime = System.currentTimeMillis(); + } } ret.put("response", response); return ret; } - /** POST JSON to server and return JSON response. - ** - ** @param json request to post. - ** - ** @return JSON response. - ** - ** @throws IOException @see java.io.IOException - ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException - ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. - **/ - private JsonObject post(JsonObject json) throws IOException, MalformedURLException, RandomOrgBadHTTPResponseException { - - HttpsURLConnection con = (HttpsURLConnection) new URL("https://api.random.org/json-rpc/1/invoke").openConnection(); + /** + * POST JSON to server and return JSON response. + * + * @param json request to post. + * + * @return JSON response. + * + * @throws IOException @see java.io.IOException + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + */ + private JsonObject post(JsonObject json) throws IOException, + MalformedURLException, + RandomOrgBadHTTPResponseException { + HttpsURLConnection con = (HttpsURLConnection) new URL("https://api.random.org/json-rpc/4/invoke").openConnection(); con.setConnectTimeout(this.httpTimeout); // headers @@ -2116,11 +5891,298 @@ private JsonObject post(JsonObject json) throws IOException, MalformedURLExcepti } in.close(); - return new JsonParser().parse(response.toString()).getAsJsonObject(); + return JsonParser.parseString(response.toString()).getAsJsonObject(); + + // Alternative to avoid the deprecation warnings when using Gson 2.8.6+: + // return JsonParser.parseString(response.toString()).getAsJsonObject(); // ...or throw error } else { - throw new RandomOrgBadHTTPResponseException("Error " + responseCode + ": " + con.getResponseMessage()); + throw new RandomOrgBadHTTPResponseException("Error " + responseCode + ": " + + con.getResponseMessage()); + } + } + + /** Helper function for generateIntegers + * + * @param n how many random integers you need. Must be within the [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, 8, 10 + * and 16 (default 10). + * @param pregeneratedRandomization JsonObject to determine whether random values should be + * generated from a pregenerated, historical randomization ("date" or "id") instead + * of a one-time on-the-fly randomization giving true randomness ({@code null}). + * @param licenseData A JsonObject which allows the caller to include data of relevance to the + * license that is associated with the API Key. + * @param userData JsonObject that will be included in unmodified form. Its maximum size in + * encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * @param signed boolean representing whether the request uses Basic API (false) or signed + * API (true). + * + * @return JsonObject returned from the request + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + */ + private JsonObject integerMethod(int n, int min, int max, boolean replacement, int base, JsonObject pregeneratedRandomization, JsonObject licenseData, JsonObject userData, String ticketId, boolean signed) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + JsonObject request = new JsonObject(); + + request.addProperty("n", n); + request.addProperty("min", min); + request.addProperty("max", max); + request.addProperty("replacement", replacement); + request.addProperty("base", base); + request.add("pregeneratedRandomization", pregeneratedRandomization); + + if (signed) { + request.add("licenseData", licenseData); + request.add("userData", userData); + request.addProperty("ticketId", ticketId); + + request = this.generateKeyedRequest(request, SIGNED_INTEGER_METHOD); + } else { + request = this.generateKeyedRequest(request, INTEGER_METHOD); + } + + return this.sendRequest(request); + } + + /** + * Helper function for generateIntegerSequences + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length the length of each array of random integers requested. Must be within the + * [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, 8, 10 + * and 16 (default 10). + * @param pregeneratedRandomization JsonObject to determine whether random values should be + * generated from a pregenerated, historical randomization ("date" or "id") instead + * of a one-time on-the-fly randomization giving true randomness ({@code null}). + * @param licenseData A JsonObject which allows the caller to include data of relevance to the + * license that is associated with the API Key. + * @param userData JsonObject that will be included in unmodified form. Its maximum size in + * encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * @param signed boolean representing whether the request uses Basic API (false) or signed + * API (true). + * + * @return JsonObject returned from the request + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + */ + private JsonObject integerSequencesMethod(int n, int length, int min, int max, boolean replacement, int base, JsonObject pregeneratedRandomization, JsonObject licenseData, JsonObject userData, String ticketId, boolean signed) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + JsonObject request = new JsonObject(); + + request.addProperty("n", n); + request.addProperty("length", length); + request.addProperty("min", min); + request.addProperty("max", max); + request.addProperty("replacement", replacement); + request.addProperty("base", base); + request.add("pregeneratedRandomization", pregeneratedRandomization); + + if (signed) { + request.add("licenseData", licenseData); + request.add("userData", userData); + request.addProperty("ticketId", ticketId); + request = this.generateKeyedRequest(request, SIGNED_INTEGER_SEQUENCE_METHOD); + } else { + request = this.generateKeyedRequest(request, INTEGER_SEQUENCE_METHOD); + } + + return this.sendRequest(request); + } + + /** + * Helper function for generateIntegerSequences with array ([]) parameters + * + * @param n how many arrays of random integers you need. Must be within the [1,1e3] range. + * @param length the length of each array of random integers requested. Must be within the + * [1,1e4] range. + * @param min the lower boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param max the upper boundary for the range from which the random numbers will be picked. + * Must be within the [-1e9,1e9] range. + * @param replacement specifies whether the random numbers should be picked with replacement. + * If true, the resulting numbers may contain duplicate values, otherwise the numbers + * will all be unique (default true). + * @param base the base that will be used to display the numbers. Values allowed are 2, 8, 10 + * and 16 (default 10). + * @param pregeneratedRandomization JsonObject to determine whether random values should be + * generated from a pregenerated, historical randomization ("date" or "id") instead + * of a one-time on-the-fly randomization giving true randomness ({@code null}). + * @param licenseData A JsonObject which allows the caller to include data of relevance to the + * license that is associated with the API Key. + * @param userData JsonObject that will be included in unmodified form. Its maximum size in + * encoded (String) form is 1,000 characters (default null). + * @param ticketId A string with ticket identifier obtained via the {@link #createTickets(int n, + * boolean showResult) createTickets} method. Specifying a value for {@code ticketId} will + * cause RANDOM.ORG to record that the ticket was used to generate the requested random + * values. Each ticket can only be used once (default null). + * @param signed boolean representing whether the request uses Basic API (false) or signed + * API (true). + * + * @return JsonObject returned from the request + * + * @throws RandomOrgSendTimeoutException blocking timeout is exceeded before the request + * can be sent. + * @throws RandomOrgKeyNotRunningError API key has been stopped. + * @throws RandomOrgInsufficientRequestsError API key's server requests allowance has + * been exceeded. + * @throws RandomOrgInsufficientBitsError API key's server bits allowance has been exceeded. + * @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received. + * @throws RandomOrgRANDOMORGError server returns a RANDOM.ORG Error. + * @throws RandomOrgJSONRPCError server returns a JSON-RPC Error. + * @throws MalformedURLException in the unlikely event something goes wrong with URL + * creation. @see java.net.MalformedURLException + * @throws IOException @see java.io.IOException + */ + private JsonObject integerSequencesMethod(int n, int[] length, int[] min, int[] max, boolean[] replacement, int[] base, JsonObject pregeneratedRandomization, JsonObject licenseData, JsonObject userData, String ticketId, boolean signed) + throws RandomOrgSendTimeoutException, + RandomOrgKeyNotRunningError, + RandomOrgInsufficientRequestsError, + RandomOrgInsufficientBitsError, + RandomOrgBadHTTPResponseException, + RandomOrgRANDOMORGError, + RandomOrgJSONRPCError, + MalformedURLException, + IOException { + JsonObject request = new JsonObject(); + + request.addProperty("n", n); + request.add("length", gson.toJsonTree(length).getAsJsonArray()); + request.add("min", gson.toJsonTree(min).getAsJsonArray()); + request.add("max", gson.toJsonTree(max).getAsJsonArray()); + request.add("replacement", gson.toJsonTree(replacement).getAsJsonArray()); + request.add("base", gson.toJsonTree(base).getAsJsonArray()); + request.add("pregeneratedRandomization", pregeneratedRandomization); + + if (signed) { + request.add("licenseData", licenseData); + request.add("userData", userData); + request.addProperty("ticketId", ticketId); + request = this.generateKeyedRequest(request, SIGNED_INTEGER_SEQUENCE_METHOD); + } else { + request = this.generateKeyedRequest(request, INTEGER_SEQUENCE_METHOD); + } + + return this.sendRequest(request); + } + + /** Helper function for createIntegerSequenceCache with array ([]) parameters */ + private int min(int[] a) { + int[] min2 = Arrays.copyOf(a, a.length); + Arrays.sort(min2); + return min2[0]; + } + + /** Helper function for createIntegerSequenceCache with array ([]) parameters */ + private int max(int[] a) { + int[] max2 = Arrays.copyOf(a, a.length); + Arrays.sort(max2); + return max2[max2.length-1]; + } + + /** Helper function for createIntegerSequenceCache with array ([]) parameters */ + private int[] adjust(int[] a, int n) { + int[] adjusted = new int[n]; + for (int i = 1, k = 0; i <= n / a.length; i++) { + for (int j = 0; j < a.length; j++) { + adjusted[k++] = a[j]; + } + } + return adjusted; + } + + /** Helper function for createIntegerSequenceCache with array ([]) parameters */ + private boolean[] adjust(boolean[] a, int n) { + boolean[] adjusted = new boolean[n]; + for (int i = 1, k = 0; i <= n / a.length; i++) { + for (int j = 0; j < a.length; j++) { + adjusted[k++] = a[j]; + } } + return adjusted; + } + + /** Helper function to make a string URL-safe (base64 and percent-encoding) */ + public String formatURL(String s) { + String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$"; + boolean isBase64 = Pattern.matches(base64Pattern, s); + + if (!isBase64) { + s = Base64.getEncoder().encodeToString((s).getBytes()); + } + + // Percent-Encoding as described in RFC 3986 for PHP + s = s.replace("=", "%3D"); + s = s.replace("+", "%2B"); + s = s.replace("/", "%2F"); + + return s; + } + + /** Helper function to create a HTML input tag */ + public static String inputHTML(String type, String name, String value) { + return ""; } } \ No newline at end of file diff --git a/RandomJSONRPC/src/org/random/api/exception/RandomOrgBadHTTPResponseException.java b/RandomJSONRPC/src/org/random/api/exception/RandomOrgBadHTTPResponseException.java index a254bef..8abdafe 100644 --- a/RandomJSONRPC/src/org/random/api/exception/RandomOrgBadHTTPResponseException.java +++ b/RandomJSONRPC/src/org/random/api/exception/RandomOrgBadHTTPResponseException.java @@ -1,14 +1,16 @@ package org.random.api.exception; -/** Exception raised by the RandomOrgClient class when the connection - ** doesn't return a HTTP 200 OK response. - **/ +/** + * Exception raised by the RandomOrgClient class when the connection + * doesn't return a HTTP 200 OK response. + */ public class RandomOrgBadHTTPResponseException extends RuntimeException { - /** Constructs a new exception with the specified detail message. - ** - ** @param message @see java.lang.Exception#Exception(java.lang.String) - **/ + /** + * Constructs a new exception with the specified detail message. + * + * @param message @see java.lang.Exception#Exception(java.lang.String) + */ public RandomOrgBadHTTPResponseException(String message) { super(message); } diff --git a/RandomJSONRPC/src/org/random/api/exception/RandomOrgInsufficientBitsError.java b/RandomJSONRPC/src/org/random/api/exception/RandomOrgInsufficientBitsError.java index bbd9a2f..faf453a 100644 --- a/RandomJSONRPC/src/org/random/api/exception/RandomOrgInsufficientBitsError.java +++ b/RandomJSONRPC/src/org/random/api/exception/RandomOrgInsufficientBitsError.java @@ -1,29 +1,30 @@ package org.random.api.exception; -/** Exception raised by the RandomOrgClient class when its API key's - ** request has exceeded its remaining server bits allowance. If the - ** client is currently issuing large requests it may be possible to - ** succeed with smaller requests. Use the client's getBitsLeft() call - ** or the getBits() in this class to help determine if an alternative - ** request size is appropriate. - **/ +/** + * Exception raised by the RandomOrgClient class when its API key's + * request has exceeded its remaining server bits allowance. If the + * client is currently issuing large requests it may be possible to + * succeed with smaller requests. Use the client's getBitsLeft() call + * or the getBits() in this class to help determine if an alternative + * request size is appropriate. + */ public class RandomOrgInsufficientBitsError extends RuntimeException { private int bits = -1; - /** Constructs a new exception with the specified detail message. - ** - ** @param message @see java.lang.Exception#Exception(java.lang.String) - ** @param bits remaining just before error thrown - **/ + /** + * Constructs a new exception with the specified detail message. + * + * @param message @see java.lang.Exception#Exception(java.lang.String) + * @param bits remaining just before error thrown + */ public RandomOrgInsufficientBitsError(String message, int bits) { super(message); this.bits = bits; } - /** @return bits remaining just before error. - **/ + /** @return bits remaining just before error. */ public int getBits() { return this.bits; } diff --git a/RandomJSONRPC/src/org/random/api/exception/RandomOrgInsufficientRequestsError.java b/RandomJSONRPC/src/org/random/api/exception/RandomOrgInsufficientRequestsError.java index 6b5adfc..77d3001 100644 --- a/RandomJSONRPC/src/org/random/api/exception/RandomOrgInsufficientRequestsError.java +++ b/RandomJSONRPC/src/org/random/api/exception/RandomOrgInsufficientRequestsError.java @@ -1,17 +1,19 @@ package org.random.api.exception; -/** Exception raised by the RandomOrgClient class when its API key's - ** server requests allowance has been exceeded. This indicates that a - ** back-off until midnight UTC is in effect, before which no requests - ** will be sent by the client as no meaningful server responses will - ** be returned. - **/ +/** + * Exception raised by the RandomOrgClient class when its API key's + * server requests allowance has been exceeded. This indicates that a + * back-off until midnight UTC is in effect, before which no requests + * will be sent by the client as no meaningful server responses will + * be returned. + */ public class RandomOrgInsufficientRequestsError extends RuntimeException { - /** Constructs a new exception with the specified detail message. - ** - ** @param message @see java.lang.Exception#Exception(java.lang.String) - **/ + /** + * Constructs a new exception with the specified detail message. + * + * @param message @see java.lang.Exception#Exception(java.lang.String) + */ public RandomOrgInsufficientRequestsError(String message) { super(message); } diff --git a/RandomJSONRPC/src/org/random/api/exception/RandomOrgJSONRPCError.java b/RandomJSONRPC/src/org/random/api/exception/RandomOrgJSONRPCError.java index 79147b6..ce17846 100644 --- a/RandomJSONRPC/src/org/random/api/exception/RandomOrgJSONRPCError.java +++ b/RandomJSONRPC/src/org/random/api/exception/RandomOrgJSONRPCError.java @@ -1,16 +1,18 @@ package org.random.api.exception; -/** Exception raised by the RandomOrgClient class when the server - ** returns a JSON-RPC Error. - ** - ** @see https://api.random.org/json-rpc/1/error-codes - **/ +/** + * Exception raised by the RandomOrgClient class when the server + * returns a JSON-RPC Error. + * + * @see https://api.random.org/json-rpc/4/error-codes + */ public class RandomOrgJSONRPCError extends RuntimeException { - /** Constructs a new exception with the specified detail message. - ** - ** @param message @see java.lang.Exception#Exception(java.lang.String) - **/ + /** + * Constructs a new exception with the specified detail message. + * + * @param message @see java.lang.Exception#Exception(java.lang.String) + */ public RandomOrgJSONRPCError(String message) { super(message); } diff --git a/RandomJSONRPC/src/org/random/api/exception/RandomOrgKeyNotRunningError.java b/RandomJSONRPC/src/org/random/api/exception/RandomOrgKeyNotRunningError.java index 181a015..6c1d648 100644 --- a/RandomJSONRPC/src/org/random/api/exception/RandomOrgKeyNotRunningError.java +++ b/RandomJSONRPC/src/org/random/api/exception/RandomOrgKeyNotRunningError.java @@ -1,15 +1,17 @@ package org.random.api.exception; -/** Exception raised by the RandomOrgClient class when its API key - ** has been stopped. Requests will not complete while API key is - ** in the stopped state. - **/ +/** + * Exception raised by the RandomOrgClient class when its API key + * has been stopped. Requests will not complete while API key is + * in the stopped state. + */ public class RandomOrgKeyNotRunningError extends RuntimeException { - /** Constructs a new exception with the specified detail message. - ** - ** @param message @see java.lang.Exception#Exception(java.lang.String) - **/ + /** + * Constructs a new exception with the specified detail message. + * + * @param message @see java.lang.Exception#Exception(java.lang.String) + */ public RandomOrgKeyNotRunningError(String message) { super(message); } diff --git a/RandomJSONRPC/src/org/random/api/exception/RandomOrgRANDOMORGError.java b/RandomJSONRPC/src/org/random/api/exception/RandomOrgRANDOMORGError.java index 0d2c5eb..68fd263 100644 --- a/RandomJSONRPC/src/org/random/api/exception/RandomOrgRANDOMORGError.java +++ b/RandomJSONRPC/src/org/random/api/exception/RandomOrgRANDOMORGError.java @@ -1,17 +1,40 @@ package org.random.api.exception; -/** Exception raised by the RandomOrgClient class when the server - ** returns a RANDOM.ORG Error. - ** - ** @see https://api.random.org/json-rpc/1/error-codes - **/ +/** + * Exception raised by the RandomOrgClient class when the server + * returns a RANDOM.ORG Error. + * + * @see https://api.random.org/json-rpc/4/error-codes + */ public class RandomOrgRANDOMORGError extends RuntimeException { - - /** Constructs a new exception with the specified detail message. - ** - ** @param message @see java.lang.Exception#Exception(java.lang.String) - **/ + int code = -1; + + /** + * Constructs a new exception with the specified detail message. + * + * @param message @see java.lang.Exception#Exception(java.lang.String) + */ public RandomOrgRANDOMORGError(String message) { super(message); } + + /** + * Constructs a new exception with the specified detail message and + * error code. + * + * @param message @see java.lang.Exception#Exception(java.lang.String) + * @param code The error code as specified here: https://api.random.org/json-rpc/4/error-codes + */ + public RandomOrgRANDOMORGError(String message, int code) { + super(message); + this.code = code; + } + + /** + * Returns the error code (or -1 if none was specified). See here for + * more information: https://api.random.org/json-rpc/4/error-codes + */ + public int getCode() { + return code; + } } \ No newline at end of file diff --git a/RandomJSONRPC/src/org/random/api/exception/RandomOrgSendTimeoutException.java b/RandomJSONRPC/src/org/random/api/exception/RandomOrgSendTimeoutException.java index cfd78b8..03e7b4b 100644 --- a/RandomJSONRPC/src/org/random/api/exception/RandomOrgSendTimeoutException.java +++ b/RandomJSONRPC/src/org/random/api/exception/RandomOrgSendTimeoutException.java @@ -1,14 +1,16 @@ package org.random.api.exception; -/** Exception raised by the RandomOrgClient class when its set - ** blocking timeout is exceeded before the request can be sent. - **/ +/** + * Exception raised by the RandomOrgClient class when its set + * blocking timeout is exceeded before the request can be sent. + */ public class RandomOrgSendTimeoutException extends RuntimeException { - /** Constructs a new exception with the specified detail message. - ** - ** @param message @see java.lang.Exception#Exception(java.lang.String) - **/ + /** + * Constructs a new exception with the specified detail message. + * + * @param message @see java.lang.Exception#Exception(java.lang.String) + */ public RandomOrgSendTimeoutException(String message) { super(message); } diff --git a/RandomJSONRPC/src/org/random/test/RandomOrgClientBasicTest.java b/RandomJSONRPC/src/org/random/test/RandomOrgClientBasicTest.java index 33027de..e428190 100644 --- a/RandomJSONRPC/src/org/random/test/RandomOrgClientBasicTest.java +++ b/RandomJSONRPC/src/org/random/test/RandomOrgClientBasicTest.java @@ -1,715 +1,2029 @@ package org.random.test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import java.util.HashMap; +import java.util.Map; import java.util.NoSuchElementException; import java.util.UUID; -import org.junit.Assert; import org.junit.BeforeClass; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ErrorCollector; import org.random.api.RandomOrgCache; import org.random.api.RandomOrgClient; import org.random.api.exception.RandomOrgRANDOMORGError; +import com.google.gson.Gson; import com.google.gson.JsonObject; -/** A set of tests for RandomOrgClient.java - ** @author Anders Haahr - **/ +import static org.hamcrest.Matchers.*; + +/** + * A set of tests for RandomOrgClient.java + */ public class RandomOrgClientBasicTest { - private static RandomOrgClient roc, roc2; + @Rule + public ErrorCollector collector = new ErrorCollector(); + + private static RandomOrgClient[] rocs = new RandomOrgClient[2]; private static final String API_KEY_1 = "YOUR_API_KEY_HERE"; private static final String API_KEY_2 = "YOUR_API_KEY_HERE"; private static final int BIT_QUOTA = 1000000; + private static final int[] LENGTH = {3, 4, 5, 6}; + private static final int[] MIN = {0, 10, 20, 30}; + private static final int[] MAX = {40, 50, 60, 70}; + private static final boolean[] REPLACEMENT = {false, true, false, true}; + private static final int[] BASE = {2, 8, 10, 16}; + + private static JsonObject userData = new JsonObject(); + private static JsonObject identifier = new JsonObject(); + private static JsonObject date = new JsonObject(); + @BeforeClass public static void testSetup() { - roc = RandomOrgClient.getRandomOrgClient(API_KEY_1, 3000, 120000, false); - roc2 = RandomOrgClient.getRandomOrgClient(API_KEY_2); + rocs[0] = RandomOrgClient.getRandomOrgClient(API_KEY_1, 5000, 120000, false); + rocs[1] = RandomOrgClient.getRandomOrgClient(API_KEY_2); + + userData.addProperty("Test", "Text"); + userData.addProperty("Test2", "Text2"); + + identifier.addProperty("id", "foo"); + date.addProperty("date", "2020-01-01"); } @Test public void testInfo() { - try { - assertTrue(roc.getBitsLeft() >= 0); - assertTrue(roc.getRequestsLeft() >= 0); - - assertTrue(roc2.getBitsLeft() >= 0); - assertTrue(roc2.getRequestsLeft() >= 0); - - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(client(i), roc.getBitsLeft(), greaterThanOrEqualTo(0)); + collector.checkThat(client(i), roc.getRequestsLeft(), greaterThanOrEqualTo(0)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } + @Test public void testAPIKeyDuplication() { RandomOrgClient dupe = RandomOrgClient.getRandomOrgClient(API_KEY_1); - assertTrue(!roc.equals(roc2)); - assertTrue(roc.equals(dupe)); + collector.checkThat("RandomOrgClient roc1 should not be the same as " + + "RandomOrgClient roc2", rocs[0].equals(rocs[1]), equalTo(false)); + collector.checkThat("RandomOrgClient roc1 and RandomOrgClient dupe " + + "should be the same", rocs[0].equals(dupe), equalTo(true)); } + @Test - public void testPositiveGetBitsLeft_1(){ - try { - int bitsLeft = roc.getBitsLeft(); - assertTrue(0 <= bitsLeft && bitsLeft <= BIT_QUOTA); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGetBitsLeft() { + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + int bitsLeft = roc.getBitsLeft(); + collector.checkThat(client(i), bitsLeft, greaterThanOrEqualTo(0)); + collector.checkThat(client(i) + i, bitsLeft, lessThanOrEqualTo(BIT_QUOTA)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } + // Test Errors + @Test - public void testPositiveGetBitsLeft_2(){ - try { - int bitsLeft = roc2.getBitsLeft(); - assertTrue(0 <= bitsLeft && bitsLeft <= BIT_QUOTA); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testNegativeErrorMessage202() { + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + roc.generateIntegers(100000, 0, 10); + collector.addError(new Error(errorMessage(i))); + } catch(RandomOrgRANDOMORGError e) { + negativeErrorHandler(e, 202); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e))); + } + i++; } } - - // Test Errors @Test - public void testNegativeErrorMessage202(){ - try{ - roc.generateIntegers(100000, 0, 10); - Assert.fail("should have thrown RandomOrgRANDOMORGError"); - } catch(RandomOrgRANDOMORGError e) { - System.out.println(e.getMessage()); - } catch (Exception e) { - Assert.fail("should have thrown RandomOrgRANDOMORGError, instead threw " + e.getClass().getName()); + public void testNegativeErrorMessage203() { + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + roc.generateIntegerSequences(3, LENGTH, MIN, MAX); + collector.addError(new Error(errorMessage(i))); + } catch(RandomOrgRANDOMORGError e) { + negativeErrorHandler(e, 203); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e))); + } + i++; } - try{ - roc2.generateIntegers(100000, 0, 10); - Assert.fail("should have thrown RandomOrgRANDOMORGError"); - } catch(RandomOrgRANDOMORGError e) { - System.out.println(e.getMessage()); - } catch (Exception e) { - Assert.fail("should have thrown RandomOrgRANDOMORGError, instead threw " + e.getClass().getName()); + } + + @Test + public void testNegativeErrorMessage204() { + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + roc.generateIntegerSequences(4, new int[] {1}, MIN, MAX); + collector.addError(new Error(errorMessage(i))); + } catch(RandomOrgRANDOMORGError e) { + negativeErrorHandler(e, 204); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e))); + } + i++; } } @Test - public void testNegativeErrorMessage203(){ - try{ - roc.generateIntegers(10, 0, 1000000001); - Assert.fail("should have thrown RandomOrgRANDOMORGError"); - } catch(RandomOrgRANDOMORGError e) { - System.out.println(e.getMessage()); - } catch (Exception e) { - Assert.fail("should have thrown RandomOrgRANDOMORGError, instead threw " + e.getClass().getName()); + public void testNegativeErrorMessage300() { + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + roc.generateIntegers(10, 10, 0); + collector.addError(new Error(errorMessage(i))); + } catch(RandomOrgRANDOMORGError e) { + negativeErrorHandler(e, 300); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e))); + } + i++; } - try{ - roc2.generateIntegers(10, 0, 1000000001); - Assert.fail("should have thrown RandomOrgRANDOMORGError"); - } catch(RandomOrgRANDOMORGError e) { - System.out.println(e.getMessage()); - } catch (Exception e) { - Assert.fail("should have thrown RandomOrgRANDOMORGError, instead threw " + e.getClass().getName()); + } + + @Test + public void testNegativeErrorMessage301() { + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + roc.generateIntegers(20, 0, 10, false); + collector.addError(new Error(errorMessage(i))); + } catch(RandomOrgRANDOMORGError e) { + negativeErrorHandler(e, 301); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e))); + } + i++; } } @Test - public void testNegativeErrorMessage300(){ - try{ - roc.generateIntegers(10, 10, 0); - Assert.fail("should have thrown RandomOrgRANDOMORGError"); + public void testNegativeErrorMessage400() { + try { + RandomOrgClient rpc2 = RandomOrgClient.getRandomOrgClient("ffffffff-ffff-ffff-ffff-ffffffffffff"); + rpc2.generateIntegers(1, 0, 1); + collector.addError(new Error(errorMessage())); } catch(RandomOrgRANDOMORGError e) { - System.out.println(e.getMessage()); + negativeErrorHandler(e, 400); } catch (Exception e) { - Assert.fail("should have thrown RandomOrgRANDOMORGError, instead threw " + e.getClass().getName()); + collector.addError(new Error(errorMessage(e))); } - try{ - roc2.generateIntegers(10, 10, 0); - Assert.fail("should have thrown RandomOrgRANDOMORGError"); - } catch(RandomOrgRANDOMORGError e) { - System.out.println(e.getMessage()); - } catch (Exception e) { - Assert.fail("should have thrown RandomOrgRANDOMORGError, instead threw " + e.getClass().getName()); + } + + @Test + public void testNegativeErrorMessage420() { + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + roc.generateSignedIntegers(5, 0, 10, false, 10, null, "ffffffffffffffff"); + collector.addError(new Error(errorMessage(i))); + } catch(RandomOrgRANDOMORGError e) { + negativeErrorHandler(e, 420); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e))); + } + i++; } } - + @Test - public void testNegativeErrorMessage301(){ - try{ - roc.generateIntegers(20, 0, 10, false); - Assert.fail("should have thrown RandomOrgRANDOMORGError"); - } catch(RandomOrgRANDOMORGError e) { - System.out.println(e.getMessage()); - } catch (Exception e) { - Assert.fail("should have thrown RandomOrgRANDOMORGError, instead threw " + e.getClass().getName()); + public void testNegativeErrorMessage421() { + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + roc.generateSignedIntegers(5, 0, 10, false, 10, null, "d5b8f6d03f99a134"); + collector.addError(new Error(errorMessage(i))); + } catch(RandomOrgRANDOMORGError e) { + negativeErrorHandler(e, 421); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e))); + } + i++; } - try{ - roc2.generateIntegers(20, 0, 10, false); - Assert.fail("should have thrown RandomOrgRANDOMORGError"); - } catch(RandomOrgRANDOMORGError e) { - System.out.println(e.getMessage()); - } catch (Exception e) { - Assert.fail("should have thrown RandomOrgRANDOMORGError, instead threw " + e.getClass().getName()); + } + + @Test + public void testNegativeErrorMessage422() { + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + + roc.generateSignedIntegers(5, 0, 10, false, 10, null, ticketId); + roc.generateSignedIntegers(5, 0, 10, false, 10, null, ticketId); + + collector.addError(new Error(errorMessage(i))); + } catch(RandomOrgRANDOMORGError e) { + negativeErrorHandler(e, 422); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e))); + } + i++; } } - + @Test - public void testNegativeErrorMessage400(){ - try{ - RandomOrgClient rpc2 = RandomOrgClient.getRandomOrgClient("ffffffff-ffff-ffff-ffff-ffffffffffff"); - rpc2.generateIntegers(1, 0, 1); - Assert.fail("should have thrown RandomOrgRANDOMORGError"); - } catch(RandomOrgRANDOMORGError e) { - System.out.println(e.getMessage()); - } catch (Exception e) { - Assert.fail("should have thrown RandomOrgRANDOMORGError, instead threw " + e.getClass().getName()); + public void testNegativeErrorMessage426() { + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + roc.revealTickets(ticketId); + + collector.addError(new Error(errorMessage(i))); + } catch(RandomOrgRANDOMORGError e) { + negativeErrorHandler(e, 426); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e))); + } + i++; } } // Test Functions - + @Test - public void testPositiveGenerateInteger_1(){ - try { - assertNotNull(roc.generateIntegers(10, 0, 10)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGenerateInteger_1() { + // Testing generateIntgers(int n, in min, int max) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateIntegers(10, 0, 10), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } - try { - assertNotNull(roc2.generateIntegers(10, 0, 10)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testPositiveGenerateInteger_2() { + // Testing generateIntgers(int n, in min, int max, boolean replacement) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateIntegers(10, 0, 10, false), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } - + @Test - public void testPositiveGenerateInteger_2(){ - try { - assertNotNull(roc.generateIntegers(10, 0, 10, false)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGenerateInteger_3() { + // Testing generateIntgers(int n, in min, int max, boolean replacement, int base) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateIntegers(10, 0, 10, false, 16), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } - try { - assertNotNull(roc2.generateIntegers(10, 0, 10, false)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testPositiveGenerateInteger_4() { + // Testing generateIntgers(int n, in min, int max, boolean replacement, + // JsonObject pregeneratedRandomization) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + int[] response = roc.generateIntegers(10, 0, 10, false, identifier); + collector.checkThat(response, notNullValue()); + + int[] response2 = roc.generateIntegers(10, 0, 10, false, identifier); + collector.checkThat(response, equalTo(response2)); + + response = roc.generateIntegers(10, 0, 10, false, date); + collector.checkThat(response, notNullValue()); + + response2 = roc.generateIntegers(10, 0, 10, false, date); + collector.checkThat(response, equalTo(response2)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } - + @Test - public void testPositiveGenerateDecimalFractions_1(){ - try { - assertNotNull(roc.generateDecimalFractions(10, 5)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGenerateInteger_5() { + // Testing generateIntgers(int n, in min, int max, boolean replacement, int base, + // JsonObject pregeneratedRandomization) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String[] response = roc.generateIntegers(10, 0, 10, false, 16, identifier); + collector.checkThat(response, notNullValue()); + + String[] response2 = roc.generateIntegers(10, 0, 10, false, 16, identifier); + collector.checkThat(response, equalTo(response2)); + + response = roc.generateIntegers(10, 0, 10, false, 16, date); + collector.checkThat(response, notNullValue()); + + response2 = roc.generateIntegers(10, 0, 10, false, 16, date); + collector.checkThat(response, equalTo(response2)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } - try { - assertNotNull(roc2.generateDecimalFractions(10, 5)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testPositiveGenerateIntegerSequences_1() { + // Testing generateIntegerSequences(int n, int length, int min, int max) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateIntegerSequences(3, 5, 0, 10), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } - + @Test - public void testPositiveGenerateDecimalFractions_2(){ - try { - assertNotNull(roc.generateDecimalFractions(10, 5, false)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGenerateIntegerSequences_2() { + // Testing generateIntegerSequences(int n, int length, int min, int max, boolean replacement) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateIntegerSequences(3, 5, 0, 10, false), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } - try { - assertNotNull(roc2.generateDecimalFractions(10, 5, false)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testPositiveGenerateIntegerSequences_3() { + // Testing generateIntegerSequences(int n, int length, int min, int max, boolean replacement, int base) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateIntegerSequences(3, 5, 0, 10, false, 16), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } - + @Test - public void testPositiveGenerateGaussians(){ - try { - assertNotNull(roc.generateGaussians(10, 3.41d, 2.1d, 4)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGenerateIntegerSequences_4() { + // Testing generateIntegerSequences(int n, int length, int min, int max, boolean replacement, + // JsonObject pregeneratedRandomization) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + int[][] response = roc.generateIntegerSequences(3, 5, 0, 10, false, identifier); + collector.checkThat(response, notNullValue()); + + int[][] response2 = roc.generateIntegerSequences(3, 5, 0, 10, false, identifier); + collector.checkThat(response, equalTo(response2)); + + response = roc.generateIntegerSequences(3, 5, 0, 10, false, date); + collector.checkThat(response, notNullValue()); + + response2 = roc.generateIntegerSequences(3, 5, 0, 10, false, date); + collector.checkThat(response, equalTo(response2)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } - try { - assertNotNull(roc2.generateGaussians(10, 3.41d, 2.1d, 4)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testPositiveGenerateIntegerSequences_5() { + // Testing generateIntegerSequences(int n, int length, int min, int max, boolean replacement, + // int base, JsonObject pregeneratedRandomization) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String[][] response = roc.generateIntegerSequences(3, 5, 0, 10, false, 16, identifier); + collector.checkThat(response, notNullValue()); + + String[][] response2 = roc.generateIntegerSequences(3, 5, 0, 10, false, 16, identifier); + collector.checkThat(response, equalTo(response2)); + + response = roc.generateIntegerSequences(3, 5, 0, 10, false, 16, date); + collector.checkThat(response, notNullValue()); + + response2 = roc.generateIntegerSequences(3, 5, 0, 10, false, 16, date); + collector.checkThat(response, equalTo(response2)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } - + @Test - public void testPositiveGenerateStrings_1(){ - try { - assertNotNull(roc.generateStrings(10, 5, "abcd")); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGenerateIntegerSequences_6() { + // Testing generateIntegerSequences(int n, int[] length, int[] min, int[] max) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateIntegerSequences(4, LENGTH, MIN, MAX), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } - try { - assertNotNull(roc2.generateStrings(10, 5, "abcd")); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testPositiveGenerateIntegerSequences_7() { + // Testing generateIntegerSequences(int n, int[] length, int[] min, + // int[] max, boolean[] replacement) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateIntegerSequences(4, LENGTH, MIN, MAX, REPLACEMENT), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } - + @Test - public void testPositiveGenerateStrings_2(){ - try { - assertNotNull(roc.generateStrings(10, 5, "abcd", false)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGenerateIntegerSequences_8() { + // Testing generateIntegerSequences(int n, int[] length, int[] min, + // int[] max, boolean[] replacement, int[] base) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateIntegerSequences(4, LENGTH, MIN, MAX, REPLACEMENT, BASE), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } - try { - assertNotNull(roc2.generateStrings(10, 5, "abcd", false)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testPositiveGenerateIntegerSequences_9() { + // Testing generateIntegerSequences(int n, int[] length, int[] min, int[] max, + // boolean[] replacement, JsonObject pregeneratedRandomization) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + int[][] response = roc.generateIntegerSequences(4, LENGTH, MIN, MAX, + REPLACEMENT, identifier); + collector.checkThat(response, notNullValue()); + + int[][] response2 = roc.generateIntegerSequences(4, LENGTH, MIN, MAX, + REPLACEMENT, identifier); + collector.checkThat(response, equalTo(response2)); + + response = roc.generateIntegerSequences(4, LENGTH, MIN, MAX, + REPLACEMENT, date); + collector.checkThat(response, notNullValue()); + + response2 = roc.generateIntegerSequences(4, LENGTH, MIN, MAX, + REPLACEMENT, date); + collector.checkThat(response, equalTo(response2)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateIntegerSequences_10() { + // Testing generateIntegerSequences(int n, int[] length, int[] min, int[] max, + // boolean[] replacement, int[] base, JsonObject pregenerateRandomization) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String[][] response = roc.generateIntegerSequences(4, LENGTH, MIN, MAX, + REPLACEMENT, BASE, identifier); + collector.checkThat(response, notNullValue()); + + String[][] response2 = roc.generateIntegerSequences(4, LENGTH, MIN, MAX, + REPLACEMENT, BASE, identifier); + collector.checkThat(response, equalTo(response2)); + + response = roc.generateIntegerSequences(4, LENGTH, MIN, MAX, + REPLACEMENT, BASE, date); + collector.checkThat(response, notNullValue()); + + response2 = roc.generateIntegerSequences(4, LENGTH, MIN, MAX, + REPLACEMENT, BASE, date); + collector.checkThat(response, equalTo(response2)); + + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } @Test - public void testPositiveGenerateUUIDs(){ - try { - assertNotNull(roc.generateUUIDs(10)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGenerateDecimalFractions_1() { + // Testing generateDecimalFractions(int n, int decimalPlaces) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateDecimalFractions(10, 5), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i ++; } - try { - assertNotNull(roc2.generateUUIDs(10)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testPositiveGenerateDecimalFractions_2() { + // Testing generateDecimalFractions(int n, int decimalPlaces, boolean replacement) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateDecimalFractions(10, 5, false), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateDecimalFractions_3() { + // Testing generateDecimalFractions(int n, int decimalPlaces, boolean replacement, + // JsonObject pregeneratedRandomization) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + double[] response = roc.generateDecimalFractions(10, 5, false, identifier); + collector.checkThat(response, notNullValue()); + + double[] response2 = roc.generateDecimalFractions(10, 5, false, identifier); + collector.checkThat(response, equalTo(response2)); + + response = roc.generateDecimalFractions(10, 5, false, date); + collector.checkThat(response, notNullValue()); + + response2 = roc.generateDecimalFractions(10, 5, false, date); + collector.checkThat(response, equalTo(response2)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateGaussians_1() { + // Testing generateGaussians(int n, double mean, double standardDeviation, + // double significantDigits) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateGaussians(10, 3.41d, 2.1d, 4), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateGaussians_2() { + // Testing generateGaussians(int n, double mean, double standardDeviation, + // double significantDigits, JsonObject pregeneratedRandomization) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + double[] response = roc.generateGaussians(10, 3.41d, 2.1d, 4, identifier); + collector.checkThat(response, notNullValue()); + + double[] response2 = roc.generateGaussians(10, 3.41d, 2.1d, 4, identifier); + collector.checkThat(response, equalTo(response2)); + + response = roc.generateGaussians(10, 3.41d, 2.1d, 4, date); + collector.checkThat(response, notNullValue()); + + response2 = roc.generateGaussians(10, 3.41d, 2.1d, 4, date); + collector.checkThat(response, equalTo(response2)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } @Test - public void testPositiveGenerateBlobs_1(){ - try { - assertNotNull(roc.generateBlobs(10, 16)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGenerateStrings_1() { + // Testing generateStrings(int n, int length, String characters) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateStrings(10, 5, "abcd"), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } - try { - assertNotNull(roc2.generateBlobs(10, 16)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testPositiveGenerateStrings_2() { + // Testing generateStrings(int n, int length, String characters, + // boolean replacement) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateStrings(10, 5, "abcd", false), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateStrings_3() { + // Testing generateStrings(int n, int length, String characters, + // boolean replacement, JsonObject pregeneratedRandomization) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String[] response = roc.generateStrings(10, 5, "abcd", false, identifier); + collector.checkThat(response, notNullValue()); + + String[] response2 = roc.generateStrings(10, 5, "abcd", false, identifier); + collector.checkThat(response, equalTo(response2)); + + response = roc.generateStrings(10, 5, "abcd", false, date); + collector.checkThat(response, notNullValue()); + + response2 = roc.generateStrings(10, 5, "abcd", false, date); + collector.checkThat(response, equalTo(response2)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateUUIDs_1() { + // Testing generateUUIDs(int n) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateUUIDs(10), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateUUIDs_2() { + // Testing generateUUIDs(int n, JsonObject pregeneratedRandomization) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + UUID[] response = roc.generateUUIDs(10, identifier); + collector.checkThat(response, notNullValue()); + + UUID[] response2 = roc.generateUUIDs(10, identifier); + collector.checkThat(response, equalTo(response2)); + + response = roc.generateUUIDs(10, date); + collector.checkThat(response, notNullValue()); + + response2 = roc.generateUUIDs(10, date); + collector.checkThat(response, equalTo(response2)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } @Test - public void testPositiveGenerateBlobs_2(){ - try { - assertNotNull(roc.generateBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGenerateBlobs_1() { + // Testing generateBlobs(int n, int size) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateBlobs(10, 16), notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } - try { - assertNotNull(roc2.generateBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX)); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testPositiveGenerateBlobs_2() { + // Testing generateBlobs(int n, int size, String format) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + collector.checkThat(roc.generateBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX), + notNullValue()); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateBlobs_3() { + // Testing generateBlobs(int n, int size, String format) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String[] response = roc.generateBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX, + identifier); + collector.checkThat(response, notNullValue()); + + String[] response2 = roc.generateBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX, + identifier); + collector.checkThat(response, equalTo(response2)); + + response = roc.generateBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX, + date); + collector.checkThat(response, notNullValue()); + + response2 = roc.generateBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX, + date); + collector.checkThat(response, equalTo(response2)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } // Test Functions (Signed) @Test - public void testPositiveGenerateSignedInteger_1(){ - try { - HashMap o = roc.generateSignedIntegers(10, 0, 10); - - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - - assertTrue(o.get("data").getClass().equals(int[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); - - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGenerateSignedInteger_1() { + // Testing generateSignedStrings(int n, int min, int max) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegers(10, 0, 10); + + this.signedValueTester(roc, i, o, int[].class); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } - try { - HashMap o = roc2.generateSignedIntegers(10, 0, 10); - - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); + } + + @Test + public void testPositiveGenerateSignedInteger_2() { + // Testing generateSignedStrings(int n, int min, int max, boolean replacement) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegers(10, 0, 10, false); + + this.signedValueTester(roc, i, o, int[].class); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedInteger_3() { + // Testing generateSignedIntegers(int n, int min, int max, boolean replacement, + // int base, JsonObject userData) -- decimal base + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegers(10, 0, 10, false, 10, userData); + + this.signedValueTester(roc, i, o, int[].class, true); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedInteger_4() { + // Testing generateSignedIntegers(int n, int min, int max, boolean replacement, + // int base, JsonObject userData) -- non-decimal base + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegers(10, 0, 10, false, 16, userData); + + this.signedValueTester(roc, i, o, String[].class, true); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedInteger_5() { + // Testing generateSignedIntegers(int n, int min, int max, boolean replacement, + // int base, JsonObject userData, String ticketId) -- decimal base + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + HashMap o = roc.generateSignedIntegers(10, 0, 10, false, 10, userData, ticketId); + + this.signedValueTester(roc, i, o, int[].class, true, ticketId); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedInteger_6() { + // Testing generateSignedIntegers(int n, int min, int max, boolean replacement, + // int base, JsonObject userData, String ticketId) -- non-decimal base + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + HashMap o = roc.generateSignedIntegers(10, 0, 10, false, 16, userData, ticketId); + + this.signedValueTester(roc, i, o, String[].class, true, ticketId); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedInteger_7() { + // Testing generateSignedIntegers(int n, int min, int max, boolean replacement, + // int base, JsonObject pregeneratedRandomization, JsonObject licenseData, + // JsonObject userData, String ticketId) + // -- decimal base + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegers(10, 0, 10, false, 10, identifier, null, + userData, null); + + this.signedValueTester(roc, i, o, int[].class, true); + + HashMap o2 = roc.generateSignedIntegers(10, 0, 10, false, 10, identifier, null, + userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + + o = roc.generateSignedIntegers(10, 0, 10, false, 10, date, null, userData, null); + o2 = roc.generateSignedIntegers(10, 0, 10, false, 10, date, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedInteger_8() { + // Testing generateSignedIntegers(int n, int min, int max, boolean replacement, + // int base, JsonObject pregeneratedRandomization, JsonObject licensseData, + // JsonObject userData, String ticketId) + // -- non-decimal base + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegers(10, 0, 10, false, 16, identifier, null, + userData, null); + + this.signedValueTester(roc, i, o, String[].class, true); + + HashMap o2 = roc.generateSignedIntegers(10, 0, 10, false, 16, identifier, null, + userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + + o = roc.generateSignedIntegers(10, 0, 10, false, 16, date, null, userData, null); + o2 = roc.generateSignedIntegers(10, 0, 10, false, 16, date, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_1() { + // Testing generateSignedIntegerSequences(int n, int length, int min, int max) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegerSequences(3, 5, 0, 10); + + this.signedValueTester(roc, i, o, int[][].class); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_2() { + // Testing generateSignedIntegerSequences(int n, int length, int min, int max, + // boolean replacement, int base, JsonObject userData) + // -- decimal base + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegerSequences(3, 5, 0, 10, false, 10, userData); + + this.signedValueTester(roc, i, o, int[][].class, true); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_3() { + // Testing generateSignedIntegerSequences(int n, int length, int min, int max, + // boolean replacement, int base, JsonObject userData) + // -- non-decimal base + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegerSequences(3, 5, 0, 10, false, 16, userData); + + this.signedValueTester(roc, i, o, String[][].class, true); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_4_decimal() { + // Testing generateSignedIntegerSequences(int n, int length, int min, int max, + // boolean replacement, int base, JsonObject userData, String ticketId) + // -- decimal base + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + HashMap o = roc.generateSignedIntegerSequences(3, 5, 0, 10, false, 10, + userData, ticketId); + + this.signedValueTester(roc, i, o, int[][].class, true, ticketId); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_4_nondecimal() { + // Testing generateSignedIntegerSequences(int n, int length, int min, int max, + // boolean replacement, int base, JsonObject userData, String ticketId) + // -- non-decimal base + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + HashMap o = roc.generateSignedIntegerSequences(3, 5, 0, 10, false, 16, + userData, ticketId); + + this.signedValueTester(roc, i, o, String[][].class, true, ticketId); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_5_decimal() { + // Testing generateSignedIntegerSequences(int n, int length, int min, int max, + // boolean replacement, int base, JsonObject pregeneratedRandomization, + // JsonObject licenseData, JsonObject userData, String ticketId) + // -- decimal base + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegerSequences(3, 5, 0, 10, false, 10, + identifier, null, userData, null); + + this.signedValueTester(roc, i, o, int[][].class, true); + + HashMap o2 = roc.generateSignedIntegerSequences(3, 5, 0, 10, false, 10, + identifier, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + + o = roc.generateSignedIntegerSequences(3, 5, 0, 10, false, 10, date, null, userData, null); + o2 = roc.generateSignedIntegerSequences(3, 5, 0, 10, false, 10, date, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_5_nondecimal() { + // Testing generateSignedIntegerSequences(int n, int length, int min, int max, + // boolean replacement, int base, JsonObject pregeneratedRandomization, + // JsonObject licenseData, JsonObject userData, String ticketId) + // -- non-decimal base + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegerSequences(3, 5, 0, 10, false, 16, + identifier, null, userData, null); + + this.signedValueTester(roc, i, o, String[][].class, true); + + HashMap o2 = roc.generateSignedIntegerSequences(3, 5, 0, 10, false, 16, + identifier, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + + o = roc.generateSignedIntegerSequences(3, 5, 0, 10, false, 16, date, null, userData, null); + o2 = roc.generateSignedIntegerSequences(3, 5, 0, 10, false, 16, date, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_6() { + // Testing generateSignedIntegerSequences(int n, int[] length, int[] min, int[] max) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegerSequences(4, LENGTH, MIN, MAX); + + this.signedValueTester(roc, i, o, int[][].class); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_7() { + // Testing generateSignedIntegerSequences(int n, int[] length, int[] min, int[] max, + // boolean[] replacement, int[] base, JsonObject userData) + // -- decimal + int[] decimalBase = {10, 10, 10, 10}; + int i = 1; + + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegerSequences(4, LENGTH, MIN, MAX, REPLACEMENT, decimalBase, userData); + + this.signedValueTester(roc, i, o, int[][].class, true); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_8() { + // Testing generateSignedIntegerSequences(int n, int[] length, int[] min, int[] max, + // boolean[] replacement, int[] base, JsonObject userData) + // -- non-decimal + int i = 1; + + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegerSequences(4, LENGTH, MIN, MAX, REPLACEMENT, BASE, userData); + + this.signedValueTester(roc, i, o, String[][].class, true); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_9_decimal() { + // Testing generateSignedIntegerSequences(int n, int[] length, int[] min, int[] max, + // boolean[] replacement, int[] base, JsonObject userData, String ticketId) + // -- decimal + int[] decimalBase = {10, 10, 10, 10}; + int i = 1; + + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + HashMap o = roc.generateSignedIntegerSequences(4, LENGTH, MIN, + MAX, REPLACEMENT, decimalBase, userData, ticketId); + + this.signedValueTester(roc, i, o, int[][].class, true, ticketId); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_9_nondecimal() { + // Testing generateSignedIntegerSequences(int n, int[] length, int[] min, int[] max, + // boolean[] replacement, int[] base, JsonObject userData, String ticketId) + // -- non-decimal + int i = 1; + + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + HashMap o = roc.generateSignedIntegerSequences(4, LENGTH, MIN, MAX, REPLACEMENT, + BASE, userData, ticketId); + + this.signedValueTester(roc, i, o, String[][].class, true, ticketId); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_10_decimal() { + // Testing generateSignedIntegerSequences(int n, int[] length, int[] min, int[] max, + // boolean[] replacement, int[] base, JsonObject pregeneratedRandomization, + // JsonObject licenseData, JsonObject userData, String ticketId) + // -- decimal + int[] decimalBase = {10, 10, 10, 10}; + int i = 1; + + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegerSequences(4, LENGTH, MIN, + MAX, REPLACEMENT, decimalBase, identifier, null, userData, null); + + this.signedValueTester(roc, i, o, int[][].class, true); + + HashMap o2 = roc.generateSignedIntegerSequences(4, LENGTH, MIN, + MAX, REPLACEMENT, decimalBase, identifier, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + + o = roc.generateSignedIntegerSequences(4, LENGTH, MIN, MAX, REPLACEMENT, decimalBase, + date, null, userData, null); + o2 = roc.generateSignedIntegerSequences(4, LENGTH, MIN, MAX, REPLACEMENT, decimalBase, + date, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedIntegerSequences_10_nondecimal() { + // Testing generateSignedIntegerSequences(int n, int[] length, int[] min, int[] max, + // boolean[] replacement, int[] base, JsonObject userData, String ticketId) + // -- non-decimal + int i = 1; + + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegerSequences(4, LENGTH, MIN, MAX, REPLACEMENT, + BASE, identifier, null, userData, null); + + this.signedValueTester(roc, i, o, String[][].class, true); + + HashMap o2 = roc.generateSignedIntegerSequences(4, LENGTH, MIN, MAX, REPLACEMENT, + BASE, identifier, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + + o = roc.generateSignedIntegerSequences(4, LENGTH, MIN, MAX, REPLACEMENT, BASE, + date, null, userData, null); + o2 = roc.generateSignedIntegerSequences(4, LENGTH, MIN, MAX, REPLACEMENT, BASE, + date, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedDecimalFractions_1() { + // Testing generateSignedDecimalFractions(int n, int decimalPlaces) + int i = 1; + + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedDecimalFractions(10, 5); - assertTrue(o.get("data").getClass().equals(int[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); + this.signedValueTester(roc, i, o, double[].class); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedDecimalFractions_2() { + // Testing generateSignedDecimalFractions(int n, int decimalPlaces, boolean replacement) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedDecimalFractions(10, 5, false); - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + this.signedValueTester(roc, i, o, double[].class); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedDecimalFractions_3() { + // Testing generateSignedDecimalFractions(int n, int decimalPlaces, + // boolean replacement, JsonObject userData) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedDecimalFractions(10, 5, false, userData); + + this.signedValueTester(roc, i, o, double[].class, true); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedDecimalFractions_4() { + // Testing generateSignedDecimalFractions(int n, int decimalPlaces, + // boolean replacement, JsonObject userData, String ticketId) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + HashMap o = roc.generateSignedDecimalFractions(10, 5, false, + userData, ticketId); + + this.signedValueTester(roc, i, o, double[].class, true, ticketId); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedDecimalFractions_5() { + // Testing generateSignedDecimalFractions(int n, int decimalPlaces, + // boolean replacement, JsonObject pregeneratedRandomization, + // JsonObject licenseData, JsonObject userData, String ticketId) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedDecimalFractions(10, 5, false, + identifier, null, userData, null); + + this.signedValueTester(roc, i, o, double[].class, true); + + HashMap o2 = roc.generateSignedDecimalFractions(10, 5, false, + identifier, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + + o = roc.generateSignedDecimalFractions(10, 5, false, date, null, userData, null); + o2 = roc.generateSignedDecimalFractions(10, 5, false, date, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedGaussians_1() { + // Testing generateSignedGaussians(int n, double mean, double standardDeviation, int significantDigits) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedGaussians(10, 3.41d, 2.1d, 4); + + this.signedValueTester(roc, i, o, double[].class); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedGaussians_2() { + // Testing generateSignedGaussians(int n, double mean, double standardDeviation, + // int significantDigits, JsonObject userData) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedGaussians(10, 3.41d, 2.1d, 4, userData); + + this.signedValueTester(roc, i, o, double[].class, true); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedGaussians_3() { + // Testing generateSignedGaussians(int n, double mean, double standardDeviation, + // int significantDigits, JsonObject userData, String ticketId) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + HashMap o = roc.generateSignedGaussians(10, 3.41d, 2.1d, 4, + userData, ticketId); + + this.signedValueTester(roc, i, o, double[].class, true, ticketId); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedGaussians_4() { + // Testing generateSignedGaussians(int n, double mean, double standardDeviation, + // int significantDigits, JsonObject pregeneratedRandomization, JsonObject licenseData, + // JsonObject userData, String ticketId) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedGaussians(10, 3.41d, 2.1d, 4, + identifier, null, userData, null); + + this.signedValueTester(roc, i, o, double[].class, true); + + HashMap o2 = roc.generateSignedGaussians(10, 3.41d, 2.1d, 4, + identifier, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + + o = roc.generateSignedGaussians(10, 3.41d, 2.1d, 4, date, null, userData, null); + o2 = roc.generateSignedGaussians(10, 3.41d, 2.1d, 4, date, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedStrings_1() { + // Testing generateSignedStrings(int n, int length, String characters) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedStrings(10, 5, "abcd"); + + this.signedValueTester(roc, i, o, String[].class); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedStrings_2() { + // Testing generateSignedStrings(int n, int length, String characters, boolean replacement) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedStrings(10, 5, "abcd", false); + + this.signedValueTester(roc, i, o, String[].class); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + public void testPositiveGenerateSignedStrings_3() { + // Testing generateSignedStrings(int n, int length, String characters, + // boolean replacement, JsonObject userData) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedStrings(10, 5, "abcd", false, userData); + + this.signedValueTester(roc, i, o, String[].class, true); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedStrings_4() { + // Testing generateSignedStrings(int n, int length, String characters, + // boolean replacement, JsonObject userData, String ticketId) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + HashMap o = roc.generateSignedStrings(10, 5, "abcd", false, + userData, ticketId); + + this.signedValueTester(roc, i, o, String[].class, true, ticketId); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedStrings_5() { + // Testing generateSignedStrings(int n, int length, String characters, + // boolean replacement, JsonObject pregeneratedRandomization, + // JsonObject licenseData,JsonObject userData, String ticketId) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedStrings(10, 5, "abcd", false, + identifier, null, userData, null); + + this.signedValueTester(roc, i, o, String[].class, true); + + HashMap o2 = roc.generateSignedStrings(10, 5, "abcd", false, + identifier, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + + o = roc.generateSignedStrings(10, 5, "abcd", false, date, null, userData, null); + o2 = roc.generateSignedStrings(10, 5, "abcd", false, date, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedUUIDs_1() { + // Testing generateSignedUUIDs(int n) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedUUIDs(10); + + this.signedValueTester(roc, i, o, UUID[].class); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedUUIDs_2() { + // Testing generateSignedUUIDs(int n, JsonObject userData) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedUUIDs(10, userData); + + this.signedValueTester(roc, i, o, UUID[].class, true); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedUUIDs_3() { + // Testing generateSignedUUIDs(int n, JsonObject userData, String ticketId) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + HashMap o = roc.generateSignedUUIDs(10, userData, ticketId); + + this.signedValueTester(roc, i, o, UUID[].class, true, ticketId); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedUUIDs_4() { + // Testing generateSignedUUIDs(int n, JsonObject pregeneratedRandomization, + // JsonObject licenseData, JsonObject userData, String ticketId) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedUUIDs(10, identifier, null, userData, null); + + this.signedValueTester(roc, i, o, UUID[].class, true); + + HashMap o2 = roc.generateSignedUUIDs(10, identifier, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + + o = roc.generateSignedUUIDs(10, date, null, userData, null); + o2 = roc.generateSignedUUIDs(10, date, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedBlobs_1() { + // Testing generateSignedBlobs(int n, int size) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedBlobs(10, 16); + + this.signedValueTester(roc, i, o, String[].class); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedBlobs_2() { + // Testing generateSignedBlobs(int n, int size, String format) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX); + + this.signedValueTester(roc, i, o, String[].class); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedBlobs_3() { + // Testing generateSignedBlobs(int n, int size, String format, JsonObject userData) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX, userData); + + this.signedValueTester(roc, i, o, String[].class, true); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; + } + } + + @Test + public void testPositiveGenerateSignedBlobs_4() { + // Testing generateSignedBlobs(int n, int size, String format, JsonObject userData, + // String ticketId) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String ticketId = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + HashMap o = roc.generateSignedBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX, + userData, ticketId); + + this.signedValueTester(roc, i, o, String[].class, true, ticketId); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } - + @Test - public void testPositiveGenerateSignedInteger_2(){ - try { - HashMap o = roc.generateSignedIntegers(10, 0, 10, false); - - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - - assertTrue(o.get("data").getClass().equals(int[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); - - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); - } - try { - HashMap o = roc2.generateSignedIntegers(10, 0, 10, false); - - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - - assertTrue(o.get("data").getClass().equals(int[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); - - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testPositiveGenerateSignedBlobs_5() { + // Testing generateSignedBlobs(int n, int size, String format, + // JsonObject pregeneratedRandomization, JsonObject licenseData, + // JsonObject userData, String ticketId) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX, + identifier, null, userData, null); + + this.signedValueTester(roc, i, o, String[].class, true); + + HashMap o2 = roc.generateSignedBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX, + identifier, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + + o = roc.generateSignedBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX, + date, null, userData, null); + o2 = roc.generateSignedBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX, + date, null, userData, null); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } - + + // Test additional functions + @Test - public void testPositiveGenerateSignedDecimalFractions_1(){ - try { - HashMap o = roc.generateSignedDecimalFractions(10, 5); - - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - - assertTrue(o.get("data").getClass().equals(double[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); - - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testGetResult() { + // Testing getResult(int serialNumber) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + HashMap o = roc.generateSignedIntegers(10, 0, 10); + HashMap o2 = roc.getResult(((JsonObject)o.get("random")).get("serialNumber").getAsInt()); + + JsonObject data = ((JsonObject)o2.get("random")).getAsJsonObject(); + int[] response = new Gson().fromJson(data.get("data"), int[].class); + + collector.checkThat((int[]) o.get("data"), equalTo(response)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } - try { - HashMap o = roc2.generateSignedDecimalFractions(10, 5); - - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - - assertTrue(o.get("data").getClass().equals(double[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); - - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testCreateTickets() { + // Testing createTickets(int n, boolean showResult) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + JsonObject[] result = roc.createTickets(1, true); + collector.checkThat(result[0], notNullValue()); + + result = roc.createTickets(1, false); + collector.checkThat(result[0], notNullValue()); + + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } - + @Test - public void testPositiveGenerateSignedDecimalFractions_2(){ - try { - HashMap o = roc.generateSignedDecimalFractions(10, 5, false); - - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - - assertTrue(o.get("data").getClass().equals(double[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); - - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testRevealTicketsSingle() { + // Testing revealTickets(String ticketId) - using and revealing + // a single ticket. + int i = 1; + for (RandomOrgClient roc : rocs) { + revealTicket(roc, i, 1); + i++; } - try { - HashMap o = roc2.generateSignedDecimalFractions(10, 5, false); - - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - - assertTrue(o.get("data").getClass().equals(double[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); - - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testRevealTicketsMultiple() { + // Testing revealTickets(String ticketId) - using and revealing + // a chain of tickets. + int i = 1; + for (RandomOrgClient roc : rocs) { + revealTicket(roc, i, 3); + i++; } } - + @Test - public void testPositiveGenerateSignedGaussians(){ - try { - HashMap o = roc.generateSignedGaussians(10, 3.41d, 2.1d, 4); - - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - - assertTrue(o.get("data").getClass().equals(double[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); - - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + public void testListTickets() { + // Testing listTickets(String type) for each type + int i = 1; + String[] types = {"singleton", "head", "tail"}; + JsonObject[] tickets = new JsonObject[0]; + for (RandomOrgClient roc : rocs) { + for (String t : types) { + try { + tickets = roc.listTickets(t); + if (tickets != null && tickets.length > 0) { + JsonObject ticket = tickets[0]; + if (t.equals("singleton")) { + collector.checkThat(ticket.get("nextTicketId").isJsonNull(), equalTo(true)); + collector.checkThat(ticket.get("previousTicketId").isJsonNull(), equalTo(true)); + } else if (t.equals("head")) { + collector.checkThat(ticket.get("nextTicketId").isJsonNull(), equalTo(false)); + collector.checkThat(ticket.get("previousTicketId").isJsonNull(), equalTo(true)); + } else if (t.equals("tail")) { + collector.checkThat(ticket.get("nextTicketId").isJsonNull(), equalTo(true)); + collector.checkThat(ticket.get("previousTicketId").isJsonNull(), equalTo(false)); + } else { + collector.addError(new Error("Invalid ticket type. ")); + } + } + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + } + i++; } - try { - HashMap o = roc2.generateSignedGaussians(10, 3.41d, 2.1d, 4); - - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - - assertTrue(o.get("data").getClass().equals(double[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); - - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + } + + @Test + public void testGetTicket() { + // Testing getTicket(String ticketId) + int i = 1; + for (RandomOrgClient roc : rocs) { + try { + String ticket = roc.createTickets(1, true)[0].get("ticketId").getAsString(); + String hiddenTicket = roc.createTickets(1, false)[0].get("ticketId").getAsString(); + + // unused ticket with showResult == true + HashMap o2 = roc.getTicket(ticket); + collector.checkThat(((JsonObject) o2.get("result")).get("result").isJsonNull(), equalTo(true)); + + // used ticket with showResult == true + HashMap o = roc.generateSignedIntegers(3, 0, 10, false, 10, null, ticket); + o2 = roc.getTicket(ticket); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + + // unused ticket with showResult == false + o2 = roc.getTicket(hiddenTicket); + collector.checkThat(((JsonObject) o2.get("result")).get("usedTime").isJsonNull(), equalTo(true)); + + // used ticket with showResult == false + roc.generateSignedIntegers(3, 0, 10, false, 10, null, hiddenTicket); + o2 = roc.getTicket(hiddenTicket); + collector.checkThat(((JsonObject) o2.get("result")).has("result"), equalTo(false)); + collector.checkThat(((JsonObject) o2.get("result")).get("usedTime").isJsonNull(), equalTo(false)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + i++; } } + // Test Functions (Cache) + @Test - public void testPositiveGenerateSignedStrings_1(){ + public void testIntegerCache_1() { + // Testing createIntegerCache(int n, int min, int max) + RandomOrgCache c = rocs[0].createIntegerCache(5, 0, 10); + c.stop(); + try { - HashMap o = roc.generateSignedStrings(10, 5, "abcd"); - - assertNotNull(o); + c.get(); + collector.addError(new Error("should have thrown NoSuchElementException")); + } catch (NoSuchElementException e) {} - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); + collector.checkThat(c.isPaused(), equalTo(true)); + c.resume(); - assertTrue(o.get("data").getClass().equals(String[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); + int[] got = null; - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + // Testing RandomOrgCache function get() + while (got == null) { + try { + got = c.get(); + } catch (NoSuchElementException e) { + try { + Thread.sleep(50); + } catch (InterruptedException e1) { + collector.addError(new Error("shouldn't have been interrupted!")); + } + } } - try { - HashMap o = roc2.generateSignedStrings(10, 5, "abcd"); - assertNotNull(o); + collector.checkThat(got, notNullValue()); - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); + got = null; - assertTrue(o.get("data").getClass().equals(String[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); + // Testing RandomOrgCache info functions + collector.checkThat(c.getCachedValues(), greaterThan(0)); + collector.checkThat((int)c.getUsedBits(), greaterThan(0)); + collector.checkThat((int)c.getUsedRequests(), greaterThan(0)); - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + // Testing RandomOrgCache function getOrWait() + while (got == null) { + try { + got = c.getOrWait(); + } catch (NoSuchElementException e) { + try { + Thread.sleep(50); + } catch (InterruptedException e1) { + collector.addError(new Error("shouldn't have been interrupted!")); + } + } catch (Exception e) { + collector.addError(new Error("should have returned a value")); + } } } - + @Test - public void testPositiveGenerateSignedStrings_2(){ - try { - HashMap o = roc.generateSignedStrings(10, 5, "abcd", false); - - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - - assertTrue(o.get("data").getClass().equals(String[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); + public void testIntegerCache_2() { + // Testing createIntegerCache(int n, int min, int max, boolean replacement, + // int base, int cacheSize) + RandomOrgCache c = rocs[0].createIntegerCache(5, 50, 100, false, 16, 5); + c.stop(); - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); - } try { - HashMap o = roc2.generateSignedStrings(10, 5, "abcd", false); - - assertNotNull(o); + c.get(); + collector.addError(new Error("should have thrown NoSuchElementException")); + } catch (NoSuchElementException e) {} - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); + collector.checkThat(c.isPaused(), equalTo(true)); + c.resume(); - assertTrue(o.get("data").getClass().equals(String[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); + String[] got = null; - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + // Testing RandomOrgCache function get() + while (got == null) { + try { + got = c.get(); + } catch (NoSuchElementException e) { + try { + Thread.sleep(50); + } catch (InterruptedException e1) { + collector.addError(new Error("shouldn't have been interrupted!")); + } + } } + + collector.checkThat(got, notNullValue()); } - + @Test - public void testPositiveGenerateSignedUUIDs(){ + public void testIntegerSequenceCache_1() { + // Testing createIntegerSequenceCache(int n, int length int min, int max) + RandomOrgCache c = rocs[0].createIntegerSequenceCache(2, 5, 0, 10); + c.stop(); + try { - HashMap o = roc.generateSignedUUIDs(10); - - assertNotNull(o); + c.get(); + collector.addError(new Error("should have thrown NoSuchElementException")); + } catch (NoSuchElementException e) {} - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); + c.resume(); - assertTrue(o.get("data").getClass().equals(UUID[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); + int[][] got = null; - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + while (got == null) { + try { + got = c.get(); + } catch (NoSuchElementException e) { + try { + Thread.sleep(50); + } catch (InterruptedException e1) { + collector.addError(new Error("shouldn't have been interrupted!")); + } + } } - try { - HashMap o = roc2.generateSignedUUIDs(10); - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - - assertTrue(o.get("data").getClass().equals(UUID[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); - - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); - } + collector.checkThat(got, notNullValue()); } - + @Test - public void testPositiveGenerateSignedBlobs_1(){ + public void testIntegerSequenceCache_2() { + // Testing createIntegerSequenceCache(int n, int length int min, int max, + // boolean replacement, int base, int cacheSize) + RandomOrgCache c = rocs[0].createIntegerSequenceCache(2, 5, 0, 10, false, 16, 3); + c.stop(); + try { - HashMap o = roc.generateSignedBlobs(10, 16); - - assertNotNull(o); + c.get(); + collector.addError(new Error("should have thrown NoSuchElementException")); + } catch (NoSuchElementException e) {} - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); + c.resume(); - assertTrue(o.get("data").getClass().equals(String[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); + String[][] got = null; - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + while (got == null) { + try { + got = c.get(); + } catch (NoSuchElementException e) { + try { + Thread.sleep(50); + } catch (InterruptedException e1) { + collector.addError(new Error("shouldn't have been interrupted!")); + } + } } - try { - HashMap o = roc2.generateSignedBlobs(10, 16); - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - - assertTrue(o.get("data").getClass().equals(String[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); - - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); - } + collector.checkThat(got, notNullValue()); } @Test - public void testPositiveGenerateSignedBlobs_2(){ + public void testIntegerSequenceCache_3() { + // Testing createIntegerSequenceCache(int n, int[] length, int[] min, int[] max) + RandomOrgCache c = rocs[0].createIntegerSequenceCache(4, LENGTH, MIN, MAX); + c.stop(); + try { - HashMap o = roc.generateSignedBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX); - - assertNotNull(o); + c.get(); + collector.addError(new Error("should have thrown NoSuchElementException")); + } catch (NoSuchElementException e) {} - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); + c.resume(); - assertTrue(o.get("data").getClass().equals(String[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); + int[][] got = null; - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + while (got == null) { + try { + got = c.get(); + } catch (NoSuchElementException e) { + try { + Thread.sleep(50); + } catch (InterruptedException e1) { + collector.addError(new Error("shouldn't have been interrupted!")); + } + } } - try { - HashMap o = roc2.generateSignedBlobs(10, 16, RandomOrgClient.BLOB_FORMAT_HEX); - - assertNotNull(o); - - assertTrue(o.containsKey("data")); - assertTrue(o.containsKey("random")); - assertTrue(o.containsKey("signature")); - assertTrue(o.get("data").getClass().equals(String[].class)); - assertTrue(o.get("random").getClass().equals(JsonObject.class)); - assertTrue(o.get("signature").getClass().equals(String.class)); - - assertTrue(roc.verifySignature((JsonObject)o.get("random"), (String)o.get("signature"))); - } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); - } + collector.checkThat(got, notNullValue()); } - - // Test Functions (Cache) @Test - public void testIntegerCache(){ - RandomOrgCache c = roc.createIntegerCache(5, 0, 10); + public void testIntegerSequenceCache_4() { + // Testing createIntegerSequenceCache(int n, int[] length, int[] min, int[] max, + // boolean[] replacement, int[] base, int cacheSize) + boolean[] replacement = {true, true, true, true}; + RandomOrgCache c = rocs[0].createIntegerSequenceCache(4, LENGTH, MIN, MAX, replacement, BASE, 10); c.stop(); try { c.get(); - Assert.fail("should have thrown NoSuchElementException"); + collector.addError(new Error("should have thrown NoSuchElementException")); } catch (NoSuchElementException e) {} c.resume(); - int[] got = null; + String[][] got = null; while (got == null) { try { @@ -718,22 +2032,27 @@ public void testIntegerCache(){ try { Thread.sleep(50); } catch (InterruptedException e1) { - Assert.fail("shouldn't have been interrupted!"); + collector.addError(new Error("shouldn't have been interrupted!")); } } } - assertNotNull(got); + for (int i = 0; i < got.length; i++) { + collector.checkThat(got[i].length == LENGTH[i], equalTo(true)); + } + + collector.checkThat(got, notNullValue()); } - + @Test - public void testDecimalFractionCache(){ - RandomOrgCache c = roc2.createDecimalFractionCache(1, 5); + public void testDecimalFractionCache() { + // Testing createDecimalFractionCache(int n, int decimalPlaces) + RandomOrgCache c = rocs[1].createDecimalFractionCache(1, 5); c.stop(); try { c.get(); - Assert.fail("should have thrown NoSuchElementException"); + collector.addError(new Error("should have thrown NoSuchElementException")); } catch (NoSuchElementException e) {} c.resume(); @@ -747,22 +2066,24 @@ public void testDecimalFractionCache(){ try { Thread.sleep(50); } catch (InterruptedException e1) { - Assert.fail("shouldn't have been interrupted!"); + collector.addError(new Error("shouldn't have been interrupted!")); } } } - assertNotNull(got); + collector.checkThat(got, notNullValue()); } @Test - public void testGaussianCache(){ - RandomOrgCache c = roc.createGaussianCache(10, 3.41d, 2.1d, 4); + public void testGaussianCache() { + // Testing createGaussianCache(int n, double mean, double standardDeviation, + // int significantDigits) + RandomOrgCache c = rocs[0].createGaussianCache(10, 3.41d, 2.1d, 4); c.stop(); try { c.get(); - Assert.fail("should have thrown NoSuchElementException"); + collector.addError(new Error("should have thrown NoSuchElementException")); } catch (NoSuchElementException e) {} c.resume(); @@ -776,22 +2097,23 @@ public void testGaussianCache(){ try { Thread.sleep(50); } catch (InterruptedException e1) { - Assert.fail("shouldn't have been interrupted!"); + collector.addError(new Error("shouldn't have been interrupted!")); } } } - assertNotNull(got); + collector.checkThat(got, notNullValue()); } @Test - public void testStringCache(){ - RandomOrgCache c = roc2.createStringCache(5, 5, "abcds"); + public void testStringCache() { + // Testing createStringCache(int n, int length, String characters) + RandomOrgCache c = rocs[1].createStringCache(5, 5, "abcds"); c.stop(); try { c.get(); - Assert.fail("should have thrown NoSuchElementException"); + collector.addError(new Error("should have thrown NoSuchElementException")); } catch (NoSuchElementException e) {} c.resume(); @@ -805,22 +2127,23 @@ public void testStringCache(){ try { Thread.sleep(50); } catch (InterruptedException e1) { - Assert.fail("shouldn't have been interrupted!"); + collector.addError(new Error("shouldn't have been interrupted!")); } } } - assertNotNull(got); + collector.checkThat(got, notNullValue()); } @Test - public void testUUIDCache(){ - RandomOrgCache c = roc.createUUIDCache(5); + public void testUUIDCache() { + // Testing createUUIDCache(int n) + RandomOrgCache c = rocs[0].createUUIDCache(5); c.stop(); try { c.get(); - Assert.fail("should have thrown NoSuchElementException"); + collector.addError(new Error("should have thrown NoSuchElementException")); } catch (NoSuchElementException e) {} c.resume(); @@ -834,22 +2157,23 @@ public void testUUIDCache(){ try { Thread.sleep(50); } catch (InterruptedException e1) { - Assert.fail("shouldn't have been interrupted!"); + collector.addError(new Error("shouldn't have been interrupted!")); } } } - assertNotNull(got); + collector.checkThat(got, notNullValue()); } @Test - public void testBlobCache(){ - RandomOrgCache c = roc2.createBlobCache(5, 8); + public void testBlobCache() { + // Testing createBlobCache(int n, int size) + RandomOrgCache c = rocs[1].createBlobCache(5, 8); c.stop(); try { c.get(); - Assert.fail("should have thrown NoSuchElementException"); + collector.addError(new Error("should have thrown NoSuchElementException")); } catch (NoSuchElementException e) {} c.resume(); @@ -863,11 +2187,195 @@ public void testBlobCache(){ try { Thread.sleep(50); } catch (InterruptedException e1) { - Assert.fail("shouldn't have been interrupted!"); + collector.addError(new Error("shouldn't have been interrupted!")); } } } - assertNotNull(got); + collector.checkThat(got, notNullValue()); + } + + // Error message and helper functions + + private String client(int i) { + return "RandomOrgClient roc" + i + " "; + } + + private String errorMessage() { + return errorMessage(-1); + } + + private String errorMessage(int i) { + return errorMessage(i, null); + } + + private String errorMessage(Exception e) { + return errorMessage(-1, e); + } + + private String errorMessage(int i, Exception e) { + return errorMessage(i, e, false); + } + + private String errorMessage(int i, Exception e, boolean networking) { + if (networking) { + return client(i) + " - Networking error: " + e.getClass().getName() + + ":" + e.getMessage(); + } else { + String s = ""; + if (i > -1) { + s += client(i); + } + s += "should have thrown RandomOrgRANDOMORGError"; + if (e != null) { + s += ", instead threw " + e.getClass().getName(); + } + return s; + } + } + + /** + * Helper function to check if the RandomOrgRANDOMORGError thrown + * is the expected error. + * + * @param e RandomOrgRANDOMORGError thrown in the test. + * @param expectedErrorCode The code of the expected RandomOrgRANDOMORGError. + */ + private void negativeErrorHandler(RandomOrgRANDOMORGError e, int expectedErrorCode) { + if (e.getCode() != expectedErrorCode) { + collector.addError(new Error("Should have thrown RandomOrgRANDOMORGError " + + expectedErrorCode + ", instead threw: " + e.getMessage())); + } + } + + /** + * Helper function for testing methods returning signed values + * + * @param roc RandomOrgClient instance being used + * @param i index of RandomOrgClient instance in rocs + * @param o HashMap returned from call to a RandomOrgClient method + * returning signed values + * @param cls Class of the data expected to be returned from the call to the + * RandomOrgClient method + * + */ + private void signedValueTester(RandomOrgClient roc, int i, HashMap o, Class cls) { + this.signedValueTester(roc, i, o, cls, false); + } + + /** + * Helper function for testing methods returning signed values + * + * @param roc RandomOrgClient instance being used + * @param i index of RandomOrgClient instance in rocs + * @param o HashMap returned from call to a RandomOrgClient method + * returning signed values + * @param cls Class of the data expected to be returned from the call to the + * RandomOrgClient method + * @param hasUserData boolean stating whether the request included userData (true) or not (false) + * + */ + private void signedValueTester(RandomOrgClient roc, int i, HashMap o, Class cls, boolean hasUserData) { + this.signedValueTester(roc, i, o, cls, hasUserData, null); + } + + /** + * Helper function for testing methods returning signed values + * + * @param roc RandomOrgClient instance being used + * @param i index of RandomOrgClient instance in rocs + * @param o HashMap returned from call to a RandomOrgClient method + * returning signed values + * @param cls Class of the data expected to be returned from the call to the + * RandomOrgClient method + * @param hasUserData boolean stating whether the request included userData (true) or not (false) + * @param ticketId String returned from a call to {@link org.random.api.RandomOrgClient#createTickets(int n, boolean showResult) + * createTickets}. {@code null} if none is used. + * + */ + private void signedValueTester(RandomOrgClient roc, int i, HashMap o, Class cls, boolean hasUserData, String ticketId) { + collector.checkThat(o, notNullValue()); + + collector.checkThat(o.containsKey("data"), equalTo(true)); + collector.checkThat(o.containsKey("random"), equalTo(true)); + collector.checkThat(o.containsKey("signature"), equalTo(true)); + + collector.checkThat(o.get("data").getClass(), equalTo(cls)); + collector.checkThat(o.get("random").getClass(), equalTo(JsonObject.class)); + collector.checkThat(o.get("signature").getClass(), equalTo(String.class)); + + if (hasUserData) { + collector.checkThat(((JsonObject) o.get("random")).get("userData"), equalTo(userData)); + } + + if (ticketId != null) { + try { + HashMap o2 = roc.getTicket(ticketId); + collector.checkThat(o.get("data"), equalTo(o2.get("data"))); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + } + + try { + collector.checkThat(roc.verifySignature((JsonObject)o.get("random"), + (String)o.get("signature")), equalTo(true)); + } catch (Exception e) { + collector.addError(new Error(errorMessage(i, e, true))); + } + } + + /** + * Helper function to test revealing tickets. + * + * @param roc RandomOrgClient instance being used. + * @param rocIndex index of RandomOrgClient instance in rocs + * @param n The number of tickets to use. + */ + private void revealTicket(RandomOrgClient roc, int rocIndex, int n) { + try { + String lastTicket = ""; + + Map> results = new HashMap>(); + + JsonObject ticket = roc.createTickets(1, false)[0]; + String ticketId = ticket.get("ticketId").getAsString(); + + + for (int i = 0; i < n; i++) { + // Use the ticket to generate integers. + HashMap result = roc.generateSignedIntegers(5, 0, 10, false, 10, null, ticketId); + + // Check that the generated data is not visible pre-reveal. + HashMap get = roc.getTicket(ticketId); + collector.checkThat(get.get("data"), nullValue()); + + // Update last ticket (which will be revealed) and results. + lastTicket = ticketId; + results.put(ticketId, result); + + // Get the next ticket. + ticketId = ((JsonObject) roc.getTicket(ticketId).get("result")).get("nextTicketId").toString(); + ticketId = ticketId.replaceAll("\"", ""); + } + + // Reveal the last ticket, which also automatically reveals + // all other tickets used (predecessors). + int ticketCount = roc.revealTickets(lastTicket); + collector.checkThat(ticketCount, is(n)); + + for(Map.Entry> entry : results.entrySet()) { + String id = entry.getKey(); + HashMap result = entry.getValue(); + + // Check that the results are now available for each revealed ticket + // and that they are the correct results. + HashMap get = roc.getTicket(id); + collector.checkThat(result.get("data"), equalTo(get.get("data"))); + } + } catch (Exception e) { + collector.addError(new Error(errorMessage(rocIndex, e, true))); + } } } diff --git a/RandomJSONRPC/src/org/random/test/RandomOrgRandomBasicTest.java b/RandomJSONRPC/src/org/random/test/RandomOrgRandomBasicTest.java index fe393f1..78d5b1d 100644 --- a/RandomJSONRPC/src/org/random/test/RandomOrgRandomBasicTest.java +++ b/RandomJSONRPC/src/org/random/test/RandomOrgRandomBasicTest.java @@ -8,8 +8,7 @@ import org.junit.Test; import org.random.util.RandomOrgRandom; -/** A set of tests for RandomOrgRandom.java - **/ +/** A set of tests for RandomOrgRandom.java */ public class RandomOrgRandomBasicTest { private static RandomOrgRandom random; @@ -29,7 +28,8 @@ public void testIntegerRange(){ assertTrue(i >= 0); assertTrue(i < 10); } catch (Exception e) { - Assert.fail("Networking error: " + e.getClass().getName() + ":" + e.getMessage()); + Assert.fail("Networking error: " + e.getClass().getName() + + ":" + e.getMessage()); } } } diff --git a/RandomJSONRPC/src/org/random/util/RandomOrgRandom.java b/RandomJSONRPC/src/org/random/util/RandomOrgRandom.java index 38c20bb..552f1b1 100644 --- a/RandomJSONRPC/src/org/random/util/RandomOrgRandom.java +++ b/RandomJSONRPC/src/org/random/util/RandomOrgRandom.java @@ -20,31 +20,30 @@ import org.random.api.exception.RandomOrgRANDOMORGError; import org.random.api.exception.RandomOrgSendTimeoutException; -/** A partial implementation of {@link Random} using RANDOM.ORG for true RNG. - **

- ** This implements a true random number generator based on the RANDOM.ORG service. - ** For more information see https://api.random.org/. - **

- ** This class offers cached number retrieving from the random.org server over the official API. - ** The cached numbers can be accessed bit wise by the typical public methods of the random class. - ** If more bits are requested than currently cached the methods will block until more data is - ** retrieved from the server. - **

- ** To use this class a official API key from https://api.random.org/api-keys is required. - **

- ** By default this caches a maximum of 512 bits in two blobs of 256 bits each. - ** To optimize the cache for your needs you can setup the cache size (number of blobs) and - ** cache bits (number of bits per blob) on creation of an instance. - ** - ** @see https://random.org/ - ** @see https://api.random.org/ - ** - ** @author Adam Wagenhaeuser - **/ +/** + * A partial implementation of {@link Random} using RANDOM.ORG for true RNG. + *

+ * This implements a true random number generator based on the RANDOM.ORG service. + * For more information see https://api.random.org/. + *

+ * This class offers cached number retrieving from the random.org server over the official API. + * The cached numbers can be accessed bit wise by the typical public methods of the random class. + * If more bits are requested than currently cached the methods will block until more data is + * retrieved from the server. + *

+ * To use this class a official API key from https://api.random.org/api-keys is required. + *

+ * By default this caches a maximum of 512 bits in two blobs of 256 bits each. + * To optimize the cache for your needs you can setup the cache size (number of blobs) and + * cache bits (number of bits per blob) on creation of an instance. + * + * @see https://random.org/ + * @see https://api.random.org/ + * + * @author Adam Wagenhaeuser + */ public class RandomOrgRandom extends Random { - /** - **/ private static final long serialVersionUID = 4785372106424073371L; /** integer bit masks */ @@ -84,21 +83,19 @@ public class RandomOrgRandom extends Random { 0xFFFFFFFF, }; - /** Default cache size is 256. - **/ + /** Default cache size is 256. */ private static final int DEFAULT_CACHE_BITS = 256; - /** Default cache number is 2. - **/ + /** Default cache number is 2. */ private static final int DEFAULT_CACHE_SIZE = 2; - /** Cache bits - number of bits to cache per blob. - ** - ** Must be within the [1,1048576] range and must be divisible by 8. - ** This will be automatically enforced (rounded up unless too large). - ** - ** Default is 256. - **/ + /* Cache bits - number of bits to cache per blob. + * + * Must be within the [1,1048576] range and must be divisible by 8. + * This will be automatically enforced (rounded up unless too large). + * + * Default is 256. + */ private int cacheBits; /** Cache size - number of blobs to cache. @@ -108,25 +105,27 @@ public class RandomOrgRandom extends Random { **/ private int cacheSize; - /** The local RANDOM.ORG blob cache. - **

- ** This stores up to {@link #cacheSize}*{@link #cacheBits} values. - **/ + /** + * The local RANDOM.ORG blob cache. + *

+ * This stores up to {@link #cacheSize}*{@link #cacheBits} values. + */ private RandomOrgCache cache; - /** The current blob from which random numbers are being pulled. - ** Once blob is in use it is removed from the blob cache. - **/ + /** + * The current blob from which random numbers are being pulled. + * Once blob is in use it is removed from the blob cache. + */ private byte[] currentBlob; - /** Next index into the currently active blob. - **/ + /** Next index into the currently active blob. */ private int currentBlobIndex; - /** The RANDOM.ORG client used for the cache. - ** - ** @see #cache - **/ + /** + * The RANDOM.ORG client used for the cache. + * + * @see #cache + */ private RandomOrgClient client; /** Left to right bit buffer for getting less than 8 bits. @@ -143,41 +142,43 @@ public class RandomOrgRandom extends Random { private static final Logger LOGGER = Logger.getLogger(RandomOrgClient.class.getPackage().getName()); - /** Create a new RandomOrgRandom instance for the given API key. - **

- ** This RandomOrgRandom needs an official API key for the RANDOM.ORG API. - ** See https://api.random.org/api-keys for more details. - **

- ** The RANDOM.ORG library guarantees only one client is running per API key at any - ** given time, so it's safe to create multiple RandomOrgRandom classes - ** with the same API key if needed. - ** - ** @param apiKey a RANDOM.ORG API key - **/ + /** + * Constructor. Create a new RandomOrgRandom instance for the given API key. + *

+ * This RandomOrgRandom needs an official API key + * for the RANDOM.ORG API. + *

+ * The RANDOM.ORG library guarantees only one client is running per API key at any + * given time, so it's safe to create multiple RandomOrgRandom classes + * with the same API key if needed. + * + * @param apiKey a RANDOM.ORG API key + */ public RandomOrgRandom(String apiKey) { this(apiKey, DEFAULT_CACHE_SIZE, DEFAULT_CACHE_BITS); } - /** Create a new RandomOrgRandom instance for the given API key and cache size. - **

- ** This RandomOrgRandom needs an official API key for the RANDOM.ORG API. - ** See https://api.random.org/api-keys for more details. - **

- ** The cacheSize specifies the number of blobs maintained by a background thread. - ** If you set the value too high it may consume much of your daily allowance on the server. - ** It the value is too low your application may block frequently. The default value is 2. - **

- ** The cacheBits parameter specifies the number of bits per blob in the cache. - ** If you set the value too high it may consume much of your daily allowance on the server. - ** It the value is too low your application will block frequently. The default value is 256. - **

- ** The RANDOM.ORG library guarantees only one client is running per API key at any - ** given time, so it's safe to create multiple RandomOrgRandom classes - ** with the same API key if needed. - ** - ** @param apiKey a RANDOM.ORG API key - ** @param cacheSize the desired cache size - **/ + /** + * Constructor. Create a new RandomOrgRandom instance for the given API key and cache size. + *

+ * This RandomOrgRandom needs an official API key + * for the RANDOM.ORG API. + *

+ * The RANDOM.ORG library guarantees only one client is running per API key at any + * given time, so it's safe to create multiple RandomOrgRandom classes + * with the same API key if needed. + * + * @param apiKey a RANDOM.ORG API key + * @param cacheSize number of blobs to cache. If you set the value too high it may consume + * much of your daily allowance on the server. It the value is too low your application + * may block frequently. Cache size minimum is 2, which will be automatically enforced + * (default 2). + * @param cacheBits number of bits to cache per blob. If you set the value too high it may + * consume much of your daily allowance on the server. It the value is too low your + * application will block frequently. Must be within the [1,1048576] range and must be + * divisible by 8. This will be automatically enforced (rounded up unless too large; + * default 256). + */ public RandomOrgRandom(String apiKey, int cacheSize, int cacheBits) { this.cacheSize = cacheSize; @@ -192,39 +193,41 @@ public RandomOrgRandom(String apiKey, int cacheSize, int cacheBits) { this.cache = this.client.createBlobCache(1, cacheBits, RandomOrgClient.BLOB_FORMAT_BASE64, cacheSize); } - /** Create a new RandomOrgRandom using the given client. - **

- ** This RandomOrgRandom needs a RANDOM.ORG client instance for the random.org API. - **

- ** The RANDOM.ORG library guarantees only one client is running per API key at any - ** given time, so it's safe to create multiple RandomOrgRandom classes - ** with the same API key if needed. - ** - ** @param client the RANDOM.ORG client to use - **/ + /** + * Constructor. Create a new RandomOrgRandom using the given client. + *

+ * This RandomOrgRandom needs a RANDOM.ORG client instance for the random.org API. + *

+ * The RANDOM.ORG library guarantees only one client is running per API key at any + * given time, so it's safe to create multiple RandomOrgRandom classes + * with the same API key if needed. + * + * @param client the RANDOM.ORG client to use + */ public RandomOrgRandom(RandomOrgClient client) { this(client, DEFAULT_CACHE_SIZE, DEFAULT_CACHE_BITS); } - /** Create a new RandomOrgRandom using the given client and cache size. - **

- ** This RandomOrgRandom needs a RANDOM.ORG client instance for the random.org API. - **

- ** The cacheSize specifies the number of blobs maintained by a background thread. - ** If you set the value too high it may consume much of your daily allowance on the server. - ** It the value is too low your application may block frequently. The default value is 2. - **

- ** The cacheBits parameter specifies the number of bits per blob in the cache. - ** If you set the value too high it may consume much of your daily allowance on the server. - ** It the value is too low your application will block frequently. The default value is 256. - **

- ** The RANDOM.ORG library guarantees only one client is running per API key at any - ** given time, so it's safe to create multiple RandomOrgRandom classes - ** with the same API key if needed. - ** - ** @param client the RANDOM.ORG client to use - ** @param cacheSize the desired cache size - **/ + /** + * Constructor. Create a new RandomOrgRandom using the given client and cache size. + *

+ * This RandomOrgRandom needs a RANDOM.ORG client instance for the random.org API. + *

+ * The RANDOM.ORG library guarantees only one client is running per API key at any + * given time, so it's safe to create multiple RandomOrgRandom classes + * with the same API key if needed. + * + * @param client the RANDOM.ORG client to use + * @param cacheSize number of blobs to cache. If you set the value too high it may consume + * much of your daily allowance on the server. It the value is too low your application + * may block frequently. Cache size minimum is 2, which will be automatically enforced + * (default 2). + * @param cacheBits number of bits to cache per blob. If you set the value too high it may + * consume much of your daily allowance on the server. It the value is too low your + * application will block frequently. Must be within the [1,1048576] range and must be + * divisible by 8. This will be automatically enforced (rounded up unless too large; + * default 256). + */ public RandomOrgRandom(RandomOrgClient client, int cacheSize, int cacheBits) { this.client = client; this.cacheSize = cacheSize; @@ -236,29 +239,30 @@ public RandomOrgRandom(RandomOrgClient client, int cacheSize, int cacheBits) { this.cache = this.client.createBlobCache(1, cacheBits, RandomOrgClient.BLOB_FORMAT_BASE64, cacheSize); } - /** Gets the remaining quota for the used key. - **

- ** This method gets the bit count still retrievable from the - ** server. If this value is negative no more bits can be retrieved. - **

- ** Note that this method will access a buffered value if that value is not too - ** old, so the returned value can be different from the value on the server. - **

- ** Note that this value does not contain the local cached bits, so the current - ** local available bit count can be larger than the return of this method. - ** - ** @return the remaining bit quota - ** - ** @throws RandomOrgSendTimeoutException @see {@link RandomOrgClient#getBitsLeft()} - ** @throws RandomOrgKeyNotRunningError @see {@link RandomOrgClient#getBitsLeft()} - ** @throws RandomOrgInsufficientRequestsError @see {@link RandomOrgClient#getBitsLeft()} - ** @throws RandomOrgInsufficientBitsError @see {@link RandomOrgClient#getBitsLeft()} - ** @throws RandomOrgBadHTTPResponseException @see {@link RandomOrgClient#getBitsLeft()} - ** @throws RandomOrgRANDOMORGError @see {@link RandomOrgClient#getBitsLeft()} - ** @throws RandomOrgJSONRPCError @see {@link RandomOrgClient#getBitsLeft()} - ** @throws MalformedURLException @see {@link RandomOrgClient#getBitsLeft()} - ** @throws IOException @see {@link RandomOrgClient#getBitsLeft()} - **/ + /** + * Gets the remaining quota for the used key. + *

+ * This method gets the bit count still retrievable from the + * server. If this value is negative no more bits can be retrieved. + *

+ * Note that this method will access a buffered value if that value is not too + * old, so the returned value can be different from the value on the server. + *

+ * Note that this value does not contain the local cached bits, so the current + * local available bit count can be larger than the return of this method. + * + * @return the remaining bit quota + * + * @throws RandomOrgSendTimeoutException @see {@link RandomOrgClient#getBitsLeft()} + * @throws RandomOrgKeyNotRunningError @see {@link RandomOrgClient#getBitsLeft()} + * @throws RandomOrgInsufficientRequestsError @see {@link RandomOrgClient#getBitsLeft()} + * @throws RandomOrgInsufficientBitsError @see {@link RandomOrgClient#getBitsLeft()} + * @throws RandomOrgBadHTTPResponseException @see {@link RandomOrgClient#getBitsLeft()} + * @throws RandomOrgRANDOMORGError @see {@link RandomOrgClient#getBitsLeft()} + * @throws RandomOrgJSONRPCError @see {@link RandomOrgClient#getBitsLeft()} + * @throws MalformedURLException @see {@link RandomOrgClient#getBitsLeft()} + * @throws IOException @see {@link RandomOrgClient#getBitsLeft()} + */ public long getRemainingQuota() throws RandomOrgSendTimeoutException, RandomOrgKeyNotRunningError, RandomOrgInsufficientRequestsError, @@ -271,35 +275,37 @@ public long getRemainingQuota() throws RandomOrgSendTimeoutException, return this.client.getBitsLeft(); } - /** Returns the size of the local cache. - **

- ** This size can be specified in the constructor. - ** - ** @return the size of the cache. - **/ + /** + * Returns the size of the local cache. + *

+ * This size can be specified in the constructor. + * + * @return the size of the cache. + */ public int getCachSize() { return this.cacheSize; } - /** Returns the size of each blob in the cache in bits. - **

- ** This size can be specified in the constructor. - ** - ** @return the number of bits per blob in the cache. - **/ + /** + * Returns the size of each blob in the cache in bits. + *

+ * This size can be specified in the constructor. + * + * @return the number of bits per blob in the cache. + */ public int getCachBits() { return this.cacheBits; } - /** Blocking implementation of {@link java.util.Random#nextInt(int)} using RANDOM.ORG's RNG service. - ** - ** @see java.util.Random#nextInt(int) - ** - ** @throws NoSuchElementException if a number couldn't be retrieved. - **/ + /** + * Blocking implementation of {@link java.util.Random#nextInt(int)} using RANDOM.ORG's RNG service. + * + * @see java.util.Random#nextInt(int) + * + * @throws NoSuchElementException if a number couldn't be retrieved. + */ @Override - public int nextInt(int n) { - + public int nextInt(int n) { if (n <= 0) { throw new IllegalArgumentException("n must be positive"); } @@ -334,15 +340,15 @@ public int nextInt(int n) { return r; } - /** Blocking implementation of {@link java.util.Random#next(int)} using RANDOM.ORG's RNG service. - ** - ** @see java.util.Random#next(int) - ** - ** @throws NoSuchElementException if a number couldn't be retrieved. - **/ + /** + * Blocking implementation of {@link java.util.Random#next(int)} using RANDOM.ORG's RNG service. + * + * @see java.util.Random#next(int) + * + * @throws NoSuchElementException if a number couldn't be retrieved. + */ @Override - public synchronized int next(int bits) { - + public synchronized int next(int bits) { // how many full bytes to read int sz = bits / 8; @@ -386,30 +392,31 @@ public synchronized int next(int bits) { return num; } - /** Gets the given count of random bits. - **

- ** Note: for standard retrieval of bits use the next(int) method. - **

- ** numBits must be in the range of 1 to 7 inclusive. - **

- ** This method will return numBits bits as an 8 bit byte value. - ** The random bits are stored in the least significant bits and the most significant bits are filled with zeros. - ** All random numbers are in the range of 0 to 2^numBits - 1 inclusive. - **

-	 ** Example getting 4 bits:
-	 ** 
-	 ** int ranBits = getSubBits(4) & 0x0F
-	 ** 
- ** - ** @param numBits number of bits to fetch - ** - ** @return a byte containing the requested number of random bits - ** - ** @see #next(int) - ** - ** @throws IllegalArgumentException if the number of bits requested is not between 1 and 7 inclusive - ** @throws NoSuchElementException if a number couldn't be retrieved. - **/ + /** + * Gets the given count of random bits. + *

+ * Note: for standard retrieval of bits use the next(int) method. + *

+ * numBits must be in the range of 1 to 7 inclusive. + *

+ * This method will return numBits bits as an 8 bit byte value. + * The random bits are stored in the least significant bits and the most significant bits are filled with zeros. + * All random numbers are in the range of 0 to 2^numBits - 1 inclusive. + *

+	 * Example getting 4 bits:
+	 * 
+	 * int ranBits = getSubBits(4) & 0x0F
+	 * 
+ * + * @param numBits number of bits to fetch + * + * @return a byte containing the requested number of random bits + * + * @see #next(int) + * + * @throws IllegalArgumentException if the number of bits requested is not between 1 and 7 inclusive + * @throws NoSuchElementException if a number couldn't be retrieved. + */ protected synchronized byte getSubBits(int numBits) { if (numBits < 1 || 7 < numBits) { @@ -447,12 +454,12 @@ protected synchronized byte getSubBits(int numBits) { return b; } - /** Gets the next blob from the cache. - ** - ** @throws NoSuchElementException if a blob couldn't be retrieved. - **/ - private synchronized void moveToNextBlob() throws NoSuchElementException { - + /** + * Gets the next blob from the cache. + * + * @throws NoSuchElementException if a blob couldn't be retrieved. + */ + private synchronized void moveToNextBlob() throws NoSuchElementException { String blob = null; try { @@ -467,29 +474,11 @@ private synchronized void moveToNextBlob() throws NoSuchElementException { if (getRemainingQuota() <= 0) { throw e; } - } catch (RandomOrgKeyNotRunningError e1) { - LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage()); + } catch (Exception e1) { + LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + + e1.getClass().getName() + ": " + e1.getMessage()); throw e; - } catch (RandomOrgInsufficientRequestsError e1) { - LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage()); - throw e; - } catch (RandomOrgInsufficientBitsError e1) { - LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage()); - throw e; - } catch (MalformedURLException e1) { - LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage()); - throw e; - } catch (RandomOrgSendTimeoutException e1) { - LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage()); - } catch (RandomOrgBadHTTPResponseException e1) { - LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage()); - } catch (RandomOrgRANDOMORGError e1) { - LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage()); - } catch (RandomOrgJSONRPCError e1) { - LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage()); - } catch (IOException e1) { - LOGGER.log(Level.INFO, "RandomOrgRandom moveToNextBlob Exception: " + e1.getClass().getName() + ": " + e1.getMessage()); - } + } } if (blob == null) { @@ -508,20 +497,22 @@ private synchronized void moveToNextBlob() throws NoSuchElementException { } } - /** Return true if n is a power of 2. - ** - ** @param n to evaluate - ** @return true if n is a power of 2 - **/ + /** + * Return true if n is a power of 2. + * + * @param n to evaluate + * @return true if n is a power of 2 + */ private boolean isPow2(int n) { return n == 0 ? false : (n & (n - 1)) == 0; } - /** Return next power of 2 greater than n. - ** - ** @param n to evaluate - ** @return next power of 2 greater than n. - **/ + /** + * Return next power of 2 greater than n. + * + * @param n to evaluate + * @return next power of 2 greater than n. + */ private int nextPow2(int n) { int v = n; v--; @@ -534,13 +525,13 @@ private int nextPow2(int n) { return v; } - /** Log2 of n. - ** - ** @param n to evaluate - should be a power of 2. - ** @return Log2 of n - **/ - private int log2(int n) { - + /** + * Log2 of n. + * + * @param n to evaluate - should be a power of 2. + * @return Log2 of n + */ + private int log2(int n) { int log = 0; if ((n & 0xffff0000) != 0 ) {