Java Code Examples for org.apache.http.client.utils.URLEncodedUtils.parse()

The following are Jave code examples for showing how to use parse() of the org.apache.http.client.utils.URLEncodedUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: text_converter   File: APKExpansionPolicy.java   View Source Code Vote up 8 votes
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;
}
 
Example 2
Project: Selenium-Foundation   File: ComponentContainer.java   View Source Code Vote up 6 votes
/**
 * 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;
}
 
Example 3
Project: hadoop-oss   File: ServletUtils.java   View Source Code Vote up 6 votes
/**
 * 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;
}
 
Example 4
Project: hadoop-oss   File: DelegationTokenAuthenticationFilter.java   View Source Code Vote up 6 votes
@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;
}
 
Example 5
Project: beaker-notebook-archive   File: ConnectionStringHolder.java   View Source Code Vote up 6 votes
/**
 * 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;
}
 
Example 6
Project: boohee_v5.6   File: AuthorizeHelper.java   View Source Code Vote up 6 votes
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);
}
 
Example 7
Project: openaudible   File: AudibleScraper.java   View Source Code Vote up 6 votes
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;
}
 
Example 8
Project: Cognizant-Intelligent-Test-Scripter   File: Entry.java   View Source Code Vote up 6 votes
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;
}
 
Example 9
Project: hadoop   File: DelegationTokenAuthenticationFilter.java   View Source Code Vote up 6 votes
@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;
}
 
Example 10
Project: hadoop   File: PseudoAuthenticationHandler.java   View Source Code Vote up 6 votes
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;
}
 
Example 11
Project: sparkler   File: DatabaseUrl.java   View Source Code Vote up 6 votes
public static Map<String, String> params(String jdbcUrl) {
  Map<String, String> results = new HashMap<>();

  if (Validations.empty(jdbcUrl)) return results;
  if (!jdbcUrl.matches("jdbc:.*")) return results;

  String url = jdbcUrl.substring(5);

  URI dbUri;
  try {
    dbUri = new URI(url);
  } catch (URISyntaxException ex) {
    logger.warn("Invalid database url: " + jdbcUrl);
    return results;
  }

  results.put("database", dbUri.getPath());
  results.put("type", dbUri.getScheme());
  results.put("host", dbUri.getHost());
  results.put("port", String.valueOf(dbUri.getPort()));

  List<NameValuePair> queryParams = URLEncodedUtils.parse(dbUri, "UTF-8");
  queryParams.forEach(p -> results.put(p.getName(), p.getValue()));

  return results;
}
 
Example 12
Project: rainbow-rest   File: RainbowRestOncePerRequestFilter.java   View Source Code Vote up 6 votes
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();
}
 
Example 13
Project: java-platform   File: QQOauthPlugin.java   View Source Code Vote up 6 votes
@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");
}
 
Example 14
Project: MiBandDecompiled   File: AuthorizeHelper.java   View Source Code Vote up 6 votes
protected static String getMacAccessTokenSignatureString(String s, String s1, String s2, String s3, String s4, String s5, String s6)
{
    if ("HmacSHA1".equalsIgnoreCase(s6))
    {
        StringBuilder stringbuilder = new StringBuilder("");
        stringbuilder.append((new StringBuilder(String.valueOf(s))).append("\n").toString());
        stringbuilder.append((new StringBuilder(String.valueOf(s1.toUpperCase()))).append("\n").toString());
        stringbuilder.append((new StringBuilder(String.valueOf(s2))).append("\n").toString());
        stringbuilder.append((new StringBuilder(String.valueOf(s3))).append("\n").toString());
        if (!TextUtils.isEmpty(s4))
        {
            StringBuffer stringbuffer = new StringBuffer();
            ArrayList arraylist = new ArrayList();
            URLEncodedUtils.parse(arraylist, new Scanner(s4), "UTF-8");
            Collections.sort(arraylist, new b());
            stringbuffer.append(URLEncodedUtils.format(arraylist, "UTF-8"));
            stringbuilder.append((new StringBuilder(String.valueOf(stringbuffer.toString()))).append("\n").toString());
        }
        return encodeSign(encryptHMACSha1(stringbuilder.toString().getBytes("UTF-8"), s5.getBytes("UTF-8")));
    } else
    {
        throw new NoSuchAlgorithmException((new StringBuilder("error mac algorithm : ")).append(s6).toString());
    }
}
 
Example 15
Project: patreon-java   File: PatreonAPI.java   View Source Code Vote up 6 votes
public String getNextCursorFromDocument(JSONAPIDocument document) {
    Links links = document.getLinks();
    if (links == null) {
        return null;
    }
    Link nextLink = links.getNext();
    if (nextLink == null) {
        return null;
    }
    String nextLinkString = nextLink.toString();
    try {
        List<NameValuePair> queryParameters = URLEncodedUtils.parse(new URI(nextLinkString), "utf8");
        for (NameValuePair pair : queryParameters) {
            String name = pair.getName();
            if (name.equals("page[cursor]")) {
                String cursorValue = pair.getValue();
                return cursorValue;
            }
        }
    } catch (URISyntaxException e) {
        LOG.error(e.getMessage());
    }
    return null;
}
 
Example 16
Project: Alite   File: APKExpansionPolicy.java   View Source Code Vote up 6 votes
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;
}
 
Example 17
Project: magloft-android-app   File: APKExpansionPolicy.java   View Source Code Vote up 6 votes
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;
}
 
Example 18
Project: incubator-servicecomb-java-chassis   File: URIEndpointObject.java   View Source Code Vote up 5 votes
public static Map<String, List<String>> splitQuery(URI uri) {
  final Map<String, List<String>> queryPairs = new LinkedHashMap<>();
  List<NameValuePair> pairs = URLEncodedUtils.parse(uri, StandardCharsets.UTF_8.name());
  for (NameValuePair pair : pairs) {
    List<String> list = queryPairs.computeIfAbsent(pair.getName(), name -> {
      return new ArrayList<>();
    });
    list.add(pair.getValue());
  }
  return queryPairs;
}
 
Example 19
Project: SlotNSlot_Android   File: ServerManagedPolicy.java   View Source Code Vote up 5 votes
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) {
            results.put(item.getName(), item.getValue());
        }
    } catch (URISyntaxException e) {
      Log.w(TAG, "Invalid syntax error while decoding extras data from server.");
    }
    return results;
}
 
Example 20
Project: e-identification-tupas-idp-public   File: ShibbolethExtAuthnHandler.java   View Source Code Vote up 5 votes
private void verifyTupasIdentification(HttpServletRequest request, HttpServletResponse response) throws ExternalAuthenticationException, IOException {
    // Identification. Requests have encoding ISO-8859-1
    String queryString = request.getQueryString();
    queryString.replaceAll("%20", "+");
    List<NameValuePair> queryParams = URLEncodedUtils.parse(queryString, Charset.forName("ISO-8859-1"));
    MultivaluedMap<String, String> requestParams = convertToMap(queryParams);
    String sessionId = request.getSession().getId();
    requestParams.putSingle("sessionId", sessionId);

    String token = requestParams.getFirst("token");
    if (StringUtils.isBlank(token)) {
        throw new ExternalAuthenticationException("Bad request, no token");
    }

    TupasIdentification identification = authenticationHandlerService.buildSession(requestParams);
    if ( identification == null ) {
        throw new ExternalAuthenticationException("Authentication verification failed");
    }

    AuthenticationContext ac = ExternalAuthentication.getProfileRequestContext(identification.getCkey(), request).getSubcontext(AuthenticationContext.class);
    if ( ac == null ) {
        logger.warn("Authentication context not valid");
        request.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY, "Bad authentication");
        ExternalAuthentication.finishExternalAuthentication(identification.getCkey(), request, response);
        return;
    }

    TupasContext tupasContext = new TupasContext(identification.getName(), identification.getHetu());
    ac.addSubcontext(tupasContext);

    request.setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, token);
    /** External authentication success. Give control back to Shibboleth IdP (4.) */
    ExternalAuthentication.finishExternalAuthentication(identification.getCkey(), request, response);
    return;
}
 
Example 21
Project: HttpClientMock   File: UrlParams.java   View Source Code Vote up 5 votes
public static List<NameValuePair> parse(String query, Charset charset) {
    if (query == null) {
        return new ArrayList<>();
    } else {
        return URLEncodedUtils.parse(query, charset);
    }
}
 
Example 22
Project: aws-sdk-java-v2   File: QueryParamsAssertion.java   View Source Code Vote up 5 votes
private List<NameValuePair> parseNameValuePairsFromQuery(LoggedRequest actual) {
    final String queryParams = URI.create(actual.getUrl()).getQuery();
    if (StringUtils.isNullOrEmpty(queryParams)) {
        return Collections.emptyList();
    }
    return URLEncodedUtils.parse(queryParams, StandardCharsets.UTF_8);
}
 
Example 23
Project: pac4j-plus   File: RedirectSAML2ClientTests.java   View Source Code Vote up 5 votes
private String getInflatedAuthnRequest(final String location) throws Exception {
    final List<NameValuePair> pairs = URLEncodedUtils.parse(java.net.URI.create(location), "UTF-8");
    final Inflater inflater = new Inflater(true);
    final byte[] decodedRequest = Base64.getDecoder().decode(pairs.get(0).getValue());
    final ByteArrayInputStream is = new ByteArrayInputStream(decodedRequest);
    final InflaterInputStream inputStream = new InflaterInputStream(is, inflater);
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, HttpConstants.UTF8_ENCODING));
    String line;
    final StringBuilder bldr = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        bldr.append(line);
    }
    return bldr.toString();
}
 
Example 24
Project: stallion-core   File: StRequest.java   View Source Code Vote up 5 votes
@Override
public Map<String, Object> getBodyMap() {
    if (bodyMap == null) {
        if (or(getHeader("Content-type"), "").startsWith("application/x-www-form-urlencoded")) {
            bodyMap = new HashMap<>();

            for (NameValuePair pair: URLEncodedUtils.parse(getContent(), Charset.forName(or(request.getCharacterEncoding(), "UTF8")))) {
                if (bodyMap.containsKey(pair.getName())) {
                    Object existing = bodyMap.get(pair.getName());
                    if (existing instanceof List) {
                        ((List)existing).add(pair.getValue());
                    } else {
                        bodyMap.put(pair.getName(), list(existing, pair.getValue()));
                    }
                } else {
                    bodyMap.put(pair.getName(), pair.getValue());
                }
            }
        } else {
            ObjectMapper mapper = new ObjectMapper();
            String content = getContent();
            if (StringUtils.isEmpty(content)) {
                bodyMap = new HashMap<>();
            } else {
                try {
                    bodyMap = mapper.readValue(getContent(),
                                new TypeReference<HashMap<String, Object>>() {
                                });
                } catch (IOException e) {
                    Log.exception(e, "Could not parse JSON body for the request: " + content);
                    throw new ClientException("Could not parse JSON body for the request.");
                }

            }
        }
    }
    return bodyMap;
}
 
Example 25
Project: aliyun-oss-hadoop-fs   File: ServletUtils.java   View Source Code Vote up 5 votes
/**
 * 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;
}
 
Example 26
Project: aliyun-oss-hadoop-fs   File: DelegationTokenAuthenticationFilter.java   View Source Code Vote up 5 votes
@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;
}
 
Example 27
Project: aliyun-oss-hadoop-fs   File: PseudoAuthenticationHandler.java   View Source Code Vote up 5 votes
private String getUserName(HttpServletRequest request) {
  String queryString = request.getQueryString();
  if(queryString == null || queryString.length() == 0) {
    return null;
  }
  List<NameValuePair> list = URLEncodedUtils.parse(queryString, UTF8_CHARSET);
  if (list != null) {
    for (NameValuePair nv : list) {
      if (PseudoAuthenticator.USER_NAME.equals(nv.getName())) {
        return nv.getValue();
      }
    }
  }
  return null;
}
 
Example 28
Project: java-platform   File: GithubOauthPlugin.java   View Source Code Vote up 5 votes
@Override
public String getAccessToken(String code) {
	Assert.hasText(code);
	Map<String, Object> parameterMap = new HashMap<>();
	parameterMap.put("client_id", getClientId());
	parameterMap.put("client_secret", getClientSecret());
	parameterMap.put("code", code);
	String accessTokenResponse = post("https://github.com/login/oauth/access_token", parameterMap);
	List<NameValuePair> nameValuePairs = URLEncodedUtils.parse(accessTokenResponse, 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");
}
 
Example 29
Project: jdbc-cb   File: CBConnection.java   View Source Code Vote up 5 votes
public CBConnection(String url, Properties props) throws SQLException
{
    try
    {
        String connectionURL;

        if (props.containsKey(ConnectionParameters.ENABLE_SSL) && props.getProperty(ConnectionParameters.ENABLE_SSL).equals("true"))
        {
            logger.trace("Enabling SSL connection");
            connectionURL = HTTPS + url.substring(14) ;

        }
        else
        {
            logger.trace("Normal http connection");
            connectionURL = HTTP + url.substring(14);
        }

        List <NameValuePair> parameters = URLEncodedUtils.parse(new URI(connectionURL),"UTF-8");

        for(NameValuePair param:parameters)
        {
            props.put(param.getName(),param.getValue());
        }
        protocol = new ProtocolImpl(connectionURL, props);
        protocol.connect();
        connected.set(true);
    }
    catch (Exception ex)
    {
        logger.error("Error opening connection for {} exception {}", url, ex.getMessage());
        throw new SQLException("Error opening connection", ex.getCause());
    }
}
 
Example 30
Project: dr-elephant   File: AzkabanWorkflowClient.java   View Source Code Vote up 5 votes
/**
 * Sets the workflow execution id given the azkaban workflow url
 * @param azkabanWorkflowUrl The url of the azkaban workflow
 * @throws MalformedURLException
 * @throws URISyntaxException
 */
private void setExecutionId(String azkabanWorkflowUrl)
    throws MalformedURLException, URISyntaxException {
  List<NameValuePair> params = URLEncodedUtils.parse(new URI(azkabanWorkflowUrl), "UTF-8");
  for (NameValuePair param : params) {
    if (param.getName() == "execid") {
      this._executionId = param.getValue();
    }
  }
}
 
Example 31
Project: emodb   File: LocationUtil.java   View Source Code Vote up 5 votes
public static Optional<String> getZkConnectionStringOverride(URI location) {
    List<NameValuePair> params = URLEncodedUtils.parse(location, Charsets.UTF_8.name());
    for (NameValuePair pair : params) {
        if (ZK_CONNECTION_STRING_PARAM.equals(pair.getName())) {
            // Deterministically sort the hosts
            String[] hosts = pair.getValue().split(",");
            Arrays.sort(hosts);
            String zkConnectionString = Joiner.on(",").join(hosts);
            return Optional.of(zkConnectionString);
        }
    }
    return Optional.absent();
}
 
Example 32
Project: aptoide-client   File: ReferrerUtils.java   View Source Code Vote up 5 votes
public static String getReferrer(String uri) {
    List<NameValuePair> params = URLEncodedUtils.parse(URI.create(uri), "UTF-8");

    String referrer = null;
    for (NameValuePair param : params) {

        if (param.getName().equals("referrer")) {
            referrer = param.getValue();
        }
    }
    return referrer;
}
 
Example 33
Project: ObbDownloadHelper   File: ServerManagedPolicy.java   View Source Code Vote up 5 votes
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) {
            results.put(item.getName(), item.getValue());
        }
    } catch (URISyntaxException e) {
      Log.w(TAG, "Invalid syntax error while decoding extras data from server.");
    }
    return results;
}
 
Example 34
Project: solr-cmd-utils   File: UrlUtil.java   View Source Code Vote up 5 votes
public static List<NameValuePair> getUrlParams(String url, String charset) {

        try {
            URL tempUrl = new URL(url);
            String query = tempUrl.getQuery();
            List<NameValuePair> urlParams = URLEncodedUtils.parse(query,
                    Charset.forName(charset));
            return urlParams;
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("The url " + url + " is not valid.");
        }
    }
 
Example 35
Project: oauth-token-java-client   File: ValidRequestExpectationCallback.java   View Source Code Vote up 5 votes
private boolean isValid(HttpRequest httpRequest) {
    String body = (String) httpRequest.getBody().getValue();
    List<NameValuePair> parsedParams = URLEncodedUtils.parse(body, Charset.forName(CharEncoding.UTF_8));
    HashMap<String, String> params = new HashMap<String, String>();
    for (NameValuePair p : parsedParams) params.put(p.getName(), p.getValue());
    return isValid(params);
}
 
Example 36
Project: big-c   File: DelegationTokenAuthenticationFilter.java   View Source Code Vote up 5 votes
@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;
}
 
Example 37
Project: ObbDownloadHelper   File: ServerManagedPolicy.java   View Source Code Vote up 5 votes
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) {
            results.put(item.getName(), item.getValue());
        }
    } catch (URISyntaxException e) {
      Log.w(TAG, "Invalid syntax error while decoding extras data from server.");
    }
    return results;
}
 
Example 38
Project: flowable-engine   File: FlowableModelQueryService.java   View Source Code Vote up 5 votes
public ResultListDataRepresentation getModels(String filter, String sort, Integer modelType, HttpServletRequest request) {

        // need to parse the filterText parameter ourselves, due to encoding issues with the default parsing.
        String filterText = null;
        List<NameValuePair> params = URLEncodedUtils.parse(request.getQueryString(), Charset.forName("UTF-8"));
        if (params != null) {
            for (NameValuePair nameValuePair : params) {
                if ("filterText".equalsIgnoreCase(nameValuePair.getName())) {
                    filterText = nameValuePair.getValue();
                }
            }
        }

        List<ModelRepresentation> resultList = new ArrayList<>();
        List<Model> models = null;

        String validFilter = makeValidFilterText(filterText);

        if (validFilter != null) {
            models = modelRepository.findByModelTypeAndFilter(modelType, validFilter, sort);

        } else {
            models = modelRepository.findByModelType(modelType, sort);
        }

        if (CollectionUtils.isNotEmpty(models)) {
            List<String> addedModelIds = new ArrayList<>();
            for (Model model : models) {
                if (!addedModelIds.contains(model.getId())) {
                    addedModelIds.add(model.getId());
                    ModelRepresentation representation = createModelRepresentation(model);
                    resultList.add(representation);
                }
            }
        }

        ResultListDataRepresentation result = new ResultListDataRepresentation(resultList);
        return result;
    }
 
Example 39
Project: FoDBugTrackerUtility   File: TFSRestConnection.java   View Source Code Vote up 5 votes
private String getIssueId(SubmittedIssue submittedIssue) {
	String id = submittedIssue.getId();
	if ( StringUtils.isBlank(id) ) {
		String deepLink = submittedIssue.getDeepLink();
		List<NameValuePair> params = URLEncodedUtils.parse(URI.create(deepLink), "UTF-8");

		for (NameValuePair param : params) {
		  if ( "id".equals(param.getName()) ) {
			  return param.getValue();
		  }
		}
	}
	return id;
}
 
Example 40
Project: apex-core   File: RecoverableRpcProxy.java   View Source Code Vote up 5 votes
private long connect(long timeMillis) throws IOException
{
  String uriStr = fsRecoveryHandler.readConnectUri();
  if (!uriStr.equals(lastConnectURI)) {
    LOG.debug("Got new RPC connect address {}", uriStr);
    lastConnectURI = uriStr;
    if (umbilical != null) {
      RPC.stopProxy(umbilical);
    }

    retryTimeoutMillis = Long.getLong(RETRY_TIMEOUT, RETRY_TIMEOUT_DEFAULT);
    retryDelayMillis = Long.getLong(RETRY_DELAY, RETRY_DELAY_DEFAULT);
    rpcTimeout = Integer.getInteger(RPC_TIMEOUT, RPC_TIMEOUT_DEFAULT);

    URI heartbeatUri = URI.create(uriStr);

    String queryStr = heartbeatUri.getQuery();
    if (queryStr != null) {
      List<NameValuePair> queryList = URLEncodedUtils.parse(queryStr, Charset.defaultCharset());
      if (queryList != null) {
        for (NameValuePair pair : queryList) {
          String value = pair.getValue();
          String key = pair.getName();
          if (QP_rpcTimeout.equals(key)) {
            this.rpcTimeout = Integer.parseInt(value);
          } else if (QP_retryTimeoutMillis.equals(key)) {
            this.retryTimeoutMillis = Long.parseLong(value);
          } else if (QP_retryDelayMillis.equals(key)) {
            this.retryDelayMillis = Long.parseLong(value);
          }
        }
      }
    }
    InetSocketAddress address = NetUtils.createSocketAddrForHost(heartbeatUri.getHost(), heartbeatUri.getPort());
    umbilical = RPC.getProxy(StreamingContainerUmbilicalProtocol.class, StreamingContainerUmbilicalProtocol.versionID, address, currentUser, conf, defaultSocketFactory, rpcTimeout);
    // reset timeout
    return System.currentTimeMillis() + retryTimeoutMillis;
  }
  return timeMillis;
}
 
Example 41
Project: hadoop-2.6.0-cdh5.4.3   File: ServletUtils.java   View Source Code Vote up 5 votes
/**
 * 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;
}
 
Example 42
Project: hadoop-2.6.0-cdh5.4.3   File: DelegationTokenAuthenticationFilter.java   View Source Code Vote up 5 votes
@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;
}
 
Example 43
Project: artifactory   File: TestMethodFactory.java   View Source Code Vote up 5 votes
private static HttpRequestBase createNuGetTestMethod(String repoUrl, String queryParams) {
    try {
        URIBuilder uriBuilder = new URIBuilder(repoUrl);
        HttpRequestBase request = new HttpGet();
        if(StringUtils.isNotBlank(queryParams)) {
            List<NameValuePair> queryParamsMap = URLEncodedUtils.parse(queryParams, Charsets.UTF_8);
            uriBuilder.setParameters(queryParamsMap);
        }
        request.setURI(uriBuilder.build());
        return request;
    } catch (URISyntaxException e) {
        throw new RuntimeException("Failed to build test URI", e);
    }
}
 
Example 44
Project: digdag   File: HttpIT.java   View Source Code Vote up 5 votes
@Test
public void testQuery()
        throws Exception
{
    String uri = "http://localhost:" + httpMockWebServer.getPort() + "/test";
    runWorkflow(folder, "acceptance/http/http_query.dig",
            ImmutableMap.of(
                    "test_uri", uri
            ),
            ImmutableMap.of(
                    "secrets.arg_value_1", "secret_arg_value_1",
                    "secrets.arg_name_2", "secret_arg_name_2",
                    "secrets.arg_value_2", "secret_arg_value_2"
            ));
    assertThat(httpMockWebServer.getRequestCount(), is(3));

    for (int i = 0; i < 3; i++) {
        RecordedRequest request = httpMockWebServer.takeRequest();
        String query = Splitter.on('?').splitToList(request.getPath()).get(1);
        List<NameValuePair> queryArgs = URLEncodedUtils.parse(query, UTF_8);
        assertThat(queryArgs.get(0).getName(), is("foo"));
        assertThat(queryArgs.get(0).getValue(), is("bar"));
        assertThat(queryArgs.get(1).getName(), is("plain_arg_name_1"));
        assertThat(queryArgs.get(1).getValue(), is("secret_arg_value_1"));
        assertThat(queryArgs.get(2).getName(), is("secret_arg_name_2"));
        assertThat(queryArgs.get(2).getValue(), is("secret_arg_value_2"));
        System.out.println(queryArgs);
    }
}
 
Example 45
Project: cft   File: SshClientSupport.java   View Source Code Vote up 5 votes
@Override
public String getSshCode() {
	try {
		URIBuilder builder = new URIBuilder(tokenUrl + "/oauth/authorize"); //$NON-NLS-1$

		builder.addParameter("response_type" //$NON-NLS-1$
				, "code"); //$NON-NLS-1$
		builder.addParameter("grant_type", //$NON-NLS-1$
				"authorization_code"); //$NON-NLS-1$
		builder.addParameter("client_id", sshClientId); //$NON-NLS-1$

		URI url = new URI(builder.toString());

		ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
		HttpStatus statusCode = response.getStatusCode();
		if (statusCode != HttpStatus.FOUND) {
			throw new CloudFoundryException(statusCode);
		}

		String loc = response.getHeaders().getFirst("Location"); //$NON-NLS-1$
		if (loc == null) {
			throw new CloudOperationException("No 'Location' header in redirect response"); //$NON-NLS-1$
		}
		List<NameValuePair> qparams = URLEncodedUtils.parse(new URI(loc), "utf8"); //$NON-NLS-1$
		for (NameValuePair pair : qparams) {
			String name = pair.getName();
			if (name.equals("code")) { //$NON-NLS-1$
				return pair.getValue();
			}
		}
		throw new CloudOperationException("No 'code' param in redirect Location: " + loc); //$NON-NLS-1$
	}
	catch (URISyntaxException e) {
		throw new CloudOperationException(e);
	}
}
 
Example 46
Project: java-hod-client   File: AuthenticationServiceImplTest.java   View Source Code Vote up 5 votes
private void checkCombinedUrl(final SignedRequest request, final List<NameValuePair> expectedParameters) throws URISyntaxException {
    final URI uri = new URI(request.getUrl());
    assertThat(uri.getScheme() + "://" + uri.getHost(), is(ENDPOINT));
    assertThat(uri.getPath(), is(COMBINED_PATH));

    final List<NameValuePair> pairs = URLEncodedUtils.parse(uri, "UTF-8");
    assertThat(pairs, containsInAnyOrder(expectedParameters.toArray()));
}
 
Example 47
Project: TiLicensing   File: ServerManagedPolicy.java   View Source Code Vote up 5 votes
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) {
            results.put(item.getName(), item.getValue());
        }
    } catch (URISyntaxException e) {
      Log.w(TAG, "Invalid syntax error while decoding extras data from server.");
    }
    return results;
}
 
Example 48
Project: hops   File: WebAppUtils.java   View Source Code Vote up 5 votes
private static String getURLEncodedQueryString(HttpServletRequest request) {
  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);
    return URLEncodedUtils.format(params, encoding);
  }
  return null;
}
 
Example 49
Project: zstack   File: MonUri.java   View Source Code Vote up 5 votes
public static String getQueryValue(URI uri, String name) {
    List<NameValuePair> params = URLEncodedUtils.parse(uri, "UTF-8");
    for (NameValuePair p : params) {
        if (!allowedQueryParameter.contains(p.getName())) {
            throw new CloudRuntimeException(String.format("unknown parameter[%s]", p.getName()));
        }

        if (p.getName().equals(name)) {
            return p.getValue();
        }
    }

    return null;
}
 
Example 50
Project: hops   File: PseudoAuthenticationHandler.java   View Source Code Vote up 5 votes
private String getUserName(HttpServletRequest request) {
  String queryString = request.getQueryString();
  if(queryString == null || queryString.length() == 0) {
    return null;
  }
  List<NameValuePair> list = URLEncodedUtils.parse(queryString, UTF8_CHARSET);
  if (list != null) {
    for (NameValuePair nv : list) {
      if (PseudoAuthenticator.USER_NAME.equals(nv.getName())) {
        return nv.getValue();
      }
    }
  }
  return null;
}
 
Example 51
Project: zstack   File: MonUri.java   View Source Code Vote up 5 votes
public static void checkQuery(URI uri) {
    List<NameValuePair> params = URLEncodedUtils.parse(uri, "UTF-8");
    for (NameValuePair p : params) {
        if (!allowedQueryParameter.contains(p.getName())) {
            throw new CloudRuntimeException(String.format("unknown parameter[%s]", p.getName()));
        }
    }
}
 
Example 52
Project: SPLGroundControl   File: RockBlockHttpHandler.java   View Source Code Vote up 4 votes
@Override
public void handle(HttpExchange t) throws IOException {
    try {
        InputStream is = t.getRequestBody();
        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer, "UTF-8");
        String theString = writer.toString();

        List<NameValuePair> params = URLEncodedUtils.parse(theString, Charset.forName("UTF-8"));

        IridiumMessage message = new IridiumMessage(params);

        logger.debug(message);

        if (message.data == null || message.data.isEmpty()) {
            logger.info(MessageFormat.format("Empty MO message received ''{0}''.", message.toString()));
        } else if (message.imei.equalsIgnoreCase(imei)) {
            MAVLinkPacket packet = message.getPacket();

            if (packet != null) {
                MAVLinkLogger.log(Level.INFO, "MO", packet);

                dst.sendMessage(packet);
            } else {
                logger.warn(MessageFormat.format("Invalid MAVLink message ''{0}''.", message.toString()));
            }
        } else {
            logger.warn(MessageFormat.format("Invalid IMEI ''{0}''.", message.imei));
        }

        //Send response
        String response = "";
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
    } catch (DecoderException e) {
        logger.error(e.getMessage());
        throw new IOException(e.getMessage());
    }
}
 
Example 53
Project: marathonv5   File: JavaProfile.java   View Source Code Vote up 4 votes
private void parse(URL url) throws URISyntaxException {
    List<NameValuePair> values = URLEncodedUtils.parse(url.toURI(), StandardCharsets.UTF_8);
    String launchModeStr = findValueOf(values, "launchmode");
    launchMode = LaunchMode.valueOf(launchModeStr);
    for (int i = 1;; i++) {
        if (hasValueFor(values, "arg" + i)) {
            appArguments.add(findValueOf(values, "arg" + i));
        } else {
            break;
        }
    }
    if (hasValueFor(values, "command")) {
        command = findValueOf(values, "command");
    }
    if (hasValueFor(values, "executablejar")) {
        executableJar = findValueOf(values, "executablejar");
    }
    if (hasValueFor(values, "swt")) {
        startWindowTitle = findValueOf(values, "swt");
    }
    if (hasValueFor(values, "javahome")) {
        javaHome = findValueOf(values, "javahome");
    }
    if (hasValueFor(values, "vmcommand")) {
        vmCommand = findValueOf(values, "vmcommand");
    }
    for (int i = 1;; i++) {
        if (hasValueFor(values, "vmarg" + i)) {
            vmArguments.add(findValueOf(values, "vmarg" + i));
        } else {
            break;
        }
    }
    for (int i = 1;; i++) {
        if (hasValueFor(values, "cp" + i)) {
            classPathEntries.add(new File(findValueOf(values, "cp" + i)));
        } else {
            break;
        }
    }
    if (hasValueFor(values, "mainclass")) {
        mainClass = findValueOf(values, "mainclass");
    }
    for (int i = 1;; i++) {
        if (hasValueFor(values, "wsarg" + i)) {
            wsArguments.add(findValueOf(values, "wsarg" + i));
        } else {
            break;
        }
    }
    if (hasValueFor(values, "jnlp")) {
        jnlpPath = findValueOf(values, "jnlp");
    }
    jnlpNoLocalCopy = false;
    if (hasValueFor(values, "jnlpNoLocalCopy")) {
        jnlpNoLocalCopy = Boolean.parseBoolean(findValueOf(values, "jnlpNoLocalCopy"));
    }
    if (hasValueFor(values, "appleturl")) {
        appletURL = findValueOf(values, "appleturl");
    }
    if (hasValueFor(values, "nativeevents")) {
        nativeEvents = true;
    }
    if (hasValueFor(values, "launchtype")) {
        launchType = LaunchType.valueOf(findValueOf(values, "launchtype"));
    }
    if (hasValueFor(values, "keepLog")) {
        keepLog = Boolean.parseBoolean(findValueOf(values, "keepLog"));
    }
}
 
Example 54
Project: careconnect-reference-implementation   File: ServerInterceptor.java   View Source Code Vote up 4 votes
@Override
public boolean incomingRequestPreProcessed(HttpServletRequest request, HttpServletResponse theResponse) {

    if (request.getMethod() != null) {

        /* KGM 3/1/2018 This is now handled by CORS headers

       if (theRequest.getMethod().equals("OPTIONS"))
            throw new MethodNotAllowedException("request must use HTTP GET");
        */

        if (request.getContentType() != null) {
           checkContentType(request.getContentType());
        }

        if (request.getQueryString() != null) {


            List<NameValuePair> params = null;
            try {
                params = URLEncodedUtils.parse(new URI("http://dummy?" + request.getQueryString()), "UTF-8");
            } catch (Exception ex) {
            }

            ListIterator paramlist = params.listIterator();
            while (paramlist.hasNext()) {
                NameValuePair param = (NameValuePair) paramlist.next();
                if (param.getName().equals("_format"))
                    checkContentType(param.getValue());

            }
        }


        // May need to re-add this at a later date (probably in conjunction with a security uplift)
        /*
        KGM 3/1/2018 disabled for crucible testing

        if (request.getMethod().equals("POST") && request.getPathInfo() != null && request.getPathInfo().contains("_search"))
            throw new MethodNotAllowedException("request must use HTTP GET");
            */
    }
    return true;
}
 
Example 55
Project: careconnect-reference-implementation   File: GatewayCamelProcessor.java   View Source Code Vote up 4 votes
@Override
public void process(Exchange exchange) throws Exception {



    if (exchange.getIn().getBody() instanceof HttpServletRequest) {
        // This is a result of a passthrough operation in the resource provider.

        HttpServletRequest httpRequest = (HttpServletRequest) exchange.getIn().getBody();

        exchange.getIn().removeHeaders("*" );

        exchange.getIn().setBody(httpRequest.getInputStream());

        exchange.getIn().setHeader(Exchange.HTTP_METHOD, httpRequest.getMethod());

        if (httpRequest.getQueryString() != null) {

            //log.info("QueryString = "+httpRequest.getQueryString());
            List<NameValuePair> params = URLEncodedUtils.parse(new URI("http://dummy?" + httpRequest.getQueryString()), "UTF-8");

            ListIterator paramlist = params.listIterator();
            while (paramlist.hasNext()) {
                // Remove format. This causes errors in the server (internally we work in JSON only)
                // KGM 3/1/2018
                NameValuePair param = (NameValuePair) paramlist.next();
                // log.info("QS Name ="+param.getName()+" Value="+param.getValue());
                if (param.getName().equals("_format")) paramlist.remove();

            }
            String queryString = URLEncodedUtils.format(params, "UTF-8");
            //log.info("New QS="+queryString);

            exchange.getIn().setHeader(Exchange.HTTP_QUERY, queryString);
        } else {
            exchange.getIn().setHeader(Exchange.HTTP_QUERY, null);
        }


        exchange.getIn().setHeader(Exchange.HTTP_PATH, httpRequest.getPathInfo());

        if (httpRequest.getRemoteAddr() !=null && !httpRequest.getRemoteAddr().isEmpty()) {
            exchange.getIn().setHeader("X-Forwarded-For", httpRequest.getRemoteAddr());
        }
        if (httpRequest.getRemoteHost() !=null && !httpRequest.getRemoteHost().isEmpty()) {
            exchange.getIn().setHeader("X-Forwarded-Host", httpRequest.getRemoteHost());
        }
    }

    exchange.getIn().setHeader(Exchange.ACCEPT_CONTENT_TYPE, "application/json");

    if (exchange.getIn().getHeader("X-Request-ID") == null || exchange.getIn().getHeader("X-Request-ID").toString().isEmpty()) {
        exchange.getIn().setHeader("X-Request-ID",exchange.getExchangeId());
    }

}
 
Example 56
Project: AppHub   File: WifiQrView.java   View Source Code Vote up 4 votes
private void setUIFromWifi() {

        if (TextUtils.isEmpty(FDroidApp.repo.address))
            return;

        String scheme = Preferences.get().isLocalRepoHttpsEnabled() ? "https://" : "http://";

        // the fingerprint is not useful on the button label
        String buttonLabel = scheme + FDroidApp.ipAddressString + ":" + FDroidApp.port;
        TextView ipAddressView = (TextView) findViewById(R.id.device_ip_address);
        ipAddressView.setText(buttonLabel);

        /*
         * Set URL to UPPER for compact QR Code, FDroid will translate it back.
         * Remove the SSID from the query string since SSIDs are case-sensitive.
         * Instead the receiver will have to rely on the BSSID to find the right
         * wifi AP to join. Lots of QR Scanners are buggy and do not respect
         * custom URI schemes, so we have to use http:// or https:// :-(
         */
        Uri sharingUri = Utils.getSharingUri(FDroidApp.repo);
        String qrUriString = (scheme + sharingUri.getHost()).toUpperCase(Locale.ENGLISH);
        if (sharingUri.getPort() != 80) {
            qrUriString += ":" + sharingUri.getPort();
        }
        qrUriString += sharingUri.getPath().toUpperCase(Locale.ENGLISH);
        boolean first = true;

        // Andorid provides an API for getting the query parameters and iterating over them:
        //   Uri.getQueryParameterNames()
        // But it is only available on later Android versions. As such we use URLEncodedUtils instead.
        List<NameValuePair> parameters = URLEncodedUtils.parse(URI.create(sharingUri.toString()), "UTF-8");
        for (NameValuePair parameter : parameters) {
            if (!"ssid".equals(parameter.getName())) {
                if (first) {
                    qrUriString += "?";
                    first = false;
                } else {
                    qrUriString += "&";
                }
                qrUriString += parameter.getName().toUpperCase(Locale.ENGLISH) + "=" +
                        parameter.getValue().toUpperCase(Locale.ENGLISH);
            }
        }

        Utils.debugLog(TAG, "Encoded swap URI in QR Code: " + qrUriString);

        new QrGenAsyncTask(getActivity(), R.id.wifi_qr_code).execute(qrUriString);

    }
 
Example 57
Project: switchyard   File: StandaloneEndpointPublisher.java   View Source Code Vote up 4 votes
/**
 * Method for get request information from a http exchange.
 *
 * @param request HttpExchange
 * @param type ContentType
 * @return Request information from a http exchange
 * @throws IOException when the request information could not be read
 */
public static HttpRequestInfo getRequestInfo(HttpExchange request, ContentType type) throws IOException {
    HttpRequestInfo requestInfo = new HttpRequestInfo();

    if (request.getHttpContext().getAuthenticator() instanceof BasicAuthenticator) {
        requestInfo.setAuthType(HttpServletRequest.BASIC_AUTH);
    }
    URI u = request.getRequestURI();
    URI requestURI = null;
    try {
        requestURI = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), u.getPath(), null, null);
    } catch (URISyntaxException e) {
        // Strange that this could happen when copying from another URI.
        LOGGER.debug(e);
    }
    requestInfo.setCharacterEncoding(type.getCharset());
    requestInfo.setContentType(type.toString());
    requestInfo.setContextPath(request.getHttpContext().getPath());
    requestInfo.setLocalAddr(request.getLocalAddress().getAddress().getHostAddress());
    requestInfo.setLocalName(request.getLocalAddress().getAddress().getHostName());
    requestInfo.setMethod(request.getRequestMethod());
    requestInfo.setProtocol(request.getProtocol());
    requestInfo.setQueryString(u.getQuery());
    requestInfo.setRemoteAddr(request.getRemoteAddress().getAddress().getHostAddress());
    requestInfo.setRemoteHost(request.getRemoteAddress().getAddress().getHostName());
    if (request.getHttpContext().getAuthenticator() instanceof BasicAuthenticator) {
        requestInfo.setRemoteUser(request.getPrincipal().getUsername());
    }
    requestInfo.setContentLength(request.getRequestBody().available());
    // requestInfo.setRequestSessionId(request.getRequestedSessionId());
    if (requestURI != null) {
        requestInfo.setRequestURI(requestURI.toString());
    }
    requestInfo.setScheme(u.getScheme());
    requestInfo.setServerName(u.getHost());
    requestInfo.setRequestPath(u.getPath());

    // Http Query params...
    if (requestInfo.getQueryString() != null) {
        Charset charset = null;
        if (type.getCharset() != null) {
            try {
                charset = Charset.forName(type.getCharset());
            } catch (Exception exception) {
                LOGGER.debug(exception);
            }
        }
        for (NameValuePair nameValuePair : URLEncodedUtils.parse(requestInfo.getQueryString(), charset)) {
            requestInfo.addQueryParam(nameValuePair.getName(), nameValuePair.getValue());
        }
    }

    // Credentials...
    requestInfo.getCredentials().addAll(new HttpExchangeCredentialExtractor().extract(request));

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(requestInfo);
    }

    return requestInfo;
}
 
Example 58
Project: oauth-java-sdk   File: CommonUtils.java   View Source Code Vote up 4 votes
/**
 * generate mac signature
 * format : nonce + \n + method(POST\GET) + \n + host + \n + uriPath + \n + qs + \n
 *
 * @param nonce random string
 * @param method POST or GET
 * @param uriPath request url path
 * @param qs query param
 * @param macAlgorithm signature algorithm, must be HmacSHA1
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 */
public static String getMacAccessTokenSignature(
        String nonce, String method, String host, String uriPath, String qs, String macKey, String macAlgorithm)
        throws InvalidKeyException, NoSuchAlgorithmException {

    log.debug("Get mac access token signature: nonce[{}], method[{}], host[{}], uriPath[{}], qs[{}], macKey[{}], macAlgorithm[{}].",
            nonce, method, host, uriPath, qs, macKey, macAlgorithm);

    List<String> elements = new ArrayList<String>();
    elements.add(nonce);
    elements.add(method.toUpperCase());
    elements.add(host);
    elements.add(uriPath);

    StringBuilder builder = new StringBuilder();
    if (StringUtils.isNotBlank(qs)) {
        // qs may be blank
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        URLEncodedUtils.parse(params, new Scanner(qs), GlobalConstants.DEFAULT_CHARSET);
        Collections.sort(params, new Comparator<NameValuePair>() {
            public int compare(NameValuePair p1, NameValuePair p2) {
                return p1.getName().compareTo(p2.getName());
            }
        });
        builder.append(URLEncodedUtils.format(params, GlobalConstants.DEFAULT_CHARSET));
    }
    elements.add(builder.toString());

    String sign = StringUtils.join(elements.toArray(), "\n");
    sign += "\n";  // don't forget this
    log.debug("The generate max sign is [{}]", sign);

    if (GlobalConstants.HMAC_SHA1.equalsIgnoreCase(macAlgorithm)) {
        try {
            return Base64.encode(
                    encryptHmacSha1(
                            sign.getBytes(GlobalConstants.DEFAULT_CHARSET), macKey.getBytes(GlobalConstants.DEFAULT_CHARSET)));
        } catch (UnsupportedEncodingException e) {
            // never happen
        }
    } else {
        throw new NoSuchAlgorithmException("Unsupported mac algorithm : " + macAlgorithm);
    }
    return StringUtils.EMPTY;
}
 
Example 59
Project: msf4j   File: ApacheHttpClient.java   View Source Code Vote up 4 votes
HttpUriRequest toHttpUriRequest(Request request, Request.Options options) throws
        UnsupportedEncodingException, MalformedURLException, URISyntaxException {
    RequestBuilder requestBuilder = RequestBuilder.create(request.method());

    //per request timeouts
    RequestConfig requestConfig = RequestConfig
            .custom()
            .setConnectTimeout(options.connectTimeoutMillis())
            .setSocketTimeout(options.readTimeoutMillis())
            .build();
    requestBuilder.setConfig(requestConfig);

    URI uri = new URIBuilder(request.url()).build();

    requestBuilder.setUri(uri.getScheme() + "://" + uri.getAuthority() + uri.getRawPath());

    //request query params
    List<NameValuePair> queryParams = URLEncodedUtils.parse(uri, requestBuilder.getCharset().name
            ());
    for (NameValuePair queryParam : queryParams) {
        requestBuilder.addParameter(queryParam);
    }

    //request headers
    boolean hasAcceptHeader = false;
    for (Map.Entry<String, Collection<String>> headerEntry : request.headers().entrySet()) {
        String headerName = headerEntry.getKey();
        if (headerName.equalsIgnoreCase(ACCEPT_HEADER_NAME)) {
            hasAcceptHeader = true;
        }

        if (headerName.equalsIgnoreCase(Util.CONTENT_LENGTH)) {
            // The 'Content-Length' header is always set by the Apache client and it
            // doesn't like us to set it as well.
            continue;
        }

        for (String headerValue : headerEntry.getValue()) {
            requestBuilder.addHeader(headerName, headerValue);
        }
    }
    //some servers choke on the default accept string, so we'll set it to anything
    if (!hasAcceptHeader) {
        requestBuilder.addHeader(ACCEPT_HEADER_NAME, "*/*");
    }

    //request body
    if (request.body() != null) {
        HttpEntity entity = null;
        if (request.charset() != null) {
            ContentType contentType = getContentType(request);
            String content = new String(request.body(), request.charset());
            entity = new StringEntity(content, contentType);
        } else {
            entity = new ByteArrayEntity(request.body());
        }

        requestBuilder.setEntity(entity);
    }

    return requestBuilder.build();
}
 
Example 60
Project: EncDecAboutJava   File: WtUtils.java   View Source Code Vote up 2 votes
/**
 * 提取URL中的参数键值对
 * @param url URL
 * @return
 * @throws URISyntaxException
 */
public static List<NameValuePair> getQueryMap(String url) throws URISyntaxException {
	List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), "UTF-8");
	return params;
}