Search in sources :

Example 41 with Result

use of com.codename1.rad.processing.Result 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 42 with Result

use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.

the class CodenameOneActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AndroidImplementation.setActivity(this);
    AndroidNativeUtil.onCreate(savedInstanceState);
    if (android.os.Build.VERSION.SDK_INT >= 11) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        getActionBar().hide();
    }
    try {
        if (isBillingEnabled()) {
            String k = getBase64EncodedPublicKey();
            if (k.length() == 0) {
                Log.e("Codename One", "android.licenseKey base64 is not configured");
            }
            mHelper = new IabHelper(this, getBase64EncodedPublicKey());
            mHelper.enableDebugLogging(true);
            mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {

                public void onIabSetupFinished(IabResult result) {
                    if (!result.isSuccess()) {
                        // Oh noes, there was a problem.
                        Log.e("Codename One", "Problem setting up in-app billing: " + result);
                        return;
                    }
                    // Have we been disposed of in the meantime? If so, quit.
                    if (mHelper == null) {
                        return;
                    }
                    // IAB is fully set up. Now, let's get an inventory of stuff we own.
                    mHelper.queryInventoryAsync(mGotInventoryListener);
                }
            });
        }
    } catch (Throwable t) {
        // might happen if billing permissions are missing
        System.out.print("This exception is totally valid and here only for debugging purposes");
        t.printStackTrace();
    }
}
Also used : IabResult(com.codename1.payments.v3.IabResult) IabHelper(com.codename1.payments.v3.IabHelper)

Example 43 with Result

use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.

the class SQLMap method select.

/**
 * Fetches the components from the database matching the given cmp description, the fields that aren't
 * null within the cmp will match the where clause
 * @param cmp the component to match
 * @param orderBy the column to order by, can be null to ignore order
 * @param ascending true to indicate ascending order
 * @param maxElements the maximum number of elements returned can be 0 or lower to ignore
 * @param page  the page within the query to match the max elements value
 * @return the result of the query
 */
public java.util.List<PropertyBusinessObject> select(PropertyBusinessObject cmp, Property orderBy, boolean ascending, int maxElements, int page) throws IOException, InstantiationException {
    String tableName = getTableName(cmp);
    StringBuilder createStatement = new StringBuilder("SELECT * FROM ");
    createStatement.append(tableName);
    ArrayList<Object> params = new ArrayList<Object>();
    createStatement.append(" WHERE ");
    boolean found = false;
    for (PropertyBase p : cmp.getPropertyIndex()) {
        if (p instanceof Property) {
            if (((Property) p).get() != null) {
                if (found) {
                    createStatement.append(" AND ");
                }
                found = true;
                params.add(((Property) p).get());
                createStatement.append(getColumnName(p));
                createStatement.append(" = ?");
            }
        }
    }
    // all properties are null undo the where append
    if (!found) {
        createStatement = new StringBuilder("SELECT * FROM ");
        createStatement.append(tableName);
    }
    if (orderBy != null) {
        createStatement.append(" ORDER BY ");
        createStatement.append(getColumnName(orderBy));
        if (!ascending) {
            createStatement.append(" DESC");
        }
    }
    if (maxElements > 0) {
        createStatement.append(" LIMIT ");
        createStatement.append(maxElements);
        if (page > 0) {
            createStatement.append(" OFFSET ");
            createStatement.append(page * maxElements);
        }
    }
    Cursor c = null;
    try {
        ArrayList<PropertyBusinessObject> response = new ArrayList<PropertyBusinessObject>();
        c = executeQuery(createStatement.toString(), params.toArray());
        while (c.next()) {
            PropertyBusinessObject pb = (PropertyBusinessObject) cmp.getClass().newInstance();
            for (PropertyBase p : pb.getPropertyIndex()) {
                Row currentRow = c.getRow();
                SqlType t = getSqlType(p);
                if (t == SqlType.SQL_EXCLUDE) {
                    continue;
                }
                Object value = t.getValue(currentRow, c.getColumnIndex(getColumnName(p)), p);
                if (p instanceof Property) {
                    ((Property) p).set(value);
                }
            }
            response.add(pb);
        }
        c.close();
        return response;
    } catch (Throwable t) {
        Log.e(t);
        if (c != null) {
            c.close();
        }
        if (t instanceof IOException) {
            throw ((IOException) t);
        } else {
            throw new IOException(t.toString());
        }
    }
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) Cursor(com.codename1.db.Cursor) Row(com.codename1.db.Row)

Example 44 with Result

use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.

the class SQLMap method selectImpl.

/**
 * Fetches the components from the database matching the given cmp description, the fields that aren't
 * null within the cmp will match the where clause
 * @param not indicates if the query should be a "not" query
 * @param cmp the component to match
 * @param orderBy the column to order by, can be null to ignore order
 * @param ascending true to indicate ascending order
 * @param maxElements the maximum number of elements returned can be 0 or lower to ignore
 * @param page  the page within the query to match the max elements value
 * @return the result of the query
 */
private java.util.List<PropertyBusinessObject> selectImpl(boolean not, PropertyBusinessObject cmp, Property orderBy, boolean ascending, int maxElements, int page) throws IOException, InstantiationException {
    String tableName = getTableName(cmp);
    StringBuilder createStatement = new StringBuilder("SELECT * FROM ");
    createStatement.append(tableName);
    ArrayList<Object> params = new ArrayList<Object>();
    createStatement.append(" WHERE ");
    boolean found = false;
    for (PropertyBase p : cmp.getPropertyIndex()) {
        if (p instanceof Property) {
            if (((Property) p).get() != null) {
                if (found) {
                    createStatement.append(" AND ");
                }
                found = true;
                params.add(((Property) p).get());
                createStatement.append(getColumnName(p));
                if (not) {
                    createStatement.append(" <> ?");
                } else {
                    createStatement.append(" = ?");
                }
            }
        }
    }
    // all properties are null undo the where append
    if (!found) {
        createStatement = new StringBuilder("SELECT * FROM ");
        createStatement.append(tableName);
    }
    if (orderBy != null) {
        createStatement.append(" ORDER BY ");
        createStatement.append(getColumnName(orderBy));
        if (!ascending) {
            createStatement.append(" DESC");
        }
    }
    if (maxElements > 0) {
        createStatement.append(" LIMIT ");
        createStatement.append(maxElements);
        if (page > 0) {
            createStatement.append(" OFFSET ");
            createStatement.append(page * maxElements);
        }
    }
    Cursor c = null;
    try {
        ArrayList<PropertyBusinessObject> response = new ArrayList<PropertyBusinessObject>();
        c = executeQuery(createStatement.toString(), params.toArray());
        while (c.next()) {
            PropertyBusinessObject pb = (PropertyBusinessObject) cmp.getClass().newInstance();
            for (PropertyBase p : pb.getPropertyIndex()) {
                Row currentRow = c.getRow();
                SqlType t = getSqlType(p);
                if (t == SqlType.SQL_EXCLUDE) {
                    continue;
                }
                Object value = t.getValue(currentRow, c.getColumnIndex(getColumnName(p)), p);
                if (p instanceof Property) {
                    ((Property) p).set(value);
                }
            }
            response.add(pb);
        }
        c.close();
        return response;
    } catch (Throwable t) {
        Log.e(t);
        if (c != null) {
            c.close();
        }
        if (t instanceof IOException) {
            throw ((IOException) t);
        } else {
            throw new IOException(t.toString());
        }
    }
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) Cursor(com.codename1.db.Cursor) Row(com.codename1.db.Row)

Example 45 with Result

use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.

the class BrowserComponent method fireBrowserNavigationCallbacks.

/**
 * Fires all of the registered browser navigation callbacks against the provided URL.
 * @param url The URL to fire the navigation callbacks against.
 * @return True if all of the callbacks say that they can browse.  False otherwise.
 */
public boolean fireBrowserNavigationCallbacks(String url) {
    boolean shouldNavigate = true;
    if (browserNavigationCallback != null && !browserNavigationCallback.shouldNavigate(url)) {
        shouldNavigate = false;
    }
    if (browserNavigationCallbacks != null) {
        for (BrowserNavigationCallback cb : browserNavigationCallbacks) {
            if (!cb.shouldNavigate(url)) {
                shouldNavigate = false;
            }
        }
    }
    if (!url.startsWith("javascript:") && url.indexOf(RETURN_URL_PREFIX) != -1) {
        // System.out.println("Received browser navigation callback "+url);
        String result = decodeURL(url.substring(url.indexOf(RETURN_URL_PREFIX) + RETURN_URL_PREFIX.length()), "UTF-8");
        // System.out.println("After decode "+result);
        Result structResult = Result.fromContent(result, Result.JSON);
        int callbackId = structResult.getAsInteger("callbackId");
        final String value = structResult.getAsString("value");
        final String type = structResult.getAsString("type");
        final String errorMessage = structResult.getAsString("errorMessage");
        final SuccessCallback<JSRef> callback = popReturnValueCallback(callbackId);
        if (jsCallbacks != null && jsCallbacks.contains(callback)) {
            // If this is a registered callback, then we treat it more like
            // an event listener, and we retain it for future callbacks.
            returnValueCallbacks.put(callbackId, callback);
        }
        if (callback != null) {
            if (errorMessage != null) {
                if (fireCallbacksOnEdt) {
                    Display.getInstance().callSerially(new Runnable() {

                        public void run() {
                            if (callback instanceof Callback) {
                                ((Callback) callback).onError(this, new RuntimeException(errorMessage), 0, errorMessage);
                            }
                        }
                    });
                } else {
                    if (callback instanceof Callback) {
                        ((Callback) callback).onError(this, new RuntimeException(errorMessage), 0, errorMessage);
                    }
                }
            } else {
                if (fireCallbacksOnEdt) {
                    Display.getInstance().callSerially(new Runnable() {

                        public void run() {
                            callback.onSucess(new JSRef(value, type));
                        }
                    });
                } else {
                    callback.onSucess(new JSRef(value, type));
                }
            }
        } else {
            Log.e(new RuntimeException("Received return value from javascript, but no callback could be found for that ID"));
        }
        shouldNavigate = false;
    }
    return shouldNavigate;
}
Also used : BrowserNavigationCallback(com.codename1.ui.events.BrowserNavigationCallback) Callback(com.codename1.util.Callback) SuccessCallback(com.codename1.util.SuccessCallback) BrowserNavigationCallback(com.codename1.ui.events.BrowserNavigationCallback) Result(com.codename1.processing.Result)

Aggregations

IOException (java.io.IOException)19 ArrayList (java.util.ArrayList)14 Form (com.codename1.ui.Form)12 Button (com.codename1.ui.Button)11 Map (java.util.Map)9 Date (java.util.Date)8 HashMap (java.util.HashMap)8 Label (com.codename1.ui.Label)7 BorderLayout (com.codename1.ui.layouts.BorderLayout)7 List (java.util.List)7 Container (com.codename1.ui.Container)6 ByteArrayInputStream (java.io.ByteArrayInputStream)6 OutputStream (java.io.OutputStream)6 JSONParser (com.codename1.io.JSONParser)5 Result (com.codename1.rad.processing.Result)5 ActionEvent (com.codename1.ui.events.ActionEvent)5 File (java.io.File)5 Cursor (com.codename1.db.Cursor)4 ConnectionRequest (com.codename1.io.ConnectionRequest)4 Entity (com.codename1.rad.models.Entity)4