Search in sources :

Example 46 with Name

use of com.codename1.rad.models.Property.Name in project CodenameOne by codenameone.

the class BlackBerryImplementation method sendMessage.

public void sendMessage(String[] recipients, String subject, Message msg) {
    Folder[] folders = Session.getDefaultInstance().getStore().list(Folder.SENT);
    net.rim.blackberry.api.mail.Message message = new net.rim.blackberry.api.mail.Message(folders[0]);
    try {
        Address[] toAdds = new Address[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            Address address = new Address(recipients[i], "");
            toAdds[i] = address;
        }
        message.addRecipients(net.rim.blackberry.api.mail.Message.RecipientType.TO, toAdds);
        message.setSubject(subject);
    } catch (Exception e) {
        EventLog.getInstance().logErrorEvent("err " + e.getMessage());
    }
    try {
        if (msg.getAttachment() != null && msg.getAttachment().length() > 0) {
            Multipart content = new Multipart();
            TextBodyPart tbp = new TextBodyPart(content, msg.getContent());
            content.addBodyPart(tbp);
            InputStream stream = com.codename1.io.FileSystemStorage.getInstance().openInputStream(msg.getAttachment());
            byte[] buf;
            buf = IOUtilities.streamToBytes(stream);
            stream.close();
            String name = msg.getAttachment();
            name = name.substring(name.lastIndexOf(getFileSystemSeparator()) + 1, name.length());
            SupportedAttachmentPart sap = new SupportedAttachmentPart(content, msg.getAttachmentMimeType(), name, buf);
            content.addBodyPart(sap);
            message.setContent(content);
        } else {
            message.setContent(msg.getContent());
        }
        app.setWaitingForReply(true);
        Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(message));
    } catch (Exception ex) {
        EventLog.getInstance().logErrorEvent("err " + ex.getMessage());
    }
}
Also used : Multipart(net.rim.blackberry.api.mail.Multipart) TextMessage(javax.wireless.messaging.TextMessage) Message(com.codename1.messaging.Message) Address(net.rim.blackberry.api.mail.Address) BufferedInputStream(com.codename1.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) DataInputStream(java.io.DataInputStream) InputStream(java.io.InputStream) TextBodyPart(net.rim.blackberry.api.mail.TextBodyPart) Folder(net.rim.blackberry.api.mail.Folder) IOException(java.io.IOException) RecordStoreException(javax.microedition.rms.RecordStoreException) MediaException(javax.microedition.media.MediaException) ConnectionNotFoundException(javax.microedition.io.ConnectionNotFoundException) MessageArguments(net.rim.blackberry.api.invoke.MessageArguments) SupportedAttachmentPart(net.rim.blackberry.api.mail.SupportedAttachmentPart)

Example 47 with Name

use of com.codename1.rad.models.Property.Name in project CodenameOne by codenameone.

the class Util method downloadUrlSafely.

/**
 * <p>
 * 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
 * <pre>.retry()</pre>, as in the code example below.</p>
 * <p>
 * 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.</p>
 * <p>
 * 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).</p>
 * <p>
 * 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.</p>
 * <p>
 * Usage example:</p>
 * <script src="https://gist.github.com/jsfan3/554590a12c3102a3d77e17533e7eca98.js"></script>
 *
 * @param url
 * @param fileName must be a valid Storage file name or FileSystemStorage
 * file path
 * @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
 * @param filesavedCallback invoked (in EDT) only when the download is
 * finished; if null, no action is taken
 * @throws IOException
 */
public static void downloadUrlSafely(String url, final String fileName, final OnComplete<Integer> percentageCallback, final OnComplete<String> filesavedCallback) throws IOException {
    // Code discussion here: https://stackoverflow.com/a/62137379/1277576
    String partialDownloadsDir = FileSystemStorage.getInstance().getAppHomePath() + FileSystemStorage.getInstance().getFileSystemSeparator() + "partialDownloads";
    if (!FileSystemStorage.getInstance().isDirectory(partialDownloadsDir)) {
        FileSystemStorage.getInstance().mkdir(partialDownloadsDir);
    }
    // do its best to be unique if there are parallel downloads
    final String uniqueId = url.hashCode() + "" + downloadUrlSafelyRandom.nextInt();
    final String partialDownloadPath = partialDownloadsDir + FileSystemStorage.getInstance().getFileSystemSeparator() + uniqueId;
    // as discussed here: https://stackoverflow.com/a/57984257
    final boolean isStorage = fileName.indexOf("/") < 0;
    // total expected download size, with a check partial download support
    final long fileSize = getFileSizeWithoutDownload(url, true);
    // 512 kbyte, size of each small download
    final int splittingSize = 512 * 1024;
    final Wrapper<Long> downloadedTotalBytes = new Wrapper<Long>(0l);
    final OutputStream out;
    if (isStorage) {
        // leave it open to append partial downloads
        out = Storage.getInstance().createOutputStream(fileName);
    } else {
        out = FileSystemStorage.getInstance().openOutputStream(fileName);
    }
    // Codename One thread that supports crash protection and similar Codename One features.
    final EasyThread mergeFilesThread = EasyThread.start("mergeFilesThread");
    final ConnectionRequest cr = new GZConnectionRequest();
    cr.setUrl(url);
    cr.setPost(false);
    if (fileSize > splittingSize) {
        // Which byte should the download start from?
        cr.addRequestHeader("Range", "bytes=0-" + splittingSize);
        cr.setDestinationFile(partialDownloadPath);
    } else {
        Util.cleanup(out);
        if (isStorage) {
            cr.setDestinationStorage(fileName);
        } else {
            cr.setDestinationFile(fileName);
        }
    }
    cr.addResponseListener(new ActionListener<NetworkEvent>() {

        @Override
        public void actionPerformed(NetworkEvent evt) {
            mergeFilesThread.run(new Runnable() {

                @Override
                public void run() {
                    try {
                        // We append the just saved partial download to the fileName, if it exists
                        if (FileSystemStorage.getInstance().exists(partialDownloadPath)) {
                            InputStream in = FileSystemStorage.getInstance().openInputStream(partialDownloadPath);
                            Util.copyNoClose(in, out, 8192);
                            Util.cleanup(in);
                            // before deleting the file, we check and update how much data we have actually downloaded
                            downloadedTotalBytes.set(downloadedTotalBytes.get() + FileSystemStorage.getInstance().getLength(partialDownloadPath));
                            FileSystemStorage.getInstance().delete(partialDownloadPath);
                        }
                        // Is the download finished?
                        if (downloadedTotalBytes.get() > fileSize) {
                            throw new IllegalStateException("More content has been downloaded than the file length, check the code.");
                        }
                        if (fileSize <= 0 || downloadedTotalBytes.get() == fileSize) {
                            // yes, download finished
                            Util.cleanup(out);
                            if (filesavedCallback != null) {
                                CN.callSerially(new Runnable() {

                                    @Override
                                    public void run() {
                                        filesavedCallback.completed(fileName);
                                    }
                                });
                            }
                        } else {
                            // no, it's not finished, we repeat the request after updating the "Range" header
                            cr.addRequestHeader("Range", "bytes=" + downloadedTotalBytes.get() + "-" + (Math.min(downloadedTotalBytes.get() + splittingSize, fileSize)));
                            NetworkManager.getInstance().addToQueue(cr);
                        }
                    } catch (IOException ex) {
                        Log.p("Error in appending splitted file to output file", Log.ERROR);
                        Log.e(ex);
                        Log.sendLogAsync();
                    }
                }
            });
        }
    });
    NetworkManager.getInstance().addToQueue(cr);
    NetworkManager.getInstance().addProgressListener(new ActionListener<NetworkEvent>() {

        @Override
        public void actionPerformed(NetworkEvent evt) {
            if (cr == evt.getConnectionRequest() && fileSize > 0) {
                // the following casting to long is necessary when the file is bigger than 21MB, otherwise the result of the calculation is wrong
                if (percentageCallback != null) {
                    CN.callSerially(new Runnable() {

                        @Override
                        public void run() {
                            percentageCallback.completed((int) ((long) downloadedTotalBytes.get() * 100 / fileSize));
                        }
                    });
                }
            }
        }
    });
}
Also used : Wrapper(com.codename1.util.Wrapper) DataInputStream(java.io.DataInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataOutputStream(java.io.DataOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) GZConnectionRequest(com.codename1.io.gzip.GZConnectionRequest) GZConnectionRequest(com.codename1.io.gzip.GZConnectionRequest) EasyThread(com.codename1.util.EasyThread)

Example 48 with Name

use of com.codename1.rad.models.Property.Name in project CodenameOne by codenameone.

the class CodenameOneImplementation method installTar.

/**
 * Installs a tar file from the build server into the file system storage so it can be used with respect for hierarchy
 */
public void installTar() throws IOException {
    String p = Preferences.get("cn1$InstallKey", null);
    String buildKey = Display.getInstance().getProperty("build_key", null);
    if (p == null || !p.equals(buildKey)) {
        FileSystemStorage fs = FileSystemStorage.getInstance();
        String tardir = fs.getAppHomePath() + "cn1html/";
        fs.mkdir(tardir);
        TarInputStream is = new TarInputStream(Display.getInstance().getResourceAsStream(getClass(), "/html.tar"));
        TarEntry t = is.getNextEntry();
        byte[] data = new byte[8192];
        while (t != null) {
            String name = t.getName();
            if (t.isDirectory()) {
                fs.mkdir(tardir + name);
            } else {
                String path = tardir + name;
                String dir = path.substring(0, path.lastIndexOf('/'));
                if (!fs.exists(dir)) {
                    mkdirs(fs, dir);
                }
                OutputStream os = fs.openOutputStream(tardir + name);
                int count;
                while ((count = is.read(data)) != -1) {
                    os.write(data, 0, count);
                }
                os.close();
            }
            t = is.getNextEntry();
        }
        Util.cleanup(is);
        Preferences.set("cn1$InstallKey", buildKey);
    }
}
Also used : FileSystemStorage(com.codename1.io.FileSystemStorage) TarInputStream(com.codename1.io.tar.TarInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) TarEntry(com.codename1.io.tar.TarEntry)

Example 49 with Name

use of com.codename1.rad.models.Property.Name in project CodenameOne by codenameone.

the class CodenameOneImplementation method downloadImageToCache.

/**
 * Downloads an image from a URL to the cache. Platforms
 * that support a native image cache {@link #supportsNativeImageCache() } (e.g. Javascript) override this method to defer to the
 * platform's handling of cached images.  Platforms that have a caches directory ({@link FileSystemStorage#hasCachesDir() }
 * will use that directory to cache the image.  Other platforms will just download to storage.
 *
 * @param url The URL of the image to download.
 * @param onSuccess Callback on success.
 * @param onFail Callback on fail.
 *
 * @see URLImage#createToCache(com.codename1.ui.EncodedImage, java.lang.String, com.codename1.ui.URLImage.ImageAdapter)
 */
public void downloadImageToCache(String url, SuccessCallback<Image> onSuccess, final FailureCallback<Image> onFail) {
    FileSystemStorage fs = FileSystemStorage.getInstance();
    if (fs.hasCachesDir()) {
        String name = "cn1_image_cache[" + url + "]";
        name = StringUtil.replaceAll(name, "/", "_");
        name = StringUtil.replaceAll(name, "\\", "_");
        name = StringUtil.replaceAll(name, "%", "_");
        name = StringUtil.replaceAll(name, "?", "_");
        name = StringUtil.replaceAll(name, "*", "_");
        name = StringUtil.replaceAll(name, ":", "_");
        name = StringUtil.replaceAll(name, "=", "_");
        String filePath = fs.getCachesDir() + fs.getFileSystemSeparator() + name;
        // We use Util.downloadImageToFileSystem rather than CodenameOneImplementation.downloadImageToFileSystem
        // because we want it to try to load from file system first.
        Util.downloadImageToFileSystem(url, filePath, onSuccess, onFail);
    } else {
        // We use Util.downloadImageToStorage rather than CodenameOneImplementation.downloadImageToStorage
        // because we want it to try to load from storage first.
        Util.downloadImageToStorage(url, "cn1_image_cache[" + url + "]", onSuccess, onFail);
    }
}
Also used : FileSystemStorage(com.codename1.io.FileSystemStorage)

Example 50 with Name

use of com.codename1.rad.models.Property.Name in project CodenameOne by codenameone.

the class CodenameOneImplementation method getStorageEntrySize.

/**
 * Returns the size of the entry in bytes
 * @param name the entry name
 * @return the size
 */
public int getStorageEntrySize(String name) {
    long size = -1;
    try {
        InputStream i = createStorageInputStream(name);
        long val = i.skip(1000000);
        if (val > -1) {
            size = 0;
            while (val > -1) {
                size += val;
                val = i.skip(1000000);
            }
        }
        Util.cleanup(i);
    } catch (IOException err) {
        Log.e(err);
    }
    return (int) size;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) DataInputStream(java.io.DataInputStream) TarInputStream(com.codename1.io.tar.TarInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException)

Aggregations

IOException (java.io.IOException)36 Component (com.codename1.ui.Component)17 Hashtable (java.util.Hashtable)17 ArrayList (java.util.ArrayList)16 AnimationObject (com.codename1.ui.animations.AnimationObject)15 File (java.io.File)14 Form (com.codename1.ui.Form)13 ByteArrayInputStream (java.io.ByteArrayInputStream)13 FileInputStream (java.io.FileInputStream)13 InputStream (java.io.InputStream)12 Label (com.codename1.ui.Label)11 Button (com.codename1.ui.Button)10 Container (com.codename1.ui.Container)10 EncodedImage (com.codename1.ui.EncodedImage)10 TextArea (com.codename1.ui.TextArea)10 BorderLayout (com.codename1.ui.layouts.BorderLayout)10 Point (java.awt.Point)10 FileOutputStream (java.io.FileOutputStream)10 Paint (android.graphics.Paint)8 BufferedInputStream (com.codename1.io.BufferedInputStream)7