Search in sources :

Example 36 with Callback

use of com.codename1.util.Callback 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 37 with Callback

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

the class Util method downloadUrlTo.

private static boolean downloadUrlTo(String url, String fileName, boolean showProgress, boolean background, boolean storage, ActionListener callback) {
    ConnectionRequest cr = new ConnectionRequest();
    cr.setPost(false);
    cr.setFailSilently(true);
    cr.setReadResponseForErrors(false);
    cr.setDuplicateSupported(true);
    cr.setUrl(url);
    if (callback != null) {
        cr.addResponseListener(callback);
    }
    if (storage) {
        cr.setDestinationStorage(fileName);
    } else {
        cr.setDestinationFile(fileName);
    }
    if (background) {
        NetworkManager.getInstance().addToQueue(cr);
        return true;
    }
    if (showProgress) {
        InfiniteProgress ip = new InfiniteProgress();
        Dialog d = ip.showInifiniteBlocking();
        NetworkManager.getInstance().addToQueueAndWait(cr);
        d.dispose();
    } else {
        NetworkManager.getInstance().addToQueueAndWait(cr);
    }
    int rc = cr.getResponseCode();
    return rc == 200 || rc == 201;
}
Also used : InfiniteProgress(com.codename1.components.InfiniteProgress) Dialog(com.codename1.ui.Dialog)

Example 38 with Callback

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

the class DefaultDocumentRequestHandler method resourceRequested.

private InputStream resourceRequested(final DocumentInfo docInfo, final IOCallback callback) {
    String url = docInfo.getUrl();
    visitingURL(url);
    // trim anchors
    int hash = url.indexOf('#');
    if (hash != -1) {
        url = url.substring(0, hash);
    }
    if (url.startsWith("jar://")) {
        callback.streamReady(Display.getInstance().getResourceAsStream(getClass(), docInfo.getUrl().substring(6)), docInfo);
        return null;
    } else {
        try {
            if (url.startsWith("local://")) {
                Image img = resFile.getImage(url.substring(8));
                if (img instanceof EncodedImage) {
                    callback.streamReady(new ByteArrayInputStream(((EncodedImage) img).getImageData()), docInfo);
                }
            }
            if (url.startsWith("res://")) {
                InputStream i = Display.getInstance().getResourceAsStream(getClass(), docInfo.getUrl().substring(6));
                Resources r = Resources.open(i);
                i.close();
                i = r.getData(docInfo.getParams());
                if (i != null) {
                    callback.streamReady(i, docInfo);
                } else {
                    Image img = r.getImage(docInfo.getParams());
                    if (img instanceof EncodedImage) {
                        callback.streamReady(new ByteArrayInputStream(((EncodedImage) img).getImageData()), docInfo);
                    }
                }
                return null;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return null;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Resources(com.codename1.ui.util.Resources) IOException(java.io.IOException) Image(com.codename1.ui.Image) EncodedImage(com.codename1.ui.EncodedImage) EncodedImage(com.codename1.ui.EncodedImage)

Example 39 with Callback

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

the class Form method sizeChangedInternal.

/**
 * This method is only invoked when the underlying canvas for the form gets
 * a size changed event.
 * This method will trigger a relayout of the Form.
 * This method will get the callback only if this Form is the Current Form
 * @param w the new width of the Form
 * @param h the new height of the Form
 */
void sizeChangedInternal(int w, int h) {
    int oldWidth = getWidth();
    int oldHeight = getHeight();
    sizeChanged(w, h);
    Style formStyle = getStyle();
    w = w - (formStyle.getHorizontalMargins());
    h = h - (formStyle.getVerticalMargins());
    setSize(new Dimension(w, h));
    setShouldCalcPreferredSize(true);
    doLayout();
    focused = getFocused();
    if (focused != null) {
        Component.setDisableSmoothScrolling(true);
        scrollComponentToVisible(focused);
        Component.setDisableSmoothScrolling(false);
    }
    if (oldWidth != w && oldHeight != h) {
        if (orientationListener != null) {
            orientationListener.fireActionEvent(new ActionEvent(this, ActionEvent.Type.OrientationChange));
        }
    }
    if (sizeChangedListener != null) {
        sizeChangedListener.fireActionEvent(new ActionEvent(this, ActionEvent.Type.SizeChange, w, h));
    }
    repaint();
}
Also used : ActionEvent(com.codename1.ui.events.ActionEvent) Style(com.codename1.ui.plaf.Style) Dimension(com.codename1.ui.geom.Dimension)

Example 40 with Callback

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

the class AsyncDocumentRequestHandlerImpl method resourceRequested.

private InputStream resourceRequested(final DocumentInfo docInfo, final IOCallback callback) {
    try {
        if (docInfo.getUrl().startsWith("file://")) {
            String url = docInfo.getUrl();
            // trim anchors
            int hash = url.indexOf('#');
            if (hash != -1) {
                url = url.substring(0, hash);
            }
            callback.streamReady(FileSystemStorage.getInstance().openInputStream(url), docInfo);
            return null;
        }
    } catch (IOException ex) {
        Log.e(ex);
    }
    final Object[] response = new Object[1];
    ConnectionRequest reqest = createConnectionRequest(docInfo, callback, response);
    reqest.setPost(docInfo.isPostRequest());
    if (docInfo.isPostRequest()) {
        reqest.setUrl(docInfo.getUrl());
        reqest.setWriteRequest(true);
    } else {
        reqest.setUrl(docInfo.getFullUrl());
    }
    NetworkManager.getInstance().addToQueue(reqest);
    if (callback == null) {
        synchronized (LOCK) {
            while (response[0] == null) {
                try {
                    LOCK.wait(50);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
            if (response[0] instanceof InputStream) {
                return (InputStream) response[0];
            }
            // we need a better way to handle this...
            if (response[0] instanceof Throwable) {
                ((Throwable) response[0]).printStackTrace();
            }
        }
    }
    return null;
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) InputStream(java.io.InputStream) IOException(java.io.IOException)

Aggregations

ActionListener (com.codename1.ui.events.ActionListener)14 ActionEvent (com.codename1.ui.events.ActionEvent)12 IOException (java.io.IOException)11 ConnectionRequest (com.codename1.io.ConnectionRequest)10 EventDispatcher (com.codename1.ui.util.EventDispatcher)8 NetworkEvent (com.codename1.io.NetworkEvent)6 InputStream (java.io.InputStream)5 Intent (android.content.Intent)4 ComponentAnimation (com.codename1.ui.animations.ComponentAnimation)4 ArrayList (java.util.ArrayList)4 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)3 Uri (android.net.Uri)3 IntentResultListener (com.codename1.impl.android.IntentResultListener)3 AccessToken (com.codename1.io.AccessToken)3 GZConnectionRequest (com.codename1.io.gzip.GZConnectionRequest)3 EncodedImage (com.codename1.ui.EncodedImage)3 Image (com.codename1.ui.Image)3 File (java.io.File)3 OutputStream (java.io.OutputStream)3 RandomAccessFile (java.io.RandomAccessFile)3