List of usage examples for android.webkit MimeTypeMap getSingleton
public static MimeTypeMap getSingleton()
From source file:com.pheromone.plugins.FileUtils.java
/** * Looks up the mime type of a given file name. * * @param filename/*from w w w .java 2 s.co m*/ * @return a mime type */ public static String getMimeType(String filename) { MimeTypeMap map = MimeTypeMap.getSingleton(); return map.getMimeTypeFromExtension(map.getFileExtensionFromUrl(filename)); }
From source file:com.ibuildapp.romanblack.WebPlugin.WebPlugin.java
public void processResult(Intent data, int resultCode) { if (null == mUploadMessage) nullValueHandler();//from www . j a va2 s . co 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: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));/*from w w w . j a v a2 s. c o m*/ return type; }
From source file:com.keylesspalace.tusky.activity.ComposeActivity.java
private void uploadMedia(final QueuedMedia item) { item.readyStage = QueuedMedia.ReadyStage.UPLOADING; final String mimeType = getContentResolver().getType(item.uri); MimeTypeMap map = MimeTypeMap.getSingleton(); String fileExtension = map.getExtensionFromMimeType(mimeType); final String filename = String.format("%s_%s_%s.%s", getString(R.string.app_name), String.valueOf(new Date().getTime()), randomAlphanumericString(10), fileExtension); byte[] content = item.content; if (content == null) { InputStream stream;/*w w w .java2 s .c om*/ try { stream = getContentResolver().openInputStream(item.uri); } catch (FileNotFoundException e) { return; } content = inputStreamGetBytes(stream); IOUtils.closeQuietly(stream); if (content == null) { return; } } RequestBody requestFile = RequestBody.create(MediaType.parse(mimeType), content); MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, requestFile); item.uploadRequest = mastodonAPI.uploadMedia(body); item.uploadRequest.enqueue(new Callback<Media>() { @Override public void onResponse(Call<Media> call, retrofit2.Response<Media> response) { if (response.isSuccessful()) { item.id = response.body().id; waitForMediaLatch.countDown(); } else { Log.d(TAG, "Upload request failed. " + response.message()); onUploadFailure(item, call.isCanceled()); } } @Override public void onFailure(Call<Media> call, Throwable t) { Log.d(TAG, t.getMessage()); onUploadFailure(item, false); } }); }
From source file:org.exoplatform.utils.ExoDocumentUtils.java
/** * Gets a DocumentInfo with info coming from the file at the given URI. * /* www.j av a 2s . c om*/ * @param fileUri the file URI (file:// ...) * @return a DocumentInfo or null if an error occurs */ public static DocumentInfo documentFromFileUri(Uri fileUri) { if (fileUri == null) return null; try { URI uri = new URI(fileUri.toString()); File file = new File(uri); DocumentInfo document = new DocumentInfo(); document.documentName = file.getName(); document.documentSizeKb = file.length() / 1024; document.documentData = new FileInputStream(file); // Guess the mime type in 2 ways try { // 1) by inspecting the file's first bytes document.documentMimeType = URLConnection.guessContentTypeFromStream(document.documentData); } catch (IOException e) { document.documentMimeType = null; } if (document.documentMimeType == null) { // 2) if it fails, by stripping the extension of the filename // and getting the mime type from it String extension = ""; int dotPos = document.documentName.lastIndexOf('.'); if (0 <= dotPos) extension = document.documentName.substring(dotPos + 1); document.documentMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } // Get the orientation angle from the EXIF properties if ("image/jpeg".equals(document.documentMimeType)) document.orientationAngle = getExifOrientationAngleFromFile(file.getAbsolutePath()); return document; } catch (URISyntaxException e) { Log.e(LOG_TAG, "Cannot retrieve the file at " + fileUri); if (Log.LOGD) Log.d(LOG_TAG, e.getMessage() + "\n" + Log.getStackTraceString(e)); } catch (FileNotFoundException e) { Log.e(LOG_TAG, "Cannot retrieve the file at " + fileUri); if (Log.LOGD) Log.d(LOG_TAG, e.getMessage() + "\n" + Log.getStackTraceString(e)); } return null; }
From source file:com.jp.miaulavirtual.DisplayMessageActivity.java
public int downloadFile(String request) { URL url2;// w w w . j ava2 s .co m URLConnection conn; int lastSlash; Long fileSize = null; BufferedInputStream inStream; BufferedOutputStream outStream; FileOutputStream fileStream; String cookies = cookieFormat(scookie); // format cookie for URL setRequestProperty final int BUFFER_SIZE = 23 * 1024; int id = 1; File file = null; Log.d("Document", "2 respueesta"); try { // Just resources lastSlash = url.toString().lastIndexOf('/'); // Directory creation String root = Environment.getExternalStorageDirectory().toString(); Boolean isSDPresent = android.os.Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED); // check if is there external storage if (!isSDPresent) { task_status = false; id = 9; } else { String folder; if (comunidades) { folder = onData.get(2)[1]; } else { folder = onData.get(1)[1]; } folder = folder.replaceAll( "\\d{4}-\\d{4}\\s|\\d{4}-\\d{2}\\s|Documentos\\sde\\s?|Gr\\..+?\\s|\\(.+?\\)", ""); folder = folder.toString().trim(); Log.d("Folder", folder); File myDir = new File(root + "/Android/data/com.jp.miaulavirtual/files/" + folder); myDir.mkdirs(); // Document creation String name = url.toString().substring(lastSlash + 1); file = new File(myDir, name); Log.d("Document", name); fileSize = (long) file.length(); // Check if we have already downloaded the whole file if (file.exists()) { dialog.setProgress(100); // full progress if file already donwloaded } else { // Start the connection with COOKIES (we already verified that the cookies aren't expired and we can use them) url2 = new URL(request); conn = url2.openConnection(); conn.setUseCaches(false); conn.setRequestProperty("Cookie", cookies); conn.setConnectTimeout(10 * 1000); conn.setReadTimeout(20 * 1000); fileSize = (long) conn.getContentLength(); // Check if we have necesary space if (fileSize >= myDir.getUsableSpace()) { task_status = false; id = 2; } else { // Start downloading inStream = new BufferedInputStream(conn.getInputStream()); fileStream = new FileOutputStream(file); outStream = new BufferedOutputStream(fileStream, BUFFER_SIZE); byte[] data = new byte[BUFFER_SIZE]; int bytesRead = 0; int setMax = (conn.getContentLength() / 1024); dialog.setMax(setMax); while (task_status && (bytesRead = inStream.read(data, 0, data.length)) >= 0) { outStream.write(data, 0, bytesRead); // update progress bar dialog.incrementProgressBy((int) (bytesRead / 1024)); } // Close stream outStream.close(); fileStream.close(); inStream.close(); // Delete file if Cancel button if (!task_status) { file.delete(); if (myDir.listFiles().length <= 0) myDir.delete(); id = 0; } } } Log.d("Status", String.valueOf(task_status)); // Open file if (task_status) { Log.d("Type", "Hola2"); dialog.dismiss(); Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); MimeTypeMap mime = MimeTypeMap.getSingleton(); // Get extension file String file_s = file.toString(); String extension = ""; int i = file_s.lastIndexOf('.'); int p = Math.max(file_s.lastIndexOf('/'), file_s.lastIndexOf('\\')); if (i > p) { extension = file_s.substring(i + 1); } // Get extension reference String doc_type = mime.getMimeTypeFromExtension(extension); Log.d("Type", extension); intent.setDataAndType(Uri.fromFile(file), doc_type); startActivity(intent); } } } catch (MalformedURLException e) // Invalid URL { task_status = false; if (file.exists()) { file.delete(); } id = 3; } catch (FileNotFoundException e) // FIle not found { task_status = false; if (file.exists()) { file.delete(); } id = 4; } catch (SocketTimeoutException e) // time out { Log.d("Timeout", "Timeout"); task_status = false; if (file.exists()) { file.delete(); } id = 7; } catch (Exception e) // General error { task_status = false; if (file.exists()) { file.delete(); } id = 8; } Log.d("Type", String.valueOf(id)); Log.d("StartOk3", "Como he llegado hasta aqu?"); // notify completion Log.d("ID", String.valueOf(id)); return id; }
From source file:com.fa.mastodon.activity.ComposeActivity.java
private void uploadMedia(final QueuedMedia item) { item.readyStage = QueuedMedia.ReadyStage.UPLOADING; final String mimeType = getContentResolver().getType(item.uri); MimeTypeMap map = MimeTypeMap.getSingleton(); String fileExtension = map.getExtensionFromMimeType(mimeType); final String filename = String.format("%s_%s_%s.%s", getString(R.string.app_name), String.valueOf(new Date().getTime()), randomAlphanumericString(10), fileExtension); byte[] content = item.content; if (content == null) { InputStream stream;//from w w w .j a v a 2 s . c o m try { stream = getContentResolver().openInputStream(item.uri); } catch (FileNotFoundException e) { return; } content = inputStreamGetBytes(stream); IOUtils.closeQuietly(stream); if (content == null) { return; } } RequestBody requestFile = RequestBody.create(MediaType.parse(mimeType), content); MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, requestFile); item.uploadRequest = mastodonAPI.uploadMedia(body); item.uploadRequest.enqueue(new Callback<Media>() { @Override public void onResponse(Call<Media> call, retrofit2.Response<Media> response) { if (response.isSuccessful()) { onUploadSuccess(item, response.body()); } else { Log.d(TAG, "Upload request failed. " + response.message()); onUploadFailure(item, call.isCanceled()); } } @Override public void onFailure(Call<Media> call, Throwable t) { Log.d(TAG, t.getMessage()); onUploadFailure(item, false); } }); }
From source file:android.webkit.LoadListener.java
/** * guess MIME type based on the file extension. *//* www . j a va 2s . co m*/ private String guessMimeTypeFromExtension() { // PENDING: need to normalize url if (Config.LOGV) { Log.v(LOGTAG, "guessMimeTypeFromExtension: mURL = " + mUrl); } String mimeType = MimeTypeMap.getSingleton() .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mUrl)); if (mimeType != null) { // XXX: Until the servers send us either correct xhtml or // text/html, treat application/xhtml+xml as text/html. if (mimeType.equals("application/xhtml+xml")) { mimeType = "text/html"; } } return mimeType; }
From source file:com.todoroo.astrid.activity.TaskEditFragment.java
private void attachFile(String file) { File src = new File(file); if (!src.exists()) { Toast.makeText(getActivity(), R.string.file_err_copy, Toast.LENGTH_LONG).show(); return;/*w ww . j av a2 s . c o m*/ } File dst = new File(FileUtilities.getAttachmentsDirectory(getActivity()) + File.separator + src.getName()); try { AndroidUtilities.copyFile(src, dst); } catch (Exception e) { Toast.makeText(getActivity(), R.string.file_err_copy, Toast.LENGTH_LONG).show(); return; } String path = dst.getAbsolutePath(); String name = dst.getName(); String extension = AndroidUtilities.getFileExtension(name); String type = TaskAttachment.FILE_TYPE_OTHER; if (!TextUtils.isEmpty(extension)) { MimeTypeMap map = MimeTypeMap.getSingleton(); String guessedType = map.getMimeTypeFromExtension(extension); if (!TextUtils.isEmpty(guessedType)) type = guessedType; } createNewFileAttachment(path, name, type); }
From source file:jackpal.androidterm.Term.java
private void doAndroidIntent(String filename) { if (filename == null) return;//w w w .jav a 2s.co m String str[] = new String[3]; try { File file = new File(filename); BufferedReader br = new BufferedReader(new FileReader(file)); for (int i = 0; i < 3; i++) { str[i] = br.readLine(); if (str[i] == null) break; } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } String action = str[0]; if (action == null || str[1] == null) return; TermSession session = getCurrentTermSession(); if (session != null) { if (action.equalsIgnoreCase("activity")) { try { startActivity(new Intent(this, Class.forName(str[1]))); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else if (action.matches("^.*(VIEW|EDIT).*")) { Intent intent = new Intent(action); String MIME; if (str[2] != null) { MIME = str[2]; } else { int ch = str[1].lastIndexOf('.'); String ext = (ch >= 0) ? str[1].substring(ch + 1) : null; MIME = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext.toLowerCase()); if (MIME != null && !MIME.equals("")) { intent.setType(MIME); } else { Log.e("CreateIntent", "MIME is Error"); } } intent.setDataAndType(Uri.parse(str[1]), MIME); startActivity(intent); } } }