Example usage for javax.servlet.http HttpServletRequest getParameter

List of usage examples for javax.servlet.http HttpServletRequest getParameter

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getParameter.

Prototype

public String getParameter(String name);

Source Link

Document

Returns the value of a request parameter as a String, or null if the parameter does not exist.

Usage

From source file:org.wuspba.ctams.ui.server.DataUtils.java

protected static CTAMSDocument getJudge(HttpServletRequest request) {

    Judge judge = new Judge();
    judge.setId(request.getParameter("id"));
    URIBuilder builder = new URIBuilder().setScheme(ServerUtils.PROTOCOL).setHost(ServerUtils.HOST)
            .setPort(ServerUtils.PORT).setParameter("firstname", request.getParameter("firstName"))
            .setParameter("lastname", request.getParameter("lastName")).setPath(ServerUtils.URI + "/person");

    try {//from w w  w . j ava2  s.  c o m
        String xml = ServerUtils.get(builder.build());
        CTAMSDocument people = XMLUtils.unmarshal(xml);
        judge.setPerson(people.getPeople().get(0));
    } catch (IOException ex) {
        LOG.error("Error finding band", ex);
    } catch (URISyntaxException uex) {
        LOG.error("Invalide URI", uex);
    }

    String qualString = request.getParameter("qualification");
    if (qualString != null) {
        String[] quals = qualString.split(",");
        for (String qual : quals) {
            String[] spl = qual.split("\\:");
            JudgeQualification qualification = new JudgeQualification();
            qualification.setType(JudgeType.valueOf(spl[0]));
            qualification.setPanel(JudgePanelType.valueOf(spl[1]));
            judge.getQualifications().add(qualification);
        }
    }

    CTAMSDocument doc = new CTAMSDocument();
    doc.getJudges().add(judge);

    return doc;
}

From source file:net.naijatek.myalumni.util.utilities.ParamUtil.java

public static String getParameter(final HttpServletRequest request, final String param) {
    String ret = request.getParameter(param);
    if (ret == null) {
        ret = "";
    }//from  ww w  . ja va  2  s .  c o m
    return ret.trim();
}

From source file:org.apache.ofbiz.passport.event.GitHubEvents.java

/**
 * Parse GitHub login response and login the user if possible.
 * //  www.  j ava2 s  . c o m
 * @return 
 */
public static String parseGitHubResponse(HttpServletRequest request, HttpServletResponse response) {
    String authorizationCode = request.getParameter(PassportUtil.COMMON_CODE);
    String state = request.getParameter(PassportUtil.COMMON_STATE);
    if (!state.equals(request.getSession().getAttribute(SESSION_GITHUB_STATE))) {
        String errMsg = UtilProperties.getMessage(resource, "GitHubFailedToMatchState",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    if (UtilValidate.isEmpty(authorizationCode)) {
        String error = request.getParameter(PassportUtil.COMMON_ERROR);
        String errorDescpriton = request.getParameter(PassportUtil.COMMON_ERROR_DESCRIPTION);
        String errMsg = null;
        try {
            errMsg = UtilProperties.getMessage(resource, "FailedToGetGitHubAuthorizationCode",
                    UtilMisc.toMap(PassportUtil.COMMON_ERROR, error, PassportUtil.COMMON_ERROR_DESCRIPTION,
                            URLDecoder.decode(errorDescpriton, "UTF-8")),
                    UtilHttp.getLocale(request));
        } catch (UnsupportedEncodingException e) {
            errMsg = UtilProperties.getMessage(resource, "GetGitHubAuthorizationCodeError",
                    UtilHttp.getLocale(request));
        }
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    Debug.logInfo("GitHub authorization code: " + authorizationCode, module);

    GenericValue oauth2GitHub = getOAuth2GitHubConfig(request);
    if (UtilValidate.isEmpty(oauth2GitHub)) {
        String errMsg = UtilProperties.getMessage(resource, "GetOAuth2GitHubConfigError",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    String clientId = oauth2GitHub.getString(PassportUtil.COMMON_CLIENT_ID);
    String secret = oauth2GitHub.getString(PassportUtil.COMMON_CLIENT_SECRET);
    String returnURI = oauth2GitHub.getString(PassportUtil.COMMON_RETURN_RUL);

    // Grant token from authorization code and oauth2 token
    // Use the authorization code to obtain an access token
    String accessToken = null;
    String tokenType = null;

    try {
        URI uri = new URIBuilder().setScheme(TokenEndpoint.substring(0, TokenEndpoint.indexOf(":")))
                .setHost(TokenEndpoint.substring(TokenEndpoint.indexOf(":") + 3)).setPath(TokenServiceUri)
                .setParameter("client_id", clientId).setParameter("client_secret", secret)
                .setParameter("code", authorizationCode).setParameter("redirect_uri", returnURI).build();
        HttpPost postMethod = new HttpPost(uri);
        CloseableHttpClient jsonClient = HttpClients.custom().build();
        // Debug.logInfo("GitHub get access token query string: " + postMethod.getURI(), module);
        postMethod.setConfig(PassportUtil.StandardRequestConfig);
        postMethod.setHeader(PassportUtil.ACCEPT_HEADER, "application/json");
        CloseableHttpResponse postResponse = jsonClient.execute(postMethod);
        String responseString = new BasicResponseHandler().handleResponse(postResponse);
        // Debug.logInfo("GitHub get access token response code: " + postResponse.getStatusLine().getStatusCode(), module);
        // Debug.logInfo("GitHub get access token response content: " + responseString, module);
        if (postResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            Debug.logInfo("Json Response from GitHub: " + responseString, module);
            JSON jsonObject = JSON.from(responseString);
            JSONToMap jsonMap = new JSONToMap();
            Map<String, Object> userMap = jsonMap.convert(jsonObject);
            accessToken = (String) userMap.get("access_token");
            tokenType = (String) userMap.get("token_type");
            // Debug.logInfo("Generated Access Token : " + accessToken, module);
            // Debug.logInfo("Token Type: " + tokenType, module);
        } else {
            String errMsg = UtilProperties.getMessage(resource, "GetOAuth2GitHubAccessTokenError",
                    UtilMisc.toMap("error", responseString), UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
    } catch (UnsupportedEncodingException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (IOException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (ConversionException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (URISyntaxException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    }

    // Get User Profile
    HttpGet getMethod = new HttpGet(ApiEndpoint + UserApiUri);
    Map<String, Object> userInfo = null;
    try {
        userInfo = GitHubAuthenticator.getUserInfo(getMethod, accessToken, tokenType,
                UtilHttp.getLocale(request));
    } catch (AuthenticatorException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } finally {
        getMethod.releaseConnection();
    }
    // Debug.logInfo("GitHub User Info:" + userInfo, module);

    // Store the user info and check login the user
    return checkLoginGitHubUser(request, userInfo, accessToken);
}

From source file:edu.utah.further.i2b2.hook.further.web.ServletUtil.java

/**
 * @param request//ww w  .  ja v a  2  s . com
 */
public static void printRequestParameters(final HttpServletRequest request) {
    log.debug("Request parameters:");
    final Enumeration<?> parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        final String name = (String) parameterNames.nextElement();
        log.debug(name + " = " + request.getParameter(name));
    }
}

From source file:com.glaf.core.util.HttpQueryUtils.java

public static String getParameter(HttpServletRequest request, String name) {
    String value = request.getParameter(name);
    if (StringUtils.isEmpty(value)) {
        String[] values = request.getParameterValues(name);
        if (values != null && values.length > 0) {
            StringBuffer buff = new StringBuffer(1000);
            for (int i = 0; i < values.length; i++) {
                if (i < values.length - 1) {
                    if (StringUtils.isNotEmpty(values[i])) {
                        buff.append(values[i]).append(',');
                    }//from  ww w.  ja v a2  s  .c  om
                } else {
                    if (StringUtils.isNotEmpty(values[i])) {
                        buff.append(values[i]);
                    }
                }
            }
            if (StringUtils.isNotEmpty(buff.toString())) {
                value = buff.toString();
            }
        }
    }
    return value;
}

From source file:jp.opencollector.guacamole.auth.delegated.DelegatedAuthenticationProvider.java

private static Optional<GuacamoleConfiguration> buildConfigurationFromRequest(HttpServletRequest req)
        throws GuacamoleException {
    try {// ww  w .j  av a 2 s. co m
        if (req.getClass().getName().equals("org.glyptodon.guacamole.net.basic.rest.APIRequest")) {
            final GuacamoleConfiguration config = new GuacamoleConfiguration();
            final String protocol = req.getParameter("protocol");
            if (protocol == null)
                throw new GuacamoleException("required parameter \"protocol\" is missing");
            config.setProtocol(protocol);
            for (Map.Entry<String, String[]> param : req.getParameterMap().entrySet()) {
                String[] values = param.getValue();
                if (values.length > 0)
                    config.setParameter(param.getKey(), values[0]);
            }
            return Optional.of(config);
        } else {
            final ServletInputStream is = req.getInputStream();
            if (!is.isReady()) {
                MediaType contentType = MediaType.parse(req.getContentType());
                boolean invalidContentType = true;
                if (contentType.type().equals("application")) {
                    if (contentType.subtype().equals("json")) {
                        invalidContentType = false;
                    } else if (contentType.subtype().equals("x-www-form-urlencoded")
                            && req.getParameter("token") != null) {
                        return Optional.<GuacamoleConfiguration>absent();
                    }
                }
                if (invalidContentType)
                    throw new GuacamoleException(String.format("expecting application/json, got %s",
                            contentType.withoutParameters()));
                final GuacamoleConfiguration config = new GuacamoleConfiguration();
                try {
                    final ObjectMapper mapper = new ObjectMapper();
                    JsonNode root = (JsonNode) mapper.readTree(
                            createJsonParser(req.getInputStream(), contentType.charset().or(UTF_8), mapper));
                    {
                        final JsonNode protocol = root.get("protocol");
                        if (protocol == null)
                            throw new GuacamoleException("required parameter \"protocol\" is missing");
                        final JsonNode parameters = root.get("parameters");
                        if (parameters == null)
                            throw new GuacamoleException("required parameter \"parameters\" is missing");
                        config.setProtocol(protocol.asText());
                        {
                            for (Iterator<Entry<String, JsonNode>> i = parameters.fields(); i.hasNext();) {
                                Entry<String, JsonNode> member = i.next();
                                config.setParameter(member.getKey(), member.getValue().asText());
                            }
                        }
                    }
                } catch (ClassCastException e) {
                    throw new GuacamoleException("error occurred during parsing configuration", e);
                }
                return Optional.of(config);
            } else {
                return Optional.<GuacamoleConfiguration>absent();
            }
        }
    } catch (IOException e) {
        throw new GuacamoleException("error occurred during retrieving configuration from the request body", e);
    }
}

From source file:org.apache.ofbiz.passport.event.LinkedInEvents.java

/**
 * Parse LinkedIn login response and login the user if possible.
 * /*from w  w w .  j  ava 2s .c  o m*/
 * @return 
 */
public static String parseLinkedInResponse(HttpServletRequest request, HttpServletResponse response) {
    String authorizationCode = request.getParameter(PassportUtil.COMMON_CODE);
    String state = request.getParameter(PassportUtil.COMMON_STATE);
    if (!state.equals(request.getSession().getAttribute(SESSION_LINKEDIN_STATE))) {
        String errMsg = UtilProperties.getMessage(resource, "LinkedInFailedToMatchState",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    if (UtilValidate.isEmpty(authorizationCode)) {
        String error = request.getParameter(PassportUtil.COMMON_ERROR);
        String errorDescpriton = request.getParameter(PassportUtil.COMMON_ERROR_DESCRIPTION);
        String errMsg = null;
        try {
            errMsg = UtilProperties.getMessage(resource, "FailedToGetLinkedInAuthorizationCode",
                    UtilMisc.toMap(PassportUtil.COMMON_ERROR, error, PassportUtil.COMMON_ERROR_DESCRIPTION,
                            URLDecoder.decode(errorDescpriton, "UTF-8")),
                    UtilHttp.getLocale(request));
        } catch (UnsupportedEncodingException e) {
            errMsg = UtilProperties.getMessage(resource, "GetLinkedInAuthorizationCodeError",
                    UtilHttp.getLocale(request));
        }
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    // Debug.logInfo("LinkedIn authorization code: " + authorizationCode, module);

    GenericValue oauth2LinkedIn = getOAuth2LinkedInConfig(request);
    if (UtilValidate.isEmpty(oauth2LinkedIn)) {
        String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInConfigError",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    String clientId = oauth2LinkedIn.getString(PassportUtil.ApiKeyLabel);
    String secret = oauth2LinkedIn.getString(PassportUtil.SecretKeyLabel);
    String returnURI = oauth2LinkedIn.getString(envPrefix + PassportUtil.ReturnUrlLabel);

    // Grant token from authorization code and oauth2 token
    // Use the authorization code to obtain an access token
    String accessToken = null;

    try {
        URI uri = new URIBuilder().setScheme(TokenEndpoint.substring(0, TokenEndpoint.indexOf(":")))
                .setHost(TokenEndpoint.substring(TokenEndpoint.indexOf(":") + 3)).setPath(TokenServiceUri)
                .setParameter("client_id", clientId).setParameter("client_secret", secret)
                .setParameter("grant_type", "authorization_code").setParameter("code", authorizationCode)
                .setParameter("redirect_uri", returnURI).build();
        HttpPost postMethod = new HttpPost(uri);
        CloseableHttpClient jsonClient = HttpClients.custom().build();
        // Debug.logInfo("LinkedIn get access token query string: " + postMethod.getURI(), module);
        postMethod.setConfig(PassportUtil.StandardRequestConfig);
        CloseableHttpResponse postResponse = jsonClient.execute(postMethod);
        String responseString = new BasicResponseHandler().handleResponse(postResponse);
        // Debug.logInfo("LinkedIn get access token response code: " + postResponse.getStatusLine().getStatusCode(), module);
        // Debug.logInfo("LinkedIn get access token response content: " + responseString, module);
        if (postResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // Debug.logInfo("Json Response from LinkedIn: " + responseString, module);
            JSON jsonObject = JSON.from(responseString);
            JSONToMap jsonMap = new JSONToMap();
            Map<String, Object> userMap = jsonMap.convert(jsonObject);
            accessToken = (String) userMap.get("access_token");
            // Debug.logInfo("Generated Access Token : " + accessToken, module);
        } else {
            String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInAccessTokenError",
                    UtilMisc.toMap("error", responseString), UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
    } catch (UnsupportedEncodingException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (IOException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (ConversionException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (URISyntaxException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    }

    // Get User Profile
    HttpGet getMethod = new HttpGet(TokenEndpoint + UserApiUri + "?oauth2_access_token=" + accessToken);
    Document userInfo = null;
    try {
        userInfo = LinkedInAuthenticator.getUserInfo(getMethod, UtilHttp.getLocale(request));
    } catch (IOException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (AuthenticatorException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (SAXException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (ParserConfigurationException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } finally {
        getMethod.releaseConnection();
    }
    // Debug.logInfo("LinkedIn User Info:" + userInfo, module);

    // Store the user info and check login the user
    return checkLoginLinkedInUser(request, userInfo, accessToken);
}

From source file:org.oncoblocks.centromere.web.controller.RequestUtils.java

/**
 * Extracts the requested filtered fields parameter from a request.
 * // w  ww  .  j  av a  2s .  c o  m
 * @param request
 * @return
 */
public static Set<String> getFilteredFieldsFromRequest(HttpServletRequest request) {
    Set<String> fields = null;
    if (request.getParameterMap().containsKey("fields")) {
        fields = new HashSet<>();
        String[] params = request.getParameter("fields").split(",");
        for (String field : params) {
            fields.add(field.trim());
        }
    }
    return fields;
}

From source file:com.gtwm.pb.servlets.ServletDataMethods.java

/**
 * Get the value of a single parameter in a HTTP request, or null if the
 * parameter doesn't exist or is empty in the request. The parameter must be
 * integer//from   w  w  w  . j a v  a2s .c  om
 * 
 * @throws NumberFormatException
 *             If the parameter value isn't an integer
 */
public static Integer getIntegerParameterValue(HttpServletRequest request, String parameterName) {
    String parameterValueString = request.getParameter(parameterName);
    if (parameterValueString != null) {
        if (!parameterValueString.equals("")) {
            return Integer.valueOf(parameterValueString);
        }
    }
    return null;
}

From source file:org.oncoblocks.centromere.web.controller.RequestUtils.java

/**
 * Extracts the requested filtered fields parameter from a request.
 *
 * @param request/*from w w  w.j  a v  a  2s .com*/
 * @return
 */
public static Set<String> getExcludedFieldsFromRequest(HttpServletRequest request) {
    Set<String> exclude = null;
    if (request.getParameterMap().containsKey("exclude")) {
        exclude = new HashSet<>();
        String[] params = request.getParameter("exclude").split(",");
        for (String field : params) {
            exclude.add(field.trim());
        }
    }
    return exclude;
}