List of usage examples for android.content.res AssetFileDescriptor createInputStream
public FileInputStream createInputStream() throws IOException
From source file:de.stadtrallye.rallyesoft.services.UploadService.java
private void upload(final PictureManager.Picture picture, boolean previewUpload) { final int biteSize = 8192 * 4; FileInputStream fileInputStream = null; picture.uploading();/*from w w w . j a v a 2s .co m*/ try { Uri uri = Uri.parse(picture.getUri()); Log.d(THIS, "Source: " + picture.getUri()); initReport(picture, biteSize); long fileSize = -1; try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && picture.getUri().startsWith("content://")) { // Check for the freshest data. persistUriPermissionApi19(uri); } AssetFileDescriptor fileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r"); fileSize = fileDescriptor.getDeclaredLength();//TODO report as indeterminate progress if length unknown fileInputStream = fileDescriptor.createInputStream(); } catch (SecurityException e) { Log.e(THIS, "No access rights... WTF", e); return; } TypedOutput uploadStream; RetroAuthCommunicator comm = Server.getCurrentServer().getAuthCommunicator(); Picture responsePicture; final long picSize = fileSize; reportUploadBegins(picSize, biteSize); final FileInputStream fIn = fileInputStream; if (previewUpload) { Bitmap img = BitmapFactory.decodeStream(fileInputStream); int biggerSide = (img.getWidth() > img.getHeight()) ? img.getWidth() : img.getHeight(); double factor = PictureSize.Preview.getDimension().height * 1.0 / biggerSide; int w = (int) Math.round(img.getWidth() * factor); int h = (int) Math.round(img.getHeight() * factor); final Bitmap scaled = Bitmap.createScaledBitmap(img, w, h, true); Log.i(THIS, "scaled bitmap. it now is " + w + "x" + h); uploadStream = new TypedOutput() { @Override public String fileName() { return picture.getHash(); } @Override public String mimeType() { return "image/jpeg"; } @Override public long length() { return -1; } @Override public void writeTo(OutputStream out) throws IOException { scaled.compress(Bitmap.CompressFormat.JPEG, 80, out); } }; reportUploadIndeterminate(picture); responsePicture = comm.uploadPreviewPicture(picture.getHash(), uploadStream); picture.uploadedPreview(); } else { uploadStream = new TypedOutput() { @Override public String fileName() { return picture.getHash(); } @Override public String mimeType() { return picture.getMimeType(); } @Override public long length() { return picSize; } @Override public void writeTo(OutputStream out) throws IOException { final byte[] buf = new byte[biteSize]; int readSize = 0; int i = 0; while (readSize >= 0) { readSize = fIn.read(buf); out.write(buf); i++; reportUploadProgress(picture, i); } } }; responsePicture = comm.uploadPicture(picture.getHash(), uploadStream); picture.uploaded(); } if (responsePicture != null) { if (!responsePicture.pictureHash.equals(picture.getHash())) { //TODO picture.serverResponse(responsePicture), possibly rename file / hash, if the server would like to Log.w(THIS, "The server responded with a different hash than it was asked for... We should rename our file, but cannot since it is not yet implemented"); } } reportUploadComplete(picture); Log.i(THIS, "Picture " + picture.pictureID + " successfully uploaded (" + picSize + " bytes)"); return; } catch (RetrofitError e) { if (e.isNetworkError()) { Log.e(THIS, "Retrofit Network error", e.getCause()); } else { Log.e(THIS, "Server declined", e); } } catch (FileNotFoundException e) { Log.e(THIS, "File was not were it was supposed to be: " + picture.getUri(), e); picture.discard(); return; } catch (IOException e) { Log.e(THIS, "Upload failed", e); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } picture.failed(); reportUploadFailure(picture); }
From source file:org.opendatakit.tables.tasks.InitializeTask.java
private void extractFromRawZip(int resourceId, boolean overwrite, ArrayList<String> result) { String message = null;/*w w w. jav a 2 s .c om*/ AssetFileDescriptor fd = null; try { fd = mContext.getResources().openRawResourceFd(resourceId); final long size = fd.getLength() / 2L; // apparently over-counts by 2x? InputStream rawInputStream = null; try { rawInputStream = fd.createInputStream(); ZipInputStream zipInputStream = null; ZipEntry entry = null; try { // count the number of files in the zip zipInputStream = new ZipInputStream(rawInputStream); int totalFiles = 0; while ((entry = zipInputStream.getNextEntry()) != null) { message = null; if (isCancelled()) { message = "cancelled"; result.add(entry.getName() + " " + message); break; } ++totalFiles; } zipInputStream.close(); // and re-open the stream, reading it this time... fd = mContext.getResources().openRawResourceFd(resourceId); rawInputStream = fd.createInputStream(); zipInputStream = new ZipInputStream(rawInputStream); long bytesProcessed = 0L; long lastBytesProcessedThousands = 0L; int nFiles = 0; while ((entry = zipInputStream.getNextEntry()) != null) { message = null; if (isCancelled()) { message = "cancelled"; result.add(entry.getName() + " " + message); break; } ++nFiles; File tempFile = new File(ODKFileUtils.getAppFolder(mAppName), entry.getName()); String formattedString = mContext.getString(R.string.expansion_unzipping_without_detail, entry.getName(), nFiles, totalFiles); String detail; if (entry.isDirectory()) { detail = mContext.getString(R.string.expansion_create_dir_detail); publishProgress(formattedString, detail); tempFile.mkdirs(); } else { int bufferSize = 8192; OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile, false), bufferSize); byte buffer[] = new byte[bufferSize]; int bread; while ((bread = zipInputStream.read(buffer)) != -1) { bytesProcessed += bread; long curThousands = (bytesProcessed / 1000L); if (curThousands != lastBytesProcessedThousands) { detail = mContext.getString(R.string.expansion_unzipping_detail, bytesProcessed, size); publishProgress(formattedString, detail); lastBytesProcessedThousands = curThousands; } out.write(buffer, 0, bread); } out.flush(); out.close(); detail = mContext.getString(R.string.expansion_unzipping_detail, bytesProcessed, size); publishProgress(formattedString, detail); } WebLogger.getLogger(mAppName).i(TAG, "Extracted ZipEntry: " + entry.getName()); message = mContext.getString(R.string.success); result.add(entry.getName() + " " + message); } ODKFileUtils.assertConfiguredTablesApp(mAppName, Tables.getInstance().getVersionCodeString()); String completionString = mContext.getString(R.string.expansion_unzipping_complete, totalFiles); publishProgress(completionString, null); } catch (IOException e) { WebLogger.getLogger(mAppName).printStackTrace(e); mPendingSuccess = false; if (e.getCause() != null) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } if (entry != null) { result.add(entry.getName() + " " + message); } else { result.add("Error accessing zipfile resource " + message); } } finally { if (zipInputStream != null) { try { zipInputStream.close(); rawInputStream = null; fd = null; } catch (IOException e) { WebLogger.getLogger(mAppName).printStackTrace(e); WebLogger.getLogger(mAppName).e(TAG, "Closing of ZipFile failed: " + e.toString()); } } if (rawInputStream != null) { try { rawInputStream.close(); fd = null; } catch (IOException e) { WebLogger.getLogger(mAppName).printStackTrace(e); WebLogger.getLogger(mAppName).e(TAG, "Closing of ZipFile failed: " + e.toString()); } } if (fd != null) { try { fd.close(); } catch (IOException e) { WebLogger.getLogger(mAppName).printStackTrace(e); WebLogger.getLogger(mAppName).e(TAG, "Closing of ZipFile failed: " + e.toString()); } } } } catch (Exception e) { WebLogger.getLogger(mAppName).printStackTrace(e); mPendingSuccess = false; if (e.getCause() != null) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } result.add("Error accessing zipfile resource " + message); } finally { if (rawInputStream != null) { try { rawInputStream.close(); } catch (IOException e) { WebLogger.getLogger(mAppName).printStackTrace(e); } } } } finally { if (fd != null) { try { fd.close(); } catch (IOException e) { WebLogger.getLogger(mAppName).printStackTrace(e); } } else { result.add("Error accessing zipfile resource."); } } }
From source file:org.opendatakit.survey.android.tasks.InitializationTask.java
private final void extractFromRawZip(int resourceId, boolean overwrite, ArrayList<String> result) { String message = null;// w ww. j a v a 2s.co m AssetFileDescriptor fd = null; try { fd = appContext.getResources().openRawResourceFd(resourceId); final long size = fd.getLength(); // apparently over-counts by 2x? InputStream rawInputStream = null; try { rawInputStream = fd.createInputStream(); ZipInputStream zipInputStream = null; ZipEntry entry = null; try { // count the number of files in the zip zipInputStream = new ZipInputStream(rawInputStream); int totalFiles = 0; while ((entry = zipInputStream.getNextEntry()) != null) { message = null; if (isCancelled()) { message = "cancelled"; result.add(entry.getName() + " " + message); break; } ++totalFiles; } zipInputStream.close(); // and re-open the stream, reading it this time... fd = appContext.getResources().openRawResourceFd(resourceId); rawInputStream = fd.createInputStream(); zipInputStream = new ZipInputStream(rawInputStream); long bytesProcessed = 0L; long lastBytesProcessedThousands = 0L; int nFiles = 0; while ((entry = zipInputStream.getNextEntry()) != null) { message = null; if (isCancelled()) { message = "cancelled"; result.add(entry.getName() + " " + message); break; } ++nFiles; File tempFile = new File(ODKFileUtils.getAppFolder(appName), entry.getName()); String formattedString = appContext.getString(R.string.expansion_unzipping_without_detail, entry.getName(), nFiles, totalFiles); String detail; if (entry.isDirectory()) { detail = appContext.getString(R.string.expansion_create_dir_detail); publishProgress(formattedString, detail); tempFile.mkdirs(); } else if (overwrite || !tempFile.exists()) { int bufferSize = 8192; OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile, false), bufferSize); byte buffer[] = new byte[bufferSize]; int bread; while ((bread = zipInputStream.read(buffer)) != -1) { bytesProcessed += bread; long curThousands = (bytesProcessed / 1000L); if (curThousands != lastBytesProcessedThousands) { detail = appContext.getString(R.string.expansion_unzipping_detail, bytesProcessed, size); publishProgress(formattedString, detail); lastBytesProcessedThousands = curThousands; } out.write(buffer, 0, bread); } out.flush(); out.close(); detail = appContext.getString(R.string.expansion_unzipping_detail, bytesProcessed, size); publishProgress(formattedString, detail); } WebLogger.getLogger(appName).i(t, "Extracted ZipEntry: " + entry.getName()); } String completionString = appContext.getString(R.string.expansion_unzipping_complete, totalFiles); publishProgress(completionString, null); } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); mPendingSuccess = false; if (e.getCause() != null) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } if (entry != null) { result.add(entry.getName() + " " + message); } else { result.add("Error accessing zipfile resource " + message); } } finally { if (zipInputStream != null) { try { zipInputStream.close(); } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); WebLogger.getLogger(appName).e(t, "Closing of ZipFile failed: " + e.toString()); } } } } catch (Exception e) { WebLogger.getLogger(appName).printStackTrace(e); mPendingSuccess = false; if (e.getCause() != null) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } result.add("Error accessing zipfile resource " + message); } finally { if (rawInputStream != null) { try { rawInputStream.close(); } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); } } } } finally { if (fd != null) { try { fd.close(); } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); } } else { result.add("Error accessing zipfile resource."); } } }
From source file:at.bitfire.davdroid.mirakel.resource.LocalAddressBook.java
protected void populatePhoto(Contact c) throws RemoteException { @Cleanup/* w w w . ja va 2 s. c o m*/ Cursor cursor = providerClient.query(dataURI(), new String[] { Photo.PHOTO_FILE_ID, Photo.PHOTO }, Photo.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?", new String[] { String.valueOf(c.getLocalID()), Photo.CONTENT_ITEM_TYPE }, null); if (cursor != null && cursor.moveToNext()) { if (!cursor.isNull(0)) { Uri photoUri = Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, c.getLocalID()), RawContacts.DisplayPhoto.CONTENT_DIRECTORY); try { @Cleanup AssetFileDescriptor fd = providerClient.openAssetFile(photoUri, "r"); @Cleanup InputStream is = fd.createInputStream(); c.setPhoto(IOUtils.toByteArray(is)); } catch (IOException ex) { Log.w(TAG, "Couldn't read high-res contact photo", ex); } } else c.setPhoto(cursor.getBlob(1)); } }
From source file:at.bitfire.davdroid.resource.LocalAddressBook.java
protected void populatePhoto(Contact c, ContentValues row) throws RemoteException { if (row.containsKey(Photo.PHOTO_FILE_ID)) { Uri photoUri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI, c.getLocalID()), RawContacts.DisplayPhoto.CONTENT_DIRECTORY); try {/* w ww . ja v a 2s . com*/ @Cleanup AssetFileDescriptor fd = providerClient.openAssetFile(photoUri, "r"); @Cleanup InputStream is = fd.createInputStream(); c.photo = IOUtils.toByteArray(is); } catch (IOException ex) { Log.w(TAG, "Couldn't read high-res contact photo", ex); } } else c.photo = row.getAsByteArray(Photo.PHOTO); }
From source file:com.granita.icloudcalsync.resource.LocalAddressBook.java
protected void populatePhoto(Contact c, ContentValues row) throws RemoteException { if (row.containsKey(Photo.PHOTO_FILE_ID)) { Uri photoUri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI, c.getLocalID()), RawContacts.DisplayPhoto.CONTENT_DIRECTORY); try {/* w w w .j a v a 2s. c o m*/ @Cleanup AssetFileDescriptor fd = providerClient.openAssetFile(photoUri, "r"); @Cleanup InputStream is = fd.createInputStream(); c.setPhoto(IOUtils.toByteArray(is)); } catch (IOException ex) { Log.w(TAG, "Couldn't read high-res contact photo", ex); } } else c.setPhoto(row.getAsByteArray(Photo.PHOTO)); }
From source file:at.bitfire.vcard4android.AndroidContact.java
protected void populatePhoto(ContentValues row) throws RemoteException { if (row.containsKey(Photo.PHOTO_FILE_ID)) { Uri photoUri = Uri.withAppendedPath(rawContactSyncURI(), RawContacts.DisplayPhoto.CONTENT_DIRECTORY); try {/*from ww w.j a v a2 s . co m*/ @Cleanup AssetFileDescriptor fd = addressBook.provider.openAssetFile(photoUri, "r"); @Cleanup InputStream stream = fd.createInputStream(); if (stream != null) contact.photo = IOUtils.toByteArray(stream); else Constants.log.warn("Ignoring inaccessible local contact photo file"); } catch (IOException e) { Constants.log.warn("Couldn't read local contact photo file", e); } } else contact.photo = row.getAsByteArray(Photo.PHOTO); }
From source file:com.android.contacts.common.model.ContactLoader.java
/** * Looks for the photo data item in entities. If found, a thumbnail will be stored. A larger * photo will also be stored if available. *//*www .j av a 2s. c o m*/ private void loadPhotoBinaryData(Contact contactData) { loadThumbnailBinaryData(contactData); // Try to load the large photo from a file using the photo URI. String photoUri = contactData.getPhotoUri(); if (photoUri != null) { try { final InputStream inputStream; final AssetFileDescriptor fd; final Uri uri = Uri.parse(photoUri); final String scheme = uri.getScheme(); if ("http".equals(scheme) || "https".equals(scheme)) { // Support HTTP urls that might come from extended directories inputStream = new URL(photoUri).openStream(); fd = null; } else { fd = getContext().getContentResolver().openAssetFileDescriptor(uri, "r"); inputStream = fd.createInputStream(); } byte[] buffer = new byte[16 * 1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { int size; while ((size = inputStream.read(buffer)) != -1) { baos.write(buffer, 0, size); } contactData.setPhotoBinaryData(baos.toByteArray()); } finally { inputStream.close(); if (fd != null) { fd.close(); } } return; } catch (IOException ioe) { // Just fall back to the case below. } } // If we couldn't load from a file, fall back to the data blob. contactData.setPhotoBinaryData(contactData.getThumbnailPhotoBinaryData()); }
From source file:eu.faircode.netguard.ActivitySettings.java
private void handleImport(final Intent data) { new AsyncTask<Object, Object, Throwable>() { @Override/*w ww . j a va 2 s . c om*/ protected Throwable doInBackground(Object... objects) { InputStream in = null; try { Log.i(TAG, "Reading URI=" + data.getData()); ContentResolver resolver = getContentResolver(); String[] streamTypes = resolver.getStreamTypes(data.getData(), "*/*"); String streamType = (streamTypes == null || streamTypes.length == 0 ? "*/*" : streamTypes[0]); AssetFileDescriptor descriptor = resolver.openTypedAssetFileDescriptor(data.getData(), streamType, null); in = descriptor.createInputStream(); xmlImport(in); return null; } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); return ex; } finally { if (in != null) try { in.close(); } catch (IOException ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } } } @Override protected void onPostExecute(Throwable ex) { if (running) { if (ex == null) { Toast.makeText(ActivitySettings.this, R.string.msg_completed, Toast.LENGTH_LONG).show(); ServiceSinkhole.reloadStats("import", ActivitySettings.this); // Update theme, request permissions recreate(); } else Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show(); } } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }
From source file:eu.faircode.netguard.ActivitySettings.java
private void handleHosts(final Intent data) { new AsyncTask<Object, Object, Throwable>() { @Override/* ww w . j av a2s .co m*/ protected Throwable doInBackground(Object... objects) { File hosts = new File(getFilesDir(), "hosts.txt"); FileOutputStream out = null; InputStream in = null; try { Log.i(TAG, "Reading URI=" + data.getData()); ContentResolver resolver = getContentResolver(); String[] streamTypes = resolver.getStreamTypes(data.getData(), "*/*"); String streamType = (streamTypes == null || streamTypes.length == 0 ? "*/*" : streamTypes[0]); AssetFileDescriptor descriptor = resolver.openTypedAssetFileDescriptor(data.getData(), streamType, null); in = descriptor.createInputStream(); out = new FileOutputStream(hosts); int len; long total = 0; byte[] buf = new byte[4096]; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); total += len; } Log.i(TAG, "Copied bytes=" + total); return null; } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); return ex; } finally { if (out != null) try { out.close(); } catch (IOException ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } if (in != null) try { in.close(); } catch (IOException ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } } } @Override protected void onPostExecute(Throwable ex) { if (running) { if (ex == null) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(ActivitySettings.this); String last = SimpleDateFormat.getDateTimeInstance().format(new Date().getTime()); prefs.edit().putString("hosts_last_import", last).apply(); if (running) { getPreferenceScreen().findPreference("hosts_import") .setSummary(getString(R.string.msg_import_last, last)); Toast.makeText(ActivitySettings.this, R.string.msg_completed, Toast.LENGTH_LONG).show(); } ServiceSinkhole.reload("hosts import", ActivitySettings.this, false); } else Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show(); } } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }