List of usage examples for android.content ContentResolver getType
public final @Nullable String getType(@NonNull Uri url)
From source file:Main.java
/** * Return text content of clipboard as individual lines * @param ctx/*from w w w .j a v a 2s . c o m*/ * @return */ @SuppressLint("NewApi") private static ArrayList<String> getTextLines(Context ctx) { String EOL = "\\r?\\n|\\r"; if (checkForText(ctx)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0); // Gets the clipboard as text. CharSequence cs = item.getText(); if (cs == null) { // item might be an URI Uri pasteUri = item.getUri(); if (pasteUri != null) { // FIXME untested try { Log.d("ClipboardUtils", "Clipboard contains an uri"); ContentResolver cr = ctx.getContentResolver(); String uriMimeType = cr.getType(pasteUri); // pasteData = resolveUri(pasteUri); // If the return value is not null, the Uri is a content Uri if (uriMimeType != null) { // Does the content provider offer a MIME type that the current application can use? if (uriMimeType.equals(ClipDescription.MIMETYPE_TEXT_PLAIN)) { // Get the data from the content provider. Cursor pasteCursor = cr.query(pasteUri, null, null, null, null); // If the Cursor contains data, move to the first record if (pasteCursor != null) { if (pasteCursor.moveToFirst()) { String pasteData = pasteCursor.getString(0); return new ArrayList<String>(Arrays.asList(pasteData.split(EOL))); } // close the Cursor pasteCursor.close(); } } } } catch (Exception e) { // FIXME given that the above is unteted, cath all here Log.e("ClipboardUtils", "Resolving URI failed " + e); e.printStackTrace(); return null; } } } else { Log.d("ClipboardUtils", "Clipboard contains text"); String pasteData = cs.toString(); return new ArrayList<String>(Arrays.asList(pasteData.split(EOL))); } } else { // Gets the clipboard as text. @SuppressWarnings("deprecation") CharSequence cs = oldClipboard.getText(); if (cs != null) { String pasteData = cs.toString(); if (pasteData != null) { // should always be the case return new ArrayList<String>(Arrays.asList(pasteData.split(EOL))); } } } Log.e("ClipboardUtils", "Clipboard contains an invalid data type"); } return null; }
From source file:de.petermoesenthin.alarming.util.FileUtil.java
/** * Returns a mime type for a file in given path. * * @param path Path to the file.// w w w .j a v a2s. c o m * @return Null if no MIME type is found. */ public static String getMimeType(Context context, String path) { Log.d(DEBUG_TAG, "Checking mime type for " + path); String mimeType = null; String extension = FilenameUtils.getExtension(path); if (extension != null) { MimeTypeMap mime = MimeTypeMap.getSingleton(); mimeType = mime.getMimeTypeFromExtension(extension); Log.d(DEBUG_TAG, "MimeTypeMap found " + mimeType + " for extension " + extension); } if (mimeType == null) { ContentResolver contentResolver = context.getContentResolver(); mimeType = contentResolver.getType(Uri.parse(path)); Log.d(DEBUG_TAG, "ContentResolver found " + mimeType + "."); } return mimeType; }
From source file:Main.java
/** * Transforms the given Uri and returns a Lookup-Uri that represents the contact. * For legacy contacts, a raw-contact lookup is performed. An {@link IllegalArgumentException} * can be thrown if the URI is null or the authority is not recognized. * * Do not call from the UI thread.// w w w . j ava2 s. co m */ @SuppressWarnings("deprecation") public static Uri ensureIsContactUri(final ContentResolver resolver, final Uri uri) throws IllegalArgumentException { if (uri == null) throw new IllegalArgumentException("uri must not be null"); final String authority = uri.getAuthority(); // Current Style Uri? if (ContactsContract.AUTHORITY.equals(authority)) { final String type = resolver.getType(uri); // Contact-Uri? Good, return it if (ContactsContract.Contacts.CONTENT_ITEM_TYPE.equals(type)) { return uri; } // RawContact-Uri? Transform it to ContactUri if (RawContacts.CONTENT_ITEM_TYPE.equals(type)) { final long rawContactId = ContentUris.parseId(uri); return RawContacts.getContactLookupUri(resolver, ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId)); } // Anything else? We don't know what this is throw new IllegalArgumentException("uri format is unknown"); } // Legacy Style? Convert to RawContact final String OBSOLETE_AUTHORITY = Contacts.AUTHORITY; if (OBSOLETE_AUTHORITY.equals(authority)) { // Legacy Format. Convert to RawContact-Uri and then lookup the contact final long rawContactId = ContentUris.parseId(uri); return RawContacts.getContactLookupUri(resolver, ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId)); } throw new IllegalArgumentException("uri authority is unknown"); }
From source file:mobisocial.musubi.objects.FileObj.java
public static Obj from(Context context, Uri dataUri) throws IOException { //TODO: is this the proper way to do it? if (dataUri == null) { throw new NullPointerException(); }//www . j a va 2s.co m ContentResolver cr = context.getContentResolver(); InputStream in = cr.openInputStream(dataUri); long length = in.available(); String ext; String mimeType; String filename; MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); if ("content".equals(dataUri.getScheme())) { ContentResolver resolver = context.getContentResolver(); mimeType = resolver.getType(dataUri); ext = mimeTypeMap.getExtensionFromMimeType(mimeType); filename = "Musubi-" + sDateFormat.format(new Date()); } else { ext = MimeTypeMap.getFileExtensionFromUrl(dataUri.toString()); mimeType = mimeTypeMap.getMimeTypeFromExtension(ext); filename = Uri.parse(dataUri.toString()).getLastPathSegment(); if (filename == null) { filename = "Musubi-" + sDateFormat.format(new Date()); } } if (mimeType == null || mimeType.isEmpty()) { throw new IOException("Unidentified mime type"); } if (ext == null || ext.isEmpty()) { ext = mimeTypeMap.getExtensionFromMimeType(mimeType); } if (!ext.isEmpty() && !filename.endsWith(ext)) { filename = filename + "." + ext; } if (mimeType.startsWith("video/")) { return VideoObj.from(context, dataUri, mimeType); } else if (mimeType.startsWith("image/")) { return PictureObj.from(context, dataUri, true); } if (length > EMBED_SIZE_LIMIT) { if (length > CORRAL_SIZE_LIMIT) { throw new IOException("file too large for push"); } else { return fromCorral(context, mimeType, filename, length, dataUri); } } else { in = cr.openInputStream(dataUri); return from(mimeType, filename, length, IOUtils.toByteArray(in)); } }
From source file:com.cyberocw.habittodosecretary.file.StorageHelper.java
/** * Retrieves uri mime-type using ContentResolver * * @param mContext//from w w w.j a va 2s .co m * @param uri * @return */ public static String getMimeType(Context mContext, Uri uri) { ContentResolver cR = mContext.getContentResolver(); String mimeType = cR.getType(uri); if (mimeType == null) { mimeType = getMimeType(uri.toString()); } return mimeType; }
From source file:mobisocial.musubi.objects.PictureObj.java
public static MemObj from(Context context, Uri imageUri, boolean referenceOrig, String text) throws IOException { // Query gallery for camera picture via // Android ContentResolver interface ContentResolver cr = context.getContentResolver(); UriImage image = new UriImage(context, imageUri); byte[] data = image.getResizedImageData(MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT, MAX_IMAGE_SIZE); JSONObject base = new JSONObject(); // Maintain a reference to original file try {/*from ww w. j a v a 2 s .c o m*/ String type = cr.getType(imageUri); if (type == null) { type = "image/jpeg"; } if (text != null && !text.isEmpty()) { base.put(TEXT, text); } base.put(CorralDownloadClient.OBJ_MIME_TYPE, type); if (referenceOrig) { base.put(CorralDownloadClient.OBJ_LOCAL_URI, imageUri.toString()); String localIp = ContentCorral.getLocalIpAddress(); // TODO: Share IP if allowed for the given feed if (localIp != null && MusubiBaseActivity.isDeveloperModeEnabled(context)) { base.put(DbContactAttributes.ATTR_LAN_IP, localIp); } } } catch (JSONException e) { Log.e(TAG, "impossible json error possible!"); } return new MemObj(TYPE, base, data); }
From source file:com.github.chenxiaolong.dualbootpatcher.FileUtils.java
public static UriMetadata[] queryUriMetadata(ContentResolver cr, Uri... uris) { ThreadUtils.enforceExecutionOnNonMainThread(); UriMetadata[] metadatas = new UriMetadata[uris.length]; for (int i = 0; i < metadatas.length; i++) { UriMetadata metadata = new UriMetadata(); metadatas[i] = metadata;/*ww w .ja v a 2 s.com*/ metadata.uri = uris[i]; metadata.mimeType = cr.getType(metadata.uri); if (SAF_SCHEME.equals(metadata.uri.getScheme())) { Cursor cursor = cr.query(metadata.uri, null, null, null, null, null); try { if (cursor != null && cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE); metadata.displayName = cursor.getString(nameIndex); if (cursor.isNull(sizeIndex)) { metadata.size = -1; } else { metadata.size = cursor.getLong(sizeIndex); } } } finally { IOUtils.closeQuietly(cursor); } } else if (FILE_SCHEME.equals(metadata.uri.getScheme())) { metadata.displayName = metadata.uri.getLastPathSegment(); metadata.size = new File(metadata.uri.getPath()).length(); } else { throw new IllegalArgumentException("Cannot handle URI: " + metadata.uri); } } return metadatas; }
From source file:com.amarinfingroup.net.utilities.EncryptionUtils.java
/** * Retrieve the encryption information for this uri. * * @param mUri either an instance URI (if previously saved) or a form URI * @param instanceMetadata/*from w ww . java 2 s . c om*/ * @return */ public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri, InstanceMetadata instanceMetadata) { ContentResolver cr = Collect.getInstance().getContentResolver(); // fetch the form information String formId; String formVersion; PublicKey pk; Base64Wrapper wrapper; Cursor formCursor = null; try { if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) { // chain back to the Form record... String[] selectionArgs = null; String selection = null; Cursor instanceCursor = null; try { instanceCursor = cr.query(mUri, null, null, null, null); if (instanceCursor.getCount() != 1) { Log.e(t, "Not exactly one record for this instance!"); return null; // save unencrypted. } instanceCursor.moveToFirst(); String jrFormId = instanceCursor .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID)); int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION); if (!instanceCursor.isNull(idxJrVersion)) { selectionArgs = new String[] { jrFormId, instanceCursor.getString(idxJrVersion) }; selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?"; } else { selectionArgs = new String[] { jrFormId }; selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL"; } } finally { if (instanceCursor != null) { instanceCursor.close(); } } formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs, null); if (formCursor.getCount() != 1) { Log.e(t, "Not exactly one blank form matches this jr_form_id"); return null; // save unencrypted } formCursor.moveToFirst(); } else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) { formCursor = cr.query(mUri, null, null, null, null); if (formCursor.getCount() != 1) { Log.e(t, "Not exactly one blank form!"); return null; // save unencrypted. } formCursor.moveToFirst(); } formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID)); if (formId == null || formId.length() == 0) { Log.e(t, "No FormId specified???"); return null; } int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION); int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY); formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion); String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey) ? null : formCursor.getString(idxBase64RsaPublicKey); if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) { return null; // this is legitimately not an encrypted form } int version = android.os.Build.VERSION.SDK_INT; if (version < 8) { Log.e(t, "Phone does not support encryption."); return null; // save unencrypted } // this constructor will throw an exception if we are not // running on version 8 or above (if Base64 is not found). try { wrapper = new Base64Wrapper(); } catch (ClassNotFoundException e) { Log.e(t, "Phone does not have Base64 class but API level is " + version); e.printStackTrace(); return null; // save unencrypted } // OK -- Base64 decode (requires API Version 8 or higher) byte[] publicKey = wrapper.decode(base64RsaPublicKey); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey); KeyFactory kf; try { kf = KeyFactory.getInstance(RSA_ALGORITHM); } catch (NoSuchAlgorithmException e) { Log.e(t, "Phone does not support RSA encryption."); e.printStackTrace(); return null; } try { pk = kf.generatePublic(publicKeySpec); } catch (InvalidKeySpecException e) { e.printStackTrace(); Log.e(t, "Invalid RSA public key."); return null; } } finally { if (formCursor != null) { formCursor.close(); } } // submission must have an OpenRosa metadata block with a non-null // instanceID value. if (instanceMetadata.instanceId == null) { Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block"); return null; } // For now, prevent encryption if the BouncyCastle implementation is not present. // https://code.google.com/p/opendatakit/issues/detail?id=918 try { Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); Log.e(t, "No BouncyCastle implementation of symmetric algorithm!"); return null; } catch (NoSuchProviderException e) { e.printStackTrace(); Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!"); return null; } catch (NoSuchPaddingException e) { e.printStackTrace(); Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!"); return null; } return new EncryptedFormInformation(formId, formVersion, instanceMetadata, pk, wrapper); }
From source file:cd.education.data.collector.android.utilities.EncryptionUtils.java
/** * Retrieve the encryption information for this uri. * * @param mUri either an instance URI (if previously saved) or a form URI * @param instanceMetadata/*from w w w . j a v a2s. c o m*/ * @return */ public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri, FormController.InstanceMetadata instanceMetadata) { ContentResolver cr = Collect.getInstance().getContentResolver(); // fetch the form information String formId; String formVersion; PublicKey pk; Base64Wrapper wrapper; Cursor formCursor = null; try { if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) { // chain back to the Form record... String[] selectionArgs = null; String selection = null; Cursor instanceCursor = null; try { instanceCursor = cr.query(mUri, null, null, null, null); if (instanceCursor.getCount() != 1) { Log.e(t, "Not exactly one record for this instance!"); return null; // save unencrypted. } instanceCursor.moveToFirst(); String jrFormId = instanceCursor .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID)); int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION); if (!instanceCursor.isNull(idxJrVersion)) { selectionArgs = new String[] { jrFormId, instanceCursor.getString(idxJrVersion) }; selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?"; } else { selectionArgs = new String[] { jrFormId }; selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL"; } } finally { if (instanceCursor != null) { instanceCursor.close(); } } formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs, null); if (formCursor.getCount() != 1) { Log.e(t, "Not exactly one blank form matches this jr_form_id"); return null; // save unencrypted } formCursor.moveToFirst(); } else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) { formCursor = cr.query(mUri, null, null, null, null); if (formCursor.getCount() != 1) { Log.e(t, "Not exactly one blank form!"); return null; // save unencrypted. } formCursor.moveToFirst(); } formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID)); if (formId == null || formId.length() == 0) { Log.e(t, "No FormId specified???"); return null; } int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION); int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY); formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion); String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey) ? null : formCursor.getString(idxBase64RsaPublicKey); if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) { return null; // this is legitimately not an encrypted form } int version = android.os.Build.VERSION.SDK_INT; if (version < 8) { Log.e(t, "Phone does not support encryption."); return null; // save unencrypted } // this constructor will throw an exception if we are not // running on version 8 or above (if Base64 is not found). try { wrapper = new Base64Wrapper(); } catch (ClassNotFoundException e) { Log.e(t, "Phone does not have Base64 class but API level is " + version); e.printStackTrace(); return null; // save unencrypted } // OK -- Base64 decode (requires API Version 8 or higher) byte[] publicKey = wrapper.decode(base64RsaPublicKey); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey); KeyFactory kf; try { kf = KeyFactory.getInstance(RSA_ALGORITHM); } catch (NoSuchAlgorithmException e) { Log.e(t, "Phone does not support RSA encryption."); e.printStackTrace(); return null; } try { pk = kf.generatePublic(publicKeySpec); } catch (InvalidKeySpecException e) { e.printStackTrace(); Log.e(t, "Invalid RSA public key."); return null; } } finally { if (formCursor != null) { formCursor.close(); } } // submission must have an OpenRosa metadata block with a non-null // instanceID value. if (instanceMetadata.instanceId == null) { Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block"); return null; } // For now, prevent encryption if the BouncyCastle implementation is not present. // https://code.google.com/p/opendatakit/issues/detail?id=918 try { Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); Log.e(t, "No BouncyCastle implementation of symmetric algorithm!"); return null; } catch (NoSuchProviderException e) { e.printStackTrace(); Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!"); return null; } catch (NoSuchPaddingException e) { e.printStackTrace(); Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!"); return null; } return new EncryptedFormInformation(formId, formVersion, instanceMetadata, pk, wrapper); }
From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java
public static File copyMediaFromUri(Context context, Uri uri) throws IOException { InputStream is = null;// ww w. j a v a 2 s . com OutputStream os = null; try { ContentResolver contentResolver = context.getContentResolver(); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "MAGE_" + timeStamp; MimeTypeMap mime = MimeTypeMap.getSingleton(); String extension = "." + mime.getExtensionFromMimeType(contentResolver.getType(uri)); File directory = context.getExternalFilesDir("media"); File file = File.createTempFile(imageFileName, /* prefix */ extension, /* suffix */ directory /* directory */ ); is = contentResolver.openInputStream(uri); os = new FileOutputStream(file); ByteStreams.copy(is, os); return file; } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } if (os != null) { try { os.close(); } catch (IOException e) { } } } }