Search in sources :

Example 6 with SuccessCallback

use of com.codename1.util.SuccessCallback in project CodenameOne by codenameone.

the class CodenameOneImplementation method downloadImageToStorage.

/**
 * Downloads an image to storage. This will *not* first check to see if the image is located in storage
 * already.  It will download and overwrite any existing image at the provided location.
 *
 * <p>Some platforms may override this method to use platform-level caching.  E.g. Javascript will use
 * the browser cache for downloading the image.</p>
 *
 * @param url The URL of the image to download.
 * @param fileName The storage key to be used to store the image.
 * @param onSuccess Callback on success.  Will be executed on EDT.
 * @param onFail Callback on failure.  Will be executed on EDT.
 */
public void downloadImageToStorage(String url, String fileName, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail) {
    ConnectionRequest cr = new ConnectionRequest();
    cr.setPost(false);
    cr.setFailSilently(true);
    cr.setReadResponseForErrors(false);
    cr.setDuplicateSupported(true);
    cr.setUrl(url);
    cr.downloadImageToStorage(fileName, onSuccess, onFail);
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest)

Example 7 with SuccessCallback

use of com.codename1.util.SuccessCallback in project CodenameOne by codenameone.

the class ConnectionRequest method downloadImage.

private void downloadImage(final SuccessCallback<Image> onSuccess, final FailureCallback<Image> onFail, boolean useCache) {
    setReadResponseForErrors(false);
    if (useCache) {
        Display.getInstance().scheduleBackgroundTask(new Runnable() {

            public void run() {
                if (getDestinationFile() != null) {
                    String file = getDestinationFile();
                    FileSystemStorage fs = FileSystemStorage.getInstance();
                    if (fs.exists(file)) {
                        try {
                            EncodedImage img = EncodedImage.create(fs.openInputStream(file), (int) fs.getLength(file));
                            if (img == null) {
                                throw new IOException("Failed to load image at " + file);
                            }
                            CallbackDispatcher.dispatchSuccess(onSuccess, img);
                        } catch (Exception ex) {
                            CallbackDispatcher.dispatchError(onFail, ex);
                        }
                    } else {
                        downloadImage(onSuccess, onFail, false);
                    }
                } else if (getDestinationStorage() != null) {
                    String file = getDestinationStorage();
                    Storage fs = Storage.getInstance();
                    if (fs.exists(file)) {
                        try {
                            EncodedImage img = EncodedImage.create(fs.createInputStream(file), fs.entrySize(file));
                            if (img == null) {
                                throw new IOException("Failed to load image at " + file);
                            }
                            CallbackDispatcher.dispatchSuccess(onSuccess, img);
                        } catch (Exception ex) {
                            CallbackDispatcher.dispatchError(onFail, ex);
                        }
                    } else {
                        downloadImage(onSuccess, onFail, false);
                    }
                }
            }
        });
    } else {
        final ActionListener onDownload = new ActionListener<NetworkEvent>() {

            public void actionPerformed(NetworkEvent nevt) {
                int rc = nevt.getResponseCode();
                if (rc == 200 || rc == 201) {
                    downloadImage(onSuccess, onFail, true);
                } else {
                    if (nevt.getError() == null) {
                        nevt.setError(new IOException("Failed to get image:  Code was " + nevt.getResponseCode()));
                    }
                    CallbackDispatcher.dispatchError(onFail, nevt.getError());
                }
                removeResponseListener(this);
            }
        };
        addResponseListener(onDownload);
        NetworkManager.getInstance().addToQueue(this);
    }
}
Also used : ActionListener(com.codename1.ui.events.ActionListener) IOException(java.io.IOException) EncodedImage(com.codename1.ui.EncodedImage) IOException(java.io.IOException) ParseException(com.codename1.l10n.ParseException)

Example 8 with SuccessCallback

use of com.codename1.util.SuccessCallback in project CodenameOne by codenameone.

the class Purchase method loadReceipts.

/**
 * Fetches receipts from the IAP service so that we know we are dealing
 * with current data.  This method should be called before checking a
 * subscription expiry date so that any changes the user has made in the
 * store is reflected here (e.g. cancelling or renewing subscription).
 * @param ifOlderThanMs Update is only performed if more than {@code ifOlderThanMs} milliseconds has elapsed
 * since the last successful fetch.
 * @param callback Callback called when request is complete.  Passed {@code true} if
 * the data was successfully fetched.  {@code false} otherwise.
 */
private final void loadReceipts(long ifOlderThanMs, final SuccessCallback<Boolean> callback) {
    if (loadInProgress) {
        Log.p("Did not load receipts because another load is in progress");
        callback.onSucess(false);
        return;
    }
    loadInProgress = true;
    Date lastRefreshTime = getReceiptsRefreshTime();
    Date now = new Date();
    if (lastRefreshTime.getTime() + ifOlderThanMs > now.getTime()) {
        Log.p("Receipts were last refreshed at " + lastRefreshTime + " so we won't refetch.");
        loadInProgress = false;
        callback.onSucess(true);
        return;
    }
    List<Receipt> oldData = new ArrayList<Receipt>();
    oldData.addAll(getReceipts());
    SuccessCallback<Receipt[]> onSuccess = new SuccessCallback<Receipt[]>() {

        public void onSucess(Receipt[] value) {
            if (value != null) {
                setReceipts(Arrays.asList(value));
                setReceiptsRefreshTime(new Date());
                loadInProgress = false;
                callback.onSucess(Boolean.TRUE);
            } else {
                loadInProgress = false;
                callback.onSucess(Boolean.FALSE);
            }
        }
    };
    if (receiptStore != null) {
        receiptStore.fetchReceipts(onSuccess);
    } else {
        Log.p("No receipt store is currently registered so no receipts were fetched");
        loadInProgress = false;
        callback.onSucess(Boolean.FALSE);
    }
}
Also used : SuccessCallback(com.codename1.util.SuccessCallback) ArrayList(java.util.ArrayList) Date(java.util.Date)

Example 9 with SuccessCallback

use of com.codename1.util.SuccessCallback in project CodenameOne by codenameone.

the class URLImage method fetch.

/**
 * Images are normally fetched from storage or network only as needed,
 * however if the download must start before the image is drawn this method
 * can be invoked. Notice that "immediately" doesn't mean synchronously, it just
 * means that the image will be added to the queue right away but probably won't be
 * available by the time the method completes.
 */
public void fetch() {
    if (fetching || imageData != null) {
        return;
    }
    fetching = true;
    try {
        locked = super.isLocked();
        if (storageFile != null) {
            if (Storage.getInstance().exists(storageFile)) {
                super.unlock();
                imageData = new byte[Storage.getInstance().entrySize(storageFile)];
                InputStream is = Storage.getInstance().createInputStream(storageFile);
                Util.readFully(is, imageData);
                resetCache();
                fetching = false;
                repaintImage = true;
                return;
            }
            if (adapter != null) {
                Util.downloadImageToStorage(url, storageFile + IMAGE_SUFFIX, new SuccessCallback<Image>() {

                    public void onSucess(Image value) {
                        DownloadCompleted onComplete = new DownloadCompleted();
                        onComplete.setSourceImage(value);
                        onComplete.actionPerformed(new ActionEvent(value));
                    }
                });
            } else {
                Util.downloadImageToStorage(url, storageFile, new SuccessCallback<Image>() {

                    public void onSucess(Image value) {
                        DownloadCompleted onComplete = new DownloadCompleted();
                        onComplete.setSourceImage(value);
                        onComplete.actionPerformed(new ActionEvent(value));
                    }
                });
            }
        } else {
            if (FileSystemStorage.getInstance().exists(fileSystemFile)) {
                super.unlock();
                imageData = new byte[(int) FileSystemStorage.getInstance().getLength(fileSystemFile)];
                InputStream is = FileSystemStorage.getInstance().openInputStream(fileSystemFile);
                Util.readFully(is, imageData);
                resetCache();
                fetching = false;
                repaintImage = true;
                return;
            }
            if (adapter != null) {
                Util.downloadImageToFileSystem(url, fileSystemFile + IMAGE_SUFFIX, new SuccessCallback<Image>() {

                    public void onSucess(Image value) {
                        DownloadCompleted onComplete = new DownloadCompleted();
                        onComplete.setSourceImage(value);
                        onComplete.actionPerformed(new ActionEvent(value));
                    }
                });
            } else {
                Util.downloadImageToFileSystem(url, fileSystemFile, new SuccessCallback<Image>() {

                    public void onSucess(Image value) {
                        DownloadCompleted onComplete = new DownloadCompleted();
                        onComplete.setSourceImage(value);
                        onComplete.actionPerformed(new ActionEvent(value));
                    }
                });
            }
        }
    } catch (IOException ioErr) {
        throw new RuntimeException(ioErr.toString());
    }
}
Also used : InputStream(java.io.InputStream) ActionEvent(com.codename1.ui.events.ActionEvent) IOException(java.io.IOException)

Example 10 with SuccessCallback

use of com.codename1.util.SuccessCallback in project CodenameOne by codenameone.

the class ComponentSelector method fadeIn.

/**
 * Fade in this set of components.  Prior to calling this, the component visibility should
 * be set to "false".
 * @param duration The duration of the fade in.
 * @param callback Callback to run when animation completes.
 * @return
 */
public ComponentSelector fadeIn(final int duration, final SuccessCallback<ComponentSelector> callback) {
    final String placeholderProperty = "com.codename1.ui.ComponentSelector#fadeOutPlaceholder";
    AnimationManager mgr = null;
    ArrayList<ComponentAnimation> animations1 = new ArrayList<ComponentAnimation>();
    final ArrayList<ComponentAnimation> animations2 = new ArrayList<ComponentAnimation>();
    final ArrayList<Component> animatingComponents = new ArrayList<Component>();
    for (Component c : this) {
        Container parent = c.getParent();
        if (parent != null) {
            AnimationManager cmgr = c.getAnimationManager();
            if (cmgr != null) {
                mgr = cmgr;
                Container placeholder = new Container();
                // placeholder.getStyle().setBgColor(0xff0000);
                // placeholder.getStyle().setBgTransparency(255);
                // placeholder.setShowEvenIfBlank(true);
                c.putClientProperty(placeholderProperty, placeholder);
                Component.setSameHeight(placeholder, c);
                Component.setSameWidth(placeholder, c);
                $(placeholder).setMargin(c.getStyle().getMarginTop(), c.getStyle().getMarginRight(false), c.getStyle().getMarginBottom(), c.getStyle().getMarginLeft(false)).setPadding(c.getStyle().getPaddingTop(), c.getStyle().getPaddingRight(false), c.getStyle().getPaddingBottom(), c.getStyle().getPaddingLeft(false));
                // System.out.println("Placeholder height "+c.getHeight());
                // parent.replace(c, placeholder, false);
                // c.setHidden(false);
                ComponentAnimation a = parent.createReplaceTransition(c, placeholder, CommonTransitions.createEmpty());
                animations1.add(a);
                animatingComponents.add(c);
            }
        // centerBackground.add(BorderLayout.CENTER, boxy);
        }
    }
    if (mgr != null) {
        mgr.addAnimation(ComponentAnimation.compoundAnimation(animations1.toArray(new ComponentAnimation[animations1.size()])), new Runnable() {

            public void run() {
                AnimationManager mgr = null;
                for (final Component c : animatingComponents) {
                    Container placeholder = (Container) c.getClientProperty(placeholderProperty);
                    if (placeholder != null) {
                        // System.out.println("Placeholder height after replace "+(c.getHeight() + c.getStyle().getMarginBottom() + c.getStyle().getMarginTop()));
                        // System.out.println("Placeholder not null");
                        c.putClientProperty(placeholderProperty, null);
                        AnimationManager cmgr = placeholder.getAnimationManager();
                        if (cmgr != null) {
                            // System.out.println("Animation manager not null");
                            mgr = cmgr;
                            c.setVisible(true);
                            Container parent = placeholder.getParent();
                            if (parent != null) {
                                // System.out.println("Parent not null");
                                ComponentAnimation a = parent.createReplaceTransition(placeholder, c, CommonTransitions.createFade(duration));
                                animations2.add(a);
                            }
                        }
                    }
                }
                if (mgr != null) {
                    final AnimationManager fmgr = mgr;
                    $(new Runnable() {

                        public void run() {
                            fmgr.addAnimation(ComponentAnimation.compoundAnimation(animations2.toArray(new ComponentAnimation[animations2.size()])), new Runnable() {

                                public void run() {
                                    if (callback != null) {
                                        callback.onSucess(ComponentSelector.this);
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });
    }
    return this;
}
Also used : ComponentAnimation(com.codename1.ui.animations.ComponentAnimation) ArrayList(java.util.ArrayList)

Aggregations

SuccessCallback (com.codename1.util.SuccessCallback)4 ArrayList (java.util.ArrayList)4 ConnectionRequest (com.codename1.io.ConnectionRequest)3 ComponentAnimation (com.codename1.ui.animations.ComponentAnimation)3 IOException (java.io.IOException)3 ActionEvent (com.codename1.ui.events.ActionEvent)2 ActionListener (com.codename1.ui.events.ActionListener)2 FileSystemStorage (com.codename1.io.FileSystemStorage)1 NetworkEvent (com.codename1.io.NetworkEvent)1 GZConnectionRequest (com.codename1.io.gzip.GZConnectionRequest)1 ParseException (com.codename1.l10n.ParseException)1 Location (com.codename1.location.Location)1 Result (com.codename1.processing.Result)1 BrowserComponent (com.codename1.ui.BrowserComponent)1 JSRef (com.codename1.ui.BrowserComponent.JSRef)1 EncodedImage (com.codename1.ui.EncodedImage)1 BrowserNavigationCallback (com.codename1.ui.events.BrowserNavigationCallback)1 Point (com.codename1.ui.geom.Point)1 Style (com.codename1.ui.plaf.Style)1 Callback (com.codename1.util.Callback)1