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:cec.easyshop.storefront.controllers.cms.AbstractCMSComponentController.java

@RequestMapping
public String handleGet(final HttpServletRequest request, final HttpServletResponse response, final Model model)
        throws Exception {

    T component = (T) request.getAttribute(COMPONENT);
    if (component != null) {
        // Add the component to the model
        model.addAttribute("component", component);

        // Allow subclasses to handle the component
        return handleComponent(request, response, model, component);
    }//  w ww.j  ava  2  s  . c o m

    String componentUid = (String) request.getAttribute(COMPONENT_UID);
    if (StringUtils.isEmpty(componentUid)) {
        componentUid = request.getParameter(COMPONENT_UID);
    }

    if (StringUtils.isEmpty(componentUid)) {
        LOG.error("No component specified in [" + COMPONENT_UID + "]");
        throw new AbstractPageController.HttpNotFoundException();
    }

    try {
        component = getCmsComponentService().getAbstractCMSComponent(componentUid);
        if (component == null) {
            LOG.error("Component with UID [" + componentUid.replaceAll(SANITIZE_REGEX, "") + "] is null");
            throw new AbstractPageController.HttpNotFoundException();
        } else {
            // Add the component to the model
            model.addAttribute("component", component);

            // Allow subclasses to handle the component
            return handleComponent(request, response, model, component);
        }
    } catch (final CMSItemNotFoundException e) {
        LOG.error("Could not find component with UID [" + componentUid.replaceAll(SANITIZE_REGEX, "") + "]");
        throw new AbstractPageController.HttpNotFoundException(e);
    }
}

From source file:com.microsoftopentechnologies.azchat.web.controllers.LoginController.java

/**
 * This method process the login information of the user.On Successful
 * verification from Azure ACS service user redirected to the Home/Landing
 * page of the application.New or first time users are redirected to the
 * Registration page for first time activity.
 * /*from   w w  w  . j av a2 s. c o  m*/
 * @param model
 * @param loginBean
 * @return
 * @throws Exception
 */
@RequestMapping(name = AzureChatConstants.FROM_PAGE_LOGIN, method = RequestMethod.GET)
public ModelAndView doLogin(HttpServletRequest request, ModelMap model, UserBean userBean) throws Exception {
    LOGGER.info("[LoginController][goLogin] start");
    userBean.setSamplToken((String) request.getAttribute("ACSSAML"));
    userBean.setServiceAction(ServiceActionEnum.LOGIN);
    userBean = (UserBean) loginService.invokeService(userBean);
    model.put(AzureChatConstants.USER_BEAN, userBean);
    if (!userBean.hasErrors()) {
        if (!userBean.isNewUser()) {
            LOGGER.debug("New user : " + userBean.isNewUser());
            return processResults(AzureChatConstants.VIEW_NAME_HOME, model, userBean);
        } else {
            LOGGER.debug("New user : " + userBean.isNewUser());
            return processResults(AzureChatConstants.VIEW_NAME_REG, model, userBean);
        }
    }
    LOGGER.debug("Has errors : " + userBean.hasErrors());
    LOGGER.info("[LoginController][goLogin] end");
    return processResults(AzureChatConstants.VIEW_NAME_INDEX, model, userBean);
}

From source file:org.opentides.web.controller.NotifyHandler.java

/**
 * When a comet request is received allow Spring to auto-magically resolve the meteor argument then:
 * Set the meteor's broadcaster to '/notify', suspend, then broadcast to this request only.
 * // w  w w.  j  a  va  2s .  co  m
 * @param m A meteor that represents the current comet session.
 */
@RequestMapping(value = "/notify/{userId}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, Object> watch(@PathVariable("userId") String userId, HttpServletRequest request)
        throws Exception {
    //Atmosphere framework puts filter/servlet that adds ATMOSPHERE_RESOURCE to all requests
    AtmosphereResource resource = (AtmosphereResource) request
            .getAttribute(ApplicationConfig.ATMOSPHERE_RESOURCE);

    //suspending resource to keep connection
    resource.suspend();

    //find broadcaster, second parameter says to create broadcaster if it doesn't exist
    Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(userId, true);

    int timezoneDiff = StringUtil.convertToInt(request.getParameter("tz"), 0);
    //saving resource for notifications
    broadcaster.addAtmosphereResource(resource);
    return notificationService.getPopupNotification(new Long(userId), timezoneDiff);

}

From source file:com.liferay.portal.util.PortalUtil.java

public static String getCompanyId(HttpServletRequest req) {
    String companyId = (String) req.getSession().getAttribute(WebKeys.COMPANY_ID);

    if (companyId == null) {
        companyId = (String) req.getAttribute(WebKeys.COMPANY_ID);
        if (companyId != null) {
            req.getSession().setAttribute(WebKeys.COMPANY_ID, companyId);
        }//from  ww w .j av  a2s .  c o m
    }
    if (companyId == null) {
        companyId = PublicCompanyFactory.getDefaultCompanyId();
        if (companyId != null) {
            req.getSession().setAttribute(WebKeys.COMPANY_ID, companyId);
        }

    }

    return companyId;
}

From source file:gov.nih.nci.cabig.caaers.web.study.SitesTab.java

@Override
public void postProcess(HttpServletRequest request, StudyCommand command, Errors errors) {
    String action = request.getParameter("_action");
    Object isAjax = request.getAttribute("_isAjax");

    if (isAjax != null)
        return;/*  ww  w  .  j a va  2s  .c  om*/

    if (StringUtils.equals(action, "removeSite")) {

        int index = Integer.parseInt(request.getParameter("_selected"));
        StudySite site = command.getStudy().getStudySites().get(index);

        if (site.getId() != null) {
            if (CollectionUtils.isNotEmpty(site.getActiveStudyInvestigators())) {
                errors.reject("STU_013", "The site is associated to investigators, so unable to delete");
                site.setRetiredIndicator(false);
            }
            if (CollectionUtils.isNotEmpty(site.getActiveStudyPersonnel())) {
                errors.reject("STU_014", "The site is associated to research staffs, so unable to delete");
                site.setRetiredIndicator(false);
            }
        }

        //remove site, if no investigator or research person is associated to site.
        if (!errors.hasErrors()) {
            command.deleteStudySiteAtIndex(index);
            command.setStudySiteIndex(-1);
        }

    }

    request.setAttribute("tabFlashMessage",
            messageSource.getMessage(
                    String.format("MSG_study.%s.flash_message", this.getClass().getSimpleName()), null,
                    Locale.getDefault()));
}

From source file:net.cloudkit.enterprises.infrastructure.commons.ExecuteTimeInterceptor.java

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) {/*from w ww .ja va 2  s.  com*/
    Long startTime = (Long) request.getAttribute(EXECUTE_TIME_ATTRIBUTE_NAME);
    Object localObject;
    if (startTime == null) {
        localObject = request.getAttribute(START_TIME);
        Long endTime = Long.valueOf(System.currentTimeMillis());
        startTime = Long.valueOf(endTime.longValue() - ((Long) localObject).longValue());
        request.setAttribute(START_TIME, localObject);
    }
    if (modelAndView != null) {
        localObject = modelAndView.getViewName();
        if (!StringUtils.startsWith((String) localObject, redirect)) {
            modelAndView.addObject(EXECUTE_TIME_ATTRIBUTE_NAME, startTime);
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("[" + handler + "] executeTime: " + startTime + "ms");
    }
}

From source file:org.withinsea.izayoi.adapter.springmvc.SpringIzayoiDispatcherFilter.java

@Override
protected void noHandlerFound(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    FilterChain chain = (FilterChain) req.getAttribute(CARRIER_CHAIN_ATTR);
    req.removeAttribute(CARRIER_CHAIN_ATTR);
    if (chain == null) {
        noHandlerFound0(req, resp);/*from   www  .  ja va  2 s.co  m*/
    } else {
        ServletFilterUtils.chain(req, resp, chain, cloister, glowworm, cortile);
    }
}

From source file:hu.fnf.devel.wishbox.gateway.GatewayREST.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(value = "/persistence/user/{userId}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String createUser(@PathVariable("userId") String userId, HttpServletRequest request) {
    StringBuilder content = new StringBuilder();
    StringBuilder stringBuilder = new StringBuilder();
    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
    for (X509Certificate cert : certs) {
        stringBuilder.append(cert.getSubjectX500Principal().getName());
    }//from w  w  w.j  a  v a  2s. c  o m
    try {
        while (request.getReader().ready()) {
            content.append(request.getReader().readLine());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return userId + ": " + content + ": " + stringBuilder;
}

From source file:in.xebia.poc.FileUploadUtils.java

public static boolean parseFileUploadRequest(HttpServletRequest request, File outputFile,
        Map<String, String> params) throws Exception {
    log.debug("Request class? " + request.getClass().toString());
    log.debug("Request is multipart? " + ServletFileUpload.isMultipartContent(request));
    log.debug("Request method: " + request.getMethod());
    log.debug("Request params: ");
    for (Object key : request.getParameterMap().keySet()) {
        log.debug((String) key);/*from  ww  w. ja  va  2  s  .  co  m*/
    }
    log.debug("Request attribute names: ");

    boolean filedataInAttributes = false;
    Enumeration attrNames = request.getAttributeNames();
    while (attrNames.hasMoreElements()) {
        String attrName = (String) attrNames.nextElement();
        log.debug(attrName);
        if ("filedata".equals(attrName)) {
            filedataInAttributes = true;
        }
    }

    if (filedataInAttributes) {
        log.debug("Found filedata in request attributes, getting it out...");
        log.debug("filedata class? " + request.getAttribute("filedata").getClass().toString());
        FileItem item = (FileItem) request.getAttribute("filedata");
        item.write(outputFile);
        for (Object key : request.getParameterMap().keySet()) {
            params.put((String) key, request.getParameter((String) key));
        }
        return true;
    }

    /*ServletFileUpload upload = new ServletFileUpload();
    //upload.setSizeMax(Globals.MAX_UPLOAD_SIZE);
    FileItemIterator iter = upload.getItemIterator(request);
    while(iter.hasNext()){
       FileItemStream item = iter.next();
       InputStream stream = item.openStream();
               
       //If this item is a file
       if(!item.isFormField()){
             
     log.debug("Found non form field in upload request with field name = " + item.getFieldName());
             
     String name = item.getName();
     if(name == null){
         throw new Exception("File upload did not have filename specified");
     }
             
        // Some browsers, including IE, return the full path so trim off everything but the file name
        name = getFileNameFromPath(name);
                 
    //Enforce required file extension, if present
    if(!name.toLowerCase().endsWith( ".zip" )){
       throw new Exception("File uploaded did not have required extension .zip");
    }
            
      bufferedCopyStream(stream, new FileOutputStream(outputFile));
       }
       else {
    params.put(item.getFieldName(), Streams.asString(stream));
       }
    }
    return true;*/

    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    List /* FileItem */ items = upload.parseRequest(request);

    // Process the uploaded items
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            log.debug("Found non form field in upload request with field name = " + item.getFieldName());

            String name = item.getName();
            if (name == null) {
                throw new Exception("File upload did not have filename specified");
            }

            // Some browsers, including IE, return the full path so trim off everything but the file name
            name = getFileNameFromPath(name);

            item.write(outputFile);
        } else {
            params.put(item.getFieldName(), item.getString());
        }
    }
    return true;
}