Search in sources :

Example 11 with JSONParser

use of com.codename1.builders.util.JSONParser in project CodenameOne by codenameone.

the class PropertyIndex method fromJSON.

/**
 * Populates the object from a JSON string
 * @param jsonString the JSON String
 */
public void fromJSON(String jsonString) {
    try {
        StringReader r = new StringReader(jsonString);
        JSONParser jp = new JSONParser();
        JSONParser.setUseBoolean(true);
        JSONParser.setUseLongs(true);
        populateFromMap(jp.parseJSON(r), parent.getClass());
    } catch (IOException err) {
        Log.e(err);
        throw new RuntimeException(err.toString());
    }
}
Also used : StringReader(com.codename1.util.regex.StringReader) JSONParser(com.codename1.io.JSONParser) IOException(java.io.IOException)

Example 12 with JSONParser

use of com.codename1.builders.util.JSONParser in project CodenameOne by codenameone.

the class GoogleImpl method nativeLoginImpl.

private void nativeLoginImpl(final GoogleApiClient client) {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(client);
    AndroidNativeUtil.startActivityForResult(signInIntent, RC_SIGN_IN, new IntentResultListener() {

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
            if (requestCode == RC_SIGN_IN) {
                final GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                if (result.isSuccess()) {
                    // Signed in successfully, show authenticated UI.
                    GoogleSignInAccount acct = result.getSignInAccount();
                    String displayName = acct.getDisplayName();
                    String acctId = acct.getId();
                    String email = acct.getEmail();
                    String requestIdToken = acct.getIdToken();
                    Set<Scope> grantedScopes = acct.getGrantedScopes();
                    String code = acct.getServerAuthCode();
                    String scopeStr = scope;
                    System.out.println("Token is " + acct.getIdToken());
                    if (acct.getIdToken() == null && clientId != null && clientSecret != null) {
                        Log.p("Received null ID token even though clientId and clientSecret are set.");
                    }
                    // otherwise we'll set the token to null.
                    if (clientId != null && clientSecret != null && requestIdToken != null && code != null) {
                        ConnectionRequest req = new ConnectionRequest() {

                            @Override
                            protected void readResponse(InputStream input) throws IOException {
                                Map<String, Object> json = new JSONParser().parseJSON(new InputStreamReader(input, "UTF-8"));
                                if (json.containsKey("access_token")) {
                                    setAccessToken(new AccessToken((String) json.get("access_token"), (String) null));
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                } else {
                                    setAccessToken(new AccessToken());
                                    Log.p("Failed to retrieve the access token from the google auth server.  Login succeeded, but access token is null, so you won't be able to use it to retrieve additional information.");
                                    Log.p("Response was " + json);
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                }
                            }
                        };
                        req.setUrl("https://www.googleapis.com/oauth2/v4/token");
                        req.addArgument("grant_type", "authorization_code");
                        // req.addArgument("client_id", "555462747934-iujpd5saj4pjpibo7c6r9tbjfef22rh1.apps.googleusercontent.com");
                        req.addArgument("client_id", clientId);
                        // req.addArgument("client_secret", "650YqplrnAI0KXb9LMUnVNnx");
                        req.addArgument("client_secret", clientSecret);
                        req.addArgument("redirect_uri", "");
                        req.addArgument("code", code);
                        req.addArgument("id_token", requestIdToken);
                        req.setPost(true);
                        req.setReadResponseForErrors(true);
                        NetworkManager.getInstance().addToQueue(req);
                    } else {
                        setAccessToken(new AccessToken());
                        Log.p("The access token was set to null because one of clientId, clientSecret, requestIdToken, or auth were null");
                        Log.p("The login succeeded, but you won't be able to make any requests to Google's REST apis using the login token.");
                        Log.p("In order to obtain a token that can be used with Google's REST APIs, you need to set the clientId, and clientSecret of" + "the GoogleConnect instance to valid OAuth2.0 Client IDs for Web Clients.");
                        Log.p("See https://console.developers.google.com/apis/credentials");
                        Log.p("You can get the OAuth2.0 client ID for this project in your google-services.json file in the oauth_client section");
                        Display.getInstance().callSerially(new Runnable() {

                            @Override
                            public void run() {
                                callback.loginSuccessful();
                            }
                        });
                    }
                } else {
                    if (callback != null) {
                        if (callback != null) {
                            Display.getInstance().callSerially(new Runnable() {

                                @Override
                                public void run() {
                                    callback.loginFailed(GooglePlayServicesUtil.getErrorString(result.getStatus().getStatusCode()));
                                }
                            });
                        }
                    }
                }
            }
        }
    });
}
Also used : Set(java.util.Set) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Intent(android.content.Intent) IOException(java.io.IOException) GoogleSignInResult(com.google.android.gms.auth.api.signin.GoogleSignInResult) ConnectionRequest(com.codename1.io.ConnectionRequest) GoogleSignInAccount(com.google.android.gms.auth.api.signin.GoogleSignInAccount) IntentResultListener(com.codename1.impl.android.IntentResultListener) AccessToken(com.codename1.io.AccessToken) JSONParser(com.codename1.io.JSONParser) Map(java.util.Map)

Example 13 with JSONParser

use of com.codename1.builders.util.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)

Example 14 with JSONParser

use of com.codename1.builders.util.JSONParser in project CodenameOne by codenameone.

the class PropertyIndex method loadJSONList.

/**
 * Loads JSON containing a list of property objects of this type
 * @param stream the input stream
 * @return list of property objects matching this type
 */
public <X extends PropertyBusinessObject> List<X> loadJSONList(InputStream stream) throws IOException {
    JSONParser jp = new JSONParser();
    JSONParser.setUseBoolean(true);
    JSONParser.setUseLongs(true);
    List<X> response = new ArrayList<X>();
    Map<String, Object> result = jp.parseJSON(new InputStreamReader(stream, "UTF-8"));
    List<Map> entries = (List<Map>) result.get("root");
    for (Map m : entries) {
        X pb = (X) newInstance();
        pb.getPropertyIndex().populateFromMap(m, parent.getClass());
        response.add(pb);
    }
    return response;
}
Also used : InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) JSONParser(com.codename1.io.JSONParser) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 15 with JSONParser

use of com.codename1.builders.util.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 (progress != null && Display.getInstance().getCurrent() == progress) {
            progress.dispose();
        }
        if (web != null) {
            web.stop();
        }
        // remove the browser component.
        if (login != null) {
            login.removeAll();
            login.revalidate();
        }
        if (url.indexOf("code=") > -1) {
            Hashtable params = getParamsFromURL(url);
            handleRedirectURLParams(params);
            class TokenRequest extends ConnectionRequest {

                boolean callbackCalled;

                protected void readResponse(InputStream input) throws IOException {
                    byte[] tok = Util.readInputStream(input);
                    String t = new String(tok);
                    boolean expiresRelative = true;
                    if (t.startsWith("{")) {
                        JSONParser p = new JSONParser();
                        Map map = p.parseJSON(new StringReader(t));
                        handleTokenRequestResponse(map);
                    } else {
                        handleTokenRequestResponse(t);
                    }
                    if (login != null) {
                        login.dispose();
                    }
                }

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

                protected void postResponse() {
                    if (backToParent && backToForm != null && !callbackCalled) {
                        backToForm.showBack();
                    }
                    if (al != null) {
                        if (!callbackCalled) {
                            callbackCalled = true;
                            if (getResponseCode() >= 200 && getResponseCode() < 300) {
                                al.actionPerformed(new ActionEvent(new AccessToken(token, expires, refreshToken, identityToken), ActionEvent.Type.Response));
                            } else {
                                al.actionPerformed(new ActionEvent(new IOException(getResponseErrorMessage()), ActionEvent.Type.Exception));
                            }
                        }
                    }
                }
            }
            ;
            final TokenRequest req = new TokenRequest();
            req.setReadResponseForErrors(true);
            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);
            if (params.containsKey("cn1_refresh_token")) {
                req.addArgument("grant_type", "refresh_token");
                req.addArgument("refresh_token", (String) params.get("code"));
            } else {
                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) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

JSONParser (com.codename1.io.JSONParser)13 InputStreamReader (java.io.InputStreamReader)12 Map (java.util.Map)11 IOException (java.io.IOException)9 ConnectionRequest (com.codename1.io.ConnectionRequest)6 InputStream (java.io.InputStream)5 AsyncResource (com.codename1.util.AsyncResource)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 HashMap (java.util.HashMap)4 ArrayList (java.util.ArrayList)3 Hashtable (java.util.Hashtable)3 LinkedHashMap (java.util.LinkedHashMap)3 InfiniteProgress (com.codename1.components.InfiniteProgress)2 Dialog (com.codename1.ui.Dialog)2 Form (com.codename1.ui.Form)2 StringReader (com.codename1.util.regex.StringReader)2 List (java.util.List)2 Intent (android.content.Intent)1 JSONParser (com.codename1.builders.util.JSONParser)1 IntentResultListener (com.codename1.impl.android.IntentResultListener)1