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:fi.okm.mpass.idp.authn.impl.OpenIdConnectIdentityTest.java

@Test
public void successGetRedirect() throws Exception {
    MockHttpServletRequest mockHttpServletRequest = getRequest();
    openIdConnectIdentity.setAuthorizationEndpoint(authorize_endpoint);
    String redirectUrl = openIdConnectIdentity.getRedirectUrl(mockHttpServletRequest);
    Assert.assertNotNull(redirectUrl);//from w ww . j a  va2 s  .  co  m
    Assert.assertEquals(verifyUrl(redirectUrl), true);
    List<NameValuePair> params = URLEncodedUtils.parse(new URI(redirectUrl), "UTF-8");
    Assert.assertNotNull(params.contains("scope"));
    Assert.assertNotNull(params.contains("response_type"));
    Assert.assertNotNull(params.contains("client_id"));
    Assert.assertNotNull(params.contains("redirect_uri"));
    Assert.assertNotNull(params.contains("state"));
    for (NameValuePair param : params) {
        if (param.getName().equals("scope")) {
            Assert.assertTrue(param.getValue().contains("openid"));
        }
        if (param.getName().equals("response_type")) {
            Assert.assertEquals(param.getValue(), "code");
        }
        if (param.getName().equals("client_id")) {
            Assert.assertEquals(param.getValue(), client_id);
        }
        if (param.getName().equals("redirect_uri")) {
            Assert.assertEquals(param.getValue(), mockHttpServletRequest.getRequestURL().toString());
        }
    }

}

From source file:org.apache.marmotta.ldclient.provider.phpbb.PHPBBForumProvider.java

/**
 * Return a mapping table mapping from RDF properties to XPath Value Mappers. Each entry in the
 * map is evaluated//from  w ww . ja  va 2s . c o  m
 * in turn; in case the XPath expression yields a result, the property is added for the
 * processed resource.
 * 
 * @return
 * @param requestUrl
 */
@Override
protected Map<String, JSoupMapper> getMappings(String resource, String requestUrl) {
    URI uri = null;
    try {
        uri = new URI(requestUrl);
        Map<String, String> params = new HashMap<String, String>();
        for (NameValuePair p : URLEncodedUtils.parse(uri, "UTF-8")) {
            params.put(p.getName(), p.getValue());
        }

        if (params.containsKey("f")) {

            Map<String, JSoupMapper> postMappings = new HashMap<String, JSoupMapper>();
            if (params.containsKey("start")) {
                // when start is set, we only take the replies; we are in a second or further
                // page of the topic
                postMappings.put(Namespaces.NS_SIOC + "container_of", new PHPBBTopicHrefMapper("a.topictitle"));
            } else {
                // otherwise we also take the initial title, creator and date for the topic
                postMappings.put(Namespaces.NS_DC + "title",
                        new CssTextLiteralMapper("div#pageheader a.titles"));
                postMappings.put(Namespaces.NS_DC + "description",
                        new CssTextLiteralMapper("div#pageheader span.forumdesc"));
                postMappings.put(Namespaces.NS_SIOC + "container_of", new PHPBBTopicHrefMapper("a.topictitle"));

                postMappings.put(Namespaces.NS_SIOC + "parent_of",
                        new PHPBBForumHrefMapper("a.forumlink, a.forumtitle"));
            }

            return postMappings;
        } else
            throw new RuntimeException(
                    "the requested resource does not seem to identify a PHPBB Forum (t=... parameter missing)");

    } catch (URISyntaxException e) {
        throw new RuntimeException(
                "the requested resource does not seem to identify a PHPBB Forum (URI syntax error)");
    }

}

From source file:com.predic8.membrane.servlet.embedded.RStudioMembraneServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String queryString = req.getQueryString() == null ? "" : "?" + req.getQueryString();

    Router router;/*  w  w w.j  a v a  2s  .c  o m*/

    // For websockets, the following paths are used by JupyterHub:
    //  /(user/[^/]*)/(api/kernels/[^/]+/channels|terminals/websocket)/?
    // forward to ws(s)://servername:port_number
    //<LocationMatch "/mypath/(user/[^/]*)/(api/kernels/[^/]+/channels|terminals/websocket)(.*)">
    //    ProxyPassMatch ws://localhost:8999/mypath/$1/$2$3
    //    ProxyPassReverse ws://localhost:8999 # this may be superfluous
    //</LocationMatch>
    //        ProxyPass /api/kernels/ ws://192.168.254.23:8888/api/kernels/
    //        ProxyPassReverse /api/kernels/ http://192.168.254.23:8888/api/kernels/
    List<NameValuePair> pairs;
    try {
        //note: HttpClient 4.2 lets you parse the string without building the URI
        pairs = URLEncodedUtils.parse(new URI(queryString), "UTF-8");
    } catch (URISyntaxException e) {
        throw new ServletException("Unexpected URI parsing error on " + queryString, e);
    }
    LinkedHashMap<String, String> params = new LinkedHashMap<>();
    for (NameValuePair pair : pairs) {
        params.put(pair.getName(), pair.getValue());
    }

    String externalIp = Ip.getHost(req.getRequestURL().toString());

    StringBuffer urlBuf = new StringBuffer("http://localhost:");

    String ctxPath = req.getRequestURI();

    int x = ctxPath.indexOf("/rstudio");
    int firstSlash = ctxPath.indexOf('/', x + 1);
    int secondSlash = ctxPath.indexOf('/', firstSlash + 1);
    String portString = ctxPath.substring(firstSlash + 1, secondSlash);
    Integer targetPort;
    try {
        targetPort = Integer.parseInt(portString);
    } catch (NumberFormatException ex) {
        logger.error("Invalid target port in the URL: " + portString);
        return;
    }
    urlBuf.append(portString);

    String newTargetUri = urlBuf.toString() + req.getRequestURI();

    StringBuilder newQueryBuf = new StringBuilder();
    newQueryBuf.append(newTargetUri);
    newQueryBuf.append(queryString);

    URI targetUriObj = null;
    try {
        targetUriObj = new URI(newQueryBuf.toString());
    } catch (Exception e) {
        throw new ServletException("Rewritten targetUri is invalid: " + newTargetUri, e);
    }
    ServiceProxy sp = new ServiceProxy(new ServiceProxyKey(externalIp, "*", "*", -1), "localhost", targetPort);
    //    ServiceProxy sp = new ServiceProxy(
    //            new ServiceProxyKey(
    //                    externalIp, "*", "*", -1),
    //            "localhost", targetPort);
    sp.setTargetURL(newQueryBuf.toString());
    // only set external hostname in case admin console is used
    try {
        router = new HopsRouter(targetUriObj);
        router.add(sp);
        router.init();
        ProxyRule proxy = new ProxyRule(new ProxyRuleKey(-1));
        router.getRuleManager().addProxy(proxy, RuleManager.RuleDefinitionSource.MANUAL);
        router.getRuleManager().addProxy(sp, RuleManager.RuleDefinitionSource.MANUAL);
        new HopsServletHandler(req, resp, router.getTransport(), targetUriObj).run();
    } catch (Exception ex) {
        Logger.getLogger(RStudioMembraneServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:it.attocchi.utils.HttpClientUtils.java

public static String getFileNameFromUrl(String url, String paramName) {
    String res = null;//from  ww w  . j  av a 2 s  .  c o  m

    String baseName = "";
    String extension = "";
    if (paramName == null || paramName.isEmpty()) {
        baseName = FilenameUtils.getBaseName(url);
        extension = FilenameUtils.getExtension(url);

        res = FilenameUtils.getName(url);

    } else {
        String fileNameOnParam = null;
        List<NameValuePair> params = URLEncodedUtils.parse(url, Charset.defaultCharset());
        if (params != null)
            for (NameValuePair p : params) {
                if (p.getName().contains(paramName)) {
                    fileNameOnParam = p.getValue();
                    break;
                }
            }
        baseName = FilenameUtils.getBaseName(fileNameOnParam);
        extension = FilenameUtils.getExtension(fileNameOnParam);

        res = FilenameUtils.getName(fileNameOnParam);
    }

    return res;
}

From source file:org.cruk.genologics.api.jaxb.URIAdapter.java

/**
 * Escape a string before conversion to a URI and, according to setting,
 * remove the state parameter./*from  w ww. j av  a 2 s. c o  m*/
 *
 * @param v The URI in string form.
 *
 * @return The encoded URI.
 */
private String escapeString(String v) {
    if (v != null) {
        int queryStart = v.indexOf('?');
        if (queryStart >= 0) {
            List<NameValuePair> queryParts = URLEncodedUtils.parse(v.substring(queryStart + 1), UTF8);
            removeStateParameter(queryParts);

            v = v.substring(0, queryStart);
            if (!queryParts.isEmpty()) {
                v += '?' + URLEncodedUtils.format(queryParts, UTF8);
            }
        }
    }
    return v;
}

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

/**
 * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
 *///  ww  w .  j a v  a  2 s.co m
@BeforeClass
public static void startHttpd() throws Exception {
    logDir = createTempDir();
    httpServer = MockHttpServer
            .createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);

    httpServer.createContext("/", (s) -> {
        Headers headers = s.getResponseHeaders();
        headers.add("Content-Type", "text/xml; charset=UTF-8");
        String action = null;
        for (NameValuePair parse : URLEncodedUtils.parse(IOUtils.toString(s.getRequestBody()),
                StandardCharsets.UTF_8)) {
            if ("Action".equals(parse.getName())) {
                action = parse.getValue();
                break;
            }
        }
        assertThat(action, equalTo("DescribeInstances"));

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
        xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
        StringWriter out = new StringWriter();
        XMLStreamWriter sw;
        try {
            sw = xmlOutputFactory.createXMLStreamWriter(out);
            sw.writeStartDocument();

            String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/";
            sw.setDefaultNamespace(namespace);
            sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace);
            {
                sw.writeStartElement("requestId");
                sw.writeCharacters(UUID.randomUUID().toString());
                sw.writeEndElement();

                sw.writeStartElement("reservationSet");
                {
                    Path[] files = FileSystemUtils.files(logDir);
                    for (int i = 0; i < files.length; i++) {
                        Path resolve = files[i].resolve("transport.ports");
                        if (Files.exists(resolve)) {
                            List<String> addresses = Files.readAllLines(resolve);
                            Collections.shuffle(addresses, random());

                            sw.writeStartElement("item");
                            {
                                sw.writeStartElement("reservationId");
                                sw.writeCharacters(UUID.randomUUID().toString());
                                sw.writeEndElement();

                                sw.writeStartElement("instancesSet");
                                {
                                    sw.writeStartElement("item");
                                    {
                                        sw.writeStartElement("instanceId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("imageId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceState");
                                        {
                                            sw.writeStartElement("code");
                                            sw.writeCharacters("16");
                                            sw.writeEndElement();

                                            sw.writeStartElement("name");
                                            sw.writeCharacters("running");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateDnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("dnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceType");
                                        sw.writeCharacters("m1.medium");
                                        sw.writeEndElement();

                                        sw.writeStartElement("placement");
                                        {
                                            sw.writeStartElement("availabilityZone");
                                            sw.writeCharacters("use-east-1e");
                                            sw.writeEndElement();

                                            sw.writeEmptyElement("groupName");

                                            sw.writeStartElement("tenancy");
                                            sw.writeCharacters("default");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateIpAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("ipAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();

            sw.writeEndDocument();
            sw.flush();

            final byte[] responseAsBytes = out.toString().getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(200, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        } catch (XMLStreamException e) {
            Loggers.getLogger(Ec2DiscoveryClusterFormationTests.class).error("Failed serializing XML", e);
            throw new RuntimeException(e);
        }
    });

    httpServer.start();
}

From source file:org.apache.marmotta.ldclient.provider.phpbb.PHPBBTopicProvider.java

/**
 * Return a mapping table mapping from RDF properties to XPath Value Mappers. Each entry in the map is evaluated
 * in turn; in case the XPath expression yields a result, the property is added for the processed resource.
 *
 * @return/* w w w . jav a  2 s  . c  o  m*/
 * @param requestUrl
 */
@Override
protected Map<String, JSoupMapper> getMappings(String resource, String requestUrl) {
    URI uri = null;
    try {
        uri = new URI(requestUrl);
        Map<String, String> params = new HashMap<String, String>();
        for (NameValuePair p : URLEncodedUtils.parse(uri, "UTF-8")) {
            params.put(p.getName(), p.getValue());
        }

        if (params.containsKey("t")) {

            Map<String, JSoupMapper> postMappings = new HashMap<String, JSoupMapper>();
            if (params.containsKey("start")) {
                // when start is set, we only take the replies; we are in a second or further page of the topic
                postMappings.put(Namespaces.NS_SIOC + "container_of",
                        new PHPBBPostIdMapper("div#pagecontent table td.gensmall a[name]"));
            } else {
                // otherwise we also take the initial title, creator and date for the topic
                postMappings.put(Namespaces.NS_DC + "title",
                        new CssTextLiteralMapper("div#pageheader a.titles"));
                postMappings.put(Namespaces.NS_DC + "creator",
                        new CssTextLiteralMapper(new CssSelectorMapper.Selector() {
                            @Override
                            public Elements select(Element node) {
                                final Element first = node.select("div#pagecontent table b.postauthor").first();
                                if (first != null)
                                    return new Elements(first);
                                return new Elements();
                            }
                        }));
                postMappings.put(Namespaces.NS_DC + "date",
                        new PHPBBDateMapper("div#pagecontent table td.gensmall div") {
                            @Override
                            public Elements select(Element htmlDoc) {
                                final Elements sel = super.select(htmlDoc);
                                if (sel.size() > 0) {
                                    final Element e = sel.get(1);
                                    if (e != null)
                                        return new Elements(e);
                                }
                                return new Elements();
                            }
                        });
                postMappings.put(Namespaces.NS_SIOC + "has_container",
                        new PHPBBForumHrefMapper("p.breadcrumbs a") {
                            @Override
                            public Elements select(Element htmlDoc) {
                                final Element select = super.select(htmlDoc).last();
                                return select != null ? new Elements(select) : new Elements();
                            }
                        });
                postMappings.put(Namespaces.NS_SIOC + "container_of",
                        new PHPBBPostIdMapper("div#pagecontent table td.gensmall a[name]"));
            }

            return postMappings;
        } else
            throw new RuntimeException(
                    "the requested resource does not seem to identify a PHPBB topic (t=... parameter missing)");

    } catch (URISyntaxException e) {
        throw new RuntimeException(
                "the requested resource does not seem to identify a PHPBB topic (URI syntax error)");
    }

}

From source file:com.soft160.app.blobstore.HttpMessageHandler.java

private void Put(HttpExchange he) throws IOException, RocksDBException {
    List<NameValuePair> pairs = URLEncodedUtils.parse(he.getRequestURI().getQuery(), StandardCharsets.UTF_8);
    UUID bucket = null, file = null;
    for (NameValuePair pair : pairs) {
        if (pair.getName().equalsIgnoreCase("bucket")) {
            bucket = parseUUID(pair.getValue());
        } else if (pair.getName().equalsIgnoreCase("blob")) {
            file = parseUUID(pair.getValue());
        }/*  ww  w .ja  v a  2 s  .  co m*/
    }
    if (bucket == null || file == null) {
        SendResponse(he, HttpStatus.SC_BAD_REQUEST, "Unknown bucket/file");
    }

    String tmpName = UUID.randomUUID().toString() + ".tmp";
    File tmpFile = File.createTempFile(tmpName, "", tmpFileDir);

    try (FileOutputStream tmpStream = new FileOutputStream(tmpFile)) {
        IOUtils.copy(he.getRequestBody(), tmpStream);
    }
    if (localStore.AddBlob(bucket, file, tmpFile)) {
        SendResponse(he, HttpStatus.SC_OK, null);
    } else {
        SendResponse(he, HttpStatus.SC_BAD_REQUEST, "Insert error");
    }

}

From source file:com.alibaba.dubbo.rpc.protocol.springmvc.support.ApacheHttpClient.java

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);
    }//from   www.j a v a2  s .  c  om

    //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();
}