Search in sources :

Example 6 with JSONParser

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

the class TwitterRESTService method initToken.

/**
 * 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;
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Hashtable(java.util.Hashtable) JSONParser(com.codename1.io.JSONParser)

Example 7 with JSONParser

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

the class Oauth2 method handleURL.

private void handleURL(String url, WebBrowser web, final ActionListener al, final Form frm, final Form backToForm, final Dialog progress) {
    if ((url.startsWith(redirectURI))) {
        if (Display.getInstance().getCurrent() == progress) {
            progress.dispose();
        }
        web.stop();
        // remove the browser component.
        if (login != null) {
            login.removeAll();
            login.revalidate();
        }
        if (url.indexOf("code=") > -1) {
            Hashtable params = getParamsFromURL(url);
            ConnectionRequest req = new ConnectionRequest() {

                protected void readResponse(InputStream input) throws IOException {
                    byte[] tok = Util.readInputStream(input);
                    String t = new String(tok);
                    if (t.startsWith("{")) {
                        JSONParser p = new JSONParser();
                        Map map = p.parseJSON(new StringReader(t));
                        token = (String) map.get("access_token");
                        Object ex = map.get("expires_in");
                        if (ex == null) {
                            ex = map.get("expires");
                        }
                        if (ex != null) {
                            expires = ex.toString();
                        }
                    } else {
                        token = t.substring(t.indexOf("=") + 1, t.indexOf("&"));
                        int off = t.indexOf("expires=");
                        int start = 8;
                        if (off == -1) {
                            off = t.indexOf("expires_in=");
                            start = 11;
                        }
                        if (off > -1) {
                            int end = t.indexOf('&', off);
                            if (end < 0 || end < off) {
                                end = t.length();
                            }
                            expires = t.substring(off + start, end);
                        }
                    }
                    if (login != null) {
                        login.dispose();
                    }
                }

                protected void handleException(Exception err) {
                    if (backToForm != null) {
                        backToForm.showBack();
                    }
                    if (al != null) {
                        al.actionPerformed(new ActionEvent(err, ActionEvent.Type.Exception));
                    }
                }

                protected void postResponse() {
                    if (backToParent && backToForm != null) {
                        backToForm.showBack();
                    }
                    if (al != null) {
                        al.actionPerformed(new ActionEvent(new AccessToken(token, expires), ActionEvent.Type.Response));
                    }
                }
            };
            req.setUrl(tokenRequestURL);
            req.setPost(true);
            req.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            req.addArgument("client_id", clientId);
            req.addArgument("redirect_uri", redirectURI);
            req.addArgument("client_secret", clientSecret);
            req.addArgument("code", (String) params.get("code"));
            req.addArgument("grant_type", "authorization_code");
            NetworkManager.getInstance().addToQueue(req);
        } else if (url.indexOf("error_reason=") > -1) {
            Hashtable table = getParamsFromURL(url);
            String error = (String) table.get("error_reason");
            if (login != null) {
                login.dispose();
            }
            if (backToForm != null) {
                backToForm.showBack();
            }
            if (al != null) {
                al.actionPerformed(new ActionEvent(new IOException(error), ActionEvent.Type.Exception));
            }
        } else {
            boolean success = url.indexOf("#") > -1;
            if (success) {
                String accessToken = url.substring(url.indexOf("#") + 1);
                if (accessToken.indexOf("&") > 0) {
                    token = accessToken.substring(accessToken.indexOf("=") + 1, accessToken.indexOf("&"));
                } else {
                    token = accessToken.substring(accessToken.indexOf("=") + 1);
                }
                if (login != null) {
                    login.dispose();
                }
                if (backToParent && backToForm != null) {
                    backToForm.showBack();
                }
                if (al != null) {
                    al.actionPerformed(new ActionEvent(new AccessToken(token, expires), ActionEvent.Type.Response));
                }
            }
        }
    } else {
        if (frm != null && Display.getInstance().getCurrent() != frm) {
            progress.dispose();
            frm.show();
        }
    }
}
Also used : Hashtable(java.util.Hashtable) InputStream(java.io.InputStream) ActionEvent(com.codename1.ui.events.ActionEvent) IOException(java.io.IOException) IOException(java.io.IOException) StringReader(com.codename1.util.regex.StringReader) Map(java.util.Map)

Example 8 with JSONParser

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

the class PropertyIndex method loadJSON.

/**
 * Loads JSON for the object from storage with the given name
 * @param name the name of the storage
 */
public void loadJSON(String name) {
    try {
        InputStream is = Storage.getInstance().createInputStream(name);
        JSONParser jp = new JSONParser();
        JSONParser.setUseBoolean(true);
        JSONParser.setUseLongs(true);
        populateFromMap(jp.parseJSON(new InputStreamReader(is, "UTF-8")), parent.getClass());
    } catch (IOException err) {
        Log.e(err);
        throw new RuntimeException(err.toString());
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) DataInputStream(java.io.DataInputStream) InputStream(java.io.InputStream) JSONParser(com.codename1.io.JSONParser) IOException(java.io.IOException)

Aggregations

JSONParser (com.codename1.io.JSONParser)7 InputStreamReader (java.io.InputStreamReader)7 IOException (java.io.IOException)6 ConnectionRequest (com.codename1.io.ConnectionRequest)5 InputStream (java.io.InputStream)5 Map (java.util.Map)4 Hashtable (java.util.Hashtable)3 InfiniteProgress (com.codename1.components.InfiniteProgress)2 Dialog (com.codename1.ui.Dialog)2 Form (com.codename1.ui.Form)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Intent (android.content.Intent)1 IntentResultListener (com.codename1.impl.android.IntentResultListener)1 AccessToken (com.codename1.io.AccessToken)1 NetworkEvent (com.codename1.io.NetworkEvent)1 ActionEvent (com.codename1.ui.events.ActionEvent)1 StringReader (com.codename1.util.regex.StringReader)1 GoogleSignInAccount (com.google.android.gms.auth.api.signin.GoogleSignInAccount)1 GoogleSignInResult (com.google.android.gms.auth.api.signin.GoogleSignInResult)1 DataInputStream (java.io.DataInputStream)1