Example usage for javax.servlet.http HttpServletRequest setAttribute

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

Introduction

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

Prototype

public void setAttribute(String name, Object o);

Source Link

Document

Stores an attribute in this request.

Usage

From source file:com.redhat.rhn.frontend.action.kickstart.PowerManagementAction.java

/**
 * Sets up and returns a list of supported Cobbler power types.
 * @param request the current request/*from  w w w  .  java2s  .c o  m*/
 * @param strutsDelegate the Struts delegate
 * @param errors ActionErrors that might have already been raised
 * @return the types
 */
public static SortedMap<String, String> setUpPowerTypes(HttpServletRequest request,
        StrutsDelegate strutsDelegate, ActionErrors errors) {
    SortedMap<String, String> types = new TreeMap<String, String>();
    String typeString = ConfigDefaults.get().getCobblerPowerTypes();
    if (typeString != null) {
        List<String> typeNames = Arrays.asList(typeString.split(" *, *"));
        for (String typeName : typeNames) {
            types.put(LocalizationService.getInstance().getPlainText("cobbler.powermanagement." + typeName),
                    typeName);
        }
    }
    request.setAttribute(TYPES, types);

    if (types.size() == 0) {
        strutsDelegate.addError(errors, "kickstart.powermanagement.jsp.no_types",
                ConfigDefaults.POWER_MANAGEMENT_TYPES);
        strutsDelegate.saveMessages(request, errors);
    }
    return types;
}

From source file:com.mmd.mssp.util.WebUtil.java

public static String getHttpQueryParam(HttpServletRequest request, String key)
        throws UnsupportedEncodingException {
    String val, ie = request.getParameter("ie");
    String ua = request.getHeader("User-Agent");
    if (ua != null && ua.contains("MSIE")) {//IE  GBK ?
        if (ie != null) {
            try {
                val = WebUtil.getHttpQueryParam(request, key, ie);
            } catch (UnsupportedEncodingException ex) {
                val = WebUtil.getHttpQueryParam(request, key, "UTF-8");
            }/*from  w ww .  j av  a2 s .c om*/
        } else {
            val = WebUtil.getHttpQueryParam(request, key, "GBK");
        }
    } else {
        val = WebUtil.getHttpQueryParam(request, key, "UTF-8");
    }
    request.setAttribute("QueryValue", val);
    //      val = val.replaceAll("\\\\", "\\\\\\\\").replaceAll("%", "\\\\%").replaceAll("_", "\\\\_");
    return val;
}

From source file:architecture.ee.web.community.spring.controller.SocialConnectController.java

protected static void setOutputFormat(NativeWebRequest request) {
    HttpServletRequest httprequest = request.getNativeRequest(HttpServletRequest.class);
    HttpServletResponse httpresponse = request.getNativeResponse(HttpServletResponse.class);
    httprequest.setAttribute("output", "json");
}

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

/**
 * Parse GitHub login response and login the user if possible.
 * /*  w  ww.ja  v  a2s . c om*/
 * @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:com.swiftcorp.portal.common.util.WebUtils.java

public static void setFailureMessages(HttpServletRequest request, String[] messageKeys,
        String messageArgValues) {
    if (messageKeys == null || messageKeys.length == 0) {
        theLogger.error("messageKeys cant null or empty");
        throw new RuntimeException("messageKeys cant null or empty");
    }//w  w w.  j a  v a2  s . c o  m

    ActionMessages actionMessages = new ActionMessages();

    for (String messageKey : messageKeys) {
        String value = null;
        value = messageArgValues;
        ActionMessage actionMessage = new ActionMessage(messageKey, value);
        actionMessages.add(ActionMessages.GLOBAL_MESSAGE, actionMessage);
    }
    request.setAttribute(Globals.ERROR_KEY, actionMessages);
}

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

/**
 * Parse LinkedIn login response and login the user if possible.
 * /*w  w  w.  jav a2s  .  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.apache.ofbiz.passport.event.GitHubEvents.java

public static GenericValue getOAuth2GitHubConfig(HttpServletRequest request) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String productStoreId = ProductStoreWorker.getProductStoreId(request);
    try {//from  w  w w  .  ja v  a2s  .  c o  m
        return getOAuth2GitHubConfig(delegator, productStoreId);
    } catch (GenericEntityException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.toString());
        String errMsg = UtilProperties.getMessage(resource, "GetOAuth2GitHubError", messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
    }
    return null;
}

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

public static GenericValue getOAuth2LinkedInConfig(HttpServletRequest request) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String productStoreId = ProductStoreWorker.getProductStoreId(request);
    try {//from  w  ww  .jav a2s. c o m
        return getOAuth2LinkedInConfig(delegator, productStoreId);
    } catch (GenericEntityException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.toString());
        String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInError", messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
    }
    return null;
}

From source file:com.liferay.portal.struts.StrutsUtil.java

public static void forward(String uri, ServletContext ctx, HttpServletRequest req, HttpServletResponse res)
        throws ServletException {

    if (!res.isCommitted()) {
        String path = Constants.TEXT_HTML_DIR + uri;
        if (BrowserSniffer.is_wml(req)) {
            path = Constants.TEXT_WML_DIR + uri;
        }/*from w w w .ja  v  a2  s.  c om*/

        ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX));

        if (portalCtx == null) {
            portalCtx = ctx;
        }

        RequestDispatcher rd = portalCtx.getRequestDispatcher(path);

        try {
            rd.forward(req, res);
        } catch (IOException ioe1) {
            Logger.error(StrutsUtil.class, ioe1.getMessage(), ioe1);
        } catch (ServletException se1) {
            req.setAttribute(PageContext.EXCEPTION, se1.getRootCause());

            String errorPath = Constants.TEXT_HTML_DIR + Constants.COMMON_ERROR;
            if (BrowserSniffer.is_wml(req)) {
                path = Constants.TEXT_WML_DIR + Constants.COMMON_ERROR;
            }

            rd = portalCtx.getRequestDispatcher(errorPath);

            try {
                rd.forward(req, res);
            } catch (IOException ioe2) {
                Logger.error(StrutsUtil.class, ioe2.getMessage(), ioe2);
            } catch (ServletException se2) {
                throw se2;
            }
        }
    } else {
        _log.warn(uri + " is already committed");
    }
}

From source file:common.web.controller.CommonActions.java

/**
 * executes an update, serves as a template method that incapsulates common logic for update action
 * @param service//from w w  w.j  ava 2 s. c om
 * @param config
 * @param val
 * @param req
 * @return false if id cannot be converted to long or where is no command with an appropriate id
 */
public static <T> boolean doUpdate(IUpdateService<T, Long> service, IControllerConfig config,
        ABindValidator val, HttpServletRequest req) {
    Long id = RequestUtils.getLongParam(req, "id");
    T command = null;
    if (id != null) {
        command = service.getUpdateBean(id);
    }
    if (id == null || command == null) {
        common.CommonAttributes.addErrorMessage("form_errors", req);
        return false;
    }

    String action = req.getParameter(ControllerConfig.ACTION_PARAM_NAME);
    RequestUtils.copyRequestAttributesFromMap(req, service.initUpdate());

    if ("update".equals(action)) {
        /** bind command */
        BindingResult res = val.bindAndValidate(command, req);
        if (res.hasErrors()) {
            //m.putAll(res.getModel());
            req.setAttribute(res.MODEL_KEY_PREFIX + config.getContentDataAttribute(), res);
            req.setAttribute(config.getContentDataAttribute(), command);
            common.CommonAttributes.addErrorMessage("form_errors", req);
        } else {
            service.update(command);
            req.setAttribute(config.getContentDataAttribute(), command);
            common.CommonAttributes.addHelpMessage("operation_succeed", req);
        }
    } else {
        req.setAttribute(config.getContentDataAttribute(), command);
    }
    return true;
}