Search in sources :

Example 1 with JSONParser

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

the class VServAds method createAdRequest.

/**
 * {@inheritDoc}
 */
protected ConnectionRequest createAdRequest() {
    ConnectionRequest con = new ConnectionRequest() {

        protected void handleErrorResponseCode(int code, String message) {
            failed = true;
        }

        protected void handleException(Exception err) {
            failed = true;
            Log.e(err);
        }

        private String getString(Hashtable h, String n) {
            Object v = h.get(n);
            if (v == null) {
                return null;
            }
            if (v instanceof Vector) {
                return (String) ((Vector) v).elementAt(0);
            }
            return (String) v;
        }

        protected void readResponse(InputStream input) throws IOException {
            JSONParser parser = new JSONParser();
            Hashtable h = parser.parse(new InputStreamReader(input, "UTF-8"));
            if (h.size() == 0) {
                return;
            }
            backgroundColor = Integer.parseInt((String) ((Hashtable) ((Vector) h.get("style")).elementAt(0)).get("background-color"), 16);
            Hashtable actionHash = ((Hashtable) ((Vector) h.get("action")).elementAt(0));
            actionNotify = getString(actionHash, "notify");
            if (actionNotify == null) {
                actionNotify = getString(actionHash, "notify-once");
            }
            destination = (String) actionHash.get("data");
            Hashtable renderHash = ((Hashtable) ((Vector) h.get("render")).elementAt(0));
            contentType = (String) renderHash.get("type");
            renderNotify = getString(renderHash, "notify");
            if (renderNotify == null) {
                renderNotify = getString(renderHash, "notify-once");
            }
            imageURL = (String) renderHash.get("data");
        }
    };
    con.setUrl(URL);
    con.setPost(false);
    con.addArgument("zoneid", getZoneId());
    con.addArgument("ua", Display.getInstance().getProperty("User-Agent", ""));
    con.addArgument("app", "1");
    con.addArgument("aid", Display.getInstance().getProperty("androidId", ""));
    con.addArgument("uuid", Display.getInstance().getProperty("uuid", ""));
    con.addArgument("im", Display.getInstance().getProperty("imei", ""));
    con.addArgument("sw", "" + Display.getInstance().getDisplayWidth());
    con.addArgument("sh", "" + Display.getInstance().getDisplayHeight());
    con.addArgument("mn", Display.getInstance().getProperty("AppName", ""));
    con.addArgument("vs3", "1");
    con.addArgument("partnerid", "1");
    con.addArgument("zc", "" + category);
    if (countryCode != null) {
        con.addArgument("cc", countryCode);
    }
    if (networkCode != null) {
        con.addArgument("nc", networkCode);
    }
    if (locale != null) {
        con.addArgument("lc", locale);
    }
    return con;
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) InputStreamReader(java.io.InputStreamReader) Hashtable(java.util.Hashtable) InputStream(java.io.InputStream) JSONParser(com.codename1.io.JSONParser) Vector(java.util.Vector) IOException(java.io.IOException)

Example 2 with JSONParser

use of com.codename1.io.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"), null));
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                } else {
                                    setAccessToken(new AccessToken(null, null));
                                    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(null, null));
                        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 3 with JSONParser

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

the class SignIn method showGoogleUser.

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();
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) InputStreamReader(java.io.InputStreamReader) InfiniteProgress(com.codename1.components.InfiniteProgress) ByteArrayInputStream(java.io.ByteArrayInputStream) Form(com.codename1.ui.Form) Dialog(com.codename1.ui.Dialog) JSONParser(com.codename1.io.JSONParser) IOException(java.io.IOException) Map(java.util.Map)

Example 4 with JSONParser

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

the class SignIn method showFacebookUser.

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();
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) InputStreamReader(java.io.InputStreamReader) InfiniteProgress(com.codename1.components.InfiniteProgress) ByteArrayInputStream(java.io.ByteArrayInputStream) Form(com.codename1.ui.Form) Dialog(com.codename1.ui.Dialog) JSONParser(com.codename1.io.JSONParser) IOException(java.io.IOException) Map(java.util.Map)

Example 5 with JSONParser

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

the class TwitterRESTService method readResponse.

/**
 * {@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));
}
Also used : InputStreamReader(java.io.InputStreamReader) NetworkEvent(com.codename1.io.NetworkEvent) JSONParser(com.codename1.io.JSONParser)

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