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.bitants.wally.fragments.SearchFragment.java

@Override
public boolean handleMessage(Message msg) {
    switch (msg.what) {

    case MSG_GET_IMAGES:
        final int index = msg.arg1;
        String query = (String) msg.obj;
        WallyApplication.getDataProviderInstance().getImages(NetworkDataProvider.PATH_SEARCH, query,
                currentColor, index, WallyApplication.getFilterSettings(),
                new DataProvider.OnImagesReceivedListener() {
                    @Override/*from   w w w.  jav a2  s  . com*/
                    public void onImagesReceived(ArrayList<Image> images) {
                        Message msgObj = uiHandler.obtainMessage();
                        msgObj.what = index == 1 ? MSG_IMAGES_REQUEST_CREATE : MSG_IMAGES_REQUEST_APPEND;
                        msgObj.obj = images;
                        uiHandler.sendMessage(msgObj);
                    }

                    @Override
                    public void onError(DataProviderError dataProviderError) {
                        showError(dataProviderError, index);
                    }
                });
        break;

    case MSG_SAVE_BUTTON_CLICKED:
        Image image = (Image) msg.obj;
        WallyApplication.getDataProviderInstance().getPageData(image.imagePageURL(),
                new DataProvider.OnPageReceivedListener() {
                    @Override
                    public void onPageReceived(ImagePage imagePage) {
                        Message msgImagePage = uiHandler.obtainMessage();
                        msgImagePage.what = MSG_PAGE_RECEIVED;
                        msgImagePage.obj = imagePage;
                        uiHandler.sendMessage(msgImagePage);
                    }

                    @Override
                    public void onError(DataProviderError dataProviderError) {
                        Message msgObj = uiHandler.obtainMessage();
                        msgObj.what = MSG_ERROR_IMAGE_SAVING;
                        msgObj.obj = dataProviderError;
                        uiHandler.sendMessage(msgObj);
                    }
                });
        break;

    case MSG_PAGE_RECEIVED:
        ImagePage imagePage = (ImagePage) msg.obj;
        if (imagePage != null) {
            SaveImageRequest saveImageRequest = WallyApplication.getDataProviderInstance()
                    .downloadImageIfNeeded(imagePage.imagePath(), imagePage.imageId(),
                            getResources().getString(R.string.notification_title_image_saving));

            if (saveImageRequest.getDownloadID() != null && getActivity() instanceof MainActivity) {
                WallyApplication.getDownloadIDs().put(saveImageRequest.getDownloadID(), imagePage.imageId());
            } else {
                getActivity().sendBroadcast(new Intent(FileReceiver.GET_FILES));
            }
        }
        break;

    case MSG_ERROR_IMAGE_REQUEST:
        if (getActivity() != null) {
            DataProviderError dataProviderError = (DataProviderError) msg.obj;
            int imagesIndex = msg.arg1;
            showErrorMessage(dataProviderError, imagesIndex);
        }
        break;

    case MSG_ERROR_IMAGE_SAVING:
        if (getActivity() != null) {
            NotificationProvider notificationProvider = new NotificationProvider();
            notificationProvider.cancelAll(getActivity());
            Toast.makeText(getActivity(), "Couldn't save image", Toast.LENGTH_SHORT).show();
        }
        break;

    case MSG_IMAGES_REQUEST_CREATE:
        ArrayList<Image> images = (ArrayList<Image>) msg.obj;
        boolean shouldScheduleLayoutAnimation = msg.arg1 == 0;
        isLoading = false;
        if (images != null) {
            hideLoader();
            imagesAdapter = new RecyclerImagesAdapter(images, itemSize);
            imagesAdapter.setOnSaveButtonClickedListener(SearchFragment.this);
            imagesAdapter.updateSavedFilesList(savedFiles);
            gridView.setAdapter(imagesAdapter);
            setupAdapter();
            if (shouldScheduleLayoutAnimation) {
                gridView.scheduleLayoutAnimation();
            }
        }
        break;

    case MSG_IMAGES_REQUEST_APPEND:
        ArrayList<Image> extraImages = (ArrayList<Image>) msg.obj;
        isLoading = false;
        if (extraImages != null) {
            hideLoader();
            int endPosition = imagesAdapter.getItemCount();
            ArrayList<Image> currentList = imagesAdapter.getImages();
            currentList.addAll(extraImages);
            imagesAdapter.notifyItemRangeInserted(endPosition, extraImages.size());
        }
        break;

    case MSG_SAVE_LIST_OF_SAVED_IMAGES:
        savedFiles = (HashMap<String, Boolean>) msg.obj;
        if (imagesAdapter != null) {
            imagesAdapter.updateSavedFilesList(savedFiles);
            imagesAdapter.notifySavedItemsChanged();
        }
        break;

    case MSG_NEW_COLOR_FETCHED:
        int color = msg.arg1;
        String colorHex = Integer.toHexString(color).substring(2);
        int[] colors = new int[1];
        colors[0] = color;
        Bitmap bitmapColor = Bitmap.createBitmap(colors, 1, 1, Bitmap.Config.ARGB_8888); //Use this to create a Palette.
        Palette palette = Palette.generate(bitmapColor);

        Message newColorMessage = uiHandler.obtainMessage();
        newColorMessage.what = MSG_RENDER_NEW_COLOR;
        newColorMessage.obj = new Pair<String, Palette>(colorHex, palette);
        uiHandler.sendMessage(newColorMessage);
        break;

    case MSG_RENDER_NEW_COLOR:
        Pair<String, Palette> pair = (Pair<String, Palette>) msg.obj;
        String colorAsHex = pair.first;
        Palette palette1 = pair.second;

        showColorTag(colorAsHex, palette1);

        break;
    }
    return false;
}

From source file:androidx.media.widget.VideoView2.java

/**
 * Sets custom actions which will be shown as custom buttons in {@link MediaControlView2}.
 *
 * @param actionList A list of {@link PlaybackStateCompat.CustomAction}. The return value of
 *                   {@link PlaybackStateCompat.CustomAction#getIcon()} will be used to draw
 *                   buttons in {@link MediaControlView2}.
 * @param executor executor to run callbacks on.
 * @param listener A listener to be called when a custom button is clicked.
 * @hide  TODO remove//from  w  w  w  . j  a  v a  2  s.  co m
 */
@RestrictTo(LIBRARY_GROUP)
public void setCustomActions(List<PlaybackStateCompat.CustomAction> actionList, Executor executor,
        OnCustomActionListener listener) {
    mCustomActionList = actionList;
    mCustomActionListenerRecord = new Pair<>(executor, listener);

    // Create a new playback builder in order to clear existing the custom actions.
    mStateBuilder = null;
    updatePlaybackState();
}

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

public void testInvokeHeadersEcho() throws Throwable {

    // Container to store callback's results and do the asserts.
    final ResultsContainer container = new ResultsContainer();
    final List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>();
    final List<String> headerNames = new ArrayList<String>();

    for (int i = 0; i < 10; i++) {
        String name;/*  ww w.  jav a 2s  .  c  om*/

        do {
            name = UUID.randomUUID().toString();
        } while (headerNames.contains(name));

        headers.add(new Pair<String, String>(name, UUID.randomUUID().toString()));
        headerNames.add(name);
    }

    MobileServiceClient client = null;
    try {
        client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext());

        client = client.withFilter(new HttpMetaEchoFilter());

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

        ServiceFilterResponse response = client
                .invokeApi("myApi", null, HttpPost.METHOD_NAME, headers, fakeParameters).get();

        if (response == null || response.getContent() == null) {
            container.setException(new Exception("Expected response"));
        } else {
            container.setResponseValue(response.getContent());
        }

    } catch (Exception exception) {
        container.setException(exception);
    }

    // Asserts
    Exception exception = container.getException();
    if (exception != null) {
        fail(exception.getMessage());
    } else {
        JsonObject jResponse = (new JsonParser()).parse(container.getResponseValue()).getAsJsonObject();

        if (jResponse.has("headers") && jResponse.get("headers").isJsonObject()) {
            JsonObject jHeaders = jResponse.getAsJsonObject("headers");

            for (Pair<String, String> header : headers) {
                if (jHeaders.has(header.first)) {
                    assertEquals(header.second, jHeaders.get(header.first).getAsString());
                } else {
                    fail("Expected header.");
                }
            }

        } else {
            fail("Expected headers.");
        }

    }
}

From source file:com.musenkishi.wally.fragments.SearchFragment.java

@Override
public boolean handleMessage(Message msg) {
    switch (msg.what) {

    case MSG_GET_IMAGES:
        final int index = msg.arg1;
        String query = (String) msg.obj;
        WallyApplication.getDataProviderInstance().getImages(NetworkDataProvider.PATH_SEARCH, query,
                currentColor, index, WallyApplication.getFilterSettings(),
                new DataProvider.OnImagesReceivedListener() {
                    @Override/*  w  w  w .  ja  va 2 s .c  o m*/
                    public void onImagesReceived(ArrayList<Image> images) {
                        Message msgObj = uiHandler.obtainMessage();
                        msgObj.what = index == 1 ? MSG_IMAGES_REQUEST_CREATE : MSG_IMAGES_REQUEST_APPEND;
                        msgObj.obj = images;
                        uiHandler.sendMessage(msgObj);
                    }

                    @Override
                    public void onError(DataProviderError dataProviderError) {
                        showError(dataProviderError, index);
                    }
                });
        break;

    case MSG_SAVE_BUTTON_CLICKED:
        Image image = (Image) msg.obj;
        WallyApplication.getDataProviderInstance().getPageData(image.imagePageURL(),
                new DataProvider.OnPageReceivedListener() {
                    @Override
                    public void onPageReceived(ImagePage imagePage) {
                        Message msgImagePage = uiHandler.obtainMessage();
                        msgImagePage.what = MSG_PAGE_RECEIVED;
                        msgImagePage.obj = imagePage;
                        uiHandler.sendMessage(msgImagePage);
                    }

                    @Override
                    public void onError(DataProviderError dataProviderError) {
                        Message msgObj = uiHandler.obtainMessage();
                        msgObj.what = MSG_ERROR_IMAGE_SAVING;
                        msgObj.obj = dataProviderError;
                        uiHandler.sendMessage(msgObj);
                    }
                });
        break;

    case MSG_PAGE_RECEIVED:
        ImagePage imagePage = (ImagePage) msg.obj;
        if (imagePage != null) {
            SaveImageRequest saveImageRequest = WallyApplication.getDataProviderInstance()
                    .downloadImageIfNeeded(imagePage.imagePath(), imagePage.imageId(),
                            getResources().getString(R.string.notification_title_image_saving));

            if (saveImageRequest.getDownloadID() != null && getActivity() instanceof MainActivity) {
                WallyApplication.getDownloadIDs().put(saveImageRequest.getDownloadID(), imagePage.imageId());
            } else {
                onFileChange();
            }
        }
        break;

    case MSG_ERROR_IMAGE_REQUEST:
        if (getActivity() != null) {
            DataProviderError dataProviderError = (DataProviderError) msg.obj;
            int imagesIndex = msg.arg1;
            showErrorMessage(dataProviderError, imagesIndex);
        }
        break;

    case MSG_ERROR_IMAGE_SAVING:
        if (getActivity() != null) {
            NotificationProvider notificationProvider = new NotificationProvider();
            notificationProvider.cancelAll(getActivity());
            Toast.makeText(getActivity(), "Couldn't save image", Toast.LENGTH_SHORT).show();
        }
        break;

    case MSG_IMAGES_REQUEST_CREATE:
        ArrayList<Image> images = (ArrayList<Image>) msg.obj;
        boolean shouldScheduleLayoutAnimation = msg.arg1 == 0;
        isLoading = false;
        if (images != null) {
            hideLoader();
            imagesAdapter = new RecyclerImagesAdapter(images, itemSize);
            imagesAdapter.setOnSaveButtonClickedListener(SearchFragment.this);
            imagesAdapter.updateSavedFilesList(savedFiles);
            gridView.setAdapter(imagesAdapter);
            setupAdapter();
            if (shouldScheduleLayoutAnimation) {
                gridView.scheduleLayoutAnimation();
            }
        }
        break;

    case MSG_IMAGES_REQUEST_APPEND:
        ArrayList<Image> extraImages = (ArrayList<Image>) msg.obj;
        isLoading = false;
        if (extraImages != null) {
            hideLoader();
            int endPosition = imagesAdapter.getItemCount();
            ArrayList<Image> currentList = imagesAdapter.getImages();
            currentList.addAll(extraImages);
            imagesAdapter.notifyItemRangeInserted(endPosition, extraImages.size());
        }
        break;

    case MSG_GET_LIST_OF_SAVED_IMAGES:
        HashMap<String, Boolean> existingFiles = new HashMap<String, Boolean>();

        FileManager fileManager = new FileManager();
        for (Uri uri : fileManager.getFiles()) {
            String filename = uri.getLastPathSegment();
            String[] filenames = filename.split("\\.(?=[^\\.]+$)"); //split filename from it's extension
            existingFiles.put(filenames[0], true);
        }

        Message fileListMessage = uiHandler.obtainMessage();
        fileListMessage.obj = existingFiles;
        fileListMessage.what = MSG_SAVE_LIST_OF_SAVED_IMAGES;
        uiHandler.sendMessage(fileListMessage);
        break;

    case MSG_SAVE_LIST_OF_SAVED_IMAGES:
        savedFiles = (HashMap<String, Boolean>) msg.obj;
        if (imagesAdapter != null) {
            imagesAdapter.updateSavedFilesList(savedFiles);
            imagesAdapter.notifySavedItemsChanged();
        }
        break;

    case MSG_NEW_COLOR_FETCHED:
        int color = msg.arg1;
        String colorHex = Integer.toHexString(color).substring(2);
        int[] colors = new int[1];
        colors[0] = color;
        Bitmap bitmapColor = Bitmap.createBitmap(colors, 1, 1, Bitmap.Config.ARGB_8888); //Use this to create a Palette.
        Palette palette = Palette.generate(bitmapColor);

        Message newColorMessage = uiHandler.obtainMessage();
        newColorMessage.what = MSG_RENDER_NEW_COLOR;
        newColorMessage.obj = new Pair<String, Palette>(colorHex, palette);
        uiHandler.sendMessage(newColorMessage);
        break;

    case MSG_RENDER_NEW_COLOR:
        Pair<String, Palette> pair = (Pair<String, Palette>) msg.obj;
        String colorAsHex = pair.first;
        Palette palette1 = pair.second;

        showColorTag(colorAsHex, palette1);

        break;
    }
    return false;
}

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

@Override
public ProgramComponentAdapter<Generator> getGeneratorAdapter(long loopId) {
    if (mCurrentGeneratorAdapter != null && mCurrentGeneratorAdapter.first == loopId) {
        return mCurrentGeneratorAdapter.second;
    }//from  ww  w .j av a2 s . com

    ProgramComponentAdapter<Generator> adapter = new ProgramComponentAdapter<Generator>(mExperiment.generators,
            mExperiment.loops.get(loopId).generators, new GeneratorListItemViewBinder(this, this));
    mCurrentGeneratorAdapter = new Pair<Long, ProgramComponentAdapter<Generator>>(loopId, adapter);

    return adapter;
}

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

/**
 * Unlike python, our temp zip file will be on disk instead of in memory. This avoids storing
 * potentially large files in memory which is not feasible with Android's limited heap space.
 * <p>//from  w  w  w  .j  a v a 2 s.c  o m
 * Notes:
 * <p>
 * - The maximum size of the changes zip is decided by the constant SYNC_ZIP_SIZE. If a media file exceeds this
 * limit, only that file (in full) will be zipped to be sent to the server.
 * <p>
 * - This method will be repeatedly called from MediaSyncer until there are no more files (marked "dirty" in the DB)
 * to send.
 * <p>
 * - Since AnkiDroid avoids scanning the media folder on every sync, it is possible for a file to be marked as a
 * new addition but actually have been deleted (e.g., with a file manager). In this case we skip over the file
 * and mark it as removed in the database. (This behaviour differs from the desktop client).
 * <p>
 */
public Pair<File, List<String>> mediaChangesZip() {
    File f = new File(mCol.getPath().replaceFirst("collection\\.anki2$", "tmpSyncToServer.zip"));
    Cursor cur = null;
    try {
        ZipOutputStream z = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
        z.setMethod(ZipOutputStream.DEFLATED);

        List<String> fnames = new ArrayList<String>();
        // meta is a list of (fname, zipname), where zipname of null is a deleted file
        // NOTE: In python, meta is a list of tuples that then gets serialized into json and added
        // to the zip as a string. In our version, we use JSON objects from the start to avoid the
        // serialization step. Instead of a list of tuples, we use JSONArrays of JSONArrays.
        JSONArray meta = new JSONArray();
        int sz = 0;
        byte buffer[] = new byte[2048];
        cur = mDb.getDatabase()
                .rawQuery("select fname, csum from media where dirty=1 limit " + Consts.SYNC_ZIP_COUNT, null);

        for (int c = 0; cur.moveToNext(); c++) {
            String fname = cur.getString(0);
            String csum = cur.getString(1);
            fnames.add(fname);
            String normname = HtmlUtil.nfcNormalized(fname);

            if (!TextUtils.isEmpty(csum)) {
                try {
                    mCol.log("+media zip " + fname);
                    File file = new File(dir(), fname);
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file), 2048);
                    z.putNextEntry(new ZipEntry(Integer.toString(c)));
                    int count = 0;
                    while ((count = bis.read(buffer, 0, 2048)) != -1) {
                        z.write(buffer, 0, count);
                    }
                    z.closeEntry();
                    bis.close();
                    meta.put(new JSONArray().put(normname).put(Integer.toString(c)));
                    sz += file.length();
                } catch (FileNotFoundException e) {
                    // A file has been marked as added but no longer exists in the media directory.
                    // Skip over it and mark it as removed in the db.
                    removeFile(fname);
                }
            } else {
                mCol.log("-media zip " + fname);
                meta.put(new JSONArray().put(normname).put(""));
            }
            if (sz >= Consts.SYNC_ZIP_SIZE) {
                break;
            }
        }

        z.putNextEntry(new ZipEntry("_meta"));
        z.write(Utils.jsonToString(meta).getBytes());
        z.closeEntry();
        z.close();
        // Don't leave lingering temp files if the VM terminates.
        f.deleteOnExit();
        return new Pair<File, List<String>>(f, fnames);
    } catch (IOException e) {
        Timber.e("Failed to create media changes zip", e);
        throw new RuntimeException(e);
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
}

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

public void testInvokeParametersEcho() throws Throwable {

    // Container to store callback's results and do the asserts.
    final ResultsContainer container = new ResultsContainer();
    final List<Pair<String, String>> parameters = new ArrayList<Pair<String, String>>();
    final List<String> parameterNames = new ArrayList<String>();

    for (int i = 0; i < 10; i++) {
        String name;//from  w  w w. jav a  2s . c o m

        do {
            name = UUID.randomUUID().toString();
        } while (parameterNames.contains(name));

        parameters.add(new Pair<String, String>(name, UUID.randomUUID().toString()));
        parameterNames.add(name);
    }

    MobileServiceClient client = null;
    try {
        client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext());

        client = client.withFilter(new HttpMetaEchoFilter());

        ServiceFilterResponse response = client.invokeApi("myApi", null, HttpPost.METHOD_NAME, null, parameters)
                .get();

        if (response == null || response.getContent() == null) {
            container.setException(new Exception("Expected response"));
        } else {
            container.setResponseValue(response.getContent());
        }

    } catch (Exception exception) {
        container.setException(exception);
    }

    // Asserts
    Exception exception = container.getException();
    if (exception != null) {
        fail(exception.getMessage());
    } else {
        JsonObject jResponse = (new JsonParser()).parse(container.getResponseValue()).getAsJsonObject();

        if (jResponse.has("parameters") && jResponse.get("parameters").isJsonObject()) {
            JsonObject jParameters = jResponse.getAsJsonObject("parameters");

            for (Pair<String, String> parameter : parameters) {
                if (jParameters.has(parameter.first)) {
                    assertEquals(parameter.second, jParameters.get(parameter.first).getAsString());
                } else {
                    fail("Expected parameter.");
                }
            }

        } else {
            fail("Expected parameters.");
        }
    }
}

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

/**
 * Undelete 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 ww  w.  java  2  s. co  m
public ListenableFuture<JsonObject> undelete(final JsonObject element, List<Pair<String, String>> parameters) {
    final SettableFuture<JsonObject> 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, "POST", 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.owncloud.android.services.OperationsService.java

/**
 * Creates a new operation, as described by operationIntent.
 * /*www. ja v  a2 s .c  o  m*/
 * TODO - move to ServiceHandler (probably)
 * 
 * @param operationIntent       Intent describing a new operation to queue and execute.
 * @return                      Pair with the new operation object and the information about its
 *                              target server.
 */
private Pair<Target, RemoteOperation> newOperation(Intent operationIntent) {
    RemoteOperation operation = null;
    Target target = null;
    try {
        if (!operationIntent.hasExtra(EXTRA_ACCOUNT) && !operationIntent.hasExtra(EXTRA_SERVER_URL)) {
            Log_OC.e(TAG, "Not enough information provided in intent");

        } else {
            Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
            String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
            String cookie = operationIntent.getStringExtra(EXTRA_COOKIE);
            target = new Target(account, (serverUrl == null) ? null : Uri.parse(serverUrl), cookie);

            String action = operationIntent.getAction();
            if (action.equals(ACTION_CREATE_SHARE_VIA_LINK)) { // Create public share via link

                String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);

                if (remotePath != null && remotePath.length() > 0) {

                    operation = new CreateShareViaLinkOperation(remotePath);

                    String name = operationIntent.getStringExtra(EXTRA_SHARE_NAME);
                    ((CreateShareViaLinkOperation) operation).setName(name);

                    String password = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD);
                    ((CreateShareViaLinkOperation) operation).setPassword(password);

                    long expirationDateMillis = operationIntent
                            .getLongExtra(EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS, 0);

                    ((CreateShareViaLinkOperation) operation).setExpirationDateInMillis(expirationDateMillis);

                    Boolean uploadToFolderPermission = operationIntent
                            .getBooleanExtra(EXTRA_SHARE_PUBLIC_UPLOAD, false);

                    ((CreateShareViaLinkOperation) operation).setPublicUpload(uploadToFolderPermission);

                    int permissions = operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS,
                            OCShare.DEFAULT_PERMISSION);

                    ((CreateShareViaLinkOperation) operation).setPermissions(permissions);
                }

            } else if (ACTION_UPDATE_SHARE_VIA_LINK.equals(action)) {
                long shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
                operation = new UpdateShareViaLinkOperation(shareId);

                String name = operationIntent.getStringExtra(EXTRA_SHARE_NAME);
                ((UpdateShareViaLinkOperation) operation).setName(name);

                String password = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD);
                ((UpdateShareViaLinkOperation) operation).setPassword(password);

                long expirationDate = operationIntent.getLongExtra(EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS, 0);
                ((UpdateShareViaLinkOperation) operation).setExpirationDate(expirationDate);

                if (operationIntent.hasExtra(EXTRA_SHARE_PUBLIC_UPLOAD)) {
                    ((UpdateShareViaLinkOperation) operation)
                            .setPublicUpload(operationIntent.getBooleanExtra(EXTRA_SHARE_PUBLIC_UPLOAD, false));
                }

                if (operationIntent.hasExtra(EXTRA_SHARE_PERMISSIONS)) {
                    ((UpdateShareViaLinkOperation) operation).setPermissions(
                            operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, OCShare.DEFAULT_PERMISSION));
                }

            } else if (ACTION_UPDATE_SHARE_WITH_SHAREE.equals(action)) {
                // Update private share, only permissions
                long shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
                operation = new UpdateSharePermissionsOperation(shareId);
                int permissions = operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, 1);
                ((UpdateSharePermissionsOperation) operation).setPermissions(permissions);

            } else if (action.equals(ACTION_CREATE_SHARE_WITH_SHAREE)) {
                // Create private share with user or group
                String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
                String shareeName = operationIntent.getStringExtra(EXTRA_SHARE_WITH);
                ShareType shareType = (ShareType) operationIntent.getSerializableExtra(EXTRA_SHARE_TYPE);
                int permissions = operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, -1);
                if (remotePath.length() > 0) {
                    operation = new CreateShareWithShareeOperation(remotePath, shareeName, shareType,
                            permissions);
                }

            } else if (action.equals(ACTION_UNSHARE)) { // Unshare file
                long shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
                operation = new RemoveShareOperation(shareId);

            } else if (action.equals(ACTION_GET_SERVER_INFO)) {
                // check OC server and get basic information from it
                operation = new GetServerInfoOperation(serverUrl, OperationsService.this);

            } else if (action.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN)) {
                // CREATE ACCESS TOKEN to the OAuth server
                String code = operationIntent.getStringExtra(EXTRA_OAUTH2_AUTHORIZATION_CODE);

                OAuth2Provider oAuth2Provider = OAuth2ProvidersRegistry.getInstance().getProvider();
                OAuth2RequestBuilder builder = oAuth2Provider.getOperationBuilder();
                builder.setGrantType(OAuth2GrantType.AUTHORIZATION_CODE);
                builder.setRequest(OAuth2RequestBuilder.OAuthRequest.CREATE_ACCESS_TOKEN);
                builder.setAuthorizationCode(code);

                operation = builder.buildOperation();

            } else if (action.equals(ACTION_GET_USER_NAME)) {
                // Get User Name
                operation = new GetRemoteUserInfoOperation();

            } else if (action.equals(ACTION_RENAME)) {
                // Rename file or folder
                String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
                String newName = operationIntent.getStringExtra(EXTRA_NEWNAME);
                operation = new RenameFileOperation(remotePath, newName);

            } else if (action.equals(ACTION_REMOVE)) {
                // Remove file or folder
                String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
                boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL, false);
                operation = new RemoveFileOperation(remotePath, onlyLocalCopy);

            } else if (action.equals(ACTION_CREATE_FOLDER)) {
                // Create Folder
                String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
                boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH, true);
                operation = new CreateFolderOperation(remotePath, createFullPath);

            } else if (action.equals(ACTION_SYNC_FILE)) {
                // Sync file
                String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
                operation = new SynchronizeFileOperation(remotePath, account, getApplicationContext());

            } else if (action.equals(ACTION_SYNC_FOLDER)) {
                // Sync folder (all its descendant files are sync'ed)
                String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
                boolean pushOnly = operationIntent.getBooleanExtra(EXTRA_PUSH_ONLY, false);
                boolean syncContentOfRegularFiles = operationIntent.getBooleanExtra(EXTRA_SYNC_REGULAR_FILES,
                        false);
                operation = new SynchronizeFolderOperation(this, // TODO remove this dependency from construction time
                        remotePath, account, System.currentTimeMillis(), // TODO remove this dependency from construction time
                        pushOnly, false, syncContentOfRegularFiles);

            } else if (action.equals(ACTION_MOVE_FILE)) {
                // Move file/folder
                String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
                String newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
                operation = new MoveFileOperation(remotePath, newParentPath);

            } else if (action.equals(ACTION_COPY_FILE)) {
                // Copy file/folder
                String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
                String newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
                operation = new CopyFileOperation(remotePath, newParentPath, account);

            } else if (action.equals(ACTION_CHECK_CURRENT_CREDENTIALS)) {
                // Check validity of currently stored credentials for a given account
                operation = new CheckCurrentCredentialsOperation(account);

            }
        }

    } catch (IllegalArgumentException e) {
        Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
        operation = null;
    }

    if (operation != null) {
        return new Pair<>(target, operation);
    } else {
        return null;
    }
}

From source file:com.saarang.samples.apps.iosched.ui.SessionDetailActivity.java

private void buildLinksSection(Cursor cursor) {
    // Compile list of links (I/O live link, submit feedback, and normal links)
    ViewGroup linkContainer = (ViewGroup) findViewById(com.saarang.samples.apps.iosched.R.id.links_container);
    linkContainer.removeAllViews();/*  w  w  w  . jav a2  s . co  m*/

    // Build links section
    // the Object can be either a string URL or an Intent
    List<Pair<Integer, Object>> links = new ArrayList<Pair<Integer, Object>>();

    long currentTimeMillis = UIUtils.getCurrentTime(this);
    if (mHasLivestream && currentTimeMillis > mSessionStart && currentTimeMillis <= mSessionEnd) {
        links.add(new Pair<Integer, Object>(com.saarang.samples.apps.iosched.R.string.session_link_livestream,
                getWatchLiveIntent(this)));
    }

    // Add session feedback link, if appropriate
    if (!mAlreadyGaveFeedback && currentTimeMillis > mSessionEnd - Config.FEEDBACK_MILLIS_BEFORE_SESSION_END) {
        links.add(new Pair<Integer, Object>(
                com.saarang.samples.apps.iosched.R.string.session_feedback_submitlink, getFeedbackIntent()));
    }

    for (int i = 0; i < SessionsQuery.LINKS_INDICES.length; i++) {
        final String linkUrl = cursor.getString(SessionsQuery.LINKS_INDICES[i]);
        if (TextUtils.isEmpty(linkUrl)) {
            continue;
        }

        links.add(new Pair<Integer, Object>(SessionsQuery.LINKS_TITLES[i],
                new Intent(Intent.ACTION_VIEW, Uri.parse(linkUrl))
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)));
    }

    // Render links
    if (links.size() > 0) {
        LayoutInflater inflater = LayoutInflater.from(this);
        int columns = getResources().getInteger(com.saarang.samples.apps.iosched.R.integer.links_columns);

        LinearLayout currentLinkRowView = null;
        for (int i = 0; i < links.size(); i++) {
            final Pair<Integer, Object> link = links.get(i);

            // Create link view
            TextView linkView = (TextView) inflater.inflate(
                    com.saarang.samples.apps.iosched.R.layout.list_item_session_link, linkContainer, false);
            if (link.first == com.saarang.samples.apps.iosched.R.string.session_feedback_submitlink) {
                mSubmitFeedbackView = linkView;
            }
            linkView.setText(getString(link.first));
            linkView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    fireLinkEvent(link.first);
                    Intent intent = null;
                    if (link.second instanceof Intent) {
                        intent = (Intent) link.second;
                    } else if (link.second instanceof String) {
                        intent = new Intent(Intent.ACTION_VIEW, Uri.parse((String) link.second))
                                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                    }
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException ignored) {
                    }
                }
            });

            // Place it inside a container
            if (columns == 1) {
                linkContainer.addView(linkView);
            } else {
                // create a new link row
                if (i % columns == 0) {
                    currentLinkRowView = (LinearLayout) inflater.inflate(
                            com.saarang.samples.apps.iosched.R.layout.include_link_row, linkContainer, false);
                    currentLinkRowView.setWeightSum(columns);
                    linkContainer.addView(currentLinkRowView);
                }

                ((LinearLayout.LayoutParams) linkView.getLayoutParams()).width = 0;
                ((LinearLayout.LayoutParams) linkView.getLayoutParams()).weight = 1;
                currentLinkRowView.addView(linkView);
            }
        }

        findViewById(com.saarang.samples.apps.iosched.R.id.session_links_header).setVisibility(View.VISIBLE);
        findViewById(com.saarang.samples.apps.iosched.R.id.links_container).setVisibility(View.VISIBLE);

    } else {
        findViewById(com.saarang.samples.apps.iosched.R.id.session_links_header).setVisibility(View.GONE);
        findViewById(com.saarang.samples.apps.iosched.R.id.links_container).setVisibility(View.GONE);
    }

}