Example usage for android.util Pair Pair

List of usage examples for android.util Pair Pair

Introduction

In this page you can find the example usage for android.util Pair Pair.

Prototype

public Pair(F first, S second) 

Source Link

Document

Constructor for a Pair.

Usage

From source file:com.owncloud.android.services.OperationsService.java

/**
 * Entry point to add a new operation to the queue of operations.
 *
 * New operations are added calling to startService(), resulting in a call to this method.
 * This ensures the service will keep on working although the caller activity goes away.
 *//*from  www.ja  v a  2  s .  co m*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log_OC.d(TAG, "Starting command with id " + startId);

    // WIP: for the moment, only SYNC_FOLDER is expected here;
    // the rest of the operations are requested through the Binder
    if (ACTION_SYNC_FOLDER.equals(intent.getAction())) {

        if (!intent.hasExtra(EXTRA_ACCOUNT) || !intent.hasExtra(EXTRA_REMOTE_PATH)) {
            Log_OC.e(TAG, "Not enough information provided in intent");
            return START_NOT_STICKY;
        }
        Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
        String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);

        Pair<Account, String> itemSyncKey = new Pair<>(account, remotePath);

        Pair<Target, RemoteOperation> itemToQueue = newOperation(intent);
        if (itemToQueue != null) {
            mSyncFolderHandler.add(account, remotePath, (SynchronizeFolderOperation) itemToQueue.second);
            Message msg = mSyncFolderHandler.obtainMessage();
            msg.arg1 = startId;
            msg.obj = itemSyncKey;
            mSyncFolderHandler.sendMessage(msg);
        }

    } else {
        Message msg = mOperationsHandler.obtainMessage();
        msg.arg1 = startId;
        mOperationsHandler.sendMessage(msg);
    }

    return START_NOT_STICKY;
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.MainActivity.java

@SuppressWarnings("unchecked")
private void refreshTestGroupsAndLog() {
    mLog = new StringBuilder();

    Thread thread = new Thread() {

        @Override//www .j  a  va  2s.co  m
        public void run() {

            final boolean isNetBackend = IsNetBackend();

            runOnUiThread(new Runnable() {

                @Override
                public void run() {

                    ArrayAdapter<TestGroup> adapter = (ArrayAdapter<TestGroup>) mTestGroupSpinner.getAdapter();
                    adapter.clear();
                    adapter.add(new RoundTripTests());
                    adapter.add(new QueryTests());
                    adapter.add(new UpdateDeleteTests());
                    //adapter.add(new ClientSDKLoginTests());
                    adapter.add(new LoginTests(isNetBackend));
                    adapter.add(new MiscTests());
                    // adapter.add(new PushTests());
                    adapter.add(new CustomApiTests());
                    adapter.add(new SystemPropertiesTests(isNetBackend));
                    adapter.add(new EnhancedPushTests(isNetBackend));
                    adapter.add(new OfflineTests());

                    ArrayList<Pair<TestCase, String>> allTests = new ArrayList<Pair<TestCase, String>>();
                    ArrayList<Pair<TestCase, String>> allUnattendedTests = new ArrayList<Pair<TestCase, String>>();
                    for (int i = 0; i < adapter.getCount(); i++) {
                        TestGroup group = adapter.getItem(i);
                        allTests.add(new Pair<TestCase, String>(
                                Util.createSeparatorTest("Start of group: " + group.getName()), "Separator"));
                        allUnattendedTests.add(new Pair<TestCase, String>(
                                Util.createSeparatorTest("Start of group: " + group.getName()), "Separator"));

                        List<TestCase> testsForGroup = group.getTestCases();
                        for (TestCase test : testsForGroup) {
                            allTests.add(new Pair<TestCase, String>(test, group.getName()));
                            if (test.canRunUnattended()) {
                                allUnattendedTests.add(new Pair<TestCase, String>(test, group.getName()));
                            }
                        }
                        allTests.add(new Pair<TestCase, String>(
                                Util.createSeparatorTest("----" + group.getName() + "----"), "Separator"));
                        allUnattendedTests.add(new Pair<TestCase, String>(
                                Util.createSeparatorTest("----" + group.getName() + "----"), "Separator"));
                    }

                    int unattendedTestsIndex = adapter.getCount();

                    adapter.add(
                            new CompositeTestGroup(TestGroup.AllUnattendedTestsGroupName, allUnattendedTests));
                    adapter.add(new CompositeTestGroup(TestGroup.AllTestsGroupName, allTests));

                    if (shouldRunUnattended()) {
                        mTestGroupSpinner.setSelection(unattendedTestsIndex);
                        selectTestGroup(unattendedTestsIndex);
                        changeCheckAllTests(true);
                        runTests();
                    } else {
                        mTestGroupSpinner.setSelection(0);
                        selectTestGroup(0);
                    }
                }
            });
        }
    };

    thread.start();
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

@Override
public Pair<JSONObject, byte[]> handleUnprocessed(Context context, JSONObject msg) {
    byte[] bytes = FastBase64.decode(msg.optString(DATA));
    msg.remove(DATA);/*from w w  w.ja  va 2  s  . c om*/
    return new Pair<JSONObject, byte[]>(msg, bytes);
}

From source file:io.github.protino.codewatch.ui.ProfileActivity.java

private void bindViews() {
    Glide.with(this).load(profileItem.getPhotoUrl()).asBitmap()
            .placeholder(R.drawable.ic_account_circle_white_24dp).into(new BitmapImageViewTarget(avatar) {
                @Override//from ww w.j  a v a2  s  .co m
                protected void setResource(Bitmap resource) {
                    RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getResources(),
                            resource);
                    drawable.setCircular(true);
                    avatar.setImageDrawable(drawable);
                }
            });

    userName.setText(profileItem.getName());
    collapsingToolbarLayout.setTitle(profileItem.getName());

    rank.setText(String.valueOf(profileItem.getRank()));

    website.setText(profileItem.getWebsite());
    Linkify.addLinks(website, Linkify.WEB_URLS);
    removeViewIfNoData(website);

    email.setText(profileItem.getEmail());
    Linkify.addLinks(email, Linkify.EMAIL_ADDRESSES);
    removeViewIfNoData(email);

    location.setText(profileItem.getLocation());
    removeViewIfNoData(location);

    dailyAverage.setText(getString(R.string.daily_average_format,
            FormatUtils.getFormattedTime(this, profileItem.getDailyAverage())));

    JSONObject languageMap;
    try {
        languageMap = new JSONObject(profileItem.getLanguageStats());
        Iterator<?> keys = languageMap.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            languageList.add(new Pair<>(key, languageMap.getInt(key)));
        }
    } catch (JSONException e) {
        Timber.e(e);
    }
    languageAdapter.swapData(languageList);
}

From source file:piuk.blockchain.android.ui.SendCoinsFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    final SendCoinsActivity activity = (SendCoinsActivity) getActivity();

    final View view = inflater.inflate(R.layout.send_coins_fragment, container);

    final MyRemoteWallet wallet = application.getRemoteWallet();

    if (wallet == null)
        return view;

    BigInteger available = null;/*  w  w  w .  j a v  a2s  .  c om*/

    if (application.isInP2PFallbackMode()) {
        try {
            available = application.bitcoinjWallet.getBalance(BalanceType.ESTIMATED);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        available = wallet.getBalance();
    }

    receivingAddressView = (AutoCompleteTextView) view.findViewById(R.id.send_coins_receiving_address);
    feeContainerView = view.findViewById(R.id.send_coins_fee_container);
    sendCoinsFromContainer = view.findViewById(R.id.send_coins_from_container);
    sendCoinsFromSpinner = (Spinner) view.findViewById(R.id.send_coins_from_spinner);
    feeAmountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_fee);
    sendTypeDescriptionContainer = view.findViewById(R.id.send_type_description_container);
    sendTypeDescription = (TextView) view.findViewById(R.id.send_type_description);
    sendTypeDescriptionIcon = (ImageView) view.findViewById(R.id.send_type_description_icon);

    {
        //Construct the from drop down list
        String[] activeAddresses = wallet.getActiveAddresses();
        Map<String, String> labelMap = wallet.getLabelMap();

        List<Pair<String, String>> pairs = new ArrayList<Pair<String, String>>();
        for (String address : activeAddresses) {

            String label = labelMap.get(address);

            if (label == null || label.length() == 0) {
                label = "No Label";
            }

            BigInteger balance = wallet.getBalance(address);

            if (balance.compareTo(BigInteger.ZERO) > 0) {
                label += " (" + WalletUtils.formatValue(balance) + " BTC)";

                pairs.add(new Pair<String, String>(address, label));
            }
        }

        pairs.add(0, new Pair<String, String>("Any Address", "Any Address"));

        sendCoinsFromSpinner.setAdapter(new SpinAdapter(activity, android.R.layout.simple_list_item_1, pairs));
    }

    feeAmountView.setAmount(wallet.getBaseFee());

    StringPairAdapter adapter = new StringPairAdapter(this.getLabelList());

    receivingAddressView.setAdapter(adapter);
    receivingAddressView.addTextChangedListener(textWatcher);

    receivingAddressView.setOnTouchListener(new RightDrawableOnTouchListener(receivingAddressView) {
        @Override
        public boolean onDrawableTouch(final MotionEvent event) {

            activity.showQRReader(activity.new QrCodeDelagate() {
                @Override
                public void didReadQRCode(String data) {
                    activity.handleScanURI(data);
                }
            });

            return true;
        }
    });

    receivingAddressErrorView = view.findViewById(R.id.send_coins_receiving_address_error);

    availableViewContainer = view.findViewById(R.id.send_coins_available_container);
    availableView = (CurrencyAmountView) view.findViewById(R.id.send_coins_available);
    availableView.setAmount(available);

    amountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_amount);
    amountView.setListener(listener);
    amountView.setContextButton(R.drawable.ic_input_calculator, new OnClickListener() {
        public void onClick(final View v) {
            final FragmentTransaction ft = getFragmentManager().beginTransaction();
            final Fragment prev = getFragmentManager().findFragmentByTag(AmountCalculatorFragment.FRAGMENT_TAG);
            if (prev != null)
                ft.remove(prev);
            ft.addToBackStack(null);
            final DialogFragment newFragment = new AmountCalculatorFragment(
                    new AmountCalculatorFragment.Listener() {
                        public void use(final BigInteger amount) {
                            amountView.setAmount(amount);
                        }
                    });
            newFragment.show(ft, AmountCalculatorFragment.FRAGMENT_TAG);
        }
    });

    viewGo = (Button) view.findViewById(R.id.send_coins_go);
    viewGo.setOnClickListener(new OnClickListener() {
        final SendProgress progress = new SendProgress() {
            public void onSend(final Transaction tx, final String message) {
                handler.post(new Runnable() {
                    public void run() {
                        state = State.SENT;

                        activity.longToast(message);

                        Intent intent = activity.getIntent();
                        intent.putExtra("tx", tx.getHash());
                        activity.setResult(Activity.RESULT_OK, intent);

                        activity.finish();

                        updateView();
                    }
                });

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                application.doMultiAddr(true);
            }

            public void onError(final String message) {
                handler.post(new Runnable() {
                    public void run() {

                        System.out.println("On Error");

                        if (message != null)
                            activity.longToast(message);

                        state = State.INPUT;

                        updateView();
                    }
                });
            }

            public void onProgress(final String message) {
                handler.post(new Runnable() {
                    public void run() {
                        state = State.SENDING;

                        updateView();
                    }
                });
            }

            public boolean onReady(Transaction tx, BigInteger fee, FeePolicy feePolicy, long priority) {

                boolean containsOutputLessThanThreshold = false;
                for (TransactionOutput output : tx.getOutputs()) {
                    if (output.getValue().compareTo(Constants.FEE_THRESHOLD_MIN) < 0) {
                        containsOutputLessThanThreshold = true;
                        break;
                    }
                }

                if (feePolicy != FeePolicy.FeeNever && fee.compareTo(BigInteger.ZERO) == 0) {
                    if (tx.bitcoinSerialize().length > 1024 || containsOutputLessThanThreshold) {
                        makeTransaction(FeePolicy.FeeForce);
                        return false;
                    } else if (priority < 97600000L) {
                        handler.post(new Runnable() {
                            public void run() {
                                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                                builder.setMessage(R.string.ask_for_fee).setCancelable(false);

                                AlertDialog alert = builder.create();

                                alert.setButton(AlertDialog.BUTTON_NEUTRAL,
                                        getString(R.string.continue_without_fee),
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                makeTransaction(FeePolicy.FeeNever);
                                                dialog.dismiss();
                                            }
                                        });

                                alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.add_fee),
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                makeTransaction(FeePolicy.FeeForce);

                                                dialog.dismiss();
                                            }
                                        });

                                alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel),
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                dialog.dismiss();
                                            }
                                        });

                                alert.show();
                            }
                        });

                        handler.post(new Runnable() {
                            public void run() {
                                state = State.INPUT;
                                updateView();
                            }
                        });
                        return false;
                    }
                }

                return true;
            }

            public ECKey onPrivateKeyMissing(final String address) {

                handler.post(new Runnable() {
                    public void run() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setMessage(getString(R.string.ask_for_private_key, address))
                                .setCancelable(false)
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        activity.scanPrivateKeyAddress = address;

                                        activity.showQRReader(activity.new QrCodeDelagate() {
                                            @Override
                                            public void didReadQRCode(String data) throws Exception {
                                                activity.handleScanPrivateKey(data);
                                            }
                                        });
                                    }
                                })
                                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {

                                        synchronized (activity.temporaryPrivateKeys) {
                                            activity.temporaryPrivateKeys.notify();
                                        }

                                        dialog.cancel();
                                    }
                                });

                        AlertDialog alert = builder.create();

                        alert.show();
                    }
                });

                try {
                    synchronized (activity.temporaryPrivateKeys) {
                        activity.temporaryPrivateKeys.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                return activity.temporaryPrivateKeys.get(address);
            }
        };

        public void send(Address receivingAddress, BigInteger fee, FeePolicy feePolicy) {

            if (application.getRemoteWallet() == null)
                return;

            if (sendType != null && !sendType.equals(SendCoinsActivity.SendTypeQuickSend)
                    && application.isInP2PFallbackMode()) {
                activity.longToast(R.string.only_quick_supported);
                return;
            }

            String[] from;
            if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeCustomSend)) {
                Pair<String, String> selected = (Pair<String, String>) sendCoinsFromSpinner.getSelectedItem();

                if (selected.first.equals("Any Address")) {
                    from = wallet.getActiveAddresses();
                } else {
                    from = new String[] { selected.first.toString() };
                }
            } else {
                from = wallet.getActiveAddresses();
            }

            final BigInteger amount;

            if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeSharedSend)) {
                BigDecimal amountDecimal = BigDecimal.valueOf(amountView.getAmount().doubleValue());

                //Add the fee
                amount = amountDecimal.add(amountDecimal.divide(BigDecimal.valueOf(100))
                        .multiply(BigDecimal.valueOf(wallet.getSharedFee()))).toBigInteger();
            } else {
                amount = amountView.getAmount();
            }

            final WalletApplication application = (WalletApplication) getActivity().getApplication();

            if (application.isInP2PFallbackMode()) {

                final long blockchainLag = System.currentTimeMillis()
                        - service.blockChain.getChainHead().getHeader().getTime().getTime();

                final boolean blockchainUptodate = blockchainLag < Constants.BLOCKCHAIN_UPTODATE_THRESHOLD_MS;

                if (!blockchainUptodate) {
                    activity.longToast(R.string.blockchain_not_upto_date);
                    return;
                }

                // create spend
                final SendRequest sendRequest = SendRequest.to(receivingAddress, amountView.getAmount());

                sendRequest.fee = fee;

                new Thread(new Runnable() {
                    public void run() {
                        final Transaction transaction = application.bitcoinjWallet
                                .sendCoinsOffline(sendRequest);

                        handler.post(new Runnable() {
                            public void run() {
                                if (transaction != null) {
                                    state = State.SENDING;

                                    updateView();

                                    service.broadcastTransaction(transaction);

                                    state = State.SENT;

                                    activity.longToast(R.string.wallet_transactions_fragment_tab_sent);

                                    Intent intent = activity.getIntent();
                                    intent.putExtra("tx", transaction.getHash());
                                    activity.setResult(Activity.RESULT_OK, intent);

                                    activity.finish();

                                    updateView();

                                    EventListeners.invokeOnTransactionsChanged();
                                } else {
                                    state = State.INPUT;

                                    updateView();

                                    activity.longToast(R.string.send_coins_error_msg);
                                }
                            }
                        });
                    }
                }).start();
            } else {
                application.getRemoteWallet().sendCoinsAsync(from, receivingAddress.toString(), amount,
                        feePolicy, fee, progress);
            }
        }

        public void makeTransaction(FeePolicy feePolicy) {

            if (application.getRemoteWallet() == null)
                return;

            try {
                MyRemoteWallet wallet = application.getRemoteWallet();

                BigInteger baseFee = wallet.getBaseFee();

                BigInteger fee = null;

                if (feePolicy == FeePolicy.FeeForce) {
                    fee = baseFee;
                } else if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeCustomSend)) {
                    feePolicy = FeePolicy.FeeOnlyIfNeeded;
                    fee = feeAmountView.getAmount();
                } else {
                    fee = (wallet.getFeePolicy() == 1) ? baseFee : BigInteger.ZERO;
                }

                final BigInteger finalFee = fee;
                final FeePolicy finalFeePolicy = feePolicy;

                if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeSharedSend)) {

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                final String addressString = MyRemoteWallet
                                        .generateSharedAddress(getToAddress());

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            send(new Address(Constants.NETWORK_PARAMETERS, addressString),
                                                    finalFee, finalFeePolicy);
                                        } catch (Exception e) {
                                            e.printStackTrace();

                                            Toast.makeText(application, e.getLocalizedMessage(),
                                                    Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                            } catch (final Exception e) {
                                handler.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        e.printStackTrace();

                                        Toast.makeText(application, e.getLocalizedMessage(), Toast.LENGTH_LONG)
                                                .show();
                                    }
                                });
                            }
                        }

                    }).start();

                } else {
                    String addressString = getToAddress();

                    Address receivingAddress = new Address(Constants.NETWORK_PARAMETERS, addressString);

                    send(receivingAddress, fee, feePolicy);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void onClick(final View v) {
            if (application.getRemoteWallet() == null)
                return;

            MyRemoteWallet remoteWallet = application.getRemoteWallet();

            if (remoteWallet.isDoubleEncrypted() == false) {
                makeTransaction(FeePolicy.FeeOnlyIfNeeded);
            } else {
                if (remoteWallet.temporySecondPassword == null) {
                    RequestPasswordDialog.show(getFragmentManager(), new SuccessCallback() {

                        public void onSuccess() {
                            makeTransaction(FeePolicy.FeeOnlyIfNeeded);
                        }

                        public void onFail() {
                            Toast.makeText(application, R.string.send_no_password_error, Toast.LENGTH_LONG)
                                    .show();
                        }
                    }, RequestPasswordDialog.PasswordTypeSecond);
                } else {
                    makeTransaction(FeePolicy.FeeOnlyIfNeeded);
                }
            }
        }
    });

    viewCancel = (Button) view.findViewById(R.id.send_coins_cancel);
    viewCancel.setOnClickListener(new OnClickListener() {
        public void onClick(final View v) {
            activity.setResult(Activity.RESULT_CANCELED);

            activity.finish();
        }
    });

    activity.setOnChangedSendTypeListener(new OnChangedSendTypeListener() {
        @Override
        public void onChangedSendType(String type) {
            sendType = type;

            feeContainerView.setVisibility(View.GONE);
            sendCoinsFromContainer.setVisibility(View.GONE);
            availableViewContainer.setVisibility(View.VISIBLE);
            sendTypeDescriptionContainer.setVisibility(View.GONE);

            if (type.equals(SendCoinsActivity.SendTypeCustomSend)) {
                feeContainerView.setVisibility(View.VISIBLE);
                sendCoinsFromContainer.setVisibility(View.VISIBLE);
                availableViewContainer.setVisibility(View.GONE);
            } else if (type.equals(SendCoinsActivity.SendTypeSharedSend)) {
                sendTypeDescriptionContainer.setVisibility(View.VISIBLE);
                sendTypeDescription
                        .setText(getString(R.string.shared_send_description, wallet.getSharedFee() + "%"));
                sendTypeDescriptionIcon.setImageResource(R.drawable.ic_icon_shared);
            }
        }
    });

    updateView();

    return view;
}

From source file:com.jefftharris.passwdsafe.sync.gdrive.GDriveProvider.java

/**
 * Retrieve a authorized service object to send requests to the Google
 * Drive API. On failure to retrieve an access token, a notification is
 * sent to the user requesting that authorization be granted for the
 * {@code https://www.googleapis.com/auth/drive} scope.
 *
 * @return An authorized service object and its auth token.
 *//*  w ww  .j av a2s  .co m*/
private static Pair<Drive, String> getDriveService(Account acct, Context ctx) {
    Drive drive = null;
    String token = null;
    try {
        GoogleAccountCredential credential = getAcctCredential(ctx);
        credential.setBackOff(new ExponentialBackOff());
        credential.setSelectedAccountName(acct.name);

        token = GoogleAuthUtil.getTokenWithNotification(ctx, acct, credential.getScope(), null,
                PasswdSafeContract.AUTHORITY, null);

        Drive.Builder builder = new Drive.Builder(AndroidHttp.newCompatibleTransport(),
                JacksonFactory.getDefaultInstance(), credential);
        builder.setApplicationName(ctx.getString(R.string.app_name));
        drive = builder.build();
    } catch (UserRecoverableNotifiedException e) {
        // User notified
        PasswdSafeUtil.dbginfo(TAG, e, "User notified auth exception");
        try {
            GoogleAuthUtil.clearToken(ctx, null);
        } catch (Exception ioe) {
            Log.e(TAG, "getDriveService clear failure", e);
        }
    } catch (GoogleAuthException e) {
        // Unrecoverable
        Log.e(TAG, "Unrecoverable auth exception", e);
    } catch (IOException e) {
        // Transient
        PasswdSafeUtil.dbginfo(TAG, e, "Transient error");
    } catch (Exception e) {
        Log.e(TAG, "Token exception", e);
    }
    return new Pair<>(drive, token);
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceFeaturesTests.java

public void testTypedTableLookupWithParametersFeatureHeader() {
    testTableFeatureHeader(new TableTestOperation() {

        @Override//from ww  w.j  ava 2  s  .c  o  m
        public void executeOperation(MobileServiceTable<PersonTestObjectWithStringId> typedTable,
                MobileServiceJsonTable jsonTable) throws Exception {
            List<Pair<String, String>> queryParams = new ArrayList<Pair<String, String>>();
            queryParams.add(new Pair<String, String>("a", "b"));
            typedTable.lookUp("1", queryParams).get();
        }
    }, false, "QS,TT");
}

From source file:org.gluu.super_gluu.app.fragment.HomeFragment.java

private Pair<String, String> getTitleBasedOnMessage(int messageId) {

    switch (messageId) {
    case Constant.AUTH_SUCCESS:
        return new Pair<>(getString(R.string.success), getString(R.string.auth_result_success));
    case Constant.AUTH_FAILURE:
    case Constant.AUTHENTICATED_FAILED_OTHER:
        return new Pair<>(getString(R.string.failed), getString(R.string.deny_result_success));
    case Constant.ENROLLMENT_SUCCESS:
        return new Pair<>(getString(R.string.enroll_result_title), getString(messageId));
    case Constant.FIDO_U2F_INVALID:
        return new Pair<>(getString(R.string.fido_failure), getString(messageId));
    case Constant.CHALLENGE:
        return new Pair<>(getString(R.string.challenge), getString(messageId));
    case Constant.DECLINE_FAILED:
        return new Pair<>(getString(R.string.decline), getString(messageId));
    case Constant.DUPLICATE_ENROLLMENT:
        return new Pair<>(getString(messageId), getString(R.string.existing_key_message));
    default://  w  w  w  .j a v  a2s . c  om
        return new Pair<>(getString(R.string.generic_auth_result), getString(messageId));
    }
}

From source file:im.r_c.android.dbox.SQLBuilder.java

static Pair<String, String[]> query(TableInfo tableInfo, DBoxCondition condition, StringBuilder orderBuilder) {
    // Example:/* w w  w.jav a  2  s  .  co  m*/
    //
    // SELECT
    //
    // FROM Student
    //   LEFT JOIN _Student_Course_mapping
    //   LEFT JOIN _Student_Clazz_mapping
    // WHERE
    //   (
    //     _Student_Course_mapping._Student_courseList_id = Student.id      -| Corresponding to "Course" table, containing 2 fields
    //     OR                                                                | Use "OR" between each field
    //     _Student_Course_mapping._Student_favoriteCourses_id = Student.id -|
    //   )
    //   AND
    //   (
    //     _Student_Clazz_mapping._Student_clazz_id = Student.id            -| Corresponding to "Clazz" table, containing 1 field
    //   )
    //   AND (
    //     {Custom where clause}
    //   )
    // ORDER BY
    //   Student.name, Student.id,
    //   _Student_favoriteCourses_index, _Student_clazzList_index, _Student_courseList_index;

    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("SELECT * FROM ").append(tableInfo.mName);

    // Key: tableB (aka table of the elem class of a field
    // Value: where clause builder
    Map<String, StringBuilder> mappingWhereBuilderMap = new ArrayMap<>();

    List<String> indexColumnList = new ArrayList<>();

    for (Map.Entry<String, ObjectColumnInfo> entry : tableInfo.mObjectColumnMap.entrySet()) {
        String field = entry.getKey();
        ObjectColumnInfo oci = entry.getValue();

        String tableB = TableInfo.nameOf(oci.mElemClass);
        String mappingTable = getMappingTableName(tableInfo.mName, tableB);

        StringBuilder mappingWhereBuilder;
        if (!mappingWhereBuilderMap.containsKey(tableB)) {
            sqlBuilder.append(" LEFT JOIN ").append(mappingTable);
            mappingWhereBuilder = new StringBuilder();
            mappingWhereBuilderMap.put(tableB, mappingWhereBuilder);
        } else {
            mappingWhereBuilder = mappingWhereBuilderMap.get(tableB);
        }

        mappingWhereBuilder.append(mappingWhereBuilder.length() == 0 ? "" : " OR ").append(mappingTable)
                .append(".").append(getMappingTableIdColumn(tableInfo.mName, field)).append(" = ")
                .append(tableInfo.mName).append(".").append(TableInfo.COLUMN_ID);

        if (oci.mType == ObjectColumnInfo.TYPE_OBJECT_ARRAY || oci.mType == ObjectColumnInfo.TYPE_OBJECT_LIST) {
            indexColumnList.add(getMappingTableIndexColumn(tableInfo.mName, field));
        }
    }

    StringBuilder fullWhereBuilder = new StringBuilder();
    boolean first = true;
    for (StringBuilder mappingWhereBuilder : mappingWhereBuilderMap.values()) {
        fullWhereBuilder.append(first ? "" : " AND ").append("(").append(mappingWhereBuilder).append(")");
        first = false;
    }

    String where = condition.build(tableInfo.mName);
    if (where.length() > 0) {
        fullWhereBuilder.append(first ? "" : " AND ").append("(").append(where).append(")");
    }

    if (fullWhereBuilder.length() > 0) {
        sqlBuilder.append(" WHERE ").append(fullWhereBuilder);
    }

    sqlBuilder.append(" ORDER BY ").append(orderBuilder.length() == 0 ? "" : orderBuilder.append(", "))
            // Always order by id after custom order and before index columns order
            .append(tableInfo.mName).append(".").append(TableInfo.COLUMN_ID);

    // Order by index columns
    for (String column : indexColumnList) {
        sqlBuilder.append(", ").append(column);
    }

    sqlBuilder.append(";");
    return new Pair<>(sqlBuilder.toString(), condition.getArgs());
}

From source file:de.azapps.mirakel.reminders.ReminderAlarm.java

private static void updateAlarms(final Context ctx) {
    new Thread(new Runnable() {
        @Override//  w ww  . j  a va  2s.c  o  m
        public void run() {
            Log.e(TAG, "update");
            alarmManager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
            // Update the Notifications at midnight
            final Intent intent = new Intent(ctx, ReminderAlarm.class);
            intent.setAction(UPDATE_NOTIFICATION);
            final PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            final Calendar triggerCal = new GregorianCalendar();
            triggerCal.set(Calendar.HOUR_OF_DAY, 0);
            triggerCal.set(Calendar.MINUTE, 0);
            triggerCal.add(Calendar.DAY_OF_MONTH, 1);
            alarmManager.setRepeating(AlarmManager.RTC, triggerCal.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
                    pendingIntent);
            // Alarms
            final List<Task> tasks = Task.getTasksWithReminders();
            final Calendar now = new GregorianCalendar();
            for (final Pair<Task, PendingIntent> p : activeAlarms) {
                final Task t = p.first;
                final Task newTask = Task.get(t.getId()).orNull();
                if ((newTask == null) || !newTask.getReminder().isPresent() || newTask.isDone()
                        || newTask.getReminder().get().after(new GregorianCalendar())) {
                    cancelAlarm(ctx, t, newTask, p, p.second);
                } else if (newTask.getReminder().isPresent()) {
                    if (newTask.getReminder().get().after(now) && !newTask.getRecurringReminder().isPresent()) {
                        closeNotificationFor(ctx, t.getId());
                        updateAlarm(ctx, newTask);
                    } else if (newTask.getReminder().get().after(now)
                            && newTask.getRecurringReminder().isPresent()
                            && (newTask.getReminder().get()
                                    .compareTo(newTask.getRecurringReminder().get()
                                            .addRecurring(newTask.getReminder()).orNull()) > 0)
                            && !now.after(newTask.getReminder())) {
                        updateAlarm(ctx, newTask);
                    } else if ((t.getRecurringReminderId() != newTask.getRecurringReminderId())
                            || t.getRecurringReminder().isPresent()) {
                        if (t.getRecurringReminder().isPresent()
                                && newTask.getRecurringReminder().isPresent()) {
                            if (!t.getRecurringReminder().get().equals(newTask.getRecurringReminder().get())) {
                                updateAlarm(ctx, newTask);
                                cancelAlarm(ctx, t, newTask, p, p.second);
                            }
                        } else if (t.getRecurringReminder().isPresent() != newTask.getRecurringReminder()
                                .isPresent()) {
                            updateAlarm(ctx, newTask);
                            cancelAlarm(ctx, t, newTask, p, p.second);
                        }
                    } else {
                        updateAlarm(ctx, newTask);
                    }
                }
            }
            for (final Task t : tasks) {
                try {
                    if (!isAlarm(t)) {
                        Log.d(TAG, "add: " + t.getName());
                        Log.i(TAG, "id " + t.getId());
                        final PendingIntent p = updateAlarm(ctx, t);
                        activeAlarms.add(new Pair<>(t, p));
                    }
                } catch (final NoSuchTaskException e) {
                    Log.wtf(TAG, "Task not found", e);
                }
            }
        }
    }).start();
}