Example usage for javax.servlet.http HttpServletRequest getAttribute

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

Introduction

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

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.

Usage

From source file:com.ofbizcn.securityext.login.LoginEvents.java

/**
 *  Email the password for the userLoginId specified in the request object.
 *
 * @param request The HTTPRequest object for the current request
 * @param response The HTTPResponse object for the current request
 * @return String specifying the exit status of this event
 *///from   w w w.  j  av  a  2 s.  c  om
public static String emailPassword(HttpServletRequest request, HttpServletResponse response) {
    String defaultScreenLocation = "component://securityext/widget/EmailSecurityScreens.xml#PasswordEmail";

    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    String productStoreId = "";//ProductStoreWorker.getProductStoreId(request);

    String errMsg = null;

    boolean useEncryption = "true".equals(
            EntityUtilProperties.getPropertyValue("security.properties", "password.encrypt", delegator));

    String userLoginId = request.getParameter("USERNAME");

    if ((userLoginId != null) && ("true".equals(
            EntityUtilProperties.getPropertyValue("security.properties", "username.lowercase", delegator)))) {
        userLoginId = userLoginId.toLowerCase();
    }

    if (!UtilValidate.isNotEmpty(userLoginId)) {
        // the password was incomplete
        errMsg = UtilProperties.getMessage(resource, "loginevents.username_was_empty_reenter",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }

    GenericValue supposedUserLogin = null;
    String passwordToSend = null;

    try {
        supposedUserLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId)
                .queryOne();
        if (supposedUserLogin == null) {
            // the Username was not found
            errMsg = UtilProperties.getMessage(resource, "loginevents.username_not_found_reenter",
                    UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
        if (useEncryption) {
            // password encrypted, can't send, generate new password and email to user
            passwordToSend = RandomStringUtils.randomAlphanumeric(Integer.parseInt(
                    EntityUtilProperties.getPropertyValue("security", "password.length.min", "5", delegator)));
            if ("true".equals(EntityUtilProperties.getPropertyValue("security.properties", "password.lowercase",
                    delegator))) {
                passwordToSend = passwordToSend.toLowerCase();
            }
            supposedUserLogin.set("currentPassword",
                    HashCrypt.cryptUTF8(LoginServices.getHashType(), null, passwordToSend));
            supposedUserLogin.set("passwordHint", "Auto-Generated Password");
            if ("true".equals(EntityUtilProperties.getPropertyValue("security.properties",
                    "password.email_password.require_password_change", delegator))) {
                supposedUserLogin.set("requirePasswordChange", "Y");
            }
        } else {
            passwordToSend = supposedUserLogin.getString("currentPassword");
        }
    } catch (GenericEntityException e) {
        Debug.logWarning(e, "", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.toString());
        errMsg = UtilProperties.getMessage(resource, "loginevents.error_accessing_password", messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }

    StringBuilder emails = new StringBuilder();
    GenericValue party = null;

    try {
        party = supposedUserLogin.getRelatedOne("Party", false);
    } catch (GenericEntityException e) {
        Debug.logWarning(e, "", module);
        party = null;
    }
    if (party != null) {
        Iterator<GenericValue> emailIter = UtilMisc
                .toIterator(ContactHelper.getContactMechByPurpose(party, "PRIMARY_EMAIL", false));
        while (emailIter != null && emailIter.hasNext()) {
            GenericValue email = emailIter.next();
            emails.append(emails.length() > 0 ? "," : "").append(email.getString("infoString"));
        }
    }

    if (!UtilValidate.isNotEmpty(emails.toString())) {
        // the Username was not found
        errMsg = UtilProperties.getMessage(resource,
                "loginevents.no_primary_email_address_set_contact_customer_service",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }

    // get the ProductStore email settings
    GenericValue productStoreEmail = null;
    try {
        productStoreEmail = EntityQuery.use(delegator).from("ProductStoreEmailSetting")
                .where("productStoreId", productStoreId, "emailType", "PRDS_PWD_RETRIEVE").queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem getting ProductStoreEmailSetting", module);
    }

    String bodyScreenLocation = null;
    if (productStoreEmail != null) {
        bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation");
    }
    if (UtilValidate.isEmpty(bodyScreenLocation)) {
        bodyScreenLocation = defaultScreenLocation;
    }

    // set the needed variables in new context
    Map<String, Object> bodyParameters = FastMap.newInstance();
    bodyParameters.put("useEncryption", Boolean.valueOf(useEncryption));
    bodyParameters.put("password", UtilFormatOut.checkNull(passwordToSend));
    bodyParameters.put("locale", UtilHttp.getLocale(request));
    bodyParameters.put("userLogin", supposedUserLogin);
    bodyParameters.put("productStoreId", productStoreId);

    Map<String, Object> serviceContext = FastMap.newInstance();
    serviceContext.put("bodyScreenUri", bodyScreenLocation);
    serviceContext.put("bodyParameters", bodyParameters);
    if (productStoreEmail != null) {
        serviceContext.put("subject", productStoreEmail.getString("subject"));
        serviceContext.put("sendFrom", productStoreEmail.get("fromAddress"));
        serviceContext.put("sendCc", productStoreEmail.get("ccAddress"));
        serviceContext.put("sendBcc", productStoreEmail.get("bccAddress"));
        serviceContext.put("contentType", productStoreEmail.get("contentType"));
    } else {
        GenericValue emailTemplateSetting = null;
        try {
            emailTemplateSetting = EntityQuery.use(delegator).from("EmailTemplateSetting")
                    .where("emailTemplateSettingId", "EMAIL_PASSWORD").cache().queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (emailTemplateSetting != null) {
            String subject = emailTemplateSetting.getString("subject");
            subject = FlexibleStringExpander.expandString(subject, UtilMisc.toMap("userLoginId", userLoginId));
            serviceContext.put("subject", subject);
            serviceContext.put("sendFrom", emailTemplateSetting.get("fromAddress"));
        } else {
            serviceContext.put("subject",
                    UtilProperties.getMessage(resource, "loginservices.password_reminder_subject",
                            UtilMisc.toMap("userLoginId", userLoginId), UtilHttp.getLocale(request)));
            serviceContext.put("sendFrom", EntityUtilProperties.getPropertyValue("general.properties",
                    "defaultFromEmailAddress", delegator));
        }
    }
    serviceContext.put("sendTo", emails.toString());
    serviceContext.put("partyId", party.getString("partyId"));

    try {
        Map<String, Object> result = dispatcher.runSync("sendMailHiddenInLogFromScreen", serviceContext);

        if (ModelService.RESPOND_ERROR.equals(result.get(ModelService.RESPONSE_MESSAGE))) {
            Map<String, Object> messageMap = UtilMisc.toMap("errorMessage",
                    result.get(ModelService.ERROR_MESSAGE));
            errMsg = UtilProperties.getMessage(resource,
                    "loginevents.error_unable_email_password_contact_customer_service_errorwas", messageMap,
                    UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
    } catch (GenericServiceException e) {
        Debug.logWarning(e, "", module);
        errMsg = UtilProperties.getMessage(resource,
                "loginevents.error_unable_email_password_contact_customer_service",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }

    // don't save password until after it has been sent
    if (useEncryption) {
        try {
            supposedUserLogin.store();
        } catch (GenericEntityException e) {
            Debug.logWarning(e, "", module);
            Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.toString());
            errMsg = UtilProperties.getMessage(resource,
                    "loginevents.error_saving_new_password_email_not_correct_password", messageMap,
                    UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
    }

    if (useEncryption) {
        errMsg = UtilProperties.getMessage(resource, "loginevents.new_password_createdandsent_check_email",
                UtilHttp.getLocale(request));
        request.setAttribute("_EVENT_MESSAGE_", errMsg);
    } else {
        errMsg = UtilProperties.getMessage(resource, "loginevents.new_password_sent_check_email",
                UtilHttp.getLocale(request));
        request.setAttribute("_EVENT_MESSAGE_", errMsg);
    }
    return "success";
}

From source file:com.liferay.portal.servlet.filters.dynamiccss.DynamicCSSUtil.java

public static String parseSass(HttpServletRequest request, String cssRealPath, String content)
        throws Exception {

    if (!DynamicCSSFilter.ENABLED) {
        return content;
    }/*  ww  w .  j  av a 2s. c  o  m*/

    StopWatch stopWatch = null;

    if (_log.isDebugEnabled()) {
        stopWatch = new StopWatch();

        stopWatch.start();
    }

    // Request will only be null when called by StripFilterTest

    if (request == null) {
        return content;
    }

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    Theme theme = null;

    if (themeDisplay == null) {
        theme = _getTheme(request, cssRealPath);

        if (theme == null) {
            String currentURL = PortalUtil.getCurrentURL(request);

            if (_log.isWarnEnabled()) {
                _log.warn("No theme found for " + currentURL);
            }

            return content;
        }
    }

    String parsedContent = null;

    boolean themeCssFastLoad = _isThemeCssFastLoad(request, themeDisplay);

    File cssRealFile = new File(cssRealPath);
    File cacheCssRealFile = SassToCssBuilder.getCacheFile(cssRealPath);

    if (themeCssFastLoad && cacheCssRealFile.exists()
            && (cacheCssRealFile.lastModified() == cssRealFile.lastModified())) {

        parsedContent = FileUtil.read(cacheCssRealFile);

        if (_log.isDebugEnabled()) {
            _log.debug("Loading SASS cache from " + cacheCssRealFile + " takes " + stopWatch.getTime() + " ms");
        }
    } else {
        content = SassToCssBuilder.parseStaticTokens(content);

        String queryString = request.getQueryString();

        if (!themeCssFastLoad && Validator.isNotNull(queryString)) {
            content = _propagateQueryString(content, queryString);
        }

        parsedContent = _parseSass(request, themeDisplay, theme, cssRealPath, content);

        if (_log.isDebugEnabled()) {
            _log.debug("Parsing SASS for " + cssRealPath + " takes " + stopWatch.getTime() + " ms");
        }
    }

    if (Validator.isNull(parsedContent)) {
        return content;
    }

    parsedContent = StringUtil.replace(parsedContent, new String[] { "@portal_ctx@", "@theme_image_path@" },
            new String[] { PortalUtil.getPathContext(), _getThemeImagesPath(request, themeDisplay, theme) });

    return parsedContent;
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.javascript.JavaScriptModuleBuilder.java

public static CompilationLevel getCompilationLevel(HttpServletRequest request) {
    CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS;
    IAggregator aggregator = (IAggregator) request.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME);
    IOptions options = aggregator.getOptions();
    if (options.isDevelopmentMode() || options.isDebugMode()) {
        OptimizationLevel optimize = (OptimizationLevel) request
                .getAttribute(IHttpTransport.OPTIMIZATIONLEVEL_REQATTRNAME);
        if (optimize == OptimizationLevel.WHITESPACE) {
            level = CompilationLevel.WHITESPACE_ONLY;
        } else if (optimize == OptimizationLevel.ADVANCED) {
            level = CompilationLevel.ADVANCED_OPTIMIZATIONS;
        } else if (optimize == OptimizationLevel.NONE) {
            level = null;/* w  w w.j a va2  s  .  c  om*/
        }
    }
    return level;
}

From source file:org.springjutsu.validation.util.RequestUtils.java

/**
 * Used by successView and validationFailureView.
 * If the user specifies a path containing RESTful url
 * wildcards, evaluate those wildcard expressions against 
 * the current model map, and plug them into the url.
 * If the wildcard is a multisegmented path, get the top level
 * bean from the model map, and fetch the sub path using 
 * a beanwrapper instance.//w  w w  .ja  v a2  s.  co  m
 * @param viewName The view potentially containing wildcards
 * @param model the model map 
 * @param request the request
 * @return a wildcard-substituted view name
 */
@SuppressWarnings("unchecked")
public static String replaceRestPathVariables(String viewName, Map<String, Object> model,
        HttpServletRequest request) {
    String newViewName = viewName;
    Matcher matcher = Pattern.compile(PATH_VAR_PATTERN).matcher(newViewName);
    while (matcher.find()) {
        String match = matcher.group();
        String varName = match.substring(1, match.length() - 1);
        String baseVarName = null;
        String subPath = null;
        if (varName.contains(".")) {
            baseVarName = varName.substring(0, varName.indexOf("."));
            subPath = varName.substring(varName.indexOf(".") + 1);
        } else {
            baseVarName = varName;
        }
        Map<String, String> uriTemplateVariables = (Map<String, String>) request
                .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        if (uriTemplateVariables != null && uriTemplateVariables.containsKey(varName)) {
            newViewName = newViewName.replace(match, String.valueOf(uriTemplateVariables.get(varName)));
        } else {
            Object resolvedObject = model.get(baseVarName);
            if (resolvedObject == null) {
                throw new IllegalArgumentException(varName + " is not present in model.");
            }
            if (subPath != null) {
                BeanWrapperImpl beanWrapper = new BeanWrapperImpl(resolvedObject);
                resolvedObject = beanWrapper.getPropertyValue(subPath);
            }
            if (resolvedObject == null) {
                throw new IllegalArgumentException(varName + " is not present in model.");
            }
            newViewName = newViewName.replace(match, String.valueOf(resolvedObject));
        }
        matcher.reset(newViewName);
    }
    return newViewName;
}

From source file:com.att.ajsc.csilogging.common.CSILoggingUtils.java

public static void completeLogging(HttpServletRequest request, String servicename) {

    try {//from  w w w  . ja v  a 2  s.co m
        logger.debug("In...:completeLogging");
        PerformanceTrackingBean perfTrackerBean = null;
        perfTrackerBean = (PerformanceTrackingBean) request.getAttribute(PERFORMANCE_TRACKER_BEAN);
        // AuditRecord ar =
        // (AuditRecord)request.getAttribute(CommonNames.AUDIT_RECORD);
        AuditRecord ar = perfTrackerBean.getAuditRecord();
        long endTime = System.currentTimeMillis();
        // long endTime = System.nanoTime()/1000000;

        // long startTime =
        // Long.parseLong((String)request.getAttribute(CommonNames.ATTR_START_TIME));
        long startTime = Long.parseLong(perfTrackerBean.getStartTime());
        ar.setElapsedTime(Long.toString(endTime - startTime));
        if (ar != null) {
            AuditRecordLogging.auditLogResult(ar, request);
        }

        if ("C".equals(ar.getTransactionStatus())) {
            // PerformanceTracking.addPerfTrack(request,
            // "Main",
            // "C",
            // Long.toString(endTime),servicename);
            PerformanceTracking.addPerfTrack(perfTrackerBean, "Main", "C", Long.toString(endTime), servicename,
                    null);

        } else {
            // PerformanceTracking.addPerfTrack(request,
            // "Main",
            // "E",
            // Long.toString(endTime),servicename);
            PerformanceTracking.addPerfTrack(perfTrackerBean, "Main", "E", Long.toString(endTime), servicename,
                    null);
        }
        // PerformanceTracking.addAdditionalPerfTrack(request, "10", "10");
        // PerformanceTracking.logTracker(request);
        PerformanceTracking.logTracker(perfTrackerBean, request);
        removeRequestAttribute(request);

    } catch (Exception e) {
        logger.error("Error completing logs - " + e);
    }
}

From source file:com.jsmartframework.web.manager.WebContext.java

/**
 * Check if attribute is carried on {@link HttpServletRequest}, {@link HttpSession} or {@link ServletContext}
 * instances associated with current request being processed.
 *
 * @param name name of the attribute.//from w  w  w.  j a  v  a2s  .  c om
 * @return true if the attribute is contained in one of the instances {@link HttpServletRequest},
 * {@link HttpSession} or {@link ServletContext}, false otherwise.
 */
public static boolean containsAttribute(String name) {
    if (name != null) {
        HttpServletRequest request = getRequest();
        if (request != null && request.getAttribute(name) != null) {
            return true;
        }

        HttpSession session = getSession();
        if (session != null) {
            synchronized (session) {
                if (session.getAttribute(name) != null) {
                    return true;
                }
            }
        }

        return getApplication().getAttribute(name) != null;
    }
    return false;
}

From source file:com.jsmartframework.web.manager.WebContext.java

/**
 * Returns the attribute carried on {@link HttpServletRequest}, {@link HttpSession} or {@link ServletContext}
 * instances associated with current request being processed.
 *
 * @param name name of the attribute.//from  w  w w.  java2s  .c  om
 * @return the {@link Object} mapped by attribute name on the current request.
 */
public static Object getAttribute(String name) {
    if (name != null) {
        HttpServletRequest request = getRequest();
        if (request != null && request.getAttribute(name) != null) {
            return request.getAttribute(name);
        }

        HttpSession session = getSession();
        if (session != null) {
            synchronized (session) {
                if (session.getAttribute(name) != null) {
                    return session.getAttribute(name);
                }
            }
        }

        ServletContext application = getApplication();
        if (application.getAttribute(name) != null) {
            return application.getAttribute(name);
        }
    }
    return null;
}

From source file:com.feilong.servlet.http.RequestUtil.java

/**
 *  attribute./*from ww  w . j  a  v  a 2  s  .c  o  m*/
 *
 * @param <T>
 *            the generic type
 * @param request
 *            the request
 * @param attributeName
 *            ??
 * @return  <code>attributeName</code> null, {@link NullPointerException}<br>
 *          <code>attributeName</code> blank, {@link IllegalArgumentException}<br>
 * @see javax.servlet.ServletRequest#getAttribute(String)
 * @since 1.3.0
 */
@SuppressWarnings("unchecked")
public static <T> T getAttribute(HttpServletRequest request, String attributeName) {
    Validate.notBlank(attributeName, "attributeName can't be null/empty!");
    return (T) request.getAttribute(attributeName);
}

From source file:com.bsb.cms.commons.web.MossActionUtils.java

/**
 * ?? ???<s:debug></s:debug> 
 * /*from   w  w  w.  j av  a  2s.  co  m*/
 * @param req
 */
@SuppressWarnings("all")
@Deprecated
public static void print(HttpServletRequest req) {
    // Application
    Map<String, Object> parameters = new WeakHashMap<String, Object>();

    // attributes in scope RequestParameter
    for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        String[] v = req.getParameterValues(name);
        if (v.length == 1) {
            if (v[0].equals(""))
                continue;
            parameters.put(name, v[0]);
        } else
            parameters.put(name, v);
    }

    // attributes in scope Request
    for (Enumeration e = req.getAttributeNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        Object v = req.getAttribute(name);
        parameters.put(name, v);
    }

    // attributes in scope Session
    HttpSession session = req.getSession();
    for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        Object v = session.getAttribute(name);
        parameters.put(name, v);
    }

    Set keys = parameters.keySet();
    Iterator it = keys.iterator();
    String key;
    Object value;
    while (it.hasNext()) {
        key = (String) it.next();
        value = parameters.get(key);
        System.out.println("key:" + key + ", value:" + value);
    }

}

From source file:jp.pigumer.sso.Application.java

private boolean isForwarded(HttpServletRequest request) {
    if (request.getAttribute("javax.servlet.forward.request_uri") == null) {
        return false;
    } else {//from  w  w w. j  a v  a 2s.  c o  m
        return true;
    }
}