List of usage examples for org.apache.http.client.utils URLEncodedUtils parse
public static List<NameValuePair> parse(final String s, final Charset charset)
From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebAppFilter.java
@Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { response.setCharacterEncoding("UTF-8"); String htmlEscapedUri = HtmlQuoting.quoteHtmlChars(request.getRequestURI()); if (htmlEscapedUri == null) { htmlEscapedUri = "/"; }/*w ww. j av a2s . c o m*/ String uriWithQueryString = htmlEscapedUri; String htmlEscapedUriWithQueryString = htmlEscapedUri; String queryString = request.getQueryString(); if (queryString != null && !queryString.isEmpty()) { String reqEncoding = request.getCharacterEncoding(); if (reqEncoding == null || reqEncoding.isEmpty()) { reqEncoding = "ISO-8859-1"; } Charset encoding = Charset.forName(reqEncoding); List<NameValuePair> params = URLEncodedUtils.parse(queryString, encoding); String urlEncodedQueryString = URLEncodedUtils.format(params, encoding); uriWithQueryString += "?" + urlEncodedQueryString; htmlEscapedUriWithQueryString = HtmlQuoting .quoteHtmlChars(request.getRequestURI() + "?" + urlEncodedQueryString); } RMWebApp rmWebApp = injector.getInstance(RMWebApp.class); rmWebApp.checkIfStandbyRM(); if (rmWebApp.isStandby() && shouldRedirect(rmWebApp, htmlEscapedUri)) { String redirectPath = rmWebApp.getRedirectPath(); if (redirectPath != null && !redirectPath.isEmpty()) { redirectPath += uriWithQueryString; String redirectMsg = "This is standby RM. The redirect url is: " + htmlEscapedUriWithQueryString; PrintWriter out = response.getWriter(); out.println(redirectMsg); response.setHeader("Location", redirectPath); response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); return; } else { boolean doRetry = true; String retryIntervalStr = request.getParameter(YarnWebParams.NEXT_REFRESH_INTERVAL); int retryInterval = 0; if (retryIntervalStr != null) { try { retryInterval = Integer.parseInt(retryIntervalStr.trim()); } catch (NumberFormatException ex) { doRetry = false; } } int next = calculateExponentialTime(retryInterval); String redirectUrl = appendOrReplaceParamter(path + uriWithQueryString, YarnWebParams.NEXT_REFRESH_INTERVAL + "=" + (retryInterval + 1)); if (redirectUrl == null || next > MAX_SLEEP_TIME) { doRetry = false; } String redirectMsg = doRetry ? "Can not find any active RM. Will retry in next " + next + " seconds." : "There is no active RM right now."; redirectMsg += "\nHA Zookeeper Connection State: " + rmWebApp.getHAZookeeperConnectionState(); PrintWriter out = response.getWriter(); out.println(redirectMsg); if (doRetry) { response.setHeader("Refresh", next + ";url=" + redirectUrl); response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); } } return; } else if (ahsEnabled) { String ahsRedirectUrl = ahsRedirectPath(uriWithQueryString, rmWebApp); if (ahsRedirectUrl != null) { response.setHeader("Location", ahsRedirectUrl); response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); return; } } super.doFilter(request, response, chain); }
From source file:io.apicurio.studio.fe.servlet.servlets.DownloadServlet.java
/** * Parses the query string into a map.//from ww w .j av a2 s. c o m * @param queryString */ protected static Map<String, String> parseQueryString(String queryString) { Map<String, String> rval = new HashMap<>(); if (queryString != null) { List<NameValuePair> list = URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8); for (NameValuePair nameValuePair : list) { rval.put(nameValuePair.getName(), nameValuePair.getValue()); } } return rval; }
From source file:es.upv.grycap.coreutils.fiber.net.UrlBuilder.java
/** * Creates a new URL relative to the base URL provided in the constructor of this class. The new relative URL * includes the path, query parameters and the internal reference of the {@link UrlBuilder#baseUrl base URL} * provided with this class. An additional fragment, as well as additional query parameters can be optionally * added to the new URL. In addition to the parameters passed to the method as an argument, the supplied * fragment can also include parameters that will be added to the created URL. The created URL is normalized * and unencoded before returning it to the caller. The current implementation has the following limitations: * <ul>//from w w w .j av a 2s . c om * <li>Arrays are not supported: <tt>q=foo&q=bar</tt> will produce an error.</li> * <li>Internal references are only supported in the base URL. Any additional reference provided with the * fragment will be silently ignored: the fragment <tt>/rd#ref</tt> will be appended to the base URL as * <tt>/rd</tt>, ignoring the internal reference.</li> * </ul> * @param fragment - optional URL fragment (may include parameters, but not references) that will be added * to the base URL * @param params - optional query parameters that will be added to the base URL * @return A relative URL created from the base URL provided in the constructor of this class and adding the * fragment and parameters passed as arguments to this method. */ public String buildRelativeUrl(final @Nullable String fragment, final @Nullable Map<String, String> params) { String url = null; final Optional<String> fragment2 = ofNullable(trimToNull(fragment)); try { final Optional<URL> fragmentUrl = ofNullable( fragment2.isPresent() ? new URL("http://example.com/" + fragment2.get()) : null); final URIBuilder uriBuilder = new URIBuilder(); // add path uriBuilder.setPath(new StringBuilder(ofNullable(trimToNull(baseUrl.getPath())).orElse("/")) .append(fragmentUrl.isPresent() ? "/" + stripEnd(fragmentUrl.get().getPath(), "/") : "") .toString().replaceAll("[/]{2,}", "/")); // add query parameters if (isNotBlank(baseUrl.getQuery())) { uriBuilder.setParameters(URLEncodedUtils.parse(baseUrl.getQuery(), defaultCharset())); } if (fragmentUrl.isPresent() && isNotBlank(fragmentUrl.get().getQuery())) { URLEncodedUtils.parse(fragmentUrl.get().getQuery(), defaultCharset()).stream().forEach(p -> { uriBuilder.addParameter(p.getName(), p.getValue()); }); } ofNullable(params).orElse(emptyMap()).entrySet().stream().forEach(p -> { uriBuilder.addParameter(p.getKey(), p.getValue()); }); // add internal reference uriBuilder.setFragment(baseUrl.getRef()); // build relative URL url = uriBuilder.build().normalize().toString(); } catch (MalformedURLException | URISyntaxException e) { throw new IllegalStateException( new StringBuilder("Failed to create relative URL from provided parameters: fragment=") .append(fragment2.orElse("null")).append(", params=") .append(params != null ? params.toString() : "null").toString(), e); } return url; }
From source file:com.smartling.api.sdk.FileApiClientAdapterTest.java
@Test public void testFileGet() throws ApiException, IOException { fileApiClientAdapter.getFile(FILE_URI, LOCALE, RetrievalType.PUBLISHED); ArgumentCaptor<HttpRequestBase> requestCaptor = ArgumentCaptor.forClass(HttpRequestBase.class); verify(httpUtils).executeHttpCall(requestCaptor.capture(), eq(proxyConfiguration)); HttpRequestBase request = requestCaptor.getValue(); List<NameValuePair> params = URLEncodedUtils.parse(request.getURI(), "UTF-8"); assertTrue(params.contains(new BasicNameValuePair(FileApiParams.API_KEY, API_KEY))); assertTrue(params.contains(new BasicNameValuePair(FileApiParams.PROJECT_ID, PROJECT_ID))); assertTrue(params.contains(new BasicNameValuePair(FileApiParams.LOCALE, LOCALE))); assertTrue(params.contains(new BasicNameValuePair(FileApiParams.FILE_URI, FILE_URI))); assertEquals(HOST, request.getURI().getHost()); }
From source file:com.subgraph.vega.impl.scanner.urls.UriParser.java
private void processPathWithQuery(IWebPath path, URI uri) { path.setPathType(PathType.PATH_FILE); List<NameValuePair> plist = URLEncodedUtils.parse(uri, "UTF-8"); synchronized (pathStateManager) { final PathState ps = getPathStateForFile(path); if (ps != null) { ps.maybeAddParameters(plist); }//from w w w. jav a 2 s . c om } }
From source file:it.anyplace.sync.core.beans.DeviceAddress.java
public @Nullable String getUriParam(final String key) { Preconditions.checkNotNull(emptyToNull(key)); try {//w w w . j a v a 2 s.c o m NameValuePair record = Iterables.find( URLEncodedUtils.parse(getUriSafe(), StandardCharsets.UTF_8.name()), new Predicate<NameValuePair>() { @Override public boolean apply(NameValuePair input) { return equal(input.getName(), key); } }, null); return record == null ? null : record.getValue(); } catch (Exception ex) { logger.warn("ex", ex); return null; } }
From source file:org.easysoa.registry.dbb.rest.ServiceFinderRest.java
/** * JSONP for bookmarklet//from ww w .ja va 2s. co m * NB. requires application/javascript mimetype to work on bookmarklet's * jquery $.ajax() side in jsonp, but doesn't work if set here, has to be put at the tope * @param uriInfo * @return * @throws Exception */ @GET @Path("/find/{url:.*}") public Object findServices(@Context UriInfo uriInfo) throws Exception { URL url = null; String callback = null; try { // Retrieve URL String restServiceURL = uriInfo.getBaseUri().toString() + "easysoa/servicefinder/find/"; url = new URL(uriInfo.getRequestUri().toString().substring(restServiceURL.length())); if (url.getQuery() != null && url.getQuery().contains("callback=")) { List<NameValuePair> queryTokens = URLEncodedUtils.parse(url.toURI(), "UTF-8"); for (NameValuePair token : queryTokens) { if (token.getName().equals("callback")) { callback = token.getValue(); // now let's remove this callback from original jsonp URL } } } } catch (MalformedURLException e) { logger.debug(e); return "{ errors: '" + formatError(e) + "' }"; } // Find WSDLs String foundServicesJson = findServices(new BrowsingContext(url)); String res; if (callback != null) { res = callback + '(' + foundServicesJson + ");"; // ')' // TODO OK } else { res = foundServicesJson; } return res; }
From source file:com.hzq.car.CarTest.java
/** * ??post,json//from w w w . j av a2 s . c o m */ private String sendAndGetResponse(String url, List<NameValuePair> params) throws IOException { HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); StringBuilder messageBuilder = new StringBuilder("\n"); messageBuilder.append(post.getMethod()); messageBuilder.append(" "); messageBuilder.append(post.getURI()); messageBuilder.append(" "); HttpEntity entity = post.getEntity(); String body = IOUtils.toString(entity.getContent()); List<NameValuePair> parse = URLEncodedUtils.parse(body, ContentType.get(entity).getCharset()); parse.stream().forEach(pair -> { messageBuilder.append(pair.getName()); messageBuilder.append(":"); messageBuilder.append(pair.getValue()); messageBuilder.append(" "); }); logger.warn("send httpRequest: {}", messageBuilder.toString()); CloseableHttpResponse response = client.execute(post); InputStream content = response.getEntity().getContent(); String s = IOUtils.toString(content); response.close(); logger.warn("get httpResponse: \n{}", s); return s; }
From source file:org.sentilo.platform.server.request.SentiloRequest.java
private void processUriParameters(final URI parsedUri) { final List<NameValuePair> pairs = URLEncodedUtils.parse(parsedUri, UTF8); parameters = new RequestParameters(pairs); }
From source file:io.hops.hopsworks.api.jupyter.URITemplateProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { //First collect params /*/*from w w w. java2s.c o m*/ * Do not use servletRequest.getParameter(arg) because that will * typically read and consume the servlet InputStream (where our * form data is stored for POST). We need the InputStream later on. * So we'll parse the query string ourselves. A side benefit is * we can keep the proxy parameters in the query string and not * have to add them to a URL encoded form attachment. */ String queryString = "?" + servletRequest.getQueryString();//no "?" but might have "#" int hash = queryString.indexOf('#'); if (hash >= 0) { queryString = queryString.substring(0, hash); } List<NameValuePair> pairs; try { //note: HttpClient 4.2 lets you parse the string without building the URI pairs = URLEncodedUtils.parse(new URI(queryString), "UTF-8"); } catch (URISyntaxException e) { throw new ServletException("Unexpected URI parsing error on " + queryString, e); } LinkedHashMap<String, String> params = new LinkedHashMap<>(); for (NameValuePair pair : pairs) { params.put(pair.getName(), pair.getValue()); } //Now rewrite the URL StringBuffer urlBuf = new StringBuffer();//note: StringBuilder isn't supported by Matcher Matcher matcher = TEMPLATE_PATTERN.matcher(targetUriTemplate); while (matcher.find()) { String arg = matcher.group(1); String replacement = params.remove(arg);//note we remove if (replacement != null) { matcher.appendReplacement(urlBuf, replacement); port = replacement; } else if (port != null) { matcher.appendReplacement(urlBuf, port); } else { throw new ServletException("Missing HTTP parameter " + arg + " to fill the template"); } } matcher.appendTail(urlBuf); String newTargetUri = urlBuf.toString(); servletRequest.setAttribute(ATTR_TARGET_URI, newTargetUri); try { targetUriObj = new URI(newTargetUri); } catch (Exception e) { throw new ServletException("Rewritten targetUri is invalid: " + newTargetUri, e); } servletRequest.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(targetUriObj)); //Determine the new query string based on removing the used names StringBuilder newQueryBuf = new StringBuilder(queryString.length()); for (Map.Entry<String, String> nameVal : params.entrySet()) { if (newQueryBuf.length() > 0) { newQueryBuf.append('&'); } newQueryBuf.append(nameVal.getKey()).append('='); if (nameVal.getValue() != null) { newQueryBuf.append(nameVal.getValue()); } } servletRequest.setAttribute(ATTR_QUERY_STRING, newQueryBuf.toString()); // Create Exchange object with targetUriObj // create transport object // ServiceProxy sp = new ServiceProxy(); // sp.setTargetUrl(ATTR_TARGET_URI); // super.service(servletRequest, servletResponse); // RouterUtil.initializeRoutersFromSpringWebContext(appCtx, config. // getServletContext(), getProxiesXmlLocation(config)); }