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.sdk.testapp.test.MobileServiceFeaturesTests.java

public void testGenericApiDoesNotOverrideExistingFeatureHeader() {
    testInvokeApiFeatureHeader(new ClientTestOperation() {

        @Override/*  w  w  w.  j  a v a 2 s. co m*/
        public void executeOperation(MobileServiceClient client) throws Exception {
            List<Pair<String, String>> queryParams = new ArrayList<Pair<String, String>>();
            queryParams.add(new Pair<String, String>("a", "b"));
            List<Pair<String, String>> requestHeaders = new ArrayList<Pair<String, String>>();
            requestHeaders.add(new Pair<String, String>("Content-Type", "text/plain"));
            requestHeaders.add(new Pair<String, String>("X-ZUMO-FEATURES", "something"));
            byte[] content = "hello world".getBytes();
            client.invokeApi("apiName", content, "POST", requestHeaders, queryParams).get();
        }

    }, "something");
}

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

public void testOperationShouldNotReplaceWithDefaultHeaders() throws Throwable {

    // Create client
    MobileServiceClient client = null;//w w w  .  j  ava2s.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 = "text/plain";
    final String acceptEncodingHeaderValue = "deflate";

    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;
            }

            if (acceptHeaderValue.equals(headers[acceptHeaderIndex].getValue())) {
                resultFuture.setException(new Exception("acceptHeaderValue != headers[acceptHeaderIndex]"));
                return resultFuture;
            }

            if (acceptEncodingHeaderValue.equals(headers[acceptEncodingHeaderIndex].getValue())) {
                resultFuture.setException(
                        new Exception("acceptEncodingHeaderValue != headers[acceptEncodingHeaderIndex]"));
                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.tmall.wireless.tangram3.dataparser.concrete.PojoGroupBasicAdapter.java

@Override
public void replaceComponent(List<BaseCell> oldComponent, List<BaseCell> newComponent) {
    if (mData != null && oldComponent != null && newComponent != null && oldComponent.size() > 0
            && newComponent.size() > 0) {
        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),
                                pair.second);
                        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);
                    }/*w  ww  . j  a va 2  s.c  o m*/
                }
                mCards.clear();
                mCards.addAll(newCards);
            }
            for (int i = 0, size = oldComponent.size(); i < size; i++) {
                BaseCell cell = oldComponent.get(i);
                if (cell != null) {
                    cell.removed();
                }
            }
            for (int i = 0, size = newComponent.size(); i < size; i++) {
                BaseCell cell = newComponent.get(i);
                if (cell != null) {
                    cell.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.microsoft.windowsazure.mobileservices.table.MobileServiceJsonTable.java

/**
 * Updates an element from a Mobile Service Table
 *
 * @param element    The JsonObject to update
 * @param parameters A list of user-defined parameters and values to include in the
 *                   request URI query string
 *///from   w w  w  . j  a v a 2 s .  co  m
public ListenableFuture<JsonObject> update(final JsonObject element, List<Pair<String, String>> parameters) {
    final SettableFuture<JsonObject> future = SettableFuture.create();

    Object id = null;
    String version = null;
    String content = null;

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

    if (!isNumericType(id)) {
        version = getVersionSystemProperty(element);
        content = removeSystemProperties(element).toString();
    } else {
        content = element.toString();
    }

    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(), content, "PATCH", 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) {
            JsonObject patchedJson = patchOriginalEntityWithResponseEntity(element, result.first);

            updateVersionFromETag(result.second, patchedJson);

            future.set(patchedJson);
        }
    });

    return future;
}

From source file:com.microsoft.windowsazure.mobileservices.MobileServiceTableBase.java

/**
 * Adds the tables requested system properties to the parameters collection.
 * @param   systemProperties   The system properties to add.
 * @param   parameters         The parameters collection.
 * @return                  The parameters collection with any requested system properties included.
 *//*  w  ww  .j  a  va 2s  .  c o m*/
protected List<Pair<String, String>> addSystemProperties(EnumSet<MobileServiceSystemProperty> systemProperties,
        List<Pair<String, String>> parameters) {
    boolean containsSystemProperties = false;

    List<Pair<String, String>> result = new ArrayList<Pair<String, String>>(
            parameters != null ? parameters.size() : 0);

    // Make sure we have a case-insensitive parameters list
    if (parameters != null) {
        for (Pair<String, String> parameter : parameters) {
            result.add(parameter);
            containsSystemProperties = containsSystemProperties
                    || parameter.first.equalsIgnoreCase(SystemPropertiesQueryParameterName);
        }
    }

    // If there is already a user parameter for the system properties, just use it
    if (!containsSystemProperties) {
        String systemPropertiesString = getSystemPropertiesString(systemProperties);

        if (systemPropertiesString != null) {
            result.add(new Pair<String, String>(SystemPropertiesQueryParameterName, systemPropertiesString));
        }
    }

    return result;
}

From source file:com.bt.download.android.gui.Librarian.java

private Pair<List<Integer>, List<String>> getAllFiles(byte fileType) {
    Pair<List<Integer>, List<String>> result = new Pair<List<Integer>, List<String>>(new ArrayList<Integer>(),
            new ArrayList<String>());

    Cursor c = null;//from w w  w  . ja v  a 2s. c  om

    try {
        TableFetcher fetcher = TableFetchers.getFetcher(fileType);

        ContentResolver cr = context.getContentResolver();

        c = cr.query(fetcher.getContentUri(), new String[] { BaseColumns._ID, MediaColumns.DATA }, null, null,
                BaseColumns._ID);

        if (c != null) {
            while (c.moveToNext()) {
                result.first.add(c.getInt(0));
                result.second.add(c.getString(1));
            }
        }
    } catch (Throwable e) {
        Log.e(TAG, "General failure getting all files", e);
    } finally {
        if (c != null) {
            c.close();
        }
    }

    return result;
}

From source file:com.ichi2.anki.NoteEditor.java

private void fetchIntentInformation(Intent intent) {
    Bundle extras = intent.getExtras();/*from w ww.  j  a  v  a 2  s  . c  o  m*/
    if (ACTION_CREATE_FLASHCARD.equals(intent.getAction())) {
        // mSourceLanguage = extras.getString(SOURCE_LANGUAGE);
        // mTargetLanguage = extras.getString(TARGET_LANGUAGE);
        mSourceText = new String[2];
        mSourceText[0] = extras.getString(SOURCE_TEXT);
        mSourceText[1] = extras.getString(TARGET_TEXT);
    } else {
        String first;
        String second;
        if (extras.getString(Intent.EXTRA_SUBJECT) != null) {
            first = extras.getString(Intent.EXTRA_SUBJECT);
        } else {
            first = "";
        }
        if (extras.getString(Intent.EXTRA_TEXT) != null) {
            second = extras.getString(Intent.EXTRA_TEXT);
        } else {
            second = "";
        }
        // Some users add cards via SEND intent from clipboard. In this case SUBJECT is empty
        if (first.equals("")) {
            // Assume that if only one field was sent then it should be the front
            first = second;
            second = "";
        }
        Pair<String, String> messages = new Pair<String, String>(first, second);

        mSourceText = new String[2];
        mSourceText[0] = messages.first;
        mSourceText[1] = messages.second;
    }
}

From source file:com.zulip.android.util.CustomHtmlToSpannedConverter.java

/**
<<<<<<< e370c9bc00e8f6b33b1d12a44b4c70a7f063c8b9
 * Parses Spanned text for existing html links and reapplies them after the text has been Linkified
=======/*  w  w w  .  j  av a  2s  .c o m*/
 * Parses Spanned text for existing html links and reapplies them.
>>>>>>> Issue #168 bugfix for links not being clickable, adds autoLink feature including web, phone, map and email
 * @see <a href="https://developer.android.com/reference/android/text/util/Linkify.html">Linkify</a>
 *
 * @param spann
 * @param mask bitmask to define which kinds of links will be searched and applied (e.g. <a href="https://developer.android.com/reference/android/text/util/Linkify.html#ALL">Linkify.ALL</a>)
 * @return
 */
public static Spanned linkifySpanned(@NonNull final Spanned spann, final int mask) {
    URLSpan[] existingSpans = spann.getSpans(0, spann.length(), URLSpan.class);
    List<Pair<Integer, Integer>> links = new ArrayList<>();

    for (URLSpan urlSpan : existingSpans) {
        links.add(new Pair<>(spann.getSpanStart(urlSpan), spann.getSpanEnd(urlSpan)));
    }

    Linkify.addLinks((Spannable) spann, mask);

    // add the links back in
    for (int i = 0; i < existingSpans.length; i++) {
        ((Spannable) spann).setSpan(existingSpans[i], links.get(i).first, links.get(i).second,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    return spann;
}

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

public void testInvokeBytesShouldNotModifyLists() {
    final byte[] content = new byte[] { 1, 2, 3, 4 };
    try {// w  w  w . j av  a2 s  . co  m
        MobileServiceClient client = new MobileServiceClient(appUrl, appKey,
                getInstrumentation().getTargetContext());
        client = client.withFilter(new EchoFilter());

        List<Pair<String, String>> expectedHeaders = new ArrayList<Pair<String, String>>();
        expectedHeaders.add(new Pair<String, String>("header1", "value1"));
        expectedHeaders.add(new Pair<String, String>("header2", "value2"));
        List<Pair<String, String>> expectedQueryParameters = new ArrayList<Pair<String, String>>();
        expectedQueryParameters.add(new Pair<String, String>("query1", "value1"));
        expectedQueryParameters.add(new Pair<String, String>("query2", "value2"));

        List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>(expectedHeaders);
        List<Pair<String, String>> queryParameters = new ArrayList<Pair<String, String>>(
                expectedQueryParameters);
        client.invokeApi("myApi", content, "POST", headers, queryParameters).get();

        assertEquals(expectedHeaders.size(), headers.size());
        for (int i = 0; i < expectedHeaders.size(); i++) {
            assertEquals(expectedHeaders.get(i).first, headers.get(i).first);
            assertEquals(expectedHeaders.get(i).second, headers.get(i).second);
        }

        assertEquals(expectedQueryParameters.size(), queryParameters.size());
        for (int i = 0; i < expectedQueryParameters.size(); i++) {
            assertEquals(expectedQueryParameters.get(i).first, queryParameters.get(i).first);
            assertEquals(expectedQueryParameters.get(i).second, queryParameters.get(i).second);
        }
    } catch (Exception exception) {
        fail(exception.getMessage());
    }
}

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

private TestCase createTypedApiTest(final Random rndGen, final TypedTestType testType) {

    String name = String.format("Typed Overload - %s", testType);

    TestCase test = new TestCase(name) {
        MobileServiceClient mClient;/*www  .  j  av  a2  s.c  om*/
        List<Pair<String, String>> mQuery;
        TestExecutionCallback mCallback;
        Movie[] mExpectedResult = null;

        TestResult mResult;

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

            final StringIdMovie ramdomMovie = QueryTestData.getRandomStringIdMovie(rndGen);
            log("Using movie: " + ramdomMovie.getTitle());

            String apiName = MOVIEFINDER_API_NAME;
            String apiUrl;
            switch (testType) {
            case GetByTitle:
                apiUrl = apiName + "/title/" + ramdomMovie.getTitle();
                log("API: " + apiUrl);
                mExpectedResult = new StringIdMovie[] { ramdomMovie };

                try {
                    AllStringIdMovies result = mClient
                            .invokeApi(apiUrl, HttpGet.METHOD_NAME, null, AllStringIdMovies.class).get();

                    if (!Util.compareArrays(mExpectedResult, result.getMovies())) {
                        createResultFromException(mResult, new ExpectedValueException(
                                Util.arrayToString(mExpectedResult), Util.arrayToString(result.getMovies())));
                    }
                } catch (Exception exception) {
                    createResultFromException(mResult, exception);
                } finally {
                    mCallback.onTestComplete(mResult.getTestCase(), mResult);
                }

                break;

            case GetByDate:
                final Date releaseDate = ramdomMovie.getReleaseDate();
                TimeZone tz = TimeZone.getTimeZone("UTC");
                Calendar c = Calendar.getInstance(tz);
                c.setTime(releaseDate);
                apiUrl = apiName + "/date/" + c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH) + 1) + "/"
                        + c.get(Calendar.DATE);
                log("API: " + apiUrl);
                SimpleMovieFilter dateFilter = new SimpleMovieFilter() {
                    @Override
                    protected boolean criteria(Movie movie) {
                        return movie.getReleaseDate().equals(releaseDate);
                    }
                };

                mExpectedResult = dateFilter.filter(QueryTestData.getAllStringIdMovies()).elements
                        .toArray(new Movie[0]);

                try {
                    AllStringIdMovies result = mClient
                            .invokeApi(apiUrl, HttpGet.METHOD_NAME, null, AllStringIdMovies.class).get();

                    if (!Util.compareArrays(mExpectedResult, result.getMovies())) {
                        createResultFromException(mResult, new ExpectedValueException(
                                Util.arrayToString(mExpectedResult), Util.arrayToString(result.getMovies())));
                    }
                } catch (Exception exception) {
                    createResultFromException(mResult, exception);
                } finally {
                    mCallback.onTestComplete(mResult.getTestCase(), mResult);
                }

                break;

            case PostByDuration:
            case PostByYear:
                String orderBy = null;
                switch (rndGen.nextInt(3)) {
                case 0:
                    orderBy = null;
                    break;
                case 1:
                    orderBy = "title";
                    break;
                case 2:
                    orderBy = "title"; //duration
                    break;
                }

                mQuery = null;
                if (orderBy != null) {
                    mQuery = new ArrayList<Pair<String, String>>();
                    mQuery.add(new Pair<String, String>("orderBy", orderBy));

                    log("OrderBy: " + orderBy);
                }

                if (testType == TypedTestType.PostByYear) {
                    apiUrl = apiName + "/moviesOnSameYear";
                } else {
                    apiUrl = apiName + "/moviesWithSameDuration";
                }

                log("API: " + apiUrl);

                final String orderByCopy = orderBy;
                SimpleMovieFilter movieFilter = new SimpleMovieFilter() {

                    @Override
                    protected boolean criteria(Movie movie) {
                        if (testType == TypedTestType.PostByYear) {
                            return movie.getYear() == ramdomMovie.getYear();
                        } else {
                            return movie.getDuration() == ramdomMovie.getDuration();
                        }
                    }

                    @Override
                    protected List<Movie> applyOrder(List<? extends Movie> movies) {
                        if (orderByCopy == null || orderByCopy.equals("title")) {
                            Collections.sort(movies, new MovieComparator("getTitle"));
                        } else if (orderByCopy.equals("duration")) {
                            Collections.sort(movies, new MovieComparator("getDuration"));
                        }

                        return new ArrayList<Movie>(movies);
                    }
                };

                mExpectedResult = movieFilter.filter(QueryTestData.getAllStringIdMovies()).elements
                        .toArray(new Movie[0]);

                if (mQuery == null) {

                    try {
                        AllStringIdMovies result = mClient.invokeApi(apiUrl, ramdomMovie, HttpPost.METHOD_NAME,
                                null, AllStringIdMovies.class).get();

                        if (!Util.compareArrays(mExpectedResult, result.getMovies())) {
                            createResultFromException(mResult,
                                    new ExpectedValueException(Util.arrayToString(mExpectedResult),
                                            Util.arrayToString(result.getMovies())));
                        }
                    } catch (Exception exception) {
                        createResultFromException(mResult, exception);
                    } finally {
                        mCallback.onTestComplete(mResult.getTestCase(), mResult);
                    }

                } else {

                    try {
                        AllStringIdMovies result = mClient.invokeApi(apiUrl, ramdomMovie, HttpPost.METHOD_NAME,
                                mQuery, AllStringIdMovies.class).get();

                        if (!Util.compareArrays(mExpectedResult, result.getMovies())) {
                            createResultFromException(mResult,
                                    new ExpectedValueException(Util.arrayToString(mExpectedResult),
                                            Util.arrayToString(result.getMovies())));
                        }
                    } catch (Exception exception) {
                        createResultFromException(mResult, exception);
                    } finally {
                        mCallback.onTestComplete(mResult.getTestCase(), mResult);
                    }
                }
                break;
            }
        }

    };

    return test;
}