Example usage for org.apache.http.client.utils URLEncodedUtils parse

List of usage examples for org.apache.http.client.utils URLEncodedUtils parse

Introduction

In this page you can find the example usage for org.apache.http.client.utils URLEncodedUtils parse.

Prototype

public static List<NameValuePair> parse(final String s, final Charset charset) 

Source Link

Document

Returns a list of NameValuePair NameValuePairs as parsed from the given string using the given character encoding.

Usage

From source file:it.smartcommunitylab.aac.controller.AuthController.java

/**
 * Handles the redirection to the specified target after the login has been
 * performed. Given the user data collected during the login, updates the
 * user information in DB and populates the security context with the user
 * credentials.// w  w  w .j a  v  a 2s  .  c  o m
 * 
 * @param authorityUrl
 *            the authority used by the user to sign in.
 * @param target
 *            target functionality address.
 * @param req
 * @return
 * @throws Exception
 */
@RequestMapping("/eauth/{authorityUrl}")
public ModelAndView forward(@PathVariable String authorityUrl, @RequestParam(required = false) String target,
        HttpServletRequest req, HttpServletResponse res) {

    String nTarget = (String) req.getSession().getAttribute("redirect");
    if (nTarget == null)
        return new ModelAndView("redirect:/logout");

    String clientId = (String) req.getSession().getAttribute(OAuth2Utils.CLIENT_ID);
    if (clientId != null) {
        Set<String> idps = clientDetailsAdapter.getIdentityProviders(clientId);
        if (!idps.contains(authorityUrl)) {
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("message", "incorrect identity provider for the app");
            return new ModelAndView("oauth_error", model);
        }
    }

    AACOAuthRequest oauthRequest = (AACOAuthRequest) req.getSession()
            .getAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST);
    if (oauthRequest != null) {
        oauthRequest.setAuthority(authorityUrl);
        req.getSession().setAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST, oauthRequest);
    }

    target = nTarget;

    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    if (old != null && old instanceof AACAuthenticationToken) {
        AACOAuthRequest oldDetails = (AACOAuthRequest) old.getDetails();
        if (oldDetails != null && !authorityUrl.equals(oldDetails.getAuthority())) {
            new SecurityContextLogoutHandler().logout(req, res, old);
            SecurityContextHolder.getContext().setAuthentication(null);

            req.getSession().setAttribute("redirect", target);
            req.getSession().setAttribute(OAuth2Utils.CLIENT_ID, clientId);

            return new ModelAndView("redirect:" + Utils.filterRedirectURL(authorityUrl));
        }
    }

    List<NameValuePair> pairs = URLEncodedUtils.parse(URI.create(nTarget), "UTF-8");

    it.smartcommunitylab.aac.model.User userEntity = null;
    if (old != null
            && (old instanceof AACAuthenticationToken || old instanceof RememberMeAuthenticationToken)) {
        String userId = old.getName();
        userEntity = userRepository.findOne(Long.parseLong(userId));
    } else {
        userEntity = providerServiceAdapter.updateUser(authorityUrl, toMap(pairs), req);
    }

    List<GrantedAuthority> list = roleManager.buildAuthorities(userEntity);

    UserDetails user = new User(userEntity.getId().toString(), "", list);
    AbstractAuthenticationToken a = new AACAuthenticationToken(user, null, authorityUrl, list);
    a.setDetails(oauthRequest);

    SecurityContextHolder.getContext().setAuthentication(a);

    if (rememberMeServices != null) {
        rememberMeServices.loginSuccess(req, res, a);
    }

    return new ModelAndView("redirect:" + target);
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

private OAuthToken getAuthToken(String urlLoc) throws MalformedURLException, URISyntaxException {
    URL url = new URL(urlLoc);
    List<NameValuePair> nvps = URLEncodedUtils.parse(new URI(urlLoc), "UTF-8");
    // add the refresh key and state to the config file 
    String refreshKey = "";
    String refreshState = "";
    for (NameValuePair nameValuePair : nvps) {
        if (nameValuePair.getName().equals("code")) {
            refreshKey = nameValuePair.getValue();
        }//from w ww . j  a va  2s  . co  m
        if (nameValuePair.getName().equals("state")) {
            refreshState = nameValuePair.getValue();
        }
    }
    OAuthToken otoken = new OAuthToken(refreshKey, refreshState);
    return otoken;
}

From source file:com.at.checkinglicense.license.APKExpansionPolicy.java

private Map<String, String> decodeExtras(String extras) {
    Map<String, String> results = new HashMap<String, String>();
    try {/*from ww w  . jav  a2 s . c o m*/
        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;
}

From source file:com.fuseim.webapp.ProxyServlet.java

protected HttpRequest newProxyRequestWithEntity(String method, String proxyRequestUri,
        HttpServletRequest servletRequest) throws IOException {
    HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);

    String contentType = servletRequest.getContentType();

    boolean isFormPost = (contentType != null && contentType.contains("application/x-www-form-urlencoded")
            && "POST".equalsIgnoreCase(servletRequest.getMethod()));

    if (isFormPost) {
        List<NameValuePair> params = new ArrayList<>();

        List<NameValuePair> queryParams = Collections.emptyList();
        String queryString = servletRequest.getQueryString();
        if (queryString != null) {
            URLEncodedUtils.parse(queryString, Consts.UTF_8);
        }/*from w ww  .j av a  2  s . c om*/
        Map<String, String[]> form = servletRequest.getParameterMap();

        OUTER_LOOP: for (Iterator<String> nameIterator = form.keySet().iterator(); nameIterator.hasNext();) {
            String name = nameIterator.next();
            for (NameValuePair queryParam : queryParams) {
                if (name.equals(queryParam.getName())) {
                    continue OUTER_LOOP;
                }
            }
            String[] value = form.get(name);
            if (value.length != 1) {
                throw new RuntimeException("expecting one value in post form");
            }
            params.add(new BasicNameValuePair(name, value[0]));
        }
        eProxyRequest.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    } else {
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), getContentLength(servletRequest)));
    }
    return eProxyRequest;
}

From source file:com.smartling.api.sdk.FileApiClientAdapterTest.java

@Test
public void testUploadFile() throws ApiException, IOException {
    FileUploadParameterBuilder fileUploadParameterBuilder = getFileUploadParameterBuilder();
    File uploadFile = mock(File.class);
    when(uploadFile.getName()).thenReturn(FILE_URI);
    when(response.getContents()).thenReturn(UPLOAD_RESPONSE);

    ApiResponse<UploadFileData> apiResponse = fileApiClientAdapter.uploadFile(uploadFile, "UTF-8",
            fileUploadParameterBuilder);

    // Validate the request
    HttpRequestBase request = requestCaptor.getValue();
    List<NameValuePair> params = URLEncodedUtils.parse(request.getURI(), "UTF-8");
    assertUploadFileRequestParams(params);
    assertEquals(HOST, request.getURI().getHost());

    // Validate the response
    assertEquals("SUCCESS", apiResponse.getCode());
    UploadFileData uploadFileData = apiResponse.getData();
    assertEquals(1, uploadFileData.getStringCount());
    assertEquals(2, uploadFileData.getWordCount());
    assertTrue(uploadFileData.isOverWritten());
}

From source file:com.basho.riak.client.util.ClientHelper.java

/**
 * Perform and HTTP request and return the resulting response using the
 * internal HttpClient.//  w w w  .  j a va2  s .c  o m
 * 
 * @param bucket
 *            Bucket of the object receiving the request.
 * @param key
 *            Key of the object receiving the request or null if the request
 *            is for a bucket.
 * @param httpMethod
 *            The HTTP request to perform; must not be null.
 * @param meta
 *            Extra HTTP headers to attach to the request. Query parameters
 *            are ignored; they should have already been used to construct
 *            <code>httpMethod</code> and query parameters.
 * @param streamResponse
 *            If true, the connection will NOT be released. Use
 *            HttpResponse.getHttpMethod().getResponseBodyAsStream() to get
 *            the response stream; HttpResponse.getBody() will return null.
 * 
 * @return The HTTP response returned by Riak from executing
 *         <code>httpMethod</code>.
 * 
 * @throws RiakIORuntimeException
 *             If an error occurs during communication with the Riak server
 *             (i.e. HttpClient threw an IOException)
 */
HttpResponse executeMethod(String bucket, String key, HttpRequestBase httpMethod, RequestMeta meta,
        boolean streamResponse) {

    if (meta != null) {
        Map<String, String> headers = meta.getHeaders();
        for (String header : headers.keySet()) {
            httpMethod.addHeader(header, headers.get(header));
        }

        Map<String, String> queryParams = meta.getQueryParamMap();
        if (!queryParams.isEmpty()) {
            URI originalURI = httpMethod.getURI();
            List<NameValuePair> currentQuery = URLEncodedUtils.parse(originalURI, CharsetUtils.UTF_8.name());
            List<NameValuePair> newQuery = new LinkedList<NameValuePair>(currentQuery);

            for (Map.Entry<String, String> qp : queryParams.entrySet()) {
                newQuery.add(new BasicNameValuePair(qp.getKey(), qp.getValue()));
            }

            // For this, HC4.1 authors, I hate you
            URI newURI;
            try {
                newURI = URIUtils.createURI(originalURI.getScheme(), originalURI.getHost(),
                        originalURI.getPort(), originalURI.getPath(), URLEncodedUtils.format(newQuery, "UTF-8"),
                        null);
            } catch (URISyntaxException e) {
                throw new RiakIORuntimeException(e);
            }
            httpMethod.setURI(newURI);
        }
    }
    HttpEntity entity;
    try {
        org.apache.http.HttpResponse response = httpClient.execute(httpMethod);

        int status = 0;
        if (response.getStatusLine() != null) {
            status = response.getStatusLine().getStatusCode();
        }

        Map<String, String> headers = ClientUtils.asHeaderMap(response.getAllHeaders());
        byte[] body = null;
        InputStream stream = null;
        entity = response.getEntity();

        if (streamResponse) {
            stream = entity.getContent();
        } else {
            if (null != entity) {
                body = EntityUtils.toByteArray(entity);
            }
        }

        if (!streamResponse) {
            EntityUtils.consume(entity);
        }

        return new DefaultHttpResponse(bucket, key, status, headers, body, stream, response, httpMethod);
    } catch (IOException e) {
        httpMethod.abort();
        return toss(new RiakIORuntimeException(e));
    }
}

From source file:org.wso2.identity.integration.test.saml.SAMLFederationDynamicQueryParametersTestCase.java

private List<NameValuePair> buildQueryParamList(String requestToFedIdpLocationHeader) {

    return URLEncodedUtils.parse(requestToFedIdpLocationHeader, StandardCharsets.UTF_8);
}

From source file:de.geeksfactory.opacclient.apis.TouchPoint.java

protected SearchRequestResult parse_search(String html, int page) throws OpacErrorException, IOException {
    Document doc = Jsoup.parse(html);

    if (doc.select("#RefineHitListForm").size() > 0) {
        // the results are located on a different page loaded via AJAX
        html = httpGet(opac_url + "/speedHitList.do?_=" + String.valueOf(System.currentTimeMillis() / 1000)
                + "&hitlistindex=0&exclusionList=", ENCODING);
        doc = Jsoup.parse(html);/*from   w  w  w . j  av a  2  s.c  o  m*/
    }

    if (doc.select(".nodata").size() > 0) {
        return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1, 1);
    }

    doc.setBaseUri(opac_url + "/searchfoo");

    int results_total = -1;

    String resultnumstr = doc.select(".box-header h2").first().text();
    if (resultnumstr.contains("(1/1)") || resultnumstr.contains(" 1/1")) {
        reusehtml = html;
        throw new OpacErrorException("is_a_redirect");
    } else if (resultnumstr.contains("(")) {
        results_total = Integer.parseInt(resultnumstr.replaceAll(".*\\(([0-9]+)\\).*", "$1"));
    } else if (resultnumstr.contains(": ")) {
        results_total = Integer.parseInt(resultnumstr.replaceAll(".*: ([0-9]+)$", "$1"));
    }

    Elements table = doc.select("table.data > tbody > tr");
    identifier = null;

    Elements links = doc.select("table.data a");
    boolean haslink = false;
    for (Element node : links) {
        if (node.hasAttr("href") & node.attr("href").contains("singleHit.do") && !haslink) {
            haslink = true;
            try {
                List<NameValuePair> anyurl = URLEncodedUtils
                        .parse(new URI(node.attr("href").replace(" ", "%20").replace("&amp;", "&")), ENCODING);
                for (NameValuePair nv : anyurl) {
                    if (nv.getName().equals("identifier")) {
                        identifier = nv.getValue();
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    List<SearchResult> results = new ArrayList<>();
    for (int i = 0; i < table.size(); i++) {
        Element tr = table.get(i);
        SearchResult sr = new SearchResult();
        if (tr.select(".icn, img[width=32]").size() > 0) {
            String[] fparts = tr.select(".icn, img[width=32]").first().attr("src").split("/");
            String fname = fparts[fparts.length - 1];
            String changedFname = fname.toLowerCase(Locale.GERMAN).replace(".jpg", "").replace(".gif", "")
                    .replace(".png", "");

            // File names can look like this: "20_DVD_Video.gif"
            Pattern pattern = Pattern.compile("(\\d+)_.*");
            Matcher matcher = pattern.matcher(changedFname);
            if (matcher.find()) {
                changedFname = matcher.group(1);
            }

            MediaType defaulttype = defaulttypes.get(changedFname);
            if (data.has("mediatypes")) {
                try {
                    sr.setType(MediaType.valueOf(data.getJSONObject("mediatypes").getString(fname)));
                } catch (JSONException | IllegalArgumentException e) {
                    sr.setType(defaulttype);
                }
            } else {
                sr.setType(defaulttype);
            }
        }
        String title;
        String text;
        if (tr.select(".results table").size() > 0) { // e.g. RWTH Aachen
            title = tr.select(".title a").text();
            text = tr.select(".title div").text();
        } else { // e.g. Schaffhausen, BSB Mnchen
            title = tr.select(".title, .hitlistTitle").text();
            text = tr.select(".results, .hitlistMetadata").first().ownText();
        }

        // we need to do some evil javascript parsing here to get the cover
        // and loan status of the item

        // get cover
        if (tr.select(".cover script").size() > 0) {
            String js = tr.select(".cover script").first().html();
            String isbn = matchJSVariable(js, "isbn");
            String ajaxUrl = matchJSVariable(js, "ajaxUrl");
            if (!"".equals(isbn) && !"".equals(ajaxUrl)) {
                String url = new URL(new URL(opac_url + "/"), ajaxUrl).toString();
                String coverUrl = httpGet(url + "?isbn=" + isbn + "&size=small", ENCODING);
                if (!"".equals(coverUrl)) {
                    sr.setCover(coverUrl.replace("\r\n", "").trim());
                }
            }
        }
        // get loan status and media ID
        if (tr.select("div[id^=loanstatus] + script").size() > 0) {
            String js = tr.select("div[id^=loanstatus] + script").first().html();
            String[] variables = new String[] { "loanstateDBId", "itemIdentifier", "hitlistIdentifier",
                    "hitlistPosition", "duplicateHitlistIdentifier", "itemType", "titleStatus", "typeofHit",
                    "context" };
            String ajaxUrl = matchJSVariable(js, "ajaxUrl");
            if (!"".equals(ajaxUrl)) {
                JSONObject id = new JSONObject();
                List<NameValuePair> map = new ArrayList<>();
                for (String variable : variables) {
                    String value = matchJSVariable(js, variable);
                    if (!"".equals(value)) {
                        map.add(new BasicNameValuePair(variable, value));
                    }
                    try {
                        if (variable.equals("itemIdentifier")) {
                            id.put("id", value);
                        } else if (variable.equals("loanstateDBId")) {
                            id.put("db", value);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                sr.setId(id.toString());
                String url = new URL(new URL(opac_url + "/"), ajaxUrl).toString();
                String loanStatusHtml = httpGet(url + "?" + URLEncodedUtils.format(map, "UTF-8"), ENCODING)
                        .replace("\r\n", "").trim();
                Document loanStatusDoc = Jsoup.parse(loanStatusHtml);
                String loanstatus = loanStatusDoc.text().replace("\u00bb", "").trim();

                if ((loanstatus.startsWith("entliehen") && loanstatus.contains("keine Vormerkung mglich")
                        || loanstatus.contains("Keine Exemplare verfgbar"))) {
                    sr.setStatus(SearchResult.Status.RED);
                } else if (loanstatus.startsWith("entliehen") || loanstatus.contains("andere Zweigstelle")) {
                    sr.setStatus(SearchResult.Status.YELLOW);
                } else if ((loanstatus.startsWith("bestellbar") && !loanstatus.contains("nicht bestellbar"))
                        || (loanstatus.startsWith("vorbestellbar")
                                && !loanstatus.contains("nicht vorbestellbar"))
                        || (loanstatus.startsWith("vorbestellbar")
                                && !loanstatus.contains("nicht vorbestellbar"))
                        || (loanstatus.startsWith("vormerkbar") && !loanstatus.contains("nicht vormerkbar"))
                        || (loanstatus.contains("heute zurckgebucht"))
                        || (loanstatus.contains("ausleihbar") && !loanstatus.contains("nicht ausleihbar"))) {
                    sr.setStatus(SearchResult.Status.GREEN);
                }
                if (sr.getType() != null) {
                    if (sr.getType().equals(MediaType.EBOOK) || sr.getType().equals(MediaType.EVIDEO)
                            || sr.getType().equals(MediaType.MP3))
                    // Especially Onleihe.de ebooks are often marked
                    // green though they are not available.
                    {
                        sr.setStatus(SearchResult.Status.UNKNOWN);
                    }
                }
            }
        }

        sr.setInnerhtml(("<b>" + title + "</b><br/>") + text);

        sr.setNr(10 * (page - 1) + i + 1);
        results.add(sr);
    }
    resultcount = results.size();
    return new SearchRequestResult(results, results_total, page);
}

From source file:com.petrodevelopment.dice.external.Router.java

private RouterParams paramsForUrl(String url) {
    final String cleanedUrl = cleanUrl(url);

    URI parsedUri = URI.create("http://tempuri.org/" + cleanedUrl);

    String urlPath = parsedUri.getPath().substring(1);

    if (this._cachedRoutes.get(cleanedUrl) != null) {
        return this._cachedRoutes.get(cleanedUrl);
    }/*from w w w .  ja v  a  2 s.  c  o m*/

    String[] givenParts = urlPath.split("/");

    RouterParams routerParams = null;
    for (Entry<String, RouterOptions> entry : this._routes.entrySet()) {
        String routerUrl = cleanUrl(entry.getKey());
        RouterOptions routerOptions = entry.getValue();
        String[] routerParts = routerUrl.split("/");

        if (routerParts.length != givenParts.length) {
            continue;
        }

        Map<String, String> givenParams = urlToParamsMap(givenParts, routerParts);
        if (givenParams == null) {
            continue;
        }

        routerParams = new RouterParams();
        routerParams.openParams = givenParams;
        routerParams.routerOptions = routerOptions;
        break;
    }

    if (routerParams == null) {
        throw new RouteNotFoundException("No route found for url " + url);
    }

    List<NameValuePair> query = URLEncodedUtils.parse(parsedUri, "utf-8");

    for (NameValuePair pair : query) {
        routerParams.openParams.put(pair.getName(), pair.getValue());
    }

    this._cachedRoutes.put(cleanedUrl, routerParams);
    return routerParams;
}