public final class Util
- Object
- Util
Methods
Inherited methods
Method details
getIgnorCharsWhileEncoding
public static String getIgnorCharsWhileEncoding()Returns
setIgnorCharsWhileEncoding
public static void setIgnorCharsWhileEncoding(String s)Parameters
sString- set of characters to skip when encoding
getReader
public static InputStreamReader getReader(InputStream in)Parameters
inInputStream- the input stream
Returns
getWriter
public static OutputStreamWriter getWriter(OutputStream out)Parameters
outOutputStream- the output stream
Returns
copy
public static void copy(InputStream i, OutputStream o)
throws IOExceptionParameters
iInputStream- source
oOutputStream- destination
Throws
copyNoClose
public static void copyNoClose(InputStream i, OutputStream o, int bufferSize)
throws IOExceptionParameters
iInputStream- source
oOutputStream- destination
bufferSizeint- the size of the buffer, which should be a power of 2 large enough
Throws
copyNoClose
public static void copyNoClose(InputStream i, OutputStream o, int bufferSize, IOProgressListener callback)
throws IOExceptionParameters
iInputStream- source
oOutputStream- destination
bufferSizeint- the size of the buffer, which should be a power of 2 large enough
callbackIOProgressListener- called after each copy step
Throws
copy
public static void copy(InputStream i, OutputStream o, int bufferSize)
throws IOExceptionParameters
iInputStream- source
oOutputStream- destination
bufferSizeint- the size of the buffer, which should be a power of 2 large enough
Throws
cleanup
public static void cleanup(Object o)Parameters
oObject- Connection, Stream or other closeable object
readToString
public static String readToString(InputStream i)
throws IOExceptionParameters
iInputStream- the input stream
Returns
Throws
IOException- thrown by the stream
readToString
public static String readToString(File file, String charset)
throws IOExceptionParameters
fileFile- The file to read.
charsetString- The Charset to use to write the file.
Returns
Throws
IOException- If the file does not exist, or cannot be read for some reason.
readToString
public static String readToString(File file)
throws IOExceptionParameters
fileFile- The file to read.
Returns
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 IOExceptionParameters
fileFile- The file to write to.
contentsString- 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 IOExceptionParameters
fileFile- The file to write to.
contentsString- The contents to write to the file.
charsetString- 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 IOExceptionParameters
iInputStream- the input stream
encodingString- the encoding of the stream
Returns
Throws
IOException- thrown by the stream
readToString
public static String readToString(Reader reader)
throws IOExceptionReturns
Throws
IOException- thrown by the stream
readInputStream
public static byte[] readInputStream(InputStream i)
throws IOExceptionParameters
iInputStream- the stream to convert
Returns
Throws
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
eExternalizable- 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
idString- id of the externalizable
cClass- the class for the externalizable
writeObject
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.
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
oObject- the object to write which can be null
outDataOutputStream- the destination output stream
Throws
IOException- thrown by the stream
instanceofObjArray
public static boolean instanceofObjArray(Object o)Parameters
oObject- object to test
Returns
instanceofByteArray
public static boolean instanceofByteArray(Object o)Parameters
oObject- object to test
Returns
instanceofShortArray
public static boolean instanceofShortArray(Object o)Parameters
oObject- object to test
Returns
instanceofLongArray
public static boolean instanceofLongArray(Object o)Parameters
oObject- object to test
Returns
instanceofIntArray
public static boolean instanceofIntArray(Object o)Parameters
oObject- object to test
Returns
instanceofFloatArray
public static boolean instanceofFloatArray(Object o)Parameters
oObject- object to test
Returns
instanceofDoubleArray
public static boolean instanceofDoubleArray(Object o)Parameters
oObject- object to test
Returns
readObject
public static Object readObject(DataInputStream input)
throws IOExceptionReads 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
inputDataInputStream- the source input stream
Throws
IOException- thrown by the stream
encodeUrl
public static String encodeUrl(String str)Parameters
strString- none encoded string
Returns
encodeUrl
public static String encodeUrl(String str, String doNotEncodeChars)Parameters
strString- The URL to encode
doNotEncodeCharsString- A string whose characters will not be encoded.
toCharArray
public static char[] toCharArray(String s)Parameters
sString- a string
Returns
decode
public static String decode(String s, String enc, boolean plusToSpace)Parameters
sString- the string
encString- the encoding (defaults to UTF-8 if null)
plusToSpaceboolean- true if plus signs be converted to spaces
Returns
encodeBody
public static String encodeBody(String str)Parameters
strString- none encoded string
Returns
encodeUrl
public static String encodeUrl(byte[] buf)Parameters
bufbyte[]- none encoded string
Returns
encodeUrl
public static String encodeUrl(char[] buf)Parameters
bufchar[]- none encoded string
Returns
encodeBody
public static String encodeBody(char[] buf)Parameters
bufchar[]- none encoded string
Returns
encodeBody
public static String encodeBody(byte[] buf)Parameters
bufbyte[]- none encoded string
Returns
relativeToAbsolute
public static String relativeToAbsolute(String baseURL, String relativeURL)Parameters
baseURLString- a source URL whose properties should be used to construct the actual URL
relativeURLString- relative address
Returns
getURLProtocol
public static String getURLProtocol(String url)Parameters
urlString- absolute URL
Returns
getURLHost
public static String getURLHost(String url)Parameters
urlString- absolute URL
Returns
getURLPath
public static String getURLPath(String url)Parameters
urlString- absolute URL
Returns
getURLBasePath
public static String getURLBasePath(String url)Parameters
urlString- absolute URL
Returns
writeUTF
public static void writeUTF(String s, DataOutputStream d)
throws IOExceptionParameters
sString- the string to write
dDataOutputStream- the destination output stream
Throws
readUTF
public static String readUTF(DataInputStream d)
throws IOExceptionParameters
dDataInputStream- the stream
Returns
Throws
readFully
public static void readFully(InputStream i, byte[] b)
throws IOExceptionParameters
iInputStream- Not documented.
bbyte[]- 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 IOExceptionParameters
iInputStream- Not documented.
bbyte[]- the buffer into which the data is read.
offint- the start offset of the data.
lenint- 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 IOExceptionParameters
iInputStream- Not documented.
bbyte[]- the buffer into which the data is read.
Returns
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)Parameters
originalString- the String to break
separatorString- the pattern to look in the original String
Returns
setImplementation
public static void setImplementation(CodenameOneImplementation impl)Parameters
implCodenameOneImplementation- implementation instance
secureRandomBytes
public static void secureRandomBytes(byte[] out)out with cryptographically secure random bytes. Used by
SecureRandom.aesEncrypt
public static byte[] aesEncrypt(String transformation, byte[] key, byte[] iv, byte[] aad, byte[] plaintext)CodenameOneImplementation.aesEncrypt for the
parameter contract. Used by Cipher.aesDecrypt
public static byte[] aesDecrypt(String transformation, byte[] key, byte[] iv, byte[] aad, byte[] ciphertext)aesEncrypt.rsaEncrypt
public static byte[] rsaEncrypt(String transformation, byte[] publicKeyX509, byte[] plaintext)rsaDecrypt
public static byte[] rsaDecrypt(String transformation, byte[] privateKeyPkcs8, byte[] ciphertext)cryptoSign
public static byte[] cryptoSign(String algorithm, String keyAlgorithm, byte[] privateKeyPkcs8, byte[] data)cryptoVerify
public static boolean cryptoVerify(String algorithm, String keyAlgorithm, byte[] publicKeyX509, byte[] data, byte[] signature)generateRsaKeyPair
public static byte[][] generateRsaKeyPair(int bits){publicKeyX509, privateKeyPkcs8}.generateSymmetricKey
public static byte[] generateSymmetricKey(int bytes)bytes of fresh symmetric key material.mergeArrays
public static void mergeArrays(Object[] arr1, Object[] arr2, Object[] destinationArray)removeObjectAtOffset
public static void removeObjectAtOffset(Object[] sourceArray, Object[] destinationArray, Object o)Parameters
sourceArrayObject[]- the source array
destinationArrayObject[]- the resulting array which should be of the length sourceArray.length - 1
oObject- the object to remove from the array
removeObjectAtOffset
public static void removeObjectAtOffset(Object[] sourceArray, Object[] destinationArray, int offset)Parameters
sourceArrayObject[]- the source array
destinationArrayObject[]- the resulting array which should be of the length sourceArray.length - 1
offsetint- the offset of the array
insertObjectAtOffset
public static void insertObjectAtOffset(Object[] sourceArray, Object[] destinationArray, int offset, Object o)Parameters
sourceArrayObject[]- the source array
destinationArrayObject[]- the resulting array which should be of the length sourceArray.length + 1
offsetint- the offset of the array
oObject- the object
indexOf
public static int indexOf(Object[] arr, Object value)Parameters
arrObject[]- the array
valueObject- the value to search
Returns
downloadUrlToStorage
public static boolean downloadUrlToStorage(String url, String fileName, boolean showProgress)Parameters
urlString- the URL
fileNameString- the storage file name
showProgressboolean- whether to block the UI until download completes/fails
Returns
downloadUrlToFile
public static boolean downloadUrlToFile(String url, String fileName, boolean showProgress)Parameters
urlString- the URL
fileNameString- the file name
showProgressboolean- whether to block the UI until download completes/fails
Returns
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
urlString- the URL
fileNameString- the storage file name
downloadUrlToFileSystemInBackground
public static void downloadUrlToFileSystemInBackground(String url, String fileName)Parameters
urlString- the URL
fileNameString- the file name
downloadUrlToStorageInBackground
public static void downloadUrlToStorageInBackground(String url, String fileName, ActionListener onCompletion)Parameters
urlString- the URL
fileNameString- the storage file name
onCompletionActionListener- invoked when download completes
downloadUrlToFileSystemInBackground
public static void downloadUrlToFileSystemInBackground(String url, String fileName, ActionListener onCompletion)Parameters
urlString- the URL
fileNameString- the file name
onCompletionActionListener- invoked when download completes
downloadImageToFileSystem
public static void downloadImageToFileSystem(String url, String fileName, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)Parameters
urlString- The URL to download the image from.
fileNameString- 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.
onSuccessSuccessCallback<Image>- Callback called on success.
onFailFailureCallback<Image>- Callback called if we fail to load the image.
downloadImageToFileSystem
public static AsyncResource<Image> downloadImageToFileSystem(String url, String fileName)Parameters
urlString- The URL to download the image from.
fileNameString- 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)Parameters
urlString- The URL to download the image from.
fileNameString- 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.
onSuccessSuccessCallback<Image>- Callback called on success.
downloadImageToStorage
public static void downloadImageToStorage(String url, String fileName, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)Parameters
urlString- The URL to download the image from.
fileNameString- 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.
onSuccessSuccessCallback<Image>- Callback called on success.
onFailFailureCallback<Image>- Callback called if we fail to load the image.
downloadImageToStorage
public static AsyncResource<Image> downloadImageToStorage(String url, String fileName)Parameters
urlString- The URL to download the image from.
fileNameString- 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)Parameters
urlString- The URL to download.
onSuccessSuccessCallback<Image>- Callback to run on successful completion.
onFailFailureCallback<Image>- Callback to run if download fails.
downloadImageToCache
public static AsyncResource<Image> downloadImageToCache(String url)Parameters
urlString- The URL of the image to download.
Returns
downloadImageToStorage
public static void downloadImageToStorage(String url, String fileName, SuccessCallback<Image> onSuccess)Parameters
urlString- The URL to download the image from.
fileNameString- 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.
onSuccessSuccessCallback<Image>- Callback called on success.
sleep
public static void sleep(int t)Parameters
tint- the time
wait
public static void wait(Object o, int t)Parameters
oObject- the object to wait on
tint- the time
wait
public static void wait(Object o)Parameters
oObject- the object to wait on
toBooleanValue
public static boolean toBooleanValue(Object val)Parameters
valObject- a boolean value as a Boolean object, String or number
Returns
toIntValue
public static int toIntValue(Object number)Parameters
numberObject- this can be a String or any number type
Returns
toLongValue
public static long toLongValue(Object number)Parameters
numberObject- this can be a String or any number type
Returns
toFloatValue
public static float toFloatValue(Object number)Parameters
numberObject- this can be a String or any number type
Returns
toDoubleValue
public static double toDoubleValue(Object number)Parameters
numberObject- this can be a String or any number type
Returns
setDateFormatter
public static void setDateFormatter(SimpleDateFormat formatter)Parameters
formatterSimpleDateFormat- the formatter to use
toDateValue
public static Date toDateValue(Object o)Parameters
oObject- an object that can be a string, number or date
Returns
xorDecode
public static String xorDecode(String s)Parameters
sString- the string to decode
Returns
xorEncode
public static String xorEncode(String s)Parameters
sString- a regular string
Returns
guessMimeType
public static String guessMimeType(String sourceFile)
throws IOExceptionhttp server or by the file extension.Returns
Throws
guessMimeType
public static String guessMimeType(InputStream in)
throws IOExceptionhttp server or by the file extension.Returns
Throws
guessMimeType
public static String guessMimeType(byte[] data)http server or by the file extension.Returns
getFileSizeWithoutDownload
public static long getFileSizeWithoutDownload(String url)Returns
getFileSizeWithoutDownload
public static long getFileSizeWithoutDownload(String url, boolean checkPartialDownloadSupport)Parameters
urlString- Not documented.
checkPartialDownloadSupportboolean- if true returns -2 if the server doesn’t accept partial downloads.
Returns
downloadUrlSafely
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; 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
urlString- Not documented.
fileNameString- must be a valid Storage file name or FileSystemStorage file path
percentageCallbackOnComplete<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
filesavedCallbackOnComplete<String>- invoked (in EDT) only when the download is finished; if null, no action is taken
Throws
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
getUUID
public static String getUUID(long time, long clockSeqAndNode)long values.Parameters
timelong- the upper 64 bits
clockSeqAndNodelong- the lower 64 bits