Example usage for javax.servlet.http HttpSession getId

List of usage examples for javax.servlet.http HttpSession getId

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession getId.

Prototype

public String getId();

Source Link

Document

Returns a string containing the unique identifier assigned to this session.

Usage

From source file:com.github.mrstampy.gameboot.web.WebProcessor.java

@Override
public void onConnection(HttpSession httpSession) throws Exception {
    try {/*ww w  .j  av a 2  s. c o m*/
        if (systemIds.containsKey(httpSession.getId())) {
            SystemIdKey key = systemIds.get(httpSession.getId());

            if (registry.contains(key)) {
                registry.restartExpiry(key);
            } else {
                registry.put(key, httpSession);
            }

            return;
        }

        SystemIdKey key = generator.next();

        systemIds.put(httpSession.getId(), key);

        registry.put(key, httpSession);
    } finally {
        setMDC(httpSession);
    }
}

From source file:com.primeleaf.krystal.web.action.console.UpdateProfilePictureAction.java

@SuppressWarnings("rawtypes")
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    if (request.getMethod().equalsIgnoreCase("POST")) {
        try {//  w  w w  . jav a  2s .  c o m
            String userName = loggedInUser.getUserName();
            String sessionid = (String) session.getId();

            String tempFilePath = System.getProperty("java.io.tmpdir");

            if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) {
                tempFilePath += System.getProperty("file.separator");
            }
            tempFilePath += userName + "_" + sessionid;

            //variables
            String fileName = "", ext = "";
            File file = null;
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
            upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING);
            List listItems = upload.parseRequest((HttpServletRequest) request);

            Iterator iter = listItems.iterator();
            FileItem fileItem = null;
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();
                if (!fileItem.isFormField()) {
                    try {
                        fileName = fileItem.getName();
                        file = new File(fileName);
                        fileName = file.getName();
                        ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                        if (!"JPEG".equalsIgnoreCase(ext) && !"JPG".equalsIgnoreCase(ext)
                                && !"PNG".equalsIgnoreCase(ext)) {
                            request.setAttribute(HTTPConstants.REQUEST_ERROR,
                                    "Invalid image. Please upload JPG or PNG file");
                            return (new MyProfileAction().execute(request, response));
                        }
                        file = new File(tempFilePath + "." + ext);
                        fileItem.write(file);
                    } catch (Exception ex) {
                        session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage());
                        return (new MyProfileAction().execute(request, response));
                    }
                }
            } //if

            if (file.length() <= 0) { //code for checking minimum size of file
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document");
                return (new MyProfileAction().execute(request, response));
            }
            if (file.length() > (1024 * 1024 * 2)) { //code for checking minimum size of file
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Image size too large. Upload upto 2MB file");
                return (new MyProfileAction().execute(request, response));
            }

            User user = loggedInUser;
            user.setProfilePicture(file);
            UserDAO.getInstance().setProfilePicture(user);

            AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER,
                    AuditLogRecord.ACTION_EDITED, loggedInUser.getUserName(), request.getRemoteAddr(),
                    AuditLogRecord.LEVEL_INFO, "", "Profile picture update"));
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
    request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Profile picture uploaded successfully");
    return (new MyProfileAction().execute(request, response));
}

From source file:com.huateng.ebank.framework.session.SessionManager.java

public String getSessionID(HttpServletRequest req) {
    if (logger.isDebugEnabled()) {
        logger.debug("getSessionID(HttpServletRequest) - start"); //$NON-NLS-1$
    }/* ww  w. jav a  2s.  co  m*/

    HttpSession session = req.getSession(false);
    if (null == session)
        return null;
    String returnString = session.getId();
    if (logger.isDebugEnabled()) {
        logger.debug("getSessionID(HttpServletRequest) - end"); //$NON-NLS-1$
    }
    return returnString;
}

From source file:jp.terasoluna.fw.web.struts.actions.MakeSessionDirectoryAction.java

/**
 * <p>/*from   ww w.  jav  a  2 s  . c  o m*/
 *  ZbVfBNg???B<br>
 *  ZbV???AZbVfBNg??
 *  p??[^??J?ANVtH??[hZbg?B<br>
 *  p??[^?????A(404)G?[?B<br>
 *  ZbV???AVXeON?B
 * </p>
 * @param mapping ANV}bsO
 * @param form ANVtH?[
 * @param req HTTPNGXg
 * @param res HTTPX|X
 * @return J?ANVtH??[h?B
 */
@Override
public ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) {

    if (log.isDebugEnabled()) {
        log.debug("doExecute() called.");
    }

    // pZbVON
    HttpSession session = req.getSession(false);
    if (session == null) {
        log.error("HttpSession is not available.");
        throw new SystemException(null, SESSION_NOT_FOUND_ERROR);
    }

    // ZbVID?AZbVfBNg???B
    FileUtil.makeSessionDirectory(session.getId());

    // p??[^??itH??[h??j
    String path = mapping.getParameter();

    if (path == null) {
        // p??[^?????A(404)G?[p
        try {
            res.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (IOException e) {
            log.error("Error page(404) forwarding failed.");
            throw new SystemException(e, FORWARD_ERRORPAGE_ERROR);
        }
        return null;
    }

    // J
    ActionForward retVal = new ActionForward(path);
    return retVal;
}

From source file:com.vportal.portal.servlet.PortalSessionListener.java

public void sessionCreated(HttpSessionEvent event) {

    /*if (PropsValues.SESSION_DISABLED) {
       return;//from   w w w .j a  va 2 s  . c o  m
    }*/
    //hoan
    if (GetterUtil.getBoolean(PropsUtil.get(PropsKeys.SESSION_DISABLED))) {
        return;
    }
    //hoan
    HttpSession ses = event.getSession();

    MethodKey method = new MethodKey("com.liferay.portal.kernel.util.Validator.PortalSessionContext", "put",
            String.class, HttpSession.class);
    Object[] args = new Object[] { ses.getId(), ses };
    //PortalSessionContext.put(ses.getId(), ses);
    try {
        PortalClassInvoker.invoke(false, method, args);
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    // Process session created events

    try {
        /*EventsProcessor.process(
        PropsKeys.SERVLET_SESSION_CREATE_EVENTS,
        PropsValues.SERVLET_SESSION_CREATE_EVENTS, ses);*/
        //hoan
        MethodKey methodProcess = new MethodKey("com.liferay.portal.events.EventsProcessorUtil", "process",
                String.class, String.class, HttpSession.class);
        Object[] argsProcess = new Object[] { PropsKeys.SERVLET_SESSION_CREATE_EVENTS,
                PropsUtil.getArray("SERVLET_SESSION_CREATE_EVENTS"), ses };
        PortalClassInvoker.invoke(false, methodProcess, argsProcess);
        /*EventsProcessorUtil.process(
              PropsKeys.SERVLET_SESSION_CREATE_EVENTS,
              PropsValues.SERVLET_SESSION_CREATE_EVENTS, ses);*/
        //hoan      
    } catch (ActionException ae) {
        _log.error(ae, ae);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.wavemaker.runtime.server.ControllerBase.java

@Override
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {

    if (request == null) {
        throw new WMRuntimeException(MessageResource.SERVER_NOREQUEST);
    } else if (response == null) {
        throw new WMRuntimeException(MessageResource.SERVER_NORESPONSE);
    }/*from  ww  w .  j  a  va 2s .co  m*/

    ModelAndView ret;
    try {
        this.runtimeAccess.setStartTime(System.currentTimeMillis());
        // add logging
        StringBuilder logEntry = new StringBuilder();
        HttpSession session = request.getSession(false);
        if (session != null) {
            logEntry.append("session " + session.getId() + ", ");
        }
        logEntry.append("thread " + Thread.currentThread().getId());
        NDC.push(logEntry.toString());

        // default responses to the DEFAULT_ENCODING
        response.setCharacterEncoding(ServerConstants.DEFAULT_ENCODING);

        getServletEventNotifier().executeStartRequest();
        initializeRuntime(request, response);

        // execute the request
        ret = executeRequest(request, response);

        getServletEventNotifier().executeEndRequest();
    } catch (Throwable t) {
        this.logger.error(t.getMessage(), t);
        String message = t.getMessage();
        if (!StringUtils.hasLength(message)) {
            message = t.toString();
        }
        if (this.serviceResponse != null && !this.serviceResponse.isPollingRequest()
                && this.serviceResponse.getConnectionTimeout() > 0
                && System.currentTimeMillis()
                        - this.runtimeAccess.getStartTime() > (this.serviceResponse.getConnectionTimeout() - 3)
                                * 1000) {
            this.serviceResponse.addError(t);
        }
        return handleError(message, t);
    } finally {
        RuntimeAccess.setRuntimeBean(null);
        NDC.pop();
        NDC.remove();
    }

    return ret;
}

From source file:org.apache.struts.action.ActivityAction.java

/**
 * Invoked immediately after execution of the related Activity has
 * been completed normally, been suspended, or been aborted by
 * the throwing of a StepException.  The Step included in this event
 * will be the last one to be executed./*www  .j  ava  2  s .c  o m*/
 *
 * @param event The <code>ContextEvent</code> that has occurred
 */
public void afterActivity(ContextEvent event) {

    WebContext context = (WebContext) event.getContext();
    HttpSession session = context.getHttpSession();
    StringBuffer sb = new StringBuffer("{");
    sb.append(session.getId());
    sb.append("} afterActivity");
    servlet.log(sb.toString());

}

From source file:org.apache.struts.action.ActivityAction.java

/**
 * Invoked immediately before execution of the related Activity has
 * started.  The Step included in this event will be the first one
 * to be executed.//from w w  w .  ja  va2 s  .  com
 *
 * @param event The <code>ContextEvent</code> that has occurred
 */
public void beforeActivity(ContextEvent event) {

    WebContext context = (WebContext) event.getContext();
    HttpSession session = context.getHttpSession();
    StringBuffer sb = new StringBuffer("{");
    sb.append(session.getId());
    sb.append("} beforeActivity");
    servlet.log(sb.toString());

}

From source file:org.apache.struts.action.ActivityAction.java

/**
 * Invoked immediately before the specified Step is executed.
 *
 * @param event The <code>ContextEvent</code> that has occurred
 *//*from   w w w.j a va  2s. c om*/
public void beforeStep(ContextEvent event) {

    WebContext context = (WebContext) event.getContext();
    HttpSession session = context.getHttpSession();
    StringBuffer sb = new StringBuffer("{");
    sb.append(session.getId());
    sb.append("} beforeStep ");
    sb.append(event.getStep());
    servlet.log(sb.toString());

}

From source file:org.apache.struts.action.ActivityAction.java

/**
 * Invoked immediately after the specified Step was executed.
 *
 * @param event The <code>ContextEvent</code> that has occurred
 *///  w  ww.ja  v a 2  s . c o m
public void afterStep(ContextEvent event) {

    WebContext context = (WebContext) event.getContext();
    HttpSession session = context.getHttpSession();
    StringBuffer sb = new StringBuffer("{");
    sb.append(session.getId());
    sb.append("} afterStep ");
    sb.append(event.getStep());
    if (context.getSuspend())
        sb.append(" (Suspended)");
    if (context.getNextStep() == null)
        sb.append(" (Finished)");
    servlet.log(sb.toString());
    if (event.getException() != null)
        servlet.log("-->Step threw exception", event.getException());

}