# Class Util

java.lang.Object
com.codename1.io.Util

public final class Util extends Object
Various utility methods used for HTTP/IO operations

- ## Method Summary

  Modifier and Type
  Method
  Description
  `static byte[]`
  `aesDecrypt(String transformation, byte[] key, byte[] iv, byte[] aad, byte[] ciphertext)`
  AES decryption -- counterpart to `aesEncrypt(String, byte[], byte[], byte[], byte[])`.
  `static byte[]`
  `aesEncrypt(String transformation, byte[] key, byte[] iv, byte[] aad, byte[] plaintext)`
  AES encryption.
  `static void`
  `cleanup(Object o)`
  Closes the object (connection, stream etc.) without throwing any exception, even if the object is null
  `static void`
  `copy(InputStream i, OutputStream o)`
  Copy the input stream into the output stream, closes both streams when finishing or in a case of an exception
  `static void`
  `copy(InputStream i, OutputStream o, int bufferSize)`
  Copy the input stream into the output stream, closes both streams when finishing or in a case of an exception
  `static void`
  `copyNoClose(InputStream i, OutputStream o, int bufferSize)`
  Copy the input stream into the output stream, without closing the streams when done
  `static void`
  `copyNoClose(InputStream i, OutputStream o, int bufferSize, IOProgressListener callback)`
  Copy the input stream into the output stream, without closing the streams when done
  `static byte[]`
  `cryptoSign(String algorithm, String keyAlgorithm, byte[] privateKeyPkcs8, byte[] data)`
  Computes a signature.
  `static boolean`
  `cryptoVerify(String algorithm, String keyAlgorithm, byte[] publicKeyX509, byte[] data, byte[] signature)`
  Verifies a signature.
  `static String`
  `decode(String s, String enc, boolean plusToSpace)`
  Decodes a String URL encoded URL
  `static AsyncResource<Image>`
  `downloadImageToCache(String url)`
  Downloads an image to the cache asynchronously.
  `static void`
  `downloadImageToCache(String url, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)`
  Downloads an image to the cache asynchronously.
  `static AsyncResource<Image>`
  `downloadImageToFileSystem(String url, String fileName)`
  Downloads an image to the file system asynchronously.
  `static void`
  `downloadImageToFileSystem(String url, String fileName, SuccessCallback<Image> onSuccess)`
  Downloads an image to the file system asynchronously.
  `static void`
  `downloadImageToFileSystem(String url, String fileName, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)`
  Downloads an image to the file system asynchronously.
  `static AsyncResource<Image>`
  `downloadImageToStorage(String url, String fileName)`
  Downloads an image to storage asynchronously.
  `static void`
  `downloadImageToStorage(String url, String fileName, SuccessCallback<Image> onSuccess)`
  Downloads an image to storage asynchronously.
  `static void`
  `downloadImageToStorage(String url, String fileName, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)`
  Downloads an image to storage asynchronously.
  `static void`
  `downloadUrlSafely(String url, String fileName, OnComplete<Integer> percentageCallback, OnComplete<String> filesavedCallback)`
  Safely download the given URL to the Storage or to the FileSystemStorage: this method is resistant to network errors and capable of resume the download as soon as network conditions allow and in a completely transparent way for the user; note that in the global network error handling, there must be an automatic
  `static boolean`
  `downloadUrlToFile(String url, String fileName, boolean showProgress)`
  Blocking method that will download the given URL to the file system storage and return when the operation completes
  `static void`
  `downloadUrlToFileSystemInBackground(String url, String fileName)`
  Non-blocking method that will download the given URL to file system storage in the background and return immediately
  `static void`
  `downloadUrlToFileSystemInBackground(String url, String fileName, ActionListener onCompletion)`
  Non-blocking method that will download the given URL to file system storage in the background and return immediately
  `static boolean`
  `downloadUrlToStorage(String url, String fileName, boolean showProgress)`
  Blocking method that will download the given URL to storage and return when the operation completes
  `static void`
  `downloadUrlToStorageInBackground(String url, String fileName)`
  Non-blocking method that will download the given URL to storage in the background and return immediately.
  `static void`
  `downloadUrlToStorageInBackground(String url, String fileName, ActionListener onCompletion)`
  Non-blocking method that will download the given URL to storage in the background and return immediately
  `static String`
  `encodeBody(byte[] buf)`
  Encode a string for HTML post requests matching the style used in application/x-www-form-urlencoded
  `static String`
  `encodeBody(char[] buf)`
  Encode a string for HTML post requests matching the style used in application/x-www-form-urlencoded
  `static String`
  `encodeBody(String str)`
  Encode a string for HTML post requests matching the style used in application/x-www-form-urlencoded
  `static String`
  `encodeUrl(byte[] buf)`
  Encode a string for HTML requests
  `static String`
  `encodeUrl(char[] buf)`
  Encode a string for HTML requests
  `static String`
  `encodeUrl(String str)`
  Encode a string for HTML requests
  `static String`
  `encodeUrl(String str, String doNotEncodeChars)`
  Encodes the provided string as a URL (with %20 for spaces).
  `static byte[][]`
  `generateRsaKeyPair(int bits)`
  Generates an RSA key pair.
  `static byte[]`
  `generateSymmetricKey(int bytes)`
  Generates `bytes` of fresh symmetric key material.
  `static long`
  `getFileSizeWithoutDownload(String url)`
  Returns -1 if the content length is unknown, a value greater than 0 if the Content-Length is known.
  `static long`
  `getFileSizeWithoutDownload(String url, boolean checkPartialDownloadSupport)`
  Returns -2 if the server doesn't accept partial downloads (and if checkPartialDownloadSupport is true), -1 if the content length is unknow, a value greater than 0 if the Content-Length is known.
  `static String`
  `getIgnorCharsWhileEncoding()`
  These chars will not be encoded by the encoding method in this class as requested in RFE 427 http://java.net/jira/browse/LWUIT-427
  `static InputStreamReader`
  `getReader(InputStream in)`
  Helper to get a reader from an input stream with UTF-8 encoding
  `static String`
  `getURLBasePath(String url)`
  Returns the URL's base path, which is the same as the path only without an ending file e.g.: http://domain.com/f/f.html would return as: /f/
  `static String`
  `getURLHost(String url)`
  Returns the URL's host portion
  `static String`
  `getURLPath(String url)`
  Returns the URL's path
  `static String`
  `getURLProtocol(String url)`
  Returns the protocol of an absolute URL e.g.
  `static String`
  `getUUID()`
  Creates a new UUID, that is a 128-bit number used to identify information in computer systems.
  `static String`
  `getUUID(long time, long clockSeqAndNode)`
  Creates a custom UUID, from the given two `long` values.
  `static OutputStreamWriter`
  `getWriter(OutputStream out)`
  Helper to get a writer from an output stream with UTF-8 encoding
  `static String`
  `guessMimeType(byte[] data)`
  Tries to determine the mime type of a byte array based on its first bytes.Direct inspection of the bytes to determine the content type is often more accurate than believing the content type claimed by the `http` server or by the file extension.
  `static String`
  `guessMimeType(InputStream in)`
  Tries to determine the mime type of an InputStream based on its first bytes.Direct inspection of the bytes to determine the content type is often more accurate than believing the content type claimed by the `http` server or by the file extension.
  `static String`
  `guessMimeType(String sourceFile)`
  Tries to determine the mime type of a file based on its first bytes.Direct inspection of the bytes to determine the content type is often more accurate than believing the content type claimed by the `http` server or by the file extension.
  `static int`
  `indexOf(Object[] arr, Object value)`
  Finds the object at the given offset while using the == operator and not the equals method call, it doesn't rely on the ordering of the elements like the Arrays method.
  `static void`
  `insertObjectAtOffset(Object[] sourceArray, Object[] destinationArray, int offset, Object o)`
  Inserts the object at the destination array offset
  `static boolean`
  `instanceofByteArray(Object o)`
  This method allows working around issue 58
  `static boolean`
  `instanceofDoubleArray(Object o)`
  This method allows working around issue 58
  `static boolean`
  `instanceofFloatArray(Object o)`
  This method allows working around issue 58
  `static boolean`
  `instanceofIntArray(Object o)`
  This method allows working around issue 58
  `static boolean`
  `instanceofLongArray(Object o)`
  This method allows working around issue 58
  `static boolean`
  `instanceofObjArray(Object o)`
  This method allows working around issue 58
  `static boolean`
  `instanceofShortArray(Object o)`
  This method allows working around issue 58
  `static void`
  `mergeArrays(Object[] arr1, Object[] arr2, Object[] destinationArray)`
  Merges arrays into one larger array
  `static int`
  `readAll(InputStream i, byte[] b)`
  Reads until the array is full or until the stream ends
  `static void`
  `readFully(InputStream i, byte[] b)`
  The read fully method from data input stream is very useful for all types of streams...
  `static void`
  `readFully(InputStream i, byte[] b, int off, int len)`
  The read fully method from data input stream is very useful for all types of streams...
  `static byte[]`
  `readInputStream(InputStream i)`
  Converts a small input stream to a byte array
  `static Object`
  `readObject(DataInputStream input)`
  Reads an object from the stream, notice that this is the inverse of the `java.io.DataOutputStream)`.
  `static String`
  `readToString(File file)`
  Reads the contents of a file to a string.
  `static String`
  `readToString(File file, String charset)`
  Reads the contents of a file to a string.
  `static String`
  `readToString(InputStream i)`
  Reads an input stream to a string
  `static String`
  `readToString(InputStream i, String encoding)`
  Reads an input stream to a string
  `static String`
  `readToString(Reader reader)`
  Reads a reader to a string
  `static String`
  `readUTF(DataInputStream d)`
  Reads a UTF string that may be null previously written by writeUTF
  `static void`
  `register(Externalizable e)`
  Registers this externalizable so readObject will be able to load such objects.
  `static void`
  `register(String id, Class c)`
  Registers this externalizable so readObject will be able to load such objects.
  `static String`
  `relativeToAbsolute(String baseURL, String relativeURL)`
  Converts a relative url e.g.: /myfile.html to an absolute url
  `static void`
  `removeObjectAtOffset(Object[] sourceArray, Object[] destinationArray, int offset)`
  Removes the object at the source array offset and copies all other objects to the destination array
  `static void`
  `removeObjectAtOffset(Object[] sourceArray, Object[] destinationArray, Object o)`
  Removes the object at the source array offset and copies all other objects to the destination array
  `static byte[]`
  `rsaDecrypt(String transformation, byte[] privateKeyPkcs8, byte[] ciphertext)`
  RSA decryption.
  `static byte[]`
  `rsaEncrypt(String transformation, byte[] publicKeyX509, byte[] plaintext)`
  RSA encryption.
  `static void`
  `secureRandomBytes(byte[] out)`
  Fills `out` with cryptographically secure random bytes.
  `static void`
  `setDateFormatter(SimpleDateFormat formatter)`
  Sets a custom formatter to use when toDateValue is invoked
  `static void`
  `setIgnorCharsWhileEncoding(String s)`
  These chars will not be encoded by the encoding method in this class as requested in RFE 427 http://java.net/jira/browse/LWUIT-427
  `static void`
  `setImplementation(CodenameOneImplementation impl)`
  Invoked internally from Display, this method is for internal use only
  `static void`
  `sleep(int t)`
  Shorthand method for Thread sleep that doesn't throw the stupid interrupted checked exception
  `static String[]`
  `split(String original, String separator)`
  Provides a utility method breaks a given String to array of String according to the given separator
  `static boolean`
  `toBooleanValue(Object val)`
  Returns true or false based on a "soft" object
  `static char[]`
  `toCharArray(String s)`
  toCharArray should return a new array always, however some devices might suffer a bug that allows mutating a String (serious security hole in the JVM) hence this method simulates the proper behavior
  `static Date`
  `toDateValue(Object o)`
  Tries to convert an arbitrary object to a date
  `static double`
  `toDoubleValue(Object number)`
  Returns the number object as a double
  `static float`
  `toFloatValue(Object number)`
  Returns the number object as a float
  `static int`
  `toIntValue(Object number)`
  Returns the number object as an int
  `static long`
  `toLongValue(Object number)`
  Returns the number object as a long
  `static void`
  `wait(Object o)`
  Shorthand method wait method that doesn't throw the stupid interrupted checked exception, it also includes the synchronized block to further reduce code clutter
  `static void`
  `wait(Object o, int t)`
  Shorthand method wait method that doesn't throw the stupid interrupted checked exception, it also includes the synchronized block to further reduce code clutter
  `static void`
  `writeObject(Object o, DataOutputStream out)`
  Writes an object to the given output stream, notice that it should be externalizable or one of the supported types.
  `static void`
  `writeStringToFile(File file, String contents)`
  Writes a string to a file using UTF-8 encoding.
  `static void`
  `writeStringToFile(File file, String contents, String charset)`
  Writes a string to a file.
  `static void`
  `writeUTF(String s, DataOutputStream d)`
  Writes a string with a null flag, this allows a String which may be null
  `static String`
  `xorDecode(String s)`
  Encodes a string in a way that makes it harder to read it "as is" this makes it possible for Strings to be "encoded" within the app and thus harder to discover by a casual search.
  `static String`
  `xorEncode(String s)`
  The inverse method of xorDecode, this is normally unnecessary and is here mostly for completeness

  ### Methods inherited from class Object

  `clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- ## Method Details

  - ### getIgnorCharsWhileEncoding

    public static String getIgnorCharsWhileEncoding()

    These chars will not be encoded by the encoding method in this class as requested in RFE 427 http://java.net/jira/browse/LWUIT-427

    ###### Returns

    chars skipped

  - ### setIgnorCharsWhileEncoding

    public static void setIgnorCharsWhileEncoding(String s)

    These chars will not be encoded by the encoding method in this class as requested in RFE 427 http://java.net/jira/browse/LWUIT-427

    ###### Parameters

    - `s`: set of characters to skip when encoding

  - ### getReader

    public static InputStreamReader getReader(InputStream in)

    Helper to get a reader from an input stream with UTF-8 encoding

    ###### Parameters

    - `in`: the input stream

    ###### Returns

    the reader

  - ### getWriter

    public static OutputStreamWriter getWriter(OutputStream out)

    Helper to get a writer from an output stream with UTF-8 encoding

    ###### Parameters

    - `out`: the output stream

    ###### Returns

    the writer

  - ### copy

    public static void copy(InputStream i, OutputStream o) throws IOException

    Copy the input stream into the output stream, closes both streams when finishing or in a case of an exception

    ###### Parameters

    - `i`: source

    - `o`: destination

    Throws:
      `IOException`

  - ### copyNoClose

    public static void copyNoClose(InputStream i, OutputStream o, int bufferSize) throws IOException

    Copy the input stream into the output stream, without closing the streams when done

    ###### Parameters

    - `i`: source

    - `o`: destination

    - `bufferSize`: the size of the buffer, which should be a power of 2 large enough

    Throws:
      `IOException`

  - ### copyNoClose

    public static void copyNoClose(InputStream i, OutputStream o, int bufferSize, IOProgressListener callback) throws IOException

    Copy the input stream into the output stream, without closing the streams when done

    ###### Parameters

    - `i`: source

    - `o`: destination

    - `bufferSize`: the size of the buffer, which should be a power of 2 large enough

    - `callback`: called after each copy step

    Throws:
      `IOException`

  - ### copy

    public static void copy(InputStream i, OutputStream o, int bufferSize) throws IOException

    Copy the input stream into the output stream, closes both streams when finishing or in a case of an exception

    ###### Parameters

    - `i`: source

    - `o`: destination

    - `bufferSize`: the size of the buffer, which should be a power of 2 large enough

    Throws:
      `IOException`

  - ### cleanup

    public static void cleanup(Object o)

    Closes the object (connection, stream etc.) without throwing any exception, even if the object is null

    ###### Parameters

    - `o`: Connection, Stream or other closeable object

  - ### readToString

    public static String readToString(InputStream i) throws IOException

    Reads an input stream to a string

    ###### Parameters

    - `i`: the input stream

    ###### Returns

    a UTF-8 string

    ###### Throws

    - `IOException`: thrown by the stream
    Throws:
      `IOException`

  - ### readToString

    public static String readToString(File file, String charset) throws IOException

    Reads the contents of a file to a string.

    ###### Parameters

    - `file`: The file to read.

    - `charset`: The Charset to use to write the file.

    ###### Returns

    The string read from the file.

    ###### Throws

    - `IOException`: If the file does not exist, or cannot be read for some reason.

    ###### Since

    8.0

    Throws:
      `IOException`

  - ### readToString

    public static String readToString(File file) throws IOException

    Reads the contents of a file to a string. Uses UTF-8 encoding.

    ###### Parameters

    - `file`: The file to read.

    ###### Returns

    The string read from the file.

    ###### Throws

    - `IOException`: If the file does not exist, or cannot be read for some reason.

    ###### Since

    8.0

    Throws:
      `IOException`

  - ### writeStringToFile

    public static void writeStringToFile(File file, String contents) throws IOException

    Writes a string to a file using UTF-8 encoding.

    ###### Parameters

    - `file`: The file to write to.

    - `contents`: The contents to write to the file.

    ###### Throws

    - `IOException`: If it cannot write to the file for some reason.

    ###### Since

    8.0

    Throws:
      `IOException`

  - ### writeStringToFile

    public static void writeStringToFile(File file, String contents, String charset) throws IOException

    Writes a string to a file.

    ###### Parameters

    - `file`: The file to write to.

    - `contents`: The contents to write to the file.

    - `charset`: The charset to use. If null, it defaults to UTF-8

    ###### Throws

    - `IOException`: If it cannot write to the file for some reason.

    ###### Since

    8.0

    Throws:
      `IOException`

  - ### readToString

    public static String readToString(InputStream i, String encoding) throws IOException

    Reads an input stream to a string

    ###### Parameters

    - `i`: the input stream

    - `encoding`: the encoding of the stream

    ###### Returns

    a string

    ###### Throws

    - `IOException`: thrown by the stream
    Throws:
      `IOException`

  - ### readToString

    public static String readToString(Reader reader) throws IOException

    Reads a reader to a string

    ###### Parameters

    - `i`: the input stream

    - `encoding`: the encoding of the stream

    ###### Returns

    a string

    ###### Throws

    - `IOException`: thrown by the stream

    ###### Since

    7.0

    Throws:
      `IOException`

  - ### readInputStream

    public static byte[] readInputStream(InputStream i) throws IOException

    Converts a small input stream to a byte array

    ###### Parameters

    - `i`: the stream to convert

    ###### Returns

    byte array of the content of the stream

    Throws:
      `IOException`

  - ### register

    public static void register(Externalizable e)

    Registers this externalizable so readObject will be able to load such objects.

    The sample below demonstrates the usage and registration of the `com.codename1.io.Externalizable` interface:

        // File: Main.java
        public class Main {
          public void init(Object o) {
            theme = UIManager.initFirstTheme("/theme");

            // IMPORTANT: Notice we don't use MyClass.class.getName()! This won't work due to obfuscation!
            Util.register("MyClass", MyClass.class);
          }

          public void start() {
            //...
          }

          public void stop() {
            //...
          }

          public void destroy() {
            //...
          }
        }

        // File: MyClass.java
        public class MyClass implements Externalizable {
          // allows us to manipulate the version, in this case we are demonstrating a data change between the initial release
          // and the current state of object data
          private static final int VERSION = 2;

          private String name;
          private Map data;

          // this field was added after version 1
          private Date startedAt;

          public int getVersion() {
            return VERSION;
          }

          public void externalize(DataOutputStream out) throws IOException {
            Util.writeUTF(name, out);
            Util.writeObject(data, out);
            if(startedAt != null) {
                out.writeBoolean(true);
                out.writeLong(startedAt.getTime());
            } else {
                out.writeBoolean(false);
            }
          }
          public void internalize(int version, DataInputStream in) throws IOException {
            name = Util.readUTF(in);
            data = (Map)Util.readObject(in);
            if(version > 1) {
                boolean hasDate = in.readBoolean();
                if(hasDate) {
                    startedAt = new Date(in.readLong());
                }
            }
          }
          public String getObjectId() {
            // IMPORTANT: Notice we don't use getClass().getName()! This won't work due to obfuscation!
            return "MyClass";
          }
        }

        // File: ReadAndWrite.java
        // will read the file or return null if failed
        MyClass object = (MyClass)Storage.getInstance().readObject("NameOfFile");

        // write the object back to storage
        Storage.getInstance().writeObject("NameOfFile", object);

    ###### Parameters

    - `e`: the externalizable instance

  - ### register

    public static void register(String id, Class c)

    Registers this externalizable so readObject will be able to load such objects.

    The sample below demonstrates the usage and registration of the `com.codename1.io.Externalizable` interface:

        // File: Main.java
        public class Main {
          public void init(Object o) {
            theme = UIManager.initFirstTheme("/theme");

            // IMPORTANT: Notice we don't use MyClass.class.getName()! This won't work due to obfuscation!
            Util.register("MyClass", MyClass.class);
          }

          public void start() {
            //...
          }

          public void stop() {
            //...
          }

          public void destroy() {
            //...
          }
        }

        // File: MyClass.java
        public class MyClass implements Externalizable {
          // allows us to manipulate the version, in this case we are demonstrating a data change between the initial release
          // and the current state of object data
          private static final int VERSION = 2;

          private String name;
          private Map data;

          // this field was added after version 1
          private Date startedAt;

          public int getVersion() {
            return VERSION;
          }

          public void externalize(DataOutputStream out) throws IOException {
            Util.writeUTF(name, out);
            Util.writeObject(data, out);
            if(startedAt != null) {
                out.writeBoolean(true);
                out.writeLong(startedAt.getTime());
            } else {
                out.writeBoolean(false);
            }
          }
          public void internalize(int version, DataInputStream in) throws IOException {
            name = Util.readUTF(in);
            data = (Map)Util.readObject(in);
            if(version > 1) {
                boolean hasDate = in.readBoolean();
                if(hasDate) {
                    startedAt = new Date(in.readLong());
                }
            }
          }
          public String getObjectId() {
            // IMPORTANT: Notice we don't use getClass().getName()! This won't work due to obfuscation!
            return "MyClass";
          }
        }

        // File: ReadAndWrite.java
        // will read the file or return null if failed
        MyClass object = (MyClass)Storage.getInstance().readObject("NameOfFile");

        // write the object back to storage
        Storage.getInstance().writeObject("NameOfFile", object);

    ###### Parameters

    - `id`: id of the externalizable

    - `c`: the class for the externalizable

  - ### writeObject

    public static void writeObject(Object o, DataOutputStream out) throws IOException

    Writes an object to the given output stream, notice that it should be externalizable or one of the supported types.

    The sample below demonstrates the usage and registration of the `com.codename1.io.Externalizable` interface:

        // File: Main.java
        public class Main {
          public void init(Object o) {
            theme = UIManager.initFirstTheme("/theme");

            // IMPORTANT: Notice we don't use MyClass.class.getName()! This won't work due to obfuscation!
            Util.register("MyClass", MyClass.class);
          }

          public void start() {
            //...
          }

          public void stop() {
            //...
          }

          public void destroy() {
            //...
          }
        }

        // File: MyClass.java
        public class MyClass implements Externalizable {
          // allows us to manipulate the version, in this case we are demonstrating a data change between the initial release
          // and the current state of object data
          private static final int VERSION = 2;

          private String name;
          private Map data;

          // this field was added after version 1
          private Date startedAt;

          public int getVersion() {
            return VERSION;
          }

          public void externalize(DataOutputStream out) throws IOException {
            Util.writeUTF(name, out);
            Util.writeObject(data, out);
            if(startedAt != null) {
                out.writeBoolean(true);
                out.writeLong(startedAt.getTime());
            } else {
                out.writeBoolean(false);
            }
          }
          public void internalize(int version, DataInputStream in) throws IOException {
            name = Util.readUTF(in);
            data = (Map)Util.readObject(in);
            if(version > 1) {
                boolean hasDate = in.readBoolean();
                if(hasDate) {
                    startedAt = new Date(in.readLong());
                }
            }
          }
          public String getObjectId() {
            // IMPORTANT: Notice we don't use getClass().getName()! This won't work due to obfuscation!
            return "MyClass";
          }
        }

        // File: ReadAndWrite.java
        // will read the file or return null if failed
        MyClass object = (MyClass)Storage.getInstance().readObject("NameOfFile");

        // write the object back to storage
        Storage.getInstance().writeObject("NameOfFile", object);

    ###### Parameters

    - `o`: the object to write which can be null

    - `out`: the destination output stream

    ###### Throws

    - `IOException`: thrown by the stream
    Throws:
      `IOException`

  - ### instanceofObjArray

    public static boolean instanceofObjArray(Object o)

    This method allows working around issue 58

    ###### Parameters

    - `o`: object to test

    ###### Returns

    true if it matches the state

    ###### Deprecated

  - ### instanceofByteArray

    public static boolean instanceofByteArray(Object o)

    This method allows working around issue 58

    ###### Parameters

    - `o`: object to test

    ###### Returns

    true if it matches the state

    ###### Deprecated

  - ### instanceofShortArray

    public static boolean instanceofShortArray(Object o)

    This method allows working around issue 58

    ###### Parameters

    - `o`: object to test

    ###### Returns

    true if it matches the state

    ###### Deprecated

  - ### instanceofLongArray

    public static boolean instanceofLongArray(Object o)

    This method allows working around issue 58

    ###### Parameters

    - `o`: object to test

    ###### Returns

    true if it matches the state

    ###### Deprecated

  - ### instanceofIntArray

    public static boolean instanceofIntArray(Object o)

    This method allows working around issue 58

    ###### Parameters

    - `o`: object to test

    ###### Returns

    true if it matches the state

    ###### Deprecated

  - ### instanceofFloatArray

    public static boolean instanceofFloatArray(Object o)

    This method allows working around issue 58

    ###### Parameters

    - `o`: object to test

    ###### Returns

    true if it matches the state

    ###### Deprecated

  - ### instanceofDoubleArray

    public static boolean instanceofDoubleArray(Object o)

    This method allows working around issue 58

    ###### Parameters

    - `o`: object to test

    ###### Returns

    true if it matches the state

    ###### Deprecated

  - ### readObject

    public static Object readObject(DataInputStream input) throws IOException

    Reads an object from the stream, notice that this is the inverse of the `java.io.DataOutputStream)`.

    The sample below demonstrates the usage and registration of the `com.codename1.io.Externalizable` interface:

        // File: Main.java
        public class Main {
          public void init(Object o) {
            theme = UIManager.initFirstTheme("/theme");

            // IMPORTANT: Notice we don't use MyClass.class.getName()! This won't work due to obfuscation!
            Util.register("MyClass", MyClass.class);
          }

          public void start() {
            //...
          }

          public void stop() {
            //...
          }

          public void destroy() {
            //...
          }
        }

        // File: MyClass.java
        public class MyClass implements Externalizable {
          // allows us to manipulate the version, in this case we are demonstrating a data change between the initial release
          // and the current state of object data
          private static final int VERSION = 2;

          private String name;
          private Map data;

          // this field was added after version 1
          private Date startedAt;

          public int getVersion() {
            return VERSION;
          }

          public void externalize(DataOutputStream out) throws IOException {
            Util.writeUTF(name, out);
            Util.writeObject(data, out);
            if(startedAt != null) {
                out.writeBoolean(true);
                out.writeLong(startedAt.getTime());
            } else {
                out.writeBoolean(false);
            }
          }
          public void internalize(int version, DataInputStream in) throws IOException {
            name = Util.readUTF(in);
            data = (Map)Util.readObject(in);
            if(version > 1) {
                boolean hasDate = in.readBoolean();
                if(hasDate) {
                    startedAt = new Date(in.readLong());
                }
            }
          }
          public String getObjectId() {
            // IMPORTANT: Notice we don't use getClass().getName()! This won't work due to obfuscation!
            return "MyClass";
          }
        }

        // File: ReadAndWrite.java
        // will read the file or return null if failed
        MyClass object = (MyClass)Storage.getInstance().readObject("NameOfFile");

        // write the object back to storage
        Storage.getInstance().writeObject("NameOfFile", object);

    ###### Parameters

    - `input`: the source input stream

    ###### Throws

    - `IOException`: thrown by the stream
    Throws:
      `IOException`

  - ### encodeUrl

    public static String encodeUrl(String str)

    Encode a string for HTML requests

    ###### Parameters

    - `str`: none encoded string

    ###### Returns

    encoded string

  - ### encodeUrl

    public static String encodeUrl(String str, String doNotEncodeChars)

    Encodes the provided string as a URL (with %20 for spaces).

    ###### Parameters

    - `str`: The URL to encode

    - `doNotEncodeChars`: A string whose characters will not be encoded.

  - ### toCharArray

    public static char[] toCharArray(String s)

    toCharArray should return a new array always, however some devices might suffer a bug that allows mutating a String (serious security hole in the JVM) hence this method simulates the proper behavior

    ###### Parameters

    - `s`: a string

    ###### Returns

    the contents of the string as a char array guaranteed to be a copy of the current array

  - ### decode

    public static String decode(String s, String enc, boolean plusToSpace)

    Decodes a String URL encoded URL

    ###### Parameters

    - `s`: the string

    - `enc`: the encoding (defaults to UTF-8 if null)

    - `plusToSpace`: true if plus signs be converted to spaces

    ###### Returns

    a decoded string

  - ### encodeBody

    public static String encodeBody(String str)

    Encode a string for HTML post requests matching the style used in application/x-www-form-urlencoded

    ###### Parameters

    - `str`: none encoded string

    ###### Returns

    encoded string

  - ### encodeUrl

    public static String encodeUrl(byte[] buf)

    Encode a string for HTML requests

    ###### Parameters

    - `buf`: none encoded string

    ###### Returns

    encoded string

    ###### Deprecated

    use encodeUrl(char[]) instead

  - ### encodeUrl

    public static String encodeUrl(char[] buf)

    Encode a string for HTML requests

    ###### Parameters

    - `buf`: none encoded string

    ###### Returns

    encoded string

  - ### encodeBody

    public static String encodeBody(char[] buf)

    Encode a string for HTML post requests matching the style used in application/x-www-form-urlencoded

    ###### Parameters

    - `buf`: none encoded string

    ###### Returns

    encoded string

  - ### encodeBody

    public static String encodeBody(byte[] buf)

    Encode a string for HTML post requests matching the style used in application/x-www-form-urlencoded

    ###### Parameters

    - `buf`: none encoded string

    ###### Returns

    encoded string

    ###### Deprecated

    use encodeUrl(char[]) instead

  - ### relativeToAbsolute

    public static String relativeToAbsolute(String baseURL, String relativeURL)

    Converts a relative url e.g.: /myfile.html to an absolute url

    ###### Parameters

    - `baseURL`: a source URL whose properties should be used to construct the actual URL

    - `relativeURL`: relative address

    ###### Returns

    an absolute URL

  - ### getURLProtocol

    public static String getURLProtocol(String url)

    Returns the protocol of an absolute URL e.g. http, https etc.

    ###### Parameters

    - `url`: absolute URL

    ###### Returns

    protocol

  - ### getURLHost

    public static String getURLHost(String url)

    Returns the URL's host portion

    ###### Parameters

    - `url`: absolute URL

    ###### Returns

    the domain of the URL

  - ### getURLPath

    public static String getURLPath(String url)

    Returns the URL's path

    ###### Parameters

    - `url`: absolute URL

    ###### Returns

    the path within the host

  - ### getURLBasePath

    public static String getURLBasePath(String url)

    Returns the URL's base path, which is the same as the path only without an ending file e.g.: http://domain.com/f/f.html would return as: /f/

    ###### Parameters

    - `url`: absolute URL

    ###### Returns

    the path within the host

  - ### writeUTF

    public static void writeUTF(String s, DataOutputStream d) throws IOException

    Writes a string with a null flag, this allows a String which may be null

    ###### Parameters

    - `s`: the string to write

    - `d`: the destination output stream

    ###### Throws

    - `java.io.IOException`
    Throws:
      `IOException`

  - ### readUTF

    public static String readUTF(DataInputStream d) throws IOException

    Reads a UTF string that may be null previously written by writeUTF

    ###### Parameters

    - `d`: the stream

    ###### Returns

    a string or null

    ###### Throws

    - `java.io.IOException`
    Throws:
      `IOException`

  - ### readFully

    public static void readFully(InputStream i, byte[] b) throws IOException

    The read fully method from data input stream is very useful for all types of streams...

    ###### Parameters

    - `b`: the buffer into which the data is read.

    ###### Throws

    - `IOException`: @throws IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
    Throws:
      `IOException`

  - ### readFully

    public static void readFully(InputStream i, byte[] b, int off, int len) throws IOException

    The read fully method from data input stream is very useful for all types of streams...

    ###### Parameters

    - `b`: the buffer into which the data is read.

    - `off`: the start offset of the data.

    - `len`: the number of bytes to read.

    ###### Throws

    - `IOException`: @throws IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
    Throws:
      `IOException`

  - ### readAll

    public static int readAll(InputStream i, byte[] b) throws IOException

    Reads until the array is full or until the stream ends

    ###### Parameters

    - `b`: the buffer into which the data is read.

    ###### Returns

    the amount read

    ###### Throws

    - `IOException`: @throws IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
    Throws:
      `IOException`

  - ### split

    public static String[] split(String original, String separator)

    Provides a utility method breaks a given String to array of String according to the given separator

    ###### Parameters

    - `original`: the String to break

    - `separator`: the pattern to look in the original String

    ###### Returns

    array of Strings from the original String

  - ### setImplementation

    public static void setImplementation(CodenameOneImplementation impl)

    Invoked internally from Display, this method is for internal use only

    ###### Parameters

    - `impl`: implementation instance

  - ### secureRandomBytes

    public static void secureRandomBytes(byte[] out)
    Fills `out` with cryptographically secure random bytes. Used by `SecureRandom`.

  - ### aesEncrypt

    public static byte[] aesEncrypt(String transformation, byte[] key, byte[] iv, byte[] aad, byte[] plaintext)
    AES encryption. See `CodenameOneImplementation.aesEncrypt(String, byte[], byte[], byte[], byte[])` for the parameter contract. Used by `Cipher`.

  - ### aesDecrypt

    public static byte[] aesDecrypt(String transformation, byte[] key, byte[] iv, byte[] aad, byte[] ciphertext)
    AES decryption -- counterpart to `aesEncrypt(String, byte[], byte[], byte[], byte[])`.

  - ### rsaEncrypt

    public static byte[] rsaEncrypt(String transformation, byte[] publicKeyX509, byte[] plaintext)
    RSA encryption.

  - ### rsaDecrypt

    public static byte[] rsaDecrypt(String transformation, byte[] privateKeyPkcs8, byte[] ciphertext)
    RSA decryption.

  - ### cryptoSign

    public static byte[] cryptoSign(String algorithm, String keyAlgorithm, byte[] privateKeyPkcs8, byte[] data)
    Computes a signature.

  - ### cryptoVerify

    public static boolean cryptoVerify(String algorithm, String keyAlgorithm, byte[] publicKeyX509, byte[] data, byte[] signature)
    Verifies a signature.

  - ### generateRsaKeyPair

    public static byte[][] generateRsaKeyPair(int bits)
    Generates an RSA key pair. Returns `{publicKeyX509, privateKeyPkcs8}`.

  - ### generateSymmetricKey

    public static byte[] generateSymmetricKey(int bytes)
    Generates `bytes` of fresh symmetric key material.

  - ### mergeArrays

    public static void mergeArrays(Object[] arr1, Object[] arr2, Object[] destinationArray)
    Merges arrays into one larger array

  - ### removeObjectAtOffset

    public static void removeObjectAtOffset(Object[] sourceArray, Object[] destinationArray, Object o)

    Removes the object at the source array offset and copies all other objects to the destination array

    ###### Parameters

    - `sourceArray`: the source array

    - `destinationArray`: the resulting array which should be of the length sourceArray.length - 1

    - `o`: the object to remove from the array

  - ### removeObjectAtOffset

    public static void removeObjectAtOffset(Object[] sourceArray, Object[] destinationArray, int offset)

    Removes the object at the source array offset and copies all other objects to the destination array

    ###### Parameters

    - `sourceArray`: the source array

    - `destinationArray`: the resulting array which should be of the length sourceArray.length - 1

    - `offset`: the offset of the array

  - ### insertObjectAtOffset

    public static void insertObjectAtOffset(Object[] sourceArray, Object[] destinationArray, int offset, Object o)

    Inserts the object at the destination array offset

    ###### Parameters

    - `sourceArray`: the source array

    - `destinationArray`: the resulting array which should be of the length sourceArray.length + 1

    - `offset`: the offset of the array

    - `o`: the object

  - ### indexOf

    public static int indexOf(Object[] arr, Object value)

    Finds the object at the given offset while using the == operator and not the equals method call, it doesn't rely on the ordering of the elements like the Arrays method.

    ###### Parameters

    - `arr`: the array

    - `value`: the value to search

    ###### Returns

    the offset or -1

  - ### downloadUrlToStorage

    public static boolean downloadUrlToStorage(String url, String fileName, boolean showProgress)

    Blocking method that will download the given URL to storage and return when the operation completes

    ###### Parameters

    - `url`: the URL

    - `fileName`: the storage file name

    - `showProgress`: whether to block the UI until download completes/fails

    ###### Returns

    true on success false on error

  - ### downloadUrlToFile

    public static boolean downloadUrlToFile(String url, String fileName, boolean showProgress)

    Blocking method that will download the given URL to the file system storage and return when the operation completes

    ###### Parameters

    - `url`: the URL

    - `fileName`: the file name

    - `showProgress`: whether to block the UI until download completes/fails

    ###### Returns

    true on success false on error

  - ### downloadUrlToStorageInBackground

    public static void downloadUrlToStorageInBackground(String url, String fileName)

    Non-blocking method that will download the given URL to storage in the background and return immediately. This method can be used to fetch data dynamically and asynchronously e.g. in this code it is used to fetch book covers for the `com.codename1.components.ImageViewer`:

        Form hi = new Form("ImageViewer", new BorderLayout());
        final EncodedImage placeholder = EncodedImage.createFromImage(
                FontImage.createMaterial(FontImage.MATERIAL_SYNC, s).
                        scaled(300, 300), false);

        class ImageList implements ListModel {
            private int selection;
            private String[] imageURLs = {
                "http://awoiaf.westeros.org/images/thumb/9/93/AGameOfThrones.jpg/300px-AGameOfThrones.jpg",
                "http://awoiaf.westeros.org/images/thumb/3/39/AClashOfKings.jpg/300px-AClashOfKings.jpg",
                "http://awoiaf.westeros.org/images/thumb/2/24/AStormOfSwords.jpg/300px-AStormOfSwords.jpg",
                "http://awoiaf.westeros.org/images/thumb/a/a3/AFeastForCrows.jpg/300px-AFeastForCrows.jpg",
                "http://awoiaf.westeros.org/images/7/79/ADanceWithDragons.jpg"
            };
            private Image[] images;
            private EventDispatcher listeners = new EventDispatcher();

            public ImageList() {
                this.images = new EncodedImage[imageURLs.length];
            }

            public Image getItemAt(final int index) {
                if(images[index] == null) {
                    images[index] = placeholder;
                    Util.downloadUrlToStorageInBackground(imageURLs[index], "list" + index, (e) -> {
                            try {
                                images[index] = EncodedImage.create(Storage.getInstance().createInputStream("list" + index));
                                listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
                            } catch(IOException err) {
                                err.printStackTrace();
                            }
                    });
                }
                return images[index];
            }

            public int getSize() {
                return imageURLs.length;
            }

            public int getSelectedIndex() {
                return selection;
            }

            public void setSelectedIndex(int index) {
                selection = index;
            }

            public void addDataChangedListener(DataChangedListener l) {
                listeners.addListener(l);
            }

            public void removeDataChangedListener(DataChangedListener l) {
                listeners.removeListener(l);
            }

            public void addSelectionListener(SelectionListener l) {
            }

            public void removeSelectionListener(SelectionListener l) {
            }

            public void addItem(Image item) {
            }

            public void removeItem(int index) {
            }
        };

        ImageList imodel = new ImageList();

        ImageViewer iv = new ImageViewer(imodel.getItemAt(0));
        iv.setImageList(imodel);
        hi.add(BorderLayout.CENTER, iv);

    ###### Parameters

    - `url`: the URL

    - `fileName`: the storage file name

  - ### downloadUrlToFileSystemInBackground

    public static void downloadUrlToFileSystemInBackground(String url, String fileName)

    Non-blocking method that will download the given URL to file system storage in the background and return immediately

    ###### Parameters

    - `url`: the URL

    - `fileName`: the file name

  - ### downloadUrlToStorageInBackground

    public static void downloadUrlToStorageInBackground(String url, String fileName, ActionListener onCompletion)

    Non-blocking method that will download the given URL to storage in the background and return immediately

    ###### Parameters

    - `url`: the URL

    - `fileName`: the storage file name

    - `onCompletion`: invoked when download completes

  - ### downloadUrlToFileSystemInBackground

    public static void downloadUrlToFileSystemInBackground(String url, String fileName, ActionListener onCompletion)

    Non-blocking method that will download the given URL to file system storage in the background and return immediately

    ###### Parameters

    - `url`: the URL

    - `fileName`: the file name

    - `onCompletion`: invoked when download completes

  - ### downloadImageToFileSystem

    public static void downloadImageToFileSystem(String url, String fileName, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)

    Downloads an image to the file system asynchronously. If the image is already downloaded it will just load it directly from the file system.

    ###### Parameters

    - `url`: The URL to download the image from.

    - `fileName`: @param fileName The the path to the file where the image should be downloaded. If this file already exists, it will simply load this file and skip the network request altogether.

    - `onSuccess`: Callback called on success.

    - `onFail`: Callback called if we fail to load the image.

    ###### Since

    3.4

    ###### See also

    - ConnectionRequest#downloadImageToFileSystem(java.lang.String, com.codename1.util.SuccessCallback, com.codename1.util.FailureCallback)

  - ### downloadImageToFileSystem

    public static AsyncResource<Image> downloadImageToFileSystem(String url, String fileName)

    Downloads an image to the file system asynchronously. If the image is already downloaded it will just load it directly from the file system.

    ###### Parameters

    - `url`: The URL to download the image from.

    - `fileName`: @param fileName The the path to the file where the image should be downloaded. If this file already exists, it will simply load this file and skip the network request altogether.

    ###### Since

    7.0

    ###### See also

    - ConnectionRequest#downloadImageToFileSystem(java.lang.String, com.codename1.util.SuccessCallback, com.codename1.util.FailureCallback)

  - ### downloadImageToFileSystem

    public static void downloadImageToFileSystem(String url, String fileName, SuccessCallback<Image> onSuccess)

    Downloads an image to the file system asynchronously. If the image is already downloaded it will just load it directly from the file system.

    ###### Parameters

    - `url`: The URL to download the image from.

    - `fileName`: @param fileName The the path to the file where the image should be downloaded. If this file already exists, it will simply load this file and skip the network request altogether.

    - `onSuccess`: Callback called on success.

    ###### Since

    3.4

    ###### See also

    - ConnectionRequest#downloadImageToFileSystem(java.lang.String, com.codename1.util.SuccessCallback)

  - ### downloadImageToStorage

    public static void downloadImageToStorage(String url, String fileName, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)

    Downloads an image to storage asynchronously. If the image is already downloaded it will just load it directly from storage.

    ###### Parameters

    - `url`: The URL to download the image from.

    - `fileName`: @param fileName The the storage file to save the image to. If this file already exists, it will simply load this file and skip the network request altogether.

    - `onSuccess`: Callback called on success.

    - `onFail`: Callback called if we fail to load the image.

    ###### Since

    3.4

    ###### See also

    - ConnectionRequest#downloadImageToStorage(java.lang.String, com.codename1.util.SuccessCallback, com.codename1.util.FailureCallback)

  - ### downloadImageToStorage

    public static AsyncResource<Image> downloadImageToStorage(String url, String fileName)

    Downloads an image to storage asynchronously. If the image is already downloaded it will just load it directly from storage.

    ###### Parameters

    - `url`: The URL to download the image from.

    - `fileName`: @param fileName The the storage file to save the image to. If this file already exists, it will simply load this file and skip the network request altogether.

    ###### Since

    7.0

    ###### See also

    - ConnectionRequest#downloadImageToStorage(java.lang.String, com.codename1.util.SuccessCallback, com.codename1.util.FailureCallback)

  - ### downloadImageToCache

    public static void downloadImageToCache(String url, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)

    Downloads an image to the cache asynchronously.

    ###### Parameters

    - `url`: The URL to download.

    - `onSuccess`: Callback to run on successful completion.

    - `onFail`: Callback to run if download fails.

  - ### downloadImageToCache

    public static AsyncResource<Image> downloadImageToCache(String url)

    Downloads an image to the cache asynchronously.

    ###### Parameters

    - `url`: The URL of the image to download.

    ###### Returns

    AsyncResource to wrap the Image.

    ###### Since

    7.0

  - ### downloadImageToStorage

    public static void downloadImageToStorage(String url, String fileName, SuccessCallback<Image> onSuccess)

    Downloads an image to storage asynchronously. If the image is already downloaded it will just load it directly from storage.

    ###### Parameters

    - `url`: The URL to download the image from.

    - `fileName`: @param fileName The the storage file to save the image to. If this file already exists, it will simply load this file and skip the network request altogether.

    - `onSuccess`: Callback called on success.

    ###### Since

    3.4

    ###### See also

    - ConnectionRequest#downloadImageToStorage(java.lang.String, com.codename1.util.SuccessCallback)

  - ### sleep

    public static void sleep(int t)

    Shorthand method for Thread sleep that doesn't throw the stupid interrupted checked exception

    ###### Parameters

    - `t`: the time

  - ### wait

    public static void wait(Object o, int t)

    Shorthand method wait method that doesn't throw the stupid interrupted checked exception, it also includes the synchronized block to further reduce code clutter

    ###### Parameters

    - `o`: the object to wait on

    - `t`: the time

  - ### wait

    public static void wait(Object o)

    Shorthand method wait method that doesn't throw the stupid interrupted checked exception, it also includes the synchronized block to further reduce code clutter

    ###### Parameters

    - `o`: the object to wait on

  - ### toBooleanValue

    public static boolean toBooleanValue(Object val)

    Returns true or false based on a "soft" object

    ###### Parameters

    - `val`: a boolean value as a Boolean object, String or number

    ###### Returns

    true or false

  - ### toIntValue

    public static int toIntValue(Object number)

    Returns the number object as an int

    ###### Parameters

    - `number`: this can be a String or any number type

    ###### Returns

    an int value or an exception

  - ### toLongValue

    public static long toLongValue(Object number)

    Returns the number object as a long

    ###### Parameters

    - `number`: this can be a String or any number type

    ###### Returns

    a long value or an exception

  - ### toFloatValue

    public static float toFloatValue(Object number)

    Returns the number object as a float

    ###### Parameters

    - `number`: this can be a String or any number type

    ###### Returns

    a float value or an exception

  - ### toDoubleValue

    public static double toDoubleValue(Object number)

    Returns the number object as a double

    ###### Parameters

    - `number`: this can be a String or any number type

    ###### Returns

    a double value or an exception

  - ### setDateFormatter

    public static void setDateFormatter(SimpleDateFormat formatter)

    Sets a custom formatter to use when toDateValue is invoked

    ###### Parameters

    - `formatter`: the formatter to use

  - ### toDateValue

    public static Date toDateValue(Object o)

    Tries to convert an arbitrary object to a date

    ###### Parameters

    - `o`: an object that can be a string, number or date

    ###### Returns

    a Date object

  - ### xorDecode

    public static String xorDecode(String s)

    Encodes a string in a way that makes it harder to read it "as is" this makes it possible for Strings to be "encoded" within the app and thus harder to discover by a casual search.

    ###### Parameters

    - `s`: the string to decode

    ###### Returns

    the decoded string

  - ### xorEncode

    public static String xorEncode(String s)

    The inverse method of xorDecode, this is normally unnecessary and is here mostly for completeness

    ###### Parameters

    - `s`: a regular string

    ###### Returns

    a String that can be used in the xorDecode method

  - ### guessMimeType

    public static String guessMimeType(String sourceFile) throws IOException

    Tries to determine the mime type of a file based on its first bytes.Direct inspection of the bytes to determine the content type is often more accurate than believing the content type claimed by the `http` server or by the file extension.

    ###### Parameters

    - `sourceFile,`: @param sourceFile, it automatically choose Storage API or FileSystemStorage API

    ###### Returns

    Returns:

      the detected mime type, or "application/octet-stream" if the type is not detected

      ###### Throws

      - `IOException`
    Throws:
      `IOException`

  - ### guessMimeType

    public static String guessMimeType(InputStream in) throws IOException

    Tries to determine the mime type of an InputStream based on its first bytes.Direct inspection of the bytes to determine the content type is often more accurate than believing the content type claimed by the `http` server or by the file extension.

    ###### Parameters

    - `in`

    ###### Returns

    Returns:

      the detected mime type, or "application/octet-stream" if the type is not detected

      ###### Throws

      - `IOException`
    Throws:
      `IOException`

  - ### guessMimeType

    public static String guessMimeType(byte[] data)

    Tries to determine the mime type of a byte array based on its first bytes.Direct inspection of the bytes to determine the content type is often more accurate than believing the content type claimed by the `http` server or by the file extension.

    ###### Parameters

    - `data`

    ###### Returns

    Returns:
      the detected mime type, or "application/octet-stream" if the type is not detected

  - ### getFileSizeWithoutDownload

    public static long getFileSizeWithoutDownload(String url)

    Returns -1 if the content length is unknown, a value greater than 0 if the Content-Length is known.

    ###### Parameters

    - `url`

    ###### Returns

    Content-Length if known

  - ### getFileSizeWithoutDownload

    public static long getFileSizeWithoutDownload(String url, boolean checkPartialDownloadSupport)

    Returns -2 if the server doesn't accept partial downloads (and if checkPartialDownloadSupport is true), -1 if the content length is unknow, a value greater than 0 if the Content-Length is known.

    ###### Parameters

    - `url`

    - `checkPartialDownloadSupport`: @param checkPartialDownloadSupport if true returns -2 if the server doesn't accept partial downloads.

    ###### Returns

    Content-Length if known

  - ### downloadUrlSafely

    public static void downloadUrlSafely(String url, String fileName, OnComplete<Integer> percentageCallback, OnComplete<String> filesavedCallback) throws IOException

    Safely download the given URL to the Storage or to the FileSystemStorage: this method is resistant to network errors and capable of resume the download as soon as network conditions allow and in a completely transparent way for the user; note that in the global network error handling, there must be an automatic

        request.retry();

    , as in the code example below.

    This method is useful if the server correctly returns Content-Length and if it supports partial downloads: if not, it works like a normal download.

    Pros: always allows you to complete downloads, even if very heavy (e.g. 100MB), even if the connection is unstable (network errors) and even if the app goes temporarily in the background (on some platforms the download will continue in the background, on others it will be temporarily suspended).

    Cons: since this method is based on splitting the download into small parts (512kbytes is the default), this approach causes many GET requests that slightly slow down the download and cause more traffic than normally needed.

    Usage example:

        import com.codename1.components.SpanLabel;
        import com.codename1.components.ToastBar;
        import static com.codename1.ui.CN.*;
        import com.codename1.ui.Display;
        import com.codename1.ui.Form;
        import com.codename1.ui.Dialog;
        import com.codename1.ui.Label;
        import com.codename1.ui.plaf.UIManager;
        import com.codename1.ui.util.Resources;
        import com.codename1.io.Log;
        import com.codename1.ui.Toolbar;
        import java.io.IOException;
        import com.codename1.ui.layouts.BoxLayout;
        import com.codename1.io.NetworkEvent;
        import com.codename1.io.Storage;
        import com.codename1.io.Util;
        import java.util.Timer;
        import java.util.TimerTask;

        /**
         * This file was generated by [Codename One](https://www.codenameone.com/) for the purpose
         * of building native mobile applications using Java.
         */
        public class MyApplication {

            private Form current;
            private Resources theme;

            public void init(Object context) {
                // use two network threads instead of one
                updateNetworkThreadCount(2);

                theme = UIManager.initFirstTheme("/theme");

                // Enable Toolbar on all Forms by default
                Toolbar.setGlobalToolbar(true);

                // Pro only feature
                Log.bindCrashProtection(true);

                // Manage both network errors (connectivity issues) and server errors (codes different from 2xx)
                addNetworkAndServerErrorListener();
            }

            public void start() {
                if(current != null){
                    current.show();
                    return;
                }

                String url = "https://www.informatica-libera.net/video/AVO_Cariati_Pasqua_2020.mp4"; // 38 MB

                Form form = new Form("Test Download 38MB", BoxLayout.y());
                Label infoLabel = new Label("Starting download...");
                form.add(infoLabel);

                try {
                    Util.downloadUrlSafely(url, "myHeavyVideo.mp4", (percentage) -> {
                        // percentage callback
                        infoLabel.setText("Downloaded: " + percentage + "%");
                        infoLabel.repaint();
                    }, (filename) -> {
                        // file saved callback
                        infoLabel.setText("Downloaded completed");
                        int fileSizeMB = Storage.getInstance().entrySize(filename) / 1048576;
                        form.add("Checking files size: " + fileSizeMB + " MB");
                        form.revalidate();
                    });
                } catch (IOException ex) {
                    Log.p("Error in downloading: " + url);
                    Log.e(ex);
                    form.add(new SpanLabel("Error in downloading:\n" + url));
                    form.revalidate();
                }

                form.show();

            }

            public void stop() {
                current = getCurrentForm();
                if(current instanceof Dialog) {
                    ((Dialog)current).dispose();
                    current = getCurrentForm();
                }
            }

            public void destroy() {
            }

            private void addNetworkAndServerErrorListener() {
                // The following way to manage network errors is discussed here:
                // https://stackoverflow.com/questions/61993127/distinguish-between-server-side-errors-and-connection-problems
                addNetworkErrorListener(err -> {
                    // prevents the event from propagating
                    err.consume();

                    if (err.getError() != null) {
                        // this is the case of a network error,
                        // like: java.io.IOException: Unreachable
                        Log.p("Error connectiong to: " + err.getConnectionRequest().getUrl(), Log.ERROR);
                        // maybe there are connectivity issues, let's try again
                        ToastBar.showInfoMessage("Reconnect...");
                        Timer timer = new Timer();
                        timer.schedule(new TimerTask() {
        @Override
                            public void run() {
                                err.getConnectionRequest().retry();
                            }
                        }, 2000);
                    } else {
                        // this is the case of a server error
                        // logs the error
                        String errorLog = "REST ERROR\nURL:" + err.getConnectionRequest().getUrl()
                                + "\nMethod: " + err.getConnectionRequest().getHttpMethod()
                                + "\nResponse code: " + err.getConnectionRequest().getResponseCode();
                        if (err.getConnectionRequest().getRequestBody() != null) {
                            errorLog += "\nRequest body: " + err.getConnectionRequest().getRequestBody();
                        }
                        if (err.getConnectionRequest().getResponseData() != null) {
                            errorLog += "\nResponse message: " + new String(err.getConnectionRequest().getResponseData());
                        }
                        if (err.getConnectionRequest().getResponseErrorMessage() != null) {
                            errorLog += "\nResponse error message: " + err.getConnectionRequest().getResponseErrorMessage();
                        }
                        Log.p(errorLog, Log.ERROR);

                        Log.sendLogAsync();
                        ToastBar.showErrorMessage("Server Error", 10000);
                    }
                });
            }

        }

    ###### Parameters

    - `url`

    - `fileName`: @param fileName must be a valid Storage file name or FileSystemStorage file path

    - `percentageCallback`: @param percentageCallback invoked (in EDT) during the download to notify the progress (from 0 to 100); it can be null if you are not interested in monitoring the progress

    - `filesavedCallback`: @param filesavedCallback invoked (in EDT) only when the download is finished; if null, no action is taken

    ###### Throws

    - `IOException`
    Throws:
      `IOException`

  - ### getUUID

    public static String getUUID()

    Creates a new UUID, that is a 128-bit number used to identify information in computer systems. UUIDs aim to be unique for practical purposes.

    This implementation uses the system clock and some device info as seeds for random data, that are enough for practical usage. More specifically, two instances of Random, instantiated with different seeds, are used. The first seed corresponds to the timestamp in which the first object of the static class UUID is created, the second seed is a number (long type) that identifies the current installation of the app and is assumed to be as different as possible from other installations of the app. A unique identifier (long type) associated with the current app installation can be specified by the developer via the Preference "CustomDeviceId__$" (as in the following example) BEFORE the generation of the first UIID, or - if it is not specified - it is obtained from an internal Codename One implementation; in the worst case, if an identifier has not been specified by the developer and Codename One is unable to distinguish the current installation of the app from other installations, an internal algorithm will be used that will generate a number based on some hardware and software characteristics of the device: the number thus generated will be the same on identical models of the same device and with the same version of the operating system, but will vary between different models. Even in the worst case scenario, the probability that two app installations with identical device identifiers will generate the first UIID in the same timestamp is very low.

    As a tip, consider that any alphanumeric text string (corresponding for example to a username) can be converted into a long type number, considering this string as a number based on 36, provided it does not exceed 12 characters. This suggestion is applied in the following example.

    Code example:

        Form hi = new Form("Test UIID", BoxLayout.y());
        Button button = new Button("Generate 10 UIID");
        hi.add(button);
        hi.show();
        button.addActionListener(l -> {
            String myId = "myUsername"; // do not exceed 12 characters
            Preferences.set("CustomDeviceId__$", Long.parseLong(myId, 36));
            hi.add(new SpanLabel("10 Random UUID"));
            for (int i = 0; i < 10; i++) {
                hi.add(new SpanLabel(Util.getUIID()));
            }
            hi.revalidate();
        });

    ###### Returns

    Returns:
      a pseudo-random Universally Unique Identifier in its canonical textual representation

  - ### getUUID

    public static String getUUID(long time, long clockSeqAndNode)

    Creates a custom UUID, from the given two `long` values.

    ###### Parameters

    - `time`: the upper 64 bits

    - `clockSeqAndNode`: the lower 64 bits

    ###### Returns

    Returns:
      a Universally Unique Identifier in its canonical textual representation