Test migration of EXTRA_STREAM to clipdata.

Bug:17606450
Change-Id: Ifd6ba4b4a9987c84f697dc88675c539b63430dea
diff --git a/tests/tests/content/AndroidManifest.xml b/tests/tests/content/AndroidManifest.xml
index a5caba8..f7080ae 100644
--- a/tests/tests/content/AndroidManifest.xml
+++ b/tests/tests/content/AndroidManifest.xml
@@ -187,6 +187,15 @@
             </intent-filter>
         </activity>
 
+        <activity android:name="com.android.cts.content.ReadableFileReceiverActivity"
+                  android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.SEND" />
+                <action android:name="android.intent.action.SEND_MULTIPLE" />
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+        </activity>
+
     </application>
 
     <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/tests/tests/content/src/android/content/cts/ReadableFileReceiverActivity.java b/tests/tests/content/src/android/content/cts/ReadableFileReceiverActivity.java
new file mode 100644
index 0000000..bab516e
--- /dev/null
+++ b/tests/tests/content/src/android/content/cts/ReadableFileReceiverActivity.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.content;
+
+import android.app.Activity;
+import android.content.ClipData;
+import android.content.ClipData.Item;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.util.ArrayList;
+import java.util.List;
+
+public class ReadableFileReceiverActivity extends Activity {
+    public static final String ACTION_CONFIRM_READ_SUCCESS
+        = "com.android.cts.content.action.CONFIRM_READ_SUCCESS";
+    private static final String TAG = ReadableUriExtraToClipDataTest.TAG;
+
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        Intent intent = getIntent();
+
+        // Check action.
+        String action = intent.getAction();
+        if (Intent.ACTION_SEND.equals(action)
+                || Intent.ACTION_SEND_MULTIPLE.equals(action)) {
+            readFilesFromClipDataUri(intent);
+        }
+
+        finish();
+    }
+
+    // Sends ACTION_FILE_READY intent when read from clipdata uri is succesful
+    // and read data matches the data written by the test.
+    private void readFilesFromClipDataUri(Intent intent) {
+        if ((intent.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0) {
+
+            // Note: since this activity is in the same package as the test we can read from the
+            // file regardless of this permission, but in general this permission is required.
+            Log.e(TAG, "Intent.FLAG_GRANT_READ_URI_PERMISSION was not granted.");
+            return;
+        }
+
+        List<File> files = getFilesFromIntent(intent);
+        if (files == null) {
+            Log.e(TAG, "Could not get files from clipdata.");
+            return;
+        }
+        for (File file : files) {
+            if (!testFileContents(file)) {
+                Log.e(TAG, "File contents of " + file.getPath()
+                        + " is incorrect or could not be verified.");
+                return;
+            }
+        }
+        Intent confirmIntent = new Intent(ACTION_CONFIRM_READ_SUCCESS);
+        sendBroadcast(confirmIntent);
+    }
+
+    private ArrayList<File> getFilesFromIntent(Intent intent) {
+        ClipData clipData = intent.getClipData();
+        if (clipData == null) {
+            Log.e(TAG, "ClipData missing.");
+            return null;
+        }
+        if (clipData.getItemCount() == 0) {
+            Log.e(TAG, "Uri missing in ClipData.");
+            return null;
+        }
+
+        ArrayList<File> result = new ArrayList<File>();
+        for (int i = 0; i < clipData.getItemCount(); i++) {
+            Uri filePath = clipData.getItemAt(i).getUri();
+            if (filePath == null) {
+                Log.e(TAG, "Uri missing in ClipData.");
+                return null;
+            }
+            try {
+                result.add(new File(filePath.getPath()));
+            } catch (IllegalArgumentException e) {
+                Log.e(TAG, "Cannot get file at Uri.");
+                return null;
+            }
+        }
+        return result;
+    }
+
+    private boolean testFileContents(File file) {
+        char[] buffer = new char[ReadableUriExtraToClipDataTest.TEST_INPUT.length()];
+        try {
+            FileReader reader = new FileReader(file);
+            reader.read(buffer);
+            reader.close();
+        } catch (IOException e) {
+            Log.e(TAG, "Error while reading file " + file.getPath() + ".");
+            return false;
+        }
+        String fileContents = new String(buffer);
+        return ReadableUriExtraToClipDataTest.TEST_INPUT.equals(fileContents);
+    }
+}
\ No newline at end of file
diff --git a/tests/tests/content/src/android/content/cts/ReadableUriExtraToClipDataTest.java b/tests/tests/content/src/android/content/cts/ReadableUriExtraToClipDataTest.java
new file mode 100644
index 0000000..129d964
--- /dev/null
+++ b/tests/tests/content/src/android/content/cts/ReadableUriExtraToClipDataTest.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.content;
+
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.net.Uri;
+import android.provider.MediaStore;
+import android.test.AndroidTestCase;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.List;
+
+public class ReadableUriExtraToClipDataTest extends AndroidTestCase {
+    private static final List<String> FILE_NAMES = Arrays.asList("testFile1.txt", "testFile2.txt");
+    private static final List<File> mTestFiles = new ArrayList<File>();
+    private static final ArrayList<Uri> mTestFileUris = new ArrayList<Uri>();
+    private final Semaphore mReadSuccessSemaphore = new Semaphore(0);
+
+    public static final String TEST_INPUT = "testString";
+    public static final String TAG = "ReadableUriExtraToClipDataTest";
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        assertEquals(0, mReadSuccessSemaphore.availablePermits());
+
+        BroadcastReceiver mReceiver = new BroadcastReceiver() {
+                @Override
+                public void onReceive(Context context, Intent intent) {
+                    mReadSuccessSemaphore.release();
+                }
+            };
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(ReadableFileReceiverActivity.ACTION_CONFIRM_READ_SUCCESS);
+        getContext().registerReceiver(mReceiver, filter);
+
+        for (String fileName : FILE_NAMES) {
+            File testFile = new File(getContext().getFilesDir() + File.separator + fileName);
+            writeTestInputToFile(testFile);
+            mTestFiles.add(testFile);
+            mTestFileUris.add(Uri.fromFile(testFile));
+        }
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        for (File testFile : mTestFiles) {
+            if (testFile.exists()) {
+                assertTrue(testFile.delete());
+            }
+        }
+        mTestFiles.clear();
+        mTestFileUris.clear();
+        super.tearDown();
+    }
+
+    public void testUriExtraStreamMigratedToClipData_sendIntent() {
+        Intent intent = new Intent(Intent.ACTION_SEND);
+        intent.setComponent(new ComponentName(getContext(), ReadableFileReceiverActivity.class));
+        intent.putExtra(Intent.EXTRA_STREAM, mTestFileUris.get(0));
+        intent.setType("*/*");
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+        getContext().startActivity(intent);
+
+        waitForConfirmationReadSuccess();
+    }
+
+    public void testUriExtraStreamMigratedToClipData_sendMultipleIntent() {
+        Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
+        intent.setComponent(new ComponentName(getContext(), ReadableFileReceiverActivity.class));
+        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, mTestFileUris);
+        intent.setType("*/*");
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+        getContext().startActivity(intent);
+
+        waitForConfirmationReadSuccess();
+    }
+
+    private void writeTestInputToFile(File file) {
+        try {
+            FileWriter writer = new FileWriter(file);
+            writer.write(TEST_INPUT);
+            writer.flush();
+            writer.close();
+        } catch (IOException e) {
+            fail(e.toString());
+            return;
+        }
+    }
+
+    private void waitForConfirmationReadSuccess() {
+        try {
+            assertTrue(mReadSuccessSemaphore.tryAcquire(5, TimeUnit.SECONDS));
+        } catch (InterruptedException e) {
+            fail(e.toString());
+        }
+    }
+}
\ No newline at end of file