Class Util
-
Method Summary
Modifier and TypeMethodDescriptionstatic voidCloses the object (connection, stream etc.) without throwing any exception, even if the object is nullstatic voidcopy(InputStream i, OutputStream o) Copy the input stream into the output stream, closes both streams when finishing or in a case of an exceptionstatic voidcopy(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 exceptionstatic voidcopyNoClose(InputStream i, OutputStream o, int bufferSize) Copy the input stream into the output stream, without closing the streams when donestatic voidcopyNoClose(InputStream i, OutputStream o, int bufferSize, IOProgressListener callback) Copy the input stream into the output stream, without closing the streams when donestatic StringDecodes a String URL encoded URLstatic AsyncResource<Image> Downloads an image to the cache asynchronously.static voiddownloadImageToCache(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 voiddownloadImageToFileSystem(String url, String fileName, SuccessCallback<Image> onSuccess) Downloads an image to the file system asynchronously.static voiddownloadImageToFileSystem(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 voiddownloadImageToStorage(String url, String fileName, SuccessCallback<Image> onSuccess) Downloads an image to storage asynchronously.static voiddownloadImageToStorage(String url, String fileName, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail) Downloads an image to storage asynchronously.static voiddownloadUrlSafely(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 automaticstatic booleandownloadUrlToFile(String url, String fileName, boolean showProgress) Blocking method that will download the given URL to the file system storage and return when the operation completesstatic voiddownloadUrlToFileSystemInBackground(String url, String fileName) Non-blocking method that will download the given URL to file system storage in the background and return immediatelystatic voiddownloadUrlToFileSystemInBackground(String url, String fileName, ActionListener onCompletion) Non-blocking method that will download the given URL to file system storage in the background and return immediatelystatic booleandownloadUrlToStorage(String url, String fileName, boolean showProgress) Blocking method that will download the given URL to storage and return when the operation completesstatic voiddownloadUrlToStorageInBackground(String url, String fileName) Non-blocking method that will download the given URL to storage in the background and return immediately.static voiddownloadUrlToStorageInBackground(String url, String fileName, ActionListener onCompletion) Non-blocking method that will download the given URL to storage in the background and return immediatelystatic StringencodeBody(byte[] buf) Encode a string for HTML post requests matching the style used in application/x-www-form-urlencodedstatic StringencodeBody(char[] buf) Encode a string for HTML post requests matching the style used in application/x-www-form-urlencodedstatic StringencodeBody(String str) Encode a string for HTML post requests matching the style used in application/x-www-form-urlencodedstatic StringencodeUrl(byte[] buf) Encode a string for HTML requestsstatic StringencodeUrl(char[] buf) Encode a string for HTML requestsstatic StringEncode a string for HTML requestsstatic StringEncodes the provided string as a URL (with %20 for spaces).static longReturns -1 if the content length is unknown, a value greater than 0 if the Content-Length is known.static longgetFileSizeWithoutDownload(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 StringThese chars will not be encoded by the encoding method in this class as requested in RFE 427 http://java.net/jira/browse/LWUIT-427static InputStreamReadergetReader(InputStream in) Helper to get a reader from an input stream with UTF-8 encodingstatic StringgetURLBasePath(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 StringgetURLHost(String url) Returns the URL's host portionstatic StringgetURLPath(String url) Returns the URL's pathstatic StringgetURLProtocol(String url) Returns the protocol of an absolute URL e.g.static StringgetUUID()Creates a new UUID, that is a 128-bit number used to identify information in computer systems.static StringgetUUID(long time, long clockSeqAndNode) Creates a custom UUID, from the given twolongvalues.static OutputStreamWritergetWriter(OutputStream out) Helper to get a writer from an output stream with UTF-8 encodingstatic StringguessMimeType(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 thehttpserver or by the file extension.static StringTries 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 thehttpserver or by the file extension.static StringguessMimeType(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 thehttpserver or by the file extension.static intFinds 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 voidinsertObjectAtOffset(Object[] sourceArray, Object[] destinationArray, int offset, Object o) Inserts the object at the destination array offsetstatic booleanThis method allows working around issue 58static booleanThis method allows working around issue 58static booleanThis method allows working around issue 58static booleanThis method allows working around issue 58static booleanThis method allows working around issue 58static booleanThis method allows working around issue 58static booleanThis method allows working around issue 58static voidmergeArrays(Object[] arr1, Object[] arr2, Object[] destinationArray) Merges arrays into one larger arraystatic intreadAll(InputStream i, byte[] b) Reads until the array is full or until the stream endsstatic voidreadFully(InputStream i, byte[] b) The read fully method from data input stream is very useful for all types of streams...static voidreadFully(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[]Converts a small input stream to a byte arraystatic ObjectreadObject(DataInputStream input) Reads an object from the stream, notice that this is the inverse of thejava.io.DataOutputStream).static StringreadToString(File file) Reads the contents of a file to a string.static StringreadToString(File file, String charset) Reads the contents of a file to a string.static StringReads an input stream to a stringstatic StringreadToString(InputStream i, String encoding) Reads an input stream to a stringstatic StringreadToString(Reader reader) Reads a reader to a stringstatic StringReads a UTF string that may be null previously written by writeUTFstatic voidRegisters this externalizable so readObject will be able to load such objects.static voidRegisters this externalizable so readObject will be able to load such objects.static StringrelativeToAbsolute(String baseURL, String relativeURL) Converts a relative url e.g.: /myfile.html to an absolute urlstatic voidremoveObjectAtOffset(Object[] sourceArray, Object[] destinationArray, int offset) Removes the object at the source array offset and copies all other objects to the destination arraystatic voidremoveObjectAtOffset(Object[] sourceArray, Object[] destinationArray, Object o) Removes the object at the source array offset and copies all other objects to the destination arraystatic voidsetDateFormatter(SimpleDateFormat formatter) Sets a custom formatter to use when toDateValue is invokedstatic voidThese chars will not be encoded by the encoding method in this class as requested in RFE 427 http://java.net/jira/browse/LWUIT-427static voidInvoked internally from Display, this method is for internal use onlystatic voidsleep(int t) Shorthand method for Thread sleep that doesn't throw the stupid interrupted checked exceptionstatic String[]Provides a utility method breaks a given String to array of String according to the given separatorstatic booleantoBooleanValue(Object val) Returns true or false based on a "soft" objectstatic char[]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 behaviorstatic DateTries to convert an arbitrary object to a datestatic doubletoDoubleValue(Object number) Returns the number object as a doublestatic floattoFloatValue(Object number) Returns the number object as a floatstatic inttoIntValue(Object number) Returns the number object as an intstatic longtoLongValue(Object number) Returns the number object as a longstatic voidShorthand method wait method that doesn't throw the stupid interrupted checked exception, it also includes the synchronized block to further reduce code clutterstatic voidShorthand method wait method that doesn't throw the stupid interrupted checked exception, it also includes the synchronized block to further reduce code clutterstatic voidwriteObject(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 voidwriteStringToFile(File file, String contents) Writes a string to a file using UTF-8 encoding.static voidwriteStringToFile(File file, String contents, String charset) Writes a string to a file.static voidwriteUTF(String s, DataOutputStream d) Writes a string with a null flag, this allows a String which may be nullstatic StringEncodes 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 StringThe inverse method of xorDecode, this is normally unnecessary and is here mostly for completeness
-
Method Details
-
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
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
Helper to get a reader from an input stream with UTF-8 encoding
Parameters
in: the input stream
Returns
the reader
-
getWriter
Helper to get a writer from an output stream with UTF-8 encoding
Parameters
out: the output stream
Returns
the writer
-
copy
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
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
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
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
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
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
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
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
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
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
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
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
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.Externalizableinterface:// File: Main.java public 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 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
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.Externalizableinterface:// File: Main.java public 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 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
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.Externalizableinterface:// File: Main.java public 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 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
-
instanceofByteArray
-
instanceofShortArray
-
instanceofLongArray
-
instanceofIntArray
-
instanceofFloatArray
-
instanceofDoubleArray
-
readObject
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.Externalizableinterface:// File: Main.java public 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 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
-
encodeUrl
-
toCharArray
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
-
encodeBody
-
encodeUrl
Encode a string for HTML requests
Parameters
buf: none encoded string
Returns
encoded string
Deprecated
use encodeUrl(char[]) instead
-
encodeUrl
Encode a string for HTML requests
Parameters
buf: none encoded string
Returns
encoded string
-
encodeBody
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
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
-
getURLProtocol
-
getURLHost
-
getURLPath
-
getURLBasePath
-
writeUTF
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
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
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
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
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
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
Invoked internally from Display, this method is for internal use only
Parameters
impl: implementation instance
-
mergeArrays
-
removeObjectAtOffset
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
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
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
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
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
-
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
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
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
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
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
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
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
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
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
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
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
Sets a custom formatter to use when toDateValue is invoked
Parameters
formatter: the formatter to use
-
toDateValue
-
xorDecode
-
xorEncode
-
guessMimeType
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
httpserver 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
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
httpserver 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
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
httpserver or by the file extension.Parameters
data
Returns
- Returns:
- the detected mime type, or "application/octet-stream" if the type is not detected
-
getFileSizeWithoutDownload
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
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
.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
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
Creates a custom UUID, from the given two
longvalues.Parameters
-
time: the upper 64 bits -
clockSeqAndNode: the lower 64 bits
Returns
- Returns:
- a Universally Unique Identifier in its canonical textual representation
-
-