Search in sources :

Example 6 with ConnectionRequest

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

the class RequestBuilder method getAsBytesAsync.

/**
 * Executes the request asynchronously and writes the response to the provided
 * Callback
 * @param callback writes the response to this callback
 */
public void getAsBytesAsync(final Callback<Response<byte[]>> callback) {
    ConnectionRequest request = createRequest(false);
    request.addResponseListener(new ActionListener<NetworkEvent>() {

        @Override
        public void actionPerformed(NetworkEvent evt) {
            Response res = null;
            res = new Response(evt.getResponseCode(), evt.getConnectionRequest().getResponseData(), evt.getMessage());
            callback.onSucess(res);
        }
    });
    CN.addToQueue(request);
}
Also used : GZConnectionRequest(com.codename1.io.gzip.GZConnectionRequest) ConnectionRequest(com.codename1.io.ConnectionRequest) NetworkEvent(com.codename1.io.NetworkEvent)

Example 7 with ConnectionRequest

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

the class RequestBuilder method getAsJsonMap.

/**
 * 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
 */
public ConnectionRequest getAsJsonMap(final SuccessCallback<Response<Map>> callback, final FailureCallback<? extends Object> onError) {
    ConnectionRequest request = createRequest(true);
    request.addResponseListener(new ActionListener<NetworkEvent>() {

        @Override
        public void actionPerformed(NetworkEvent evt) {
            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);
    CN.addToQueue(request);
    return request;
}
Also used : GZConnectionRequest(com.codename1.io.gzip.GZConnectionRequest) ConnectionRequest(com.codename1.io.ConnectionRequest) NetworkEvent(com.codename1.io.NetworkEvent) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with ConnectionRequest

use of com.codename1.io.ConnectionRequest 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 9 with ConnectionRequest

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

the class AnalyticsService method visitPage.

/**
 * Subclasses should override this method to track page visits
 * @param page the page visited
 * @param referer the page from which the user came
 */
protected void visitPage(String page, String referer) {
    if (appsMode) {
        // https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#apptracking
        ConnectionRequest req = GetGARequest();
        req.addArgument("t", "appview");
        req.addArgument("an", Display.getInstance().getProperty("AppName", "Codename One App"));
        String version = Display.getInstance().getProperty("AppVersion", "1.0");
        req.addArgument("av", version);
        req.addArgument("cd", page);
        NetworkManager.getInstance().addToQueue(req);
    } else {
        String url = Display.getInstance().getProperty("cloudServerURL", "https://codename-one.appspot.com/") + "anal";
        ConnectionRequest r = new ConnectionRequest();
        r.setUrl(url);
        r.setPost(false);
        r.setFailSilently(failSilently);
        r.addArgument("guid", "ON");
        r.addArgument("utmac", instance.agent);
        r.addArgument("utmn", Integer.toString((int) (System.currentTimeMillis() % 0x7fffffff)));
        if (page == null || page.length() == 0) {
            page = "-";
        }
        r.addArgument("utmp", page);
        if (referer == null || referer.length() == 0) {
            referer = "-";
        }
        r.addArgument("utmr", referer);
        r.addArgument("d", instance.domain);
        r.setPriority(ConnectionRequest.PRIORITY_LOW);
        NetworkManager.getInstance().addToQueue(r);
    }
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest)

Example 10 with ConnectionRequest

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

the class AnalyticsService method GetGARequest.

private static ConnectionRequest GetGARequest() {
    ConnectionRequest req = new ConnectionRequest();
    req.setUrl("https://www.google-analytics.com/collect");
    req.setPost(true);
    req.setFailSilently(true);
    req.addArgument("v", "1");
    req.addArgument("tid", instance.agent);
    long uniqueId = Log.getUniqueDeviceId();
    req.addArgument("cid", String.valueOf(uniqueId));
    return req;
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest)

Aggregations

ConnectionRequest (com.codename1.io.ConnectionRequest)41 IOException (java.io.IOException)11 GZConnectionRequest (com.codename1.io.gzip.GZConnectionRequest)7 InputStream (java.io.InputStream)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 Map (java.util.Map)6 JSONParser (com.codename1.io.JSONParser)5 ActionEvent (com.codename1.ui.events.ActionEvent)5 InputStreamReader (java.io.InputStreamReader)5 InfiniteProgress (com.codename1.components.InfiniteProgress)4 NetworkEvent (com.codename1.io.NetworkEvent)4 Dialog (com.codename1.ui.Dialog)4 Form (com.codename1.ui.Form)4 ActionListener (com.codename1.ui.events.ActionListener)3 DataInputStream (java.io.DataInputStream)3 Hashtable (java.util.Hashtable)3 Component (com.codename1.ui.Component)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 HashMap (java.util.HashMap)2 Vector (java.util.Vector)2