Example usage for android.os ParcelFileDescriptor createReliablePipe

List of usage examples for android.os ParcelFileDescriptor createReliablePipe

Introduction

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

Prototype

public static ParcelFileDescriptor[] createReliablePipe() throws IOException 

Source Link

Document

Create two ParcelFileDescriptors structured as a data pipe.

Usage

From source file:com.example.android.vault.EncryptedDocumentTest.java

public void testEmptyFile() throws Exception {
    mFile.createNewFile();//w  ww.j a  va 2 s  .  c o  m
    final EncryptedDocument doc = new EncryptedDocument(4, mFile, mDataKey, mMacKey);

    try {
        doc.readMetadata();
        fail("expected metadata to throw");
    } catch (IOException expected) {
    }

    try {
        final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
        doc.readContent(pipe[1]);
        fail("expected content to throw");
    } catch (IOException expected) {
    }
}

From source file:com.example.android.vault.EncryptedDocumentTest.java

private void testMetadataAndContents(byte[] content) throws Exception {
    final EncryptedDocument doc = new EncryptedDocument(4, mFile, mDataKey, mMacKey);
    final byte[] beforeContent = content;

    final ParcelFileDescriptor[] beforePipe = ParcelFileDescriptor.createReliablePipe();
    new Thread() {
        @Override/*www.  ja  va2 s .  c  o m*/
        public void run() {
            final FileOutputStream os = new FileOutputStream(beforePipe[1].getFileDescriptor());
            try {
                os.write(beforeContent);
                beforePipe[1].close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }.start();

    // fully write metadata and content
    final JSONObject before = new JSONObject();
    before.put("meow", "cake");
    doc.writeMetadataAndContent(before, beforePipe[0]);

    // now go back and verify we can read
    final JSONObject after = doc.readMetadata();
    assertEquals("cake", after.getString("meow"));

    final CountDownLatch latch = new CountDownLatch(1);
    final ParcelFileDescriptor[] afterPipe = ParcelFileDescriptor.createReliablePipe();
    final byte[] afterContent = new byte[beforeContent.length];
    new Thread() {
        @Override
        public void run() {
            final FileInputStream is = new FileInputStream(afterPipe[0].getFileDescriptor());
            try {
                int i = 0;
                while (i < afterContent.length) {
                    int n = is.read(afterContent, i, afterContent.length - i);
                    i += n;
                }
                afterPipe[0].close();
                latch.countDown();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }.start();

    doc.readContent(afterPipe[1]);
    latch.await(5, TimeUnit.SECONDS);

    MoreAsserts.assertEquals(beforeContent, afterContent);
}

From source file:com.example.android.vault.EncryptedDocumentTest.java

public void testNormalMetadataOnly() throws Exception {
    final EncryptedDocument doc = new EncryptedDocument(4, mFile, mDataKey, mMacKey);

    // write only metadata
    final JSONObject before = new JSONObject();
    before.put("lol", "wut");
    doc.writeMetadataAndContent(before, null);

    // verify we can read
    final JSONObject after = doc.readMetadata();
    assertEquals("wut", after.getString("lol"));

    final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
    try {//  ww w.j a  va  2s. c  o m
        doc.readContent(pipe[1]);
        fail("found document content");
    } catch (IOException expected) {
    }
}

From source file:com.example.android.vault.EncryptedDocumentTest.java

public void testErrorAbortsWrite() throws Exception {
    final EncryptedDocument doc = new EncryptedDocument(4, mFile, mDataKey, mMacKey);

    // write initial metadata
    final JSONObject init = new JSONObject();
    init.put("color", "red");
    doc.writeMetadataAndContent(init, null);

    // try writing with a pipe that reports failure
    final byte[] content = "KITTENS".getBytes(StandardCharsets.UTF_8);
    final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
    new Thread() {
        @Override/* ww w .  j a va 2 s  . c  o m*/
        public void run() {
            final FileOutputStream os = new FileOutputStream(pipe[1].getFileDescriptor());
            try {
                os.write(content);
                pipe[1].closeWithError("ZOMG");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }.start();

    final JSONObject second = new JSONObject();
    second.put("color", "blue");
    try {
        doc.writeMetadataAndContent(second, pipe[0]);
        fail("somehow wrote without error");
    } catch (IOException ignored) {
    }

    // verify that original metadata still in place
    final JSONObject after = doc.readMetadata();
    assertEquals("red", after.getString("color"));
}

From source file:com.seafile.seadroid2.provider.SeafileProvider.java

@Override
public AssetFileDescriptor openDocumentThumbnail(String documentId, Point sizeHint, CancellationSignal signal)
        throws FileNotFoundException {

    Log.d(DEBUG_TAG, "openDocumentThumbnail(): " + documentId);

    String repoId = DocumentIdParser.getRepoIdFromId(documentId);
    if (repoId.isEmpty()) {
        throw new FileNotFoundException();
    }//  ww w. java  2  s .c  om

    String mimeType = Utils.getFileMimeType(documentId);
    if (!mimeType.startsWith("image/")) {
        throw new FileNotFoundException();
    }

    DataManager dm = createDataManager(documentId);

    String path = DocumentIdParser.getPathFromId(documentId);

    final DisplayImageOptions options = new DisplayImageOptions.Builder().extraForDownloader(dm.getAccount())
            .cacheInMemory(false) // SAF does its own caching
            .cacheOnDisk(true).considerExifParams(true).build();

    final ParcelFileDescriptor[] pair;
    try {
        pair = ParcelFileDescriptor.createReliablePipe();
    } catch (IOException e) {
        throw new FileNotFoundException();
    }

    final String url = dm.getThumbnailLink(repoId, path, sizeHint.x);
    if (url == null)
        throw new FileNotFoundException();

    // do thumbnail download in another thread to avoid possible network access in UI thread
    final Future future = ConcurrentAsyncTask.submit(new Runnable() {

        @Override
        public void run() {
            try {
                FileOutputStream fileStream = new FileOutputStream(pair[1].getFileDescriptor());

                // load the file. this might involve talking to the seafile server. this will hang until
                // it is done.
                Bitmap bmp = ImageLoader.getInstance().loadImageSync(url, options);

                if (bmp != null) {
                    bmp.compress(Bitmap.CompressFormat.PNG, 100, fileStream);
                }
            } finally {
                IOUtils.closeQuietly(pair[1]);
            }
        }
    });

    if (signal != null) {
        signal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
            @Override
            public void onCancel() {
                Log.d(DEBUG_TAG, "openDocumentThumbnail() cancelling download");
                future.cancel(true);
                IOUtils.closeQuietly(pair[1]);
            }
        });
    }

    return new AssetFileDescriptor(pair[0], 0, AssetFileDescriptor.UNKNOWN_LENGTH);
}

From source file:com.example.android.vault.VaultProvider.java

/**
 * Kick off a thread to handle a read request for the given document.
 * Internally creates a pipe and returns the read end for returning to a
 * remote process./*from w ww .ja  v  a  2s.  c  o m*/
 */
private ParcelFileDescriptor startRead(final EncryptedDocument doc) throws IOException {
    final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
    final ParcelFileDescriptor readEnd = pipe[0];
    final ParcelFileDescriptor writeEnd = pipe[1];

    new Thread() {
        @Override
        public void run() {
            try {
                doc.readContent(writeEnd);
                Log.d(TAG, "Success reading " + doc);
                closeQuietly(writeEnd);
            } catch (IOException e) {
                Log.w(TAG, "Failed reading " + doc, e);
                closeWithErrorQuietly(writeEnd, e.toString());
            } catch (GeneralSecurityException e) {
                Log.w(TAG, "Failed reading " + doc, e);
                closeWithErrorQuietly(writeEnd, e.toString());
            }
        }
    }.start();

    return readEnd;
}

From source file:com.example.android.vault.VaultProvider.java

/**
 * Kick off a thread to handle a write request for the given document.
 * Internally creates a pipe and returns the write end for returning to a
 * remote process.//  w  w w . j  a v  a2 s.co  m
 */
private ParcelFileDescriptor startWrite(final EncryptedDocument doc) throws IOException {
    final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
    final ParcelFileDescriptor readEnd = pipe[0];
    final ParcelFileDescriptor writeEnd = pipe[1];

    new Thread() {
        @Override
        public void run() {
            try {
                final JSONObject meta = doc.readMetadata();
                doc.writeMetadataAndContent(meta, readEnd);
                Log.d(TAG, "Success writing " + doc);
                closeQuietly(readEnd);
            } catch (IOException e) {
                Log.w(TAG, "Failed writing " + doc, e);
                closeWithErrorQuietly(readEnd, e.toString());
            } catch (GeneralSecurityException e) {
                Log.w(TAG, "Failed writing " + doc, e);
                closeWithErrorQuietly(readEnd, e.toString());
            }
        }
    }.start();

    return writeEnd;
}

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

/**
 * Kick off a thread to handle a write request for the given document.
 * Internally creates a pipe and returns the write end for returning to a
 * remote process./*from ww w  .  j  a v a2 s .c  o  m*/
 */
private ParcelFileDescriptor startWrite(final EncryptedDocument doc) throws IOException {
    final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
    final ParcelFileDescriptor readEnd = pipe[0];
    final ParcelFileDescriptor writeEnd = pipe[1];

    new Thread() {
        @Override
        public void run() {
            try {
                // get already written metadata from file
                final JSONObject meta = doc.readMetadata();
                doc.writeMetadataAndContent(meta, readEnd);
                Log.d(TAG, "Success writing " + doc);
                closeQuietly(readEnd);
            } catch (IOException e) {
                Log.w(TAG, "Failed writing " + doc, e);
                closeWithErrorQuietly(readEnd, e.toString());
            } catch (GeneralSecurityException e) {
                Log.w(TAG, "Failed writing " + doc, e);
                closeWithErrorQuietly(readEnd, e.toString());
            }
        }
    }.start();

    return writeEnd;
}