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.jaspersoft.jasperserver.war.util.LRUSessionObjectAccessor.java

protected ObjectSerie getObjectSerie(HttpSession session) {
    Object mutex = WebUtils.getSessionMutex(session);
    ObjectSerie serie;/*from  w w w.j av a 2  s . c  o m*/
    boolean created = false;
    synchronized (mutex) {
        serie = (ObjectSerie) session.getAttribute(getListSessionName());
        if (serie == null) {
            created = true;
            serie = new ObjectSerie(getMaxSize(), getListener());
            session.setAttribute(getListSessionName(), serie);
        }
    }

    if (created && log.isDebugEnabled()) {
        log.debug(listSessionName + " created object serie " + serie + " for session " + session.getId());
    }

    return serie;
}

From source file:nl.strohalm.cyclos.utils.LoginHelper.java

/**
 * Returns the currently logged user, ensuring there is one
 *//*  w  ww .j  av  a  2s.c  om*/
public User validateLoggedUser(final HttpServletRequest request) {
    final HttpSession session = request.getSession();

    // Find the logged user
    final User user = getLoggedUser(request);
    if (user == null) {
        throw new LoggedOutException();
    }
    // Find the registered logged user for the session id
    User serviceUser;
    try {
        serviceUser = accessService.getLoggedUser(session.getId());
    } catch (final NotConnectedException e) {
        throw new LoggedOutException();
    }
    // The web container session indicates there is an user, but there's no tracked session: invalidate the session's user
    if (user != null && serviceUser == null) {
        session.removeAttribute("loggedUser");
        throw new LoggedOutException();
    } else {
        // Ensure they match
        final boolean valid = user != null && user.equals(serviceUser);
        if (!valid) {
            session.invalidate();
            throw new AccessDeniedException();
        }
    }
    return user;
}

From source file:org.apache.struts.webapp.example2.EditRegistrationAction.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.// w  ww  .j  a v a  2s.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";
    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"));
        }
    }

    // Populate the user registration form
    if (form == null) {
        if (log.isTraceEnabled()) {
            log.trace(" Creating new RegistrationForm bean under key " + mapping.getAttribute());
        }
        form = new RegistrationForm();
        if ("request".equals(mapping.getScope()))
            request.setAttribute(mapping.getAttribute(), form);
        else
            session.setAttribute(mapping.getAttribute(), form);
    }
    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");
    }
    if ("Create".equals(action)) {
        return (mapping.findForward("register"));
    } else {
        return (mapping.findForward("success"));
    }

}

From source file:com.twinsoft.convertigo.engine.servlets.GenericServlet.java

protected void removeSession(HttpServletRequest request, int interval) {
    if (Engine.isEngineMode()) {
        Engine.logContext.debug("[GenericServlet] End of session required => try to invalidate session");
        try {/*from   ww w  .java  2  s  . c  o m*/
            HttpSession httpSession = request.getSession();
            boolean isAdminSession = "true".equals((String) httpSession.getAttribute("administration"));
            if (!isAdminSession && Engine.theApp.contextManager.isSessionEmtpy(httpSession.getId())) {
                Engine.logContext.debug(
                        "[GenericServlet] The owner HTTP session is empty => invalidating HTTP session in "
                                + interval + "s.");
                httpSession.setMaxInactiveInterval(interval);
            }
        } catch (Exception e) {
            Engine.logContext
                    .debug("[GenericServlet] End of session required => failed to get the session: " + e);
        }
    }
}

From source file:org.beanfuse.security.monitor.SecurityFilter.java

/**
 * //from w w w . j av a 2  s . c o  m
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    String resource = resourceExtractor.extract(httpRequest);
    request.setAttribute("resourceName", resource);
    HttpSession session = httpRequest.getSession(true);
    if (null == monitor) {
        WebApplicationContext wac = WebApplicationContextUtils
                .getRequiredWebApplicationContext(session.getServletContext());
        monitor = (SecurityMonitor) wac.getBean("securityMonitor", SecurityMonitor.class);
    }
    // ??login??
    if (!freeResources.contains(resource) && !monitor.isPublicResource(resource)) {
        OnlineActivity info = monitor.getSessionController().getOnlineActivity(session.getId());
        if (info != null && null != httpRequest.getRemoteUser()
                && !info.getPrincipal().equals(httpRequest.getRemoteUser())) {
            info = null;
        }
        if (null == info) {
            Authentication auth = null;
            // remember me
            if (monitor.enableRememberMe()) {
                auth = monitor.getRememberMeService().autoLogin(httpRequest);
            }
            if (null == auth) {
                auth = new SsoAuthentication(httpRequest);
                auth.setDetails(monitor.getUserDetailsSource().buildDetails(httpRequest));
            }
            try {
                monitor.authenticate(auth);
            } catch (AuthenticationException e) {
                // URL
                session.setAttribute(PREVIOUS_URL,
                        httpRequest.getRequestURL() + "?" + httpRequest.getQueryString());
                redirectTo((HttpServletRequest) request, (HttpServletResponse) response, loginFailPath);
                return;
            }
        } else if (info.isExpired()) {
            monitor.logout(session);
            // URL
            session.setAttribute(PREVIOUS_URL,
                    httpRequest.getRequestURL() + "?" + httpRequest.getQueryString());
            redirectTo((HttpServletRequest) request, (HttpServletResponse) response, expiredPath);
            return;
        } else {
            info.refreshLastRequest();
            boolean pass = monitor.isAuthorized(info.getUserid(), resource);
            if (pass) {
                logger.debug("user {} access {} success", info.getPrincipal(), resource);
            } else {
                logger.info("user {} cannot access resource[{}]", info.getPrincipal(), resource);
                redirectTo((HttpServletRequest) request, (HttpServletResponse) response, noAuthorityPath);
                return;
            }
        }
    } else {
        logger.debug("free or public resource {} was accessed", resource);
    }
    chain.doFilter(request, response);
}

From source file:gov.nih.nci.ispy.web.taglib.CorrScatterPlotTag.java

public int doStartTag() {
    chart = null;/*  ww w .  j a va 2  s  . c o m*/
    plotPoints.clear();

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();

    try {
        //retrieve the Finding from cache and build the list of PCAData points
        ISPYCorrelationFinding corrFinding = (ISPYCorrelationFinding) businessTierCache
                .getSessionFinding(session.getId(), taskId);

        Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
        List<String> sampleIds = new ArrayList<String>();

        List<DataPoint> points = corrFinding.getDataPoints();

        ClinicalDataService cqs = ClinicalDataServiceFactory.getInstance();
        IdMapperFileBasedService idMapper = IdMapperFileBasedService.getInstance();

        List<ISPYPlotPoint> plotPoints = new ArrayList<ISPYPlotPoint>();
        ISPYPlotPoint pp;
        SampleInfo si;
        ISPYclinicalDataQueryDTO dto;
        Set<String> sampleHolder = new HashSet<String>(); //set just holds one entry need this for the dto
        Set<PatientData> dataHolder = new HashSet<PatientData>();
        PatientData pd = null;
        for (DataPoint p : points) {
            pp = new ISPYPlotPoint(p.getId());
            pp.setX(p.getX());
            pp.setY(p.getY());
            pp.setZ(p.getZ());

            String patientId = null;

            if (corrFinding.isSampleBased()) {
                si = idMapper.getSampleInfoForLabtrackId(p.getId());
                if (si != null) {
                    pp.setSampleInfo(si);
                    patientId = si.getISPYId();
                } else {
                    logger.warn("Could not get sample info for DataPoint=" + p.getId());
                }
            } else if (corrFinding.isPatientBased()) {
                patientId = p.getId();
            }

            if (patientId != null) {
                dto = new ISPYclinicalDataQueryDTO();
                sampleHolder.clear();
                sampleHolder.add(patientId);
                dto.setRestrainingSamples(sampleHolder);
                dataHolder.clear();
                dataHolder = cqs.getClinicalData(dto);

                if (dataHolder.size() == 1) {
                    Iterator i = dataHolder.iterator();
                    pd = (PatientData) i.next();
                    pp.setPatientData(pd);
                } else {
                    logger.error("Internal Error. Did not get back correct patient data for  patientId="
                            + patientId);
                }
            }

            plotPoints.add(pp);
        }

        ISPYCorrelationScatterPlot plot = new ISPYCorrelationScatterPlot(plotPoints,
                corrFinding.getGroup1Name(), corrFinding.getGroup2Name(), corrFinding.getContinuousType1(),
                corrFinding.getContinuousType2(), corrFinding.getCorrelationValue(),
                ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase()));
        chart = plot.getChart();
        ISPYImageFileHandler imageHandler = new ISPYImageFileHandler(session.getId(), "png", 650, 600);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        String finalURLpath = imageHandler.getFinalURLPath();
        /*
         * Create the actual charts, writing it to the session temp folder
        */
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        String mapName = imageHandler.createUniqueMapName();
        //PrintWriter writer = new PrintWriter(new FileWriter(mapName));
        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 650, 600, info);
        //ImageMapUtil.writeBoundingRectImageMap(writer,"PCAimageMap",info,true);
        //writer.close();

        /*   This is here to put the thread into a loop while it waits for the
         *   image to be available.  It has an unsophisticated timer but at 
         *   least it is something to avoid an endless loop.
         **/
        boolean imageReady = false;
        int timeout = 1000;
        FileInputStream inputStream = null;
        while (!imageReady) {
            timeout--;
            try {
                inputStream = new FileInputStream(finalPath);
                inputStream.available();
                imageReady = true;
                inputStream.close();
            } catch (IOException ioe) {
                imageReady = false;
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            if (timeout <= 1) {

                break;
            }
        }

        out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName, true, info));
        finalURLpath = finalURLpath.replace("\\", "/");
        long randomness = System.currentTimeMillis(); //prevent image caching
        out.print("<img id=\"geneChart\" name=\"geneChart\" src=\"" + finalURLpath + "?" + randomness
                + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

        //(imageHandler.getImageTag(mapFileName));

    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        logger.error(sw.toString());
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTest.java

@Test
public void buildRequestSessionInvalidate() throws Exception {
    String sessionId = "session-id";
    webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);

    MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
    HttpSession sessionToRemove = actualRequest.getSession();
    sessionToRemove.invalidate();//from   ww  w .  ja  va  2s .  c  o  m

    assertThat(!sessions.containsKey(sessionToRemove.getId()));
    assertSingleSessionCookie("JSESSIONID=" + sessionToRemove.getId()
            + "; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/test; Domain=example.com");

    webRequest.removeAdditionalHeader("Cookie");
    requestBuilder = new HtmlUnitRequestBuilder(sessions, cookieManager, webRequest);

    actualRequest = requestBuilder.buildRequest(servletContext);

    assertThat(actualRequest.getSession().isNew()).isTrue();
    assertThat(!sessions.containsKey(sessionToRemove.getId()));
}

From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTest.java

@Test
public void buildRequestSession() throws Exception {
    MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

    HttpSession newSession = actualRequest.getSession();
    assertThat(newSession).isNotNull();//from  w w w .  j a v  a  2  s  .  c  o m
    assertSingleSessionCookie("JSESSIONID=" + newSession.getId() + "; Path=/test; Domain=example.com");

    webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + newSession.getId());

    requestBuilder = new HtmlUnitRequestBuilder(sessions, cookieManager, webRequest);
    actualRequest = requestBuilder.buildRequest(servletContext);

    assertThat(actualRequest.getSession()).isSameAs(newSession);
}

From source file:com.aurel.track.attachment.AttachmentAction.java

public String thumbnail() {
    //TODO check if access is allowed for thumbnail attachment
    boolean isAccessAllowed = true;
    if (!isAccessAllowed) {
        addActionError("item.err.noAccess");
        LOGGER.debug("Access to attachment denied.");
        return null;
    }/*from   ww  w. ja  va  2 s.com*/
    String sessionID = null;
    TAttachmentBean attach = extractAttachmentBean();

    if (attach == null) {
        LOGGER.error("Error loading attachment with id " + attachKey + " for item " + workItemID);
        return null;
    }
    if (workItemID == null) {
        HttpServletRequest request = org.apache.struts2.ServletActionContext.getRequest();
        HttpSession httpSession = request.getSession();
        sessionID = httpSession.getId();
    }
    if (!AttachBL.isImage(attach)) {
        LOGGER.error("Attachment with id" + attachKey + " for item " + workItemID + " is not an image!");
        return null;
    }
    HttpServletResponse response = org.apache.struts2.ServletActionContext.getResponse();
    OutputStream outstream = null;
    try {
        outstream = response.getOutputStream();
    } catch (IOException e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        LOGGER.error("Error obtaining output stream from request." + e.getMessage());
        return null;
    }
    if (AttachBL.hasTumbnail(sessionID, attach)) {
        //Attach have thumb
    } else {
        boolean okThumb = AttachBL.createTumbnail(sessionID, attach);
        if (!okThumb) {
            LOGGER.error("Error get attachment thumbnail with id" + attachKey + " for item " + workItemID);
            return null;
        }
    }
    try {
        AttachBL.downloadThumb(sessionID, attach, outstream);
    } catch (AttachBLException e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        LOGGER.error("Error download attachemnt" + e.getMessage());
        return null;
    } finally {
        if (outstream != null) {
            try {
                outstream.flush();
                outstream.close();
            } catch (Exception t) {
                // just ignore
            }
        }
    }
    return null;
}

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

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

    // Extract attributes and parameters we will need
    MessageResources messages = getResources(request);
    HttpSession session = request.getSession();
    SubscriptionForm subform = (SubscriptionForm) form;
    String action = subform.getAction();
    if (action == null) {
        action = "?";
    }/*from  www .  j a v  a  2s . c o  m*/
    if (log.isDebugEnabled()) {
        log.debug("SaveSubscriptionAction:  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"));
    }

    // Was this transaction cancelled?
    if (isCancelled(request)) {
        if (log.isTraceEnabled()) {
            log.trace(" Transaction '" + action + "' was cancelled");
        }
        session.removeAttribute(Constants.SUBSCRIPTION_KEY);
        return (mapping.findForward("success"));
    }

    // Is there a related Subscription object?
    Subscription subscription = (Subscription) session.getAttribute(Constants.SUBSCRIPTION_KEY);
    if ("Create".equals(action)) {
        subscription = user.createSubscription(request.getParameter("host"));
    }
    if (subscription == null) {
        if (log.isTraceEnabled()) {
            log.trace(" Missing subscription for user '" + user.getUsername() + "'");
        }
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, messages.getMessage("error.noSubscription"));
        return (null);
    }

    // Was this transaction a Delete?
    if (action.equals("Delete")) {
        if (log.isTraceEnabled()) {
            log.trace(" Deleting mail server '" + subscription.getHost() + "' for user '" + user.getUsername()
                    + "'");
        }
        user.removeSubscription(subscription);
        session.removeAttribute(Constants.SUBSCRIPTION_KEY);
        try {
            UserDatabase database = (UserDatabase) servlet.getServletContext()
                    .getAttribute(Constants.DATABASE_KEY);
            database.save();
        } catch (Exception e) {
            log.error("Database save", e);
        }
        return (mapping.findForward("success"));
    }

    // All required validations were done by the form itself

    // Update the persistent subscription information
    if (log.isTraceEnabled()) {
        log.trace(" Populating database from form bean");
    }
    try {
        PropertyUtils.copyProperties(subscription, subform);
    } catch (InvocationTargetException e) {
        Throwable t = e.getTargetException();
        if (t == null)
            t = e;
        log.error("Subscription.populate", t);
        throw new ServletException("Subscription.populate", t);
    } catch (Throwable t) {
        log.error("Subscription.populate", t);
        throw new ServletException("Subscription.populate", t);
    }

    try {
        UserDatabase database = (UserDatabase) servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);
        database.save();
    } catch (Exception e) {
        log.error("Database save", e);
    }

    // Remove the obsolete form bean and current subscription
    if (mapping.getAttribute() != null) {
        if ("request".equals(mapping.getScope()))
            request.removeAttribute(mapping.getAttribute());
        else
            session.removeAttribute(mapping.getAttribute());
    }
    session.removeAttribute(Constants.SUBSCRIPTION_KEY);

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

}