List of usage examples for android.content ContentResolver getType
public final @Nullable String getType(@NonNull Uri url)
From source file:net.henryco.opalette.application.StartUpActivity.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == Utils.activity.REQUEST_PICK_IMAGE) { Intent intent = new Intent(this, MainActivity.class); BitmapPack.pushUpBitmap = Utils.loadIntentBitmap(this, data); ContentResolver cR = getContentResolver(); MimeTypeMap mime = MimeTypeMap.getSingleton(); if (!checkImgType(mime.getExtensionFromMimeType(cR.getType(data.getData())))) wrongTypeDialog.run();// w ww.j a v a2 s .c o m else { closeAction(); startActivity(intent); close(); } } } }
From source file:info.guardianproject.notepadbot.NoteCipher.java
private void importDataStream() { if (mCacheWord.isLocked()) return;/*w ww .j a v a2 s . c o m*/ try { ContentResolver cr = getContentResolver(); InputStream is = cr.openInputStream(dataStream); String mimeType = cr.getType(dataStream); byte[] data = NoteUtils.readBytesAndClose(is); if (data.length > NConstants.MAX_STREAM_SIZE) { Toast.makeText(this, R.string.err_size, Toast.LENGTH_LONG).show(); } else { String title = dataStream.getLastPathSegment(); String body = dataStream.getPath(); new NotesDbAdapter(mCacheWord, this).createNote(title, body, data, mimeType); Toast.makeText(this, getString(R.string.on_import, title), Toast.LENGTH_LONG).show(); // handleDelete(); data = null; dataStream = null; title = null; body = null; System.gc(); fillData(); } } catch (FileNotFoundException e) { Log.e(NConstants.TAG, e.getMessage(), e); } catch (IOException e) { Log.e(NConstants.TAG, e.getMessage(), e); } catch (OutOfMemoryError e) { Toast.makeText(this, R.string.err_size, Toast.LENGTH_LONG).show(); } finally { dataStream = null; } }
From source file:net.gsantner.opoc.util.ContextUtils.java
/** * Detect MimeType of given file/*www . j a va2s . c o m*/ * Android/Java's own MimeType map is very very small and detection barely works at all * Hence use custom map for some file extensions */ public String getMimeType(Uri uri) { String mimeType = null; if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) { ContentResolver cr = _context.getContentResolver(); mimeType = cr.getType(uri); } else { String ext = MimeTypeMap.getFileExtensionFromUrl(uri.toString()); mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext.toLowerCase()); // Try to guess if the recommended methods fail if (TextUtils.isEmpty(mimeType)) { switch (ext) { case "md": case "markdown": case "mkd": case "mdown": case "mkdn": case "mdwn": case "rmd": mimeType = "text/markdown"; break; case "yaml": case "yml": mimeType = "text/yaml"; break; case "json": mimeType = "text/json"; break; case "txt": mimeType = "text/plain"; break; } } } if (TextUtils.isEmpty(mimeType)) { mimeType = "*/*"; } return mimeType; }
From source file:org.exoplatform.utils.ExoDocumentUtils.java
/** * Gets a DocumentInfo with info coming from the document at the given URI. * /*from w ww . jav a 2 s . c o m*/ * @param contentUri the content URI of the document (content:// ...) * @param context * @return a DocumentInfo or null if an error occurs */ public static DocumentInfo documentFromContentUri(Uri contentUri, Context context) { if (contentUri == null) return null; try { ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(contentUri, null, null, null, null); int sizeIndex = c.getColumnIndex(OpenableColumns.SIZE); int nameIndex = c.getColumnIndex(OpenableColumns.DISPLAY_NAME); int orientIndex = c.getColumnIndex(MediaStore.Images.ImageColumns.ORIENTATION); c.moveToFirst(); DocumentInfo document = new DocumentInfo(); document.documentName = c.getString(nameIndex); document.documentSizeKb = c.getLong(sizeIndex) / 1024; document.documentData = cr.openInputStream(contentUri); document.documentMimeType = cr.getType(contentUri); if (orientIndex != -1) { // if found orientation column document.orientationAngle = c.getInt(orientIndex); } return document; } catch (FileNotFoundException e) { Log.d(LOG_TAG, e.getClass().getSimpleName(), e.getLocalizedMessage()); } catch (Exception e) { Log.e(LOG_TAG, "Cannot retrieve the content at " + contentUri); if (Log.LOGD) Log.d(LOG_TAG, e.getMessage() + "\n" + Log.getStackTraceString(e)); } return null; }
From source file:com.stfalcon.contentmanager.ContentManager.java
private String guessFileExtensionFromUrl(String url) { ContentResolver cR = activity.getContentResolver(); MimeTypeMap mime = MimeTypeMap.getSingleton(); String type = mime.getExtensionFromMimeType(cR.getType(Uri.parse(url))); cR.getType(Uri.parse(url));//ww w . j a va2s. co m return type; }
From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.PictureObj.java
public static DbObject from(Context context, Uri imageUri) throws IOException { // Query gallery for camera picture via // Android ContentResolver interface ContentResolver cr = context.getContentResolver(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;// ww w . jav a 2s .c o m BitmapFactory.decodeStream(cr.openInputStream(imageUri), null, options); int targetSize = 200; int xScale = (options.outWidth + targetSize - 1) / targetSize; int yScale = (options.outHeight + targetSize - 1) / targetSize; int scale = xScale < yScale ? xScale : yScale; //uncomment this to get faster power of two scaling //for(int i = 0; i < 32; ++i) { // int mushed = scale & ~(1 << i); // if(mushed != 0) // scale = mushed; //} options.inJustDecodeBounds = false; options.inSampleSize = scale; Bitmap sourceBitmap = BitmapFactory.decodeStream(cr.openInputStream(imageUri), null, options); int width = sourceBitmap.getWidth(); int height = sourceBitmap.getHeight(); int cropSize = Math.min(width, height); float scaleSize = ((float) targetSize) / cropSize; Matrix matrix = new Matrix(); matrix.postScale(scaleSize, scaleSize); float rotation = PhotoTaker.rotationForImage(context, imageUri); if (rotation != 0f) { matrix.preRotate(rotation); } Bitmap resizedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, width, height, matrix, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos); byte[] data = baos.toByteArray(); sourceBitmap.recycle(); sourceBitmap = null; resizedBitmap.recycle(); resizedBitmap = null; System.gc(); // TODO: gross. JSONObject base = new JSONObject(); if (ContentCorral.CONTENT_CORRAL_ENABLED) { try { String type = cr.getType(imageUri); if (type == null) { type = "image/jpeg"; } base.put(CorralClient.OBJ_LOCAL_URI, imageUri.toString()); base.put(CorralClient.OBJ_MIME_TYPE, type); String localIp = ContentCorral.getLocalIpAddress(); if (localIp != null) { base.put(Contact.ATTR_LAN_IP, localIp); } } catch (JSONException e) { Log.e(TAG, "impossible json error possible!"); } } return from(base, data); }
From source file:com.ibuildapp.romanblack.WebPlugin.WebPlugin.java
public void processResult(Intent data, int resultCode) { if (null == mUploadMessage) nullValueHandler();//from ww w .j av a 2s. c o m Uri result = data == null || resultCode != RESULT_OK ? null : data.getData(); String filePath = result.getPath(); Uri fileUri = Uri.fromFile(new File(filePath)); if (isMedia) { ContentResolver cR = WebPlugin.this.getContentResolver(); MimeTypeMap mime = MimeTypeMap.getSingleton(); String type = mime.getExtensionFromMimeType(cR.getType(result)); fileUri = Uri.parse(fileUri.toString() + "." + type); data.setData(fileUri); isMedia = false; } mUploadMessage.onReceiveValue(fileUri); mUploadMessage = null; }
From source file:org.linkdroid.PostJob.java
/** * Posts the data to our webhook./*w w w. j a va 2 s . com*/ * * The HMAC field calculation notes: * <ol> * <li>The Extras.HMAC field is calculated from all the non Extras.STREAM * fields; this includes all the original bundle extra fields, plus the * linkdroid fields (e.g Extras.STREAM_MIME_TYPE, and including * Extras.STREAM_HMAC); the NONCE is NOT prepended to the input since it will * be somewhere in the data bundle.</li> * <li>The Extras.STREAM_HMAC field is calculated by digesting the concat of * the NONCE (first) and the actual binary data obtained from the * EXTRAS_STREAM uri; this STREAM_HMAC field (along with the other * Extras.STREAM_* fields) are added to the data bundle, which will also be * hmac'd.</li> * <li>If no hmac secret is set, then the NONCEs will not be set in the upload * </li> * </ol> * * @param contentResolver * @param webhook * @param data * @throws UnsupportedEncodingException * @throws IOException * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ public static void execute(ContentResolver contentResolver, Bundle webhook, Bundle data) throws UnsupportedEncodingException, IOException, InvalidKeyException, NoSuchAlgorithmException { // Set constants that may be used in this method. final String secret = webhook.getString(WebhookColumns.SECRET); // This is the multipart form object that will contain all the data bundle // extras; it also will include the data of the extra stream and any other // extra linkdroid specific field required. MultipartEntity entity = new MultipartEntity(); // Do the calculations to create our nonce string, if necessary. String nonce = obtainNonce(webhook); // Add the nonce to the data bundle if we have it. if (nonce != null) { data.putString(Extras.NONCE, nonce); } // We have a stream of data, so we need to add that to the multipart form // upload with a possible HMAC. if (data.containsKey(Intent.EXTRA_STREAM)) { Uri mediaUri = (Uri) data.get(Intent.EXTRA_STREAM); // Open our mediaUri, base 64 encode it and add it to our multipart upload // entity. ByteArrayOutputStream baos = new ByteArrayOutputStream(); Base64OutputStream b64os = new Base64OutputStream(baos); InputStream is = contentResolver.openInputStream(mediaUri); byte[] bytes = new byte[1024]; int count; while ((count = is.read(bytes)) != -1) { b64os.write(bytes, 0, count); } is.close(); baos.close(); b64os.close(); final String base64EncodedString = new String(baos.toByteArray(), UTF8); entity.addPart(Extras.STREAM, new StringBody(base64EncodedString, UTF8_CHARSET)); // Add the mimetype of the stream to the data bundle. final String mimeType = contentResolver.getType(mediaUri); if (mimeType != null) { data.putString(Extras.STREAM_MIME_TYPE, mimeType); } // Do the hmac calculation of the stream and add it to the data bundle. // NOTE: This hmac string will be included as part of the input to the // other Extras hmac. if (shouldDoHmac(webhook)) { InputStream inputStream = contentResolver.openInputStream(mediaUri); final String streamHmac = hmacSha1(inputStream, secret, nonce); inputStream.close(); data.putString(Extras.STREAM_HMAC, streamHmac); Log.d(TAG, "STREAM_HMAC: " + streamHmac); } } // Calculate the Hmac for all the items by iterating over the data bundle // keys in order. if (shouldDoHmac(webhook)) { final String dataHmac = calculateBundleExtrasHmac(data, secret); data.putString(Extras.HMAC, dataHmac); Log.d(TAG, "HMAC: " + dataHmac); } // Dump all the data bundle keys into the form. for (String k : data.keySet()) { Object value = data.get(k); // If the value is null, the key will still be in the form, but with // an empty string as its value. if (value != null) { entity.addPart(k, new StringBody(value.toString(), UTF8_CHARSET)); } else { entity.addPart(k, new StringBody("", UTF8_CHARSET)); } } // Create the client and request, then populate it with our multipart form // upload entity as part of the POST request; finally post the form. final String webhookUri = webhook.getString(WebhookColumns.URI); final HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(USER_AGENT_KEY, USER_AGENT); final HttpPost request = new HttpPost(webhookUri); request.setEntity(entity); HttpResponse response = client.execute(request); switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: case HttpStatus.SC_ACCEPTED: break; default: throw new RuntimeException(response.getStatusLine().toString()); } }
From source file:org.awesomeapp.messenger.ui.AccountViewFragment.java
private void initFragment() { Intent i = getIntent();/*from www . j a v a2 s . c om*/ mApp = (ImApp) getActivity().getApplication(); String action = i.getAction(); if (i.hasExtra("isSignedIn")) isSignedIn = i.getBooleanExtra("isSignedIn", false); final ProviderDef provider; mSignInHelper = new SignInHelper(getActivity(), new SimpleAlertHandler(getActivity())); SignInHelper.SignInListener signInListener = new SignInHelper.SignInListener() { @Override public void connectedToService() { } @Override public void stateChanged(int state, long accountId) { if (state == ImConnection.LOGGED_IN) { // mSignInHelper.goToAccount(accountId); // finish(); isSignedIn = true; } else { isSignedIn = false; } } }; mSignInHelper.setSignInListener(signInListener); ContentResolver cr = getActivity().getContentResolver(); Uri uri = i.getData(); // check if there is account information and direct accordingly if (Intent.ACTION_INSERT_OR_EDIT.equals(action)) { if ((uri == null) || !Imps.Account.CONTENT_ITEM_TYPE.equals(cr.getType(uri))) { action = Intent.ACTION_INSERT; } else { action = Intent.ACTION_EDIT; } } if (Intent.ACTION_INSERT.equals(action) && uri.getScheme().equals("ima")) { ImPluginHelper helper = ImPluginHelper.getInstance(getActivity()); String authority = uri.getAuthority(); String[] userpass_host = authority.split("@"); String[] user_pass = userpass_host[0].split(":"); mUserName = user_pass[0].toLowerCase(Locale.getDefault()); String pass = user_pass[1]; mDomain = userpass_host[1].toLowerCase(Locale.getDefault()); mPort = 0; final boolean regWithTor = i.getBooleanExtra("useTor", false); Cursor cursor = openAccountByUsernameAndDomain(cr); boolean exists = cursor.moveToFirst(); long accountId; if (exists) { accountId = cursor.getLong(0); mAccountUri = ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId); pass = cursor.getString(ACCOUNT_PASSWORD_COLUMN); setAccountKeepSignedIn(true); mSignInHelper.activateAccount(mProviderId, accountId); mSignInHelper.signIn(pass, mProviderId, accountId, true); // setResult(RESULT_OK); cursor.close(); // finish(); return; } else { mProviderId = helper.createAdditionalProvider(helper.getProviderNames().get(0)); //xmpp FIXME accountId = ImApp.insertOrUpdateAccount(cr, mProviderId, -1, mUserName, mUserName, pass); mAccountUri = ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId); mSignInHelper.activateAccount(mProviderId, accountId); createNewAccount(mUserName, pass, accountId, regWithTor); cursor.close(); return; } } else if (Intent.ACTION_INSERT.equals(action)) { mOriginalUserAccount = ""; // TODO once we implement multiple IM protocols mProviderId = ContentUris.parseId(uri); provider = mApp.getProvider(mProviderId); } else if (Intent.ACTION_EDIT.equals(action)) { if ((uri == null) || !Imps.Account.CONTENT_ITEM_TYPE.equals(cr.getType(uri))) { LogCleaner.warn(ImApp.LOG_TAG, "<AccountActivity>Bad data"); return; } isEdit = true; Cursor cursor = cr.query(uri, ACCOUNT_PROJECTION, null, null, null); if (cursor == null) { return; } if (!cursor.moveToFirst()) { cursor.close(); return; } mAccountId = cursor.getLong(cursor.getColumnIndexOrThrow(BaseColumns._ID)); mProviderId = cursor.getLong(ACCOUNT_PROVIDER_COLUMN); provider = mApp.getProvider(mProviderId); Cursor pCursor = cr.query(Imps.ProviderSettings.CONTENT_URI, new String[] { Imps.ProviderSettings.NAME, Imps.ProviderSettings.VALUE }, Imps.ProviderSettings.PROVIDER + "=?", new String[] { Long.toString(mProviderId) }, null); Imps.ProviderSettings.QueryMap settings = new Imps.ProviderSettings.QueryMap(pCursor, cr, mProviderId, false /* don't keep updated */, null /* no handler */); try { mOriginalUserAccount = cursor.getString(ACCOUNT_USERNAME_COLUMN) + "@" + settings.getDomain(); mEditUserAccount.setText(mOriginalUserAccount); mEditPass.setText(cursor.getString(ACCOUNT_PASSWORD_COLUMN)); //mRememberPass.setChecked(!cursor.isNull(ACCOUNT_PASSWORD_COLUMN)); //mUseTor.setChecked(settings.getUseTor()); mBtnQrDisplay.setVisibility(View.VISIBLE); } finally { settings.close(); cursor.close(); } } else { LogCleaner.warn(ImApp.LOG_TAG, "<AccountActivity> unknown intent action " + action); return; } setupUIPost(); }
From source file:com.mobicage.rogerthat.util.ui.SendMessageView.java
private void setFileExtemsionFromUri(Uri file) { L.d("setFileExtemsionFromUri: " + file.toString()); final ContentResolver cr = mActivity.getContentResolver(); final String fileType = cr.getType(file); L.d("fileType: " + fileType); if (fileType == null) { // lets hope it was a correct... } else {/*from ww w . jav a2 s . c o m*/ if (fileType.toLowerCase(Locale.US).startsWith("image/")) { if (AttachmentViewerActivity.CONTENT_TYPE_PNG.equalsIgnoreCase(fileType)) { mUploadFileExtenstion = AttachmentViewerActivity.CONTENT_TYPE_PNG; } else { mUploadFileExtenstion = AttachmentViewerActivity.CONTENT_TYPE_JPEG; } } else if (!AttachmentViewerActivity.CONTENT_TYPE_VIDEO_MP4.equalsIgnoreCase(fileType)) { L.bug("A video convert is needed for type: " + fileType); } } }