Java Code Examples for java.net.URL#getQuery()

The following examples show how to use java.net.URL#getQuery() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: mercury   File: AsyncHttpRequest.java    License: Apache License 2.0 6 votes vote down vote up
public AsyncHttpRequest setRelay(String host) {
    if (host != null && (host.startsWith(HTTP_PROTOCOL) || host.startsWith(HTTPS_PROTOCOL))) {
        try {
            URL u = new URL(host);
            if (!u.getPath().isEmpty()) {
                throw new IllegalArgumentException("Invalid host - Must not contain path");
            }
            if (u.getQuery() != null) {
                throw new IllegalArgumentException("Invalid host - Must not contain query");
            }
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("Invalid host - "+e.getMessage());
        }
        this.relay = host;
        return this;
    } else {
        throw new IllegalArgumentException("Invalid host - must starts with "+HTTP_PROTOCOL+" or "+HTTPS_PROTOCOL);
    }
}
 
Example 2
private static void parseUrl(XulHttpTask xulHttpTask, String url) {
	try {
		URL reqUrl = new URL(url);
		xulHttpTask.setSchema(reqUrl.getProtocol())
				.setHost(reqUrl.getHost())
				.setPort(reqUrl.getPort())
				.setPath(reqUrl.getPath());
		String queryStr = reqUrl.getQuery();
		if (!TextUtils.isEmpty(queryStr)) {
			String[] params = queryStr.split("&");
			for (String param : params) {
				String[] pair = param.split("=");
				encodeParams(pair);
				if (pair.length == 2) {
					xulHttpTask.addQuery(pair[0], pair[1]);
				} else if (pair.length == 1) {
					xulHttpTask.addQuery(pair[0], "");
				} // else 无效参数
			}
		}
	} catch (MalformedURLException e) {
		xulHttpTask.setPath(url);
	}
}
 
Example 3
public static java.net.URI toURI(URL url) {
    String protocol = url.getProtocol();
    String auth = url.getAuthority();
    String path = url.getPath();
    String query = url.getQuery();
    String ref = url.getRef();
    if (path != null && !(path.startsWith("/")))
        path = "/" + path;

    //
    // In java.net.URI class, a port number of -1 implies the default
    // port number. So get it stripped off before creating URI instance.
    //
    if (auth != null && auth.endsWith(":-1"))
        auth = auth.substring(0, auth.length() - 3);

    java.net.URI uri;
    try {
        uri = createURI(protocol, auth, path, query, ref);
    } catch (java.net.URISyntaxException e) {
        uri = null;
    }
    return uri;
}
 
Example 4
Source Project: j2objc   File: ParseUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static java.net.URI toURI(URL url) {
    String protocol = url.getProtocol();
    String auth = url.getAuthority();
    String path = url.getPath();
    String query = url.getQuery();
    String ref = url.getRef();
    if (path != null && !(path.startsWith("/")))
        path = "/" + path;

    //
    // In java.net.URI class, a port number of -1 implies the default
    // port number. So get it stripped off before creating URI instance.
    //
    if (auth != null && auth.endsWith(":-1"))
        auth = auth.substring(0, auth.length() - 3);

    java.net.URI uri;
    try {
        uri = createURI(protocol, auth, path, query, ref);
    } catch (java.net.URISyntaxException e) {
        uri = null;
    }
    return uri;
}
 
Example 5
public static Map<String, String> paramsFromURL(final URL url)
{
  final Map<String, String> res = new HashMap<String, String>();
  final String query = url.getQuery();
  if (null != query) {
    final StringTokenizer st = new StringTokenizer(query, "&");
    while (st.hasMoreTokens()) {
      final String tok = st.nextToken();
      final int delimPos = tok.indexOf('=');
      final String key = tok.substring(0, delimPos).trim();
      final String value = tok.substring(delimPos + 1).trim();

      res.put(key, value);
    }
  }
  return res;
}
 
Example 6
private String urltoString(URL u) {
    int len = u.getProtocol().length() + 1;
    if (u.getAuthority() != null && u.getAuthority().length() > 0)
        len += 2 + u.getAuthority().length();
    if (u.getPath() != null) {
        len += u.getPath().length();
    }
    if (u.getQuery() != null) {
        len += 1 + u.getQuery().length();
    }
    if (u.getRef() != null)
        len += 1 + u.getRef().length();

    StringBuffer result = new StringBuffer(len);
    result.append(u.getProtocol());
    result.append(":");
    if (u.getAuthority() != null && u.getAuthority().length() > 0) {
        result.append("//");
        result.append(u.getAuthority());
    }
    if (u.getPath() != null) {
        result.append(u.getPath());
    }
    return result.toString();
}
 
Example 7
private String urltoString(URL u) {
    int len = u.getProtocol().length() + 1;
    if (u.getAuthority() != null && u.getAuthority().length() > 0)
        len += 2 + u.getAuthority().length();
    if (u.getPath() != null) {
        len += u.getPath().length();
    }
    if (u.getQuery() != null) {
        len += 1 + u.getQuery().length();
    }
    if (u.getRef() != null)
        len += 1 + u.getRef().length();

    StringBuffer result = new StringBuffer(len);
    result.append(u.getProtocol());
    result.append(":");
    if (u.getAuthority() != null && u.getAuthority().length() > 0) {
        result.append("//");
        result.append(u.getAuthority());
    }
    if (u.getPath() != null) {
        result.append(u.getPath());
    }
    return result.toString();
}
 
Example 8
Source Project: pili-sdk-java   File: Mac.java    License: MIT License 5 votes vote down vote up
public String signRequest(URL url, String method, byte[] body, String contentType) throws Exception {
    StringBuilder sb = new StringBuilder();

    sb.append(String.format("%s %s", method, url.getPath()));
    if (url.getQuery() != null) {
        sb.append(String.format("?%s", url.getQuery()));
    }

    sb.append(String.format("\nHost: %s", url.getHost()));
    if (url.getPort() > 0) {
        sb.append(String.format(":%d", url.getPort()));
    }

    if (contentType != null) {
        sb.append(String.format("\nContent-Type: %s", contentType));
    }

    // body
    sb.append("\n\n");
    if (incBody(body, contentType)) {
        sb.append(new String(body));
    }

    byte[] sum = HMac.HmacSHA1Encrypt(sb.toString(), this.secretKey);
    String sign = UrlSafeBase64.encodeToString(sum);
    return this.accessKey + ":" + sign;

}
 
Example 9
@Test
public void testFormatReportUrl() throws MalformedURLException {
  URL url = new URL(BugReportCommandHandler.formatReportUrl());

  assertEquals("https", url.getProtocol());
  assertEquals("github.com", url.getHost());
  assertEquals("/GoogleCloudPlatform/google-cloud-eclipse/issues/new", url.getPath());

  // check that values are properly filled in
  Pattern pattern =
      Pattern.compile(
          "body="
              + "%3C%21--%0ABefore\\+reporting\\+a\\+possible\\+bug%3A%0A%0A"
              + "1.\\+Please\\+ensure\\+you\\+are\\+running\\+the\\+latest\\+version\\+of\\+CT4E\\+with\\+_Help\\+%3E\\+Check\\+for\\+Updates_%0A"
              + "2.\\+If\\+the\\+problem\\+occurs\\+when\\+you\\+deploy\\+or\\+after\\+the\\+application\\+has\\+been\\+deployed%2C\\+try\\+deploying\\+from\\+the\\+command\\+line\\+using\\+gcloud\\+or\\+Maven."
              + "\\+If\\+the\\+problem\\+does\\+not\\+go\\+away%2C\\+then\\+the\\+issue\\+is\\+likely\\+not\\+with\\+Cloud\\+Tools\\+for\\+Eclipse.%0A--%3E%0A"
              + "-\\+Cloud\\+Tools\\+for\\+Eclipse\\+version%3A\\+(?<toolVersion>.*)%0A"
              + "-\\+Google\\+Cloud\\+SDK\\+version%3A\\+(?<gcloudVersion>[\\d.]*)\\+%28non-managed%29%0A"
              + "-\\+Eclipse\\+version%3A\\+(?<eclipseVersion>.*)%0A"
              + "-\\+OS%3A\\+(?<os>.*)%0A"
              + "-\\+Java\\+version%3A\\+(?<javaVersion>.*)%0A%0A"
              + "\\*\\*What\\+did\\+you\\+do%3F\\*\\*%0A%0A"
              + "\\*\\*What\\+did\\+you\\+expect\\+to\\+see%3F\\*\\*%0A%0A"
              + "\\*\\*What\\+did\\+you\\+see\\+instead%3F\\*\\*%0A%0A"
              + "%3C%21--\\+Screenshots\\+and\\+stacktraces\\+are\\+helpful.\\+--%3E");
  String query = url.getQuery();
  Matcher matcher = pattern.matcher(query);
  assertTrue(query, matcher.matches());
  String toolVersion = matcher.group("toolVersion");
  String gcloudVersion = matcher.group("gcloudVersion");
  String eclipseVersion = matcher.group("eclipseVersion");
  String os = matcher.group("os");
  String javaVersion = matcher.group("javaVersion");

  assertTrue(Pattern.compile("^\\d+\\.\\d+\\.\\d+").matcher(toolVersion).find());
  assertThat(javaVersion, anyOf(startsWith("1.7."), startsWith("1.8."), is("11"), startsWith("11.")));
  assertThat(os, anyOf(startsWith("Linux"), startsWith("Mac"), startsWith("Windows")));
  assertTrue(Pattern.compile("^\\d+\\.\\d+").matcher(eclipseVersion).find());
  new CloudSdkVersion(gcloudVersion); // throws IllegalArgumentException if invalid
}
 
Example 10
@Test
@Category(UnitTest.class)
public void getAuthorizationURLSuccess() throws Exception {
    List<String> scopes = new ArrayList<String>();
    scopes.add("root_readwrite");
    scopes.add("manage_groups");

    URL authURL = BoxAPIConnection.getAuthorizationURL("wncmz88sacf5oyaxf502dybcruqbzzy0",
            new URI("http://localhost:3000"), "test", scopes);

    Assert.assertTrue(authURL.toString().startsWith("https://account.box.com/api/oauth2/authorize"));

    StringTokenizer tokenizer = new StringTokenizer(authURL.getQuery(), "&");
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        if (token.startsWith("client_id")) {
            Assert.assertEquals(token, "client_id=wncmz88sacf5oyaxf502dybcruqbzzy0");
        } else if (token.startsWith("response_type")) {
            Assert.assertEquals(token, "response_type=code");
        } else if (token.startsWith("redirect_uri")) {
            Assert.assertEquals(token, "redirect_uri=http%3A%2F%2Flocalhost%3A3000");
        } else if (token.startsWith("state")) {
            Assert.assertEquals(token, "state=test");
        } else if (token.startsWith("scope")) {
            Assert.assertEquals(token, "scope=root_readwrite+manage_groups");
        }
    }
}
 
Example 11
public void output(Page page) {
    try {
        URL _URL = new URL(page.url());
        String query = "";
        if (_URL.getQuery() != null) {
            query = "_" + _URL.getQuery();
        }
        String path = _URL.getPath();
        if (path.length() == 0) {
            path = "index.html";
        } else {
            if (path.endsWith("/")) {
                path = path + "index.html";
            } else {
                int lastSlash = path.lastIndexOf("/");
                int lastPoint = path.lastIndexOf(".");
                if (lastPoint < lastSlash) {
                    path = path + ".html";
                }
            }
        }
        path += query;
        File domain_path = new File(root, _URL.getHost());
        File f = new File(domain_path, path);
        FileUtils.write(f, page.content());
        LOG.info("output " + f.getAbsolutePath());
    } catch (Exception ex) {
        LOG.info("Exception", ex);
    }
}
 
Example 12
public static String getAbsoluteUrl(String urlString, String baseUrlString) throws URISyntaxException,
        MalformedURLException {
    if (urlString.startsWith("http")) {
        return urlString;
    } else {
        URL url = new URL(baseUrlString);
        URI baseUri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                url.getPath(), url.getQuery(), url.getRef());
        return baseUri.resolve(urlString).toString();
    }
}
 
Example 13
protected PemJwksURLConnection(URL url) {
    super(url);
    this.path = url.getPath();
    // Look for kid=xxx
    String query = url.getQuery();
    if(query != null) {
        String[] parts = query.split("=");
        kid = parts[1];
    }
    else {
        // Some random kid
        kid = Long.toHexString(Double.doubleToLongBits(Math.random()));
    }
}
 
Example 14
Source Project: shipkit   File: GitHubListFetcher.java    License: MIT License 5 votes vote down vote up
private String queryParamValue(URL url, String page) {
    String query = url.getQuery();
    for (String param : query.split("&")) {
        if (param.startsWith(page)) {
            return param.substring(param.indexOf('=') + 1, param.length());
        }
    }
    return "N/A";
}
 
Example 15
Source Project: jsflight   File: JMeterProxy.java    License: Apache License 2.0 5 votes vote down vote up
private String getUrlWithoutQuery(URL url)
{
    String fullUrl = url.toString();
    String urlWithoutQuery = fullUrl;
    String query = url.getQuery();
    if (query != null)
    {
        // Get rid of the query and the ?
        urlWithoutQuery = urlWithoutQuery.substring(0, urlWithoutQuery.length() - query.length() - 1);
    }
    return urlWithoutQuery;
}
 
Example 16
Source Project: pacbot   File: LDAPManager.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * This method used to get the Kernel Version of an instance.
 * 
 * @param instanceId
 * @return String, if kernel version available else null
 */

public static String getQueryfromLdapElasticSearch(String instanceId,
        String ldapApi) {
    JsonParser jsonParser = new JsonParser();
    JsonArray jsonArray = new JsonArray();

    try {
        HttpClient client = HttpClientBuilder.create().build();

        URL url = new URL(ldapApi);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(),
                url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());

        // prepare Json pay load for GET query.
        JsonObject innerJson = new JsonObject();
        JsonObject matchPhrase = new JsonObject();
        JsonObject must = new JsonObject();
        JsonObject bool = new JsonObject();
        JsonObject query = new JsonObject();

        innerJson.addProperty("instanceid", instanceId);
        matchPhrase.add("match_phrase", innerJson);
        must.add("must", matchPhrase);
        bool.add("bool", must);
        query.add("query", bool);
        StringEntity strjson = new StringEntity(query.toString());

        // Qurying the ES
        HttpPost httpPost = new HttpPost();
        httpPost.setURI(uri);
        httpPost.setEntity(strjson);
        httpPost.setHeader("Content-Type", "application/json");
        HttpResponse response = client.execute(httpPost);

        String jsonString = EntityUtils.toString(response.getEntity());
        JsonObject resultJson = (JsonObject) jsonParser.parse(jsonString);
        String hitsJsonString = resultJson.get("hits").toString();
        JsonObject hitsJson = (JsonObject) jsonParser.parse(hitsJsonString);
        jsonArray = hitsJson.getAsJsonObject().get("hits").getAsJsonArray();
        if (jsonArray.size() > 0) {
            JsonObject firstObject = (JsonObject) jsonArray.get(0);
            JsonObject sourceJson = (JsonObject) firstObject.get("_source");
            if (sourceJson != null) {
                JsonElement osVersion = sourceJson.get("os_version");
                if (osVersion != null) {
                    return getKernelVersion(osVersion);
                }
            }
        } else {
            logger.info("no records found in ElasticSearch");
        }
    } catch (MalformedURLException me) {
        logger.error(me.getMessage());
    } catch (UnsupportedEncodingException ue) {
        logger.error(ue.getMessage());
    } catch (ClientProtocolException ce) {
        logger.error(ce.getMessage());
    } catch (IOException ioe) {
        logger.error(ioe.getMessage());
    } catch (URISyntaxException use) {
        logger.error(use.getMessage());
    }

    return null;
}
 
Example 17
Source Project: BeanStack   File: BurpExtender.java    License: Apache License 2.0 4 votes vote down vote up
private String url2uri(URL url) {
	return (url.getPath() != null ? url.getPath() : "")
		+ (url.getQuery() != null ? url.getQuery() : "");
}
 
Example 18
Source Project: pacbot   File: PacmanUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static Map<String, String> getSeviceLimit(String id, String accountId, String esUrl) {
    JsonParser jsonParser = new JsonParser();
    JsonArray jsonArray = new JsonArray();
    Map<String, String> data = new HashMap<>();
    try {
        HttpClient client = HttpClientBuilder.create().build();

        URL url = new URL(esUrl);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());

        // prepare Json pay load for GET query.
        JsonObject innerJson = new JsonObject();
        JsonObject innerJson1 = new JsonObject();
        JsonObject matchPhrase = new JsonObject();
        JsonObject matchPhrase1 = new JsonObject();
        JsonObject mustObj = new JsonObject();
        JsonArray mustArray = new JsonArray();
        JsonObject bool = new JsonObject();
        JsonObject query = new JsonObject();

        innerJson.addProperty(PacmanRuleConstants.CHECK_ID_KEYWORD, id);
        innerJson1.addProperty(PacmanRuleConstants.ACCOUNTID, accountId);
        matchPhrase.add("match", innerJson);
        matchPhrase1.add("match", innerJson1);
        mustArray.add(matchPhrase);
        mustArray.add(matchPhrase1);
        mustObj.add("must", mustArray);
        bool.add("bool", mustObj);
        query.add(PacmanRuleConstants.QUERY, bool);
        StringEntity strjson = new StringEntity(query.toString());

        // Qurying the ES
        HttpPost httpPost = new HttpPost();
        httpPost.setURI(uri);
        httpPost.setEntity(strjson);
        httpPost.setHeader(PacmanRuleConstants.CONTENT_TYPE, PacmanRuleConstants.APPLICATION_JSON);
        HttpResponse response = client.execute(httpPost);

        String jsonString = EntityUtils.toString(response.getEntity());
        JsonObject resultJson = (JsonObject) jsonParser.parse(jsonString);
        String hitsJsonString = resultJson.get(PacmanRuleConstants.HITS).toString();
        JsonObject hitsJson = (JsonObject) jsonParser.parse(hitsJsonString);
        jsonArray = hitsJson.getAsJsonObject().get(PacmanRuleConstants.HITS).getAsJsonArray();
        if (jsonArray.size() > 0) {

            for (int i = 0; i < jsonArray.size(); i++) {
                JsonObject firstObject = (JsonObject) jsonArray.get(i);
                JsonObject sourceJson = (JsonObject) firstObject.get(PacmanRuleConstants.SOURCE);
                if (sourceJson != null) {
                    String resourceinfo = sourceJson.get(PacmanRuleConstants.RESOURCE_INFO).getAsString();
                    JsonObject resourceinfoJson = (JsonObject) jsonParser.parse(resourceinfo);
                    String service = resourceinfoJson.get("Service").getAsString();
                    String status = resourceinfoJson.get(PacmanRuleConstants.STATUS_CAP).getAsString();
                    String cUsage = resourceinfoJson.get("Current Usage").getAsString();
                    String lAmount = resourceinfoJson.get("Limit Amount").getAsString();

                    if (cUsage != null && lAmount != null && !"null".equalsIgnoreCase(cUsage)
                            && !"null".equalsIgnoreCase(lAmount)) {
                        Double percentage = (Double.parseDouble(cUsage) / Double.parseDouble(lAmount)) * 100;
                        if (percentage >= 80 && status.equalsIgnoreCase(PacmanRuleConstants.STATUS_RED)) {
                            data.put(service, percentage.toString());
                            data.put("status_" + status, "RED");
                        } else if (percentage >= 80 && status.equalsIgnoreCase(PacmanRuleConstants.STATUS_YELLOW)) {
                            data.put(service, percentage.toString());
                        }
                    }
                }
            }
        }
    } catch (Exception me) {
        logger.error(me.getMessage());
    }

    return data;
}
 
Example 19
private void
checkSubscriptionForStuff(
	Subscription	sub )
{
	if ( sub.isSearchTemplate()){

		return;
	}

	if ( sub.isSubscribed() && sub.getAddType() != Subscription.ADD_TYPE_IMPORT ){

		return;
	}

	try{
		Engine engine = sub.getEngine();

		if ( engine instanceof RSSEngine ){

			RSSEngine re = (RSSEngine)engine;

			String url_str = re.getSearchUrl( true );

			URL url = new URL( url_str );

			String prot = url.getProtocol();

			if ( prot.equals( "azplug" )){

				String q = url.getQuery();

				Map<String,String>	args = UrlUtils.decodeArgs( q );

				String id = args.get( "id" );

				if ( id.equals( "azbuddy" )){

					String arg = args.get( "arg" );

					String[] bits = arg.split( ":", 2 );

					String chat_protocol = bits[0];

					if ( chat_protocol.startsWith( "chat" )){

						Map<String,String> chat_args = UrlUtils.decodeArgs( bits[1]);

						String	chat_key = chat_args.get( "" );

						int pos = chat_key.toLowerCase( Locale.US ).indexOf( "website[pk=" );

						if ( pos != -1 ){

							Map<String,String>	cb_data = new HashMap<>();

							cb_data.put( "subname", sub.getName());

							cb_data.put( "subid", sub.getID());

							LocalActivityManager.addLocalActivity(
								"Website:" + sub.getID(),
								"rss",
								MessageText.getString(
									"subs.activity.website.found",
									new String[]{ sub.getName() }),
								new String[]{ MessageText.getString( "subscriptions.listwindow.subscribe" )},
								ActivityCallback.class,
								cb_data );
						}
					}
				}
			}
		}
	}catch( Throwable e ){
		// ignore, nothing to see!
	}
}
 
Example 20
public static URL
adjustURLForHosting(
	URL		url_in )
{
	if ( isHosting( url_in )){

		String	url = url_in.getProtocol() + "://";

		if ( bind_ip.length() < 7 ){

				// TODO: this won't work in a pure IPv6 setup

			url += "127.0.0.1";

		}else{

			if ( bind_ip.contains( ":" )){

				url += "[" + bind_ip + "]";

			}else{
			      url += bind_ip;
			}
		}

		int	port = url_in.getPort();

		if ( port != -1 ){

			url += ":" + url_in.getPort();
		}

		url += url_in.getPath();

		String query = url_in.getQuery();

		if ( query != null ){

			url += "?" + query;
		}

		try{
			return( new URL( url ));

		}catch( MalformedURLException e ){

			Debug.printStackTrace( e );
		}
	}

	return( url_in );
}