Example usage for android.content ContentResolver openInputStream

List of usage examples for android.content ContentResolver openInputStream

Introduction

In this page you can find the example usage for android.content ContentResolver openInputStream.

Prototype

public final @Nullable InputStream openInputStream(@NonNull Uri uri) throws FileNotFoundException 

Source Link

Document

Open a stream on to the content associated with a content URI.

Usage

From source file:org.linkdroid.PostJob.java

/**
 * Posts the data to our webhook.// ww w  . j ava 2  s  .co m
 * 
 * The HMAC field calculation notes:
 * <ol>
 * <li>The Extras.HMAC field is calculated from all the non Extras.STREAM
 * fields; this includes all the original bundle extra fields, plus the
 * linkdroid fields (e.g Extras.STREAM_MIME_TYPE, and including
 * Extras.STREAM_HMAC); the NONCE is NOT prepended to the input since it will
 * be somewhere in the data bundle.</li>
 * <li>The Extras.STREAM_HMAC field is calculated by digesting the concat of
 * the NONCE (first) and the actual binary data obtained from the
 * EXTRAS_STREAM uri; this STREAM_HMAC field (along with the other
 * Extras.STREAM_* fields) are added to the data bundle, which will also be
 * hmac'd.</li>
 * <li>If no hmac secret is set, then the NONCEs will not be set in the upload
 * </li>
 * </ol>
 * 
 * @param contentResolver
 * @param webhook
 * @param data
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 */
public static void execute(ContentResolver contentResolver, Bundle webhook, Bundle data)
        throws UnsupportedEncodingException, IOException, InvalidKeyException, NoSuchAlgorithmException {

    // Set constants that may be used in this method.
    final String secret = webhook.getString(WebhookColumns.SECRET);

    // This is the multipart form object that will contain all the data bundle
    // extras; it also will include the data of the extra stream and any other
    // extra linkdroid specific field required.
    MultipartEntity entity = new MultipartEntity();

    // Do the calculations to create our nonce string, if necessary.
    String nonce = obtainNonce(webhook);

    // Add the nonce to the data bundle if we have it.
    if (nonce != null) {
        data.putString(Extras.NONCE, nonce);
    }

    // We have a stream of data, so we need to add that to the multipart form
    // upload with a possible HMAC.
    if (data.containsKey(Intent.EXTRA_STREAM)) {
        Uri mediaUri = (Uri) data.get(Intent.EXTRA_STREAM);

        // Open our mediaUri, base 64 encode it and add it to our multipart upload
        // entity.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Base64OutputStream b64os = new Base64OutputStream(baos);
        InputStream is = contentResolver.openInputStream(mediaUri);
        byte[] bytes = new byte[1024];
        int count;
        while ((count = is.read(bytes)) != -1) {
            b64os.write(bytes, 0, count);
        }
        is.close();
        baos.close();
        b64os.close();
        final String base64EncodedString = new String(baos.toByteArray(), UTF8);
        entity.addPart(Extras.STREAM, new StringBody(base64EncodedString, UTF8_CHARSET));

        // Add the mimetype of the stream to the data bundle.
        final String mimeType = contentResolver.getType(mediaUri);
        if (mimeType != null) {
            data.putString(Extras.STREAM_MIME_TYPE, mimeType);
        }

        // Do the hmac calculation of the stream and add it to the data bundle.
        // NOTE: This hmac string will be included as part of the input to the
        // other Extras hmac.
        if (shouldDoHmac(webhook)) {
            InputStream inputStream = contentResolver.openInputStream(mediaUri);
            final String streamHmac = hmacSha1(inputStream, secret, nonce);
            inputStream.close();
            data.putString(Extras.STREAM_HMAC, streamHmac);
            Log.d(TAG, "STREAM_HMAC: " + streamHmac);
        }
    }

    // Calculate the Hmac for all the items by iterating over the data bundle
    // keys in order.
    if (shouldDoHmac(webhook)) {
        final String dataHmac = calculateBundleExtrasHmac(data, secret);
        data.putString(Extras.HMAC, dataHmac);
        Log.d(TAG, "HMAC: " + dataHmac);
    }

    // Dump all the data bundle keys into the form.
    for (String k : data.keySet()) {
        Object value = data.get(k);
        // If the value is null, the key will still be in the form, but with
        // an empty string as its value.
        if (value != null) {
            entity.addPart(k, new StringBody(value.toString(), UTF8_CHARSET));
        } else {
            entity.addPart(k, new StringBody("", UTF8_CHARSET));
        }
    }

    // Create the client and request, then populate it with our multipart form
    // upload entity as part of the POST request; finally post the form.
    final String webhookUri = webhook.getString(WebhookColumns.URI);
    final HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(USER_AGENT_KEY, USER_AGENT);
    final HttpPost request = new HttpPost(webhookUri);
    request.setEntity(entity);
    HttpResponse response = client.execute(request);
    switch (response.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
        break;
    default:
        throw new RuntimeException(response.getStatusLine().toString());
    }
}

From source file:com.polyvi.xface.extension.contact.XContactsExt.java

/**
 *  URI?? content://, http://, file://.//from  w ww .  j ava2 s  .  co  m
 *
 * @param path
 *            
 * @return ?
 * @throws IOException
 */
private InputStream getDataStreamFromUri(String path) throws IOException {
    if (path.startsWith("content:")) {
        Uri uri = Uri.parse(path);
        ContentResolver resolver = getContext().getContentResolver();
        return resolver.openInputStream(uri);
    } else if (path.startsWith("http:") || path.startsWith("file:")) {
        URL url = new URL(path);
        return url.openStream();
    } else {
        return new FileInputStream(path);
    }
}

From source file:com.jefftharris.passwdsafe.file.PasswdFileUri.java

/** Load the password file */
public PwsFile load(StringBuilder passwd, Context context) throws NoSuchAlgorithmException, EndOfFileException,
        InvalidPassphraseException, IOException, UnsupportedFileVersionException {
    switch (itsType) {
    case FILE: {//  w  w w .  j  a  v a 2s  .co  m
        return PwsFileFactory.loadFile(itsFile.getAbsolutePath(), passwd);
    }
    case SYNC_PROVIDER: {
        ContentResolver cr = context.getContentResolver();
        InputStream is = cr.openInputStream(itsUri);
        String id = getIdentifier(context, false);
        PwsStorage storage = new PasswdFileSyncStorage(itsUri, id, is);
        return PwsFileFactory.loadFromStorage(storage, passwd);
    }
    case EMAIL:
    case GENERIC_PROVIDER: {
        ContentResolver cr = context.getContentResolver();
        InputStream is = cr.openInputStream(itsUri);
        String id = getIdentifier(context, false);
        PwsStorage storage;
        if (itsWritableInfo.first) {
            storage = new PasswdFileGenProviderStorage(itsUri, id, is);
        } else {
            storage = new PwsStreamStorage(id, is);
        }
        return PwsFileFactory.loadFromStorage(storage, passwd);
    }
    }
    return null;
}

From source file:net.tjado.passwdsafe.file.PasswdFileUri.java

/** Load the password file */
public PwsFile load(Owner<PwsPassword>.Param passwd, Context context)
        throws EndOfFileException, InvalidPassphraseException, IOException, UnsupportedFileVersionException {
    switch (itsType) {
    case FILE: {// w w w . java 2 s.c o m
        return PwsFileFactory.loadFile(itsFile.getAbsolutePath(), passwd);
    }
    case SYNC_PROVIDER: {
        ContentResolver cr = context.getContentResolver();
        InputStream is = cr.openInputStream(itsUri);
        String id = getIdentifier(context, false);
        PwsStorage storage = new PasswdFileSyncStorage(itsUri, id, is);
        return PwsFileFactory.loadFromStorage(storage, passwd);
    }
    case EMAIL:
    case GENERIC_PROVIDER: {
        ContentResolver cr = context.getContentResolver();
        InputStream is = cr.openInputStream(itsUri);
        String id = getIdentifier(context, false);
        PwsStorage storage;
        if (itsWritableInfo.first) {
            storage = new PasswdFileGenProviderStorage(itsUri, id, is);
        } else {
            storage = new PwsStreamStorage(id, is);
        }
        return PwsFileFactory.loadFromStorage(storage, passwd);
    }
    }
    return null;
}

From source file:org.skt.runtime.original.CameraLauncher.java

/**
 * Called when the camera view exits. //from  www.  j  ava2 s .com
 * 
 * @param requestCode       The request code originally supplied to startActivityForResult(), 
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // Create an ExifHelper to save the exif data that is lost during compression
    ExifHelper exif = new ExifHelper();
    try {
        if (this.encodingType == JPEG) {
            exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx.getContext()) + "/Pic.jpg");
            exif.readExifData();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    // If CAMERA
    if (srcType == CAMERA) {
        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Read in bitmap of captured image
                Bitmap bitmap;
                try {
                    bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(),
                            imageUri);
                } catch (FileNotFoundException e) {
                    Uri uri = intent.getData();
                    android.content.ContentResolver resolver = this.ctx.getContentResolver();
                    bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
                }

                bitmap = scaleBitmap(bitmap);

                // If sending base64 image back
                if (destType == DATA_URL) {
                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    // Create entry in media store for image
                    // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
                    ContentValues values = new ContentValues();
                    values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                    Uri uri = null;
                    try {
                        uri = this.ctx.getContentResolver()
                                .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                    } catch (UnsupportedOperationException e) {
                        LOG.d(LOG_TAG, "Can't write to external media storage.");
                        try {
                            uri = this.ctx.getContentResolver().insert(
                                    android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                        } catch (UnsupportedOperationException ex) {
                            LOG.d(LOG_TAG, "Can't write to internal media storage.");
                            this.failPicture("Error capturing image - no media storage found.");
                            return;
                        }
                    }

                    // Add compressed version of captured image to returned media store Uri
                    OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                    os.close();

                    // Restore exif data to file
                    if (this.encodingType == JPEG) {
                        exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
                        exif.writeExifData();
                    }

                    // Send Uri back to JavaScript for viewing image
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                }
                bitmap.recycle();
                bitmap = null;
                System.gc();

                checkForDuplicateImage(FILE_URI);
            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();
            android.content.ContentResolver resolver = this.ctx.getContentResolver();

            // If you ask for video or all media type you will automatically get back a file URI 
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
            } else {
                // If sending base64 image back
                if (destType == DATA_URL) {
                    try {
                        Bitmap bitmap = android.graphics.BitmapFactory
                                .decodeStream(resolver.openInputStream(uri));
                        String[] cols = { MediaStore.Images.Media.ORIENTATION };
                        Cursor cursor = this.ctx.getContentResolver().query(intent.getData(), cols, null, null,
                                null);
                        if (cursor != null) {
                            cursor.moveToPosition(0);
                            rotate = cursor.getInt(0);
                            cursor.close();
                        }
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            matrix.setRotate(rotate);
                            bitmap = bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                        }
                        bitmap = scaleBitmap(bitmap);
                        this.processPicture(bitmap);
                        bitmap.recycle();
                        bitmap = null;
                        System.gc();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                        this.failPicture("Error retrieving image.");
                    }
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    // Do we need to scale the returned file
                    if (this.targetHeight > 0 && this.targetWidth > 0) {
                        try {
                            Bitmap bitmap = android.graphics.BitmapFactory
                                    .decodeStream(resolver.openInputStream(uri));
                            bitmap = scaleBitmap(bitmap);

                            String fileName = DirectoryManager.getTempDirectoryPath(ctx.getContext())
                                    + "/resize.jpg";
                            OutputStream os = new FileOutputStream(fileName);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                            os.close();

                            // Restore exif data to file
                            if (this.encodingType == JPEG) {
                                exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
                                exif.writeExifData();
                            }

                            bitmap.recycle();
                            bitmap = null;

                            // The resized image is cached by the app in order to get around this and not have to delete you 
                            // application cache I'm adding the current system time to the end of the file url.
                            this.success(
                                    new PluginResult(PluginResult.Status.OK,
                                            ("file://" + fileName + "?" + System.currentTimeMillis())),
                                    this.callbackId);
                            System.gc();
                        } catch (Exception e) {
                            e.printStackTrace();
                            this.failPicture("Error retrieving image.");
                        }
                    } else {
                        this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                    }
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:net.sourceforge.fidocadj.FidoMain.java

/** Inspired from
           //  w w  w  .ja  v a  2 s.  c  o m
   http://richardleggett.co.uk/blog/2013/01/26/
   registering_for_file_types_in_android/
           
   detects if in the data there is a file indication, open it and
   load its contents.
   @return true if something has been loaded, false otherwise
*/
private boolean importData(Uri data) {
    final String scheme = data.getScheme();
    // Check wether there is a file in the data provided.
    if (ContentResolver.SCHEME_FILE.equals(scheme)) {
        try {
            ContentResolver cr = getContentResolver();
            InputStream is = cr.openInputStream(data);
            if (is == null)
                return false;

            // Read the contents of the file.
            StringBuffer buf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String str;
            if (is != null) {
                while ((str = reader.readLine()) != null) {
                    buf.append(str + "\n");
                }
            }
            is.close();
            return true;
        } catch (Exception e) {
            Log.e("fidocadj", "FidoMain.ImportData, Error reading file: " + e.toString());
        }
    }
    return false;
}

From source file:com.polyvi.xface.extension.camera.XCameraExt.java

private void cameraSucess(Intent intent) {
    try {// w  w  w  .j a va 2 s  . c  o m
        Bitmap bitmap = null;
        try {
            //???imagebitmap
            if (mAllowEdit) {
                //??????Android???
                //???URI
                Bundle extras = intent.getExtras();
                if (extras != null) {
                    bitmap = extras.getParcelable("data");
                }

                //?????URI
                if ((bitmap == null) || (extras == null)) {
                    bitmap = getCroppedBitmap(intent);
                }
            } else { // ????
                bitmap = android.provider.MediaStore.Images.Media.getBitmap(getContext().getContentResolver(),
                        mImageUri);
            }
        } catch (FileNotFoundException e) {
            Uri uri = intent.getData();
            android.content.ContentResolver resolver = getContext().getContentResolver();
            bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
        } catch (IOException e) {
            mCallbackCtx.error("Can't open image");
        } catch (OutOfMemoryError e) {
            XNotification notification = new XNotification(mExtensionContext.getSystemContext());
            notification.alert("Size of Image is too large!", "Save Image Error", "OK", null, DURATION);
            mCallbackCtx.error("Size of image is too large");
            return;
        }

        // ???
        Bitmap scaleBitmap = scaleBitmap(bitmap);
        Uri uri = null;
        if (mDestType == DATA_URL) {
            processPicture(scaleBitmap);
            checkForDuplicateImage(DATA_URL);
        } else if (mDestType == FILE_URI || mDestType == NATIVE_URI) {
            if (!this.mSaveToPhotoAlbum) {
                String suffixName = null;
                if (mEncodingType == JPEG) {
                    suffixName = ".jpg";
                } else if (mEncodingType == PNG) {
                    suffixName = ".png";
                } else {
                    throw new IllegalArgumentException("Invalid Encoding Type: " + mEncodingType);
                }
                String photoName = System.currentTimeMillis() + suffixName;
                uri = Uri.fromFile(new File(mWebContext.getWorkSpace(), photoName));
            } else {
                uri = getUriFromMediaStore();
            }
            if (uri == null) {
                mCallbackCtx.error("Error capturing image - no media storage found.");
            }

            // ?
            OutputStream os = getContext().getContentResolver().openOutputStream(uri);
            scaleBitmap.compress(Bitmap.CompressFormat.JPEG, mQuality, os);
            os.close();

            // ??success callback
            XPathResolver pathResolver = new XPathResolver(uri.toString(), "", getContext());
            mCallbackCtx.success(XConstant.FILE_SCHEME + pathResolver.resolve());
        }
        scaleBitmap.recycle();
        scaleBitmap = null;
        cleanup(FILE_URI, mImageUri, uri, bitmap);
    } catch (IOException e) {
        mCallbackCtx.error("Error capturing image.");
    }
}

From source file:com.wiret.arbrowser.AbstractArchitectCamActivity.java

/**
 * loads poiInformation and returns them as JSONArray. Ensure attributeNames of JSON POIs are well known in JavaScript, so you can parse them easily
 * @param userLocation the location of the user
 * @return POI information in JSONArray/*from www. j a  v a2s  .com*/
 */
public JSONArray getPoiInformation(final Location userLocation, String kmlPath) {

    if (userLocation == null) {
        return null;
    }

    ArrayList<KmlParser.Place> places = new ArrayList<>();
    try {
        ContentResolver cr = getApplicationContext().getContentResolver();
        InputStream is = cr.openInputStream(Uri.fromFile(new File(kmlPath)));
        places = new KmlParser().parse(is);
    } catch (final Exception e) {
        AbstractArchitectCamActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(AbstractArchitectCamActivity.this, "Invalid kml file \n" + e.getMessage(),
                        Toast.LENGTH_LONG).show();
            }
        });
    }

    final JSONArray pois = new JSONArray();

    // ensure these attributes are also used in JavaScript when extracting POI data
    final String ATTR_ID = "id";
    final String ATTR_NAME = "name";
    final String ATTR_DESCRIPTION = "description";
    final String ATTR_LATITUDE = "latitude";
    final String ATTR_LONGITUDE = "longitude";
    final String ATTR_ALTITUDE = "altitude";
    //ArrayList<KmlParser.Place> places = getIntent().getExtras().getParcelableArrayList("places");
    for (KmlParser.Place place : places) {
        final HashMap<String, String> poiInformation = new HashMap<String, String>();
        poiInformation.put(ATTR_ID, "1");
        poiInformation.put(ATTR_NAME, place.name);
        poiInformation.put(ATTR_DESCRIPTION, place.description != null ? place.description : "");
        //double[] poiLocationLatLon = getRandomLatLonNearby(userLocation.getLatitude(), userLocation.getLongitude());
        poiInformation.put(ATTR_LATITUDE, place.lat);
        poiInformation.put(ATTR_LONGITUDE, place.lon);
        final float UNKNOWN_ALTITUDE = -32768f; // equals "AR.CONST.UNKNOWN_ALTITUDE" in JavaScript (compare AR.GeoLocation specification)
        // Use "AR.CONST.UNKNOWN_ALTITUDE" to tell ARchitect that altitude of places should be on user level. Be aware to handle altitude properly in locationManager in case you use valid POI altitude value (e.g. pass altitude only if GPS accuracy is <7m).
        poiInformation.put(ATTR_ALTITUDE, String.valueOf(UNKNOWN_ALTITUDE));
        pois.put(new JSONObject(poiInformation));
    }

    return pois;
}

From source file:org.exoplatform.utils.ExoDocumentUtils.java

/**
 * Gets a DocumentInfo with info coming from the document at the given URI.
 * //from www  .j a  v  a 2  s .com
 * @param contentUri the content URI of the document (content:// ...)
 * @param context
 * @return a DocumentInfo or null if an error occurs
 */
public static DocumentInfo documentFromContentUri(Uri contentUri, Context context) {
    if (contentUri == null)
        return null;

    try {
        ContentResolver cr = context.getContentResolver();
        Cursor c = cr.query(contentUri, null, null, null, null);
        int sizeIndex = c.getColumnIndex(OpenableColumns.SIZE);
        int nameIndex = c.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int orientIndex = c.getColumnIndex(MediaStore.Images.ImageColumns.ORIENTATION);
        c.moveToFirst();

        DocumentInfo document = new DocumentInfo();
        document.documentName = c.getString(nameIndex);
        document.documentSizeKb = c.getLong(sizeIndex) / 1024;
        document.documentData = cr.openInputStream(contentUri);
        document.documentMimeType = cr.getType(contentUri);
        if (orientIndex != -1) { // if found orientation column
            document.orientationAngle = c.getInt(orientIndex);
        }
        return document;
    } catch (FileNotFoundException e) {
        Log.d(LOG_TAG, e.getClass().getSimpleName(), e.getLocalizedMessage());
    } catch (Exception e) {
        Log.e(LOG_TAG, "Cannot retrieve the content at " + contentUri);
        if (Log.LOGD)
            Log.d(LOG_TAG, e.getMessage() + "\n" + Log.getStackTraceString(e));
    }
    return null;
}

From source file:com.amaze.filemanager.utils.files.GenericCopyUtil.java

/**
 * Starts copy of file/*  w w  w. j a  va  2  s .  c o  m*/
 * Supports : {@link File}, {@link jcifs.smb.SmbFile}, {@link DocumentFile}, {@link CloudStorage}
 * @param lowOnMemory defines whether system is running low on memory, in which case we'll switch to
 *                    using streams instead of channel which maps the who buffer in memory.
 *                    TODO: Use buffers even on low memory but don't map the whole file to memory but
 *                          parts of it, and transfer each part instead.
 */
private void startCopy(boolean lowOnMemory) throws IOException {

    FileInputStream inputStream = null;
    FileOutputStream outputStream = null;
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    BufferedInputStream bufferedInputStream = null;
    BufferedOutputStream bufferedOutputStream = null;

    try {

        // initializing the input channels based on file types
        if (mSourceFile.isOtgFile()) {
            // source is in otg
            ContentResolver contentResolver = mContext.getContentResolver();
            DocumentFile documentSourceFile = OTGUtil.getDocumentFile(mSourceFile.getPath(), mContext, false);

            bufferedInputStream = new BufferedInputStream(
                    contentResolver.openInputStream(documentSourceFile.getUri()), DEFAULT_BUFFER_SIZE);
        } else if (mSourceFile.isSmb()) {

            // source is in smb
            bufferedInputStream = new BufferedInputStream(mSourceFile.getInputStream(), DEFAULT_BUFFER_SIZE);
        } else if (mSourceFile.isSftp()) {
            bufferedInputStream = new BufferedInputStream(mSourceFile.getInputStream(mContext),
                    DEFAULT_BUFFER_SIZE);
        } else if (mSourceFile.isDropBoxFile()) {

            CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
            bufferedInputStream = new BufferedInputStream(
                    cloudStorageDropbox.download(CloudUtil.stripPath(OpenMode.DROPBOX, mSourceFile.getPath())));
        } else if (mSourceFile.isBoxFile()) {

            CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
            bufferedInputStream = new BufferedInputStream(
                    cloudStorageBox.download(CloudUtil.stripPath(OpenMode.BOX, mSourceFile.getPath())));
        } else if (mSourceFile.isGoogleDriveFile()) {

            CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
            bufferedInputStream = new BufferedInputStream(
                    cloudStorageGdrive.download(CloudUtil.stripPath(OpenMode.GDRIVE, mSourceFile.getPath())));
        } else if (mSourceFile.isOneDriveFile()) {

            CloudStorage cloudStorageOnedrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
            bufferedInputStream = new BufferedInputStream(cloudStorageOnedrive
                    .download(CloudUtil.stripPath(OpenMode.ONEDRIVE, mSourceFile.getPath())));
        } else {

            // source file is neither smb nor otg; getting a channel from direct file instead of stream
            File file = new File(mSourceFile.getPath());
            if (FileUtil.isReadable(file)) {

                if (mTargetFile.isOneDriveFile() || mTargetFile.isDropBoxFile()
                        || mTargetFile.isGoogleDriveFile() || mTargetFile.isBoxFile() || lowOnMemory) {
                    // our target is cloud, we need a stream not channel
                    bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
                } else {

                    inChannel = new RandomAccessFile(file, "r").getChannel();
                }
            } else {
                ContentResolver contentResolver = mContext.getContentResolver();
                DocumentFile documentSourceFile = FileUtil.getDocumentFile(file, mSourceFile.isDirectory(),
                        mContext);

                bufferedInputStream = new BufferedInputStream(
                        contentResolver.openInputStream(documentSourceFile.getUri()), DEFAULT_BUFFER_SIZE);
            }
        }

        // initializing the output channels based on file types
        if (mTargetFile.isOtgFile()) {

            // target in OTG, obtain streams from DocumentFile Uri's

            ContentResolver contentResolver = mContext.getContentResolver();
            DocumentFile documentTargetFile = OTGUtil.getDocumentFile(mTargetFile.getPath(), mContext, true);

            bufferedOutputStream = new BufferedOutputStream(
                    contentResolver.openOutputStream(documentTargetFile.getUri()), DEFAULT_BUFFER_SIZE);
        } else if (mTargetFile.isSftp()) {
            bufferedOutputStream = new BufferedOutputStream(mTargetFile.getOutputStream(mContext),
                    DEFAULT_BUFFER_SIZE);
        } else if (mTargetFile.isSmb()) {

            bufferedOutputStream = new BufferedOutputStream(mTargetFile.getOutputStream(mContext),
                    DEFAULT_BUFFER_SIZE);
        } else if (mTargetFile.isDropBoxFile()) {
            // API doesn't support output stream, we'll upload the file directly
            CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);

            if (mSourceFile.isDropBoxFile()) {
                // we're in the same provider, use api method
                cloudStorageDropbox.copy(CloudUtil.stripPath(OpenMode.DROPBOX, mSourceFile.getPath()),
                        CloudUtil.stripPath(OpenMode.DROPBOX, mTargetFile.getPath()));
                return;
            } else {
                cloudStorageDropbox.upload(CloudUtil.stripPath(OpenMode.DROPBOX, mTargetFile.getPath()),
                        bufferedInputStream, mSourceFile.getSize(), true);
                return;
            }
        } else if (mTargetFile.isBoxFile()) {
            // API doesn't support output stream, we'll upload the file directly
            CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);

            if (mSourceFile.isBoxFile()) {
                // we're in the same provider, use api method
                cloudStorageBox.copy(CloudUtil.stripPath(OpenMode.BOX, mSourceFile.getPath()),
                        CloudUtil.stripPath(OpenMode.BOX, mTargetFile.getPath()));
                return;
            } else {
                cloudStorageBox.upload(CloudUtil.stripPath(OpenMode.BOX, mTargetFile.getPath()),
                        bufferedInputStream, mSourceFile.getSize(), true);
                bufferedInputStream.close();
                return;
            }
        } else if (mTargetFile.isGoogleDriveFile()) {
            // API doesn't support output stream, we'll upload the file directly
            CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);

            if (mSourceFile.isGoogleDriveFile()) {
                // we're in the same provider, use api method
                cloudStorageGdrive.copy(CloudUtil.stripPath(OpenMode.GDRIVE, mSourceFile.getPath()),
                        CloudUtil.stripPath(OpenMode.GDRIVE, mTargetFile.getPath()));
                return;
            } else {
                cloudStorageGdrive.upload(CloudUtil.stripPath(OpenMode.GDRIVE, mTargetFile.getPath()),
                        bufferedInputStream, mSourceFile.getSize(), true);
                bufferedInputStream.close();
                return;
            }
        } else if (mTargetFile.isOneDriveFile()) {
            // API doesn't support output stream, we'll upload the file directly
            CloudStorage cloudStorageOnedrive = dataUtils.getAccount(OpenMode.ONEDRIVE);

            if (mSourceFile.isOneDriveFile()) {
                // we're in the same provider, use api method
                cloudStorageOnedrive.copy(CloudUtil.stripPath(OpenMode.ONEDRIVE, mSourceFile.getPath()),
                        CloudUtil.stripPath(OpenMode.ONEDRIVE, mTargetFile.getPath()));
                return;
            } else {
                cloudStorageOnedrive.upload(CloudUtil.stripPath(OpenMode.ONEDRIVE, mTargetFile.getPath()),
                        bufferedInputStream, mSourceFile.getSize(), true);
                bufferedInputStream.close();
                return;
            }
        } else {
            // copying normal file, target not in OTG
            File file = new File(mTargetFile.getPath());
            if (FileUtil.isWritable(file)) {

                if (lowOnMemory) {
                    bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
                } else {

                    outChannel = new RandomAccessFile(file, "rw").getChannel();
                }
            } else {
                ContentResolver contentResolver = mContext.getContentResolver();
                DocumentFile documentTargetFile = FileUtil.getDocumentFile(file, mTargetFile.isDirectory(),
                        mContext);

                bufferedOutputStream = new BufferedOutputStream(
                        contentResolver.openOutputStream(documentTargetFile.getUri()), DEFAULT_BUFFER_SIZE);
            }
        }

        if (bufferedInputStream != null) {
            if (bufferedOutputStream != null)
                copyFile(bufferedInputStream, bufferedOutputStream);
            else if (outChannel != null) {
                copyFile(bufferedInputStream, outChannel);
            }
        } else if (inChannel != null) {
            if (bufferedOutputStream != null)
                copyFile(inChannel, bufferedOutputStream);
            else if (outChannel != null)
                copyFile(inChannel, outChannel);
        }

    } catch (IOException e) {
        e.printStackTrace();
        Log.d(getClass().getSimpleName(), "I/O Error!");
        throw new IOException();
    } catch (OutOfMemoryError e) {
        e.printStackTrace();

        // we ran out of memory to map the whole channel, let's switch to streams
        AppConfig.toast(mContext, mContext.getString(R.string.copy_low_memory));

        startCopy(true);
    } finally {

        try {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
            if (inputStream != null)
                inputStream.close();
            if (outputStream != null)
                outputStream.close();
            if (bufferedInputStream != null)
                bufferedInputStream.close();
            if (bufferedOutputStream != null)
                bufferedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            // failure in closing stream
        }

        //If target file is copied onto the device and copy was successful, trigger media store
        //rescan

        if ((mTargetFile.isLocal() || mTargetFile.isOtgFile()) && mTargetFile.exists(mContext)) {

            DocumentFile documentFile = FileUtil.getDocumentFile(mTargetFile.getFile(), false, mContext);
            //If FileUtil.getDocumentFile() returns null, fall back to DocumentFile.fromFile()
            if (documentFile == null)
                documentFile = DocumentFile.fromFile(mTargetFile.getFile());

            FileUtils.scanFile(documentFile.getUri(), mContext);
        }
    }
}