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.google.android.apps.paco.ExploreDataActivity.java

private void showRelationshipForVarsInDifferentExperiments(HashMap<Long, List<Long>> choices) {

    ArrayList<Pair<Experiment, Long>> experimentInputPairs = new ArrayList<Pair<Experiment, Long>>();

    for (Long experimentId : choices.keySet()) {
        Long inputId = choices.get(experimentId).get(0);
        Experiment fullyLoadedExperiment = getFullyLoadedExperiment(experimentId);
        if (fullyLoadedExperiment == null) {
            Toast.makeText(ExploreDataActivity.this, R.string.experiment_does_not_exist_warning,
                    Toast.LENGTH_SHORT).show();
            return;
        }/*from  w  w  w  .j a  va  2  s.  c om*/
        experimentInputPairs.add(new Pair<Experiment, Long>(fullyLoadedExperiment, inputId));
    }

    setContentView(R.layout.feedback);
    rawDataButton = (Button) findViewById(R.id.rawDataButton);
    rawDataButton.setVisibility(View.INVISIBLE);

    webView = (WebView) findViewById(R.id.feedbackText);
    webView.getSettings().setJavaScriptEnabled(true);

    final Map<String, String> map = new HashMap<String, String>();

    map.put("xAxisData", convertExperimentResultsToJsonString(experimentInputPairs.get(0).first));
    map.put("yAxisData", convertExperimentResultsToJsonString(experimentInputPairs.get(1).first));

    map.put("xAxisInputId", Long.toString(experimentInputPairs.get(0).second));
    map.put("yAxisInputId", Long.toString(experimentInputPairs.get(1).second));

    setWebChromeClientThatHandlesAlertsAsDialogs();
    WebViewClient webViewClient = createWebViewClientThatHandlesFileLinksForCharts();
    webView.setWebViewClient(webViewClient);

    final Environment env = new Environment(map);
    webView.addJavascriptInterface(env, "env");

    webView.loadUrl("file:///android_asset/relationships.html");

}

From source file:net.etuldan.sparss.fragment.EditFeedsListFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_edit_feed_list, container, false);

    mListView = (DragNDropExpandableListView) rootView.findViewById(android.R.id.list);
    mListView.setFastScrollEnabled(true);
    mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    mListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override/*from   w ww.  j  av a  2  s.com*/
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition,
                long id) {
            startActivity(new Intent(Intent.ACTION_EDIT).setData(FeedColumns.CONTENT_URI(id)));
            return true;
        }
    });
    mListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
        @Override
        public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
            if (v.findViewById(R.id.indicator).getVisibility() != View.VISIBLE) { // This is no a real group
                startActivity(new Intent(Intent.ACTION_EDIT).setData(FeedColumns.CONTENT_URI(id)));
                return true;
            }
            return false;
        }
    });
    mListView.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            ActionBarActivity activity = (ActionBarActivity) getActivity();
            if (activity != null) {
                String title = ((TextView) view.findViewById(android.R.id.text1)).getText().toString();
                Matcher m = Pattern.compile("(.*) \\([0-9]+\\)$").matcher(title);
                if (m.matches()) {
                    title = m.group(1);
                }

                long feedId = mListView.getItemIdAtPosition(position);
                ActionMode actionMode;
                if (view.findViewById(R.id.indicator).getVisibility() == View.VISIBLE) { // This is a group
                    actionMode = activity.startSupportActionMode(mGroupActionModeCallback);
                } else { // This is a feed
                    actionMode = activity.startSupportActionMode(mFeedActionModeCallback);
                }
                actionMode.setTag(new Pair<>(feedId, title));

                mListView.setItemChecked(position, true);
            }
            return true;
        }
    });

    mListView.setAdapter(new FeedsCursorAdapter(getActivity(), FeedColumns.GROUPS_CONTENT_URI));

    mListView.setDragNDropListener(new DragNDropListener() {
        boolean fromHasGroupIndicator = false;

        @Override
        public void onStopDrag(View itemView) {
        }

        @Override
        public void onStartDrag(View itemView) {
            fromHasGroupIndicator = itemView.findViewById(R.id.indicator).getVisibility() == View.VISIBLE;
        }

        @Override
        public void onDrop(final int flatPosFrom, final int flatPosTo) {
            final boolean fromIsGroup = ExpandableListView.getPackedPositionType(mListView
                    .getExpandableListPosition(flatPosFrom)) == ExpandableListView.PACKED_POSITION_TYPE_GROUP;
            final boolean toIsGroup = ExpandableListView.getPackedPositionType(mListView
                    .getExpandableListPosition(flatPosTo)) == ExpandableListView.PACKED_POSITION_TYPE_GROUP;

            final boolean fromIsFeedWithoutGroup = fromIsGroup && !fromHasGroupIndicator;

            View toView = mListView.getChildAt(flatPosTo - mListView.getFirstVisiblePosition());
            boolean toIsFeedWithoutGroup = toIsGroup
                    && toView.findViewById(R.id.indicator).getVisibility() != View.VISIBLE;

            final long packedPosTo = mListView.getExpandableListPosition(flatPosTo);
            final int packedGroupPosTo = ExpandableListView.getPackedPositionGroup(packedPosTo);

            if ((fromIsFeedWithoutGroup || !fromIsGroup) && toIsGroup && !toIsFeedWithoutGroup) {
                new AlertDialog.Builder(getActivity()) //
                        .setTitle(R.string.to_group_title) //
                        .setMessage(R.string.to_group_message) //
                        .setPositiveButton(R.string.to_group_into, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ContentValues values = new ContentValues();
                                values.put(FeedColumns.PRIORITY, 1);
                                values.put(FeedColumns.GROUP_ID, mListView.getItemIdAtPosition(flatPosTo));

                                ContentResolver cr = getActivity().getContentResolver();
                                cr.update(FeedColumns.CONTENT_URI(mListView.getItemIdAtPosition(flatPosFrom)),
                                        values, null, null);
                                cr.notifyChange(FeedColumns.GROUPS_CONTENT_URI, null);
                            }
                        }).setNegativeButton(R.string.to_group_above, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                moveItem(fromIsGroup, toIsGroup, fromIsFeedWithoutGroup, packedPosTo,
                                        packedGroupPosTo, flatPosFrom);
                            }
                        }).show();
            } else {
                moveItem(fromIsGroup, toIsGroup, fromIsFeedWithoutGroup, packedPosTo, packedGroupPosTo,
                        flatPosFrom);
            }
        }

        @Override
        public void onDrag(int x, int y, ListView listView) {
        }
    });

    return rootView;
}

From source file:com.viktorrudometkin.burramys.fragment.EditFeedsListFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_edit_feed_list, container, false);

    mListView = (DragNDropExpandableListView) rootView.findViewById(android.R.id.list);
    mListView.setFastScrollEnabled(true);
    mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    mListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override//w ww . j  ava2  s . c o m
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition,
                long id) {
            startActivity(new Intent(Intent.ACTION_EDIT).setData(FeedColumns.CONTENT_URI(id)));
            return true;
        }
    });
    mListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
        @Override
        public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
            if (v.findViewById(R.id.indicator).getVisibility() != View.VISIBLE) { // This is no a real group
                startActivity(new Intent(Intent.ACTION_EDIT).setData(FeedColumns.CONTENT_URI(id)));
                return true;
            }
            return false;
        }
    });
    mListView.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            AppCompatActivity activity = (AppCompatActivity) getActivity();
            if (activity != null) {
                String title = ((TextView) view.findViewById(android.R.id.text1)).getText().toString();
                Matcher m = Pattern.compile("(.*) \\([0-9]+\\)$").matcher(title);
                if (m.matches()) {
                    title = m.group(1);
                }

                long feedId = mListView.getItemIdAtPosition(position);
                ActionMode actionMode;
                if (view.findViewById(R.id.indicator).getVisibility() == View.VISIBLE) { // This is a group
                    actionMode = activity.startSupportActionMode(mGroupActionModeCallback);
                } else { // This is a feed
                    actionMode = activity.startSupportActionMode(mFeedActionModeCallback);
                }
                actionMode.setTag(new Pair<>(feedId, title));

                mListView.setItemChecked(position, true);
            }
            return true;
        }
    });

    mListView.setAdapter(new FeedsCursorAdapter(getActivity(), FeedColumns.GROUPS_CONTENT_URI));

    mListView.setDragNDropListener(new DragNDropListener() {
        boolean fromHasGroupIndicator = false;

        @Override
        public void onStopDrag(View itemView) {
        }

        @Override
        public void onStartDrag(View itemView) {
            fromHasGroupIndicator = itemView.findViewById(R.id.indicator).getVisibility() == View.VISIBLE;
        }

        @Override
        public void onDrop(final int flatPosFrom, final int flatPosTo) {
            final boolean fromIsGroup = ExpandableListView.getPackedPositionType(mListView
                    .getExpandableListPosition(flatPosFrom)) == ExpandableListView.PACKED_POSITION_TYPE_GROUP;
            final boolean toIsGroup = ExpandableListView.getPackedPositionType(mListView
                    .getExpandableListPosition(flatPosTo)) == ExpandableListView.PACKED_POSITION_TYPE_GROUP;

            final boolean fromIsFeedWithoutGroup = fromIsGroup && !fromHasGroupIndicator;

            View toView = mListView.getChildAt(flatPosTo - mListView.getFirstVisiblePosition());
            boolean toIsFeedWithoutGroup = toIsGroup
                    && toView.findViewById(R.id.indicator).getVisibility() != View.VISIBLE;

            final long packedPosTo = mListView.getExpandableListPosition(flatPosTo);
            final int packedGroupPosTo = ExpandableListView.getPackedPositionGroup(packedPosTo);

            if ((fromIsFeedWithoutGroup || !fromIsGroup) && toIsGroup && !toIsFeedWithoutGroup) {
                new AlertDialog.Builder(getActivity()) //
                        .setTitle(R.string.to_group_title) //
                        .setMessage(R.string.to_group_message) //
                        .setPositiveButton(R.string.to_group_into, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ContentValues values = new ContentValues();
                                values.put(FeedColumns.PRIORITY, 1);
                                values.put(FeedColumns.GROUP_ID, mListView.getItemIdAtPosition(flatPosTo));

                                ContentResolver cr = getActivity().getContentResolver();
                                cr.update(FeedColumns.CONTENT_URI(mListView.getItemIdAtPosition(flatPosFrom)),
                                        values, null, null);
                                cr.notifyChange(FeedColumns.GROUPS_CONTENT_URI, null);
                            }
                        }).setNegativeButton(R.string.to_group_above, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                moveItem(fromIsGroup, toIsGroup, fromIsFeedWithoutGroup, packedPosTo,
                                        packedGroupPosTo, flatPosFrom);
                            }
                        }).show();
            } else {
                moveItem(fromIsGroup, toIsGroup, fromIsFeedWithoutGroup, packedPosTo, packedGroupPosTo,
                        flatPosFrom);
            }
        }

        @Override
        public void onDrag(int x, int y, ListView listView) {
        }
    });

    return rootView;
}

From source file:mobisocial.musubi.identity.AphidIdentityProvider.java

private byte[] getAphidResultForIdentity(IBIdentity ident, String property) throws IdentityProviderException {
    Log.d(TAG, "Getting key for " + ident.principal_);

    // Populate tokens from identity providers (only Google and Facebook for now)
    try {//from   ww w  . ja v a 2s  .co m
        cacheGoogleTokens();
    } catch (IdentityProviderException.Auth e) {
        // No need to continue if this is our identity and token fetch failed
        if (e.identity.equalsStable(ident)) {
            throw new IdentityProviderException.Auth(ident);
        }
    } catch (IdentityProviderException.NeedsRetry e) {
        if (e.identity.equalsStable(ident)) {
            throw new IdentityProviderException.NeedsRetry(ident);
        }
    }
    try {
        cacheCurrentFacebookToken();
    } catch (IdentityProviderException e) {
        // No need to continue if this is our identity and token fetch failed
        if (e.identity.equalsStable(ident)) {
            throw new IdentityProviderException.Auth(ident);
        }
    }

    String aphidType = null;
    String aphidToken = null;
    // Get a service-specific token if it exists
    Pair<Authority, String> userProperties = new Pair<Authority, String>(ident.authority_, ident.principal_);
    if (mKnownTokens.containsKey(userProperties)) {
        aphidToken = mKnownTokens.get(userProperties);
    }

    // The IBE server has its own identifiers for providers
    switch (ident.authority_) {
    case Facebook:
        aphidType = "facebook";
        break;
    case Email:
        if (mKnownTokens.containsKey(userProperties)) {
            aphidType = "google";
        }
        break;
    case PhoneNumber:
        // Aphid doesn't return keys for a phone number without verification
        throw new IdentityProviderException.TwoPhase(ident);
    }

    // Do not ask the server for identities we don't know how to handle
    if (aphidType == null || aphidToken == null) {
        throw new IdentityProviderException(ident);
    }

    // Bundle arguments as JSON
    JSONObject jsonObj = new JSONObject();
    try {
        jsonObj.put("type", aphidType);
        jsonObj.put("token", aphidToken);
        jsonObj.put("starttime", ident.temporalFrame_);
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
    }
    JSONArray userinfo = new JSONArray();
    userinfo.put(jsonObj);

    // Contact the server
    try {
        JSONObject resultObj = getAphidResult(userinfo);
        if (resultObj == null) {
            throw new IdentityProviderException.NeedsRetry(ident);
        }
        String encodedKey = resultObj.getString(property);
        boolean hasError = resultObj.has("error");
        if (!hasError) {
            long temporalFrame = resultObj.getLong("time");
            if (encodedKey != null && temporalFrame == ident.temporalFrame_) {
                // Success!
                return Base64.decode(encodedKey, Base64.DEFAULT);
            } else {
                // Might have jumped the gun a little bit, so try again later
                throw new IdentityProviderException.NeedsRetry(ident);
            }
        } else {
            // Aphid authentication error means Musubi has a bad token
            String error = resultObj.getString("error");
            if (error.contains("401")) {
                // Authentication errors require user action
                String accountType = Character.toString(Character.toUpperCase(aphidType.charAt(0)))
                        + aphidType.substring(1);
                sendNotification(accountType);
                throw new IdentityProviderException.Auth(ident);
            } else {
                // Other failures should be retried silently
                throw new IdentityProviderException.NeedsRetry(ident);
            }
        }
    } catch (IOException e) {
        Log.e(TAG, e.toString());
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
    }
    throw new IdentityProviderException.NeedsRetry(ident);
}

From source file:com.azure.webapi.MobileServiceClient.java

/**
 * Invokes a custom API/*from   w w  w .ja  v  a 2s. c o m*/
 * 
 * @param apiName
 *            The API name
 * @param body
 *            The json element to send as the request body
 * @param httpMethod
 *            The HTTP Method used to invoke the API
 * @param parameters
 *            The query string parameters sent in the request
 * @param callback
 *            The callback to invoke after the API execution
 */
public void invokeApi(String apiName, JsonElement body, String httpMethod,
        List<Pair<String, String>> parameters, final ApiJsonOperationCallback callback) {

    byte[] content = null;
    if (body != null) {
        try {
            content = body.toString().getBytes(UTF8_ENCODING);
        } catch (UnsupportedEncodingException e) {
            if (callback != null) {
                callback.onCompleted(null, e, null);
            }
            return;
        }
    }

    List<Pair<String, String>> requestHeaders = new ArrayList<Pair<String, String>>();
    if (body != null) {
        requestHeaders
                .add(new Pair<String, String>(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE));
    }

    invokeApi(apiName, content, httpMethod, requestHeaders, parameters, new ServiceFilterResponseCallback() {

        @Override
        public void onResponse(ServiceFilterResponse response, Exception exception) {
            if (callback != null) {
                if (exception == null) {
                    String content = response.getContent();
                    JsonElement json = new JsonParser().parse(content);

                    callback.onCompleted(json, null, response);
                } else {
                    callback.onCompleted(null, exception, response);
                }
            }
        }
    });
}

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

/**
 * Given a list of remote GTaskLists, iterates through it and their versions
 * (if any) in the local database. If the remote version is newer, the local
 * version is updated.//from  ww w.ja v a  2s  .co  m
 * 
 * If local list has a remote id, but it does not exist in the list of
 * remote lists, then it has been deleted remotely and is deleted locally as
 * well.
 * 
 * Returns a list of pairs (local, remote).
 */
public static List<Pair<TaskList, GoogleTaskList>> synchronizeListsLocally(final Context context,
        final List<GoogleTaskList> remoteLists) {
    final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    final ArrayList<Pair<TaskList, GoogleTaskList>> listPairs = new ArrayList<Pair<TaskList, GoogleTaskList>>();
    // For every list
    for (final GoogleTaskList remoteList : remoteLists) {
        // Compare with local
        Log.d(TAG, "Loading remote lists from db");
        TaskList localList = loadRemoteListFromDB(context, remoteList);

        if (localList == null) {
            if (remoteList.remotelyDeleted) {
                Log.d(TAG, "List was remotely deleted1");
                // Deleted locally AND on server
                remoteList.delete(context);
            } else if (remoteList.isDeleted()) {
                Log.d(TAG, "List was locally deleted");
                // Was deleted locally
            } else {
                // is a new list
                Log.d(TAG, "Inserting new list: " + remoteList.title);
                localList = new TaskList();
                localList.title = remoteList.title;
                localList.save(context, remoteList.updated);
                // Save id in remote also
                remoteList.dbid = localList._id;
                remoteList.save(context);
            }
        } else {
            // If local is newer, update remote object
            if (remoteList.remotelyDeleted) {
                Log.d(TAG, "Remote list was deleted2: " + remoteList.title);
                localList.delete(context);
                localList = null;
                remoteList.delete(context);
            } else if (localList.updated > remoteList.updated) {
                Log.d(TAG, "Local list newer");
                remoteList.title = localList.title;
                // Updated is set by Google
            } else if (localList.updated.equals(remoteList.updated)) {
                // Nothing to do
            } else {
                Log.d(TAG, "Updating local list: " + remoteList.title);
                // If remote is newer, update local and save to db
                localList.title = remoteList.title;
                localList.save(context, remoteList.updated);
            }
        }
        if (!remoteList.remotelyDeleted)
            listPairs.add(new Pair<TaskList, GoogleTaskList>(localList, remoteList));
    }

    // Add local lists without a remote version to pairs
    for (final TaskList tl : loadNewListsFromDB(context, remoteLists.get(0))) {
        Log.d(TAG, "loading new list db: " + tl.title);
        listPairs.add(new Pair<TaskList, GoogleTaskList>(tl, null));
    }

    // return pairs
    return listPairs;
}

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

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

        @Override/*from   w w w  . j a  v  a 2  s. c  o m*/
        public void executeOperation(MobileServiceTable<PersonTestObjectWithStringId> typedTable,
                MobileServiceJsonTable jsonTable) throws Exception {
            JsonObject jo = createJsonObject();
            List<Pair<String, String>> queryParams = new ArrayList<Pair<String, String>>();
            queryParams.add(new Pair<String, String>("a", "b"));
            jsonTable.update(jo, queryParams).get();
        }
    }, false, "QS,TU");
}

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

private TestCase createHttpContentApiTest(final DataFormat inputFormat, final DataFormat outputFormat,
        final Random rndGen) {
    String name = String.format("HttpContent Overload - Input: %s - Output: %s", inputFormat, outputFormat);

    TestCase test = new TestCase(name) {
        private static final String TEST_HEADER_PREFIX = "x-test-zumo-";
        MobileServiceClient mClient;//from   w w w  .j av  a2  s .c  o m
        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;
            mHeaders = new ArrayList<Pair<String, String>>();

            createHttpContentTestInput(inputFormat, outputFormat, rndGen);

            try {

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

                Exception ex = validateResponseHeaders(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;
                    if (outputFormat == DataFormat.Json) {
                        jsonResponse = new JsonParser().parse(responseContent);
                    } else if (outputFormat == DataFormat.Other) {
                        String decodedContent = responseContent.replace("__{__", "{").replace("__}__", "}")
                                .replace("__[__", "[").replace("__]__", "]");
                        jsonResponse = new JsonParser().parse(decodedContent);
                    }

                    switch (outputFormat) {
                    case Json:
                    case Other:
                        if (!Util.compareJson(mExpectedResult, jsonResponse)) {
                            createResultFromException(mResult,
                                    new ExpectedValueException(mExpectedResult, jsonResponse));
                        }
                        break;
                    default:
                        String expectedResultContent = jsonToXml(mExpectedResult);
                        // Normalize CRLF
                        expectedResultContent = expectedResultContent.replace("\r\n", "\n");
                        responseContent = responseContent.replace("\r\n", "\n");

                        if (!expectedResultContent.equals(responseContent)) {
                            createResultFromException(mResult,
                                    new ExpectedValueException(expectedResultContent, responseContent));
                        }
                        break;
                    }

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

            mCallback.onTestComplete(mResult.getTestCase(), mResult);
        }

        private Exception validateResponseHeaders(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 {

                for (Pair<String, String> header : mHeaders) {
                    if (header.first.startsWith(TEST_HEADER_PREFIX)) {
                        if (!Util.responseContainsHeader(response, header.first)) {
                            mResult.getTestCase().log("Header " + header.first + " not found");
                            return new ExpectedValueException("Header: " + header.first, "");
                        } else {
                            String headerValue = Util.getHeaderValue(response, header.first);
                            if (!header.second.equals(headerValue)) {
                                mResult.getTestCase().log("Invalid Header value for " + header.first);
                                return new ExpectedValueException(header.second, headerValue);
                            }
                        }
                    }
                }
            }

            return null;
        }

        private void createHttpContentTestInput(DataFormat inputFormat, DataFormat outputFormat,
                Random rndGen) {
            mHttpMethod = createHttpMethod(rndGen);
            log("Method = " + mHttpMethod);

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

            JsonElement body = null;
            String textBody = null;
            if (!mHttpMethod.equals(HttpGet.METHOD_NAME) && !mHttpMethod.equals(HttpDelete.METHOD_NAME)) {
                body = createJson(rndGen, 0, true);
                if (outputFormat == DataFormat.Xml || inputFormat == DataFormat.Xml) {
                    // to prevent non-XML names from interfering with checks
                    body = sanitizeJsonXml(body);
                }

                try {
                    switch (inputFormat) {
                    case Json:
                        mContent = body.toString().getBytes("utf-8");
                        mHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, "application/json"));
                        break;

                    case Xml:
                        textBody = jsonToXml(body);
                        mContent = textBody.getBytes("utf-8");
                        mHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, "text/xml"));
                        break;
                    default:
                        textBody = body.toString().replace('{', '<').replace('}', '>').replace("[", "__[__")
                                .replace("]", "__]__");
                        mContent = textBody.getBytes("utf-8");
                        mHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, "text/plain"));
                        break;
                    }
                } catch (UnsupportedEncodingException e) {
                    // this will never happen
                }
            }

            if (body != null) {
                if (inputFormat == DataFormat.Json) {
                    mExpectedResult.add("body", body);
                } else {
                    mExpectedResult.addProperty("body", textBody);
                }
            }

            int choice = rndGen.nextInt(5);
            for (int j = 0; j < choice; j++) {
                String name = TEST_HEADER_PREFIX + j;
                String value = Util.createSimpleRandomString(rndGen, rndGen.nextInt(10) + 1, 'a', 'z');
                mHeaders.add(new Pair<String, String>(name, value));
            }

            mQuery = createQuery(rndGen);
            if (mQuery == null) {
                mQuery = new ArrayList<Pair<String, String>>();
            }

            if (mQuery.size() > 0) {
                JsonObject outputQuery = new JsonObject();
                for (Pair<String, String> element : mQuery) {
                    outputQuery.addProperty(element.first, element.second);
                }

                mExpectedResult.add("query", outputQuery);
            }

            mQuery.add(new Pair<String, String>("format",
                    outputFormat.toString().toLowerCase(Locale.getDefault())));
            mExpectedStatusCode = 200;

            if (rndGen.nextInt(4) == 0) {
                // non-200 responses
                int[] options = new int[] { 400, 404, 500, 201 };
                int status = options[rndGen.nextInt(options.length)];
                mExpectedStatusCode = status;
                mQuery.add(new Pair<String, String>("status", Integer.valueOf(status).toString()));
            }
        }

        private String jsonToXml(JsonElement json) {
            StringBuilder sb = new StringBuilder();
            sb.append("<root>");
            jsonToXml(json, sb);
            sb.append("</root>");
            return sb.toString();
        }

        private void jsonToXml(JsonElement json, StringBuilder sb) {
            if (json == null) {
                json = new JsonPrimitive("");
            }

            if (json.isJsonNull()) {
                sb.append("null");
            } else if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isBoolean()) {
                sb.append(json.toString().toLowerCase(Locale.getDefault()));
            } else if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber()) {
                sb.append(json.toString());
            } else if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString()) {
                sb.append(json.getAsJsonPrimitive().getAsString());
            } else if (json.isJsonArray()) {
                sb.append("<array>");
                JsonArray array = json.getAsJsonArray();
                for (int i = 0; i < array.size(); i++) {
                    sb.append("<item>");
                    jsonToXml(array.get(i), sb);
                    sb.append("</item>");
                }
                sb.append("</array>");
            } else {
                Set<Entry<String, JsonElement>> entrySet = json.getAsJsonObject().entrySet();

                List<String> keys = new ArrayList<String>();
                for (Entry<String, JsonElement> entry : entrySet) {
                    keys.add(entry.getKey());
                }

                Collections.sort(keys);
                for (String key : keys) {
                    sb.append("<" + key + ">");
                    jsonToXml(json.getAsJsonObject().get(key), sb);
                    sb.append("</" + key + ">");
                }

            }
        }

        private JsonElement sanitizeJsonXml(JsonElement body) {
            if (body.isJsonArray()) {
                JsonArray array = new JsonArray();
                for (JsonElement element : body.getAsJsonArray()) {
                    array.add(sanitizeJsonXml(element));
                }

                return array;
            } else if (body.isJsonObject()) {
                JsonObject object = new JsonObject();
                Set<Entry<String, JsonElement>> entrySet = body.getAsJsonObject().entrySet();

                int i = 0;
                for (Entry<String, JsonElement> entry : entrySet) {
                    object.add("memeber" + i, sanitizeJsonXml(entry.getValue()));
                    i++;
                }

                return object;
            } else {
                return body;
            }
        }
    };

    return test;
}

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

/**
 * !!! Do not call this method directly. It's not designed for users.
 *
 * @param component the component to be removed
 *//* ww w  .  j  a  v a2  s. com*/
@Override
public void removeComponent(BaseCell component) {
    int removePosition = getPositionByItem(component);
    if (mData != null && component != null && removePosition >= 0) {
        if (mCards != null) {
            List<Pair<Range<Integer>, Card>> newCards = new ArrayList<>();
            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 < removePosition) {
                    //do nothing
                    newCards.add(pair);
                } else if (start <= removePosition && removePosition < end) {
                    int itemCount = end - start - 1;
                    if (itemCount > 0) {
                        Pair<Range<Integer>, Card> newPair = new Pair<>(Range.create(start, end - 1),
                                pair.second);
                        newCards.add(newPair);
                    }

                } else if (removePosition <= start) {
                    Pair<Range<Integer>, Card> newPair = new Pair<>(Range.create(start - 1, end - 1),
                            pair.second);
                    newCards.add(newPair);
                }
            }
            component.removed();
            mCards.clear();
            mCards.addAll(newCards);
            mData.remove(component);
            notifyItemRemoved(removePosition);
            int last = mLayoutManager.findLastVisibleItemPosition();
            notifyItemRangeChanged(removePosition, last - removePosition);
        }
    }
}

From source file:ru.gkpromtech.exhibition.db.Table.java

public <F extends Entity, S extends Entity> List<Pair<F, S>> selectLinked(Class<F> f, Class<S> s,
        String selection, String[] selectionArgs, String orderBy)
        throws InvalidClassException, IllegalAccessException, InstantiationException {

    if (mFks.length != 2)
        throw new InvalidClassException("Entity " + mEntityClass.getName() + " is not a link");

    List<Pair<F, S>> result = new ArrayList<>();
    FkInfo fk1;/*from w w  w  .j ava  2  s  .c  o m*/
    FkInfo fk2;

    if (mFks[0].entityClass.equals(f) && mFks[1].entityClass.equals(s)) {
        fk1 = mFks[0];
        fk2 = mFks[1];
    } else if (mFks[1].entityClass.equals(f) && mFks[0].entityClass.equals(s)) {
        //     ?   ?? ?
        fk1 = mFks[1];
        fk2 = mFks[0];
    } else {
        throw new InvalidClassException("Invalid classes passed as arguments");
    }

    Table<F> table1 = ((DbHelper) mSqlHelper).getTableFor(f);
    Table<S> table2 = ((DbHelper) mSqlHelper).getTableFor(s);

    StringBuilder query = new StringBuilder();
    for (String column : table1.mColumns) {
        query.append(",f.").append(column);
    }
    for (String column : table2.mColumns)
        query.append(",s.").append(column);
    query.replace(0, 1, "SELECT ");

    query.append("\nFROM ").append(mTableName).append(" t\nJOIN ").append(table1.mTableName).append(" f ON f.")
            .append(fk1.fkName).append(" = t.").append(fk1.fieldName).append("\nJOIN ")
            .append(table2.mTableName).append(" s ON s.").append(fk2.fkName).append(" = t.")
            .append(fk2.fieldName);
    if (selection != null)
        query.append("\nWHERE ").append(selection);
    if (orderBy != null)
        query.append("\nORDER BY ").append(orderBy);

    String queryString = query.toString();
    if (BuildConfig.DEBUG)
        Log.d("PP", queryString);

    SQLiteDatabase db = mSqlHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(queryString, selectionArgs);

    //noinspection TryFinallyCanBeTryWithResources
    try {
        while (cursor.moveToNext()) {
            F entity1 = f.newInstance();
            S entity2 = s.newInstance();
            for (int i = 0; i < table1.mFields.length; ++i)
                fillFieldValue(table1.mType[i], table1.mFields[i], entity1, cursor, i);
            for (int i = 0; i < table2.mFields.length; ++i)
                fillFieldValue(table2.mType[i], table2.mFields[i], entity2, cursor, table1.mFields.length + i);
            result.add(new Pair<>(entity1, entity2));
        }
    } finally {
        cursor.close();
        db.close();
    }

    return result;
}