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:com.mirth.connect.connectors.ws.WebServiceReceiver.java

private com.sun.net.httpserver.Authenticator createAuthenticator() throws ConnectorTaskException {
    final Authenticator authenticator;
    try {//from w  w  w  .  j  a  v  a2s.com
        authenticator = authenticatorProvider.getAuthenticator();
    } catch (Exception e) {
        throw new ConnectorTaskException("Unable to create authenticator.", e);
    }

    return new com.sun.net.httpserver.Authenticator() {
        @Override
        public Result authenticate(final HttpExchange exch) {
            String remoteAddress = StringUtils
                    .trimToEmpty(exch.getRemoteAddress().getAddress().getHostAddress());
            int remotePort = exch.getRemoteAddress().getPort();
            String localAddress = StringUtils.trimToEmpty(exch.getLocalAddress().getAddress().getHostAddress());
            int localPort = exch.getLocalAddress().getPort();
            String protocol = StringUtils.trimToEmpty(exch.getProtocol());
            String method = StringUtils.trimToEmpty(exch.getRequestMethod());
            String requestURI = StringUtils.trimToEmpty(exch.getRequestURI().toString());
            Map<String, List<String>> headers = exch.getRequestHeaders();

            Map<String, List<String>> queryParameters = new LinkedHashMap<String, List<String>>();
            for (NameValuePair nvp : URLEncodedUtils.parse(exch.getRequestURI(), "UTF-8")) {
                List<String> list = queryParameters.get(nvp.getName());
                if (list == null) {
                    list = new ArrayList<String>();
                    queryParameters.put(nvp.getName(), list);
                }
                list.add(nvp.getValue());
            }

            EntityProvider entityProvider = new EntityProvider() {
                @Override
                public byte[] getEntity() throws IOException {
                    byte[] entity = (byte[]) exch.getAttribute(ATTRIBUTE_NAME);
                    if (entity == null) {
                        entity = IOUtils.toByteArray(exch.getRequestBody());
                        exch.setAttribute(ATTRIBUTE_NAME, entity);
                        exch.setStreams(new ByteArrayInputStream(entity), exch.getResponseBody());
                    }
                    return entity;
                }
            };

            RequestInfo requestInfo = new RequestInfo(remoteAddress, remotePort, localAddress, localPort,
                    protocol, method, requestURI, headers, queryParameters, entityProvider);

            try {
                AuthenticationResult result = authenticator.authenticate(requestInfo);

                for (Entry<String, List<String>> entry : result.getResponseHeaders().entrySet()) {
                    if (StringUtils.isNotBlank(entry.getKey()) && entry.getValue() != null) {
                        for (int i = 0; i < entry.getValue().size(); i++) {
                            if (i == 0) {
                                exch.getResponseHeaders().set(entry.getKey(), entry.getValue().get(i));
                            } else {
                                exch.getResponseHeaders().add(entry.getKey(), entry.getValue().get(i));
                            }
                        }
                    }
                }

                switch (result.getStatus()) {
                case CHALLENGED:
                    return new com.sun.net.httpserver.Authenticator.Retry(HttpServletResponse.SC_UNAUTHORIZED);
                case SUCCESS:
                    String username = StringUtils.trimToEmpty(result.getUsername());
                    String realm = StringUtils.trimToEmpty(result.getRealm());
                    return new com.sun.net.httpserver.Authenticator.Success(new HttpPrincipal(username, realm));
                case FAILURE:
                default:
                    return new com.sun.net.httpserver.Authenticator.Failure(
                            HttpServletResponse.SC_UNAUTHORIZED);

                }
            } catch (Throwable t) {
                logger.error("Error in HTTP authentication for " + connectorProperties.getName() + " ("
                        + connectorProperties.getName() + " \"Source\" on channel " + getChannelId() + ").", t);
                eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), null,
                        ErrorEventType.DESTINATION_CONNECTOR, "Source", connectorProperties.getName(),
                        "Error in HTTP authentication for " + connectorProperties.getName(), t));
                return new com.sun.net.httpserver.Authenticator.Failure(
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }
    };
}

From source file:org.apache.hadoop.yarn.webapp.util.WebAppUtils.java

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";
        }/*from  w  w w  .  j a  v  a2  s  .c  o  m*/
        Charset encoding = Charset.forName(reqEncoding);
        List<NameValuePair> params = URLEncodedUtils.parse(queryString, encoding);
        return URLEncodedUtils.format(params, encoding);
    }
    return null;
}

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

/**
 * Perform and HTTP request and return the resulting response using the
 * internal HttpClient.//  w ww .ja  v a 2 s.  c om
 * 
 * @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 = new URIBuilder(originalURI).setQuery(URLEncodedUtils.format(newQuery, "UTF-8"))
                        .build();
            } catch (URISyntaxException e) {
                e.printStackTrace();
                throw new RiakIORuntimeException(e);
            }
            httpMethod.setURI(newURI);
        }
    }
    HttpEntity entity = null;
    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);
            }
        }

        key = extractKeyFromResponseIfItWasNotAlreadyProvided(key, response);

        return new DefaultHttpResponse(bucket, key, status, headers, body, stream, response, httpMethod);
    } catch (IOException e) {
        httpMethod.abort();
        return toss(new RiakIORuntimeException(e));
    } finally {
        if (!streamResponse && entity != null) {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                // NO-OP
            }
        }
    }
}

From source file:org.keycloak.testsuite.OAuthClient.java

public Map<String, String> getCurrentQuery() {
    Map<String, String> m = new HashMap<String, String>();
    List<NameValuePair> pairs = URLEncodedUtils.parse(getCurrentUri(), "UTF-8");
    for (NameValuePair p : pairs) {
        m.put(p.getName(), p.getValue());
    }//from   w  w  w. j a  v a  2 s. c om
    return m;
}

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

protected SearchRequestResult parse_search(String html, int page) throws OpacErrorException {
    Document doc = Jsoup.parse(html);
    doc.setBaseUri(opac_url + "/searchfoo");

    if (doc.select(".error").size() > 0) {
        throw new OpacErrorException(doc.select(".error").text().trim());
    } else if (doc.select(".nohits").size() > 0) {
        throw new OpacErrorException(doc.select(".nohits").text().trim());
    } else if (doc.select(".box-header h2, #nohits").text().contains("keine Treffer")) {
        return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1, 1);
    }//from   w  w w . j  ava  2s.c om

    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 (int i = 0; i < links.size(); i++) {
        Element node = links.get(i);
        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("td img[title]").size() > 0) {
            String title = tr.select("td img").get(0).attr("title");
            String[] fparts = tr.select("td img").get(0).attr("src").split("/");
            String fname = fparts[fparts.length - 1];
            MediaType default_by_fname = defaulttypes.get(fname.toLowerCase(Locale.GERMAN).replace(".jpg", "")
                    .replace(".gif", "").replace(".png", ""));
            MediaType default_by_title = defaulttypes.get(title);
            MediaType default_name = default_by_title != null ? default_by_title : default_by_fname;
            if (data.has("mediatypes")) {
                try {
                    sr.setType(MediaType.valueOf(data.getJSONObject("mediatypes").getString(fname)));
                } catch (JSONException | IllegalArgumentException e) {
                    sr.setType(default_name);
                }
            } else {
                sr.setType(default_name);
            }
        }
        String alltext = tr.text();
        if (alltext.contains("eAudio") || alltext.contains("eMusic")) {
            sr.setType(MediaType.MP3);
        } else if (alltext.contains("eVideo")) {
            sr.setType(MediaType.EVIDEO);
        } else if (alltext.contains("eBook")) {
            sr.setType(MediaType.EBOOK);
        } else if (alltext.contains("Munzinger")) {
            sr.setType(MediaType.EDOC);
        }

        if (tr.children().size() > 3 && tr.child(3).select("img[title*=cover]").size() == 1) {
            sr.setCover(tr.child(3).select("img[title*=cover]").attr("abs:src"));
            if (sr.getCover().contains("showCover.do")) {
                downloadCover(sr);
            }
        }

        Element middlething;
        if (tr.children().size() > 2 && tr.child(2).select("a").size() > 0) {
            middlething = tr.child(2);
        } else {
            middlething = tr.child(1);
        }

        List<Node> children = middlething.childNodes();
        if (middlething.select("div").not("#hlrightblock,.bestellfunktionen").size() == 1) {
            Element indiv = middlething.select("div").not("#hlrightblock,.bestellfunktionen").first();
            if (indiv.children().size() > 1) {
                children = indiv.childNodes();
            }
        } else if (middlething.select("span.titleData").size() == 1) {
            children = middlething.select("span.titleData").first().childNodes();
        }
        int childrennum = children.size();

        List<String[]> strings = new ArrayList<>();
        for (int ch = 0; ch < childrennum; ch++) {
            Node node = children.get(ch);
            if (node instanceof TextNode) {
                String text = ((TextNode) node).text().trim();
                if (text.length() > 3) {
                    strings.add(new String[] { "text", "", text });
                }
            } else if (node instanceof Element) {

                List<Node> subchildren = node.childNodes();
                for (int j = 0; j < subchildren.size(); j++) {
                    Node subnode = subchildren.get(j);
                    if (subnode instanceof TextNode) {
                        String text = ((TextNode) subnode).text().trim();
                        if (text.length() > 3) {
                            strings.add(new String[] { ((Element) node).tag().getName(), "text", text,
                                    ((Element) node).className(), node.attr("style") });
                        }
                    } else if (subnode instanceof Element) {
                        String text = ((Element) subnode).text().trim();
                        if (text.length() > 3) {
                            strings.add(new String[] { ((Element) node).tag().getName(),
                                    ((Element) subnode).tag().getName(), text, ((Element) node).className(),
                                    node.attr("style") });
                        }
                    }
                }
            }
        }

        StringBuilder description = null;
        if (tr.select("span.Z3988").size() == 1) {
            // Sometimes there is a <span class="Z3988"> item which provides
            // data in a standardized format.
            List<NameValuePair> z3988data;
            boolean hastitle = false;
            try {
                description = new StringBuilder();
                z3988data = URLEncodedUtils
                        .parse(new URI("http://dummy/?" + tr.select("span.Z3988").attr("title")), "UTF-8");
                for (NameValuePair nv : z3988data) {
                    if (nv.getValue() != null) {
                        if (!nv.getValue().trim().equals("")) {
                            if (nv.getName().equals("rft.btitle") && !hastitle) {
                                description.append("<b>").append(nv.getValue()).append("</b>");
                                hastitle = true;
                            } else if (nv.getName().equals("rft.atitle") && !hastitle) {
                                description.append("<b>").append(nv.getValue()).append("</b>");
                                hastitle = true;
                            } else if (nv.getName().equals("rft.au")) {
                                description.append("<br />").append(nv.getValue());
                            } else if (nv.getName().equals("rft.date")) {
                                description.append("<br />").append(nv.getValue());
                            }
                        }
                    }
                }
            } catch (URISyntaxException e) {
                description = null;
            }
        }
        boolean described = false;
        if (description != null && description.length() > 0) {
            sr.setInnerhtml(description.toString());
            described = true;
        } else {
            description = new StringBuilder();
        }
        int k = 0;
        boolean yearfound = false;
        boolean titlefound = false;
        boolean sigfound = false;
        for (String[] part : strings) {
            if (!described) {
                if (part[0].equals("a") && (k == 0 || !titlefound)) {
                    if (k != 0) {
                        description.append("<br />");
                    }
                    description.append("<b>").append(part[2]).append("</b>");
                    titlefound = true;
                } else if (part[2].matches("\\D*[0-9]{4}\\D*") && part[2].length() <= 10) {
                    yearfound = true;
                    if (k != 0) {
                        description.append("<br />");
                    }
                    description.append(part[2]);
                } else if (k == 1 && !yearfound && part[2].matches("^\\s*\\([0-9]{4}\\)$")) {
                    if (k != 0) {
                        description.append("<br />");
                    }
                    description.append(part[2]);
                } else if (k == 1 && !yearfound && part[2].matches("^\\s*\\([0-9]{4}\\)$")) {
                    if (k != 0) {
                        description.append("<br />");
                    }
                    description.append(part[2]);
                } else if (k > 1 && k < 4 && !sigfound && part[0].equals("text")
                        && part[2].matches("^[A-Za-z0-9,\\- ]+$")) {
                    description.append("<br />");
                    description.append(part[2]);
                }
            }
            if (part.length == 4) {
                if (part[0].equals("span") && part[3].equals("textgruen")) {
                    sr.setStatus(SearchResult.Status.GREEN);
                } else if (part[0].equals("span") && part[3].equals("textrot")) {
                    sr.setStatus(SearchResult.Status.RED);
                }
            } else if (part.length == 5) {
                if (part[4].contains("purple")) {
                    sr.setStatus(SearchResult.Status.YELLOW);
                }
            }
            if (sr.getStatus() == null) {
                if ((part[2].contains("entliehen")
                        && part[2].startsWith("Vormerkung ist leider nicht mglich"))
                        || part[2].contains("nur in anderer Zweigstelle ausleihbar und nicht bestellbar")) {
                    sr.setStatus(SearchResult.Status.RED);
                } else if (part[2].startsWith("entliehen")
                        || part[2].contains("Ein Exemplar finden Sie in einer anderen Zweigstelle")) {
                    sr.setStatus(SearchResult.Status.YELLOW);
                } else if ((part[2].startsWith("bestellbar") && !part[2].contains("nicht bestellbar"))
                        || (part[2].startsWith("vorbestellbar") && !part[2].contains("nicht vorbestellbar"))
                        || (part[2].startsWith("vorbestellbar") && !part[2].contains("nicht vorbestellbar"))
                        || (part[2].startsWith("vormerkbar") && !part[2].contains("nicht vormerkbar"))
                        || (part[2].contains("heute zurckgebucht"))
                        || (part[2].contains("ausleihbar") && !part[2].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);
                    }
                }
            }
            k++;
        }
        if (!described) {
            sr.setInnerhtml(description.toString());
        }

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

From source file:com.nominanuda.web.http.HttpCoreHelper.java

public @Nullable String getQueryParamFirstOccurrence(HttpRequest request, String name) {
    List<NameValuePair> l = URLEncodedUtils.parse(URI.create(request.getRequestLine().getUri()), UTF_8);
    for (NameValuePair nvp : l) {
        if (name.equals(nvp.getName())) {
            return nvp.getValue();
        }/*  w  w w.  j  a v a 2s. c  om*/
    }
    return null;
}

From source file:com.mobicage.rogerthat.plugins.scan.ProcessScanActivity.java

private void processInvitation(final String url) {
    URI uri;//  w  ww .j a va 2  s. c  o m
    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        L.bug(e);
        return;
    }

    String secret = null;
    String invitor = null;

    for (NameValuePair arg : URLEncodedUtils.parse(uri, "UTF-8")) {
        if (INVITATION_SECRET_ARG.equals(arg.getName())) {
            secret = arg.getValue();
        } else if (INVITATION_INVITOR_ARG.equals(arg.getName())) {
            invitor = arg.getValue();
        }

        if (secret != null && invitor != null) {
            break;
        }
    }

    if (secret == null || invitor == null) {
        L.d("I don't know how to process this URL: " + url);
    } else {
        String invitorEmailHash = url.substring(URL_ROGERTHAT_PREFIX.length(), url.indexOf("?"));
        if (!isMyEmailHash(invitorEmailHash)) {
            FriendsPlugin friendsPlugin = mService.getPlugin(FriendsPlugin.class);
            if (friendsPlugin.ackInvitationBySecret(invitorEmailHash, secret)) {
                UIUtils.showLongToast(this, getString(R.string.invitation_successfully_accepted, invitor));
            } else {
                UIUtils.showLongToast(this, getString(R.string.invitation_acception_failure));
            }
        }
    }
    finish();
}

From source file:com.nominanuda.web.http.HttpCoreHelper.java

public DataStruct getQueryParams(HttpRequest request) {
    List<NameValuePair> l = URLEncodedUtils.parse(URI.create(request.getRequestLine().getUri()), UTF_8);
    return toDataStruct(l);
}

From source file:android.webkit.AccessibilityInjector.java

/**
 * Returns the script injection preference requested by the URL, or
 * {@link #ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED} if the page has no
 * preference.//from w  w  w .  jav a2  s.co  m
 *
 * @param url The URL to check.
 * @return A script injection preference.
 */
private int getAxsUrlParameterValue(String url) {
    if (url == null) {
        return ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED;
    }

    try {
        final List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), null);

        for (NameValuePair param : params) {
            if ("axs".equals(param.getName())) {
                return verifyInjectionValue(param.getValue());
            }
        }
    } catch (URISyntaxException e) {
        // Do nothing.
    } catch (IllegalArgumentException e) {
        // Catch badly-formed URLs.
    }

    return ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED;
}