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.microsoft.windowsazure.mobileservices.MobileServicePush.java

/**
 * Updates a registration/*from  w ww.  j  av  a  2  s . c o m*/
 * 
 * @param registration
 *            The registration to update
 * @param callback
 *            The operation callback
 */
private void upsertRegistrationInternal(final Registration registration,
        final UpsertRegistrationInternalCallback callback) {

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder = gsonBuilder.excludeFieldsWithoutExposeAnnotation();

    Gson gson = gsonBuilder.create();

    String resource = registration.getURI();
    JsonElement json = gson.toJsonTree(registration);
    String body = json.toString();
    byte[] content = null;

    try {
        content = body.getBytes(MobileServiceClient.UTF8_ENCODING);
    } catch (UnsupportedEncodingException e) {
        callback.onUpsert(registration, e);
        return;
    }

    List<Pair<String, String>> requestHeaders = new ArrayList<Pair<String, String>>();

    requestHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE));

    mClient.invokeApiInternal(resource, content, "PUT", requestHeaders, null, MobileServiceClient.PNS_API_URL,
            new ServiceFilterResponseCallback() {

                @Override
                public void onResponse(ServiceFilterResponse response, Exception exception) {
                    if (exception != null) {
                        if (response.getStatus().getStatusCode() == 410) {
                            exception = new RegistrationGoneException(exception);
                        }

                        callback.onUpsert(registration, exception);

                        return;
                    } else {
                        callback.onUpsert(registration, null);

                        return;
                    }
                }
            });
}

From source file:com.ichi2.libanki.Media.java

private Pair<List<String>, List<String>> _changes() {
    Map<String, Object[]> cache = new HashMap<String, Object[]>();
    Cursor cur = null;//  w  w  w.j a  va2 s .  c  om
    try {
        cur = mDb.getDatabase().rawQuery("select fname, csum, mtime from media where csum is not null", null);
        while (cur.moveToNext()) {
            String name = cur.getString(0);
            String csum = cur.getString(1);
            Long mod = cur.getLong(2);
            cache.put(name, new Object[] { csum, mod, false });
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    List<String> added = new ArrayList<String>();
    List<String> removed = new ArrayList<String>();
    // loop through on-disk files
    for (File f : new File(dir()).listFiles()) {
        // ignore folders and thumbs.db
        if (f.isDirectory()) {
            continue;
        }
        String fname = f.getName();
        if (fname.equalsIgnoreCase("thumbs.db")) {
            continue;
        }
        // and files with invalid chars
        if (hasIllegal(fname)) {
            continue;
        }
        // empty files are invalid; clean them up and continue
        long sz = f.length();
        if (sz == 0) {
            f.delete();
            continue;
        }
        if (sz > 100 * 1024 * 1024) {
            mCol.log("ignoring file over 100MB", f);
            continue;
        }
        // check encoding
        String normf = HtmlUtil.nfcNormalized(fname);
        if (!fname.equals(normf)) {
            // wrong filename encoding which will cause sync errors
            File nf = new File(dir(), normf);
            if (nf.exists()) {
                f.delete();
            } else {
                f.renameTo(nf);
            }
        }
        // newly added?
        if (!cache.containsKey(fname)) {
            added.add(fname);
        } else {
            // modified since last time?
            if (_mtime(f.getAbsolutePath()) != (Long) cache.get(fname)[1]) {
                // and has different checksum?
                if (!_checksum(f.getAbsolutePath()).equals(cache.get(fname)[0])) {
                    added.add(fname);
                }
            }
            // mark as used
            cache.get(fname)[2] = true;
        }
    }
    // look for any entries in the cache that no longer exist on disk
    for (String fname : cache.keySet()) {
        if (!((Boolean) cache.get(fname)[2])) {
            removed.add(fname);
        }
    }
    return new Pair<List<String>, List<String>>(added, removed);
}

From source file:nz.ac.otago.psyanlab.common.designer.ExperimentDesignerActivity.java

@Override
public ProgramComponentAdapter<Action> getActionAdapter(long ruleId) {
    if (mCurrentActionAdapter != null && mCurrentActionAdapter.first == ruleId) {
        return mCurrentActionAdapter.second;
    }//from   w  w w .j ava  2s . c  o m

    ProgramComponentAdapter<Action> adapter = new ProgramComponentAdapter<Action>(mExperiment.actions,
            mExperiment.rules.get(ruleId).actions, new ActionListItemViewBinder(this, this));
    mCurrentActionAdapter = new Pair<Long, ProgramComponentAdapter<Action>>(ruleId, adapter);

    return adapter;
}

From source file:com.tmall.wireless.tangram3.dataparser.concrete.PojoGroupBasicAdapter.java

@Override
public void replaceComponent(Card oldGroup, Card newGroup) {
    if (mData != null && mCards != null && oldGroup != null && newGroup != null) {
        List<BaseCell> oldComponent = oldGroup.getCells();
        List<BaseCell> newComponent = newGroup.getCells();
        int index = mData.indexOf(oldComponent.get(0));
        if (index >= 0) {
            if (mCards != null) {
                List<Pair<Range<Integer>, Card>> newCards = new ArrayList<>();
                int diff = 0;
                for (int i = 0, size = mCards.size(); i < size; i++) {
                    Pair<Range<Integer>, Card> pair = mCards.get(i);
                    int start = pair.first.getLower();
                    int end = pair.first.getUpper();
                    if (end <= index) {
                        //do nothing
                        newCards.add(pair);
                    } else if (start <= index && index < end) {
                        diff = newComponent.size() - oldComponent.size();
                        Pair<Range<Integer>, Card> newPair = new Pair<>(Range.create(start, end + diff),
                                newGroup);
                        newCards.add(newPair);
                    } else if (index <= start) {
                        Pair<Range<Integer>, Card> newPair = new Pair<>(Range.create(start + diff, end + diff),
                                pair.second);
                        newCards.add(newPair);
                    }//from   ww  w.  j  a  v  a2 s  . c o m
                }
                mCards.clear();
                mCards.addAll(newCards);
            }
            oldGroup.removed();
            newGroup.added();
            mData.removeAll(oldComponent);
            mData.addAll(index, newComponent);
            int oldSize = oldComponent.size();
            int newSize = newComponent.size();
            notifyItemRangeChanged(index, Math.max(oldSize, newSize));
        }
    }
}

From source file:com.ichi2.libanki.Media.java

public Pair<String, Integer> syncInfo(String fname) {
    Cursor cur = null;/*w ww  . j av a 2s.  com*/
    try {
        cur = mDb.getDatabase().rawQuery("select csum, dirty from media where fname=?", new String[] { fname });
        if (cur.moveToNext()) {
            String csum = cur.getString(0);
            int dirty = cur.getInt(1);
            return new Pair<String, Integer>(csum, dirty);
        } else {
            return new Pair<String, Integer>(null, 0);
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
}

From source file:dynamite.zafroshops.app.MainActivity.java

private void setDataVersion() {
    ListenableFuture<JsonElement> result = MainActivity.MobileClient.invokeApi("mobileZop", "GET",
            new ArrayList<Pair<String, String>>() {
                {/*from w  ww  .  j av  a2s  .  co m*/
                    add(new Pair<>("version", "0"));
                }
            });

    Futures.addCallback(result, new FutureCallback<JsonElement>() {
        @Override
        public void onSuccess(JsonElement result) {
            DataVersion = result.getAsInt();
        }

        @Override
        public void onFailure(@NonNull Throwable t) {

        }
    });
}

From source file:com.nononsenseapps.notepad.sync.googleapi.GoogleTaskSync.java

public static List<Pair<Task, GoogleTask>> synchronizeTasksLocally(final Context context,
        final List<GoogleTask> remoteTasks, final Pair<TaskList, GoogleTaskList> listPair) {
    final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    final ArrayList<Pair<Task, GoogleTask>> taskPairs = new ArrayList<Pair<Task, GoogleTask>>();
    // For every list
    for (final GoogleTask remoteTask : remoteTasks) {
        // Compare with local
        Task localTask = loadRemoteTaskFromDB(context, remoteTask);

        // When no local version was found, either
        // a) it was deleted by the user or
        // b) it was created on the server
        if (localTask == null) {
            if (remoteTask.remotelydeleted) {
                Log.d(TAG, "slocal: task was remotely deleted1: " + remoteTask.title);
                // Nothing to do
                remoteTask.delete(context);
            } else if (remoteTask.isDeleted()) {
                Log.d(TAG, "slocal: task was locally deleted: " + remoteTask.remoteId);
                // upload change
            } else {
                //Log.d(TAG, "slocal: task was new: " + remoteTask.title);
                // If no local, and updated is higher than latestupdate,
                // create new
                localTask = new Task();
                localTask.title = remoteTask.title;
                localTask.note = remoteTask.notes;
                localTask.dblist = remoteTask.listdbid;
                // Don't touch time
                if (remoteTask.dueDate != null && !remoteTask.dueDate.isEmpty()) {
                    try {
                        localTask.due = RFC3339Date.combineDateAndTime(remoteTask.dueDate, localTask.due);
                    } catch (Exception e) {
                    }//from w  w w  .ja  v  a 2 s.c  o  m
                }
                if (remoteTask.status != null && remoteTask.status.equals(GoogleTask.COMPLETED)) {
                    localTask.completed = remoteTask.updated;
                }

                localTask.save(context, remoteTask.updated);
                // Save id in remote also
                remoteTask.dbid = localTask._id;
                remoteTask.save(context);
            }
        } else {
            // If local is newer, update remote object
            if (localTask.updated > remoteTask.updated) {
                remoteTask.fillFrom(localTask);
                // Updated is set by Google
            }
            // Remote is newer
            else if (remoteTask.remotelydeleted) {
                Log.d(TAG, "slocal: task was remotely deleted2: " + remoteTask.title);
                localTask.delete(context);
                localTask = null;
                remoteTask.delete(context);
            } else if (localTask.updated.equals(remoteTask.updated)) {
                // Nothing to do, we are already updated
            } else {
                //Log.d(TAG, "slocal: task was remotely updated: " + remoteTask.title);
                // If remote is newer, update local and save to db
                localTask.title = remoteTask.title;
                localTask.note = remoteTask.notes;
                localTask.dblist = remoteTask.listdbid;
                if (remoteTask.dueDate != null && !remoteTask.dueDate.isEmpty()) {
                    try {
                        // dont touch time
                        localTask.due = RFC3339Date.combineDateAndTime(remoteTask.dueDate, localTask.due);
                    } catch (Exception e) {
                        localTask.due = null;
                    }
                } else {
                    localTask.due = null;
                }

                if (remoteTask.status != null && remoteTask.status.equals(GoogleTask.COMPLETED)) {
                    // Only change this if it is not already completed
                    if (localTask.completed == null) {
                        localTask.completed = remoteTask.updated;
                    }
                } else {
                    localTask.completed = null;
                }

                localTask.save(context, remoteTask.updated);
            }
        }
        if (remoteTask.remotelydeleted) {
            // Dont
            Log.d(TAG, "skipping remotely deleted");
        } else if (localTask != null && remoteTask != null && localTask.updated.equals(remoteTask.updated)) {
            Log.d(TAG, "skipping equal update");
            // Dont
        } else {
            //            if (localTask != null) {
            //               Log.d("nononsenseapps gtasksync", "going to upload: " + localTask.title + ", l." + localTask.updated + " r." + remoteTask.updated);
            //            }
            Log.d(TAG, "add to sync list: " + remoteTask.title);
            taskPairs.add(new Pair<Task, GoogleTask>(localTask, remoteTask));
        }
    }

    // Add local lists without a remote version to pairs
    for (final Task t : loadNewTasksFromDB(context, listPair.first._id, listPair.second.account)) {
        //Log.d("nononsenseapps gtasksync", "adding local only: " + t.title);
        taskPairs.add(new Pair<Task, GoogleTask>(t, null));
    }

    // return pairs
    return taskPairs;
}

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

public void testOperationDefaultHeadersShouldBeIdempotent() throws Throwable {

    // Create client
    MobileServiceClient client = null;/* w  w  w.  jav a  2  s .c o m*/
    try {
        client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    final String acceptHeaderKey = "Accept";
    final String acceptEncodingHeaderKey = "Accept-Encoding";
    final String acceptHeaderValue = "application/json";
    final String acceptEncodingHeaderValue = "gzip";

    List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>();
    headers.add(new Pair<String, String>(acceptHeaderKey, acceptHeaderValue));
    headers.add(new Pair<String, String>(acceptEncodingHeaderKey, acceptEncodingHeaderValue));

    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {
            int acceptHeaderIndex = -1;
            int acceptEncodingHeaderIndex = -1;
            int acceptHeaderCount = 0;
            int acceptEncodingHeaderCount = 0;

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();

            Header[] headers = request.getHeaders();
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName() == acceptHeaderKey) {
                    acceptHeaderIndex = i;
                    acceptHeaderCount++;
                } else if (headers[i].getName() == acceptEncodingHeaderKey) {
                    acceptEncodingHeaderIndex = i;
                    acceptEncodingHeaderCount++;
                }
            }

            if (acceptHeaderIndex == -1) {
                resultFuture.setException(new Exception("acceptHeaderIndex == -1"));
                return resultFuture;
            }
            if (acceptHeaderCount == -1) {
                resultFuture.setException(new Exception("acceptHeaderCount == -1"));
                return resultFuture;
            }
            if (acceptEncodingHeaderIndex == -1) {
                resultFuture.setException(new Exception("acceptEncodingHeaderIndex == -1"));
                return resultFuture;
            }
            if (acceptEncodingHeaderCount == -1) {
                resultFuture.setException(new Exception("acceptEncodingHeaderIndex == -1"));
                return resultFuture;
            }

            ServiceFilterResponseMock response = new ServiceFilterResponseMock();
            response.setContent("{}");

            resultFuture.set(response);

            return resultFuture;
        }
    });

    try {
        client.invokeApi("myApi", null, HttpPost.METHOD_NAME, headers).get();
    } catch (Exception exception) {
        if (exception instanceof ExecutionException) {
            fail(exception.getCause().getMessage());
        } else {
            fail(exception.getMessage());
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.tests.MiscTests.java

private TestCase createHttpContentApiTest() {
    String name = "Use \"text/plain\" Content and \"identity\" Encoding Headers";

    TestCase test = new TestCase(name) {
        MobileServiceClient mClient;/*from ww w.  j  a  va  2  s  .com*/
        List<Pair<String, String>> mQuery;
        List<Pair<String, String>> mHeaders;
        TestExecutionCallback mCallback;
        JsonObject mExpectedResult;
        int mExpectedStatusCode;
        String mHttpMethod;
        byte[] mContent;

        TestResult mResult;

        @Override
        protected void executeTest(MobileServiceClient client, TestExecutionCallback callback) {
            mResult = new TestResult();
            mResult.setTestCase(this);
            mResult.setStatus(TestStatus.Passed);
            mClient = client;
            mCallback = callback;

            createHttpContentTestInput();

            try {

                ServiceFilterResponse response = mClient
                        .invokeApi(APP_API_NAME, mContent, mHttpMethod, mHeaders, mQuery).get();

                Exception ex = validateResponse(response);
                if (ex != null) {
                    createResultFromException(mResult, ex);
                } else {
                    mResult.getTestCase().log("Header validated successfully");

                    String responseContent = response.getContent();

                    mResult.getTestCase().log("Response content: " + responseContent);

                    JsonElement jsonResponse = null;
                    String decodedContent = responseContent.replace("__{__", "{").replace("__}__", "}")
                            .replace("__[__", "[").replace("__]__", "]");
                    jsonResponse = new JsonParser().parse(decodedContent);

                    if (!Util.compareJson(mExpectedResult, jsonResponse)) {
                        createResultFromException(mResult,
                                new ExpectedValueException(mExpectedResult, jsonResponse));
                    }
                }

                mCallback.onTestComplete(mResult.getTestCase(), mResult);
            } catch (Exception exception) {
                createResultFromException(exception);
                mCallback.onTestComplete(mResult.getTestCase(), mResult);
                return;
            }
        }

        ;

        private Exception validateResponse(ServiceFilterResponse response) {
            if (mExpectedStatusCode != response.getStatus().getStatusCode()) {
                mResult.getTestCase().log("Invalid status code");
                String content = response.getContent();
                if (content != null) {
                    mResult.getTestCase().log("Response: " + content);
                }
                return new ExpectedValueException(mExpectedStatusCode, response.getStatus().getStatusCode());
            } else {
                return null;
            }
        }

        private void createHttpContentTestInput() {
            mHttpMethod = HttpGet.METHOD_NAME;
            log("Method = " + mHttpMethod);

            mExpectedResult = new JsonObject();
            mExpectedResult.addProperty("method", mHttpMethod);
            JsonObject user = new JsonObject();
            user.addProperty("level", "anonymous");
            mExpectedResult.add("user", user);

            mHeaders = new ArrayList<Pair<String, String>>();
            mHeaders.add(new Pair<String, String>("Accept", "text/plain"));
            mHeaders.add(new Pair<String, String>("Accept-Encoding", "identity"));

            mQuery = new ArrayList<Pair<String, String>>();
            mQuery.add(new Pair<String, String>("format", "other"));

            mExpectedStatusCode = 200;
        }
    };

    return test;
}

From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceJsonTable.java

/**
 * Delete an element from a Mobile Service Table
 *
 * @param element    The JsonObject to undelete
 * @param parameters A list of user-defined parameters and values to include in the
 *                   request URI query string
 *///from   w w w .  j  a va 2  s.c o  m
public ListenableFuture<Void> delete(JsonObject element, List<Pair<String, String>> parameters) {

    validateId(element);

    final SettableFuture<Void> future = SettableFuture.create();

    Object id = null;
    String version = null;

    try {
        id = validateId(element);
    } catch (Exception e) {
        future.setException(e);
        return future;
    }

    if (!isNumericType(id)) {
        version = getVersionSystemProperty(element);
    }

    EnumSet<MobileServiceFeatures> features = mFeatures.clone();
    if (parameters != null && parameters.size() > 0) {
        features.add(MobileServiceFeatures.AdditionalQueryParameters);
    }

    parameters = addSystemProperties(mSystemProperties, parameters);
    List<Pair<String, String>> requestHeaders = null;
    if (version != null) {
        requestHeaders = new ArrayList<Pair<String, String>>();
        requestHeaders.add(new Pair<String, String>("If-Match", getEtagFromValue(version)));
        features.add(MobileServiceFeatures.OpportunisticConcurrency);
    }

    ListenableFuture<Pair<JsonObject, ServiceFilterResponse>> internalFuture = this.executeTableOperation(
            TABLES_URL + mTableName + "/" + id.toString(), null, "DELETE", requestHeaders, parameters,
            features);

    Futures.addCallback(internalFuture, new FutureCallback<Pair<JsonObject, ServiceFilterResponse>>() {
        @Override
        public void onFailure(Throwable exc) {
            future.setException(exc);
        }

        @Override
        public void onSuccess(Pair<JsonObject, ServiceFilterResponse> result) {
            future.set(null);
        }
    });

    return future;
}