List of usage examples for android.webkit MimeTypeMap getSingleton
public static MimeTypeMap getSingleton()
From source file:com.bitants.wally.fragments.ImageZoomFragment.java
private void setImageAsWallpaperPicker(Uri fileUri) { Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); intent.setType("image/*"); MimeTypeMap map = MimeTypeMap.getSingleton(); String mimeType = map.getMimeTypeFromExtension("png"); intent.setDataAndType(fileUri, mimeType); intent.putExtra("mimeType", mimeType); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(intent, getString(R.string.action_set_as))); }
From source file:com.devpaul.filepickerlibrary.FilePickerActivity.java
/** * Initializes all the views in the layout of the activity. *//* www . j a va2 s.co m*/ private void initializeViews() { directoryTitle = (TextView) findViewById(R.id.file_directory_title); addButton = (MaterialFloatingActionButton) findViewById(R.id.file_picker_add_button); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NameFileDialog nfd = NameFileDialog.newInstance(); nfd.show(getFragmentManager(), "NameDialog"); } }); if (fabColorId != -1) { addButton.setButtonColor(getResources().getColor(fabColorId)); } selectButton = (Button) findViewById(R.id.select_button); selectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (requestCode == REQUEST_DIRECTORY) { if (currentFile.isDirectory()) { curDirectory = currentFile; data = new Intent(); data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath()); setResult(RESULT_OK, data); finish(); } else { SnackbarManager.show(Snackbar.with(FilePickerActivity.this) .text(R.string.file_picker_snackbar_select_directory_message).duration(1500)); } } else { //request code is for a file if (currentFile.isDirectory()) { curDirectory = currentFile; new UpdateFilesTask(FilePickerActivity.this).execute(curDirectory); } else { if (mimeType != null) { MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); String requiredExtension = "." + mimeTypeMap.getExtensionFromMimeType(mimeType); if (requiredExtension.equalsIgnoreCase(fileExt(currentFile.toString()))) { data = new Intent(); data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath()); setResult(RESULT_OK, data); finish(); } else { SnackbarManager.show(Snackbar.with(FilePickerActivity.this) .text(String.format( getString(R.string.file_picker_snackbar_select_file_ext_message), requiredExtension)) .duration(1500)); } } else { data = new Intent(); data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath()); setResult(RESULT_OK, data); finish(); } } } } }); openButton = (Button) findViewById(R.id.open_button); openButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (currentFile.isDirectory()) { curDirectory = currentFile; directoryTitle.setText(curDirectory.getName()); new UpdateFilesTask(FilePickerActivity.this).execute(curDirectory); } else { Intent newIntent = new Intent(android.content.Intent.ACTION_VIEW); String file = currentFile.toString(); if (file != null) { newIntent.setDataAndType(Uri.fromFile(currentFile), mimeType); newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { startActivity(newIntent); } catch (android.content.ActivityNotFoundException e) { SnackbarManager.show(Snackbar.with(FilePickerActivity.this) .text(R.string.file_picker_snackbar_no_file_type_handler)); } } else { SnackbarManager.show(Snackbar.with(FilePickerActivity.this) .text(R.string.file_picker_snackbar_no_read_type)); } } } }); buttonContainer = (LinearLayout) findViewById(R.id.button_container); buttonContainer.setVisibility(View.INVISIBLE); header = (RelativeLayout) findViewById(R.id.header_container); }
From source file:com.mpower.mintel.android.tasks.InstanceUploaderTask.java
@Override protected HashMap<String, String> doInBackground(Long... values) { mResults = new HashMap<String, String>(); String postResponse;//from ww w . j ava 2s .c o m String selection = InstanceColumns._ID + "=?"; String[] selectionArgs = new String[values.length]; for (int i = 0; i < values.length; i++) { if (i != values.length - 1) { selection += " or " + InstanceColumns._ID + "=?"; } selectionArgs[i] = values[i].toString(); } // get shared HttpContext so that authentication and cookies are // retained. HttpContext localContext = MIntel.getInstance().getHttpContext(); HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT); Map<URI, URI> uriRemap = new HashMap<URI, URI>(); Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c.getCount() > 0) { c.moveToPosition(-1); next_submission: while (c.moveToNext()) { if (isCancelled()) { return mResults; } publishProgress(c.getPosition() + 1, c.getCount()); String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); String id = c.getString(c.getColumnIndex(InstanceColumns._ID)); Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id); String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI)); if (urlString == null) { SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(MIntel.getInstance()); urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null); urlString = urlString + WebUtils.URL_PART_SUBMISSION; } ContentValues cv = new ContentValues(); URI u = null; try { URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (MalformedURLException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (URISyntaxException e) { e.printStackTrace(); mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (UnsupportedEncodingException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } boolean openRosaServer = false; if (uriRemap.containsKey(u)) { // we already issued a head request and got a response, // so we know the proper URL to send the submission to // and the proper scheme. We also know that it was an // OpenRosa compliant server. openRosaServer = true; u = uriRemap.get(u); } else { // we need to issue a head request HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u); // prepare response HttpResponse response = null; try { response = httpclient.execute(httpHead, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { // we need authentication, so stop and return what // we've // done so far. mAuthRequestingServer = u; return null; } else if (statusCode == 204) { Header[] locations = response.getHeaders("Location"); if (locations != null && locations.length == 1) { try { URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8")); URI uNew = url.toURI(); if (u.getHost().equalsIgnoreCase(uNew.getHost())) { openRosaServer = true; // trust the server to tell us a new // location // ... and possibly to use https // instead. uriRemap.put(u, uNew); u = uNew; } else { // Don't follow a redirection attempt to // a different host. // We can't tell if this is a spoof or // not. mResults.put(id, fail + "Unexpected redirection attempt to a different host: " + uNew.toString()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } catch (Exception e) { e.printStackTrace(); mResults.put(id, fail + urlString + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } else { // may be a server that does not handle try { // have to read the stream in order to reuse the // connection InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) ; is.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } Log.w(t, "Status code on Head request: " + statusCode); if (statusCode >= 200 && statusCode <= 299) { mResults.put(id, fail + "Invalid status code on Head request. If you have a web proxy, you may need to login to your network. "); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } catch (ClientProtocolException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Client Protocol Exception"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (ConnectTimeoutException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Connection Timeout"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (UnknownHostException e) { e.printStackTrace(); mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (Exception e) { e.printStackTrace(); mResults.put(id, fail + "Generic Exception"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } // At this point, we may have updated the uri to use https. // This occurs only if the Location header keeps the host name // the same. If it specifies a different host name, we error // out. // // And we may have set authentication cookies in our // cookiestore (referenced by localContext) that will enable // authenticated publication to the server. // // get instance file File instanceFile = new File(instance); if (!instanceFile.exists()) { mResults.put(id, fail + "instance XML file does not exist!"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } // find all files in parent directory File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files List<File> files = new ArrayList<File>(); for (File f : allFiles) { String fileName = f.getName(); int dotIndex = fileName.lastIndexOf("."); String extension = ""; if (dotIndex != -1) { extension = fileName.substring(dotIndex + 1); } if (fileName.startsWith(".")) { // ignore invisible files continue; } if (fileName.equals(instanceFile.getName())) { continue; // the xml file has already been added } else if (openRosaServer) { files.add(f); } else if (extension.equals("jpg")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gpp")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gp")) { // legacy 0.9x files.add(f); } else if (extension.equals("mp4")) { // legacy 0.9x files.add(f); } else if (extension.equals("amr")) { // legacy 0.9x files.add(f); } else { Log.w(t, "unrecognized file type " + f.getName()); } } postResponse = ""; boolean first = true; int j = 0; while (j < files.size() || first) { first = false; HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth); MimeTypeMap m = MimeTypeMap.getSingleton(); long byteCount = 0L; // mime post MultipartEntity entity = new MultipartEntity(); // add the submission file first... FileBody fb = new FileBody(instanceFile, "text/xml"); entity.addPart("xml_submission_file", fb); Log.i(t, "added xml_submission_file: " + instanceFile.getName()); byteCount += instanceFile.length(); for (; j < files.size(); j++) { File f = files.get(j); String fileName = f.getName(); int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } String contentType = m.getMimeTypeFromExtension(extension); // we will be processing every one of these, so // we only need to deal with the content type // determination... if (extension.equals("xml")) { fb = new FileBody(f, "text/xml"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xml file " + f.getName()); } else if (extension.equals("jpg")) { fb = new FileBody(f, "image/jpeg"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added image file " + f.getName()); } else if (extension.equals("3gpp")) { fb = new FileBody(f, "audio/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("3gp")) { fb = new FileBody(f, "video/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("mp4")) { fb = new FileBody(f, "video/mp4"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("csv")) { fb = new FileBody(f, "text/csv"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added csv file " + f.getName()); } else if (f.getName().endsWith(".amr")) { fb = new FileBody(f, "audio/amr"); entity.addPart(f.getName(), fb); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("xls")) { fb = new FileBody(f, "application/vnd.ms-excel"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xls file " + f.getName()); } else if (contentType != null) { fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName()); } else { contentType = "application/octet-stream"; fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName()); } // we've added at least one attachment to the request... if (j + 1 < files.size()) { if (byteCount + files.get(j + 1).length() > 10000000L) { // the next file would exceed the 10MB // threshold... Log.i(t, "Extremely long post is being split into multiple posts"); try { StringBody sb = new StringBody("yes", Charset.forName("UTF-8")); entity.addPart("*isIncomplete*", sb); } catch (Exception e) { e.printStackTrace(); // never happens... } ++j; // advance over the last attachment // added... break; } } } httppost.setEntity(entity); // prepare response and return uploaded HttpResponse response = null; try { response = httpclient.execute(httppost, localContext); int responseCode = response.getStatusLine().getStatusCode(); // try { // // have to read the stream in order to reuse the // connection // InputStream is = response.getEntity().getContent(); // // read to end of stream... // final long count = 1024L; // while (is.skip(count) == count) // ; // is.close(); // } catch (IOException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } HttpEntity httpEntity = response.getEntity(); try { postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim(); } catch (IOException e) { e.printStackTrace(); } Log.i(t, "Response code:" + responseCode); // verify that the response was a 201 or 202. // If it wasn't, the submission has failed. if (responseCode != 201 && responseCode != 202) { if (responseCode == 200) { mResults.put(id, fail + "Network login failure? Again?"); } else { if (postResponse.length() > 0) { mResults.put(id, postResponse); } else { mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " (" + responseCode + ") at " + urlString); } } cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } catch (Exception e) { e.printStackTrace(); mResults.put(id, fail + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } // if it got here, it must have worked if (postResponse.length() > 0) { // Custom msg from server mResults.put(id, postResponse); } else { // There is no response from server, use default string mResults.put(id, MIntel.getInstance().getString(R.string.success)); } // mResults.put(id, // MIntel.getInstance().getString(R.string.success)); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); } if (c != null) { c.close(); } } // end while return mResults; }
From source file:com.github.developerpaul123.filepickerlibrary.FilePickerActivity.java
/** * Initializes all the views in the layout of the activity. *//*from www . jav a2 s . c om*/ private void initializeViews() { directoryTitle = (TextView) findViewById(R.id.file_directory_title); addButton = (MaterialFloatingActionButton) findViewById(R.id.file_picker_add_button); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NameFileDialog nfd = NameFileDialog.newInstance(); nfd.show(getFragmentManager(), "NameDialog"); } }); if (fabColorId != -1) { addButton.setButtonColor(getResources().getColor(fabColorId)); } selectButton = (Button) findViewById(R.id.select_button); selectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (requestCode == Request.DIRECTORY) { if (currentFile.isDirectory()) { curDirectory = currentFile; data = new Intent(); data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath()); setResult(RESULT_OK, data); finish(); } else { Snackbar.make(getWindow().getDecorView(), R.string.file_picker_snackbar_select_directory_message, Snackbar.LENGTH_SHORT) .show(); } } else { //request code is for a file if (currentFile.isDirectory()) { curDirectory = currentFile; new UpdateFilesTask(FilePickerActivity.this).execute(curDirectory); } else { if (!TextUtils.isEmpty(mimeType)) { MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); String requiredExtension = "." + mimeTypeMap.getExtensionFromMimeType(mimeType); if (requiredExtension.equalsIgnoreCase(fileExt(currentFile.toString()))) { data = new Intent(); data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath()); setResult(RESULT_OK, data); finish(); } else { Snackbar.make(getWindow().getDecorView(), String.format( getString(R.string.file_picker_snackbar_select_file_ext_message), requiredExtension), Snackbar.LENGTH_SHORT).show(); } } else { data = new Intent(); data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath()); setResult(RESULT_OK, data); finish(); } } } } }); openButton = (Button) findViewById(R.id.open_button); openButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (currentFile.isDirectory()) { curDirectory = currentFile; directoryTitle.setText(curDirectory.getName()); new UpdateFilesTask(FilePickerActivity.this).execute(curDirectory); } else { Intent newIntent = new Intent(Intent.ACTION_VIEW); String file = currentFile.toString(); if (file != null) { newIntent.setDataAndType(Uri.fromFile(currentFile), mimeType); newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { startActivity(newIntent); } catch (ActivityNotFoundException e) { Snackbar.make(getWindow().getDecorView(), R.string.file_picker_snackbar_no_file_type_handler, Snackbar.LENGTH_SHORT) .show(); } } else { Snackbar.make(getWindow().getDecorView(), R.string.file_picker_snackbar_no_read_type, Snackbar.LENGTH_SHORT).show(); } } } }); buttonContainer = (LinearLayout) findViewById(R.id.button_container); buttonContainer.setVisibility(View.INVISIBLE); header = (RelativeLayout) findViewById(R.id.header_container); }
From source file:com.bitants.wally.activities.ImageDetailsActivity.java
private void setImageAsWallpaperPicker(Uri path) { Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); intent.setType("image/*"); MimeTypeMap map = MimeTypeMap.getSingleton(); String mimeType = map.getMimeTypeFromExtension("png"); intent.setDataAndType(path, mimeType); intent.putExtra("mimeType", mimeType); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(intent, getString(R.string.action_set_as))); }
From source file:com.mpower.daktar.android.tasks.InstanceUploaderTask.java
@Override protected HashMap<String, String> doInBackground(final Long... values) { mResults = new HashMap<String, String>(); String postResponse;//from www .j a va 2s . c om String selection = BaseColumns._ID + "=?"; final String[] selectionArgs = new String[values.length]; for (int i = 0; i < values.length; i++) { if (i != values.length - 1) { selection += " or " + BaseColumns._ID + "=?"; } selectionArgs[i] = values[i].toString(); } // get shared HttpContext so that authentication and cookies are // retained. final HttpContext localContext = MIntel.getInstance().getHttpContext(); final HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT); final Map<URI, URI> uriRemap = new HashMap<URI, URI>(); final Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c.getCount() > 0) { c.moveToPosition(-1); next_submission: while (c.moveToNext()) { if (isCancelled()) return mResults; publishProgress(c.getPosition() + 1, c.getCount()); final String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); final String id = c.getString(c.getColumnIndex(BaseColumns._ID)); final Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id); String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI)); if (urlString == null) { final SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(MIntel.getInstance()); urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null); urlString = urlString + WebUtils.URL_PART_SUBMISSION; } final ContentValues cv = new ContentValues(); URI u = null; try { final URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (final MalformedURLException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final URISyntaxException e) { e.printStackTrace(); mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final UnsupportedEncodingException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } boolean openRosaServer = false; if (uriRemap.containsKey(u)) { // we already issued a head request and got a response, // so we know the proper URL to send the submission to // and the proper scheme. We also know that it was an // OpenRosa compliant server. openRosaServer = true; u = uriRemap.get(u); } else { // we need to issue a head request final HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u); // prepare response HttpResponse response = null; try { response = httpclient.execute(httpHead, localContext); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { // we need authentication, so stop and return what // we've // done so far. mAuthRequestingServer = u; return null; } else if (statusCode == 204) { final Header[] locations = response.getHeaders("Location"); if (locations != null && locations.length == 1) { try { final URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8")); final URI uNew = url.toURI(); if (u.getHost().equalsIgnoreCase(uNew.getHost())) { openRosaServer = true; // trust the server to tell us a new // location // ... and possibly to use https // instead. uriRemap.put(u, uNew); u = uNew; } else { // Don't follow a redirection attempt to // a different host. // We can't tell if this is a spoof or // not. mResults.put(id, fail + "Unexpected redirection attempt to a different host: " + uNew.toString()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + urlString + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } else { // may be a server that does not handle try { // have to read the stream in order to reuse the // connection final InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) { ; } is.close(); } catch (final IOException e) { e.printStackTrace(); } catch (final Exception e) { e.printStackTrace(); } Log.w(t, "Status code on Head request: " + statusCode); if (statusCode >= 200 && statusCode <= 299) { mResults.put(id, fail + "Invalid status code on Head request. If you have a web proxy, you may need to login to your network. "); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } catch (final ClientProtocolException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Client Protocol Exception"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final ConnectTimeoutException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Connection Timeout"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final UnknownHostException e) { e.printStackTrace(); mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + "Generic Exception"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } // At this point, we may have updated the uri to use https. // This occurs only if the Location header keeps the host name // the same. If it specifies a different host name, we error // out. // // And we may have set authentication cookies in our // cookiestore (referenced by localContext) that will enable // authenticated publication to the server. // // get instance file final File instanceFile = new File(instance); if (!instanceFile.exists()) { mResults.put(id, fail + "instance XML file does not exist!"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } // find all files in parent directory final File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files final List<File> files = new ArrayList<File>(); for (final File f : allFiles) { final String fileName = f.getName(); final int dotIndex = fileName.lastIndexOf("."); String extension = ""; if (dotIndex != -1) { extension = fileName.substring(dotIndex + 1); } if (fileName.startsWith(".")) { // ignore invisible files continue; } if (fileName.equals(instanceFile.getName())) { continue; // the xml file has already been added } else if (openRosaServer) { files.add(f); } else if (extension.equals("jpg")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gpp")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gp")) { // legacy 0.9x files.add(f); } else if (extension.equals("mp4")) { // legacy 0.9x files.add(f); } else if (extension.equals("amr")) { // legacy 0.9x files.add(f); } else { Log.w(t, "unrecognized file type " + f.getName()); } } postResponse = ""; boolean first = true; int j = 0; while (j < files.size() || first) { first = false; final HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth); final MimeTypeMap m = MimeTypeMap.getSingleton(); long byteCount = 0L; // mime post final MultipartEntity entity = new MultipartEntity(); // add the submission file first... FileBody fb = new FileBody(instanceFile, "text/xml"); entity.addPart("xml_submission_file", fb); Log.i(t, "added xml_submission_file: " + instanceFile.getName()); byteCount += instanceFile.length(); for (; j < files.size(); j++) { final File f = files.get(j); final String fileName = f.getName(); final int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } String contentType = m.getMimeTypeFromExtension(extension); // we will be processing every one of these, so // we only need to deal with the content type // determination... if (extension.equals("xml")) { fb = new FileBody(f, "text/xml"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xml file " + f.getName()); } else if (extension.equals("jpg")) { fb = new FileBody(f, "image/jpeg"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added image file " + f.getName()); } else if (extension.equals("3gpp")) { fb = new FileBody(f, "audio/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("3gp")) { fb = new FileBody(f, "video/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("mp4")) { fb = new FileBody(f, "video/mp4"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("csv")) { fb = new FileBody(f, "text/csv"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added csv file " + f.getName()); } else if (f.getName().endsWith(".amr")) { fb = new FileBody(f, "audio/amr"); entity.addPart(f.getName(), fb); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("xls")) { fb = new FileBody(f, "application/vnd.ms-excel"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xls file " + f.getName()); } else if (contentType != null) { fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName()); } else { contentType = "application/octet-stream"; fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName()); } // we've added at least one attachment to the request... if (j + 1 < files.size()) { if (byteCount + files.get(j + 1).length() > 10000000L) { // the next file would exceed the 10MB // threshold... Log.i(t, "Extremely long post is being split into multiple posts"); try { final StringBody sb = new StringBody("yes", Charset.forName("UTF-8")); entity.addPart("*isIncomplete*", sb); } catch (final Exception e) { e.printStackTrace(); // never happens... } ++j; // advance over the last attachment // added... break; } } } httppost.setEntity(entity); // prepare response and return uploaded HttpResponse response = null; try { response = httpclient.execute(httppost, localContext); final int responseCode = response.getStatusLine().getStatusCode(); // try { // // have to read the stream in order to reuse the // connection // InputStream is = response.getEntity().getContent(); // // read to end of stream... // final long count = 1024L; // while (is.skip(count) == count) // ; // is.close(); // } catch (IOException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } final HttpEntity httpEntity = response.getEntity(); try { postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim(); } catch (final IOException e) { e.printStackTrace(); } Log.i(t, "Response code:" + responseCode); // verify that the response was a 201 or 202. // If it wasn't, the submission has failed. if (responseCode != 201 && responseCode != 202) { if (responseCode == 200) { mResults.put(id, fail + "Network login failure? Again?"); } else { if (postResponse.length() > 0) { mResults.put(id, postResponse); } else { mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " (" + responseCode + ") at " + urlString); } } cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } // if it got here, it must have worked if (postResponse.length() > 0) { // Custom msg from server mResults.put(id, postResponse); } else { // There is no response from server, use default string mResults.put(id, MIntel.getInstance().getString(R.string.success)); } // mResults.put(id, // MIntel.getInstance().getString(R.string.success)); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); } if (c != null) { c.close(); } } // end while return mResults; }
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 w w . j a v a 2s . c o m*/ else { closeAction(); startActivity(intent); close(); } } } }
From source file:com.docd.purefm.utils.MimeTypes.java
/** * It is impossible to detect whether path is a directory for sure. * Call this only if you sure the path does not point to a directory * * @param path File path/* ww w . j a v a2 s. c o m*/ * @return mime type based on file extension */ @Nullable private static String getMimeType(@NonNull final String path) { if (path.endsWith(File.separator)) { return null; } String type = null; final String extension = FilenameUtils.getExtension(FilenameUtils.getName(path)); if (extension != null && !extension.isEmpty()) { final String extensionLowerCase = extension.toLowerCase(Locale.US); final MimeTypeMap mime = MimeTypeMap.getSingleton(); type = mime.getMimeTypeFromExtension(extensionLowerCase); if (type == null) { type = MIME_TYPES.get(extensionLowerCase); } } return type; }
From source file:com.applozic.mobicommons.file.FileUtils.java
public static String getMimeType(String url) { String type = null;/*from w w w. ja v a2 s . c o m*/ String extension = MimeTypeMap.getFileExtensionFromUrl(url); if (TextUtils.isEmpty(extension) && url.contains(".")) { extension = url.substring(url.lastIndexOf('.') + 1).toLowerCase(); } if (!TextUtils.isEmpty(extension)) { MimeTypeMap mime = MimeTypeMap.getSingleton(); type = mime.getMimeTypeFromExtension(extension.toLowerCase()); } return type; }