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:cn.mrdear.pay.util.WebUtils.java

/**
 * ??/*from   w  w  w .  java  2s . co m*/
 *
 * @param query
 *            
 * @param encoding
 *            ??
 * @return ?
 */
public static Map<String, String> parse(String query, String encoding) {

    Charset charset;
    if (StringUtils.isNotEmpty(encoding)) {
        charset = Charset.forName(encoding);
    } else {
        charset = Charset.forName("UTF-8");
    }
    List<NameValuePair> nameValuePairs = URLEncodedUtils.parse(query, charset);
    Map<String, String> parameterMap = new HashMap<String, String>();
    for (NameValuePair nameValuePair : nameValuePairs) {
        parameterMap.put(nameValuePair.getName(), nameValuePair.getValue());
    }
    return parameterMap;
}

From source file:org.asimba.wa.integrationtest.util.AsimbaHtmlPage.java

/**
 * Find a link (anchor element) that has "{parameter}={parameterValue}" in its querystring
 * @param paramName//from  w  w w .j  a v a 2 s  . c  o  m
 * @param paramValue
 * @return HtmlAnchor that matches, or null if there was no match
 */
public HtmlAnchor findLinkWithParameterValue(String paramName, String paramValue) {
    if (_htmlPage == null) {
        _logger.error("Uninitialized htmlPage");
        return null;
    }
    HtmlAnchor theAnchor = null;
    // alternative to:
    //   List<?> list = htmlPage.getByXPath(
    //      "/html/body/div[@id='container']/div[@id='content']/div[@id='contentMain']/form[@id='selectionForm']/fieldset/ul/li/a");

    try {
        List<HtmlAnchor> anchors = _htmlPage.getAnchors();
        theanchorloop: for (HtmlAnchor anchor : anchors) {
            String href = anchor.getHrefAttribute();
            List<NameValuePair> params = URLEncodedUtils.parse(new URI(href), "UTF-8");
            for (NameValuePair nvp : params) {
                if (paramName.equals(nvp.getName())) {
                    if (paramValue.equals(nvp.getValue())) {
                        theAnchor = anchor;
                        break theanchorloop;
                    }
                }
            }
        }
    } catch (URISyntaxException e) {
        _logger.error("Could not encode parameter", e);
        return null;
    }

    _logger.info("Found anchor: {}", theAnchor);
    return theAnchor;
}

From source file:jobhunter.infoempleo.Client.java

public Job execute() throws IOException, URISyntaxException {
    l.debug("Connecting to {}", url);

    update("Connecting", 1L);
    final Document doc = Jsoup.connect(url).get();

    update("Parsing HTML", 2L);
    final Job job = Job.of();

    job.setPortal(InfoEmpleoWebPlugin.portal);
    job.setLink(url);/*  ww  w . ja  v  a2  s  . c om*/
    job.setExtId("");

    final StringBuilder description = new StringBuilder();

    doc.getElementsByClass("linea").forEach(td -> {
        td.getElementsByTag("p").forEach(p -> {
            description.append(StringEscapeUtils.unescapeHtml4(p.html())).append(System.lineSeparator());
        });
    });

    job.setDescription(description.toString());

    job.setPosition(doc.getElementById("ctl00_CPH_Body_Link_Subtitulo").attr("title"));

    job.getCompany().setName(getCompany(doc));

    final String href = doc.getElementById("ctl00_CPH_Body_lnkEnviarAmigoI").attr("href");

    final String extId = URLEncodedUtils.parse(new URI(href), "UTF-8").stream()
            .filter(nvp -> nvp.getName().equalsIgnoreCase("Id_Oferta")).findFirst().get().getValue();

    job.setExtId(extId);

    update("Done", 3L);
    return job;
}

From source file:com.bt.download.android.gui.httpserver.DownloadHandler.java

public void internalHandler(HttpExchange exchange) throws IOException {
    assertUPnPActive();//www  .ja  va  2  s .  c  o m

    OutputStream os = null;
    FileInputStream fis = null;

    byte type = -1;
    int id = -1;

    PeerHttpUpload upload = null;

    try {

        List<NameValuePair> query = URLEncodedUtils.parse(exchange.getRequestURI(), "UTF-8");

        for (NameValuePair item : query) {
            if (item.getName().equals("type")) {
                type = Byte.parseByte(item.getValue());
            }
            if (item.getName().equals("id")) {
                id = Integer.parseInt(item.getValue());
            }
        }

        if (type == -1 || id == -1) {
            exchange.sendResponseHeaders(Code.HTTP_BAD_REQUEST, 0);
            return;
        }

        if (TransferManager.instance().getActiveUploads() >= ConfigurationManager.instance()
                .maxConcurrentUploads()) {
            sendBusyResponse(exchange);
            return;
        }

        FileDescriptor fd = Librarian.instance().getFileDescriptor(type, id);
        if (fd == null) {
            throw new IOException("There is no such file shared");
        }

        upload = TransferManager.instance().upload(fd);

        exchange.getResponseHeaders().add("Content-Type", fd.mime);
        exchange.sendResponseHeaders(Code.HTTP_OK, fd.fileSize);

        os = exchange.getResponseBody();

        fis = new FileInputStream(fd.filePath);

        byte[] buffer = new byte[4 * 1024];
        int n;
        int count = 0;

        while ((n = fis.read(buffer, 0, buffer.length)) != -1) {
            os.write(buffer, 0, n);
            upload.addBytesSent(n);

            if (upload.isCanceled()) {
                try {
                    throw new IOException("Upload cancelled");
                } finally {
                    os.close();
                }
            }

            count += n;
            if (count > 4096) {
                count = 0;
                Thread.yield();
            }
        }

    } catch (IOException e) {
        LOG.log(Level.INFO, "Error uploading file type=" + type + ", id=" + id);
        throw e;
    } finally {
        close(os);
        close(fis);

        try {
            exchange.close();
        } catch (Throwable e) {
            // ignore
        }

        if (upload != null) {
            upload.complete();
        }
    }
}

From source file:org.elasticsearch.discovery.ec2.AmazonEC2Fixture.java

@Override
protected Response handle(final Request request) throws IOException {
    if ("/".equals(request.getPath()) && ("POST".equals(request.getMethod()))) {
        final String userAgent = request.getHeader("User-Agent");
        if (userAgent != null && userAgent.startsWith("aws-sdk-java")) {
            // Simulate an EC2 DescribeInstancesResponse
            byte[] responseBody = EMPTY_BYTE;
            for (NameValuePair parse : URLEncodedUtils.parse(new String(request.getBody(), UTF_8), UTF_8)) {
                if ("Action".equals(parse.getName())) {
                    responseBody = generateDescribeInstancesResponse();
                    break;
                }//from w  w w.  j a v  a2  s .co  m
            }
            return new Response(RestStatus.OK.getStatus(), contentType("text/xml; charset=UTF-8"),
                    responseBody);
        }
    }
    return null;
}

From source file:io.wcm.caravan.io.http.request.Request.java

/**
 * @param name of the query parameter/*from  ww w .jav a  2  s  .co  m*/
 * @return true if the parameter exists in this request's query
 */
public boolean hasParameter(String name) {

    // TODO: is there really no easier function for this on the classpath (e.g. parse into some MultiValueMap)
    List<NameValuePair> parameters = URLEncodedUtils.parse(URI.create(url), CharEncoding.UTF_8);

    return Streams.of(parameters).filter(param -> param.getName().equals(name)).iterator().hasNext();
}

From source file:com.envirover.rockblock.RockBlockHttpHandler.java

@Override
public void handle(HttpExchange t) throws IOException {
    try {/*  www  .j a  v a  2  s. c  o m*/
        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());
    }
}

From source file:com.twitter.hbc.httpclient.auth.OAuth1.java

@Override
public void signRequest(HttpUriRequest request, String postParams) {
    // TODO: this is a little odd: we already encoded the values earlier, but using URLEncodedUtils.parse will decode the values,
    // which we will encode again.
    List<NameValuePair> httpGetParams = URLEncodedUtils.parse(request.getURI().getRawQuery(), Charsets.UTF_8);
    List<Pair> javaParams = new ArrayList<Pair>(httpGetParams.size());
    for (NameValuePair params : httpGetParams) {
        Pair tuple = new Pair(UrlCodec.encode(params.getName()), UrlCodec.encode(params.getValue()));
        javaParams.add(tuple);//from  w ww . jav a2  s  .com
    }

    if (postParams != null) {
        List<NameValuePair> httpPostParams = URLEncodedUtils.parse(postParams, Charsets.UTF_8);

        for (NameValuePair params : httpPostParams) {
            Pair tuple = new Pair(UrlCodec.encode(params.getName()), UrlCodec.encode(params.getValue()));
            javaParams.add(tuple);
        }
    }

    long timestampSecs = generateTimestamp();
    String nonce = generateNonce();

    OAuthParams.OAuth1Params oAuth1Params = new OAuthParams.OAuth1Params(token, consumerKey, nonce,
            timestampSecs, Long.toString(timestampSecs), "", OAuthParams.HMAC_SHA1, OAuthParams.ONE_DOT_OH);

    int port = request.getURI().getPort();
    if (port <= 0) {
        // getURI can return a -1 for a port
        if (request.getURI().getScheme().equalsIgnoreCase(HttpConstants.HTTP_SCHEME)) {
            port = HttpConstants.DEFAULT_HTTP_PORT;
        } else if (request.getURI().getScheme().equalsIgnoreCase(HttpConstants.HTTPS_SCHEME)) {
            port = HttpConstants.DEFAULT_HTTPS_PORT;
        } else {
            throw new IllegalStateException("Bad URI scheme: " + request.getURI().getScheme());
        }
    }

    String normalized = normalizer.normalize(request.getURI().getScheme(), request.getURI().getHost(), port,
            request.getMethod().toUpperCase(), request.getURI().getPath(), javaParams, oAuth1Params);

    String signature;
    try {
        signature = signer.getString(normalized, tokenSecret, consumerSecret);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    Map<String, String> oauthHeaders = new HashMap<String, String>();
    oauthHeaders.put(OAuthParams.OAUTH_CONSUMER_KEY, quoted(consumerKey));
    oauthHeaders.put(OAuthParams.OAUTH_TOKEN, quoted(token));
    oauthHeaders.put(OAuthParams.OAUTH_SIGNATURE, quoted(signature));
    oauthHeaders.put(OAuthParams.OAUTH_SIGNATURE_METHOD, quoted(OAuthParams.HMAC_SHA1));
    oauthHeaders.put(OAuthParams.OAUTH_TIMESTAMP, quoted(Long.toString(timestampSecs)));
    oauthHeaders.put(OAuthParams.OAUTH_NONCE, quoted(nonce));
    oauthHeaders.put(OAuthParams.OAUTH_VERSION, quoted(OAuthParams.ONE_DOT_OH));
    String header = Joiner.on(", ").withKeyValueSeparator("=").join(oauthHeaders);

    request.setHeader(HttpHeaders.AUTHORIZATION, "OAuth " + header);

}

From source file:org.apache.marmotta.ldclient.provider.youtube.mapping.YoutubeUriMapper.java

/**
 * Take the selected value, process it according to the mapping definition, and create Sesame Values using the
 * factory passed as argument.//  w  w w.java2  s .c o m
 *
 *
 * @param resourceUri
 * @param selectedValue
 * @param factory
 * @return
 */
@Override
public List<Value> map(String resourceUri, String selectedValue, ValueFactory factory) {
    if (selectedValue.startsWith("http://gdata.youtube.com/feeds/api/videos")
            && selectedValue.indexOf('?') >= 0) {
        return Collections.singletonList(
                (Value) factory.createURI(selectedValue.substring(0, selectedValue.indexOf('?'))));
    } else if (selectedValue.startsWith("http://www.youtube.com/v/")) {
        String[] p_components = selectedValue.split("/");
        String video_id = p_components[p_components.length - 1];

        return Collections.singletonList(
                (Value) factory.createURI("http://gdata.youtube.com/feeds/api/videos/" + video_id));
    } else if (selectedValue.startsWith("http://www.youtube.com/watch")) {
        try {
            URI uri = new URI(selectedValue);

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

            String video_id = null;
            for (NameValuePair pair : params) {
                if ("v".equals(pair.getName())) {
                    video_id = pair.getValue();
                }
            }

            if (video_id != null) {
                return Collections.singletonList(
                        (Value) factory.createURI("http://gdata.youtube.com/feeds/api/videos/" + video_id));
            }
        } catch (URISyntaxException e) {
            return Collections.singletonList((Value) factory.createURI(selectedValue));
        }
    }
    return Collections.singletonList((Value) factory.createURI(selectedValue));
}

From source file:com.google.maps.LocalTestServerContext.java

private List<NameValuePair> parseQueryParamsFromRequestLine(String requestLine) throws URISyntaxException {
    // Extract the URL part from the HTTP request line
    String[] chunks = requestLine.split("\\s");
    String url = chunks[1];// w w w.ja v  a 2 s.co m

    return URLEncodedUtils.parse(new URI(url), Charset.forName("UTF-8"));
}