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 onDisconnection(HttpSession httpSession) throws Exception {
    String id = httpSession.getId();

    SystemIdKey systemId = systemIds.remove(id);
    cleaner.cleanup(systemId);/*from  w  w  w . java2s. c  o  m*/

    Set<Entry<AbstractRegistryKey<?>, HttpSession>> set = registry.getKeysForValue(httpSession);

    set.forEach(e -> registry.remove(e.getKey()));
}

From source file:de.itsvs.cwtrpc.security.AbstractRpcProcessingFilter.java

protected void invalidateSession(HttpServletRequest request) throws IOException, ServletException {
    final HttpSession session;

    session = request.getSession(false);
    if (session != null) {
        if (log.isDebugEnabled()) {
            log.debug("Invalidating session " + session.getId());
        }//from   w  ww .  j a va2s .  c o  m
        session.invalidate();
    }
}

From source file:SessionFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws java.io.IOException, ServletException {

    HttpSession session = ((HttpServletRequest) request).getSession();
    ServletContext context = config.getServletContext();
    /*/*from  ww  w . j a va 2  s  .c om*/
     * use the ServletContext.log method to log filter messages
     */
    context.log("doFilter called in: " + config.getFilterName() + " on " + (new java.util.Date()));

    // log the session ID
    context.log("session ID: " + session.getId());

    // Find out whether the logged-in session attribute is set
    String logged = (String) session.getAttribute("logged-in");
    if (logged == null)
        session.setAttribute("logged-in", "no");

    //log a message about the log-in status
    context.log("log-in status: " + (String) session.getAttribute("logged-in"));
    context.log("");
    chain.doFilter(request, response);
}

From source file:de.jaxenter.eesummit.caroline.gui.filter.LogFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    String remoteAddress = null;//from   w  w  w .j a  va 2 s .c  o m
    String sessionId = null;
    String uid = "0";

    long start = 0;
    String url = "";
    String method = "";
    Throwable throwable = null;
    boolean dropped = false;
    String agent = null;
    try {
        Validate.isTrue(request instanceof HttpServletRequest, "filter oops?");
        HttpServletRequest req = (HttpServletRequest) request;

        if (req.getCharacterEncoding() == null || forceRequestEncoding) {
            req.setCharacterEncoding(requestEncoding);
        }

        url = req.getRequestURI();
        method = req.getMethod();
        String qs = req.getQueryString();
        agent = req.getHeader("User-Agent");
        if (qs != null) {
            url += "?" + qs;
        }

        for (String stopUrl : dropUrls) { // does any stopUrl match url
            if (url.indexOf(stopUrl) != -1) {
                dropped = true;
                break; // stop searching
            }
        }

        if (!dropped) {
            if (ndcEnabled) {
                if (ndcAddress) {
                    String forwarded = req.getHeader("X-Forwarded-For");
                    if (forwarded != null) {
                        remoteAddress = forwarded;
                    } else {
                        remoteAddress = request.getRemoteAddr();
                    }
                }
                if (ndcSession) {
                    HttpSession session = req.getSession(false); // do not create
                    if (session != null) {
                        sessionId = session.getId();
                        String sessOID = (String) session.getAttribute("USER_ID_LOG");
                        uid = sessOID == null ? "0" : sessOID;
                    }
                }
            }
            StringBuilder msg = simulateNDC(remoteAddress, sessionId, uid);
            msg.append("request start ").append(method).append(" ").append(url).append(" UA=").append(agent);
            logger.info(msg.toString());
            start = System.currentTimeMillis();
        }

        filterChain.doFilter(request, response);
    } catch (IOException e) {
        throwable = e;
        throw e;
    } catch (ServletException e) {
        if (e.getRootCause() != null) {
            throwable = e.getRootCause();
        } else {
            throwable = e;
        }
        throw e;
    } catch (Throwable e) { // be sure to get all errors
        throwable = e;
        throw new ServletException(e);
    } finally {
        if (!dropped) {
            long time = System.currentTimeMillis() - start;
            StringBuilder msg = simulateNDC(remoteAddress, sessionId, uid);
            msg.append("request done ").append(method).append(" ");
            msg.append(url).append(" time=").append(time).append("ms");

            if (throwable == null) {
                logger.info(msg.toString());
            } else {
                String name = throwable.getClass().getSimpleName();
                msg.append(" ex=").append(name);
                msg.append(" msg=").append(throwable.getMessage());
                if (name.equals("ViewExpiredException") || name.equals("ClientAbortException")) {
                    logger.warn(msg.toString());
                } else {
                    msg.append(" UA=").append(agent); // also log agent in error case
                    logger.error(msg.toString());
                }
            }
        }
    }
}

From source file:airport.web.controller.ServicesController.java

@JsonIgnore
@RequestMapping("/service/setting")
public void serviceSetting(HttpServletRequest request, HttpServletResponse response) {
    User user = new User();
    HttpSession httpSession = request.getSession();
    user.setId(httpSession.getId());

    if (!serviceUsers.checkUserOnline(user)) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (LOG.isInfoEnabled()) {
            LOG.info("the user isn't authorized. Session id : " + httpSession.getId()
                    + ". URL : service/setting");
        }//from  w w w . j  a  v  a2  s.  c om

        return;
    }

    SettingFrontEnd settingFrontEnd = new SettingFrontEnd();

    settingFrontEnd.setCheckSettingMusicAirplane(Integer.valueOf(request.getParameter("musicAirplane")));
    settingFrontEnd.setCheckSettingMusicChat(Integer.valueOf(request.getParameter("musicChat")));
    settingFrontEnd.setCheckSettingMusicService(Integer.valueOf(request.getParameter("musicService")));
    settingFrontEnd.setCheckSettingShowClock(Integer.valueOf(request.getParameter("showClock")));
    settingFrontEnd
            .setCheckSettingShowDispatcherOnline(Integer.valueOf(request.getParameter("showDispatcher")));
    settingFrontEnd.setCheckSettingShowNewMessage(Integer.valueOf(request.getParameter("showNewMessage")));
    settingFrontEnd.setCheckSettingShowProfile(Integer.valueOf(request.getParameter("showProfile")));
    settingFrontEnd.setCheckSettingShowWeather(Integer.valueOf(request.getParameter("showWeather")));

    serviceSetting.setSettingFrontEnd(user, settingFrontEnd);

    if (LOG.isInfoEnabled()) {
        LOG.info("user set setting. Session id : " + httpSession.getId() + ". User : " + user
                + ". URL : service/setting");
    }
}

From source file:org.shredzone.commons.view.manager.ViewInvoker.java

/**
 * Evaluates a single parameter of the handler method's parameter list.
 *
 * @param type/*  w  w w  .  ja v a 2 s  . c o m*/
 *            Expected parameter type
 * @param anno
 *            {@link Annotation} of this parameter
 * @param optional
 *            if this parameter is optional and may be {@code null}
 * @param context
 *            {@link ViewContext} containing all necessary data for invoking the view
 * @return Parameter value to be passed to the method
 */
private Object evaluateParameter(Class<?> type, Annotation anno, boolean optional, ViewContext context)
        throws ViewException {

    if (anno instanceof Parameter) {
        String name = ((Parameter) anno).value();
        String value = context.getParameter(name);
        if (value == null && !optional) {
            throw new ViewContextException("Missing parameter " + name);
        }
        return conversionService.convert(value, type);
    }

    if (anno instanceof PathPart) {
        String part = ((PathPart) anno).value();
        String value = context.getPathParts().get(part);
        if (value != null) {
            return conversionService.convert(value, type);
        } else if (optional) {
            return conversionService.convert(null, TypeDescriptor.valueOf(String.class),
                    TypeDescriptor.valueOf(type));
        } else {
            throw new ViewException("Unsatisfied path part: " + part);
        }
    }

    if (anno instanceof Attribute) {
        String name = ((Attribute) anno).value();
        ServletRequest req = context.getValueOfType(ServletRequest.class);
        Object value = req.getAttribute(name);
        if (value == null && !optional) {
            throw new ViewContextException("Missing attribute " + name);
        }
        return conversionService.convert(value, type);
    }

    if (anno instanceof Cookie) {
        String name = ((Cookie) anno).value();
        HttpServletRequest req = context.getValueOfType(HttpServletRequest.class);
        for (javax.servlet.http.Cookie cookie : req.getCookies()) {
            if (name.equals(cookie.getName())) {
                return conversionService.convert(cookie.getValue(), type);
            }
        }
        if (optional) {
            return conversionService.convert(null, TypeDescriptor.valueOf(String.class),
                    TypeDescriptor.valueOf(type));
        } else {
            throw new ViewException("Cookie not set: " + name);
        }
    }

    if (anno instanceof SessionId) {
        HttpSession session = context.getValueOfType(HttpSession.class);
        if (session != null) {
            return conversionService.convert(session.getId(), type);
        } else {
            return conversionService.convert(null, TypeDescriptor.valueOf(String.class),
                    TypeDescriptor.valueOf(type));
        }
    }

    if (anno instanceof Qualifier) {
        // Qualifiers are always optional
        return conversionService.convert(context.getQualifier(), type);
    }

    // Finally, try to get an object of that type from the data provider
    try {
        return context.getValueOfType(type);
    } catch (ViewContextException ex) {
        // ignore and continue...
    }

    // Who the heck would need this...
    if (ViewContext.class.isAssignableFrom(type)) {
        return context;
    }

    // Alas, we cannot find anything to satisfy this parameter
    throw new ViewContextException("Unknown parameter type " + type.getName());
}

From source file:com.silverpeas.authentication.AuthenticationServlet.java

/**
 * Write session cookie.//from   www.  j  av  a 2s .c  o  m
 *
 * @return
 */
private void writeSessionCookie(HttpServletResponse response, HttpSession session, boolean secured) {
    Cookie cookie = new Cookie("JSESSIONID", session.getId());
    cookie.setMaxAge(-1);
    cookie.setPath(session.getServletContext().getContextPath());
    cookie.setHttpOnly(true);
    if (secured) {
        cookie.setSecure(secured);
    }
    response.addCookie(cookie);
}

From source file:com.aurel.track.item.ItemSaveAction.java

public String execute() {
    boolean useProjectSpecificID = false;
    ApplicationBean appBean = (ApplicationBean) application.get(Constants.APPLICATION_BEAN);
    if (appBean.getSiteBean().getProjectSpecificIDsOn() != null) {
        useProjectSpecificID = appBean.getSiteBean().getProjectSpecificIDsOn().booleanValue();
    }/*from   w  ww.  j a  v a 2 s  . c  om*/
    String jsonResponse = "";
    boolean isNew = ItemBL.itemIsNew(actionID);
    LOGGER.debug("execute(): isNew=" + isNew + " actionID=" + actionID);
    WorkItemContext workItemContext = null;
    if (isNew) {
        workItemContext = (WorkItemContext) session.get("workItemContext");
    } else {
        Boolean accessLevelFlag = Boolean.FALSE;
        Integer stateID = null;
        workItemContext = ItemBL.getWorkItemContext(actionID, workItemID, projectID, issueTypeID, stateID,
                accessLevelFlag, personID, locale);
        if (ItemBL.isMove(actionID)) {
            Boolean moveChildren = (Boolean) session.get("moveChildren" + workItemID);
            if (moveChildren != null) {
                workItemContext.getWorkItemBean().setMoveChildren(moveChildren);
            }
        }
    }
    LOGGER.debug("lastModified=" + lastModified);
    Date lastModifiedDate = DateTimeUtils.getInstance().parseISODateTime(lastModified);

    List<IntegerStringBean> conversionErrors = new ArrayList<IntegerStringBean>();
    Map<Integer, Object> fieldValuesObject = null;
    if (inlineEditInNavigator) {
        fieldValuesObject = ItemSaveBL.unwrapContextNavigatorInlineEdit(workItemContext, fieldValues,
                conversionErrors);
    } else {
        fieldValuesObject = ItemSaveBL.unwrapContext(workItemContext, fieldValues, conversionErrors,
                MobileBL.isMobileApp(session));
    }
    ItemSaveBL.updateCtx(workItemContext, fieldValuesObject);
    if (!conversionErrors.isEmpty()) {
        jsonResponse = ItemSaveJSON.encodeConversionErrors(conversionErrors);
    } else {
        if (workItemContext.getWorkItemBean().getObjectID() != null
                && ItemSaveBL.isOutOfDate(lastModifiedDate, workItemContext)) {
            LOGGER.info("workitem is out of date: " + workItemContext.getWorkItemBean().getObjectID() + " "
                    + workItemContext.getWorkItemBean().getSynopsis());
            Boolean accessLevelFlag = Boolean.FALSE;
            Integer stateID = null;
            //reload the workItem
            workItemContext = ItemBL.getWorkItemContext(actionID, workItemID, projectID, issueTypeID, stateID,
                    accessLevelFlag, personID, locale);
            jsonResponse = ItemSaveJSON.encodeErrorOutOfDate(workItemContext, locale, useProjectSpecificID,
                    personBean, MobileBL.isMobileApp(session));
        } else {
            HttpSession httpSession = ServletActionContext.getRequest().getSession();
            workItemContext.setSessionID(httpSession.getId());
            List<ErrorData> errorDataList = new ArrayList<ErrorData>();
            Integer newWorkItemID = ItemBL.saveWorkItem(workItemContext, errorDataList, actionID, confirm);
            if (!errorDataList.isEmpty()) {
                LOGGER.warn("There were " + errorDataList.size() + " error(s) by saving the item");
                if (LOGGER.isDebugEnabled()) {
                    debugErrors(errorDataList);
                }
                boolean onlyConfirm = true;
                for (ErrorData errorData : errorDataList) {
                    if (!errorData.isConfirm()) {
                        onlyConfirm = false;
                        break;
                    }
                }
                int errorCode = ItemSaveBL.ERROR_CODE.GENERAL;
                if (onlyConfirm) {
                    errorCode = ItemSaveBL.ERROR_CODE.CONFIRMATION;
                }
                jsonResponse = ItemSaveJSON.encodeErrorData(errorDataList, errorCode, locale);
            } else {
                String workItemIDDisplay = null;
                if (workItemContext.getWorkItemBean().getObjectID() != null) {
                    if (useProjectSpecificID) {
                        workItemIDDisplay = ItemBL.getSpecificProjectID(workItemContext);
                    } else {
                        workItemIDDisplay = workItemContext.getWorkItemBean().getObjectID().toString();
                    }
                }
                if (!isNew) {
                    ItemLockBL.removeLockedIssueBySession(workItemContext.getWorkItemBean().getObjectID(),
                            ServletActionContext.getRequest().getSession().getId());
                }
                jsonResponse = ItemSaveJSON.encodeSuccess(newWorkItemID, workItemIDDisplay,
                        workItemContext.getWorkItemBean().getSynopsis());

                /* The newly created work item, will be inserted after workItemIDAbove */
                if (workItemIDAbove != null) {
                    DAOFactory.getFactory().getWorkItemDAO().dropNearWorkItem(newWorkItemID, workItemIDAbove,
                            false);
                }
            }
        }
    }

    return encodeResult(jsonResponse);
}

From source file:org.frat.common.security.authc.SessionTimeoutAuthenticationFilter.java

@Override
protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response)
        throws IOException {
    saveRequest(request);//from  w  ww  . ja  va  2s  .  co m
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    if (WebUtil.isAjaxRequest(req)) {
        ObjectMapper objectMapper = new ObjectMapper();
        res.setContentType("application/json;charset=UTF-8");
        res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        ResultDto error = new ResultDto();
        error.setCode(ResultCode.SESSION_TIME_OUT);
        error.setMessage(MessageUtil.getMessage(SESSION_TIMEOUT_MSG));
        objectMapper.writeValue(response.getWriter(), error);
        LOGGER.debug("session time out for ajax request:{}", req.getRequestURI());
    } else {
        LOGGER.debug("session time out for request:{}", req.getRequestURI());
        req.getSession().setAttribute(SESSION_TIMEOUT, true);
        redirectToLogin(request, response);
    }
    HttpSession session = req.getSession(false);
    if (session != null) {
        LOGGER.debug(
                "session time out with id:"
                        + " {}, is sesion new:{}, started: {}, last accessed: {}, request headers: {}",
                session.getId(), session.isNew(),
                DateFormatUtils.format(session.getCreationTime(), DATE_FORMAT),
                DateFormatUtils.format(session.getLastAccessedTime(), DATE_FORMAT), getHeaderString(request));
    } else {
        LOGGER.debug("session time out, no session available for current request");
    }
}

From source file:at.gv.egiz.pdfas.web.helper.PdfAsHelper.java

public static void setErrorURL(HttpServletRequest request, HttpServletResponse response, String url) {
    HttpSession session = request.getSession();
    logger.debug("[" + session.getId() + "]: Setting Error URL to: " + url);
    session.setAttribute(PDF_ERR_URL, url);
}