public final class Util

  1. Object
  2. Util
Various utility methods used for HTTP/IO operations

Methods

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
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
public static InputStreamReader getReader(InputStream in)Helper to get a reader from an input stream with UTF-8 encoding
public static OutputStreamWriter getWriter(OutputStream out)Helper to get a writer from an output stream with UTF-8 encoding
public static void copy(InputStream i, OutputStream o) throws IOExceptionCopy the input stream into the output stream, closes both streams when finishing or in a case of an exception
public static void copyNoClose(InputStream i, OutputStream o, int bufferSize) throws IOExceptionCopy the input stream into the output stream, without closing the streams when done
public static void copyNoClose(InputStream i, OutputStream o, int bufferSize, IOProgressListener callback) throws IOExceptionCopy the input stream into the output stream, without closing the streams when done
public static void copy(InputStream i, OutputStream o, int bufferSize) throws IOExceptionCopy the input stream into the output stream, closes both streams when finishing or in a case of an exception
public static void cleanup(Object o)Closes the object (connection, stream etc.) without throwing any exception, even if the object is null
public static String readToString(InputStream i) throws IOExceptionReads an input stream to a string
public static String readToString(File file, String charset) throws IOExceptionReads the contents of a file to a string.
public static String readToString(File file) throws IOExceptionReads the contents of a file to a string.
public static void writeStringToFile(File file, String contents) throws IOExceptionWrites a string to a file using UTF-8 encoding.
public static void writeStringToFile(File file, String contents, String charset) throws IOExceptionWrites a string to a file.
public static String readToString(InputStream i, String encoding) throws IOExceptionReads an input stream to a string
public static String readToString(Reader reader) throws IOExceptionReads a reader to a string
public static byte[] readInputStream(InputStream i) throws IOExceptionConverts a small input stream to a byte array
public static void register(Externalizable e)Registers this externalizable so readObject will be able to load such objects.
public static void register(String id, Class c)Registers this externalizable so readObject will be able to load such objects.
public static void writeObject(Object o, DataOutputStream out) throws IOExceptionWrites an object to the given output stream, notice that it should be externalizable or one of the supported types.
public static boolean instanceofObjArray(Object o)Deprecated This method allows working around issue 58
public static boolean instanceofByteArray(Object o)Deprecated This method allows working around issue 58
public static boolean instanceofShortArray(Object o)Deprecated This method allows working around issue 58
public static boolean instanceofLongArray(Object o)Deprecated This method allows working around issue 58
public static boolean instanceofIntArray(Object o)Deprecated This method allows working around issue 58
public static boolean instanceofFloatArray(Object o)Deprecated This method allows working around issue 58
public static boolean instanceofDoubleArray(Object o)Deprecated This method allows working around issue 58
public static Object readObject(DataInputStream input) throws IOExceptionReads an object from the stream, notice that this is the inverse of the java.io.DataOutputStream).
public static String encodeUrl(String str)Encode a string for HTML requests
public static String encodeUrl(String str, String doNotEncodeChars)Encodes the provided string as a URL (with %20 for spaces).
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
public static String decode(String s, String enc, boolean plusToSpace)Decodes a String URL encoded URL
public static String encodeBody(String str)Encode a string for HTML post requests matching the style used in application/x-www-form-urlencoded
public static String encodeUrl(byte[] buf)Deprecated Encode a string for HTML requests
public static String encodeUrl(char[] buf)Encode a string for HTML requests
public static String encodeBody(char[] buf)Encode a string for HTML post requests matching the style used in application/x-www-form-urlencoded
public static String encodeBody(byte[] buf)Deprecated Encode a string for HTML post requests matching the style used in application/x-www-form-urlencoded
public static String relativeToAbsolute(String baseURL, String relativeURL)Converts a relative url e.g.: /myfile.html to an absolute url
public static String getURLProtocol(String url)Returns the protocol of an absolute URL e.g. http, https etc.
public static String getURLHost(String url)Returns the URL’s host portion
public static String getURLPath(String url)Returns the URL’s path
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/
public static void writeUTF(String s, DataOutputStream d) throws IOExceptionWrites a string with a null flag, this allows a String which may be null
public static String readUTF(DataInputStream d) throws IOExceptionReads a UTF string that may be null previously written by writeUTF
public static void readFully(InputStream i, byte[] b) throws IOExceptionThe read fully method from data input stream is very useful for all types of streams…
public static void readFully(InputStream i, byte[] b, int off, int len) throws IOExceptionThe read fully method from data input stream is very useful for all types of streams…
public static int readAll(InputStream i, byte[] b) throws IOExceptionReads until the array is full or until the stream ends
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
public static void setImplementation(CodenameOneImplementation impl)Invoked internally from Display, this method is for internal use only
public static void secureRandomBytes(byte[] out)Fills out with cryptographically secure random bytes.
public static byte[] aesEncrypt(String transformation, byte[] key, byte[] iv, byte[] aad, byte[] plaintext)AES encryption.
public static byte[] aesDecrypt(String transformation, byte[] key, byte[] iv, byte[] aad, byte[] ciphertext)AES decryption – counterpart to aesEncrypt.
public static byte[] rsaEncrypt(String transformation, byte[] publicKeyX509, byte[] plaintext)RSA encryption.
public static byte[] rsaDecrypt(String transformation, byte[] privateKeyPkcs8, byte[] ciphertext)RSA decryption.
public static byte[] cryptoSign(String algorithm, String keyAlgorithm, byte[] privateKeyPkcs8, byte[] data)Computes a signature.
public static boolean cryptoVerify(String algorithm, String keyAlgorithm, byte[] publicKeyX509, byte[] data, byte[] signature)Verifies a signature.
public static byte[][] generateRsaKeyPair(int bits)Generates an RSA key pair.
public static byte[] generateSymmetricKey(int bytes)Generates bytes of fresh symmetric key material.
public static void mergeArrays(Object[] arr1, Object[] arr2, Object[] destinationArray)Merges arrays into one larger array
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
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
public static void insertObjectAtOffset(Object[] sourceArray, Object[] destinationArray, int offset, Object o)Inserts the object at the destination array offset
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.
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
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
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.
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
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
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
public static void downloadImageToFileSystem(String url, String fileName, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)Downloads an image to the file system asynchronously.
public static AsyncResource<Image> downloadImageToFileSystem(String url, String fileName)Downloads an image to the file system asynchronously.
public static void downloadImageToFileSystem(String url, String fileName, SuccessCallback<Image> onSuccess)Downloads an image to the file system asynchronously.
public static void downloadImageToStorage(String url, String fileName, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)Downloads an image to storage asynchronously.
public static AsyncResource<Image> downloadImageToStorage(String url, String fileName)Downloads an image to storage asynchronously.
public static void downloadImageToCache(String url, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)Downloads an image to the cache asynchronously.
public static AsyncResource<Image> downloadImageToCache(String url)Downloads an image to the cache asynchronously.
public static void downloadImageToStorage(String url, String fileName, SuccessCallback<Image> onSuccess)Downloads an image to storage asynchronously.
public static void sleep(int t)Shorthand method for Thread sleep that doesn’t throw the stupid interrupted checked exception
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
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
public static boolean toBooleanValue(Object val)Returns true or false based on a “soft” object
public static int toIntValue(Object number)Returns the number object as an int
public static long toLongValue(Object number)Returns the number object as a long
public static float toFloatValue(Object number)Returns the number object as a float
public static double toDoubleValue(Object number)Returns the number object as a double
public static void setDateFormatter(SimpleDateFormat formatter)Sets a custom formatter to use when toDateValue is invoked
public static Date toDateValue(Object o)Tries to convert an arbitrary object to a date
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.
public static String xorEncode(String s)The inverse method of xorDecode, this is normally unnecessary and is here mostly for completeness
public static String guessMimeType(String sourceFile) throws IOExceptionTries 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.
public static String guessMimeType(InputStream in) throws IOExceptionTries 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.
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.
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.
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.
public static void downloadUrlSafely(String url, String fileName, OnComplete<Integer> percentageCallback, OnComplete<String> filesavedCallback) throws IOExceptionSafely 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; no…
public static String getUUID()Creates a new UUID, that is a 128-bit number used to identify information in computer systems.
public static String getUUID(long time, long clockSeqAndNode)Creates a custom UUID, from the given two long values.

Inherited methods

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 String
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 InputStream
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 OutputStream
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 InputStream
source
o OutputStream
destination

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 InputStream
source
o OutputStream
destination
bufferSize int
the size of the buffer, which should be a power of 2 large enough

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 InputStream
source
o OutputStream
destination
bufferSize int
the size of the buffer, which should be a power of 2 large enough
callback IOProgressListener
called after each copy step

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 InputStream
source
o OutputStream
destination
bufferSize int
the size of the buffer, which should be a power of 2 large enough

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 Object
Connection, Stream or other closeable object

readToString

public static String readToString(InputStream i) throws IOException
Reads an input stream to a string

Parameters

i InputStream
the input stream

Returns

a UTF-8 string

Throws

IOException
thrown by the stream

readToString

public static String readToString(File file, String charset) throws IOException
Reads the contents of a file to a string.

Parameters

file File
The file to read.
charset String
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.

readToString

public static String readToString(File file) throws IOException
Reads the contents of a file to a string. Uses UTF-8 encoding.

Parameters

file 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.

writeStringToFile

public static void writeStringToFile(File file, String contents) throws IOException
Writes a string to a file using UTF-8 encoding.

Parameters

file File
The file to write to.
contents String
The contents to write to the file.

Throws

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

writeStringToFile

public static void writeStringToFile(File file, String contents, String charset) throws IOException
Writes a string to a file.

Parameters

file File
The file to write to.
contents String
The contents to write to the file.
charset String
The charset to use. If null, it defaults to UTF-8

Throws

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

readToString

public static String readToString(InputStream i, String encoding) throws IOException
Reads an input stream to a string

Parameters

i InputStream
the input stream
encoding String
the encoding of the stream

Returns

a string

Throws

IOException
thrown by the stream

readToString

public static String readToString(Reader reader) throws IOException
Reads a reader to a string

Returns

a string

Throws

IOException
thrown by the stream

readInputStream

public static byte[] readInputStream(InputStream i) throws IOException
Converts a small input stream to a byte array

Parameters

i InputStream
the stream to convert

Returns

byte array of the content of the stream

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 Externalizable
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 String
id of the externalizable
c Class
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 Object
the object to write which can be null
out DataOutputStream
the destination output stream

Throws

IOException
thrown by the stream

instanceofObjArray

public static boolean instanceofObjArray(Object o)
Deprecated. this method serves as a temporary workaround for an XMLVM bug and will be removed once the bug is fixed
This method allows working around issue 58

Parameters

o Object
object to test

Returns

true if it matches the state

instanceofByteArray

public static boolean instanceofByteArray(Object o)
Deprecated. this method serves as a temporary workaround for an XMLVM bug and will be removed once the bug is fixed
This method allows working around issue 58

Parameters

o Object
object to test

Returns

true if it matches the state

instanceofShortArray

public static boolean instanceofShortArray(Object o)
Deprecated. this method serves as a temporary workaround for an XMLVM bug and will be removed once the bug is fixed
This method allows working around issue 58

Parameters

o Object
object to test

Returns

true if it matches the state

instanceofLongArray

public static boolean instanceofLongArray(Object o)
Deprecated. this method serves as a temporary workaround for an XMLVM bug and will be removed once the bug is fixed
This method allows working around issue 58

Parameters

o Object
object to test

Returns

true if it matches the state

instanceofIntArray

public static boolean instanceofIntArray(Object o)
Deprecated. this method serves as a temporary workaround for an XMLVM bug and will be removed once the bug is fixed
This method allows working around issue 58

Parameters

o Object
object to test

Returns

true if it matches the state

instanceofFloatArray

public static boolean instanceofFloatArray(Object o)
Deprecated. this method serves as a temporary workaround for an XMLVM bug and will be removed once the bug is fixed
This method allows working around issue 58

Parameters

o Object
object to test

Returns

true if it matches the state

instanceofDoubleArray

public static boolean instanceofDoubleArray(Object o)
Deprecated. this method serves as a temporary workaround for an XMLVM bug and will be removed once the bug is fixed
This method allows working around issue 58

Parameters

o Object
object to test

Returns

true if it matches the state

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 DataInputStream
the source input stream

Throws

IOException
thrown by the stream

encodeUrl

public static String encodeUrl(String str)
Encode a string for HTML requests

Parameters

str String
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 String
The URL to encode
doNotEncodeChars String
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 String
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 String
the string
enc String
the encoding (defaults to UTF-8 if null)
plusToSpace boolean
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 String
none encoded string

Returns

encoded string

encodeUrl

public static String encodeUrl(byte[] buf)
Deprecated. use encodeUrl(char[]) instead
Encode a string for HTML requests

Parameters

buf byte[]
none encoded string

Returns

encoded string

encodeUrl

public static String encodeUrl(char[] buf)
Encode a string for HTML requests

Parameters

buf char[]
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 char[]
none encoded string

Returns

encoded string

encodeBody

public static String encodeBody(byte[] buf)
Deprecated. use encodeUrl(char[]) instead
Encode a string for HTML post requests matching the style used in application/x-www-form-urlencoded

Parameters

buf byte[]
none encoded string

Returns

encoded string

relativeToAbsolute

public static String relativeToAbsolute(String baseURL, String relativeURL)
Converts a relative url e.g.: /myfile.html to an absolute url

Parameters

baseURL String
a source URL whose properties should be used to construct the actual URL
relativeURL String
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 String
absolute URL

Returns

protocol

getURLHost

public static String getURLHost(String url)
Returns the URL’s host portion

Parameters

url String
absolute URL

Returns

the domain of the URL

getURLPath

public static String getURLPath(String url)
Returns the URL’s path

Parameters

url String
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 String
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 String
the string to write
d DataOutputStream
the destination output stream

readUTF

public static String readUTF(DataInputStream d) throws IOException
Reads a UTF string that may be null previously written by writeUTF

Parameters

d DataInputStream
the stream

Returns

a string or null

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

i InputStream
Not documented.
b byte[]
the buffer into which the data is read.

Throws

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

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

i InputStream
Not documented.
b byte[]
the buffer into which the data is read.
off int
the start offset of the data.
len int
the number of bytes to read.

Throws

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

readAll

public static int readAll(InputStream i, byte[] b) throws IOException
Reads until the array is full or until the stream ends

Parameters

i InputStream
Not documented.
b byte[]
the buffer into which the data is read.

Returns

the amount read

Throws

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

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 String
the String to break
separator String
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 CodenameOneImplementation
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 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.

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 Object[]
the source array
destinationArray Object[]
the resulting array which should be of the length sourceArray.length - 1
o Object
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 Object[]
the source array
destinationArray Object[]
the resulting array which should be of the length sourceArray.length - 1
offset int
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 Object[]
the source array
destinationArray Object[]
the resulting array which should be of the length sourceArray.length + 1
offset int
the offset of the array
o Object
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 Object[]
the array
value Object
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 String
the URL
fileName String
the storage file name
showProgress boolean
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 String
the URL
fileName String
the file name
showProgress boolean
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 String
the URL
fileName String
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 String
the URL
fileName String
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 String
the URL
fileName String
the storage file name
onCompletion ActionListener
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 String
the URL
fileName String
the file name
onCompletion ActionListener
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 String
The URL to download the image from.
fileName String
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 SuccessCallback<Image>
Callback called on success.
onFail FailureCallback<Image>
Callback called if we fail to load the image.

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 String
The URL to download the image from.
fileName String
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.

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 String
The URL to download the image from.
fileName String
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 SuccessCallback<Image>
Callback called on success.

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 String
The URL to download the image from.
fileName String
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 SuccessCallback<Image>
Callback called on success.
onFail FailureCallback<Image>
Callback called if we fail to load the image.

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 String
The URL to download the image from.
fileName String
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.

downloadImageToCache

public static void downloadImageToCache(String url, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)
Downloads an image to the cache asynchronously.

Parameters

url String
The URL to download.
onSuccess SuccessCallback<Image>
Callback to run on successful completion.
onFail FailureCallback<Image>
Callback to run if download fails.

downloadImageToCache

public static AsyncResource<Image> downloadImageToCache(String url)
Downloads an image to the cache asynchronously.

Parameters

url String
The URL of the image to download.

Returns

AsyncResource to wrap the Image.

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 String
The URL to download the image from.
fileName String
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 SuccessCallback<Image>
Callback called on success.

sleep

public static void sleep(int t)
Shorthand method for Thread sleep that doesn’t throw the stupid interrupted checked exception

Parameters

t int
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 Object
the object to wait on
t int
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 Object
the object to wait on

toBooleanValue

public static boolean toBooleanValue(Object val)
Returns true or false based on a “soft” object

Parameters

val Object
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 Object
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 Object
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 Object
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 Object
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 SimpleDateFormat
the formatter to use

toDateValue

public static Date toDateValue(Object o)
Tries to convert an arbitrary object to a date

Parameters

o Object
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 String
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 String
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.

Returns

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

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.

Returns

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

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.

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.

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 String
Not documented.
checkPartialDownloadSupport boolean
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 String
Not documented.
fileName String
must be a valid Storage file name or FileSystemStorage file path
percentageCallback OnComplete<Integer>
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 OnComplete<String>
invoked (in EDT) only when the download is finished; if null, no action is taken

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

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 long
the upper 64 bits
clockSeqAndNode long
the lower 64 bits

Returns

a Universally Unique Identifier in its canonical textual representation