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.aurel.track.item.ItemDetailAction.java

/**
 * Gets the list of attachments for the workItem
 * @return/*from w  ww.j  a  va  2  s.co m*/
 */
public String doGetAttachments() {
    String sessionID = null;
    List<TAttachmentBean> attachList;
    if (workItemID == null) {
        HttpServletRequest request = org.apache.struts2.ServletActionContext.getRequest();
        HttpSession httpSession = request.getSession();
        sessionID = httpSession.getId();
        WorkItemContext workItemContext = ((WorkItemContext) session.get("workItemContext"));
        attachList = workItemContext.getAttachmentsList();
        if (attachList != null && !attachList.isEmpty()) {
            for (int i = 0; i < attachList.size(); i++) {
                TAttachmentBean attachmentBean = attachList.get(i);
                if (attachmentBean.getChangedByName() == null
                        || attachmentBean.getChangedByName().length() == 0) {
                    attachmentBean.setChangedByName(person.getFullName());
                }
            }
        }
    } else {
        attachList = AttachBL.getAttachments(workItemID);
    }
    boolean isProjectActive = ProjectBL.projectIsActive(projectID);
    boolean editable = true;
    if (workItemID != null) {
        TWorkItemBean workItemBean = null;
        try {
            workItemBean = ItemBL.loadWorkItem(workItemID);
            ErrorData editPermissionErrorData = ItemBL.hasEditPermission(person.getObjectID(), workItemBean);
            if (editPermissionErrorData != null) {
                editable = false;
            }
        } catch (ItemLoaderException e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
        }

    }

    encodeTabJSON(ItemDetailBL.encodeJSON_Attachments(sessionID, attachList, locale, person.getObjectID(),
            isProjectActive, editable));
    return null;
}

From source file:org.wso2.carbon.ml.rest.api.LoginLogoutApiV10.java

/**
 * Logout./*from   www.  j av a 2 s  . co  m*/
 */
@POST
@Path("/logout")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response logout() {
    HttpSession session = httpServletRequest.getSession();
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    String username = carbonContext.getUsername();
    String tenantDomain = carbonContext.getTenantDomain();
    int tenantId = carbonContext.getTenantId();
    if (session != null) {
        session.invalidate();
    }
    auditLog.info(String.format(
            "User [name] %s of tenant [id] %s [domain] %s is logged-out from WSO2 Machine Learner. "
                    + "Granted session id is %s",
            username, tenantId, tenantDomain, session == null ? null : session.getId()));
    return Response.status(Response.Status.OK).entity("User logged out: " + carbonContext.getUsername())
            .build();
}

From source file:it.scoppelletti.programmerpower.web.spring.ApplicationContextListener.java

/**
 * Inizializzazione di una sessione.//from   w w w  .j  a  v  a2 s .co m
 * 
 * @param event Evento.
 */
public void sessionCreated(HttpSessionEvent event) {
    HttpSession session = event.getSession();
    EventContext eventCtx = null;

    if (mySessionListeners == null) {
        return;
    }

    try {
        eventCtx = new EventContext(ApplicationContextListener.THREAD_SESSION_CREATE,
                session.getServletContext());

        for (Map.Entry<String, HttpSessionListener> entry : mySessionListeners.entrySet()) {
            myLogger.trace("Calling method sessionCreated({}) of " + "HttpSessionListener {}.", session.getId(),
                    entry.getKey());
            try {
                entry.getValue().sessionCreated(event);
            } catch (Exception ex) {
                myLogger.error(entry.getKey(), ex);
            }
        }
    } finally {
        if (eventCtx != null) {
            eventCtx.dispose();
            eventCtx = null;
        }
    }
}

From source file:org.apache.struts.webapp.example.EditSubscriptionAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    HttpSession session = request.getSession();
    String action = request.getParameter("action");
    if (action == null) {
        action = "Create";
    }/*w w  w  .j  av  a 2  s .  c o m*/

    String host = request.getParameter("host");
    if (log.isDebugEnabled()) {
        log.debug("EditSubscriptionAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user?
    User user = (User) session.getAttribute(Constants.USER_KEY);
    if (user == null) {
        if (log.isTraceEnabled()) {
            log.trace(" User is not logged on in session " + session.getId());
        }
        return (mapping.findForward("logon"));
    }

    // Identify the relevant subscription
    Subscription subscription = user.findSubscription(request.getParameter("host"));

    if ((subscription == null) && !action.equals("Create")) {
        if (log.isTraceEnabled()) {
            log.trace(" No subscription for user " + user.getUsername() + " and host " + host);
        }

        return (mapping.findForward("failure"));
    }

    if (subscription != null) {
        session.setAttribute(Constants.SUBSCRIPTION_KEY, subscription);
    }

    SubscriptionForm subform = (SubscriptionForm) form;
    subform.setAction(action);
    if (!action.equals("Create")) {
        if (log.isTraceEnabled()) {
            log.trace(" Populating form from " + subscription);
        }

        try {
            PropertyUtils.copyProperties(subform, subscription);
            subform.setAction(action);

        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            if (t == null)
                t = e;
            log.error("SubscriptionForm.populate", t);
            throw new ServletException("SubscriptionForm.populate", t);

        } catch (Throwable t) {
            log.error("SubscriptionForm.populate", t);
            throw new ServletException("SubscriptionForm.populate", t);
        }
    }

    // Forward control to the edit subscription page
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to 'success' page");
    }

    return (mapping.findForward("success"));

}

From source file:org.kmnet.com.fw.web.token.transaction.TransactionTokenInterceptor.java

/**
 * Creates a new <code>TransactionToken</code> <br>
 * <p>//from   ww w  . j av a 2s . c om
 * Generated <code>TransactionToken</code> instance is stored in <code>TransactionTokenStore</code> and also set to request
 * attribute <code>TransactionTokenInterceptor.NEXT_TOKEN</code>.
 * <p>
 * @param request
 * @param session
 * @param tokenInfo TransactionTokenInfo
 * @param generator TokenStringGenerator
 * @param tokenStore TransactionTokenStore
 */
void createToken(HttpServletRequest request, HttpSession session, TransactionTokenInfo tokenInfo,
        TokenStringGenerator generator, TransactionTokenStore tokenStore) {
    TransactionToken nextToken;
    synchronized (WebUtils.getSessionMutex(session)) {
        String tokenKey = tokenStore.createAndReserveTokenKey(tokenInfo.getTokenName());
        nextToken = new TransactionToken(tokenInfo.getTokenName(), tokenKey,
                generator.generate(session.getId()));
        tokenStore.store(nextToken);
    }
    request.setAttribute(NEXT_TOKEN_REQUEST_ATTRIBUTE_NAME, nextToken);
}

From source file:org.apache.struts.webapp.example.EditRegistrationAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    HttpSession session = request.getSession();
    String action = request.getParameter("action");
    if (action == null) {
        action = "Create";
    }/*from w  ww . j  av  a2 s  . c  o  m*/

    if (log.isDebugEnabled()) {
        log.debug("EditRegistrationAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user?
    User user = null;
    if (!"Create".equals(action)) {
        user = (User) session.getAttribute(Constants.USER_KEY);
        if (user == null) {
            if (log.isDebugEnabled()) {
                log.debug(" User is not logged on in session " + session.getId());
            }
            return (mapping.findForward("logon"));
        }
    }

    RegistrationForm regform = (RegistrationForm) form;
    if (user != null) {
        if (log.isTraceEnabled()) {
            log.trace(" Populating form from " + user);
        }

        try {
            PropertyUtils.copyProperties(regform, user);
            regform.setAction(action);
            regform.setPassword(null);
            regform.setPassword2(null);

        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            if (t == null)
                t = e;
            log.error("RegistrationForm.populate", t);
            throw new ServletException("RegistrationForm.populate", t);

        } catch (Throwable t) {
            log.error("RegistrationForm.populate", t);
            throw new ServletException("RegistrationForm.populate", t);
        }
    }

    // Set a transactional control token to prevent double posting
    if (log.isTraceEnabled()) {
        log.trace(" Setting transactional control token");
    }

    saveToken(request);

    // Forward control to the edit user registration page
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to 'success' page");
    }

    return (mapping.findForward("success"));

}

From source file:org.apache.struts.webapp.example2.EditSubscriptionAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.//from  w w  w  . j a v a 2  s.  c  o  m
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if the application business logic throws
 *  an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    Locale locale = getLocale(request);
    MessageResources messages = getResources(request);
    HttpSession session = request.getSession();
    String action = request.getParameter("action");
    if (action == null) {
        action = "Create";
    }
    String host = request.getParameter("host");
    if (log.isDebugEnabled()) {
        log.debug("EditSubscriptionAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user?
    User user = (User) session.getAttribute(Constants.USER_KEY);
    if (user == null) {
        if (log.isTraceEnabled()) {
            log.trace(" User is not logged on in session " + session.getId());
        }
        return (mapping.findForward("logon"));
    }

    // Identify the relevant subscription
    Subscription subscription = user.findSubscription(request.getParameter("host"));
    if ((subscription == null) && !action.equals("Create")) {
        if (log.isTraceEnabled()) {
            log.trace(" No subscription for user " + user.getUsername() + " and host " + host);
        }
        return (mapping.findForward("failure"));
    }
    if (subscription != null) {
        session.setAttribute(Constants.SUBSCRIPTION_KEY, subscription);
    }

    // Populate the subscription form
    if (form == null) {
        if (log.isTraceEnabled()) {
            log.trace(" Creating new SubscriptionForm bean under key " + mapping.getAttribute());
        }
        form = new SubscriptionForm();
        if ("request".equals(mapping.getScope())) {
            request.setAttribute(mapping.getAttribute(), form);
        } else {
            session.setAttribute(mapping.getAttribute(), form);
        }
    }
    SubscriptionForm subform = (SubscriptionForm) form;
    subform.setAction(action);
    if (!action.equals("Create")) {
        if (log.isTraceEnabled()) {
            log.trace(" Populating form from " + subscription);
        }
        try {
            PropertyUtils.copyProperties(subform, subscription);
            subform.setAction(action);
        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            if (t == null)
                t = e;
            log.error("SubscriptionForm.populate", t);
            throw new ServletException("SubscriptionForm.populate", t);
        } catch (Throwable t) {
            log.error("SubscriptionForm.populate", t);
            throw new ServletException("SubscriptionForm.populate", t);
        }
    }

    // Forward control to the edit subscription page
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to 'success' page");
    }
    return (mapping.findForward("success"));

}

From source file:it.scoppelletti.programmerpower.web.spring.ApplicationContextListener.java

/**
 * Termine di una sessione./*from  w  w w.  ja v a 2s.  c  o  m*/
 * 
 * @param event Evento.
 */
public void sessionDestroyed(HttpSessionEvent event) {
    HttpSession session = event.getSession();
    EventContext eventCtx = null;

    if (mySessionListeners == null) {
        return;
    }

    try {
        eventCtx = new EventContext(ApplicationContextListener.THREAD_SESSION_DESTROY,
                session.getServletContext());

        for (Map.Entry<String, HttpSessionListener> entry : mySessionListeners.entrySet()) {
            myLogger.trace("Calling method sessionDestroyed({}) of " + "HttpSessionListener {}.",
                    session.getId(), entry.getKey());
            try {
                entry.getValue().sessionDestroyed(event);
            } catch (Exception ex) {
                myLogger.error(entry.getKey(), ex);
            }
        }
    } finally {
        if (eventCtx != null) {
            eventCtx.dispose();
            eventCtx = null;
        }
    }
}

From source file:de.sub.goobi.forms.ModuleServerForm.java

/**
 * Eine Shortsession fr einen Schritt starten.
 *///  w  w w.j a  v  a  2s. c  o  m
public String startShortSession(Task inSchritt) throws GoobiException, XmlRpcException {
    myModule = null;
    if (inSchritt.getTypeModuleName() == null || inSchritt.getTypeModuleName().length() == 0) {
        Helper.setFehlerMeldung("this step has no mudule");
        return null;
    }

    /*
     * zustzliche Parameter neben dem Modulnamen
     */
    HashMap<String, Object> typeParameters = new HashMap<>();
    String schrittModuleName = inSchritt.getTypeModuleName();
    StrTokenizer tokenizer = new StrTokenizer(inSchritt.getTypeModuleName());
    int counter = 0;
    while (tokenizer.hasNext()) {
        String tok = (String) tokenizer.next();
        if (counter == 0) {
            schrittModuleName = tok;
        } else {
            if (tok.contains(":")) {
                String key = tok.split(":")[0];
                String value = tok.split(":")[1];
                typeParameters.put(key, value);
            }
        }
        counter++;
    }

    /*
     * Modulserver luft noch nicht
     */
    if (modulmanager == null) {
        throw new GoobiException(0, "Der Modulserver luft nicht");
    }

    /*
     * ohne gewhltes Modul gleich wieder raus
     */
    for (ModuleDesc md : modulmanager) {
        if (md.getName().equals(schrittModuleName)) {
            myModule = md;
        }
    }
    if (myModule == null) {
        Helper.setFehlerMeldung("Module not found");
        return null;
    }

    /*
     * Verbindung zum Modul aufbauen und url zurckgeben
     */
    String processId = String.valueOf(inSchritt.getProcess().getId().intValue());
    String tempID = UniqueID.generate_session();
    myRunningShortSessions.put(tempID, processId);

    GoobiModuleParameter gmp1 = new GoobiModuleParameter(processId, tempID,
            myModule.getModuleClient().longsessionID, typeParameters);
    HttpSession insession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext()
            .getSession(false);

    String applicationUrl = new HelperForm().getServletPathWithHostAsUrl();
    gmp1.put("return_url", applicationUrl + HelperForm.MAIN_JSF_PATH
            + "/AktuelleSchritteBearbeiten.jsf?jsessionId=" + insession.getId());
    myModule.getGmps().add(gmp1); // add session in den Manager
    return myModule.getModuleClient().start(gmp1);
}

From source file:org.workspace7.moviestore.controller.HomeController.java

@GetMapping("/")
public ModelAndView home(ModelAndView modelAndView, HttpServletRequest request) {

    final String hostname = System.getenv().getOrDefault("HOSTNAME", "unknown");
    log.info("Request served by HOST {} ", hostname);

    HttpSession session = request.getSession(false);

    List<Movie> movies = movieDBHelper.getAll();

    List<MovieCartItem> movieList = movies.stream()
            .map((Movie movie) -> MovieCartItem.builder().movie(movie).quantity(1).total(0).build())
            .collect(Collectors.toList());

    if (session != null) {
        AdvancedCache<String, Object> sessionCache = (AdvancedCache<String, Object>) cacheManager
                .getCache("moviestore-sessions-cache").getNativeCache();

        Optional<MapSession> mapSession = Optional.ofNullable((MapSession) sessionCache.get(session.getId()));

        log.info("Session already exists, retrieving values from session {}", mapSession);

        int cartCount = 0;

        if (mapSession.isPresent()) {

            MovieCart movieCart = mapSession.get().getAttribute(ShoppingCartController.SESSION_ATTR_MOVIE_CART);

            if (movieCart != null) {

                log.info("Movie Cart:{} for session id:{}", movieCart, session.getId());

                final Map<String, Integer> movieItems = movieCart.getMovieItems();

                movieList = movieList.stream().map(movieCartItem -> {
                    Movie movie = movieCartItem.getMovie();
                    String movieId = movie.getId();
                    if (movieItems.containsKey(movieId)) {
                        int quantity = movieItems.get(movieId);
                        movieCartItem.setQuantity(quantity);
                    } else {
                        movieCartItem.setQuantity(1);
                    }/*from   w w w  .j  a  va  2s.co m*/
                    return movieCartItem;

                }).collect(Collectors.toList());

                cartCount = movieItems.size();
            }
        }
        modelAndView.addObject("cartCount", cartCount);
        modelAndView.addObject("movies", movieList);
    } else {
        log.info("New Session");
        modelAndView.addObject("movies", movieList);
    }
    modelAndView.setViewName("home");
    modelAndView.addObject("hostname", hostname);
    return modelAndView;
}