|
| 1 | +package org.otzaria.otzaria; |
| 2 | + |
| 3 | +import android.database.Cursor; |
| 4 | +import android.database.MatrixCursor; |
| 5 | +import android.os.Bundle; |
| 6 | +import android.os.CancellationSignal; |
| 7 | +import android.os.Handler; |
| 8 | +import android.os.Looper; |
| 9 | +import android.os.ParcelFileDescriptor; |
| 10 | +import android.provider.DocumentsContract; |
| 11 | +import android.provider.DocumentsProvider; |
| 12 | +import java.io.File; |
| 13 | +import java.io.FileNotFoundException; |
| 14 | +import java.io.FileOutputStream; |
| 15 | +import java.io.IOException; |
| 16 | +import java.util.ArrayList; |
| 17 | +import java.util.Arrays; |
| 18 | +import java.util.Comparator; |
| 19 | +import java.util.HashSet; |
| 20 | +import java.util.Set; |
| 21 | +import java.util.concurrent.TimeUnit; |
| 22 | + |
| 23 | +public final class PdfExportDocumentsProvider extends DocumentsProvider { |
| 24 | + private static final String[] DOCUMENT_COLUMNS = { |
| 25 | + DocumentsContract.Document.COLUMN_DOCUMENT_ID, |
| 26 | + DocumentsContract.Document.COLUMN_DISPLAY_NAME, |
| 27 | + DocumentsContract.Document.COLUMN_MIME_TYPE, |
| 28 | + DocumentsContract.Document.COLUMN_FLAGS, |
| 29 | + DocumentsContract.Document.COLUMN_SIZE, |
| 30 | + DocumentsContract.Document.COLUMN_LAST_MODIFIED |
| 31 | + }; |
| 32 | + |
| 33 | + @Override public boolean onCreate() { |
| 34 | + PdfExportFixture.initialize(getContext()); |
| 35 | + return true; |
| 36 | + } |
| 37 | + |
| 38 | + @Override public Cursor queryRoots(String[] projection) { |
| 39 | + String[] columns = projection != null ? projection : new String[] { |
| 40 | + DocumentsContract.Root.COLUMN_ROOT_ID, DocumentsContract.Root.COLUMN_DOCUMENT_ID, |
| 41 | + DocumentsContract.Root.COLUMN_TITLE, DocumentsContract.Root.COLUMN_FLAGS, |
| 42 | + DocumentsContract.Root.COLUMN_MIME_TYPES |
| 43 | + }; |
| 44 | + MatrixCursor cursor = new MatrixCursor(columns); |
| 45 | + MatrixCursor.RowBuilder row = cursor.newRow(); |
| 46 | + for (String column : columns) { |
| 47 | + Object value; |
| 48 | + switch (column) { |
| 49 | + case DocumentsContract.Root.COLUMN_ROOT_ID: value = "pdf-export"; break; |
| 50 | + case DocumentsContract.Root.COLUMN_DOCUMENT_ID: value = PdfExportFixture.ROOT; break; |
| 51 | + case DocumentsContract.Root.COLUMN_TITLE: value = "PDF export fixture"; break; |
| 52 | + case DocumentsContract.Root.COLUMN_FLAGS: |
| 53 | + value = DocumentsContract.Root.FLAG_SUPPORTS_CREATE | DocumentsContract.Root.FLAG_SUPPORTS_IS_CHILD; break; |
| 54 | + case DocumentsContract.Root.COLUMN_MIME_TYPES: value = "application/pdf"; break; |
| 55 | + default: value = null; |
| 56 | + } |
| 57 | + row.add(column, value); |
| 58 | + } |
| 59 | + return cursor; |
| 60 | + } |
| 61 | + |
| 62 | + @Override public Cursor queryDocument(String documentId, String[] projection) throws FileNotFoundException { |
| 63 | + String[] columns = projection != null ? projection : DOCUMENT_COLUMNS; |
| 64 | + PdfExportFixture.Document document = PdfExportFixture.documents.get(documentId); |
| 65 | + if (!PdfExportFixture.ROOT.equals(documentId) && document != null && document.options.getBoolean("nameFailure") && |
| 66 | + Arrays.equals(columns, new String[] {DocumentsContract.Document.COLUMN_DISPLAY_NAME})) { |
| 67 | + throw new FileNotFoundException("Fixture name query denied"); |
| 68 | + } |
| 69 | + MatrixCursor cursor = new MatrixCursor(columns); |
| 70 | + addDocument(cursor, documentId); |
| 71 | + return cursor; |
| 72 | + } |
| 73 | + |
| 74 | + @Override public Cursor queryChildDocuments(String parentDocumentId, String[] projection, String sortOrder) throws FileNotFoundException { |
| 75 | + PdfExportFixture.check(PdfExportFixture.ROOT.equals(parentDocumentId), "Unknown parent"); |
| 76 | + MatrixCursor cursor = new MatrixCursor(projection != null ? projection : DOCUMENT_COLUMNS); |
| 77 | + ArrayList<PdfExportFixture.Document> sorted = new ArrayList<>(PdfExportFixture.documents.values()); |
| 78 | + sorted.sort(Comparator.comparing(document -> document.name)); |
| 79 | + for (PdfExportFixture.Document document : sorted) { |
| 80 | + if (!document.deleted) addDocument(cursor, document.id); |
| 81 | + } |
| 82 | + return cursor; |
| 83 | + } |
| 84 | + |
| 85 | + private void addDocument(MatrixCursor cursor, String id) throws FileNotFoundException { |
| 86 | + boolean root = PdfExportFixture.ROOT.equals(id); |
| 87 | + PdfExportFixture.Document document = root ? null : PdfExportFixture.documents.get(id); |
| 88 | + if (!root && document == null) throw new FileNotFoundException(id); |
| 89 | + int flags = root ? DocumentsContract.Document.FLAG_DIR_SUPPORTS_CREATE : |
| 90 | + DocumentsContract.Document.FLAG_SUPPORTS_WRITE | |
| 91 | + ("unsupported".equals(document.options.getString("deleteMode")) ? 0 : DocumentsContract.Document.FLAG_SUPPORTS_DELETE); |
| 92 | + MatrixCursor.RowBuilder row = cursor.newRow(); |
| 93 | + for (String column : cursor.getColumnNames()) { |
| 94 | + Object value; |
| 95 | + switch (column) { |
| 96 | + case DocumentsContract.Document.COLUMN_DOCUMENT_ID: value = id; break; |
| 97 | + case DocumentsContract.Document.COLUMN_DISPLAY_NAME: value = root ? "PDF export fixture" : document.name; break; |
| 98 | + case DocumentsContract.Document.COLUMN_MIME_TYPE: value = root ? DocumentsContract.Document.MIME_TYPE_DIR : "application/pdf"; break; |
| 99 | + case DocumentsContract.Document.COLUMN_FLAGS: value = flags; break; |
| 100 | + case DocumentsContract.Document.COLUMN_SIZE: value = root ? 0L : document.file.length(); break; |
| 101 | + case DocumentsContract.Document.COLUMN_LAST_MODIFIED: value = root ? 0L : document.file.lastModified(); break; |
| 102 | + default: value = null; |
| 103 | + } |
| 104 | + row.add(column, value); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + @Override public boolean isChildDocument(String parentDocumentId, String documentId) { |
| 109 | + return PdfExportFixture.ROOT.equals(parentDocumentId) && PdfExportFixture.documents.containsKey(documentId); |
| 110 | + } |
| 111 | + |
| 112 | + @Override public String createDocument(String parentDocumentId, String mimeType, String displayName) throws FileNotFoundException { |
| 113 | + PdfExportFixture.check(PdfExportFixture.ROOT.equals(parentDocumentId) && "application/pdf".equals(mimeType), "Unexpected create request"); |
| 114 | + Bundle options = new Bundle(PdfExportFixture.options); |
| 115 | + PdfExportFixture.events.add("create-enter"); |
| 116 | + if (options.getBoolean("blockCreate")) PdfExportFixture.awaitRelease(); |
| 117 | + if (options.getBoolean("createFailure")) throw new FileNotFoundException("Fixture create failure"); |
| 118 | + if (options.getBoolean("createReturnsParent")) return parentDocumentId; |
| 119 | + String id = "copy-" + PdfExportFixture.sequence.incrementAndGet(); |
| 120 | + Set<String> used = new HashSet<>(); |
| 121 | + for (PdfExportFixture.Document document : PdfExportFixture.documents.values()) used.add(document.name); |
| 122 | + String actualName = displayName; |
| 123 | + String stem = displayName.endsWith(".pdf") ? displayName.substring(0, displayName.length() - 4) : displayName; |
| 124 | + int suffix = 2; |
| 125 | + while (used.contains(actualName)) actualName = stem + " (" + suffix++ + ").pdf"; |
| 126 | + File file = new File(PdfExportFixture.directory, id); |
| 127 | + try { |
| 128 | + PdfExportFixture.check(file.createNewFile(), "Fixture document already exists"); |
| 129 | + } catch (IOException error) { |
| 130 | + throw fileError(error); |
| 131 | + } |
| 132 | + PdfExportFixture.documents.put(id, new PdfExportFixture.Document(id, actualName, file, options)); |
| 133 | + PdfExportFixture.events.add("create-return:" + id); |
| 134 | + return id; |
| 135 | + } |
| 136 | + |
| 137 | + @Override public ParcelFileDescriptor openDocument(String documentId, String mode, CancellationSignal signal) throws FileNotFoundException { |
| 138 | + PdfExportFixture.events.add("open-request:" + documentId); |
| 139 | + PdfExportFixture.Document document = PdfExportFixture.documents.get(documentId); |
| 140 | + if (document == null) throw new FileNotFoundException(documentId); |
| 141 | + if ("r".equals(mode)) return ParcelFileDescriptor.open(document.file, ParcelFileDescriptor.MODE_READ_ONLY); |
| 142 | + PdfExportFixture.check(!"existing".equals(documentId), "Existing user document must not be opened for writing"); |
| 143 | + PdfExportFixture.check("w".equals(mode), "The export path must support a nonseekable writer"); |
| 144 | + if (document.options.getBoolean("openFailure")) throw new FileNotFoundException("Fixture output open failure"); |
| 145 | + document.opened = true; |
| 146 | + PdfExportFixture.events.add("write-open:" + documentId); |
| 147 | + try { |
| 148 | + if (!document.options.getBoolean("pipe")) { |
| 149 | + return ParcelFileDescriptor.open(document.file, ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_TRUNCATE, |
| 150 | + new Handler(Looper.getMainLooper()), error -> { |
| 151 | + document.readerError = error == null ? null : error.getMessage(); |
| 152 | + document.closed.countDown(); |
| 153 | + PdfExportFixture.events.add("write-close:" + documentId); |
| 154 | + }); |
| 155 | + } |
| 156 | + ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe(); |
| 157 | + PdfExportFixture.readers.incrementAndGet(); |
| 158 | + new Thread(() -> readPipe(document, pipe[0]), "pdf-export-fixture-pipe").start(); |
| 159 | + return pipe[1]; |
| 160 | + } catch (IOException error) { |
| 161 | + throw fileError(error); |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + private void readPipe(PdfExportFixture.Document document, ParcelFileDescriptor pipe) { |
| 166 | + try (ParcelFileDescriptor.AutoCloseInputStream input = new ParcelFileDescriptor.AutoCloseInputStream(pipe); |
| 167 | + FileOutputStream output = new FileOutputStream(document.file)) { |
| 168 | + byte[] buffer = new byte[65536]; |
| 169 | + boolean gated = false; |
| 170 | + int count; |
| 171 | + while ((count = input.read(buffer)) >= 0) { |
| 172 | + output.write(buffer, 0, count); |
| 173 | + document.bytes += count; |
| 174 | + if (!gated && document.options.getBoolean("blockWrite")) { |
| 175 | + gated = true; |
| 176 | + PdfExportFixture.events.add("write-gate:" + document.id); |
| 177 | + PdfExportFixture.awaitRelease(); |
| 178 | + } |
| 179 | + long failAfter = document.options.getLong("failAfter"); |
| 180 | + if (failAfter > 0 && document.bytes >= failAfter) { |
| 181 | + pipe.closeWithError("Fixture pipe failed after positive bytes"); |
| 182 | + break; |
| 183 | + } |
| 184 | + } |
| 185 | + } catch (Exception error) { |
| 186 | + document.readerError = error.getMessage(); |
| 187 | + } finally { |
| 188 | + document.closed.countDown(); |
| 189 | + PdfExportFixture.readers.decrementAndGet(); |
| 190 | + PdfExportFixture.events.add("write-close:" + document.id); |
| 191 | + } |
| 192 | + } |
| 193 | + |
| 194 | + @Override public void deleteDocument(String documentId) throws FileNotFoundException { |
| 195 | + PdfExportFixture.events.add("delete-request:" + documentId); |
| 196 | + PdfExportFixture.check(!"existing".equals(documentId), "Existing user document must not be deleted"); |
| 197 | + PdfExportFixture.Document document = PdfExportFixture.documents.get(documentId); |
| 198 | + if (document == null) throw new FileNotFoundException(documentId); |
| 199 | + PdfExportFixture.events.add("delete:" + documentId); |
| 200 | + try { |
| 201 | + if (document.opened && !document.closed.await(10, TimeUnit.SECONDS)) { |
| 202 | + throw new FileNotFoundException("Writer did not close before cleanup"); |
| 203 | + } |
| 204 | + } catch (InterruptedException error) { |
| 205 | + Thread.currentThread().interrupt(); |
| 206 | + throw fileError(error); |
| 207 | + } |
| 208 | + if ("unsupported".equals(document.options.getString("deleteMode"))) { |
| 209 | + throw new UnsupportedOperationException("Fixture does not support deletion"); |
| 210 | + } |
| 211 | + if ("failed".equals(document.options.getString("deleteMode"))) { |
| 212 | + throw new FileNotFoundException("Fixture deletion refused"); |
| 213 | + } |
| 214 | + PdfExportFixture.check(document.file.delete(), "Fixture document was not deleted"); |
| 215 | + document.deleted = true; |
| 216 | + } |
| 217 | + |
| 218 | + private static FileNotFoundException fileError(Exception error) { |
| 219 | + FileNotFoundException result = new FileNotFoundException(error.getMessage()); |
| 220 | + result.initCause(error); |
| 221 | + return result; |
| 222 | + } |
| 223 | +} |
0 commit comments