com.codename1.io.NetworkEvent Java Examples

The following examples show how to use com.codename1.io.NetworkEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets a user from a user id
 *
 * @param userId the user id or null to get detaild on the authenticated user
 * @param user an object to fill with the user details
 * @param callback the callback that should be updated when the data arrives
 */
public void getUser(String userId, final User user, final ActionListener callback) throws IOException {
    String id = userId;
    if (id == null) {
        id = "me";
    }
    getFaceBookObject(id, new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            Vector v = (Vector) ((NetworkEvent) evt).getMetaData();
            Hashtable t = (Hashtable) v.elementAt(0);
            if (user != null) {
                user.copy(t);
            }
            if (callback != null) {
                callback.actionPerformed(evt);
            }
        }
    });
}
 
Example #2
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gest a post from a post Id
 *
 * @param postId the postId
 * @param post an Object to fill with the data
 * @param callback the callback that should be updated when the data arrives
 */
public void getPost(String postId, final Post post, final ActionListener callback) throws IOException {
    getFaceBookObject(postId, new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            Vector v = (Vector) ((NetworkEvent) evt).getMetaData();
            Hashtable t = (Hashtable) v.elementAt(0);
            if (post != null) {
                post.copy(t);
            }
            if (callback != null) {
                callback.actionPerformed(evt);
            }
        }
    });
}
 
Example #3
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gest a photo from a photo Id
 *
 * @param photoId the photoId
 * @param photo an Object to fill with the data
 * @param callback the callback that should be updated when the data arrives
 */
public void getPhoto(String photoId, final Photo photo, final ActionListener callback) throws IOException {
    getFaceBookObject(photoId, new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            Vector v = (Vector) ((NetworkEvent) evt).getMetaData();
            Hashtable t = (Hashtable) v.elementAt(0);
            if (photo != null) {
                photo.copy(t);
            }
            if (callback != null) {
                callback.actionPerformed(evt);
            }
        }
    });
}
 
Example #4
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gest an album from an albumId
 *
 * @param albumId the albumId
 * @param album an Object to fill with the data
 * @param callback the callback that should be updated when the data arrives
 */
public void getAlbum(String albumId, final Album album, final ActionListener callback) throws IOException {
    getFaceBookObject(albumId, new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            Vector v = (Vector) ((NetworkEvent) evt).getMetaData();
            Hashtable t = (Hashtable) v.elementAt(0);
            if (album != null) {
                album.copy(t);
            }
            if (callback != null) {
                callback.actionPerformed(evt);
            }
        }
    });
}
 
Example #5
Source File: FacebookRESTService.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
protected void readResponse(InputStream input) throws IOException {
    //BufferedInputStream i = new BufferedInputStream(new InputStreamReader(input, ));
    BufferedInputStream i;
    if(input instanceof BufferedInputStream){
        i = (BufferedInputStream) input;
    }else{
        i = new BufferedInputStream(input);
    }
    i.setYield(-1);
    InputStreamReader reader = new InputStreamReader(i, "UTF-8");
    JSONParser.parse(reader, this);
    Util.cleanup(reader);
    if(stack.size() > 0){
        fireResponseListener(new NetworkEvent(this, stack.elementAt(0)));
    }
}
 
Example #6
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes the request asynchronously and writes the response to the provided
 * Callback
 * @param callback writes the response to this callback
 * @param onError the error callback
 * @return returns the Connection Request object so it can be killed if necessary
 * @deprecated use {@link #fetchAsJsonMap(com.codename1.util.OnComplete)} instead
 */ 
public ConnectionRequest getAsJsonMap(final SuccessCallback<Response<Map>> callback, final FailureCallback<? extends Object> onError) {
    final Connection request = createRequest(true);
    request.addResponseListener(new ActionListener<NetworkEvent>() {
        @Override
        public void actionPerformed(NetworkEvent evt) {
            if(request.errorCode) {
                return;
            }
            if(onError != null) {
                // this is an error response code and should be handled as an error
                if(evt.getResponseCode() > 310) {
                    return;
                }
            }
            Response res = null;
            Map response = (Map)evt.getMetaData();
            res = new Response(evt.getResponseCode(), response, evt.getMessage());
            callback.onSucess(res);
        }
    });
    bindOnError(request, onError);
    fetched = true;
    CN.addToQueue(request);       
    return request;
}
 
Example #7
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes the request asynchronously and writes the response to the provided
 * Callback. This fetches JSON data and parses it into a properties business object
 * @param callback writes the response to this callback
 * @param type the class of the business object returned
 * @return returns the Connection Request object so it can be killed if necessary
 */ 
public ConnectionRequest fetchAsProperties(final OnComplete<Response<PropertyBusinessObject>> callback, final Class type) {
    final Connection request = createRequest(true);
    request.addResponseListener(new ActionListener<NetworkEvent>() {
        @Override
        public void actionPerformed(NetworkEvent evt) {
            if(request.errorCode) {
                return;
            }
            Response res = null;
            Map response = (Map)evt.getMetaData();
            try {
                PropertyBusinessObject pb = (PropertyBusinessObject)type.newInstance();
                pb.getPropertyIndex().populateFromMap(response);
                res = new Response(evt.getResponseCode(), pb, evt.getMessage());
                callback.completed(res);
            } catch(Exception err) {
                Log.e(err);
                throw new RuntimeException(err.toString());
            }
        }
    });
    fetched = true;
    CN.addToQueue(request);       
    return request;
}
 
Example #8
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes the request asynchronously and writes the response to the provided
 * Callback
 * @param callback writes the response to this callback
 * @return returns the Connection Request object so it can be killed if necessary
 */ 
public ConnectionRequest fetchAsJsonMap(final OnComplete<Response<Map>> callback) {
    final Connection request = createRequest(true);
    request.addResponseListener(new ActionListener<NetworkEvent>() {
        @Override
        public void actionPerformed(NetworkEvent evt) {
            if(request.errorCode) {
                return;
            }
            Response res = null;
            Map response = (Map)evt.getMetaData();
            res = new Response(evt.getResponseCode(), response, evt.getMessage());
            callback.completed(res);
        }
    });
    fetched = true;
    CN.addToQueue(request);       
    return request;
}
 
Example #9
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private ConnectionRequest getAsBytesAsyncImpl(final Object callback) {
    final Connection request = createRequest(false);
    request.addResponseListener(new ActionListener<NetworkEvent>() {
        @Override
        public void actionPerformed(NetworkEvent evt) {
            if(request.errorCode) {
                return;
            }
            Response res = null;
            res = new Response(evt.getResponseCode(), evt.getConnectionRequest().getResponseData(), evt.getMessage());
            if(callback instanceof Callback) {
                ((Callback)callback).onSucess(res);
            } else {
                ((OnComplete)callback).completed(res);
            }
        }
    });
    fetched = true;
    CN.addToQueue(request);        
    return request;
}
 
Example #10
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private ConnectionRequest getAsStringAsyncImpl(final Object callback) {
    final Connection request = createRequest(false);
    request.addResponseListener(new ActionListener<NetworkEvent>() {
        @Override
        public void actionPerformed(NetworkEvent evt) {
            if(request.errorCode) {
                return;
            }
            Response res = null;
            try {
                res = new Response(evt.getResponseCode(), new String(evt.getConnectionRequest().getResponseData(), "UTF-8"), evt.getMessage());
                if(callback instanceof Callback) {
                    ((Callback)callback).onSucess(res);
                } else {
                    ((OnComplete<Response<String>>)callback).completed(res);
                }
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
        }
    });
    fetched = true;
    CN.addToQueue(request);        
    return request;
}
 
Example #11
Source File: Login.java    From codenameone-demos with GNU General Public License v2.0 6 votes vote down vote up
public static void login(final Form form) {
    if (firstLogin()) {
        Login logForm = new Login(form);
        logForm.show();
    } else {
        //token exists no need to authenticate
        TOKEN = (String) Storage.getInstance().readObject("token");
        FaceBookAccess.setToken(TOKEN);
        //in case token has expired re-authenticate
        FaceBookAccess.getInstance().addResponseCodeListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent evt) {
                NetworkEvent ne = (NetworkEvent) evt;
                int code = ne.getResponseCode();
                //token has expired
                if (code == 400) {
                    signIn(form);
                }                    
            }
        });
    }
}
 
Example #12
Source File: ImageDownloadService.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs an image request that will automatically populate the given Label
 * when the response arrives, it will cache the file locally.
 *
 * @param url the image URL
 * @param callback the callback that should be updated when the data arrives
 * @param destFile local file to store the data into the given path
 */
public static void createImageToFileSystem(String url, ActionListener callback, String destFile) {

    Image im = cacheImage(null, false, destFile, null, null, defaultMaintainAspectRatio);
    if (im != null) {
        callback.actionPerformed(new NetworkEvent(null, im));
        return;
    }
    //image not found on cache go and download from the url
    ImageDownloadService i = new ImageDownloadService(url, callback);
    i.cacheImages = true;
    i.destinationFile = destFile;
    i.setFailSilently(true);
    NetworkManager.getInstance().addToQueue(i);
}
 
Example #13
Source File: Progress.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void actionPerformed(ActionEvent evt) {
     NetworkEvent ev = (NetworkEvent)evt;
     if(ev.getConnectionRequest() == request) {
         if(disposeOnCompletion && ev.getProgressType() == NetworkEvent.PROGRESS_TYPE_COMPLETED) {
             dispose();
             return;
         }
         if(autoShow && !showing) {
             showing = true;
             showModeless();
         }
     }
}
 
Example #14
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Executes the request asynchronously and writes the response to the provided
 * Callback. This fetches JSON data and parses it into a properties business object
 * @param callback writes the response to this callback
 * @param type the class of the business object returned
 * @return returns the Connection Request object so it can be killed if necessary
 */ 
public ConnectionRequest fetchAsPropertyList(final OnComplete<Response<List<PropertyBusinessObject>>> callback, final Class type) {
    final Connection request = createRequest(true);
    request.addResponseListener(new ActionListener<NetworkEvent>() {
        @Override
        public void actionPerformed(NetworkEvent evt) {
            if(request.errorCode) {
                return;
            }
            Response res = null;
            Map response = (Map)evt.getMetaData();
            List<Map> lst = (List<Map>)response.get("root");
            if(lst == null) {
                return;
            }
            try {
                List<PropertyBusinessObject> result = new ArrayList<PropertyBusinessObject>();
                for(Map m : lst) {
                    PropertyBusinessObject pb = (PropertyBusinessObject)type.newInstance();
                    pb.getPropertyIndex().populateFromMap(m);
                    result.add(pb);
                }
                res = new Response(evt.getResponseCode(), result, evt.getMessage());
                callback.completed(res);
            } catch(Exception err) {
                Log.e(err);
                throw new RuntimeException(err.toString());
            }
        }
    });
    fetched = true;
    CN.addToQueue(request);       
    return request;
}
 
Example #15
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invoked for exceptions or failures such as disconnect
 * @param error callback for a networking error
 * @param replace If true, replaces the existing errorCallback(s) with the handler
 * provided.
 * @return RequestBuilder instance
 * @since 7.0
 */
public RequestBuilder onError(ActionListener<NetworkEvent> error, boolean replace) {
    checkFetched();
    if (replace) {
        errorCallbacks.clear();
    }
    errorCallbacks.add(error);
    return this;
}
 
Example #16
Source File: ImageDownloadService.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs an image request that will automatically populate the given Label
 * when the response arrives, it will cache the file locally.
 *
 * @param url the image URL
 * @param callback the callback that should be updated when the data arrives
 * @param cacheId a unique identifier to be used to store the image into storage
 * @param keep if set to true keeps the file in RAM once loaded
 */
public static void createImageToStorage(String url, ActionListener callback, String cacheId, boolean keep) {

    Image im = cacheImage(cacheId, keep, null, null, null, defaultMaintainAspectRatio);
    if (im != null) {
        callback.actionPerformed(new NetworkEvent(null, im));
        return;
    }
    //image not found on cache go and download from the url
    ImageDownloadService i = new ImageDownloadService(url, callback);
    i.cacheImages = true;
    i.cacheId = cacheId;
    i.setFailSilently(true);
    NetworkManager.getInstance().addToQueue(i);
}
 
Example #17
Source File: ImageDownloadService.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void handleErrorResponseCode(int code, String message) {
    if(onErrorListeners != null) {
        NetworkEvent ne = new NetworkEvent(this, code, message);
        onErrorListeners.fireActionEvent(ne);
    }
}
 
Example #18
Source File: ImageDownloadService.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void handleException(Exception err) {
    if(onErrorListeners != null) {
        NetworkEvent ne = new NetworkEvent(this, err);
        onErrorListeners.fireActionEvent(ne);
    }
}
 
Example #19
Source File: ProxyHttpTile.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an Http Tile
 * 
 * @param tileSize the tile size
 * @param bbox the tile bounding box
 * @param url the url to bring the image from
 */
public ProxyHttpTile(Dimension tileSize, BoundingBox bbox, final String url) {
    super(tileSize, bbox, null);
    _url = url;
    String cacheId = url.substring(url.indexOf(":")+1);
    cacheId = StringUtil.replaceAll(cacheId, "\\", "_");
    cacheId = StringUtil.replaceAll(cacheId, "/", "_");
    cacheId = StringUtil.replaceAll(cacheId, ".", "_");
    cacheId = StringUtil.replaceAll(cacheId, "?", "_");
    cacheId = StringUtil.replaceAll(cacheId, "&", "_");
    
    ImageDownloadService.createImageToStorage(url, new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            NetworkEvent ne = (NetworkEvent) evt;

            Image i = (Image) ne.getMetaData();
            i.lock();
            _tile = new Tile(ProxyHttpTile.this.dimension(),
                    ProxyHttpTile.this.getBoundingBox(),
                    i);
            ProxyHttpTile.this.fireReady();
        }
    }, cacheId, true);


}
 
Example #20
Source File: ImageDownloadService.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void postResponse() {
    // trigger an exception in case of an invalid image
    result.getWidth();
    Image image = result;

    if (toScale != null && toScale.getWidth() != image.getWidth() && toScale.getHeight() != image.getHeight()) {
        image = scaleImage(image, toScale, maintainAspectRatio);
    }

    final Image i = image;
    if(parentLabel != null) {
        final Dimension pref = parentLabel.getPreferredSize();
        if(parentLabel.getComponentForm() != null) {
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    if(isDownloadToStyles()) {
                        parentLabel.getUnselectedStyle().setBgImage(i);
                        parentLabel.getSelectedStyle().setBgImage(i);
                        parentLabel.getPressedStyle().setBgImage(i);
                    } else {
                        parentLabel.setIcon(i);
                    }
                    Dimension newPref = parentLabel.getPreferredSize();
                    // if the preferred size changed we need to reflow the UI
                    // this might not be necessary if the label already had an identically
                    // sized image in place or has a hardcoded preferred size.
                    if(pref.getWidth() != newPref.getWidth() || pref.getHeight() != newPref.getHeight()) {
                        parentLabel.getComponentForm().revalidate();
                    }
                }
            });

        } else {
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    if(isDownloadToStyles()) {
                        parentLabel.getUnselectedStyle().setBgImage(i);
                        parentLabel.getSelectedStyle().setBgImage(i);
                        parentLabel.getPressedStyle().setBgImage(i);
                    } else {
                        parentLabel.setIcon(i);
                    }
                    
                }
            });
        }
        parentLabel.repaint();
        return;
    } else {
        if(targetList != null) {
            setEntryInListModel(targetOffset, image);
                            
            // revalidate only once to avoid multiple revalidate refreshes during scroll
            if(targetList.getParent() != null) {
                if(alwaysRevalidate) {
                    targetList.getParent().revalidate();
                } else {
                    if(targetList.getClientProperty("$imgDSReval") == null) {
                        targetList.putClientProperty("$imgDSReval", Boolean.TRUE);
                        targetList.getParent().revalidate();
                    } else {
                        targetList.repaint();
                    }
                }
            }
        }
    }

    // if this is a list cell renderer component
    fireResponseListener(new NetworkEvent(this, result));
}
 
Example #21
Source File: TwitterRESTService.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void readResponse(InputStream input) throws IOException  {
    InputStreamReader i = new InputStreamReader(input, "UTF-8");
    parseTree = new JSONParser().parse(i);
    fireResponseListener(new NetworkEvent(this, parseTree));
}
 
Example #22
Source File: CachedDataService.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void readResponse(InputStream input) throws IOException  {
    data.setData(Util.readInputStream(input));
    fireResponseListener(new NetworkEvent(this, data));
    data.setFetching(false);
}
 
Example #23
Source File: FacebookShare.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void share(String text, final String image, final String mime) {
    final ShareForm[] f = new ShareForm[1];
    if (image == null) {
        f[0] = new ShareForm(getOriginal(), "Post on My Wall", null, text,
                new ActionListener() {

                    public void actionPerformed(ActionEvent evt) {
                        try {
                            InfiniteProgress inf = new InfiniteProgress();
                            final Dialog progress = inf.showInifiniteBlocking();
                            FaceBookAccess.getInstance().addResponseCodeListener(new ActionListener() {

                                public void actionPerformed(ActionEvent evt) {
                                    NetworkEvent ne = (NetworkEvent) evt;
                                    int code = ne.getResponseCode();
                                    FaceBookAccess.getInstance().removeResponseCodeListener(this);
                                    progress.dispose();
                                    Dialog.show("Failed to Share", "for some reason sharing has failed, try again later.", "Ok", null);
                                    finish();
                                }
                            });
                            FaceBookAccess.getInstance().postOnWall("me", f[0].getMessage(), new ActionListener() {

                                public void actionPerformed(ActionEvent evt) {
                                    progress.dispose();
                                    finish();
                                }
                            });

                        } catch (IOException ex) {
                            Log.e(ex);
                            System.out.println("failed to share " + ex.getMessage());
                        }
                    }
                });
        f[0].show();
    } else {
        f[0] = new ShareForm(getOriginal(), "Post on My Wall", null, text, image,
                new ActionListener() {

                    public void actionPerformed(ActionEvent evt) {

                        InfiniteProgress inf = new InfiniteProgress();
                        final Dialog progress = inf.showInifiniteBlocking();
                        FaceBookAccess.getInstance().addResponseCodeListener(new ActionListener() {

                            public void actionPerformed(ActionEvent evt) {
                                NetworkEvent ne = (NetworkEvent) evt;
                                int code = ne.getResponseCode();
                                FaceBookAccess.getInstance().removeResponseCodeListener(this);
                                progress.dispose();
                                Dialog.show("Failed to Share", "for some reason sharing has failed, try again later.", "Ok", null);
                                finish();
                            }
                        });

                        MultipartRequest req = new MultipartRequest();
                        req.addResponseListener(new ActionListener() {                                
                            public void actionPerformed(ActionEvent evt) {
                                progress.dispose();
                                finish();
                            }
                        });
                        final String endpoint = "https://graph.facebook.com/me/photos?access_token=" + token;
                        req.setUrl(endpoint);
                        req.addArgumentNoEncoding("message", f[0].getMessage());
                        InputStream is = null;
                        try {
                            is = FileSystemStorage.getInstance().openInputStream(image);
                            req.addData("source", is, FileSystemStorage.getInstance().getLength(image), mime);
                            NetworkManager.getInstance().addToQueue(req);
                        } catch (IOException ioe) {
                            Log.e(ioe);
                        }
                    }
                });
        f[0].show();

    }

}
 
Example #24
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Invoked for exceptions or failures such as disconnect.  Replaces any existing
 * callbacks previously registered with {@link #onError(com.codename1.ui.events.ActionListener) }
 * @param error callback for a networking error
 * @return RequestBuilder instance
 * @see #onError(com.codename1.ui.events.ActionListener, boolean) 
 * 
 */
public RequestBuilder onError(ActionListener<NetworkEvent> error) {
    return onError(error, true);
}
 
Example #25
Source File: CN.java    From CodenameOne with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Adds a listener to be notified when progress updates
 *
 * @param al action listener
 */
public static void removeNetworkProgressListener(ActionListener<NetworkEvent> al) {
    NetworkManager.getInstance().removeProgressListener(al);
}
 
Example #26
Source File: CN.java    From CodenameOne with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Adds a listener to be notified when progress updates
 *
 * @param al action listener
 */
public static void addNetworkProgressListener(ActionListener<NetworkEvent> al) {
    NetworkManager.getInstance().addProgressListener(al);
}
 
Example #27
Source File: CN.java    From CodenameOne with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Removes the given error listener
 *
 * @param e callback to remove
 */
public static void removeNetworkErrorListener(ActionListener<NetworkEvent> e) {
    NetworkManager.getInstance().removeErrorListener(e);
}
 
Example #28
Source File: CN.java    From CodenameOne with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Adds a generic listener to a network error that is invoked before the exception is propagated.
 * Note that this handles also server error codes by default! You can change this default behavior setting to false
 * ConnectionRequest.setHandleErrorCodesInGlobalErrorHandler(boolean).
 * Consume the event in order to prevent it from propagating further.
 *
 * @param e callback will be invoked with the Exception as the source object
 */
public static void addNetworkErrorListener(ActionListener<NetworkEvent> e) {
    NetworkManager.getInstance().addErrorListener(e);
}