Search in sources :

Example 16 with NetworkEvent

use of com.codename1.io.NetworkEvent 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 17 with NetworkEvent

use of com.codename1.io.NetworkEvent in project CodenameOne by codenameone.

the class ConnectionRequest method addResponseCodeListener.

/**
 * Adds a listener that would be notified on the CodenameOne thread of a response code that
 * is not a 200 (OK) or 301/2 (redirect) response code.
 *
 * @param a listener
 */
public void addResponseCodeListener(ActionListener<NetworkEvent> a) {
    if (responseCodeListeners == null) {
        responseCodeListeners = new EventDispatcher();
        responseCodeListeners.setBlocking(false);
    }
    responseCodeListeners.addListener(a);
}
Also used : EventDispatcher(com.codename1.ui.util.EventDispatcher)

Example 18 with NetworkEvent

use of com.codename1.io.NetworkEvent in project CodenameOne by codenameone.

the class SliderBridge method bindProgress.

/**
 * Allows binding progress to an arbitrary slider
 *
 * @param sources the source connection request (null for all network activity)
 * @param s the slider
 */
public static void bindProgress(final ConnectionRequest[] sources, final Slider s) {
    Vector v = null;
    int portions = 100;
    if (sources != null) {
        v = new Vector();
        int slen = sources.length;
        for (int iter = 0; iter < slen; iter++) {
            v.addElement(sources[iter]);
        }
        portions = portions / slen;
    }
    final Vector sourceVec = v;
    final int portionPerSource = portions;
    NetworkManager.getInstance().addProgressListener(new ActionListener() {

        private float currentLength;

        private int soFar;

        /**
         * {@inheritDoc}
         */
        public void actionPerformed(ActionEvent evt) {
            if (sources != null) {
                if (!sourceVec.contains(evt.getSource())) {
                    return;
                }
            }
            NetworkEvent e = (NetworkEvent) evt;
            switch(e.getProgressType()) {
                case NetworkEvent.PROGRESS_TYPE_COMPLETED:
                    s.setInfinite(false);
                    // s.setProgress(s.getMaxValue());
                    soFar += portionPerSource;
                    s.setProgress(soFar);
                    if (sources != null) {
                        NetworkManager.getInstance().removeProgressListener(this);
                    }
                    break;
                case NetworkEvent.PROGRESS_TYPE_INITIALIZING:
                    s.setInfinite(true);
                    break;
                case NetworkEvent.PROGRESS_TYPE_INPUT:
                case NetworkEvent.PROGRESS_TYPE_OUTPUT:
                    if (e.getLength() > 0) {
                        currentLength = e.getLength();
                        // s.setMaxValue(1000);
                        s.setInfinite(false);
                        float sentReceived = e.getSentReceived();
                        sentReceived = sentReceived / currentLength * portionPerSource;
                        s.setProgress((int) sentReceived + soFar);
                    // s.setProgress(e.getSentReceived());
                    // s.setMaxValue(e.getLength());
                    } else {
                        s.setInfinite(true);
                    }
                    break;
            }
        }
    });
}
Also used : ActionListener(com.codename1.ui.events.ActionListener) ActionEvent(com.codename1.ui.events.ActionEvent) NetworkEvent(com.codename1.io.NetworkEvent) Vector(java.util.Vector)

Example 19 with NetworkEvent

use of com.codename1.io.NetworkEvent in project CodenameOne by codenameone.

the class RequestBuilder method getAsStringAsync.

/**
 * Executes the request asynchronously and writes the response to the provided
 * Callback
 * @param callback writes the response to this callback
 */
public void getAsStringAsync(final Callback<Response<String>> callback) {
    ConnectionRequest request = createRequest(false);
    request.addResponseListener(new ActionListener<NetworkEvent>() {

        @Override
        public void actionPerformed(NetworkEvent evt) {
            Response res = null;
            try {
                res = new Response(evt.getResponseCode(), new String(evt.getConnectionRequest().getResponseData(), "UTF-8"), evt.getMessage());
                callback.onSucess(res);
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
        }
    });
    CN.addToQueue(request);
}
Also used : GZConnectionRequest(com.codename1.io.gzip.GZConnectionRequest) ConnectionRequest(com.codename1.io.ConnectionRequest) NetworkEvent(com.codename1.io.NetworkEvent) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 20 with NetworkEvent

use of com.codename1.io.NetworkEvent in project CodenameOne by codenameone.

the class CachedDataService method readResponse.

/**
 * {@inheritDoc}
 */
protected void readResponse(InputStream input) throws IOException {
    data.setData(Util.readInputStream(input));
    fireResponseListener(new NetworkEvent(this, data));
    data.setFetching(false);
}
Also used : NetworkEvent(com.codename1.io.NetworkEvent)

Aggregations

NetworkEvent (com.codename1.io.NetworkEvent)21 ActionEvent (com.codename1.ui.events.ActionEvent)10 ActionListener (com.codename1.ui.events.ActionListener)10 Vector (java.util.Vector)8 IOException (java.io.IOException)7 Hashtable (java.util.Hashtable)7 EventDispatcher (com.codename1.ui.util.EventDispatcher)6 EncodedImage (com.codename1.ui.EncodedImage)4 FileEncodedImage (com.codename1.components.FileEncodedImage)3 StorageImage (com.codename1.components.StorageImage)3 ConnectionRequest (com.codename1.io.ConnectionRequest)3 GZConnectionRequest (com.codename1.io.gzip.GZConnectionRequest)3 Image (com.codename1.ui.Image)3 InputStreamReader (java.io.InputStreamReader)3 InfiniteProgress (com.codename1.components.InfiniteProgress)1 BufferedInputStream (com.codename1.io.BufferedInputStream)1 CharArrayReader (com.codename1.io.CharArrayReader)1 JSONParser (com.codename1.io.JSONParser)1 MultipartRequest (com.codename1.io.MultipartRequest)1 ParseException (com.codename1.l10n.ParseException)1