com.codename1.io.NetworkManager Java Examples

The following examples show how to use com.codename1.io.NetworkManager. 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: TwitterRESTService.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Logs in to twitter as an application
 * 
 * @param consumerKey the key to login with
 * @param consumerSecret the secret to to login with
 * @return the authorization token
 */
public static String initToken(String consumerKey, String consumerSecret) {
    ConnectionRequest auth = new ConnectionRequest() {
        protected void readResponse(InputStream input) throws IOException  {
            JSONParser p = new JSONParser();
            Hashtable h = p.parse(new InputStreamReader(input));
            authToken = (String)h.get("access_token");
            if(authToken == null) {
                return;
            }
        }
    };
    auth.setPost(true);
    auth.setUrl("https://api.twitter.com/oauth2/token");
    
    // YOU MUST CHANGE THIS IF YOU BUILD YOUR OWN APP
    String encoded = Base64.encodeNoNewline((consumerKey + ":" + consumerSecret).getBytes());
    auth.addRequestHeader("Authorization", "Basic " + encoded);
    auth.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
    auth.addArgument("grant_type", "client_credentials");
    NetworkManager.getInstance().addToQueueAndWait(auth);
    return authToken;
}
 
Example #2
Source File: GoogleConnect.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected boolean validateToken(String token) {
    //make a call to the API if the return value is 40X the token is not 
    //valid anymore
    final boolean[] retval = new boolean[1];
    retval[0] = true;
    ConnectionRequest req = new ConnectionRequest() {
        @Override
        protected void handleErrorResponseCode(int code, String message) {
            //access token not valid anymore
            if (code >= 400 && code <= 410) {
                retval[0] = false;
                return;
            }
            super.handleErrorResponseCode(code, message);
        }

    };
    req.setPost(false);
    req.setUrl("https://www.googleapis.com/plus/v1/people/me");
    req.addRequestHeader("Authorization", "Bearer " + token);
    NetworkManager.getInstance().addToQueueAndWait(req);
    return retval[0];

}
 
Example #3
Source File: FacebookConnect.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected boolean validateToken(String token) {
    //make a call to the API if the return value is 40X the token is not 
    //valid anymore
    final boolean[] retval = new boolean[1];
    retval[0] = true;
    ConnectionRequest req = new ConnectionRequest() {
        @Override
        protected void handleErrorResponseCode(int code, String message) {
            //access token not valid anymore
            if (code >= 400 && code <= 410) {
                retval[0] = false;
                return;
            }
            super.handleErrorResponseCode(code, message);
        }

    };
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/v2.4/me");
    req.addArgumentNoEncoding("access_token", token);
    NetworkManager.getInstance().addToQueueAndWait(req);
    return retval[0];
}
 
Example #4
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method returns immediately and will call the callback when it returns with
 * the FaceBook Object data.
 *
 * @param faceBookId the object id that we would like to query
 * @param callback the callback that should be updated when the data arrives
 */
public void getFaceBookObject(String faceBookId, final ActionListener callback) throws IOException {
    checkAuthentication();
    final FacebookRESTService con = new FacebookRESTService(token, faceBookId, "", false);
    con.addResponseListener(new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            if (!con.isAlive()) {
                return;
            }
            if (callback != null) {
                callback.actionPerformed(evt);
            }
        }
    });
    if (slider != null) {
        SliderBridge.bindProgress(con, slider);
    }
    for (int i = 0; i < responseCodeListeners.size(); i++) {
        con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
    }
    current = con;
    NetworkManager.getInstance().addToQueue(con);
}
 
Example #5
Source File: CloudStorage.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Commit works synchronously and returns one of the return codes above to indicate 
 * the status. 
 * @return status code from the constants in this class
 */
public synchronized int commit() {
    if(storageQueue.size() > 0) { 
        if(CloudPersona.getCurrentPersona().getToken() == null) {
            CloudPersona.createAnonymous();
        }
        StorageRequest req = new StorageRequest();
        req.setContentType("multipart/form-data");
        req.setUrl(SERVER_URL + "/objStoreCommit");
        req.setPost(true);
        NetworkManager.getInstance().addToQueueAndWait(req);

        int i = req.getReturnCode();
        if(i == RETURN_CODE_SUCCESS) {
            storageQueue.clear();
            Storage.getInstance().deleteStorageFile("CN1StorageQueue");
        }
        return i;
    }
    return RETURN_CODE_EMPTY_QUEUE;
}
 
Example #6
Source File: CloudStorage.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Deletes a file from the cloud storage
 * 
 * @param fileId the file id to delete
 * @return true if the operation was successful
 * @deprecated this API is currently deprecated due to Googles cloud storage deprection
 */
public boolean deleteCloudFile(String fileId) {
    if(CloudPersona.getCurrentPersona().getToken() == null) {
        CloudPersona.createAnonymous();
    }
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setFailSilently(true);
    req.setUrl(SERVER_URL + "/fileStoreDelete");
    req.addArgument("i", fileId);
    req.addArgument("t", CloudPersona.getCurrentPersona().getToken());
    NetworkManager.getInstance().addToQueueAndWait(req);
    if(req.getResponseCode() == 200) {
        return new String(req.getResponseData()).equals("OK");
    }
    return false;
}
 
Example #7
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a list of FaceBook objects for a given id
 * 
 * @param faceBookId the id to preform the query upon
 * @param itemsConnection the type of the query
 * @param feed
 * @param params
 * @param callback the callback that should be updated when the data arrives
 */
public void getFaceBookObjectItems(String faceBookId, String itemsConnection,
        final DefaultListModel feed, Hashtable params, final ActionListener callback) throws IOException {
    checkAuthentication();

    final FacebookRESTService con = new FacebookRESTService(token, faceBookId, itemsConnection, false);
    con.setResponseDestination(feed);
    con.addResponseListener(new Listener(con, callback));
    if (params != null) {
        Enumeration keys = params.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            con.addArgument(key, (String) params.get(key));
        }
    }
    if (slider != null) {
        SliderBridge.bindProgress(con, slider);
    }
    for (int i = 0; i < responseCodeListeners.size(); i++) {
        con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
    }
    current = con;
    NetworkManager.getInstance().addToQueue(con);
}
 
Example #8
Source File: CloudStorage.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private int refreshImpl(CloudObject[] objects, CloudResponse<Integer> response) {
    RefreshConnection refreshRequest = new RefreshConnection();
    refreshRequest.objects = objects;
    refreshRequest.response = response;
    refreshRequest.setPost(true);
    refreshRequest.setUrl(SERVER_URL + "/objStoreRefresh");
    for(int iter = 0 ; iter  < objects.length ; iter++) {
        objects[iter].setStatus(CloudObject.STATUS_REFRESH_IN_PROGRESS);
        refreshRequest.addArgument("i" + iter, objects[iter].getCloudId());
        refreshRequest.addArgument("m" + iter, "" + objects[iter].getLastModified());
    }
    refreshRequest.addArgument("t", CloudPersona.getCurrentPersona().getToken());
    refreshRequest.addArgument("pk", Display.getInstance().getProperty("package_name", null));
    refreshRequest.addArgument("bb", Display.getInstance().getProperty("built_by_user", null));
    
    // async code
    if(response != null) {
        NetworkManager.getInstance().addToQueue(refreshRequest);
        return -1;
    } 
    
    NetworkManager.getInstance().addToQueueAndWait(refreshRequest);
    
    return refreshRequest.returnValue;
}
 
Example #9
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Post a message on the users wall
 *
 * @param userId the userId
 * @param message the message to post
 */
public void postOnWall(String userId, String message, ActionListener callback) throws IOException {
    checkAuthentication();

    FacebookRESTService con = new FacebookRESTService(token, userId, FacebookRESTService.FEED, true);
    con.addArgument("message", "" + message);
    con.addResponseListener(new Listener(con, callback));
    if (slider != null) {
        SliderBridge.bindProgress(con, slider);
    }
    for (int i = 0; i < responseCodeListeners.size(); i++) {
        con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
    }
    current = con;
    NetworkManager.getInstance().addToQueueAndWait(con);
}
 
Example #10
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Post a comment on a given post
 *
 * @param postId the post id
 * @param message the message to post
 */
public void postComment(String postId, String message, ActionListener callback) throws IOException {
    checkAuthentication();

    FacebookRESTService con = new FacebookRESTService(token, postId, FacebookRESTService.COMMENTS, true);
    con.addResponseListener(new Listener(con, callback));
    con.addArgument("message", "" + message);
    if (slider != null) {
        SliderBridge.bindProgress(con, slider);
    }
    for (int i = 0; i < responseCodeListeners.size(); i++) {
        con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
    }
    current = con;
    NetworkManager.getInstance().addToQueueAndWait(con);
}
 
Example #11
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Post a note onto the users wall
 *
 * @param userId the userId
 * @param message the message to post
 */
public void createNote(String userId, String subject, String message, ActionListener callback) throws IOException {
    checkAuthentication();
    
    FacebookRESTService con = new FacebookRESTService(token, userId, FacebookRESTService.NOTES, true);
    con.addResponseListener(new Listener(con, callback));
    con.addArgument("subject","" + subject);
    con.addArgument("message", "" + message);
    if (slider != null) {
        SliderBridge.bindProgress(con, slider);
    }
    for (int i = 0; i < responseCodeListeners.size(); i++) {
        con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
    }
    current = con;        
    System.out.println(con.getUrl());
    NetworkManager.getInstance().addToQueueAndWait(con);
}
 
Example #12
Source File: CachedDataService.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks that the cached data is up to date and if a newer version exits it updates the data in place
 * 
 * @param d the data to check
 * @param callback optional callback to be invoked on request completion
 */
public static void updateData(CachedData d, ActionListener callback) {
    if(d.isFetching()) {
        return;
    }
    d.setFetching(true);
    CachedDataService c = new CachedDataService();
    c.setUrl(d.getUrl());
    c.setPost(false);
    if(callback != null) {
        c.addResponseListener(callback);
    }
    if(d.getModified() != null && d.getModified().length() > 0) {
        c.addRequestHeader("If-Modified-Since", d.getModified());
        if(d.getEtag() != null) {
            c.addRequestHeader("If-None-Match", d.getEtag());
        }
    }
    NetworkManager.getInstance().addToQueue(c);        
}
 
Example #13
Source File: BlackBerryImplementation.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @inheritDoc
 */
public int getAPType(String id) {
    Vector v = getValidSBEntries();
    for (int iter = 0; iter < v.size(); iter++) {
        ServiceRecord r = (ServiceRecord) v.elementAt(iter);
        if (("" + r.getUid()).equals(id)) {
            if (r.getUid().toLowerCase().indexOf("wifi") > -1) {
                return NetworkManager.ACCESS_POINT_TYPE_WLAN;
            }
            // wap2
            if (r.getCid().toLowerCase().indexOf("wptcp") > -1) {
                return NetworkManager.ACCESS_POINT_TYPE_NETWORK3G;
            }
            return NetworkManager.ACCESS_POINT_TYPE_UNKNOWN;
        }
    }
    return NetworkManager.ACCESS_POINT_TYPE_UNKNOWN;
}
 
Example #14
Source File: Progress.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Binds the progress UI to the completion of this request
 *
 * @param title the title of the progress dialog
 * @param request the network request pending
 * @param showPercentage shows percentage on the progress bar
 */
public Progress(String title, ConnectionRequest request, boolean showPercentage) {
    super(title);
    this.request = request;
    SliderBridge b = new SliderBridge(request);
    b.setRenderPercentageOnTop(showPercentage);
    b.setRenderValueOnTop(true);
    setLayout(new BoxLayout(BoxLayout.Y_AXIS));
    addComponent(b);
    Command cancel = new Command(UIManager.getInstance().localize("cancel", "Cancel"));
    if(Display.getInstance().isTouchScreenDevice() || getSoftButtonCount() < 2) {
        // if this is a touch screen device or a blackberry use a centered button
        Button btn = new Button(cancel);
        Container cnt = new Container(new FlowLayout(CENTER));
        cnt.addComponent(btn);
        addComponent(cnt);
    } else {
        // otherwise use a command
        addCommand(cancel);
    }
    setDisposeWhenPointerOutOfBounds(false);
    setAutoDispose(false);
    NetworkManager.getInstance().addProgressListener(this);
}
 
Example #15
Source File: SignIn.java    From codenameone-demos with GNU General Public License v2.0 6 votes vote down vote up
private void showGoogleUser(String token){
    ConnectionRequest req = new ConnectionRequest();
    req.addRequestHeader("Authorization", "Bearer " + token);
    req.setUrl("https://www.googleapis.com/plus/v1/people/me");
    req.setPost(false);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog d = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(req);
    d.dispose();
    byte[] data = req.getResponseData();
    JSONParser parser = new JSONParser();
    Map map = null;
    try {
        map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String name = (String) map.get("displayName");
    Map im = (Map) map.get("image");
    String url = (String) im.get("url");
    Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), url);
    userForm.show();
}
 
Example #16
Source File: SignIn.java    From codenameone-demos with GNU General Public License v2.0 6 votes vote down vote up
private void showFacebookUser(String token){
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/v2.3/me");
    req.addArgumentNoEncoding("access_token", token);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog d = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(req);
    byte[] data = req.getResponseData();
    JSONParser parser = new JSONParser();
    Map map = null;
    try {
        map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String name = (String) map.get("name");
    d.dispose();
    Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), "https://graph.facebook.com/v2.3/me/picture?access_token=" + token);
    userForm.show();
}
 
Example #17
Source File: RSSReader.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Send the request to the server, will only work once. This is called implicitly
 * when the list is initialized
 */
public void sendRequest() {
    if(service == null) {
        service = new RSSService(url, limit);
        if(iconPlaceholder != null) {
            service.setIconPlaceholder(iconPlaceholder);
        }
        service.addResponseListener(new EventHandler());
        if(blockList) {
            Progress p = new Progress(progressTitle, service, displayProgressPercentage);
            p.setAutoShow(true);
            p.setDisposeOnCompletion(true);
        }
        setHint(progressTitle);
        NetworkManager.getInstance().addToQueue(service);
    }
}
 
Example #18
Source File: SignIn.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private void showFacebookUser(String token){
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/v2.3/me");
    req.addArgumentNoEncoding("access_token", token);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog d = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(req);
    byte[] data = req.getResponseData();
    JSONParser parser = new JSONParser();
    Map map = null;
    try {
        map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String name = (String) map.get("name");
    d.dispose();
    Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), "https://graph.facebook.com/v2.3/me/picture?access_token=" + token);
    userForm.show();
}
 
Example #19
Source File: SignIn.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private void showGoogleUser(String token){
    ConnectionRequest req = new ConnectionRequest();
    req.addRequestHeader("Authorization", "Bearer " + token);
    req.setUrl("https://www.googleapis.com/plus/v1/people/me");
    req.setPost(false);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog d = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(req);
    d.dispose();
    byte[] data = req.getResponseData();
    JSONParser parser = new JSONParser();
    Map map = null;
    try {
        map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String name = (String) map.get("displayName");
    Map im = (Map) map.get("image");
    String url = (String) im.get("url");
    Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), url);
    userForm.show();
}
 
Example #20
Source File: AutocompleteOverrideFilterSample.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
String[] searchLocations(String text) {        
    try {
        if(text.length() > 0) {
            if (currRequest != null) {
                //currRequest.kill();
                
            }
                
            ConnectionRequest r = new ConnectionRequest();
            currRequest = r;
            r.setPost(false);
            r.setUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json");
            r.addArgument("key", apiKey.getText());
            r.addArgument("input", text);
            NetworkManager.getInstance().addToQueueAndWait(r);
            Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
            String[] res = Result.fromContent(result).getAsStringArray("//description");
            return res;
        }
    } catch(Exception err) {
        Log.e(err);
    }
    return null;
}
 
Example #21
Source File: Progress.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void dispose() {
    NetworkManager.getInstance().removeProgressListener(this);
    super.dispose();
    showing = false;
    autoShow = false;
}
 
Example #22
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 #23
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 list
 * when the response arrives, it will cache the file locally as a file
 * in the file storage.
 * This assumes the GenericListCellRenderer style of
 * list which relies on a map based model approach.
 *
 * @param url the image URL
 * @param targetList the list that should be updated when the data arrives
 * @param targetModel the model
 * @param targetOffset the offset within the list to insert the image
 * @param targetKey the key for the map in the target offset
 * @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
 * @param scale the scale of the image to put in the List or null
 */
private static void createImageToStorage(final String url, final Component targetList, final ListModel targetModel, final int targetOffset,
        final String targetKey, final String cacheId, final boolean keep, final Dimension scale, final byte priority, final Image placeholderImage,
        final boolean maintainAspectRatio) {
    if (Display.getInstance().isEdt()) {
        Display.getInstance().scheduleBackgroundTask(new Runnable() {

            public void run() {
                createImageToStorage(url, targetList, targetModel, targetOffset,
                        targetKey, cacheId, keep, scale, priority, placeholderImage, maintainAspectRatio);
            }
        });
        return;
    }
    Image im = cacheImage(cacheId, keep, null, scale, placeholderImage, maintainAspectRatio);
    ImageDownloadService i = new ImageDownloadService(url, targetList, targetOffset, targetKey);
    i.targetModel = targetModel;
    i.maintainAspectRatio = maintainAspectRatio;
    if (im != null) {
        i.setEntryInListModel(targetOffset, im);
        targetList.repaint();            
        
        return;
    }
    //image not found on cache go and download from the url
    i.cacheImages = true;
    i.cacheId = cacheId;
    i.keep = keep;
    i.toScale = scale;
    i.placeholder = placeholderImage;
    i.setPriority(priority);
    i.setFailSilently(true);
    NetworkManager.getInstance().addToQueue(i);
}
 
Example #24
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 list
 * when the response arrives, it will cache the file locally as a file
 * in the file storage.
 * This assumes the GenericListCellRenderer style of
 * list which relies on a map based model approach.
 *
 * @param url the image URL
 * @param targetList the list that should be updated when the data arrives
 * @param targetOffset the offset within the list to insert the image
 * @param targetKey the key for the map in the target offset
 * @param destFile local file to store the data into the given path
 */
private static void createImageToFileSystem(final String url, final Component targetList, final ListModel targetModel, final int targetOffset,
        final String targetKey, final String destFile, final Dimension toScale, final byte priority, final Image placeholderImage, 
        final boolean maintainAspectRatio) {
    if (Display.getInstance().isEdt()) {
        Display.getInstance().scheduleBackgroundTask(new Runnable() {

            public void run() {
                createImageToFileSystem(url, targetList, targetModel, targetOffset,
                        targetKey, destFile, toScale, priority, placeholderImage, maintainAspectRatio);
            }
        });
        return;
    }


    //image not found on cache go and download from the url
    ImageDownloadService i = new ImageDownloadService(url, targetList, targetOffset, targetKey);
    i.targetModel = targetModel;
    i.maintainAspectRatio = maintainAspectRatio;
    Image im = cacheImage(null, false, destFile, toScale, placeholderImage, maintainAspectRatio);
    if (im != null) {
        i.setEntryInListModel(targetOffset, im);
        targetList.repaint();
        
        return;
    }
    i.cacheImages = true;
    i.destinationFile = destFile;
    i.toScale = toScale;
    i.placeholder = placeholderImage;
    i.setPriority(priority);
    i.setFailSilently(true);
    NetworkManager.getInstance().addToQueue(i);
}
 
Example #25
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * log out the current user
 */
public static void logOut(){
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl("https://www.facebook.com/logout.php?access_token="+token+"&confirm=1&next="+redirectURI);
    NetworkManager.getInstance().addToQueueAndWait(req);
    token = null;
}
 
Example #26
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 #27
Source File: CloudPersona.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an anonymous persona that will be unique in the cloud, NEVER logout an anonymous user!
 * @return false in case login failed e.g. due to bad network connection
 */
public static boolean createAnonymous() {
    if(instance == null) {
        getCurrentPersona();
    }
    ConnectionRequest login = new ConnectionRequest();
    login.setPost(true);
    login.setUrl(CloudStorage.SERVER_URL + "/objStoreUser");
    login.addArgument("pk", Display.getInstance().getProperty("package_name", null));
    login.addArgument("bb", Display.getInstance().getProperty("built_by_user", null));
    NetworkManager.getInstance().addToQueueAndWait(login);
    if(login.getResposeCode() != 200) {
        return false;
    }
    
    ByteArrayInputStream bi = new ByteArrayInputStream(login.getResponseData());
    DataInputStream di = new DataInputStream(bi);
    
    if(instance == null) {
        instance = new CloudPersona();
    } 
    try {
        instance.persona = di.readUTF();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    Preferences.set("CN1Persona", instance.persona);
    Preferences.set("CN1PersonaAnonymous", true);
    
    Util.cleanup(di);
    
    return true;
}
 
Example #28
Source File: SocialChat.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void fetchData(String token, Runnable callback) {
    this.token = token;
    ConnectionRequest req = new ConnectionRequest() {
        @Override
        protected void readResponse(InputStream input) throws IOException {
            JSONParser parser = new JSONParser();
            Map<String, Object> parsed = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
            name = (String) parsed.get("name");
            id = (String) parsed.get("id");
        }

        @Override
        protected void postResponse() {
            callback.run();
        }

        @Override
        protected void handleErrorResponseCode(int code, String message) {
            //access token not valid anymore
            if(code >= 400 && code <= 410){
                doLogin(FacebookConnect.getInstance(), FacebookData.this, true);
                return;
            }
            super.handleErrorResponseCode(code, message);
        }
    };
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/v2.4/me");
    req.addArgumentNoEncoding("access_token", token);
    NetworkManager.getInstance().addToQueue(req);
}
 
Example #29
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Some simple queries for public data can work just fine with anonymous login without requiring the whole
 * OAuth process, they still need a facebook application though
 * @param appid the id of the application
 * @param clientSecret the client secret for the application
 */
public static void anonymousLogin(String appid, String clientSecret) {
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/oauth/access_token");
    req.addArgument("client_id", appid);
    req.addArgument("client_secret", clientSecret);
    req.addArgument("grant_type", "client_credentials");
    NetworkManager.getInstance().addToQueueAndWait(req);
    if(req.getResponseData() != null) {
        token = new String(req.getResponseData());
        token = token.substring(token.indexOf('=') + 1);
    }
}
 
Example #30
Source File: AnalyticsService.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * In apps mode we can send information about an exception to the analytics server
 * @param t the exception
 * @param message up to 150 character message, 
 * @param fatal is the exception fatal
 */
public static void sendCrashReport(Throwable t, String message, boolean fatal) {
    // https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#exception
    ConnectionRequest req = GetGARequest();
    req.addArgument("t", "exception");
    System.out.println(message);
    req.addArgument("exd", message.substring(0, Math.min(message.length(), 150) - 1));
    if(fatal) {
        req.addArgument("exf", "1");
    } else {
        req.addArgument("exf", "0");
    }
    
    NetworkManager.getInstance().addToQueue(req);
}