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:org.jahia.modules.spamfiltering.rules.SpamFilteringRuleService.java

/**
 * Verifies the content of the node with anti-spam service and applies spam filtering (by assigning a special mixin).
 * //  w  w  w .j a  v  a  2  s.  co m
 * @param nodeFact
 *            the node which content should be checked
 * @param maxSpamCount the number of maximum spams tolerated before the user is locked and his session is killed.
 * @param drools
 *            the rule engine helper class
 * @throws RepositoryException
 *             in case of an error
 */
public void checkForSpam(AddedNodeFact nodeFact, Integer maxSpamCount, KnowledgeHelper drools)
        throws RepositoryException {
    if (logger.isDebugEnabled()) {
        logger.debug("Checking content of the node {} for spam", nodeFact.getPath());
    }

    try {
        User user = (User) drools.getWorkingMemory().getGlobal("user");

        HttpServletRequest httpServletRequest = spamFilter.getHttpServletRequest();

        if (httpServletRequest == null) {
            // we didn't manage to get the request from our own filter, try to access it through Spring MVC's
            // framework
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) {
                ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
                httpServletRequest = servletRequestAttributes.getRequest();
            }
        }

        boolean isSpam = false;
        JCRNodeWrapper node = nodeFact.getNode();
        String text = getTextContent(node);
        if (StringUtils.isNotEmpty(text)) {
            isSpam = spamFilteringService.isSpam(text, node, httpServletRequest);
        }

        if (isSpam) {
            if (!node.isNodeType(SPAM_DETECTED_MIXIN)) {
                // is detected as spam -> add mixin
                node.getSession().checkout(node);
                node.addMixin(SPAM_DETECTED_MIXIN);
            }
            if (maxSpamCount != null && httpServletRequest != null) {
                HttpSession httpSession = httpServletRequest.getSession(false);
                JahiaUser jahiaUser = user.getJahiaUser();
                if (httpSession != null && !"guest".equals(jahiaUser.getName())) {
                    String spamSessionsValue = jahiaUser.getProperty(SPAM_SESSIONS_PROPERTY_NAME);
                    List<String> spamSessions = new ArrayList<String>();
                    if (spamSessionsValue != null) {
                        spamSessions.addAll(Arrays.asList(spamSessionsValue.split(",")));
                    }

                    spamSessions.add(httpSession.getId());

                    if (spamSessions.size() >= maxSpamCount) {
                        logger.info("Maximum number of spam count reached (" + maxSpamCount
                                + "), locking user account and killing session...");
                        logger.info("Marking session " + httpSession.getId()
                                + " as invalid and will be killed on next access.");
                        spamFilter.addSessionToKill(httpSession.getId());
                        // add code to lock account
                        logger.info("Locking account " + jahiaUser + "...");
                        jahiaUser.setProperty("j:accountLocked", "true");
                        if (sendSpamNotificationEmails) {
                            logger.info("Sending account lock notification to administrator...");
                            sendAccountLockNotification(node, jahiaUser, httpServletRequest);
                        }
                        // we clear the session list to avoid it growing to big
                        spamSessions.clear();
                    } else {
                        logger.info("User " + jahiaUser + " has sent " + spamSessions.size() + " spam so far.");
                    }

                    if (spamSessions.size() > 0) {
                        jahiaUser.setProperty(SPAM_SESSIONS_PROPERTY_NAME, StringUtils.join(spamSessions, ","));
                    } else {
                        jahiaUser.removeProperty(SPAM_SESSIONS_PROPERTY_NAME);
                    }

                }
            }
        } else if (node.isNodeType(SPAM_DETECTED_MIXIN)) {
            // no longer spam -> remove mixin
            node.getSession().checkout(node);
            node.removeMixin(SPAM_DETECTED_MIXIN);
        }
        logger.info("Content of the node {} is{} detected as spam", node.getPath(), !isSpam ? " not" : "");
    } catch (Exception e) {
        logger.warn("Unable to check the content of the node " + nodeFact.getPath() + " for spam. Cause: "
                + e.getMessage(), e);
    }
}

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

@Test
public void buildRequestSessionWithExistingSession() throws Exception {
    String sessionId = "session-id";
    webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
    MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

    HttpSession session = actualRequest.getSession();
    assertThat(session.getId(), equalTo(sessionId));
    assertSingleSessionCookie("JSESSIONID=" + session.getId() + "; Path=/test; Domain=example.com");

    requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);
    actualRequest = requestBuilder.buildRequest(servletContext);
    assertThat(actualRequest.getSession(), equalTo(session));

    webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId + "NEW");
    actualRequest = requestBuilder.buildRequest(servletContext);
    assertThat(actualRequest.getSession(), not(equalTo(session)));
    assertSingleSessionCookie(//from w  w w.  j  a  v a  2s. c  o  m
            "JSESSIONID=" + actualRequest.getSession().getId() + "; Path=/test; Domain=example.com");
}

From source file:it.scoppelletti.programmerpower.web.security.SsoAuthenticationService.java

/**
 * Autenticazione SSO.//from ww w.  j av  a  2s  . c  om
 * 
 * @param  req  Richiesta.
 * @param  resp Risposta.
 * @return      Token autenticato. Se il SSO non avviene, restituisce
 *              {@code null}.  
 */
private Authentication singleSignOn(HttpServletRequest req, HttpServletResponse resp) {
    String tgt, ticket;
    HttpSession session;
    Authentication result;
    AbstractAuthenticationToken authRequest;

    tgt = getTicketGrantingTicket(req, resp);
    if (Strings.isNullOrEmpty(tgt)) {
        return null;
    }

    try {
        ticket = myCasClient.newServiceTicket(tgt);
    } catch (IOException ex) {
        myCasClient.removeTicketGrantingTicket(req, resp);
        throw new AuthenticationServiceException("Single Sing-On failed.", ex);
    }

    session = req.getSession(true);
    myLogger.debug("New ticket {} for session {}.", ticket, session.getId());

    authRequest = new UsernamePasswordAuthenticationToken(CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER,
            ticket);
    authRequest.setDetails(myAuthDetailsSource.buildDetails(req));

    result = myAuthManager.authenticate(authRequest);
    if (result == null) {
        return null;
    }

    myCasClient.addAuthenticatedSession(ticket, session);

    return result;
}

From source file:edu.harvard.i2b2.fhir.server.ws.I2b2FhirWS.java

private Resource getParticularResource(HttpServletRequest request, String resourceName, String id,
        HttpHeaders headers) throws IOException, XQueryUtilException, JAXBException, AuthenticationFailure,
        FhirServerException, InterruptedException {
    MetaResourceDb md = new MetaResourceDb();
    String msg = null;/*ww  w . j  a  va  2  s. c o  m*/
    Resource r = null;
    Bundle s = null;
    String mediaType = null;

    HttpSession session = request.getSession();
    authService.authenticateSession(headers.getRequestHeader(AuthenticationFilter.AUTHENTICATION_HEADER).get(0),
            session);

    logger.debug("session id:" + session.getId());
    logger.info("searching particular resource:<" + resourceName + "> with id:<" + id + ">");
    Class c = FhirUtil.getResourceClass(resourceName);
    if (c == null)
        throw new RuntimeException("class not found for resource:" + resourceName);

    if (FhirHelper.isPatientDependentResource(c)) {

        String patientId = id;
        if (patientId.contains("-"))
            patientId = patientId.split("-")[0];

        s = I2b2Helper.parsePatientIdToFetchPDO(session, request.getRequestURI(), request.getQueryString(),
                resourceName, service, ppmMgr, patientId);
        md.addBundle(s);
    } else {
        FhirHelper.loadTestResources(md);
    }
    r = md.getParticularResource(c, id);
    return r;
}

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

@SuppressWarnings({ "unchecked", "rawtypes" })
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    try {//from  www .java  2s . c  o m
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            String errorMessage;
            String tempFilePath = System.getProperty("java.io.tmpdir");

            if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) {
                tempFilePath += System.getProperty("file.separator");
            }
            tempFilePath += loggedInUser.getUserName() + "_" + session.getId();

            String revisionId = "", comments = "", fileName = "", ext = "", version = "";
            int documentId = 0;
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest((HttpServletRequest) request);
            upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING);
            //Create a file upload progress listener

            Iterator iter = items.iterator();
            FileItem item = null;
            File file = null;
            while (iter.hasNext()) {
                item = (FileItem) iter.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString(HTTPConstants.CHARACTER_ENCODING);
                    if (name.equals("documentid")) {
                        try {
                            documentId = Integer.parseInt(value);
                        } catch (Exception ex) {
                            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
                            return (new CheckInDocumentView(request, response));
                        }
                    } else if (name.equals("revisionid")) {
                        revisionId = value;
                    } else if (name.equals("txtNote")) {
                        comments = value;
                    } else if ("version".equalsIgnoreCase(name)) {
                        version = value;
                    }
                } else {
                    fileName = item.getName();
                    ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                    file = new File(tempFilePath + "." + ext);
                    item.write(file);
                }
            }
            iter = null;

            Document document = DocumentDAO.getInstance().readDocumentById(documentId);
            if (document == null) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid document");
                return (new CheckInDocumentView(request, response));
            }
            if (document.getStatus().equalsIgnoreCase(Hit.STATUS_AVAILABLE)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid check-in");
                return (new CheckInDocumentView(request, response));
            }
            revisionId = document.getRevisionId();
            DocumentClass documentClass = DocumentClassDAO.getInstance()
                    .readDocumentClassById(document.getClassId());
            AccessControlManager aclManager = new AccessControlManager();
            ACL acl = aclManager.getACL(documentClass, loggedInUser);
            if (!acl.canCheckin()) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Access Denied");
                return (new CheckInDocumentView(request, response));
            }

            if (file.length() <= 0) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document");
                return (new CheckInDocumentView(request, response));
            }
            if (file.length() > documentClass.getMaximumFileSize()) { //code for checking maximum size of document in a class
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Document size exceeded");
                return (new CheckInDocumentView(request, response));
            }

            String indexValue = "";
            String indexName = "";

            Hashtable indexRecord = new Hashtable();
            for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) {
                indexName = indexDefinition.getIndexColumnName();
                Iterator itemsIterator = items.iterator();
                while (itemsIterator.hasNext()) {
                    FileItem fileItem = (FileItem) itemsIterator.next();
                    if (fileItem.isFormField()) {
                        String name = fileItem.getFieldName();
                        String value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING);
                        if (name.equals(indexName)) {
                            indexValue = value;
                            if (indexValue != null) {
                                if (indexDefinition.isMandatory()) {
                                    if (indexValue.trim().length() <= 0) {
                                        errorMessage = "Invalid input for "
                                                + indexDefinition.getIndexDisplayName();
                                        request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage);
                                        return (new CheckInDocumentView(request, response));
                                    }
                                }
                                if (IndexDefinition.INDEXTYPE_NUMBER
                                        .equalsIgnoreCase(indexDefinition.getIndexType())) {
                                    if (indexValue.trim().length() > 0) {
                                        if (!GenericValidator.matchRegexp(indexValue,
                                                HTTPConstants.NUMERIC_REGEXP)) {
                                            errorMessage = "Invalid input for "
                                                    + indexDefinition.getIndexDisplayName();
                                            request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage);
                                            return (new CheckInDocumentView(request, response));
                                        }
                                    }
                                } else if (IndexDefinition.INDEXTYPE_DATE
                                        .equalsIgnoreCase(indexDefinition.getIndexType())) {
                                    if (indexValue.trim().length() > 0) {
                                        if (!GenericValidator.isDate(indexValue, "yyyy-MM-dd", true)) {
                                            errorMessage = "Invalid input for "
                                                    + indexDefinition.getIndexDisplayName();
                                            request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage);
                                            return (new CheckInDocumentView(request, response));
                                        }
                                    }
                                }

                                if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking maximum length of index field
                                    errorMessage = "Document index length exceeded.  Index Name :" +

                                            indexDefinition.getIndexDisplayName() + " [ " + "Index Length : "
                                            + indexDefinition.getIndexMaxLength() + " , " + "Actual Length  : "
                                            + indexValue.length() + " ]";
                                    request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage);
                                    return (new CheckInDocumentView(request, response));
                                }
                            }
                            indexRecord.put(indexName, indexValue);
                        }
                    }
                    fileItem = null;
                } // while iter
                itemsIterator = null;
            } // while indexDefinitionItr

            CheckedOutDocument checkedOutDocument = new CheckedOutDocument();
            checkedOutDocument.setDocumentId(documentId);
            // Added by Viral Visaria. For the Version Control minor and major.
            // In minor revision increment by 0.1. (No Changes required for the minor revision its handled in the core logic) 
            // In major revision increment by 1.0  (Below chages are incremented by 0.9 and rest 0.1 will be added in the core logic. (0.9 + 0.1 = 1.0)
            double rev = Double.parseDouble(revisionId);
            if ("major".equals(version)) {
                rev = Math.floor(rev);
                rev = rev + 0.9;
                revisionId = String.valueOf(rev);
            }
            checkedOutDocument.setRevisionId(revisionId);
            checkedOutDocument.setUserName(loggedInUser.getUserName());
            RevisionManager revisionManager = new RevisionManager();
            revisionManager.checkIn(checkedOutDocument, documentClass, indexRecord, file, comments, ext,
                    loggedInUser.getUserName());

            //revision id incremented by 0.1 for making entry in audit log 
            rev += 0.1;
            revisionId = String.valueOf(rev);
            //add to audit log 
            AuditLogManager.log(new AuditLogRecord(documentId, AuditLogRecord.OBJECT_DOCUMENT,
                    AuditLogRecord.ACTION_CHECKIN, loggedInUser.getUserName(), request.getRemoteAddr(),
                    AuditLogRecord.LEVEL_INFO, "Document ID :  " + documentId + " Revision ID :" + revisionId,
                    "Checked In"));
            request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Document checked in successfully");
            return (new CheckInDocumentView(request, response));
        }
        int documentId = 0;
        try {
            documentId = Integer.parseInt(
                    request.getParameter("documentid") != null ? request.getParameter("documentid") : "0");
        } catch (Exception e) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
            return (new CheckInDocumentView(request, response));
        }
        Document document = DocumentDAO.getInstance().readDocumentById(documentId);
        if (document == null) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid document");
            return (new CheckInDocumentView(request, response));
        }
        if (!Hit.STATUS_LOCKED.equalsIgnoreCase(document.getStatus())) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid checkin");
            return (new CheckInDocumentView(request, response));
        }
        DocumentClass documentClass = DocumentClassDAO.getInstance()
                .readDocumentClassById(document.getClassId());
        LinkedHashMap<String, String> documentIndexes = IndexRecordManager.getInstance()
                .readIndexRecord(documentClass, documentId, document.getRevisionId());

        request.setAttribute("DOCUMENTCLASS", documentClass);
        request.setAttribute("DOCUMENT", document);
        request.setAttribute("DOCUMENTINDEXES", documentIndexes);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return (new CheckInDocumentView(request, response));
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * This method parses the submit action, puts in session a listener where the
 * progress status is updated, and eventually stores the received data in
 * the user session./*from ww w  .  j a v a 2  s. c o  m*/
 * 
 * returns null in the case of success or a string with the error
 * 
 */
@SuppressWarnings("unchecked")
protected String parsePostRequest(HttpServletRequest request, HttpServletResponse response) {

    try {
        String delay = request.getParameter(PARAM_DELAY);
        uploadDelay = Integer.parseInt(delay);
    } catch (Exception e) {
    }

    HttpSession session = request.getSession();

    logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received.");

    AbstractUploadListener listener = getCurrentListener(request);
    if (listener != null) {
        if (listener.isFrozen() || listener.isCanceled() || listener.getPercent() >= 100) {
            removeCurrentListener(request);
        } else {
            String error = getMessage("busy");
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") " + error);
            return error;
        }
    }
    // Create a file upload progress listener, and put it in the user session,
    // so the browser can use ajax to query status of the upload process
    listener = createNewListener(request);

    List<FileItem> uploadedItems;
    try {

        // Call to a method which the user can override
        checkRequest(request);

        // Create the factory used for uploading files,
        FileItemFactory factory = getFileItemFactory(request.getContentLength());
        ServletFileUpload uploader = new ServletFileUpload(factory);
        uploader.setSizeMax(maxSize);
        uploader.setProgressListener(listener);

        // Receive the files
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsing HTTP POST request ");
        uploadedItems = uploader.parseRequest(request);
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsed request, " + uploadedItems.size()
                + " items received.");

        // Received files are put in session
        Vector<FileItem> sessionFiles = (Vector<FileItem>) getSessionFileItems(request);
        if (sessionFiles == null) {
            sessionFiles = new Vector<FileItem>();
        }

        String error = "";
        session.setAttribute(SESSION_LAST_FILES, uploadedItems);

        if (uploadedItems.size() > 0) {
            sessionFiles.addAll(uploadedItems);
            String msg = "";
            for (FileItem i : sessionFiles) {
                msg += i.getFieldName() + " => " + i.getName() + "(" + i.getSize() + " bytes),";
            }
            logger.debug("UPLOAD-SERVLET (" + session.getId() + ") puting items in session: " + msg);
            session.setAttribute(SESSION_FILES, sessionFiles);
        } else {
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") error NO DATA received ");
            error += getMessage("no_data");
        }

        return error.length() > 0 ? error : null;

    } catch (SizeLimitExceededException e) {
        RuntimeException ex = new UploadSizeLimitException(e.getPermittedSize(), e.getActualSize());
        listener.setException(ex);
        throw ex;
    } catch (UploadSizeLimitException e) {
        listener.setException(e);
        throw e;
    } catch (UploadCanceledException e) {
        listener.setException(e);
        throw e;
    } catch (UploadTimeoutException e) {
        listener.setException(e);
        throw e;
    } catch (Exception e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Unexpected Exception -> "
                + e.getMessage() + "\n" + stackTraceToString(e));
        e.printStackTrace();
        RuntimeException ex = new UploadException(e);
        listener.setException(ex);
        throw ex;
    }
}

From source file:SessionSnoop.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    HttpSession session = req.getSession();

    Integer count = (Integer) session.getAttribute("count");
    if (count == null)
        count = new Integer(1);
    else//from w w  w.j ava  2  s. com
        count = new Integer(count.intValue() + 1);
    session.setAttribute("count", count);

    out.println("<HTML><HEAD><TITLE>Session Count</TITLE></HEAD>");
    out.println("<BODY><H1>Session Count</H1>");

    out.println("You've visited this page " + count + ((count == 1) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
}

From source file:com.egt.core.util.Utils.java

public void trace(String objeto, String metodo, String contexto) {
    System.out.println(objeto + "." + metodo + "(" + contexto + ")");
    FacesContext facesContext = FacesContext.getCurrentInstance();
    System.out.println(objeto + "." + metodo + "(" + facesContext + ")");
    if (facesContext == null) {
        return;//  w w  w  . j a  v a2s  .  com
    }
    traceContext();
    HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
    System.out.println("request ..................... " + request);
    System.out.println("request.getAuthType ......... " + request.getAuthType());
    System.out.println("request.getUserPrincipal .... " + request.getUserPrincipal());
    Principal principal = facesContext.getExternalContext().getUserPrincipal();
    System.out.println("principal ................... " + principal);
    if (principal != null) {
        System.out.println("principal.getName ........... " + principal.getName());
        System.out.println("isSuperUsuario .............. " + request.isUserInRole("SuperUsuario"));
        System.out.println("isUsuarioEstandar ........... " + request.isUserInRole("UsuarioEstandar"));
        System.out.println("isUsuarioBasico.. ........... " + request.isUserInRole("UsuarioBasico"));
    }
    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
    HttpSession session = request.getSession(false);
    System.out.println("session ..................... " + facesContext.getExternalContext().getSession(false));
    System.out.println("session.getId ............... " + session.getId());
    String key;
    Object object;
    Set sessionKeys = facesContext.getExternalContext().getSessionMap().keySet();
    if (sessionKeys.isEmpty()) {
    } else {
        Iterator iterator = sessionKeys.iterator();
        while (iterator.hasNext()) {
            object = iterator.next();
            if (object instanceof String) {
                key = (String) object;
                object = facesContext.getExternalContext().getSessionMap().get(key);
                if (object != null) {
                    System.out.println(key + " = (" + object.getClass().getName() + ") " + object);
                }
            }
        }
    }
    System.out.println("request.getContextPath ...... " + request.getContextPath());
    System.out.println("request.getServletPath ...... " + request.getServletPath());
    System.out.println("request.getPathInfo ......... " + request.getPathInfo());
    System.out.println("request.getRequestURI ....... " + request.getRequestURI());
    System.out.println("request.getContextPathURL ... " + request.getRequestURL().toString());
    String clave;
    System.out.println("*** parametros ***");
    Iterator iterator = request.getParameterMap().keySet().iterator();
    while (iterator.hasNext()) {
        clave = (String) iterator.next();
        System.out.println(clave + " = " + request.getParameter(clave));
    }
    String cookieName;
    System.out.println("**** cookies  ****");
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookieName = cookies[i].getName();
            System.out.println(cookieName + " = " + cookies[i].getValue());
        }
    }
}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationFilterTest.java

@Test(expected = AccessDeniedException.class)
public void doFilterOtherTenantAccess() throws IOException, ServletException {
    HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    HttpServletResponse servletResponse = mock(HttpServletResponse.class);
    FilterChain filterChain = mock(FilterChain.class);
    HttpSession httpSession = mock(HttpSession.class);
    Authentication authResult = mock(Authentication.class);
    PaasManagerUser paasUser = mock(PaasManagerUser.class);

    when(servletRequest.getHeader(OpenStackAuthenticationFilter.OPENSTACK_HEADER_TOKEN))
            .thenReturn("3df25213cac246f8bccad5c70cb3582e");
    when(servletRequest.getHeader(OpenStackAuthenticationFilter.HEADER_ACCEPT)).thenReturn("application/json");
    when(servletRequest.getHeader(OpenStackAuthenticationFilter.OPENSTACK_HEADER_TENANTID))
            .thenReturn("00000000000000000000000000000194");

    when(servletRequest.getRequestURI()).thenReturn("/vdc/00000000000000000000000000000001/");
    when(servletRequest.getPathInfo()).thenReturn("/path");
    when(servletRequest.getSession()).thenReturn(httpSession);
    when(httpSession.getId()).thenReturn("1234");
    when(authenticationManager.authenticate(any(Authentication.class))).thenReturn(authResult);

    when(authResult.getPrincipal()).thenReturn(paasUser);

    // when// ww w .  ja v a2s .c o m
    openStackAuthenticationFilter.doFilter(servletRequest, servletResponse, filterChain);

    // then
    verify(servletRequest).getHeader(OpenStackAuthenticationFilter.OPENSTACK_HEADER_TOKEN);
    verify(servletRequest).getHeader(OpenStackAuthenticationFilter.HEADER_ACCEPT);
    verify(httpSession).getId();

}

From source file:MyServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    HttpSession session = req.getSession();

    Integer count = (Integer) session.getAttribute("snoop.count");
    if (count == null)
        count = new Integer(1);
    else//w w  w  .  j  a  va  2  s .c om
        count = new Integer(count.intValue() + 1);
    session.setAttribute("snoop.count", count);

    out.println("<HTML><HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
    out.println("<BODY><H1>Session Snoop</H1>");

    out.println("You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
}