List of usage examples for android.net Uri toString
public abstract String toString();
From source file:bhaskarandroidnannodegree.popularmoviesstage1.asynctasks.FetchTrailReview.java
@Override protected Void doInBackground(String... params) { if (params.length == 0) { return null; }//ww w . j av a 2s. c o m // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String movieJsonStr = null; try { // Construct the URL for the movieAPI query // Possible parameters are avaiable at OWM's forecast API page, at final String MOVIE_BASE_URL = "http://api.themoviedb.org/3/movie/"; final String APPID_PARAM = "api_key"; final String DATA = "append_to_response"; Uri builtUri = Uri.parse(MOVIE_BASE_URL).buildUpon().appendPath(params[0]) .appendQueryParameter(APPID_PARAM, BuildConfig.MOVIE_DB_API_KEY) .appendQueryParameter(DATA, "trailers,reviews").build(); URL url = new URL(builtUri.toString()); Log.v("BHASKAR", "URL=" + url.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } movieJsonStr = buffer.toString(); getMovieDataFromJson(movieJsonStr); } catch (IOException e) { //Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the movie data, there's no point in attemping // to parse it. return null; } catch (JSONException e) { //Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { //Log.e(LOG_TAG, "Error closing stream", e); } } } // This will only happen if there was an error getting or parsing the forecast. return null; }
From source file:mobisocial.musubi.nearby.scanner.GpsScannerTask.java
@Override protected List<NearbyItem> doInBackground(Void... params) { if (DBG)/*from w w w . j a va2 s .com*/ Log.d(TAG, "Scanning for nearby gps..."); while (!mmLocationScanComplete) { synchronized (mmLocationResult) { if (!mmLocationScanComplete) { try { if (DBG) Log.d(TAG, "Waiting for location results..."); mmLocationResult.wait(); } catch (InterruptedException e) { } } } } if (DBG) Log.d(TAG, "Got location " + mmLocation); if (isCancelled()) { return null; } try { if (DBG) Log.d(TAG, "Querying gps server..."); Uri uri = Uri.parse("http://bumblebee.musubi.us:6253/nearbyapi/0/findgroup"); StringBuffer sb = new StringBuffer(); DefaultHttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(uri.toString()); httpPost.addHeader("Content-Type", "application/json"); JSONArray buckets = new JSONArray(); double lat = mmLocation.getLatitude(); double lng = mmLocation.getLongitude(); long[] coords = GridHandler.getGridCoords(lat, lng, 5280 / 2); Log.i(TAG, "coords: " + Arrays.toString(coords)); //TODO: encrypt coords with mmPassword for (long c : coords) { MessageDigest md; try { byte[] obfuscate = ("sadsalt193s" + mmPassword).getBytes(); md = MessageDigest.getInstance("SHA-256"); ByteBuffer b = ByteBuffer.allocate(8 + obfuscate.length); b.putLong(c); b.put(obfuscate); String secret_bucket = Base64.encodeToString(md.digest(b.array()), Base64.DEFAULT); buckets.put(buckets.length(), secret_bucket); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("your platform does not support sha256", e); } } Log.i(TAG, "buckets: " + buckets); httpPost.setEntity(new StringEntity(buckets.toString())); try { HttpResponse execute = client.execute(httpPost); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { if (isCancelled()) { return null; } sb.append(s); } } catch (Exception e) { e.printStackTrace(); } HashSet<Pair<TByteArrayList, TByteArrayList>> dupes = new HashSet<Pair<TByteArrayList, TByteArrayList>>(); String response = sb.toString(); JSONArray groupsJSON = new JSONArray(response); Log.d(TAG, "Got " + groupsJSON.length() + " groups"); for (int i = 0; i < groupsJSON.length(); i++) { try { String s_enc_data = groupsJSON.get(i).toString(); byte[] enc_data = Base64.decode(s_enc_data, Base64.DEFAULT); byte[] key = Util.sha256(("happysalt621" + mmPassword).getBytes()); byte[] data; Cipher cipher; AlgorithmParameterSpec iv_spec; SecretKeySpec sks; try { cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); } catch (Exception e) { throw new RuntimeException("AES not supported on this platform", e); } try { iv_spec = new IvParameterSpec(enc_data, 0, 16); sks = new SecretKeySpec(key, "AES"); cipher.init(Cipher.DECRYPT_MODE, sks, iv_spec); } catch (Exception e) { throw new RuntimeException("bad iv or key", e); } try { data = cipher.doFinal(enc_data, 16, enc_data.length - 16); } catch (Exception e) { throw new RuntimeException("body decryption failed", e); } JSONObject group = new JSONObject(new String(data)); String group_name = group.getString("group_name"); byte[] group_capability = Base64.decode(group.getString("group_capability"), Base64.DEFAULT); String sharer_name = group.getString("sharer_name"); byte[] sharer_hash = Base64.decode(group.getString("sharer_hash"), Base64.DEFAULT); byte[] thumbnail = null; if (group.has("thumbnail")) thumbnail = Base64.decode(group.getString("thumbnail"), Base64.DEFAULT); int member_count = group.getInt("member_count"); int sharer_type = group.getInt("sharer_type"); Pair<TByteArrayList, TByteArrayList> p = Pair.with(new TByteArrayList(sharer_hash), new TByteArrayList(group_capability)); if (dupes.contains(p)) continue; dupes.add(p); addNearbyItem(new NearbyFeed(mContext, group_name, group_capability, sharer_name, Authority.values()[sharer_type], sharer_hash, thumbnail, member_count)); } catch (Throwable e) { Log.e(TAG, "Failed to parse group " + i, e); } } } catch (Exception e) { if (DBG) Log.d(TAG, "Error searching nearby feeds", e); } return null; }
From source file:com.cars.manager.utils.imageChooser.threads.MediaProcessorThread.java
@SuppressLint("NewApi") protected String getAbsoluteImagePathFromUri(Uri imageUri) { String[] proj = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME }; if (imageUri.toString().startsWith("content://com.android.gallery3d.provider")) { imageUri = Uri/*from www .ja va2s . c o m*/ .parse(imageUri.toString().replace("com.android.gallery3d", "com.google.android.gallery3d")); } Cursor cursor = context.getContentResolver().query(imageUri, proj, null, null, null); cursor.moveToFirst(); String filePath = ""; String imageUriString = imageUri.toString(); if (imageUriString.startsWith("content://com.google.android.gallery3d") || imageUriString.startsWith("content://com.google.android.apps.photos.content") || imageUriString.startsWith("content://com.android.providers.media.documents")) { filePath = imageUri.toString(); } else { filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.DATA)); } cursor.close(); return filePath; }
From source file:com.groupe1.miage.ujf.tracestaroute.FetchTrackTask.java
@Override protected Void doInBackground(String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; }/* ww w .j ava2 s . c om*/ String postalcodeQuery = params[0]; // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; //Pour l'instant, nombre de rsultat en dur String limit = "14"; //Cl pour acceder a l'api String api_key = "32b8fd610550"; try { final String FORECAST_BASE_URL = "http://api.la-trace.com/v1/track/search/?"; final String LIMIT_PARAM = "limit"; final String POSTAL_CODE = "postalcode"; final String API_KEY = "api_key"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon() .appendQueryParameter(POSTAL_CODE, postalcodeQuery).appendQueryParameter(API_KEY, api_key) .build(); URL url = new URL(builtUri.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); getTrackDataFromJson(forecastJsonStr); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e("ForecastFragment", "Error closing stream", e); } } } return null; }
From source file:com.example.cuisoap.agrimac.homePage.machineDetail.machineInfoFragment.java
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { Uri uri = data.getData(); Log.e("uri", uri.toString()); ContentResolver cr = context.getContentResolver(); try {// w ww.ja va 2s.c o m Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); bitmap = ImageUtils.comp(bitmap); switch (requestCode) { case 1: license_uri1 = uri; license_pic1.setImageBitmap(bitmap); license_pic1.setVisibility(View.VISIBLE); license1.setVisibility(View.GONE); license_pic1.setOnClickListener(myOnClickListener); machineDetailData.machine_license_filepath1 = ImageUtils.saveMyBitmap(bitmap, null); break; case 2: license_uri2 = uri; license_pic2.setImageBitmap(bitmap); license_pic2.setVisibility(View.VISIBLE); license2.setVisibility(View.GONE); license_pic2.setOnClickListener(myOnClickListener); machineDetailData.machine_license_filepath2 = ImageUtils.saveMyBitmap(bitmap, null); break; } } catch (FileNotFoundException e) { Log.e("Exception", e.getMessage(), e); } } else { Toast.makeText(context, "?", Toast.LENGTH_SHORT).show(); } super.onActivityResult(requestCode, resultCode, data); }
From source file:com.example.android.popularmovies.FetchMovieTask.java
@Override protected Void doInBackground(String... params) { // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String movieJsonStr = null;/*from w ww. java2 s .co m*/ String sortFormat = "popularity.desc"; String apiId = mContext.getString(R.string.api_key); try { // Construct the URL for the moviedb query final String MOVIE_BASE_URL = "http://api.themoviedb.org/3/discover/movie?"; final String SORT_PARAM = "sort_by"; final String API_ID_PARAM = "api_key"; int rowsDeleted; SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext); String sortType = pref.getString(mContext.getString(R.string.pref_sort_key), mContext.getString(R.string.pref_sort_popular)); if (sortType.equals(mContext.getString(R.string.pref_sort_popular))) { Log.v(LOG_TAG, "Sort: Order Popular"); sortFormat = "popularity.desc"; // rowsDeleted = delete( // MovieContract.MovieListEntry.TABLE_NAME, null, null); // if (rowsDeleted != 0) { // mContext.getContentResolver().notifyChange(uri, null); } else if (sortType.equals(mContext.getString(R.string.pref_sort_highestrated))) { Log.v(LOG_TAG, "Sort: Order Highest Rated"); sortFormat = "vote_average.desc"; // rowsDeleted = db.delete( // MovieContract.MovieListEntry.TABLE_NAME, null, null); // if (rowsDeleted != 0) { // mContext.getContentResolver().notifyChange(uri, null); } else if (sortType.equals(mContext.getString(R.string.pref_sort_favourite))) { Log.v(LOG_TAG, "Sort: Order Favorite"); //TODO routine for Favorite } else { Log.d(LOG_TAG, "Sort Order Not Found:" + sortType); } /* if (sortType.equals(mContext.getString(R.string.pref_sort_popular))) { Log.v(LOG_TAG, "Sort: Order Popular"); sortFormat = "popularity.desc"; } else if (sortType.equals(mContext.getString(R.string.pref_sort_highestrated))) { Log.v(LOG_TAG, "Sort: Order Highest Rated"); sortFormat = "vote_average.desc"; } else { Log.d(LOG_TAG, "Sort Order Not Found:" + sortType); }*/ Uri builtUri = Uri.parse(MOVIE_BASE_URL).buildUpon().appendQueryParameter(SORT_PARAM, sortFormat) .appendQueryParameter(API_ID_PARAM, apiId).build(); URL url = new URL(builtUri.toString()); Log.v(LOG_TAG, "Built URI " + builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } movieJsonStr = buffer.toString(); Log.v(LOG_TAG, "Movie JSON String: " + movieJsonStr); getMovieDataFromJson(movieJsonStr, sortType); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the movie data, there's no point in attemping // to parse it. } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } return null; }
From source file:com.polyvi.xface.extension.capture.MediaType.java
/** * Audio Video .//from w w w . j a v a 2 s .c o m * * @param mediaFileUri media Uri * @return JSONObject image JSONObject */ private JSONObject createAudioVideoFile(Uri mediaFileUri) { XPathResolver pathResolver = new XPathResolver(mediaFileUri.toString(), null, getContext()); String mediaStorePath = pathResolver.resolve(); File fp = new File(mediaStorePath); JSONObject obj = computeFileProp(fp); try { // ".3gp" ".3gpp" ??? type // getMimeType? if (fp.getAbsoluteFile().toString().endsWith(".3gp") || fp.getAbsoluteFile().toString().endsWith(".3gpp")) { if (mediaFileUri.toString().contains("/audio/")) { obj.put(PROP_TYPE, AUDIO_3GPP); } else { obj.put(PROP_TYPE, VIDEO_3GPP); } } } catch (JSONException e) { e.printStackTrace(); } return obj; }
From source file:com.polyvi.xface.extension.zip.XZipExt.java
/** * assets/*from w ww.ja v a 2s.c o m*/ * * @param srcFileUri * @param zos * @param entry * @throws IOException */ private void compressAssetsFile(Uri srcFileUri, ZipOutputStream zos, String entry) throws IOException, FileNotFoundException { srcFileUri = handleUri(srcFileUri); String srcPath = srcFileUri.getPath().substring(XConstant.ANDROID_ASSET.length()); if (XAssetsFileUtils.isFile(mContext, srcPath)) { zipFile(srcFileUri, zos, entry + srcFileUri.getLastPathSegment()); } else { String childrens[] = mContext.getAssets().list(srcPath); if (null == childrens || 0 == childrens.length) { XLog.e(CLASS_NAME, "Method compressAssetsFile: Source file path does not exist!"); throw new FileNotFoundException(); } Uri srcRootUri = srcFileUri; for (int index = 0; index < childrens.length; index++) { srcFileUri = Uri.parse(srcRootUri.toString() + File.separator + childrens[index]); if (XAssetsFileUtils.isFile(mContext, srcPath + File.separator + childrens[index])) { zipFile(srcFileUri, zos, entry + childrens[index]); } else { compressAssetsFile(srcFileUri, zos, entry + childrens[index] + File.separator); } } } }
From source file:com.rjfun.cordova.sms.SMSPlugin.java
private PluginResult restoreSMS(JSONArray array, CallbackContext callbackContext) { ContentResolver resolver = this.cordova.getActivity().getContentResolver(); Uri uri = Uri.parse(SMS_URI_INBOX); int n = array.length(); int m = 0;//from w w w. j a va 2s .co m for (int i = 0; i < n; ++i) { JSONObject json; if ((json = array.optJSONObject(i)) == null) continue; String str = json.toString(); Log.d(LOGTAG, str); Uri newuri = resolver.insert(uri, this.getContentValuesFromJson(json)); Log.d(LOGTAG, ("inserted: " + newuri.toString())); ++m; } if (callbackContext != null) { callbackContext.success(m); } return null; }
From source file:com.amazonaws.cognito.sync.demo.MainActivity.java
void retrieveTwitterCredentials(Intent intent) { final Uri uri = intent.getData(); String callbackUrl = "callback://" + getString(R.string.twitter_callback_url); if (uri == null || !uri.toString().startsWith(callbackUrl)) { Log.e(TAG, "This is not our Twitter callback"); return;/*from w ww . jav a2s .c om*/ } new Thread(new Runnable() { @Override public void run() { try { // Get token and secret String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER); mOauthProvider.retrieveAccessToken(mOauthConsumer, verifier); String token = mOauthConsumer.getToken(); String tokenSecret = mOauthConsumer.getTokenSecret(); setTwitterSession(token, tokenSecret); } catch (Exception e) { Log.e("Exception", e.getMessage()); e.printStackTrace(); } } }).start(); }