List of usage examples for java.net URL getQuery
public String getQuery()
From source file:com.celamanzi.liferay.portlets.rails286.RouteAnalyzer.java
/** Gets the href attribute of a link, and returns the request path */ public String getRequestRoute(String href) throws java.net.MalformedURLException { java.net.URL url = null; String path = null;//from ww w . j a v a 2 s. co m String params = null; String route = null; log.debug("Parsing the request route from: " + href); // ignore the url convertion if an absolute path is detected if (RouteAnalyzer.isAbsolutePath(href)) { return href; } // first extract path component, // without servlet definition, the path from a valid URL is returned. try { url = new java.net.URL(href); log.debug("Url: " + url.toString()); path = url.getPath(); log.debug("Path (pre-processed): " + path); params = url.getQuery(); log.debug("Params: " + params); } catch (java.net.MalformedURLException e) { path = href; params = null; } if (path == null) { path = ""; } // strip servlet? if (servlet != null) { // strip servlet from the path path = path.replaceFirst("/?" + servlet, ""); } // if an url is given, consider and empty path to represent "/" if (path.equals("") && url != null) { path = "/"; } log.debug("Path: " + path); // construct the route from path + params route = path; if (params != null) { route += "?" + params; } log.debug("Route: " + route); return route; }
From source file:com.ecomnext.rest.ning.NingRestRequestHolder.java
public NingRestRequestHolder(NingRestClient client, String url, String... params) { try {// w w w.ja v a 2 s . c o m this.client = client; UriTemplate uriTemplate = UriTemplate.fromTemplate(url); if (uriTemplate.getVariables().length != params.length) { throw new IllegalArgumentException( "The number of variables in the URL and the number of values do not match"); } for (int i = 0; i < params.length; i++) { uriTemplate.set(uriTemplate.getVariables()[i], params[i]); } url = uriTemplate.expand(); URL reference = new URL(url); this.url = url; String userInfo = reference.getUserInfo(); if (userInfo != null) { this.setAuth(userInfo); } if (reference.getQuery() != null) { this.setQueryString(reference.getQuery()); } } catch (MalformedURLException | MalformedUriTemplateException | VariableExpansionException e) { throw new RuntimeException(e); } }
From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientRemoteStorage.java
/** * Appends repository configured additional query string to provided URL. * * @param url to append to// ww w. ja va2s . co m * @param repository that may contain additional query string * @return URL with appended query string or original URL if repository does not have an configured query string * @throws RemoteStorageException if query string could not be appended (resulted in an Malformed URL exception) */ private URL appendQueryString(final URL url, final ProxyRepository repository) throws RemoteStorageException { final RemoteStorageContext ctx = getRemoteStorageContext(repository); final String queryString = ctx.getRemoteConnectionSettings().getQueryString(); if (StringUtils.isNotBlank(queryString)) { try { if (StringUtils.isBlank(url.getQuery())) { return new URL(url.toExternalForm() + "?" + queryString); } else { return new URL(url.toExternalForm() + "&" + queryString); } } catch (MalformedURLException e) { throw new RemoteStorageException( "Could not append query string \"" + queryString + "\" to url \"" + url + "\"", e); } } return url; }
From source file:com.pearson.pdn.learningstudio.oauth.OAuth1SignatureService.java
/** * Normalizes all OAuth signable parameters and url query parameters * according to OAuth 1.0//from w ww. jav a 2 s . c o m * * @param httpMethod * The upper-cased HTTP method * @param URL * The request URL * @param oauthParams * The associative set of signable oAuth parameters * @param requstBody * The serialized POST/PUT message body * * @return A string containing normalized and encoded oAuth parameters * * @throws UnsupportedEncodingException */ private String normalizeParams(String httpMethod, URL url, Map<String, String> oauthParams, byte[] requestBody) throws UnsupportedEncodingException { // Sort the parameters in lexicographical order, 1st by Key then by Value Map<String, String> kvpParams = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); kvpParams.putAll(oauthParams); // Place any query string parameters into a key value pair using equals // ("=") to mark // the key/value relationship and join each parameter with an ampersand // ("&") if (url.getQuery() != null) { for (String keyValue : url.getQuery().split("&")) { String[] p = keyValue.split("="); kvpParams.put(p[0], p[1]); } } // Include the body parameter if dealing with a POST or PUT request if ("POST".equals(httpMethod) || "PUT".equals(httpMethod)) { String body = Base64.encodeBase64String(requestBody).replaceAll("\r\n", ""); // url encode the body 2 times now before combining other params body = URLEncoder.encode(body, "UTF-8"); body = URLEncoder.encode(body, "UTF-8"); kvpParams.put("body", body); } // separate the key and values with a "=" // separate the kvp with a "&" StringBuilder combinedParams = new StringBuilder(); String delimiter = ""; for (String key : kvpParams.keySet()) { combinedParams.append(delimiter); combinedParams.append(key); combinedParams.append("="); combinedParams.append(kvpParams.get(key)); delimiter = "&"; } // url encode the entire string again before returning return URLEncoder.encode(combinedParams.toString(), "UTF-8"); }
From source file:de.tor.tribes.util.OBSTReportSender.java
public static void sendReport(URL pTarget, String pData) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(pTarget.getHost(), pTarget.getPort()); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {/*from w w w. ja v a 2 s . c om*/ HttpEntity[] requestBodies = { new StringEntity(pData) }; for (int i = 0; i < requestBodies.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", pTarget.getPath() + "?" + pTarget.getQuery()); request.setEntity(requestBodies[i]); // System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); // System.out.println("<< Response: " + response.getStatusLine()); // System.out.println(EntityUtils.toString(response.getEntity())); // System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
From source file:org.apache.nutch.net.urlnormalizer.protocol.ProtocolURLNormalizer.java
public String normalize(String url, CrawlDatum crawlDatum, String scope) throws MalformedURLException { // Get URL repr. URL u = new URL(url); // Get the host String host = u.getHost();//w w w. j a va 2s . c o m // Do we have a rule for this host? if (protocolsMap.containsKey(host)) { String protocol = u.getProtocol(); String requiredProtocol = protocolsMap.get(host); // Incorrect protocol? if (!protocol.equals(requiredProtocol)) { // Rebuild URL with new protocol StringBuilder buffer = new StringBuilder(requiredProtocol); buffer.append(PROTOCOL_DELIMITER); buffer.append(host); buffer.append(u.getPath()); String queryString = u.getQuery(); if (queryString != null) { buffer.append(QUESTION_MARK); buffer.append(queryString); } url = buffer.toString(); } } return url; }
From source file:cn.com.loopj.android.http.AsyncHttpClient.java
/** * Will encode url, if not disabled, and adds params on the end of it * * @param url String with URL, should be valid URL without params * @param params RequestParams to be appended on the end of URL * @param shouldEncodeUrl whether url should be encoded (replaces spaces with %20) * @return encoded url if requested with params appended if any available *///from w ww . java2s . c o m public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) { if (url == null) return null; if (shouldEncodeUrl) { try { String decodedURL = URLDecoder.decode(url, "UTF-8"); URL _url = new URL(decodedURL); URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(), _url.getPath(), _url.getQuery(), _url.getRef()); url = _uri.toASCIIString(); } catch (Exception ex) { // Should not really happen, added just for sake of validity log.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex); } } if (params != null) { // Construct the query string and trim it, in case it // includes any excessive white spaces. String paramString = params.getParamString().trim(); // Only add the query string if it isn't empty and it // isn't equal to '?'. if (!paramString.equals("") && !paramString.equals("?")) { url += url.contains("?") ? "&" : "?"; url += paramString; } } return url; }
From source file:com.appeligo.search.actions.ToolbarUpdateAction.java
public String execute() throws Exception { Integer toolbarRevision = (Integer) getSession().get("toolbarRevision"); if (toolbarRevision == null) { revision = 0;//from w ww . j av a 2s .c o m } else { revision = toolbarRevision.intValue() + 1; } getSession().put("toolbarRevision", new Integer(revision)); try { URL u = new URL(url); String host = u.getHost(); if (host.startsWith("www.")) { host = host.substring(4); } log.debug(host); log.debug(u.getPort()); log.debug(u.getPath()); SearchEngine searchEngine = searchEngineMap.get(host); if ((searchEngine != null) && (u.getPort() == searchEngine.getPort() || ((u.getPort() == -1) && (searchEngine.getPort() == 80))) && (u.getPath().indexOf(searchEngine.getPath()) == 0)) { String query = u.getQuery(); if (query != null) { String[] params = query.split("&"); for (String param : params) { if (param.startsWith(searchEngine.getParam())) { log.debug(param); String q = param.substring(searchEngine.getParam().length()); q = URLDecoder.decode(q, "UTF-8"); log.debug(q); setQuery(q); String indexDir = ConfigUtils.getSystemConfig().getString("luceneIndex"); String compositeIndexDir = ConfigUtils.getSystemConfig().getString("compositeIndex"); if (IndexReader.indexExists(indexDir)) { String lineup = getLineup(); searchResults = new SearchResults(indexDir, compositeIndexDir, 10, lineup); searchResults.setLineup(lineup); searchResults.setQuery(getQuery()); searchResults.setSearchType(getSearchTypeAsSearchType()); hits = searchResults.getSearchResults(0); } break; } } } } } catch (MalformedURLException e) { //ignore; } return SUCCESS; }
From source file:com.bigstep.datalake.DLFileSystem.java
/** * Remove offset parameter, if there is any, from the url *///w w w . j av a2 s. c om static URL removeOffsetParam(final URL url) throws MalformedURLException { String query = url.getQuery(); if (query == null) { return url; } final String lower = StringUtils.toLowerCase(query); if (!lower.startsWith(OFFSET_PARAM_PREFIX) && !lower.contains("&" + OFFSET_PARAM_PREFIX)) { return url; } //rebuild query StringBuilder b = null; for (final StringTokenizer st = new StringTokenizer(query, "&"); st.hasMoreTokens();) { final String token = st.nextToken(); if (!StringUtils.toLowerCase(token).startsWith(OFFSET_PARAM_PREFIX)) { if (b == null) { b = new StringBuilder("?").append(token); } else { b.append('&').append(token); } } } query = b == null ? "" : b.toString(); final String urlStr = url.toString(); return new URL(urlStr.substring(0, urlStr.indexOf('?')) + query); }
From source file:com.all.facebook.impl.FacebookServiceImpl.java
@Override public String authorizeUrl(String responseUrl) throws FacebookServiceException { URL url; try {// www . j ava 2 s.com url = new URL(responseUrl); } catch (MalformedURLException e) { throw new FacebookServiceException(e); } if (!responseUrl.contains(REDIRECT_URI)) { throw new FacebookServiceException( "The url does not correpond with the redirect_uri parameter: " + responseUrl); } String ref = url.getRef(); if (ref == null) { Map<String, String> error = extractKeyValuePairs(url.getQuery()); String errorType = error.get("error"); throw new FacebookServiceException(error.toString(), errorType); } Map<String, String> keyValuePairs = extractKeyValuePairs(ref); if (!keyValuePairs.containsKey("access_token")) { throw new FacebookServiceException( "Could not find the access token in the responseUrl: " + responseUrl); } authorize(keyValuePairs.get("access_token")); return accessToken; }