List of usage examples for java.net URL getQuery
public String getQuery()
From source file:com.amytech.android.library.utils.asynchttp.AsyncHttpClient.java
/** * Will encode url, if not disabled, and adds params on the end of it * * @param url//from w w w . j av a 2 s. co m * 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 */ 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:org.apache.stratos.load.balancer.endpoint.TenantAwareLoadBalanceEndpoint.java
private EndpointReference getEndpointReferenceAfterURLRewrite(MessageContext synCtx, org.apache.axis2.clustering.Member currentMember, String transport) { try {/*from www . j a va 2 s. c o m*/ if (transport.startsWith(Constants.HTTPS)) { transport = Constants.HTTPS; } else if (transport.startsWith(Constants.HTTP)) { transport = Constants.HTTP; } else { String msg = "Cannot load balance for non-HTTP/S transport " + transport; log.error(msg); throwSynapseException(synCtx, 500, msg); } String address = synCtx.getTo().getAddress(); if (address.startsWith(Constants.HTTP + "://") || address.startsWith(Constants.HTTPS + "://")) { // Remove protocol, hostname and port found in address try { URL addressUrl = new URL(address); address = addressUrl.getPath() + (StringUtils.isNotBlank(addressUrl.getQuery()) ? "?" + addressUrl.getQuery() : ""); } catch (MalformedURLException e) { String msg = String.format("URL is malformed: %s", address); log.error(msg, e); throw new SynapseException(msg, e); } } String hostName = extractTargetHost(synCtx); if (LoadBalancerContext.getInstance().getHostNameAppContextMap().contains(hostName)) { String appContext = LoadBalancerContext.getInstance().getHostNameAppContextMap() .getAppContext(hostName); if (StringUtils.isNotBlank(appContext)) { if (log.isDebugEnabled()) { log.debug(String.format( "Domain mapping found with application context: [domain-name] %s [app-context] %s", hostName, appContext)); log.debug(String.format("Incoming request address: %s", address)); } address = "/" + cleanURLPath(appContext) + "/" + cleanURLPath(address); if (log.isDebugEnabled()) { log.debug(String.format("Outgoing request address: %s", address)); } } } String memberHostName = currentMember.getHostName(); int memberPort = (transport.startsWith(Constants.HTTPS)) ? currentMember.getHttpsPort() : currentMember.getHttpPort(); return new EndpointReference(new URL(transport, memberHostName, memberPort, address).toString()); } catch (MalformedURLException e) { if (log.isErrorEnabled()) { log.error("Could not create endpoint reference", e); } throwSynapseException(synCtx, 500, "Internal server error"); return null; } }
From source file:org.imsglobal.lti.toolProvider.ToolConsumer.java
/** * Add the OAuth signature to an LTI message. * * @param String url URL for message request * @param String type LTI message type * @param String version LTI version * @param Map params Message parameters * * @return array Array of signed message parameters *//* w ww. ja v a 2 s. c om*/ public Map<String, List<String>> signParameters(String urlString, String type, String version, String method, Map<String, List<String>> params) { List<Entry<String, String>> oparams = new ArrayList<Entry<String, String>>(); Map<String, List<String>> queryParams = new HashMap<String, List<String>>(); if (urlString != null) { // Check for query parameters which need to be included in the signature try { URL url = new URL(urlString); String query = url.getQuery(); if (StringUtils.isNotEmpty(query)) { queryParams = OAuthUtil.parse_parameters(url.getQuery()); } params.putAll(queryParams); // Add standard parameters LTIUtil.setParameter(params, "lti_version", version); LTIUtil.setParameter(params, "lti_message_type", type); LTIUtil.setParameter(params, "oauth_callback", "about:blank"); oparams = convert(params); if (StringUtils.isEmpty(method)) { method = "POST"; } // Add OAuth signature OAuthMessage message = doSignature(urlString, oparams, getKey(), getSecret(), method); oparams = message.getParameters(); //replace with signed parameters // Remove parameters being passed on the query string oparams = removeQueryParams(oparams, queryParams); } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } catch (OAuthException e1) { e1.printStackTrace(); } catch (URISyntaxException e1) { e1.printStackTrace(); } } return convertBack(oparams); }
From source file:com.xpn.xwiki.web.XWikiServletURLFactory.java
/** * Converts a URL to a relative URL if it's a XWiki URL (keeping only the path + query string + anchor) and leave * the URL unchanged if it's an external URL. * <p>//from w w w .ja v a 2 s .c o m * An URL is considered to be external if its server component doesn't match the server of the current request URL. * This means that URLs are made relative with respect to the current request URL rather than the current wiki set * on the XWiki context. Let's take an example: * * <pre> * {@code * request URL: http://playground.xwiki.org/xwiki/bin/view/Sandbox/TestURL * current wiki: code (code.xwiki.org) * URL (1): http://code.xwiki.org/xwiki/bin/view/Main/WebHome * URL (2): http://playground.xwiki.org/xwiki/bin/view/Spage/Page * * The result will be: * (1) http://code.xwiki.org/xwiki/bin/view/Main/WebHome * (2) /xwiki/bin/view/Spage/Page * } * </pre> * * @param url the URL to convert * @return the converted URL as a string * @see com.xpn.xwiki.web.XWikiDefaultURLFactory#getURL(java.net.URL, com.xpn.xwiki.XWikiContext) */ @Override public String getURL(URL url, XWikiContext context) { try { if (url == null) { return ""; } String surl = url.toString(); if (!surl.startsWith(serverURL.toString())) { // External URL: leave it as is. return surl; } else { // Internal XWiki URL: convert to relative. StringBuffer sbuf = new StringBuffer(url.getPath()); String querystring = url.getQuery(); if (!StringUtils.isEmpty(querystring)) { sbuf.append("?"); sbuf.append(StringUtils.chomp(StringUtils.chomp(querystring, "&"), "&")); // sbuf.append(querystring.replaceAll("&","&")); } String anchor = url.getRef(); if (!StringUtils.isEmpty(anchor)) { sbuf.append("#"); sbuf.append(anchor); } return Util.escapeURL(sbuf.toString()); } } catch (Exception e) { e.printStackTrace(); return ""; } }
From source file:com.google.acre.script.NHttpClient.java
public void fetch(String url, String method, Map<String, String> headers, byte[] body, long timeout, boolean no_redirect, NHttpClientCallback callback) throws NHttpException { URL u; String path;/*from www .ja v a2s .co m*/ HttpRequest req; try { u = new URL(url); } catch (MalformedURLException e) { throw new NHttpException(e); } // Proxies expect the entire URL as the path if (_proxy == null || !_proxy.use_proxy(url)) { path = u.getPath(); if (path.equals("")) { path = "/"; } if (u.getQuery() != null) { path += "?" + u.getQuery(); } } else { path = url; } if ((method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) && body.length > 0) { req = new BasicHttpEntityEnclosingRequest(method, path); NByteArrayEntity bae = new NByteArrayEntity(body); ((HttpEntityEnclosingRequest) req).setEntity(bae); } else { req = new BasicHttpRequest(method, path); } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { req.addHeader(header.getKey(), header.getValue()); } } if (req instanceof HttpEntityEnclosingRequest) req.removeHeaders("Content-Length"); fetch(u, req, timeout, no_redirect, callback); }
From source file:de.betterform.agent.betty.Betty.java
protected AppletProcessor initAdapter(URL documentBaseUrl) throws MalformedURLException, XFormsException, URISyntaxException, DOMUnsupportedException, DOMAccessException, TransformerException { // update splash screen // javascriptCall("setView", getSplashScreen("initializing", this.documentName)); // create context and uri Map context = new HashMap(); URI documentBaseURI = Betty.toFileCompatibleURI(documentBaseUrl); // parse cookies ans parameters Betty.parseCookies(this, context); if (documentBaseUrl.getQuery() != null) { Betty.parseParameters(documentBaseUrl, context); }//from ww w . j a va 2 s .c o m // setup processor AppletProcessor processor = new AppletProcessor(); processor.setBetterFormApplet(this); processor.setContextClassLoader(Thread.currentThread().getContextClassLoader()); processor.setUploadDir(new File(documentBaseURI).getParentFile().getAbsolutePath()); //hack around AbstractBetterFormAdapter to set contextmap processor.setContext(context); processor.setBaseURI(documentBaseURI.toString()); processor.setXForms(documentBaseURI); // init processor processor.init(); return processor; }
From source file:org.piwik.SimplePiwikTracker.java
/** * Returns the uery part for the url with all parameters from all given informations set to this tracker. This * function is called in the defined URL for the tacking purpose. * /*from w w w.j a v a2 s .c o m*/ * @return the query part for the URL as string object */ public final String getGeneralQuery() { final URL rootURL = this.apiurl; final String rootQuery = rootURL.getQuery(); final String eventCategory = this.addParameter(rootQuery, "e_c", this.eventCategory); final String eventAction = this.addParameter(eventCategory, "e_a", this.eventAction); final String eventName = this.addParameter(eventAction, "e_n", this.eventName); String value = null; if (this.eventValue != null) { value = Float.toString(this.eventValue); } final String eventValue = this.addParameter(eventName, "e_v", value); final String withIdsite = this.addParameter(eventValue, "idsite", this.idSite); final String withRec = this.addParameter(withIdsite, "rec", 1); // what ever this is final String withApiVersion = this.addParameter(withRec, "apiv", SimplePiwikTracker.VERSION); final String withURL = this.addParameter(withApiVersion, "url", this.pageUrl); final String withURLReferrer = this.addParameter(withURL, "urlref", this.urlReferrer); final String withVisitorId = this.addParameter(withURLReferrer, "_id", this.visitorId); final String withReferrer = this.addParameter(withVisitorId, "ref", this.urlReferrer); final String withReferrerForcedTimestamp = this.addParameter(withReferrer, "_refts", this.forcedDatetime); final String withIp = this.addParameter(withReferrerForcedTimestamp, "cip", this.ip); final String withForcedTimestamp = this.addParameter(withIp, "cdt", forcedDatetime == null ? null : new SimpleDateFormat("yyyyMMdd HH:mm:ssZ").format(forcedDatetime)); final String withAuthtoken = this.addParameter(withForcedTimestamp, "token_auth", this.tokenAuth); String withPlugins = withAuthtoken; for (final Map.Entry<BrowserPlugins, Boolean> entry : this.plugins.entrySet()) { withPlugins = this.addParameter(withPlugins, entry.getKey().toString(), entry.getValue()); } final String withLocalTime; if (this.localTime == null) { withLocalTime = withPlugins; } else { final Calendar c = new GregorianCalendar(); c.setTime(this.localTime); final String withHour = this.addParameter(withPlugins, "h", c.get(Calendar.HOUR_OF_DAY)); final String withMinute = this.addParameter(withHour, "m", c.get(Calendar.MINUTE)); withLocalTime = this.addParameter(withMinute, "s", c.get(Calendar.SECOND)); } final String withResolution; if (this.width > 0 && this.height > 0) { withResolution = this.addParameter(withLocalTime, "res", this.width + "x" + this.height); } else { withResolution = withLocalTime; } final String withCookieInfo = this.addParameter(withResolution, "cookie", this.requestCookie != null); final String withVisitorCustomData = this.addParameter(withCookieInfo, "data", this.visitorCustomData); /* ADD VISITOR CUSTOM VARIABLES */ final String withVisitorCustomVar; if (this.visitorCustomVar.isEmpty()) { withVisitorCustomVar = withVisitorCustomData; } else { final Map<String, List<String>> customVariables = new HashMap<String, List<String>>(); int i = 0; for (final Map.Entry<String, String> entry : this.visitorCustomVar.entrySet()) { i++; final List<String> list = new ArrayList<String>(); list.add(entry.getKey()); list.add(entry.getValue()); customVariables.put(Integer.toString(i), list); } final JSONArray json = new JSONArray(); json.put(customVariables); // remove unnecessary parent square brackets from JSON-string String jsonString = json.toString().substring(1, json.toString().length() - 1); // visitor custom variables: _cvar withVisitorCustomVar = this.addParameter(withVisitorCustomData, "_cvar", jsonString); } /* ADD PAGE CUSTOM VARIABLES */ final String withPageCustomData = this.addParameter(withVisitorCustomVar, "data", this.pageCustomData); final String withPageCustomVar; if (this.pageCustomVar.isEmpty()) { withPageCustomVar = withPageCustomData; } else { final Map<String, List<String>> customVariables = new HashMap<String, List<String>>(); int i = 0; for (final Map.Entry<String, String> entry : this.pageCustomVar.entrySet()) { i++; final List<String> list = new ArrayList<String>(); list.add(entry.getKey()); list.add(entry.getValue()); customVariables.put(Integer.toString(i), list); } final JSONArray json = new JSONArray(); json.put(customVariables); // remove unnecessary parent square brackets from JSON-string String jsonString = json.toString().substring(1, json.toString().length() - 1); // page custom variables: cvar withPageCustomVar = this.addParameter(withPageCustomData, "cvar", jsonString); } final String withRand = this.addParameter(withPageCustomVar, "r", String.valueOf(random.nextDouble()).substring(2, 8)); return (withRand + this.debugAppendUrl); }
From source file:gov.loc.www.zing.srw.srw_bindings.SRWSoapBindingImpl.java
public ScanResponseType scanOperation(ScanRequestType request) throws java.rmi.RemoteException { log.debug("Enter: scanOperation"); if (log.isInfoEnabled()) { log.info("request: maximumTerms:" + request.getMaximumTerms() + " scanClause:" + request.getScanClause() + " stylesheet:" + request.getStylesheet() + " responsePosition:" + request.getResponsePosition() + " version:" + request.getVersion()); }/*from w w w.j a va 2 s.co m*/ MessageContext msgContext = MessageContext.getCurrentContext(); ScanResponseType response; String dbname = (String) msgContext.getProperty("dbname"); SRWDatabase db = (SRWDatabase) msgContext.getProperty("db"); if (log.isDebugEnabled()) log.debug("db=" + db); if (request.getScanClause() == null) { response = new ScanResponseType(); db.diagnostic(SRWDiagnostic.MandatoryParameterNotSupplied, "scanClause", response); } else if (request.getResponsePosition() != null && request.getResponsePosition().intValue() == Integer.MAX_VALUE) { response = new ScanResponseType(); db.diagnostic(SRWDiagnostic.UnsupportedParameterValue, "responsePosition", response); } else if (request.getMaximumTerms() != null && request.getMaximumTerms().intValue() == Integer.MAX_VALUE) { response = new ScanResponseType(); db.diagnostic(SRWDiagnostic.UnsupportedParameterValue, "maximumTerms", response); } else try { response = db.doRequest(request); // set extraResponseData StringBuffer extraResponseData = new StringBuffer(); // we're going to stick the database name in extraResponseData every time if (db.databaseTitle != null) extraResponseData.append("<databaseTitle>").append(db.databaseTitle).append("</databaseTitle>"); else extraResponseData.append("<databaseTitle>").append(dbname).append("</databaseTitle>"); Hashtable extraRequestDataElements = SRWDatabase.parseElements(request.getExtraRequestData()); String s = (String) extraRequestDataElements.get("returnTargetURL"); log.info("returnTargetURL=" + s); if (s != null && !s.equals("false")) { String targetStr = (String) msgContext.getProperty("targetURL"); log.info("targetStr=" + targetStr); if (targetStr != null && targetStr.length() > 0) { URL target = new URL(targetStr); extraResponseData.append("<targetURL>").append("<host>").append(target.getHost()) .append("</host>").append("<port>").append(target.getPort()).append("</port>") .append("<path>").append(target.getPath()).append("</path>").append("<query>") .append(Utilities.xmlEncode(target.getQuery())).append("</query>") .append("</targetURL>"); } } // set extraResponseData SRWDatabase.setExtraResponseData(response, extraResponseData.toString()); } catch (Exception e) { log.error(e, e); throw new RemoteException(e.getMessage(), e); } finally { SRWDatabase.putDb(dbname, db); } if (response != null) { log.info("calling setEchoedScanRequestType"); setEchoedScanRequestType(request, response); log.info("called setEchoedScanRequestType"); response.setVersion("1.1"); } log.debug("Exit: scanOperation"); return response; }
From source file:com.diversityarrays.dalclient.DefaultDALClient.java
private DalResponse performQueryInternal(String command, boolean needToCheck) throws IOException, DalResponseException { String urls;// w w w .j ava 2s. com if (command.startsWith("http:")) { //$NON-NLS-1$ // Hmmm. This is a hack to support the results of export commands et. al. urls = command; } else { StringBuilder sb = new StringBuilder(baseUrl); sb.append(command); if (!responseType.isXML()) { URL url = new URL(sb.toString()); // User may already have appended parameters sb.append((url.getQuery() == null) ? '?' : '&').append("ctype=").append(responseType.postValue); //$NON-NLS-1$ } urls = sb.toString(); } if (needToCheck) { checkIfOkToPerform(urls.substring(baseUrl.length())); } logInfo("performing query: " + urls); //$NON-NLS-1$ DalRequest request = dalHttpFactory.createHttpGet(urls); Long[] elapsedMillis = new Long[1]; HttpResponseInfo result = DalUtil.doHttp(httpClient, request, dalHttpFactory.createResponseHandler(), elapsedMillis); result.elapsedMillis = elapsedMillis[0].longValue(); logDebug("Elapsed ms=" + result.elapsedMillis + " for " + urls); //$NON-NLS-1$ //$NON-NLS-2$ return buildDalResponse(urls, result); }
From source file:gov.loc.www.zing.srw.srw_bindings.SRWSoapBindingImpl.java
public SearchRetrieveResponseType searchRetrieveOperation(SearchRetrieveRequestType request) throws RemoteException { log.debug("Enter: searchRetrieveOperation"); if (log.isInfoEnabled()) { log.info("request: maximumRecords:" + request.getMaximumRecords() + " query:" + request.getQuery() + " recordPacking:" + request.getRecordPacking() + " recordSchema:" + request.getRecordSchema() + " recordXpath:" + request.getRecordXPath() + " sortKeys:" + request.getSortKeys() + " startRecord:" + request.getStartRecord() + " stylesheet:" + request.getStylesheet() + " version:" + request.getVersion()); }//w w w . jav a2s . c om long startTime = System.currentTimeMillis(); MessageContext msgContext = MessageContext.getCurrentContext(); SearchRetrieveResponseType response; int resultSetIdleTime = ((Integer) msgContext.getProperty("resultSetIdleTime")).intValue(); NonNegativeInteger nni = request.getResultSetTTL(); if (log.isDebugEnabled()) log.debug("resultSetTTL()=" + nni); if (nni != null) { int ttl = nni.intValue(); log.debug("ttl=" + ttl); if (ttl < resultSetIdleTime) resultSetIdleTime = ttl; } String dbname = (String) msgContext.getProperty("dbname"); SRWDatabase db = (SRWDatabase) msgContext.getProperty("db"); if (log.isDebugEnabled()) log.debug("db=" + db); String sortKeys = request.getSortKeys(); if (sortKeys != null) request.setSortKeys(sortKeys); String query = request.getQuery(); if (query.indexOf('%') >= 0) try { request.setQuery(java.net.URLDecoder.decode(query, "utf-8")); } catch (java.io.UnsupportedEncodingException e) { } if (query == null) { response = new SearchRetrieveResponseType(); db.diagnostic(SRWDiagnostic.MandatoryParameterNotSupplied, "query", response); } else if (request.getStartRecord() != null && request.getStartRecord().intValue() == Integer.MAX_VALUE) { response = new SearchRetrieveResponseType(); db.diagnostic(SRWDiagnostic.UnsupportedParameterValue, "startRecord", response); } else if (request.getMaximumRecords() != null && request.getMaximumRecords().intValue() == Integer.MAX_VALUE) { response = new SearchRetrieveResponseType(); db.diagnostic(SRWDiagnostic.UnsupportedParameterValue, "maximumRecords", response); } else if (request.getResultSetTTL() != null && request.getResultSetTTL().intValue() == Integer.MAX_VALUE) { response = new SearchRetrieveResponseType(); db.diagnostic(SRWDiagnostic.UnsupportedParameterValue, "resultSetTTL", response); } else try { response = db.doRequest(request); if (response == null) { response = new SearchRetrieveResponseType(); response.setVersion("1.1"); setEchoedSearchRetrieveRequestType(request, response); db.diagnostic(SRWDiagnostic.GeneralSystemError, null, response); return response; } if (msgContext.getProperty("sru") != null && request.getStylesheet() != null) // you can't ask for a stylesheet in srw! db.diagnostic(SRWDiagnostic.StylesheetsNotSupported, null, response); setEchoedSearchRetrieveRequestType(request, response); if (request.getRecordXPath() != null) db.diagnostic(72, null, response); if (request.getSortKeys() != null && !request.getSortKeys().equals("") && !db.supportsSort()) db.diagnostic(SRWDiagnostic.SortNotSupported, null, response); // set extraResponseData StringBuffer extraResponseData = new StringBuffer(); // we're going to stick the database name in extraResponseData every time if (db.databaseTitle != null) extraResponseData.append("<databaseTitle>").append(db.databaseTitle).append("</databaseTitle>"); else extraResponseData.append("<databaseTitle>").append(dbname).append("</databaseTitle>"); // did they ask for the targetURL to be returned? Hashtable extraRequestDataElements = SRWDatabase.parseElements(request.getExtraRequestData()); String s = (String) extraRequestDataElements.get("returnTargetURL"); log.info("returnTargetURL=" + s); if (s != null && !s.equals("false")) { String targetStr = (String) msgContext.getProperty("targetURL"); log.info("targetStr=" + targetStr); if (targetStr != null && targetStr.length() > 0) { URL target = new URL(targetStr); extraResponseData.append("<targetURL>").append("<host>").append(target.getHost()) .append("</host>").append("<port>").append(target.getPort()).append("</port>") .append("<path>").append(target.getPath()).append("</path>").append("<query>") .append(Utilities.xmlEncode(target.getQuery())).append("</query>") .append("</targetURL>"); } } // set extraResponseData SRWDatabase.setExtraResponseData(response, extraResponseData.toString()); } catch (Exception e) { log.error(e, e); throw new RemoteException(e.getMessage(), e); } finally { SRWDatabase.putDb(dbname, db); } response.setVersion("1.1"); log.info("\"" + query + "\"==>" + response.getNumberOfRecords() + " (" + (System.currentTimeMillis() - startTime) + "ms)"); log.debug("Exit: searchRetrieveOperation"); return response; }