Example usage for android.os ParcelFileDescriptor getFileDescriptor

List of usage examples for android.os ParcelFileDescriptor getFileDescriptor

Introduction

In this page you can find the example usage for android.os ParcelFileDescriptor getFileDescriptor.

Prototype

public FileDescriptor getFileDescriptor() 

Source Link

Document

Retrieve the actual FileDescriptor associated with this object.

Usage

From source file:com.stfalcon.contentmanager.ContentManager.java

protected String getFileFromContentProvider(String uri) {

    BufferedInputStream inputStream = null;
    BufferedOutputStream outStream = null;
    ParcelFileDescriptor parcelFileDescriptor = null;
    try {//from w ww  . ja v  a 2 s.c  om
        String localFilePath = generateFileName(uri);
        parcelFileDescriptor = activity.getContentResolver().openFileDescriptor(Uri.parse(uri), "r");

        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

        inputStream = new BufferedInputStream(new FileInputStream(fileDescriptor));
        BufferedInputStream reader = new BufferedInputStream(inputStream);

        outStream = new BufferedOutputStream(new FileOutputStream(localFilePath));
        byte[] buf = new byte[2048];
        int len;
        while ((len = reader.read(buf)) > 0) {
            outStream.write(buf, 0, len);
        }
        outStream.flush();
        uri = localFilePath;
    } catch (IOException e) {
        return uri;
    } finally {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            try {
                parcelFileDescriptor.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            outStream.flush();
            outStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return uri;
}

From source file:com.awrtechnologies.carbudgetsales.MainActivity.java

public String getRealPathFromURIUpdated(Context context, Uri contentUri) {

    ParcelFileDescriptor parcelFileDescriptor;
    String path = "";
    try {//from  www .j  a  v  a  2s.co m
        parcelFileDescriptor = getContentResolver().openFileDescriptor(contentUri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        path = getImagePath(contentUri);
        parcelFileDescriptor.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return path;
}

From source file:im.vector.activity.RoomActivity.java

private void writeMediaUrl(Uri destUri) {
    try {/* ww  w.  ja va 2  s.c  o m*/
        ParcelFileDescriptor pfd = this.getContentResolver().openFileDescriptor(destUri, "w");

        FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());

        File sourceFile = mMediasCache.mediaCacheFile(mPendingMediaUrl, mPendingMimeType);

        FileInputStream inputStream = new FileInputStream(sourceFile);

        byte[] buffer = new byte[1024 * 10];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, len);
        }

        fileOutputStream.close();
        pfd.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.drrickorang.loopback.LoopbackActivity.java

/** Save a screenshot of the main activity. */
void saveScreenShot(Uri uri) {
    ParcelFileDescriptor parcelFileDescriptor = null;
    FileOutputStream outputStream;
    try {/*from  w  w w .  j av a2  s  .c om*/
        parcelFileDescriptor = getApplicationContext().getContentResolver().openFileDescriptor(uri, "w");

        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        outputStream = new FileOutputStream(fileDescriptor);

        log("Done creating output stream");

        LinearLayout LL = (LinearLayout) findViewById(R.id.linearLayoutMain);

        View v = LL.getRootView();
        v.setDrawingCacheEnabled(true);
        Bitmap b = v.getDrawingCache();

        //save
        b.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        parcelFileDescriptor.close();
        v.setDrawingCacheEnabled(false);
    } catch (Exception e) {
        log("Failed to open png file " + e);
    } finally {
        try {
            if (parcelFileDescriptor != null) {
                parcelFileDescriptor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log("Error closing ParcelFile Descriptor");
        }
    }
}

From source file:org.drrickorang.loopback.LoopbackActivity.java

/**
 * Save a .txt file of the given buffer period's data.
 * First column is time, second column is count.
 *//*from  w  ww. ja  va  2s .com*/
void saveBufferPeriod(Uri uri, int[] bufferPeriodArray, int maxBufferPeriod) {
    ParcelFileDescriptor parcelFileDescriptor = null;
    FileOutputStream outputStream;
    if (bufferPeriodArray != null) {
        try {
            parcelFileDescriptor = getApplicationContext().getContentResolver().openFileDescriptor(uri, "w");

            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            outputStream = new FileOutputStream(fileDescriptor);
            log("Done creating output stream for saving buffer period");

            int usefulDataRange = Math.min(maxBufferPeriod + 1, bufferPeriodArray.length);
            int[] usefulBufferData = Arrays.copyOfRange(bufferPeriodArray, 0, usefulDataRange);

            String endline = "\n";
            String tab = "\t";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < usefulBufferData.length; i++) {
                sb.append(i + tab + usefulBufferData[i] + endline);
            }

            outputStream.write(sb.toString().getBytes());
            parcelFileDescriptor.close();

        } catch (Exception e) {
            log("Failed to open text file " + e);
        } finally {
            try {
                if (parcelFileDescriptor != null) {
                    parcelFileDescriptor.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                log("Error closing ParcelFile Descriptor");
            }
        }
    }

}

From source file:org.drrickorang.loopback.LoopbackActivity.java

/** Save a .txt file of various test results. */
void saveReport(Uri uri) {
    ParcelFileDescriptor parcelFileDescriptor = null;
    FileOutputStream outputStream;
    try {/* ww  w.  j  ava  2  s  .c o m*/
        parcelFileDescriptor = getApplicationContext().getContentResolver().openFileDescriptor(uri, "w");

        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        outputStream = new FileOutputStream(fileDescriptor);

        log("Done creating output stream");

        String endline = "\n";
        final int stringLength = 300;
        StringBuilder sb = new StringBuilder(stringLength);
        sb.append("DateTime = " + mCurrentTime + endline);
        sb.append(INTENT_SAMPLING_FREQUENCY + " = " + getApp().getSamplingRate() + endline);
        sb.append(INTENT_RECORDER_BUFFER + " = "
                + getApp().getRecorderBufferSizeInBytes() / Constant.BYTES_PER_FRAME + endline);
        sb.append(INTENT_PLAYER_BUFFER + " = "
                + getApp().getPlayerBufferSizeInBytes() / Constant.BYTES_PER_FRAME + endline);
        sb.append(INTENT_AUDIO_THREAD + " = " + getApp().getAudioThreadType() + endline);
        int micSource = getApp().getMicSource();

        String audioType = "unknown";
        switch (getApp().getAudioThreadType()) {
        case Constant.AUDIO_THREAD_TYPE_JAVA:
            audioType = "JAVA";
            break;
        case Constant.AUDIO_THREAD_TYPE_NATIVE:
            audioType = "NATIVE";
            break;
        }
        sb.append(INTENT_AUDIO_THREAD + "_String = " + audioType + endline);

        sb.append(INTENT_MIC_SOURCE + " = " + micSource + endline);
        sb.append(INTENT_MIC_SOURCE + "_String = " + getApp().getMicSourceString(micSource) + endline);
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        sb.append(INTENT_AUDIO_LEVEL + " = " + currentVolume + endline);

        switch (mTestType) {
        case Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_LATENCY:
            if (mCorrelation.mEstimatedLatencyMs > 0.0001) {
                sb.append(String.format("LatencyMs = %.2f", mCorrelation.mEstimatedLatencyMs) + endline);
            } else {
                sb.append(String.format("LatencyMs = unknown") + endline);
            }

            sb.append(String.format("LatencyConfidence = %.2f", mCorrelation.mEstimatedLatencyConfidence)
                    + endline);
            break;
        case Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_BUFFER_PERIOD:
            sb.append("Buffer Test Duration (s) = " + mBufferTestDuration + endline);

            // report expected recorder buffer period
            int expectedRecorderBufferPeriod = mRecorderBufferSizeInBytes / Constant.BYTES_PER_FRAME
                    * Constant.MILLIS_PER_SECOND / mSamplingRate;
            sb.append("Expected Recorder Buffer Period (ms) = " + expectedRecorderBufferPeriod + endline);

            // report recorder results
            int recorderBufferSize = mRecorderBufferSizeInBytes / Constant.BYTES_PER_FRAME;
            int[] recorderBufferData = null;
            int recorderBufferDataMax = 0;
            switch (mAudioThreadType) {
            case Constant.AUDIO_THREAD_TYPE_JAVA:
                recorderBufferData = mRecorderBufferPeriod.getBufferPeriodArray();
                recorderBufferDataMax = mRecorderBufferPeriod.getMaxBufferPeriod();
                break;
            case Constant.AUDIO_THREAD_TYPE_NATIVE:
                recorderBufferData = mNativeRecorderBufferPeriodArray;
                recorderBufferDataMax = mNativeRecorderMaxBufferPeriod;
                break;
            }
            if (recorderBufferData != null) {
                // this is the range of data that actually has values
                int usefulDataRange = Math.min(recorderBufferDataMax + 1, recorderBufferData.length);
                int[] usefulBufferData = Arrays.copyOfRange(recorderBufferData, 0, usefulDataRange);
                PerformanceMeasurement measurement = new PerformanceMeasurement(recorderBufferSize,
                        mSamplingRate, usefulBufferData);
                boolean isBufferSizesMismatch = measurement.determineIsBufferSizesMatch();
                double benchmark = measurement.computeWeightedBenchmark();
                int outliers = measurement.countOutliers();
                sb.append("Recorder Buffer Sizes Mismatch = " + isBufferSizesMismatch + endline);
                sb.append("Recorder Benchmark = " + benchmark + endline);
                sb.append("Recorder Number of Outliers = " + outliers + endline);
            } else {
                sb.append("Cannot Find Recorder Buffer Period Data!" + endline);
            }

            // report player results
            int playerBufferSize = mPlayerBufferSizeInBytes / Constant.BYTES_PER_FRAME;
            int[] playerBufferData = null;
            int playerBufferDataMax = 0;
            switch (mAudioThreadType) {
            case Constant.AUDIO_THREAD_TYPE_JAVA:
                playerBufferData = mPlayerBufferPeriod.getBufferPeriodArray();
                playerBufferDataMax = mPlayerBufferPeriod.getMaxBufferPeriod();
                break;
            case Constant.AUDIO_THREAD_TYPE_NATIVE:
                playerBufferData = mNativePlayerBufferPeriodArray;
                playerBufferDataMax = mNativePlayerMaxBufferPeriod;
                break;
            }
            if (playerBufferData != null) {
                // this is the range of data that actually has values
                int usefulDataRange = Math.min(playerBufferDataMax + 1, playerBufferData.length);
                int[] usefulBufferData = Arrays.copyOfRange(playerBufferData, 0, usefulDataRange);
                PerformanceMeasurement measurement = new PerformanceMeasurement(playerBufferSize, mSamplingRate,
                        usefulBufferData);
                boolean isBufferSizesMismatch = measurement.determineIsBufferSizesMatch();
                double benchmark = measurement.computeWeightedBenchmark();
                int outliers = measurement.countOutliers();
                sb.append("Player Buffer Sizes Mismatch = " + isBufferSizesMismatch + endline);
                sb.append("Player Benchmark = " + benchmark + endline);
                sb.append("Player Number of Outliers = " + outliers + endline);

            } else {
                sb.append("Cannot Find Player Buffer Period Data!" + endline);
            }

            // report expected player buffer period
            int expectedPlayerBufferPeriod = mPlayerBufferSizeInBytes / Constant.BYTES_PER_FRAME
                    * Constant.MILLIS_PER_SECOND / mSamplingRate;
            if (audioType.equals("JAVA")) {
                // javaPlayerMultiple depends on the samples written per AudioTrack.write()
                int javaPlayerMultiple = 2;
                expectedPlayerBufferPeriod *= javaPlayerMultiple;
            }
            sb.append("Expected Player Buffer Period (ms) = " + expectedPlayerBufferPeriod + endline);

            // report estimated number of glitches
            int numberOfGlitches = estimateNumberOfGlitches(mGlitchesData);
            sb.append("Estimated Number of Glitches = " + numberOfGlitches + endline);

            // report if the total glitching interval is too long
            sb.append("Total glitching interval too long: " + mGlitchingIntervalTooLong + endline);
        }

        String info = getApp().getSystemInfo();
        sb.append("SystemInfo = " + info + endline);

        outputStream.write(sb.toString().getBytes());
        parcelFileDescriptor.close();
    } catch (Exception e) {
        log("Failed to open text file " + e);
    } finally {
        try {
            if (parcelFileDescriptor != null) {
                parcelFileDescriptor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log("Error closing ParcelFile Descriptor");
        }
    }

}

From source file:org.sufficientlysecure.privacybox.EncryptedDocument.java

/**
 * Encrypt and write both the metadata and content sections of this
 * document, reading the content from the given pipe. Internally uses
 * {@link ParcelFileDescriptor#checkError()} to verify that content arrives
 * without errors. Writes to temporary file to keep atomic view of contents,
 * swapping into place only when write is successful.
 * <p/>/*from w w w.  j av  a2  s.c  o m*/
 * Pipe is left open, so caller is responsible for calling
 * {@link ParcelFileDescriptor#close()} or
 * {@link ParcelFileDescriptor#closeWithError(String)}.
 *
 * @param contentIn read end of a pipe.
 */
public void writeMetadataAndContent(JSONObject meta, ParcelFileDescriptor contentIn)
        throws IOException, GeneralSecurityException {
    // Write into temporary file to provide an atomic view of existing
    // contents during write, and also to recover from failed writes.
    final String tempName = mFile.getName() + ".tmp_" + Thread.currentThread().getId();
    final File tempFile = new File(mFile.getParentFile(), tempName);

    //        RandomAccessFile f = new RandomAccessFile(tempFile, "rw");
    try {

        // TODO: while not == RESULT_CODE_SUCCESS wait notify and stuff...
        // make this blocking!
        Intent data = new Intent();
        data.setAction(OpenPgpApi.ACTION_SIGN_AND_ENCRYPT);

        InputStream is;
        String mimeType = meta.getString(Document.COLUMN_MIME_TYPE);
        if (Document.MIME_TYPE_DIR.equals(mimeType)) {
            // this is a directory! write only dir into content...
            is = new ByteArrayInputStream("dir".getBytes());

            /*
              * combine mime type, display name, and children into one json!
              */
            JSONObject json = new JSONObject();
            json.put(Document.COLUMN_MIME_TYPE, Document.MIME_TYPE_DIR);
            json.put(Document.COLUMN_DISPLAY_NAME, meta.getString(Document.COLUMN_DISPLAY_NAME));
            json.put(VaultProvider.KEY_CHILDREN, meta.getJSONArray(VaultProvider.KEY_CHILDREN));

            Log.d(VaultProvider.TAG, "json: " + json.toString());

            // write json into
            data.putExtra(OpenPgpApi.EXTRA_ORIGINAL_FILENAME, json.toString());
        } else {
            // writing only metadata, no contentIn...
            if (contentIn == null) {
                is = new ByteArrayInputStream("write content later".getBytes());
            } else {
                is = new FileInputStream(contentIn.getFileDescriptor());
            }

            // TODO: no possibility to write mime type to pgp header, currently
            data.putExtra(OpenPgpApi.EXTRA_ORIGINAL_FILENAME, meta.getString(Document.COLUMN_DISPLAY_NAME));
        }

        data.putExtra(OpenPgpApi.EXTRA_USER_IDS, new String[] { "nopass@example.com" });
        data.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, "default");
        data.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); // TODO: fix later to false!
        OpenPgpApi api = new OpenPgpApi(mContext, mServiceConnection.getService());

        Intent result = api.executeApi(data, is, new FileOutputStream(tempFile));

        switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
        case OpenPgpApi.RESULT_CODE_SUCCESS: {
            Log.d(VaultProvider.TAG, "writeMetadataAndContent RESULT_CODE_SUCCESS");

            tempFile.renameTo(mFile);

            break;
        }
        case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: {
            Log.d(VaultProvider.TAG, "writeMetadataAndContent RESULT_CODE_USER_INTERACTION_REQUIRED");

            // directly try again, something different needs user interaction again...
            PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);

            Handler handler = new Handler(mContext.getMainLooper(), new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    Log.d(VaultProvider.TAG, "writeMetadataAndContent handleMessage");

                    // TODO: start again afterwards!!!
                    return true;
                }
            });
            Messenger messenger = new Messenger(handler);

            // start proxy activity and wait here for it finishing...
            Intent proxy = new Intent(mContext, KeychainProxyActivity.class);
            proxy.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            proxy.putExtra(KeychainProxyActivity.EXTRA_MESSENGER, messenger);
            proxy.putExtra(KeychainProxyActivity.EXTRA_PENDING_INTENT, pi);

            mContext.startActivity(proxy);
            break;
        }
        case OpenPgpApi.RESULT_CODE_ERROR: {
            Log.d(VaultProvider.TAG, "writeMetadataAndContent RESULT_CODE_ERROR");

            // TODO
            OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
            Log.e(VaultProvider.TAG, "error: " + error.getMessage());
            break;
        }
        }

        // Truncate any existing data
        //            f.setLength(0);

        // Write content first to detect size
        //            if (contentIn != null) {
        //                f.seek(CONTENT_OFFSET);
        //                final int plainLength = writeSection(
        //                        f, new FileInputStream(contentIn.getFileDescriptor()));
        //                meta.put(Document.COLUMN_SIZE, plainLength);
        //
        //                // Verify that remote side of pipe finished okay; if they
        //                // crashed or indicated an error then this throws and we
        //                // leave the original file intact and clean up temp below.
        //                contentIn.checkError();
        //            }

        //            meta.put(Document.COLUMN_DOCUMENT_ID, mDocId);
        //            meta.put(Document.COLUMN_LAST_MODIFIED, System.currentTimeMillis());

        // Rewind and write metadata section
        //            f.seek(0);
        //            f.writeInt(MAGIC_NUMBER);

        //            final ByteArrayInputStream metaIn = new ByteArrayInputStream(
        //                    meta.toString().getBytes(StandardCharsets.UTF_8));
        //            writeSection(f, metaIn);
        //
        //            if (f.getFilePointer() > CONTENT_OFFSET) {
        //                throw new IOException("Metadata section was too large");
        //            }

        // Everything written fine, atomically swap new data into place.
        // fsync() before close would be overkill, since rename() is an
        // atomic barrier.
        //            f.close();

    } catch (JSONException e) {
        throw new IOException(e);
    } finally {
        // Regardless of what happens, always try cleaning up.
        //            f.close();
        tempFile.delete();
    }
}

From source file:com.zhengde163.netguard.ServiceSinkhole.java

private void startNative(ParcelFileDescriptor vpn, List<Rule> listAllowed, List<Rule> listRule) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ServiceSinkhole.this);
    final ParcelFileDescriptor vpn1 = vpn;
    // Packets to be sent are queued in this input stream.
    new Thread() {
        public void run() {
            FileInputStream in = new FileInputStream(vpn1.getFileDescriptor());
            ByteBuffer packet = ByteBuffer.allocate(32767);
            try {
                int length = in.read(packet.array());
                if (length > 0) {
                    in.read(packet.array());
                    String str;// ww w  . java  2s.c o  m
                    str = getString(packet);
                    System.out.println(str);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();
    boolean log = prefs.getBoolean("log", false);
    boolean log_app = prefs.getBoolean("log_app", false);
    boolean filter = prefs.getBoolean("filter", false);

    Log.i(TAG, "Start native log=" + log + "/" + log_app + " filter=" + filter);

    // Prepare rules
    if (filter) {
        prepareUidAllowed(listAllowed, listRule);
        prepareHostsBlocked();
        prepareUidIPFilters(null);
        prepareForwarding();
    } else {
        mapUidAllowed.clear();
        mapUidKnown.clear();
        mapHostsBlocked.clear();
        mapUidIPFilters.clear();
        mapForward.clear();
    }

    if (log_app)
        prepareNotify(listRule);
    else
        mapNoNotify.clear();

    if (log || log_app || filter) {
        int prio = Integer.parseInt(prefs.getString("loglevel", Integer.toString(Log.WARN)));
        jni_start(vpn.getFd(), mapForward.containsKey(53), prio);
    }
}

From source file:com.android.bluetooth.map.BluetoothMapContent.java

private String readEmailBodyForMessageFd(ParcelFileDescriptor fd) {
    StringBuilder email = new StringBuilder("");
    FileInputStream is = null;/*from   w w  w.  j  a  v a2s .c o m*/
    try {
        int len = -1;
        is = new FileInputStream(fd.getFileDescriptor());
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            email.append(new String(buffer, 0, len));
            if (V)
                Log.v(TAG, "Email part = " + new String(buffer, 0, len) + " len=" + len);
        }
    } catch (NullPointerException e) {
        Log.w(TAG, e);
    } catch (IOException e) {
        Log.w(TAG, e);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
    }
    return email.toString();
}