List of usage examples for android.content.res AssetFileDescriptor getDeclaredLength
public long getDeclaredLength()
From source file:org.apache.cordova.contactVcardpicker.ContactVcardPicker.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d("customPlugin", "Calling onActivityResult"); if (resultCode == Activity.RESULT_OK && requestCode == 5) { String vCard = null;//from ww w .j av a 2 s .c om try { Uri contactData = data.getData(); @SuppressWarnings("deprecation") Cursor cursor = cordova.getActivity().getContentResolver().query(contactData, null, null, null, null); cursor.moveToFirst(); String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); AssetFileDescriptor fd = cordova.getActivity().getContentResolver().openAssetFileDescriptor(uri, "r"); FileInputStream fis = fd.createInputStream(); byte[] b = new byte[(int) fd.getDeclaredLength()]; fis.read(b); vCard = new String(b); System.out.println("VACRD :" + vCard); String contactId = data.getData().getLastPathSegment(); Cursor c = this.cordova.getActivity().getContentResolver().query(RawContacts.CONTENT_URI, new String[] { RawContacts._ID }, RawContacts.CONTACT_ID + " = " + contactId, null, null); if (!c.moveToFirst()) { this.callbackContext.error("Error occured while retrieving contact raw id"); return; } String id = c.getString(c.getColumnIndex(RawContacts._ID)); c.close(); this.contactAccessor = new ContactAccessorSdk5(this.cordova); JSONObject contact = contactAccessor.getContactById(id); String returnText = "{\"contact\": {\"contactData\": \"" + contact.toString() + "\",\"vCard\": \"" + vCard + "\"}}"; System.out.println("returnText :" + returnText); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, returnText); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); // readVCard(vCard); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:org.apache.cordova.plugin.ExportVCFsToFilePlugin.java
private String getVcardString(String fileName, String fileExtension) throws IOException { contactsSet = new HashSet<String>(); cursor = this.cordova.getActivity().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);/*from w ww . ja v a 2 s .c o m*/ if (cursor != null && cursor.getCount() > 0) { int i; File outputDir = this.cordova.getActivity().getCacheDir(); String fullFilePath = outputDir.getAbsolutePath() + "/" + fileName + "." + fileExtension; FileOutputStream mFileOutputStream = new FileOutputStream(fullFilePath, false); cursor.moveToFirst(); for (i = 0; i < cursor.getCount(); i++) { Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY))); AssetFileDescriptor fd; try { fd = this.cordova.getActivity().getContentResolver().openAssetFileDescriptor(uri, "r"); FileInputStream fis = fd.createInputStream(); byte[] buf = new byte[(int) fd.getDeclaredLength()]; fis.read(buf); contactsSet.add(new String(buf)); } catch (Exception e1) { } cursor.moveToNext(); } Iterator it = contactsSet.iterator(); while (it.hasNext()) { try { mFileOutputStream.write(it.next().toString().getBytes()); } catch (IOException e) { } } mFileOutputStream.close(); cursor.close(); return fullFilePath; } else { Log.d("TAG", "No Contacts in Your Phone"); return ""; } }
From source file:com.wifi.brainbreaker.mydemo.http.ModAssetServer.java
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { AbstractHttpEntity body = null;//www . ja v a2 s . c om final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } final String url = URLDecoder.decode(request.getRequestLine().getUri()); if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length); } final String location = "www" + (url.equals("/") ? "/index.htm" : url); response.setStatusCode(HttpStatus.SC_OK); try { Log.i(TAG, "Requested: \"" + url + "\""); // Compares the Last-Modified date header (if present) with the If-Modified-Since date if (request.containsHeader("If-Modified-Since")) { try { Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue()); if (date.compareTo(mServer.mLastModified) <= 0) { // The file has not been modified response.setStatusCode(HttpStatus.SC_NOT_MODIFIED); return; } } catch (DateParseException e) { e.printStackTrace(); } } // We determine if the asset is compressed try { AssetFileDescriptor afd = mAssetManager.openFd(location); // The asset is not compressed FileInputStream fis = new FileInputStream(afd.getFileDescriptor()); fis.skip(afd.getStartOffset()); body = new InputStreamEntity(fis, afd.getDeclaredLength()); Log.d(TAG, "Serving uncompressed file " + "www" + url); } catch (FileNotFoundException e) { // The asset may be compressed // AAPT compresses assets so first we need to uncompress them to determine their length InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING); ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000); byte[] tmp = new byte[4096]; int length = 0; while ((length = stream.read(tmp)) != -1) buffer.write(tmp, 0, length); body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size()); stream.close(); Log.d(TAG, "Serving compressed file " + "www" + url); } body.setContentType(getMimeMediaType(url) + "; charset=UTF-8"); response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified)); } catch (IOException e) { // File does not exist response.setStatusCode(HttpStatus.SC_NOT_FOUND); body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write("<html><body><h1>"); writer.write("File "); writer.write("www" + url); writer.write(" not found"); writer.write("</h1></body></html>"); writer.flush(); } }); Log.d(TAG, "File " + "www" + url + " not found"); body.setContentType("text/html; charset=UTF-8"); } response.setEntity(body); }
From source file:net.facework.core.http.ModAssetServer.java
@Override public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { AbstractHttpEntity body = null;//from ww w.j ava 2 s . c o m final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } final String url = URLDecoder.decode(request.getRequestLine().getUri()); if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length); } final String location = "www" + (url.equals("/") ? "/index.htm" : url); response.setStatusCode(HttpStatus.SC_OK); try { Log.i(TAG, "Requested: \"" + url + "\""); // Compares the Last-Modified date header (if present) with the If-Modified-Since date if (request.containsHeader("If-Modified-Since")) { try { Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue()); if (date.compareTo(mServer.mLastModified) <= 0) { // The file has not been modified response.setStatusCode(HttpStatus.SC_NOT_MODIFIED); return; } } catch (DateParseException e) { e.printStackTrace(); } } // We determine if the asset is compressed try { AssetFileDescriptor afd = mAssetManager.openFd(location); // The asset is not compressed FileInputStream fis = new FileInputStream(afd.getFileDescriptor()); fis.skip(afd.getStartOffset()); body = new InputStreamEntity(fis, afd.getDeclaredLength()); Log.d(TAG, "Serving uncompressed file " + "www" + url); } catch (FileNotFoundException e) { // The asset may be compressed // AAPT compresses assets so first we need to uncompress them to determine their length InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING); ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000); byte[] tmp = new byte[4096]; int length = 0; while ((length = stream.read(tmp)) != -1) buffer.write(tmp, 0, length); body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size()); stream.close(); Log.d(TAG, "Serving compressed file " + "www" + url); } body.setContentType(getMimeMediaType(url) + "; charset=UTF-8"); response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified)); } catch (IOException e) { // File does not exist response.setStatusCode(HttpStatus.SC_NOT_FOUND); body = new EntityTemplate(new ContentProducer() { @Override public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write("<html><body><h1>"); writer.write("File "); writer.write("www" + url); writer.write(" not found"); writer.write("</h1></body></html>"); writer.flush(); } }); Log.d(TAG, "File " + "www" + url + " not found"); body.setContentType("text/html; charset=UTF-8"); } response.setEntity(body); }
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 va 2s . c om*/ 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); }