private Map<String, String> decodeExtras(String extras) { Map<String, String> results = new HashMap<String, String>(); try { URI rawExtras = new URI("?" + extras); List<NameValuePair> extraList = URLEncodedUtils.parse(rawExtras, "UTF-8"); for (NameValuePair item : extraList) { String name = item.getName(); int i = 0; while (results.containsKey(name)) { name = item.getName() + ++i; } results.put(name, item.getValue()); } } catch (URISyntaxException e) { Log.w(TAG, "Invalid syntax error while decoding extras data from server."); } return results; }
protected String paramString(Map<String, ?> paramMap) { List<NameValuePair> params = Lists.newArrayList(); if( paramMap != null ) { for( Entry<String, ?> paramEntry : paramMap.entrySet() ) { Object value = paramEntry.getValue(); if( value != null ) { params.add(new BasicNameValuePair(paramEntry.getKey(), value.toString())); } } } return URLEncodedUtils.format(params, "UTF-8"); }
private String genAddressWithoutSchema(String addressWithoutSchema, Map<String, String> pairs) { if (addressWithoutSchema == null || pairs == null || pairs.isEmpty()) { return addressWithoutSchema; } int idx = addressWithoutSchema.indexOf('?'); if (idx == -1) { addressWithoutSchema += "?"; } else { addressWithoutSchema += "&"; } String encodedQuery = URLEncodedUtils.format(pairs.entrySet().stream().map(entry -> { return new BasicNameValuePair(entry.getKey(), entry.getValue()); }).collect(Collectors.toList()), StandardCharsets.UTF_8.name()); if (!RegistryUtils.getServiceRegistry().getFeatures().isCanEncodeEndpoint()) { addressWithoutSchema = genAddressWithoutSchemaForOldSC(addressWithoutSchema, encodedQuery); } else { addressWithoutSchema += encodedQuery; } return addressWithoutSchema; }
/** * Get list of expected query parameters. * * @param pageUrl page URL annotation * @param expectUri expected landing page URI * @return list of expected query parameters */ private static List<NameValuePair> getExpectedParams(PageUrl pageUrl, URI expectUri) { List<NameValuePair> expectParams = new ArrayList<>(); String[] params = pageUrl.params(); if (params.length > 0) { for (String param : params) { String[] nameValueBits = param.split("="); if (nameValueBits.length == 2) { String name = nameValueBits[0].trim(); String value = nameValueBits[1].trim(); expectParams.add(new BasicNameValuePair(name, value)); } else { throw new IllegalArgumentException("Format of PageUrl parameter '" + param + "' does not conform to template [name]=[pattern]"); } } } else if (expectUri != null) { expectParams = URLEncodedUtils.parse(expectUri, "UTF-8"); } return expectParams; }
/** * Extract a query string parameter without triggering http parameters * processing by the servlet container. * * @param request the request * @param name the parameter to get the value. * @return the parameter value, or <code>NULL</code> if the parameter is not * defined. * @throws IOException thrown if there was an error parsing the query string. */ public static String getParameter(HttpServletRequest request, String name) throws IOException { List<NameValuePair> list = URLEncodedUtils.parse(request.getQueryString(), UTF8_CHARSET); if (list != null) { for (NameValuePair nv : list) { if (name.equals(nv.getName())) { return nv.getValue(); } } } return null; }
@VisibleForTesting static String getDoAs(HttpServletRequest request) { List<NameValuePair> list = URLEncodedUtils.parse(request.getQueryString(), UTF8_CHARSET); if (list != null) { for (NameValuePair nv : list) { if (DelegationTokenAuthenticatedURL.DO_AS. equalsIgnoreCase(nv.getName())) { return nv.getValue(); } } } return null; }
@Override public void getCourseListings() throws MalformedURLException { // From the home page, retrieve all links to current courses // We also need to remove any links present in the course data block to prevent announcements // from being interpreted as classes WebElement simpleTable = action.waitForElement(By.xpath("//*[@id=\"_3_1termCourses_noterm\"]/ul")); List<WebElement> links = simpleTable.findElements(By.tagName("a")); List<WebElement> courseDataBlocks = simpleTable.findElements(By.className("courseDataBlock")); for (WebElement we : courseDataBlocks) { links.removeAll(we.findElements(By.tagName("a"))); } CourseListing[] cls = new CourseListing[links.size()]; for (int i = 0; i < links.size(); i++) { cls[i] = new CourseListing(); cls[i].course_name = links.get(i).getText(); String course_url = links.get(i).getAttribute("href"); cls[i].base_url = course_url; try { List<NameValuePair> params; params = URLEncodedUtils.parse(new URI(course_url), java.nio.charset.StandardCharsets.UTF_8); //Find course_id str for(NameValuePair nvp : params) { if(nvp.getName().equals("course_id")) { cls[i].course_id = nvp.getValue(); break; } } } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } addSubGrabber(cls); }
/** * MSSQL driver do not return password, so we need to parse it manually * @param property * @param connectionString * @return */ protected static String getProperty(String property, String connectionString) { String ret = null; if (property != null && !property.isEmpty() && connectionString != null && !connectionString.isEmpty()) { for (NameValuePair param : URLEncodedUtils.parse(connectionString, StandardCharsets.UTF_8, SEPARATORS)) { if(property.equals(param.getName())){ ret = param.getValue(); break; } } } return ret; }
private JsonNode doMyResourcesSearch(String query, String subsearch, Map<?, ?> otherParams, String token) throws Exception { List<NameValuePair> params = Lists.newArrayList(); if( query != null ) { params.add(new BasicNameValuePair("q", query)); } for( Entry<?, ?> entry : otherParams.entrySet() ) { params.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString())); } // params.add(new BasicNameValuePair("token", // TokenSecurity.createSecureToken(username, "token", "token", null))); String paramString = URLEncodedUtils.format(params, "UTF-8"); HttpGet get = new HttpGet(context.getBaseUrl() + "api/search/myresources/" + subsearch + "?" + paramString); HttpResponse response = execute(get, false, token); return mapper.readTree(response.getEntity().getContent()); }
private JsonNode doSearch(String info, String query, Map<?, ?> otherParams, String token) throws Exception { List<NameValuePair> params = Lists.newArrayList(); if( info != null ) { params.add(new BasicNameValuePair("info", info)); } if( query != null ) { params.add(new BasicNameValuePair("q", query)); } for( Entry<?, ?> entry : otherParams.entrySet() ) { params.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString())); } // params.add(new BasicNameValuePair("token", // TokenSecurity.createSecureToken(username, "token", "token", null))); String paramString = URLEncodedUtils.format(params, "UTF-8"); HttpGet get = new HttpGet(context.getBaseUrl() + "api/search?" + paramString); HttpResponse response = execute(get, false, token); return mapper.readTree(response.getEntity().getContent()); }
private JsonNode doNotificationsSearch(String query, String subsearch, Map<?, ?> otherParams, String token) throws Exception { List<NameValuePair> params = Lists.newArrayList(); if( query != null ) { params.add(new BasicNameValuePair("q", query)); } if( subsearch != null ) { params.add(new BasicNameValuePair("type", subsearch)); } for( Entry<?, ?> entry : otherParams.entrySet() ) { params.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString())); } String paramString = URLEncodedUtils.format(params, "UTF-8"); HttpGet get = new HttpGet(context.getBaseUrl() + "api/notification?" + paramString); HttpResponse response = execute(get, false, token); return mapper.readTree(response.getEntity().getContent()); }
protected static String getMacAccessTokenSignatureString(String nonce, String method, String host, String uriPath, String query, String macKey, String macAlgorithm) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException { if ("HmacSHA1".equalsIgnoreCase(macAlgorithm)) { StringBuilder joined = new StringBuilder(""); joined.append(new StringBuilder(String.valueOf(nonce)).append("\n").toString()); joined.append(method.toUpperCase() + "\n"); joined.append(new StringBuilder(String.valueOf(host)).append("\n").toString()); joined.append(new StringBuilder(String.valueOf(uriPath)).append("\n").toString()); if (!TextUtils.isEmpty(query)) { StringBuffer sb = new StringBuffer(); List<NameValuePair> paramList = new ArrayList(); URLEncodedUtils.parse(paramList, new Scanner(query), "UTF-8"); Collections.sort(paramList, new Comparator<NameValuePair>() { public int compare(NameValuePair p1, NameValuePair p2) { return p1.getName().compareTo(p2.getName()); } }); sb.append(URLEncodedUtils.format(paramList, "UTF-8")); joined.append(sb.toString() + "\n"); } return encodeSign(encryptHMACSha1(joined.toString().getBytes("UTF-8"), macKey .getBytes("UTF-8"))); } throw new NoSuchAlgorithmException("error mac algorithm : " + macAlgorithm); }
private Bundle parseUrl(String url) { Bundle b = new Bundle(); if (url != null) { try { for (NameValuePair pair : URLEncodedUtils.parse(new URI(url), "UTF-8")) { if (!(TextUtils.isEmpty(pair.getName()) || TextUtils.isEmpty(pair.getValue()) )) { b.putString(pair.getName(), pair.getValue()); } } } catch (URISyntaxException e) { Log.e("openauth", e.getMessage()); } } return b; }
public static String doHttpGet(Context context, String path, long clientId, String accessToken, String macKey, String macAlgorithm) throws XMAuthericationException { List<NameValuePair> params = new ArrayList(); params.add(new BasicNameValuePair("clientId", String.valueOf(clientId))); params.add(new BasicNameValuePair("token", accessToken)); String nonce = AuthorizeHelper.generateNonce(); try { return Network.downloadXml(context, new URL(AuthorizeHelper.generateUrl(HTTP_PROTOCOL + HOST + path, params)), null, null, AuthorizeHelper.buildMacRequestHead (accessToken, nonce, AuthorizeHelper.getMacAccessTokenSignatureString(nonce, METHOD_GET, HOST, path, URLEncodedUtils.format(params, "UTF-8"), macKey, macAlgorithm)), null); } catch (Throwable e) { throw new XMAuthericationException(e); } catch (Throwable e2) { throw new XMAuthericationException(e2); } catch (Throwable e22) { throw new XMAuthericationException(e22); } catch (Throwable e222) { throw new XMAuthericationException(e222); } }
public final byte[] a() { try { List arrayList = new ArrayList(); if (this.d != null) { arrayList.add(new BasicNameValuePair("extParam", f.a(this.d))); } arrayList.add(new BasicNameValuePair("operationType", this.a)); arrayList.add(new BasicNameValuePair("id", this.c)); new StringBuilder("mParams is:").append(this.b); arrayList.add(new BasicNameValuePair("requestData", this.b == null ? "[]" : f.a(this.b))); return URLEncodedUtils.format(arrayList, Constants.UTF_8).getBytes(); } catch (Throwable e) { Throwable th = e; throw new RpcException(Integer.valueOf(9), new StringBuilder("request =").append(this.b).append(":").append(th).toString() == null ? "" : th.getMessage(), th); } }
public JSONArray getParams(ResourceTimings e) { JSONArray paramList = new JSONArray(); try { List<NameValuePair> params = URLEncodedUtils.parse(new URI(e.name), "UTF-8"); for (NameValuePair pair : params) { JSONObject jsonPair = new JSONObject(); jsonPair.put("name", pair.getName()); jsonPair.put("value", pair.getValue()); paramList.add(jsonPair); } } catch (Exception ex) { return paramList; } return paramList; }
private String getUserName(HttpServletRequest request) { List<NameValuePair> list = URLEncodedUtils.parse(request.getQueryString(), UTF8_CHARSET); if (list != null) { for (NameValuePair nv : list) { if (PseudoAuthenticator.USER_NAME.equals(nv.getName())) { return nv.getValue(); } } } return null; }
public String getURLField(String u, String which) throws URISyntaxException { for (NameValuePair nvp : URLEncodedUtils.parse(new URI(u), "UTF-8")) { LOG.info(nvp.getName() + "=" + nvp.getValue()); if (nvp.getName().equals(which)) { return nvp.getValue(); } } return null; }
public String getUrlForGettingDoc(String q, List<String> languages, String dataSetId) { List<NameValuePair> parameters = Lists.newArrayList(); parameters.add(new BasicNameValuePair("q", getPhraseQueryString(q))); parameters.add(new BasicNameValuePair("defType", "edismax")); parameters.add(new BasicNameValuePair("lowercaseOperators", "false")); parameters.add(new BasicNameValuePair("rows", "100000")); parameters.add(new BasicNameValuePair("qs", "10")); parameters.add(new BasicNameValuePair("fl", Properties.idField.get() + ", " + Properties.titleFields.get().get(0) + "_en")); parameters.add(new BasicNameValuePair("sort", Properties.idField.get() + " DESC")); parameters.add(new BasicNameValuePair("qf", getQueryFields(languages))); parameters.add(new BasicNameValuePair("fq", Properties.docTypeFieldName.get() + ":" + dataSetId)); parameters.add(new BasicNameValuePair("wt", "json")); return getServerUrl() + "/select?" + URLEncodedUtils.format(parameters, BaseIndexer.ENCODING); }
private String makeBankPayData(String url) throws URISyntaxException { BANK_TID = ""; List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), "UTF-8"); StringBuilder ret_data = new StringBuilder(); List<String> keys = Arrays.asList(new String[] {"firm_name", "amount", "serial_no", "approve_no", "receipt_yn", "user_key", "callbackparam2", ""}); String k,v; for (NameValuePair param : params) { k = param.getName(); v = param.getValue(); if ( keys.contains(k) ) { if ( "user_key".equals(k) ) { BANK_TID = v; } ret_data.append("&").append(k).append("=").append(v); } } ret_data.append("&callbackparam1="+"nothing"); ret_data.append("&callbackparam3="+"nothing"); return ret_data.toString(); }
@Override public boolean accepts(HttpRequest request) { boolean result = false; URI uri = URI.create(request.getUri()); String path = uri.getPath(); if (path != null && path.startsWith(urlPrefix)) { String query = uri.getQuery(); if (expectedParams.isEmpty() && StringUtils.isEmpty(query)) { result = true; } else if (StringUtils.isNotEmpty(query)) { List<NameValuePair> params = URLEncodedUtils.parse(query, Charsets.UTF_8); result = hasAllExpectedParams(expectedParams, params); } } return result; }
public static String getUrlWithQueryParams(String url, List<NameValuePair> params) { if (url == null) { return null; } url = url.replace(" ", "%20"); if(!url.endsWith("?")) url += "?"; if (params != null && params.size() > 0) { String paramString = URLEncodedUtils.format(params, "utf-8"); url += paramString; } return url; }
protected URI buildUri( ServletRequest request, String relativeUrl ) throws URISyntaxException { int questionMarkIndex = relativeUrl.indexOf( '?' ); String path = questionMarkIndex != -1 ? relativeUrl.substring( 0, relativeUrl.indexOf( '?' ) ) : relativeUrl; List<NameValuePair> params = URLEncodedUtils.parse( new URI( relativeUrl ), Charset.forName( "UTF-8" ) ); return new URIBuilder() .setScheme( request.getScheme() ) .setHost( request.getLocalName() ) .setPort( request.getLocalPort() ) .setPath( path ) .setParameters( params ) .build(); }
private JSONObject getResponseJsonObject(String httpMethod, String url, Object params) throws IOException, MtWmErrorException { HttpUriRequest httpUriRequest = null; String fullUrl = getBaseApiUrl() + url; List<NameValuePair> sysNameValuePairs = getSysNameValuePairs(fullUrl, params); List<NameValuePair> nameValuePairs = getNameValuePairs(params); if (HTTP_METHOD_GET.equals(httpMethod)) { sysNameValuePairs.addAll(nameValuePairs); HttpGet httpGet = new HttpGet(fullUrl + "?" + URLEncodedUtils.format(sysNameValuePairs, UTF_8)); setRequestConfig(httpGet); httpUriRequest = httpGet; } else if (HTTP_METHOD_POST.equals(httpMethod)) { HttpPost httpPost = new HttpPost(fullUrl + "?" + URLEncodedUtils.format(sysNameValuePairs, UTF_8)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, UTF_8)); setRequestConfig(httpPost); httpUriRequest = httpPost; } CloseableHttpResponse response = this.httpClient.execute(httpUriRequest); String resultContent = new BasicResponseHandler().handleResponse(response); JSONObject jsonObject = JSON.parseObject(resultContent); MtWmError error = MtWmError.fromJson(jsonObject); if (error != null) { logging(url, httpMethod, false, httpUriRequest.getURI() + "\nBody:" + JSON.toJSONString(params), resultContent); throw new MtWmErrorException(error.getErrorCode(), error.getErrorMsg()); } logging(url, httpMethod, true, httpUriRequest.getURI() + "\nBody:" + JSON.toJSONString(params), resultContent); return jsonObject; }
public static boolean cifsCredentialsPresent(final URI uri) { final List<NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8"); boolean foundUser = false; boolean foundPswd = false; for (final NameValuePair nvp : args) { final String name = nvp.getName(); if (name.equals("user")) { foundUser = true; s_logger.debug("foundUser is" + foundUser); } else if (name.equals("password")) { foundPswd = true; s_logger.debug("foundPswd is" + foundPswd); } } return (foundUser && foundPswd); }
/** * Creates an encoded query string from all the parameters in the specified * request. * * @param request * The request containing the parameters to encode. * * @return Null if no parameters were present, otherwise the encoded query * string for the parameters present in the specified request. */ public static String encodeParameters(Request<?> request) { List<NameValuePair> nameValuePairs = null; if (request.getParameters().size() > 0) { nameValuePairs = new ArrayList<NameValuePair>(request.getParameters().size()); for (Entry<String, String> entry : request.getParameters().entrySet()) { nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } String encodedParams = null; if (nameValuePairs != null) { encodedParams = URLEncodedUtils.format(nameValuePairs, DEFAULT_ENCODING); } return encodedParams; }
public static Source get(CloseableHttpClient client, Map<String, String> headers, String url, String encode, List<NameValuePair> pairs) { if(null == client){ if(url.contains("https://")){ client = defaultSSLClient(); }else{ client = defaultClient(); } } Source result = new Source(); if (null != pairs) { String params = URLEncodedUtils.format(pairs,encode); if (url.contains("?")) { url += "&" + params; } else { url += "?" + params; } } HttpGet method = new HttpGet(url); setHeader(method, headers); result = exe(client, method, encode); return result; }
public static Source delete(CloseableHttpClient client, Map<String, String> headers, String url, String encode, List<NameValuePair> pairs) { if(null == client){ if(url.contains("https://")){ client = defaultSSLClient(); }else{ client = defaultClient(); } } Source result = new Source(); if (null != pairs) { String params = URLEncodedUtils.format(pairs,encode); if (url.contains("?")) { url += "&" + params; } else { url += "?" + params; } } HttpDelete method = new HttpDelete(url); setHeader(method, headers); result = exe(client, method, encode); return result; }
private List<YoutubeTrackFormat> loadTrackFormatsFromAdaptive(String adaptiveFormats) throws Exception { List<YoutubeTrackFormat> tracks = new ArrayList<>(); for (String formatString : adaptiveFormats.split(",")) { Map<String, String> format = convertToMapLayout(URLEncodedUtils.parse(formatString, Charset.forName(CHARSET))); tracks.add(new YoutubeTrackFormat( ContentType.parse(format.get("type")), Long.parseLong(format.get("bitrate")), Long.parseLong(format.get("clen")), format.get("url"), format.get("s") )); } return tracks; }
private List<YoutubeTrackFormat> loadTrackFormatsFromFormatStreamMap(String adaptiveFormats) throws Exception { List<YoutubeTrackFormat> tracks = new ArrayList<>(); for (String formatString : adaptiveFormats.split(",")) { Map<String, String> format = convertToMapLayout(URLEncodedUtils.parse(formatString, Charset.forName(CHARSET))); String url = format.get("url"); String contentLength = DataFormatTools.extractBetween(url, "clen=", "&"); if (contentLength == null) { log.debug("Could not find content length from URL {}, skipping format", url); continue; } tracks.add(new YoutubeTrackFormat( ContentType.parse(format.get("type")), qualityToBitrateValue(format.get("quality")), Long.parseLong(contentLength), url, format.get("s") )); } return tracks; }
/** * Parses the request for the queryString * * @return URL Encoded String of Parameter Value Pair */ public static String getQueryString() { List<BasicNameValuePair> fields = new LinkedList<BasicNameValuePair>(); final Set<Map.Entry<String, String[]>> entries = request().queryString().entrySet(); for (Map.Entry<String, String[]> entry : entries) { final String key = entry.getKey(); final String value = entry.getValue()[0]; if (!key.equals(PAGE)) { fields.add(new BasicNameValuePair(key, value)); } } if (fields.isEmpty()) { return null; } else { return URLEncodedUtils.format(fields, "utf-8"); } }
private static HttpGet buildGet(String url, Map<String, String> params) { StringBuilder sb = new StringBuilder(url); if (params != null && params.size() > 0) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); Iterator iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> entry = (Map.Entry) iterator.next(); nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } sb.append("?"); sb.append(URLEncodedUtils.format(nameValuePairs, DEFAULT_CHARSET)); } HttpGet httpGet = new HttpGet(sb.toString()); httpGet.setHeader("Accept-Encoding", ""); return httpGet; }
@Override public String getAccessToken(String code) { Assert.hasText(code); Map<String, Object> parameterMap = new HashMap<>(); parameterMap.put("grant_type", "authorization_code"); parameterMap.put("client_id", getClientId()); parameterMap.put("client_secret", getClientSecret()); parameterMap.put("code", code); parameterMap.put("redirect_uri", getRedirectUri()); String responseString = get("https://graph.qq.com/oauth2.0/token", parameterMap); List<NameValuePair> nameValuePairs = URLEncodedUtils.parse(responseString, Charset.forName("utf-8")); Map<String, Object> result = new HashMap<>(); for (NameValuePair nameValuePair : nameValuePairs) { result.put(nameValuePair.getName(), nameValuePair.getValue()); } return getParameter(nameValuePairs, "access_token"); }
@RequestMapping(method = RequestMethod.GET, produces = "application/json") public ResultListDataRepresentation getDecisionTables(HttpServletRequest request) { // need to parse the filterText parameter ourselves, due to encoding issues with the default parsing. String filter = null; String excludeId = null; List<NameValuePair> params = URLEncodedUtils.parse(request.getQueryString(), Charset.forName("UTF-8")); if (params != null) { for (NameValuePair nameValuePair : params) { if ("filter".equalsIgnoreCase(nameValuePair.getName())) { filter = nameValuePair.getValue(); } else if ("excludeId".equalsIgnoreCase(nameValuePair.getName())) { excludeId = nameValuePair.getValue(); } } } return caseService.getCases(filter, excludeId); }
/** * 拼装Url与参数 * * @param url * @param params * @return */ public static String mergeUrlParams(@NotNull String url, HashMap<String, String> params) { if (params == null || params.isEmpty()) { return url; } String[] s = splitUrl(url); List<NameValuePair> parse; if (s[1] != null) { parse = URLEncodedUtils.parse(s[1], Charset.defaultCharset()); } else { parse = new ArrayList<>(); } // System.out.println(parse); for (Map.Entry<String, String> entry : params.entrySet()) { parse.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } String p = URLEncodedUtils.format(parse, Charset.defaultCharset()); // System.out.println(p); return s[0] + "?" + p; }
public Optional<String> getFileId(String url) { // https://docs.google.com/a/mycompany.com/document/d/0B7a_ei8brT1TMy1CQ0o5NmZQNEE/edit?usp=sharing // https://drive.google.com/file/d/0B7a_ei8brT1TMy1CQ0o5NmZQNEE/view?usp=sharing // https://drive.google.com/open?id=0B7a_ei8brT1TMy1CQ0o5NmZQNEE try { URI uri = new URI(url); if (uri.getHost() == null || !uri.getHost().endsWith(".google.com")) { return Optional.empty(); } List<NameValuePair> params = URLEncodedUtils.parse(uri, "UTF-8"); Optional<String> idValue = getParameterValue(params, "id"); if (idValue.isPresent()) { return idValue; } Pattern pattern = Pattern.compile("/d/(.{25,})/"); Matcher matcher = pattern.matcher(uri.getPath()); if (!matcher.find()) { return Optional.empty(); } return Optional.of(matcher.group(1)); } catch (URISyntaxException e) { return Optional.empty(); } }