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.persistent.cloudninja.controller.TenantProfileController.java

/********************************* USER LIST  FLOW *************************************************************************/
@RequestMapping(value = "{tenantId}/deleteTenant.htm", method = RequestMethod.GET)
public String deleteTenant(HttpServletRequest request,
        @CookieValue(value = "CLOUDNINJAAUTH", required = false) String cookie) {

    if (cookie == null) {
        cookie = request.getAttribute("cookieNameAttr").toString();
    }/*from  ww w .  ja v  a 2 s .  co m*/
    String tenantId = AuthFilterUtils.getFieldValueFromCookieString(CloudNinjaConstants.COOKIE_TENANTID_PREFIX,
            cookie);

    tenantProfileService.deleteTenant(tenantId);
    return "logoutSecurityPage";
}

From source file:org.wallride.web.controller.guest.page.PageDescribeController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    BlogLanguage blogLanguage = (BlogLanguage) request
            .getAttribute(BlogLanguageMethodArgumentResolver.BLOG_LANGUAGE_ATTRIBUTE);
    if (blogLanguage == null) {
        Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
        blogLanguage = blog.getLanguage(blog.getDefaultLanguage());
    }/*from ww w .j  a v a  2 s .c  om*/

    String path = urlPathHelper.getLookupPathForRequest(request);

    PathMatcher pathMatcher = new AntPathMatcher();
    if (!pathMatcher.match(PATH_PATTERN, path)) {
        throw new HttpNotFoundException();
    }

    Map<String, String> variables = pathMatcher.extractUriTemplateVariables(PATH_PATTERN, path);
    request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, variables);

    Page page = pageService.getPageByCode(variables.get("code"), blogLanguage.getLanguage());
    if (page == null) {
        page = pageService.getPageByCode(variables.get("code"), blogLanguage.getBlog().getDefaultLanguage());
    }
    if (page == null) {
        throw new HttpNotFoundException();
    }
    if (page.getStatus() != Post.Status.PUBLISHED) {
        throw new HttpNotFoundException();
    }

    return createModelAndView(page);
}

From source file:eionet.webq.converter.CdrRequestConverter.java

/**
 * Check whether authorization against CDR succeed.
 *
 * @param request http request/* w w  w. j a  v a2 s. com*/
 * @return is authorization succeed
 */
private boolean authorizationAgainstCdrSucceed(HttpServletRequest request) {
    Object attribute = request.getAttribute(CdrAuthorizationInterceptor.AUTHORIZATION_FAILED_ATTRIBUTE);
    return attribute == null;
}

From source file:io.restassured.module.mockmvc.http.AttributeController.java

@RequestMapping(value = "/attribute", method = GET, produces = APPLICATION_JSON_VALUE)
public @ResponseBody String attribute(HttpServletRequest request) {
    Collection<String> attributes = new ArrayList<String>();
    for (String attributeName : Collections.list(request.getAttributeNames())) {
        attributes.add("\"" + attributeName + "\": \"" + request.getAttribute(attributeName) + "\"");
    }//  www  .java2 s .c  o  m

    return "{" + StringUtils.join(attributes, ", ") + "}";
}

From source file:com.salesmanager.core.util.www.tags.UrlTag.java

/**
 * Overwrites default struts 2 tag in order to add merchantId in url
 * parameters if configured in the system
 *//*from   ww  w.  ja va  2 s. com*/
protected void populateParams() {

    super.populateParams();

    HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();

    MerchantStore store = (MerchantStore) req.getAttribute("STORE");

    URL url = (URL) component;

    Map parameters = url.getParameters();
    if (parameters == null) {
        parameters = new LinkedHashMap();
    }

    if (store != null) {

        // check if merchantId has to be set in the url
        boolean useMerchantId = config.getBoolean("core.url.usemerchantid", false);
        if (useMerchantId) {
            parameters.put("merchantId", store.getMerchantId());
        }

    }

    if (!StringUtils.isBlank(scheme)) {
        if (("https").equalsIgnoreCase(scheme)) {
            scheme = (String) config.getString("core.domain.http.secure", "https");
        }
    }

    url.setIncludeParams(includeParams);
    url.setScheme(scheme);
    url.setValue(value);
    url.setMethod(method);
    url.setNamespace(namespace);
    url.setAction(action);
    url.setPortletMode(portletMode);
    url.setPortletUrlType(portletUrlType);
    url.setWindowState(windowState);
    url.setAnchor(anchor);

    if (encode != null) {
        url.setEncode(Boolean.valueOf(encode).booleanValue());
    }
    if (includeContext != null) {
        url.setIncludeContext(Boolean.valueOf(includeContext).booleanValue());
    }
    if (escapeAmp != null) {
        url.setEscapeAmp(Boolean.valueOf(escapeAmp).booleanValue());
    }
    if (forceAddSchemeHostAndPort != null) {
        url.setForceAddSchemeHostAndPort(Boolean.valueOf(forceAddSchemeHostAndPort).booleanValue());
    }

}

From source file:com.benfante.taglib.frontend.utils.FlashHelperTest.java

private void assertThatValueInRequestEqualToCode(HttpServletRequest req, String code, String type,
        String attribute) {//  w w w .  ja  v a2 s.c  o m
    Map<String, String> flashMap = (Map<String, String>) req.getAttribute(attribute);
    String value = flashMap.get(type);
    assertThat(value, equalTo(code));
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.teacher.executionCourse.EvaluationMethodDA.java

public ActionForward prepareEditEvaluationMethod(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    final ExecutionCourse executionCourse = (ExecutionCourse) request.getAttribute("executionCourse");
    EvaluationMethod evaluationMethod = executionCourse.getEvaluationMethod();
    MultiLanguageString evaluationElements = evaluationMethod == null ? null
            : evaluationMethod.getEvaluationElements();
    if (evaluationMethod == null || evaluationElements == null || evaluationElements.isEmpty()
            || StringUtils.isEmpty(evaluationElements.getContent())) {
        MultiLanguageString evaluationMethodMls = new MultiLanguageString();
        final Set<CompetenceCourse> competenceCourses = executionCourse.getCompetenceCourses();
        if (!competenceCourses.isEmpty()) {
            final CompetenceCourse competenceCourse = competenceCourses.iterator().next();
            final String pt = competenceCourse.getEvaluationMethod();
            final String en = competenceCourse.getEvaluationMethodEn();
            evaluationMethodMls = evaluationMethodMls.with(MultiLanguageString.pt, pt == null ? "" : pt)
                    .with(MultiLanguageString.en, en == null ? "" : en);
        }//from  w w  w.j  ava2s.c om
        EditEvaluation.runEditEvaluation(executionCourse, evaluationMethodMls);
        evaluationMethod = executionCourse.getEvaluationMethod();
    }
    return forward(request, "/teacher/executionCourse/editEvaluationMethod.jsp");
}

From source file:com.remediatetheflag.global.actions.unauth.DoLoginAction.java

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    JsonElement usernameElement = json.get(Constants.ACTION_PARAM_USERNAME);
    String username = usernameElement.getAsString();

    JsonElement passwordElement = json.get(Constants.ACTION_PARAM_PASSWORD);
    String password = passwordElement.getAsString();

    if (null == username || username.equals("") || null == password || password.equals("")) {
        MessageGenerator.sendRedirectMessage(Constants.INDEX_PAGE, response);
        return;//  ww w .  j  av  a2 s.c om
    }
    Integer failedAttempts = hpc.getFailedLoginAttemptsForUser(username);
    if (failedAttempts >= Constants.FAILED_ATTEMPTS_LOCKOUT) {
        logger.warn("Username " + username + " is locked out, login refused");
        MessageGenerator.sendErrorMessage(Constants.JSON_VALUE_ERROR_ACCOUNT_LOCKOUT, response);
        User lockedUser = hpc.getUserFromUsername(username);
        if (null != lockedUser) {
            lockedUser.setStatus(UserStatus.LOCKED);
            hpc.updateUserInfo(lockedUser);
        }
        MessageGenerator.sendRedirectMessage(Constants.INDEX_PAGE, response);
        return;
    }

    User user = hpc.getUser(username, password);

    UserAuthenticationEvent attempt = new UserAuthenticationEvent();
    attempt.setUsername(username);

    if (null != user && user.getUsername() != null) {
        if (!user.getStatus().equals(UserStatus.ACTIVE)) {
            logger.warn("Login UNSUCCESSFUL for USER: " + username + " - USER IS: " + user.getStatus());
            MessageGenerator.sendRedirectMessage(Constants.INDEX_PAGE, response);
            return;
        }
        request.getSession().invalidate();
        request.getSession(true);
        request.getSession().setAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT, user);
        request.getSession().setAttribute(Constants.ATTRIBUTE_SECURITY_ROLE, user.getRole());
        CSRFTokenUtils.setToken(request.getSession());
        if (user.getRole() <= Constants.ROLE_STATS) {
            logger.debug("Login successful for ADMIN: " + user.getUsername());
            MessageGenerator.sendRedirectMessage(Constants.MGMT_HOME, response);
        } else {
            logger.debug("Login successful for USER: " + user.getUsername());
            MessageGenerator.sendRedirectMessage(Constants.USER_HOME, response);
        }
        hpc.setFailedLoginAttemptsForUser(username, 0);
        user.setLastLogin(new Date());
        hpc.updateUserInfo(user);
        attempt.setSessionIdHash(DigestUtils.sha256Hex(request.getSession().getId()));
        attempt.setLoginSuccessful(true);
        attempt.setLoginDate(new Date());
        hpc.addLoginEvent(attempt);
    } else {
        failedAttempts++;
        hpc.setFailedLoginAttemptsForUser(username, failedAttempts);
        attempt.setLoginSuccessful(false);
        attempt.setLoginDate(new Date());
        hpc.addLoginEvent(attempt);
        logger.warn("Login UNSUCCESSFUL for USER: " + username);
        MessageGenerator.sendRedirectMessage(Constants.INDEX_PAGE, response);
    }
}

From source file:com.runwaysdk.web.WebFileUploadServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST);

    // capture the session id
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    if (!isMultipart) {
        // TODO Change exception type
        String msg = "The HTTP Request must contain multipart content.";
        throw new RuntimeException(msg);
    }// w ww . ja  v a2  s .  c  o m

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload();

    upload.setFileItemFactory(factory);

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);

        String fileName = null;
        String extension = null;
        InputStream stream = null;
        String uploadPath = null;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream input = item.openStream();
            if (item.isFormField() && item.getFieldName().equals(WEB_FILE_UPLOAD_PATH_FIELD_NAME)) {
                uploadPath = Streams.asString(input);
            } else if (!item.isFormField()) {
                String fullName = item.getName();
                int extensionInd = fullName.lastIndexOf(".");
                fileName = fullName.substring(0, extensionInd);
                extension = fullName.substring(extensionInd + 1);
                stream = input;
            }
        }

        if (stream != null) {
            clientRequest.newFile(uploadPath, fileName, extension, stream);
        }
    } catch (FileUploadException e) {
        throw new FileWriteExceptionDTO(e.getLocalizedMessage());
    }
}

From source file:fr.univlille2.ecm.platform.ui.web.auth.cas2.SecurityExceptionHandler.java

protected String getURLToReach(HttpServletRequest request) {
    log.debug(String.format("getURLToReach#urlToReach"));
    DocumentView docView = (DocumentView) request.getAttribute(URLPolicyService.DOCUMENT_VIEW_REQUEST_KEY);

    if (docView != null) {
        String urlToReach = getURLPolicyService().getUrlFromDocumentView(docView, "");

        if (urlToReach != null) {
            return urlToReach;
        }/*from  w ww  . j  av a2  s  .c o  m*/
    }
    log.debug(String.format("getURLToReach#urlToReach#%s?%s", request.getRequestURL().toString(),
            request.getQueryString()));
    return request.getRequestURL().toString() + "?" + request.getQueryString();
}