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.subgraph.vega.internal.model.web.WebModel.java

private List<NameValuePair> uriToParameterList(URI uri) {
    return URLEncodedUtils.parse(uri, "UTF-8");
}

From source file:org.surfnet.oaaas.selenium.AuthorizationCodeRequestHandler.java

private Map<String, String> getParamsFromUri(String uri) {
    String query = URI.create(uri).getRawQuery();
    List<NameValuePair> pairs = URLEncodedUtils.parse(query, Charset.forName("UTF-8"));

    Map<String, String> map = new HashMap<String, String>();
    for (NameValuePair p : pairs) {
        map.put(p.getName(), p.getValue());
    }/* www . ja v  a  2s  .c  om*/
    return map;
}

From source file:org.eclipse.cft.server.core.internal.ssh.SshClientSupport.java

public String getSshCode() {
    try {/*from ww  w  . ja v  a2s. c o  m*/
        URIBuilder builder = new URIBuilder(authorizationUrl + "/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);
    }
}

From source file:uk.org.openeyes.oink.hl7v2.A19Processor.java

private String getQueryParameterValue(OINKRequestMessage request, String key) {
    List<NameValuePair> params = URLEncodedUtils.parse(request.getParameters(), Charset.forName("UTF-8"));
    for (NameValuePair param : params) {
        if (param.getName().equals(key)) {
            String value = param.getValue();
            return value;
        }/*from  w  w w. j  a  v a2  s.c o  m*/
    }
    return null;
}

From source file:com.lucidworks.security.authentication.server.PseudoAuthenticationHandler.java

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();
            }//w w  w.j  av  a  2  s  .co m
        }
    }
    return null;
}

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

protected ModelAndView processNativeAuth(Device device, HttpServletRequest request,
        HttpServletResponse response, String authority) throws UnsupportedEncodingException {
    Map<String, Object> model = new HashMap<String, Object>();
    String clientId = request.getParameter(OAuth2Utils.CLIENT_ID);
    if (clientId == null || clientId.isEmpty()) {
        model.put("message", "Missing client_id");
        return new ModelAndView("oauth_error", model);
    }// w  w w  .jav  a  2 s  . com
    // each time create new OAuth request
    ClientAppBasic client = clientDetailsAdapter.getByClientId(clientId);
    AACOAuthRequest oauthRequest = new AACOAuthRequest(request, device, client.getScope(),
            client.getDisplayName());

    List<NameValuePair> pairs = URLEncodedUtils
            .parse(URI.create(request.getRequestURI() + "?" + request.getQueryString()), "UTF-8");

    String target = prepareRedirect(request, "/oauth/authorize");
    it.smartcommunitylab.aac.model.User userEntity = providerServiceAdapter.updateNativeUser(authority,
            request.getParameter("token"), toMap(pairs));
    List<GrantedAuthority> list = roleManager.buildAuthorities(userEntity);

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

    if (rememberMeServices != null) {
        rememberMeServices.loginSuccess(request, response, a);
    }

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

From source file:net.wasdev.gameon.auth.github.GitHubCallback.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //ok, we have our code.. so the user has agreed to our app being authed.
    String code = request.getParameter("code");

    String state = (String) request.getSession().getAttribute("github");

    //now we need to invoke the access_token endpoint to swap the code for a token.
    StringBuffer callbackURL = request.getRequestURL();
    int index = callbackURL.lastIndexOf("/");
    callbackURL.replace(index, callbackURL.length(), "").append("/GitHubCallback");

    HttpRequestFactory requestFactory;/*from w w  w . j a  va2 s. c  o m*/
    try {
        //we'll ignore the ssl cert of the github server for now.. 
        //eventually we may add this to the player truststore.. 
        requestFactory = new NetHttpTransport.Builder().doNotValidateCertificate().build()
                .createRequestFactory();

        //prepare the request.. 
        GenericUrl url = new GenericUrl("https://github.com/login/oauth/access_token");
        //set the client id & secret from the injected environment.
        url.put("client_id", key);
        url.put("client_secret", secret);
        //add the code we just got given.. 
        url.put("code", code);
        url.put("redirect_uri", callbackURL);
        url.put("state", state);

        //now place the request to github..
        HttpRequest infoRequest = requestFactory.buildGetRequest(url);
        HttpResponse r = infoRequest.execute();
        String resp = "failed.";
        if (r.isSuccessStatusCode()) {

            //response comes back as query param encoded data.. we'll grab the token from that...
            resp = r.parseAsString();

            //http client way to parse query params.. 
            List<NameValuePair> params = URLEncodedUtils.parse(resp, Charset.forName("UTF-8"));
            String token = null;
            for (NameValuePair param : params) {
                if ("access_token".equals(param.getName())) {
                    token = param.getValue();
                }
            }

            if (token != null) {
                //great, we have a token, now we can use that to request the user profile..                    
                GenericUrl query = new GenericUrl("https://api.github.com/user");
                query.put("access_token", token);

                HttpRequest userRequest = requestFactory.buildGetRequest(query);
                HttpResponse u = userRequest.execute();
                if (u.isSuccessStatusCode()) {
                    //user profile comes back as json..                         
                    resp = u.parseAsString();
                    System.out.println(resp);

                    //use om to parse the json, so we can grab the id & name from it.
                    ObjectMapper om = new ObjectMapper();
                    JsonNode jn = om.readValue(resp, JsonNode.class);

                    Map<String, String> claims = new HashMap<String, String>();
                    claims.put("valid", "true");
                    //github id is a number, but we'll read it as text incase it changes in future.. 
                    claims.put("id", "github:" + jn.get("id").asText());
                    claims.put("name", jn.get("login").textValue());

                    String jwt = createJwt(claims);

                    //log for now, we'll clean this up once it's all working =)
                    System.out.println("New User Authed: " + claims.get("id") + " jwt " + jwt);
                    response.sendRedirect(callbackSuccess + "/" + jwt);

                } else {
                    System.out.println(u.getStatusCode());
                    response.sendRedirect("http://game-on.org/#/game");
                }
            } else {
                System.out.println("did not find token in github response " + resp);
                response.sendRedirect("http://game-on.org/#/game");
            }
        } else {
            response.sendRedirect("http://game-on.org/#/game");
        }

    } catch (GeneralSecurityException e) {
        throw new ServletException(e);
    }

}

From source file:org.gameontext.auth.github.GitHubCallback.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //ok, we have our code.. so the user has agreed to our app being authed.
    String code = request.getParameter("code");

    String state = (String) request.getSession().getAttribute("github");

    //now we need to invoke the access_token endpoint to swap the code for a token.
    String callbackURL = authURL + "/GitHubCallback";

    HttpRequestFactory requestFactory;/*from  w  ww .  ja  v a  2  s.co  m*/
    try {
        //we'll ignore the ssl cert of the github server for now..
        //eventually we may add this to the player truststore..
        requestFactory = new NetHttpTransport.Builder().doNotValidateCertificate().build()
                .createRequestFactory();

        //prepare the request..
        GenericUrl url = new GenericUrl("https://github.com/login/oauth/access_token");
        //set the client id & secret from the injected environment.
        url.put("client_id", key);
        url.put("client_secret", secret);
        //add the code we just got given..
        url.put("code", code);
        url.put("redirect_uri", callbackURL);
        url.put("state", state);

        //now place the request to github..
        HttpRequest infoRequest = requestFactory.buildGetRequest(url);
        HttpResponse r = infoRequest.execute();
        String resp = "failed.";
        if (r.isSuccessStatusCode()) {

            //response comes back as query param encoded data.. we'll grab the token from that...
            resp = r.parseAsString();

            //http client way to parse query params..
            List<NameValuePair> params = URLEncodedUtils.parse(resp, Charset.forName("UTF-8"));
            String token = null;
            for (NameValuePair param : params) {
                if ("access_token".equals(param.getName())) {
                    token = param.getValue();
                }
            }

            if (token != null) {
                //great, we have a token, now we can use that to request the user profile..
                GenericUrl query = new GenericUrl("https://api.github.com/user");
                query.put("access_token", token);

                HttpRequest userRequest = requestFactory.buildGetRequest(query);
                HttpResponse u = userRequest.execute();
                if (u.isSuccessStatusCode()) {
                    //user profile comes back as json..
                    resp = u.parseAsString();

                    //use om to parse the json, so we can grab the id & name from it.
                    ObjectMapper om = new ObjectMapper();
                    JsonNode jn = om.readValue(resp, JsonNode.class);

                    Map<String, String> claims = new HashMap<String, String>();
                    claims.put("valid", "true");
                    //github id is a number, but we'll read it as text incase it changes in future..
                    claims.put("id", "github:" + jn.get("id").asText());
                    claims.put("name", jn.get("login").textValue());

                    GenericUrl emailQuery = new GenericUrl("https://api.github.com/user/emails");
                    emailQuery.put("access_token", token);
                    HttpRequest emailRequest = requestFactory.buildGetRequest(emailQuery);
                    HttpResponse er = emailRequest.execute();

                    claims.put("email", "unknown");
                    if (er.isSuccessStatusCode()) {
                        resp = er.parseAsString();
                        JsonNode en = om.readValue(resp, JsonNode.class);
                        if (en.isArray()) {
                            for (JsonNode email : en) {
                                Boolean primary = Boolean.valueOf(email.get("primary").booleanValue());
                                if (primary) {
                                    claims.put("email", email.get("email").textValue());
                                }
                            }
                        }
                    }

                    String jwt = createJwt(claims);

                    //log for now, we'll clean this up once it's all working =)
                    System.out.println("New User Authed: " + claims.get("id") + " jwt " + jwt);
                    response.sendRedirect(callbackSuccess + "/" + jwt);

                } else {
                    System.out.println(u.getStatusCode());
                    response.sendRedirect(callbackFailure);
                }
            } else {
                System.out.println("did not find token in github response " + resp);
                response.sendRedirect(callbackFailure);
            }
        } else {
            response.sendRedirect(callbackFailure);
        }

    } catch (GeneralSecurityException e) {
        throw new ServletException(e);
    }

}

From source file:com.devicehive.model.oauth.GithubAuthProvider.java

private String getAccessToken(final String code) {
    final String endpoint = identityProvider.getTokenEndpoint();
    Map<String, String> params = new HashMap<>();
    params.put("code", code);
    params.put("client_id", configurationService.get(Constants.GITHUB_IDENTITY_CLIENT_ID));
    params.put("client_secret", configurationService.get(Constants.GITHUB_IDENTITY_CLIENT_SECRET));
    final String response = identityProviderUtils.executePost(new NetHttpTransport(), params, endpoint,
            GITHUB_PROVIDER_NAME);// w  w w. j a  v a2 s .  c o  m
    List<NameValuePair> responseParams = URLEncodedUtils.parse(response, Charset.forName(Constants.UTF8));
    if (!"access_token".equals(responseParams.get(0).getName())) {
        logger.error("Exception has been caught during Identity Provider GET request execution", response);
        throw new HiveException(
                String.format(Messages.GETTING_OAUTH_ACCESS_TOKEN_FAILED, GITHUB_PROVIDER_NAME, response),
                Response.Status.UNAUTHORIZED.getStatusCode());
    }
    return responseParams.get(0).getValue();
}