List of usage examples for android.net Uri decode
public static String decode(String s)
From source file:com.nostra13.universalimageloader.core.decode.ContentImageDecoder.java
protected ExifInfo getExifInfoFromFile(String imageUri, Object extra) { return defineExifOrientation(Uri.decode(imageUri)); }
From source file:com.ichi2.libanki.Media.java
/** * Percent-escape UTF-8 characters in local image filenames. * @param string The string to search for image references and escape the filenames. * @return The string with the filenames of any local images percent-escaped as UTF-8. *///from w w w . j a v a 2 s .c o m public String escapeImages(String string, boolean unescape) { for (Pattern p : Arrays.asList(fImgRegExpQ, fImgRegExpU)) { Matcher m = p.matcher(string); // NOTE: python uses the named group 'fname'. Java doesn't have named groups, so we have to determine // the index based on which pattern we are using int fnameIdx = p == fImgRegExpU ? 2 : 3; while (m.find()) { String tag = m.group(0); String fname = m.group(fnameIdx); if (fRemotePattern.matcher(fname).find()) { //dont't do any escaping if remote image } else { if (unescape) { string = string.replace(tag, tag.replace(fname, Uri.decode(fname))); } else { string = string.replace(tag, tag.replace(fname, Uri.encode(fname))); } } } } return string; }
From source file:net.exclaimindustries.geohashdroid.services.WikiService.java
@Override protected Intent deserializeFromDisk(InputStream is) { // Now we go the other way around. InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); Intent toReturn = new Intent(); try {/*from w w w. j av a 2s . c om*/ // Date, as a long. String read = br.readLine(); if (read != null && !read.isEmpty()) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(Long.parseLong(read)); toReturn.putExtra(EXTRA_TIMESTAMP, cal); } // Location, as two doubles. read = br.readLine(); if (read != null && !read.isEmpty()) { String parts[] = read.split(":"); Location loc = new Location(""); loc.setLatitude(Double.parseDouble(parts[0])); loc.setLongitude(Double.parseDouble(parts[1])); toReturn.putExtra(EXTRA_LOCATION, loc); } // Image URI, as a string. read = br.readLine(); if (read != null && !read.isEmpty()) { Uri file = Uri.parse(read); toReturn.putExtra(EXTRA_IMAGE, file); } // The Info object, as a mess of things. read = br.readLine(); if (read != null && !read.isEmpty()) { String parts[] = read.split(":"); double lat = Double.parseDouble(parts[0]); double lon = Double.parseDouble(parts[1]); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(Long.parseLong(parts[2])); Graticule grat = null; // If there's less than seven elements, this is a null Graticule // and thus a globalhash. Otherwise... if (parts.length >= 7) { int glat = Integer.parseInt(parts[3]); boolean gsouth = parts[4].equals("1"); int glon = Integer.parseInt(parts[5]); boolean gwest = parts[6].equals("1"); grat = new Graticule(glat, gsouth, glon, gwest); } // And now we can form an Info. toReturn.putExtra(EXTRA_INFO, new Info(lat, lon, grat, cal)); } // Finally, the message. This is just one URI-encoded string. read = br.readLine(); if (read != null && !read.isEmpty()) toReturn.putExtra(EXTRA_MESSAGE, Uri.decode(read)); // There! Rebuilt! return toReturn; } catch (IOException e) { Log.e(DEBUG_TAG, "Exception when deserializing an Intent!", e); return null; } }
From source file:com.samsung.spen.SpenPlugin.java
/** * /*from w w w . j av a 2 s .c om*/ * @param args * JSON array of options sent from the script. * @param surfaceType * int * @param callbackContext * CallbackContext * @return options * SpenTrayBarOptions * @throws JSONException */ private SpenTrayBarOptions createTrayBarOptions(JSONArray args, int surfaceType, CallbackContext callbackContext) throws JSONException { if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) { Log.d(TAG, "Inside createTrayBarOptions"); } String tempId = args.getString(ID); if (tempId != null) { tempId = tempId.trim(); if (tempId.length() > MAX_ID_LENGTH) { tempId = tempId.substring(0, MAX_ID_LENGTH); } } final String id = tempId; if (id == null || id.equals("") || id.equals("null") || !id.matches("^[ !#-)+-.0-9;=@-Z^-{}~]+$")) { SpenException.sendPluginResult(SpenExceptionType.INVALID_SURFACE_ID, callbackContext); return null; } int sPenFlags = args.optInt(SPEN_FLAGS, Integer.MIN_VALUE); if (sPenFlags == Integer.MIN_VALUE || sPenFlags > Utils.MAX_FLAGS_VALUE || sPenFlags < Utils.MIN_FLAGS_VALUE) { SpenException.sendPluginResult(SpenExceptionType.INVALID_FLAGS, callbackContext); return null; } int returnType = args.optInt(RETURN_TYPE); if (returnType != Utils.RETURN_TYPE_IMAGE_DATA && returnType != Utils.RETURN_TYPE_IMAGE_URI && returnType != Utils.RETURN_TYPE_TEXT) { SpenException.sendPluginResult(SpenExceptionType.INVALID_RETURN_TYPE, callbackContext); return null; } String backgroundColor = args.getString(BACKGROUND_COLOR); String imagePath = args.getString(IMAGE_PATH); if (imagePath.equals("") || imagePath.equals("null")) { imagePath = null; } else { imagePath = Uri.decode(imagePath); String truncatedPath = truncateQueryPart(imagePath); File file = new File(truncatedPath); if (file.exists()) { imagePath = truncatedPath; } } int bgImageScaleType = args.optInt(BACKGROUND_IMAGE_SCALE_TYPE); if (bgImageScaleType != Utils.BACKGROUND_IMAGE_MODE_CENTER && bgImageScaleType != Utils.BACKGROUND_IMAGE_MODE_FIT && bgImageScaleType != Utils.BACKGROUND_IMAGE_MODE_STRETCH && bgImageScaleType != Utils.BACKGROUND_IMAGE_MODE_TILE) { bgImageScaleType = Utils.BACKGROUND_IMAGE_MODE_FIT; } int imageUriScaleType = args.optInt(IMAGE_URI_SCALE_TYPE); if (imageUriScaleType != Utils.IMAGE_URI_MODE_CENTER && imageUriScaleType != Utils.IMAGE_URI_MODE_FIT && imageUriScaleType != Utils.IMAGE_URI_MODE_TILE && imageUriScaleType != Utils.IMAGE_URI_MODE_STRETCH) { imageUriScaleType = Utils.IMAGE_URI_MODE_FIT; } if (surfaceType == Utils.SURFACE_INLINE) { if ((sPenFlags & Utils.FLAG_ADD_PAGE) == Utils.FLAG_ADD_PAGE) { if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) { Log.d(TAG, "Add Page is not supported in Inline"); } sPenFlags = sPenFlags & ~Utils.FLAG_ADD_PAGE; } } else if (surfaceType == Utils.SURFACE_POPUP) { if ((sPenFlags & Utils.FLAG_EDIT) == Utils.FLAG_EDIT) { if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) { Log.d(TAG, "Edit Page is not supported in Popup"); } sPenFlags = sPenFlags & ~Utils.FLAG_EDIT; } if ((sPenFlags & Utils.FLAG_PEN) == Utils.FLAG_PEN) { if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) { Log.d(TAG, "Pen option is provided by default, is not configurable in Popup"); } sPenFlags = sPenFlags & ~Utils.FLAG_PEN; } if ((sPenFlags & Utils.FLAG_ERASER) == Utils.FLAG_ERASER) { if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) { Log.d(TAG, "Eraser option is provided by default, is not configurable in Popup"); } sPenFlags = sPenFlags & ~Utils.FLAG_ERASER; } if ((sPenFlags & Utils.FLAG_UNDO_REDO) == Utils.FLAG_UNDO_REDO) { if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) { Log.d(TAG, "Undo Redo option is provided by default, is not configurable in Popup"); } sPenFlags = sPenFlags & ~Utils.FLAG_UNDO_REDO; } } else { SpenException.sendPluginResult(SpenExceptionType.INVALID_SURFACE_TYPE, callbackContext); return null; } if ((sPenFlags & Utils.FLAG_TEXT_RECOGNITION) == Utils.FLAG_TEXT_RECOGNITION || (sPenFlags & Utils.FLAG_SHAPE_RECOGNITION) == Utils.FLAG_SHAPE_RECOGNITION) { sPenFlags = sPenFlags | Utils.FLAG_SELECTION; } SpenTrayBarOptions options = new SpenTrayBarOptions(sPenFlags); options.setId(id); options.setIsfeatureEnabled(mSpenState == SPEN_AND_HAND_SUPPORTED ? true : false); options.setColor(backgroundColor); options.setBgImageScaleType(bgImageScaleType); options.setImageUriScaleType(imageUriScaleType); options.setReturnType(returnType); options.setSurfaceType(surfaceType); options.setImagePath(imagePath); options.setDensity(mActivity.getApplicationContext().getResources().getDisplayMetrics().density); if (surfaceType == Utils.SURFACE_INLINE) { long xRect = 0, yRect = 0, width = 0, height = 0, xBodyRect = 0, yBodyRect = 0; if (args.isNull(RECTANGLE_X_VALUE) || args.isNull(RECTANGLE_Y_VALUE) || args.isNull(WIDTH) || args.isNull(HEIGHT)) { SpenException.sendPluginResult(SpenExceptionType.INVALID_INLINE_CORDINATES, callbackContext); return null; } else { xRect = args.optLong(RECTANGLE_X_VALUE, Integer.MIN_VALUE); yRect = args.optLong(RECTANGLE_Y_VALUE, Integer.MIN_VALUE); width = args.optLong(WIDTH, Integer.MIN_VALUE); height = args.optLong(HEIGHT, Integer.MIN_VALUE); xBodyRect = args.optLong(BODY_RECTANGLE_X_VALUE, Integer.MIN_VALUE); yBodyRect = args.optLong(BODY_RECTANGLE_Y_VALUE, Integer.MAX_VALUE); if (xRect == Integer.MIN_VALUE || yRect == Integer.MIN_VALUE || width == Integer.MIN_VALUE || height == Integer.MIN_VALUE || xBodyRect == Integer.MIN_VALUE || yBodyRect == Integer.MIN_VALUE || xRect > (long) Integer.MAX_VALUE || yRect > (long) Integer.MAX_VALUE || width > (long) Integer.MAX_VALUE || height > (long) Integer.MAX_VALUE || xBodyRect > (long) Integer.MAX_VALUE || yBodyRect > (long) Integer.MAX_VALUE) { SpenException.sendPluginResult(SpenExceptionType.INVALID_INLINE_CORDINATES, callbackContext); return null; } } SurfacePosition surfacePosition = new SurfacePosition(mActivity.getApplicationContext(), (int) width, (int) height, (int) xRect - (int) xBodyRect, (int) yRect - (int) yBodyRect); if (!surfacePosition.isSurfaceValid(options, mActivity.getApplicationContext())) { SpenException.sendPluginResult(SpenExceptionType.INVALID_INLINE_CORDINATES, callbackContext); return null; } options.setSurfacePosition(surfacePosition); } else if (surfaceType == Utils.SURFACE_POPUP) { long popupWidth = 0, popupHeight = 0; popupWidth = args.optLong(POPUP_WIDTH, Integer.MIN_VALUE); popupHeight = args.optLong(POPUP_HEIGHT, Integer.MIN_VALUE); SurfacePosition surfacePosition = new SurfacePosition(mActivity.getApplicationContext(), (int) popupWidth, (int) popupHeight); options.setSurfacePosition(surfacePosition); } return options; }
From source file:gc.david.dfm.ui.activity.MainActivity.java
private void handleGeoSchemeIntent(final Uri uri) { final String schemeSpecificPart = uri.getSchemeSpecificPart(); final Matcher matcher = getMatcherForUri(schemeSpecificPart); if (matcher.find()) { if (matcher.group(1).equals("0") && matcher.group(2).equals("0")) { if (matcher.find()) { // Manage geo:0,0?q=lat,lng(label) setDestinationPosition(matcher); } else { // Manage geo:0,0?q=my+street+address String destination = Uri.decode(uri.getQuery()).replace('+', ' '); destination = destination.replace("q=", ""); // TODO check this ugly workaround addressPresenter.searchPositionByName(destination); searchMenuItem.collapseActionView(); mustShowPositionWhenComingFromOutside = true; }//www . java 2 s . c o m } else { // Manage geo:latitude,longitude or geo:latitude,longitude?z=zoom setDestinationPosition(matcher); } } else { final NoSuchFieldException noSuchFieldException = new NoSuchFieldException( "Error al obtener las coordenadas. Matcher = " + matcher.toString()); DFMLogger.logException(noSuchFieldException); toastIt("Unable to parse address", this); } }
From source file:org.mdc.chess.MDChess.java
/** * Return PGN/FEN data or filename from the Intent. Both can not be non-null. * * @return Pair of PGN/FEN data and filename. *///from w w w . ja v a 2s.com private Pair<String, String> getPgnOrFenIntent() { String pgnOrFen = null; String filename = null; try { Intent intent = getIntent(); Uri data = intent.getData(); if (data == null) { Bundle b = intent.getExtras(); if (b != null) { Object strm = b.get(Intent.EXTRA_STREAM); if (strm instanceof Uri) { data = (Uri) strm; if ("file".equals(data.getScheme())) { filename = data.getEncodedPath(); if (filename != null) { filename = Uri.decode(filename); } } } } } if (data == null) { if ((Intent.ACTION_SEND.equals(intent.getAction()) || Intent.ACTION_VIEW.equals(intent.getAction())) && ("application/x-chess-pgn".equals(intent.getType()) || "application/x-chess-fen".equals(intent.getType()))) { pgnOrFen = intent.getStringExtra(Intent.EXTRA_TEXT); } } else { String scheme = intent.getScheme(); if ("file".equals(scheme)) { filename = data.getEncodedPath(); if (filename != null) { filename = Uri.decode(filename); } } if ((filename == null) && ("content".equals(scheme) || "file".equals(scheme))) { ContentResolver resolver = getContentResolver(); InputStream in = resolver.openInputStream(intent.getData()); StringBuilder sb = new StringBuilder(); while (true) { byte[] buffer = new byte[16384]; int len = in != null ? in.read(buffer) : 0; if (len <= 0) { break; } sb.append(new String(buffer, 0, len)); } pgnOrFen = sb.toString(); } } } catch (IOException e) { Toast.makeText(getApplicationContext(), R.string.failed_to_read_pgn_data, Toast.LENGTH_SHORT).show(); } return new Pair<>(pgnOrFen, filename); }
From source file:net.gsantner.opoc.util.ShareUtil.java
/** * Try to force extract a absolute filepath from an intent * * @param receivingIntent The intent from {@link Activity#getIntent()} * @return A file or null if extraction did not succeed *///from w w w . j a v a 2 s. c o m public File extractFileFromIntent(Intent receivingIntent) { String action = receivingIntent.getAction(); String type = receivingIntent.getType(); File tmpf; String tmps; String fileStr; if ((Intent.ACTION_VIEW.equals(action) || Intent.ACTION_EDIT.equals(action)) || Intent.ACTION_SEND.equals(action)) { // Markor, S.M.T FileManager if (receivingIntent.hasExtra((tmps = EXTRA_FILEPATH))) { return new File(receivingIntent.getStringExtra(tmps)); } // Analyze data/Uri Uri fileUri = receivingIntent.getData(); if (fileUri != null && (fileStr = fileUri.toString()) != null) { // Uri contains file if (fileStr.startsWith("file://")) { return new File(fileUri.getPath()); } if (fileStr.startsWith((tmps = "content://"))) { fileStr = fileStr.substring(tmps.length()); String fileProvider = fileStr.substring(0, fileStr.indexOf("/")); fileStr = fileStr.substring(fileProvider.length() + 1); // Some file managers dont add leading slash if (fileStr.startsWith("storage/")) { fileStr = "/" + fileStr; } // Some do add some custom prefix for (String prefix : new String[] { "file", "document", "root_files", "name" }) { if (fileStr.startsWith(prefix)) { fileStr = fileStr.substring(prefix.length()); } } // Next/OwnCloud Fileprovider for (String fp : new String[] { "org.nextcloud.files", "org.nextcloud.beta.files", "org.owncloud.files" }) { if (fileProvider.equals(fp) && fileStr.startsWith(tmps = "external_files/")) { return new File(Uri.decode("/storage/" + fileStr.substring(tmps.length()))); } } // AOSP File Manager/Documents if (fileProvider.equals("com.android.externalstorage.documents") && fileStr.startsWith(tmps = "/primary%3A")) { return new File(Uri.decode(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + fileStr.substring(tmps.length()))); } // Mi File Explorer if (fileProvider.equals("com.mi.android.globalFileexplorer.myprovider") && fileStr.startsWith(tmps = "external_files")) { return new File(Uri.decode(Environment.getExternalStorageDirectory().getAbsolutePath() + fileStr.substring(tmps.length()))); } // URI Encoded paths with full path after content://package/ if (fileStr.startsWith("/") || fileStr.startsWith("%2F")) { tmpf = new File(Uri.decode(fileStr)); if (tmpf.exists()) { return tmpf; } else if ((tmpf = new File(fileStr)).exists()) { return tmpf; } } } } fileUri = receivingIntent.getParcelableExtra(Intent.EXTRA_STREAM); if (fileUri != null && !TextUtils.isEmpty(tmps = fileUri.getPath()) && tmps.startsWith("/") && (tmpf = new File(tmps)).exists()) { return tmpf; } } return null; }
From source file:com.owncloud.android.ui.activity.Uploader.java
public void uploadFiles() { try {/*from www .j a v a 2s . c om*/ // ArrayList for files with path in external storage ArrayList<String> local = new ArrayList<String>(); ArrayList<String> remote = new ArrayList<String>(); // this checks the mimeType for (Parcelable mStream : mStreamsToUpload) { Uri uri = (Uri) mStream; String data = null; String filePath = ""; if (uri != null) { if (uri.getScheme().equals("content")) { String mimeType = getContentResolver().getType(uri); if (mimeType.contains("image")) { String[] CONTENT_PROJECTION = { Images.Media.DATA, Images.Media.DISPLAY_NAME, Images.Media.MIME_TYPE, Images.Media.SIZE }; Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null); c.moveToFirst(); int index = c.getColumnIndex(Images.Media.DATA); data = c.getString(index); filePath = mUploadPath + c.getString(c.getColumnIndex(Images.Media.DISPLAY_NAME)); } else if (mimeType.contains("video")) { String[] CONTENT_PROJECTION = { Video.Media.DATA, Video.Media.DISPLAY_NAME, Video.Media.MIME_TYPE, Video.Media.SIZE, Video.Media.DATE_MODIFIED }; Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null); c.moveToFirst(); int index = c.getColumnIndex(Video.Media.DATA); data = c.getString(index); filePath = mUploadPath + c.getString(c.getColumnIndex(Video.Media.DISPLAY_NAME)); } else if (mimeType.contains("audio")) { String[] CONTENT_PROJECTION = { Audio.Media.DATA, Audio.Media.DISPLAY_NAME, Audio.Media.MIME_TYPE, Audio.Media.SIZE }; Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null); c.moveToFirst(); int index = c.getColumnIndex(Audio.Media.DATA); data = c.getString(index); filePath = mUploadPath + c.getString(c.getColumnIndex(Audio.Media.DISPLAY_NAME)); } else { Cursor cursor = getContentResolver().query(uri, new String[] { MediaStore.MediaColumns.DISPLAY_NAME }, null, null, null); cursor.moveToFirst(); int nameIndex = cursor.getColumnIndex(cursor.getColumnNames()[0]); if (nameIndex >= 0) { filePath = mUploadPath + cursor.getString(nameIndex); } } } else if (uri.getScheme().equals("file")) { filePath = Uri.decode(uri.toString()).replace(uri.getScheme() + "://", ""); if (filePath.contains("mnt")) { String splitedFilePath[] = filePath.split("/mnt"); filePath = splitedFilePath[1]; } final File file = new File(filePath); data = file.getAbsolutePath(); filePath = mUploadPath + file.getName(); } else { throw new SecurityException(); } if (data == null) { mRemoteCacheData.add(filePath); CopyTmpFileAsyncTask copyTask = new CopyTmpFileAsyncTask(this); Object[] params = { uri, filePath, mRemoteCacheData.size() - 1, getAccount().name, getContentResolver() }; mNumCacheFile++; showWaitingCopyDialog(); copyTask.execute(params); } else { remote.add(filePath); local.add(data); } } else { throw new SecurityException(); } Intent intent = new Intent(getApplicationContext(), FileUploader.class); intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES); intent.putExtra(FileUploader.KEY_LOCAL_FILE, local.toArray(new String[local.size()])); intent.putExtra(FileUploader.KEY_REMOTE_FILE, remote.toArray(new String[remote.size()])); intent.putExtra(FileUploader.KEY_ACCOUNT, getAccount()); startService(intent); //Save the path to shared preferences SharedPreferences.Editor appPrefs = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()).edit(); appPrefs.putString("last_upload_path", mUploadPath); appPrefs.apply(); finish(); } } catch (SecurityException e) { String message = String.format(getString(R.string.uploader_error_forbidden_content), getString(R.string.app_name)); Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } }
From source file:ml.puredark.hviewer.ui.fragments.SettingFragment.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == RESULT_CHOOSE_DIRECTORY) { Uri uriTree = data.getData(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { try { getActivity().getContentResolver().takePersistableUriPermission(uriTree, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } catch (SecurityException e) { e.printStackTrace(); }/* w ww . j av a2 s.co m*/ } String path = uriTree.toString(); String displayPath = Uri.decode(path); SharedPreferencesUtil.saveData(getActivity(), KEY_PREF_DOWNLOAD_PATH, path); getPreferenceManager().findPreference(KEY_PREF_DOWNLOAD_PATH).setSummary(displayPath); } } }
From source file:com.lgallardo.qbittorrentclient.JSONParser.java
public String postCommand(String command, String hash) throws JSONParserStatusCodeException { String key = "hash"; String urlContentType = "application/x-www-form-urlencoded"; String limit = ""; String tracker = ""; String boundary = null;/* w ww .j av a2 s. c o m*/ String fileId = ""; String filePriority = ""; String result = ""; StringBuilder fileContent = null; HttpResponse httpResponse; DefaultHttpClient httpclient; String url = ""; String label = ""; if ("start".equals(command) || "startSelected".equals(command)) { url = "command/resume"; } if ("pause".equals(command) || "pauseSelected".equals(command)) { url = "command/pause"; } if ("delete".equals(command) || "deleteSelected".equals(command)) { url = "command/delete"; key = "hashes"; } if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) { url = "command/deletePerm"; key = "hashes"; } if ("addTorrent".equals(command)) { url = "command/download"; key = "urls"; } if ("addTracker".equals(command)) { url = "command/addTrackers"; key = "hash"; } if ("addTorrentFile".equals(command)) { url = "command/upload"; key = "urls"; boundary = "-----------------------" + (new Date()).getTime(); urlContentType = "multipart/form-data; boundary=" + boundary; } if ("pauseall".equals(command)) { url = "command/pauseall"; } if ("pauseAll".equals(command)) { url = "command/pauseAll"; } if ("resumeall".equals(command)) { url = "command/resumeall"; } if ("resumeAll".equals(command)) { url = "command/resumeAll"; } if ("increasePrio".equals(command)) { url = "command/increasePrio"; key = "hashes"; } if ("decreasePrio".equals(command)) { url = "command/decreasePrio"; key = "hashes"; } if ("maxPrio".equals(command)) { url = "command/topPrio"; key = "hashes"; } if ("minPrio".equals(command)) { url = "command/bottomPrio"; key = "hashes"; } if ("setFilePrio".equals(command)) { url = "command/setFilePrio"; String[] tmpString = hash.split("&"); hash = tmpString[0]; fileId = tmpString[1]; filePriority = tmpString[2]; // Log.d("Debug", "hash: " + hash); // Log.d("Debug", "fileId: " + fileId); // Log.d("Debug", "filePriority: " + filePriority); } if ("setQBittorrentPrefefrences".equals(command)) { url = "command/setPreferences"; key = "json"; } if ("setUploadRateLimit".equals(command)) { url = "command/setTorrentsUpLimit"; key = "hashes"; String[] tmpString = hash.split("&"); hash = tmpString[0]; try { limit = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { limit = "-1"; } } if ("setDownloadRateLimit".equals(command)) { url = "command/setTorrentsDlLimit"; key = "hashes"; Log.d("Debug", "Hash before: " + hash); String[] tmpString = hash.split("&"); hash = tmpString[0]; try { limit = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { limit = "-1"; } // Log.d("Debug", "url: " + url); // Log.d("Debug", "Hashes: " + hash + " | limit: " + limit); } if ("recheckSelected".equals(command)) { url = "command/recheck"; } if ("toggleFirstLastPiecePrio".equals(command)) { url = "command/toggleFirstLastPiecePrio"; key = "hashes"; } if ("toggleSequentialDownload".equals(command)) { url = "command/toggleSequentialDownload"; key = "hashes"; } if ("toggleAlternativeSpeedLimits".equals(command)) { // Log.d("Debug", "Toggling alternative rates"); url = "command/toggleAlternativeSpeedLimits"; key = "hashes"; } if ("setLabel".equals(command)) { url = "command/setLabel"; key = "hashes"; String[] tmpString = hash.split("&"); hash = tmpString[0]; try { label = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { label = ""; } // Log.d("Debug", "Hash2: " + hash + "| label2: " + label); } if ("setCategory".equals(command)) { url = "command/setCategory"; key = "hashes"; String[] tmpString = hash.split("&"); hash = tmpString[0]; try { label = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { label = ""; } // Log.d("Debug", "Hash2: " + hash + "| label2: " + label); } if ("alternativeSpeedLimitsEnabled".equals(command)) { // Log.d("Debug", "Getting alternativeSpeedLimitsEnabled"); url = "command/alternativeSpeedLimitsEnabled"; key = "hashes"; } // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; } HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); try { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url; HttpPost httpget = new HttpPost(url); if ("addTorrent".equals(command)) { URI hash_uri = new URI(hash); hash = hash_uri.toString(); } if ("addTracker".equals(command)) { String[] tmpString = hash.split("&"); hash = tmpString[0]; URI hash_uri = new URI(hash); hash = hash_uri.toString(); try { tracker = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { tracker = ""; } // Log.d("Debug", "addTracker - hash: " + hash); // Log.d("Debug", "addTracker - tracker: " + tracker); } // In order to pass the hash we must set the pair name value BasicNameValuePair bnvp = new BasicNameValuePair(key, hash); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(bnvp); // Add limit if (!limit.equals("")) { Log.d("Debug", "JSONParser - Limit: " + limit); nvps.add(new BasicNameValuePair("limit", limit)); } // Set values for setting file priority if ("setFilePrio".equals(command)) { nvps.add(new BasicNameValuePair("id", fileId)); nvps.add(new BasicNameValuePair("priority", filePriority)); } // Add label if (label != null && !label.equals("")) { label = Uri.decode(label); if ("setLabel".equals(command)) { nvps.add(new BasicNameValuePair("label", label)); } else { nvps.add(new BasicNameValuePair("category", label)); } // Log.d("Debug", "Hash3: " + hash + "| label3: >" + label + "<"); } // Add tracker if (tracker != null && !tracker.equals("")) { nvps.add(new BasicNameValuePair("urls", tracker)); // Log.d("Debug", ">Tracker: " + key + " | " + hash + " | " + tracker + "<"); } String entityValue = URLEncodedUtils.format(nvps, HTTP.UTF_8); // This replaces encoded char "+" for "%20" so spaces can be passed as parameter entityValue = entityValue.replaceAll("\\+", "%20"); StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8); stringEntity.setContentType(URLEncodedUtils.CONTENT_TYPE); httpget.setEntity(stringEntity); // Set content type and urls if ("addTorrent".equals(command) || "increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command) || "setFilePrio".equals(command) || "toggleAlternativeSpeedLimits".equals(command) || "alternativeSpeedLimitsEnabled".equals(command) || "setLabel".equals(command) || "setCategory".equals(command) || "addTracker".equals(command)) { httpget.setHeader("Content-Type", urlContentType); } // Set cookie if (this.cookie != null) { httpget.setHeader("Cookie", this.cookie); } // Set content type and urls if ("addTorrentFile".equals(command)) { httpget.setHeader("Content-Type", urlContentType); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Add boundary builder.setBoundary(boundary); // Add torrent file as binary File file = new File(hash); // FileBody fileBody = new FileBody(file); // builder.addPart("file", fileBody); builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, hash); // Build entity HttpEntity entity = builder.build(); // Set entity to http post httpget.setEntity(entity); } httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); // Log.d("Debug", "JSONPArser - mStatusCode: " + mStatusCode); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); // Log.d("Debug", "JSONPArser - command result: " + result); return result; } catch (UnsupportedEncodingException e) { } catch (ClientProtocolException e) { Log.e("Debug", "Client: " + e.toString()); e.printStackTrace(); } catch (SSLPeerUnverifiedException e) { Log.e("JSON", "SSLPeerUnverifiedException: " + e.toString()); throw new JSONParserStatusCodeException(NO_PEER_CERTIFICATE); } catch (IOException e) { Log.e("Debug", "IO: " + e.toString()); httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(TIMEOUT_ERROR); } catch (JSONParserStatusCodeException e) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(e.getCode()); } catch (Exception e) { Log.e("Debug", "Generic: " + e.toString()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } return null; }