Example usage for javax.servlet.http HttpServletRequest getSession

List of usage examples for javax.servlet.http HttpServletRequest getSession

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getSession.

Prototype

public HttpSession getSession();

Source Link

Document

Returns the current session associated with this request, or if the request does not have a session, creates one.

Usage

From source file:org.jruby.rack.mock.WebUtils.java

/**
 * Set the session attribute with the given name to the given value.
 * Removes the session attribute if value is null, if a session existed at all.
 * Does not create a new session if not necessary!
 * @param request current HTTP request/*from   w w w  .  j  a  v a 2s  . co m*/
 * @param name the name of the session attribute
 * @param value the value of the session attribute
 */
public static void setSessionAttribute(HttpServletRequest request, String name, Object value) {
    Assert.notNull(request, "Request must not be null");
    if (value != null) {
        request.getSession().setAttribute(name, value);
    } else {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.removeAttribute(name);
        }
    }
}

From source file:org.apache.ofbiz.passport.event.GitHubEvents.java

/**
 * Redirect to GitHub login page.//from  w  ww  .jav a2  s  .c  o  m
 * 
 * @return 
 */
public static String gitHubRedirect(HttpServletRequest request, HttpServletResponse response) {
    GenericValue oauth2GitHub = getOAuth2GitHubConfig(request);
    if (UtilValidate.isEmpty(oauth2GitHub)) {
        return "error";
    }

    String clientId = oauth2GitHub.getString(PassportUtil.COMMON_CLIENT_ID);
    String returnURI = oauth2GitHub.getString(PassportUtil.COMMON_RETURN_RUL);

    // Get user authorization code
    try {
        String state = System.currentTimeMillis() + String.valueOf((new Random(10)).nextLong());
        request.getSession().setAttribute(SESSION_GITHUB_STATE, state);
        String redirectUrl = TokenEndpoint + AuthorizeUri + "?client_id=" + clientId + "&scope=" + DEFAULT_SCOPE
                + "&redirect_uri=" + URLEncoder.encode(returnURI, "UTF-8") + "&state=" + state;
        Debug.logInfo("Request to GitHub: " + redirectUrl, module);
        response.sendRedirect(redirectUrl);
    } catch (NullPointerException e) {
        String errMsg = UtilProperties.getMessage(resource, "RedirectToGitHubOAuth2NullException",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    } catch (IOException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.toString());
        String errMsg = UtilProperties.getMessage(resource, "RedirectToGitHubOAuth2Error", messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }

    return "success";
}

From source file:ece356.UserDBAO.java

public static boolean isLoggedIn(HttpServletRequest request) {
    HttpSession session = request.getSession();
    UserData loggedInUser = (UserData) session.getAttribute("userData");
    return loggedInUser != null;
}

From source file:com.alkacon.opencms.documentcenter.NewDocumentsTree.java

/**
 * Returns a String which holds the selected categories for the result page of the new documents query.<p>
 * //from   w  ww  .  ja v  a  2 s .  co m
 * @param cms the CmsObject
 * @param request the HttpServletRequest
 * @param messageAll the localized message String used when all categories were selected
 * @return String with comma separated selected categories or localized "all" message
 */
public static String getCategories(CmsObject cms, HttpServletRequest request, String messageAll) {

    StringBuffer retValue = new StringBuffer(128);

    // get the current user's HHTP session
    //HttpSession session = ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getSession();
    HttpSession session = request.getSession();

    // get the required parameters
    String paramAll = (String) session.getAttribute(C_DOCUMENT_SEARCH_PARAM_ALL);

    if ("true".equals(paramAll)) {
        return messageAll;
    } else {
        List categories = getCategoryList((String) session.getAttribute(C_DOCUMENT_SEARCH_PARAM_CATEGORYLIST));
        Iterator i = categories.iterator();
        while (i.hasNext()) {
            String path = (String) i.next();
            try {
                retValue.append(cms.readPropertyObject(path, CmsCategory.CATEGORY_TITLE, false).getValue());
            } catch (CmsException e) {
                // noop
            }
            if (i.hasNext()) {
                retValue.append(", ");
            }
        }

        // clear objects to release memory
        categories = null;
        i = null;
    }
    return retValue.toString();
}

From source file:org.apache.ofbiz.passport.event.LinkedInEvents.java

/**
 * Redirect to LinkedIn login page./*from w  w  w  .ja  v a2  s  .com*/
 * 
 * @return 
 */
public static String linkedInRedirect(HttpServletRequest request, HttpServletResponse response) {
    GenericValue oauth2LinkedIn = getOAuth2LinkedInConfig(request);
    if (UtilValidate.isEmpty(oauth2LinkedIn)) {
        return "error";
    }

    String clientId = oauth2LinkedIn.getString(PassportUtil.ApiKeyLabel);
    String returnURI = oauth2LinkedIn.getString(envPrefix + PassportUtil.ReturnUrlLabel);

    // Get user authorization code
    try {
        String state = System.currentTimeMillis() + String.valueOf((new Random(10)).nextLong());
        request.getSession().setAttribute(SESSION_LINKEDIN_STATE, state);
        String redirectUrl = TokenEndpoint + AuthorizeUri + "?client_id=" + clientId + "&response_type=code"
                + "&scope=" + DEFAULT_SCOPE + "&redirect_uri=" + URLEncoder.encode(returnURI, "UTF-8")
                + "&state=" + state;
        response.sendRedirect(redirectUrl);
    } catch (NullPointerException e) {
        String errMsg = UtilProperties.getMessage(resource, "RedirectToLinkedInOAuth2NullException",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    } catch (IOException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.toString());
        String errMsg = UtilProperties.getMessage(resource, "RedirectToLinkedInOAuth2Error", messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }

    return "success";
}

From source file:com.alkacon.opencms.v8.documentcenter.NewDocumentsTree.java

/**
 * Returns a String which holds the selected categories for the result page of the new documents query.<p>
 * /*from   w ww.j a va  2s. c  o m*/
 * @param cms the CmsObject
 * @param request the HttpServletRequest
 * @param messageAll the localized message String used when all categories were selected
 * @return String with comma separated selected categories or localized "all" message
 */
public static String getCategories(CmsObject cms, HttpServletRequest request, String messageAll) {

    StringBuffer retValue = new StringBuffer(128);

    // get the current user's HHTP session
    //HttpSession session = ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getSession();
    HttpSession session = request.getSession();

    // get the required parameters
    String paramAll = (String) session.getAttribute(C_DOCUMENT_SEARCH_PARAM_ALL);

    if ("true".equals(paramAll)) {
        return messageAll;
    } else {
        List<String> categories = getCategoryList(
                (String) session.getAttribute(C_DOCUMENT_SEARCH_PARAM_CATEGORYLIST));
        Iterator<String> i = categories.iterator();
        while (i.hasNext()) {
            String path = i.next();
            try {
                retValue.append(cms.readPropertyObject(path, CmsCategory.CATEGORY_TITLE, false).getValue());
            } catch (CmsException e) {
                // noop
            }
            if (i.hasNext()) {
                retValue.append(", ");
            }
        }

        // clear objects to release memory
        categories = null;
        i = null;
    }
    return retValue.toString();
}

From source file:gov.utah.dts.det.ccl.actions.facility.information.license.reports.LicenseCertificate.java

private static void writePdf(License license, ByteArrayOutputStream ba, HttpServletRequest request)
        throws DocumentException, BadElementException {
    SimpleDateFormat df = new SimpleDateFormat("MMMM d, yyyy");
    StringBuilder sb;// ww  w.j a  va  2s  . c  o m

    // Retrieve the certificate template to use as watermark
    ServletContext context = request.getSession().getServletContext();
    String templatefile = context.getRealPath("/resources") + "/LicenseCertificateTemplate.pdf";
    PdfReader reader = getTemplateReader(templatefile);
    if (reader != null && reader.getNumberOfPages() > 0) {
        Phrase phrase;

        // Create new document using the page size of the certificate template document
        Document document = new Document(reader.getPageSizeWithRotation(1), 0, 0, 0, 0);
        PdfWriter writer = PdfWriter.getInstance(document, ba);
        document.open();

        // Get the writer under content byte for placing of watermark
        PdfContentByte under = writer.getDirectContentUnder();
        PdfContentByte over = writer.getDirectContent();

        // Retrieve the first page of the template document and wrap as an Image to use as new document watermark
        PdfImportedPage page = writer.getImportedPage(reader, 1);
        Image img = Image.getInstance(page);
        // Make sure the image has an absolute page position
        if (!img.hasAbsoluteX() || !img.hasAbsoluteY()) {
            img.setAbsolutePosition(0, 0);
        }

        under.addImage(img);

        /*
         * THE FOLLOWING TWO FUNCTION CALLS DISPLAY THE PAGE MARGINS AND TEXT COLUMN BORDERS FOR DEBUGGING TEXT PLACEMENT.
         * UNCOMMENT EACH FUNCTION CALL TO HAVE BORDERS DISPLAYED ON THE OUTPUT DOCUMENT.  THIS WILL HELP WHEN YOU NEED
         * TO SEE WHERE TEXT WILL BE PLACED ON THE CERTIFICATE FORM.
         */
        // Show the page margins
        //showPageMarginBorders(over);

        // Show the text column borders
        //showColumnBorders(over);

        ColumnText ct = new ColumnText(over);
        ct.setLeading(fixedLeading);

        // Add Facility Name to column
        String text = license.getFacility().getName();
        if (text != null) {
            phrase = new Phrase(text.toUpperCase(), mediumfontB);
            phrase.setLeading(noLeading);
            ct.addText(phrase);
            ct.addText(Chunk.NEWLINE);
        }
        // Add Facility Site to column
        text = license.getFacility().getSiteName();
        if (text != null) {
            phrase = new Phrase(text.toUpperCase(), mediumfontB);
            phrase.setLeading(noLeading);
            ct.addText(phrase);
            ct.addText(Chunk.NEWLINE);
        }
        // Add Facility Address to column
        text = license.getFacility().getLocationAddress().getAddressOne();
        if (text != null) {
            phrase = new Phrase(text.toUpperCase(), mediumfontB);
            phrase.setLeading(noLeading);
            ct.addText(phrase);
            ct.addText(Chunk.NEWLINE);
        }
        text = license.getFacility().getLocationAddress().getCityStateZip();
        if (text != null) {
            phrase = new Phrase(text.toUpperCase(), mediumfontB);
            phrase.setLeading(noLeading);
            ct.addText(phrase);
            ct.addText(Chunk.NEWLINE);
        }
        // Write column to document
        ct.setAlignment(Element.ALIGN_CENTER);
        ct.setSimpleColumn(COLUMNS[0][0], COLUMNS[0][1], COLUMNS[0][2], COLUMNS[0][3]);
        ct.go();

        // Add Certification Service Code to column
        ct = new ColumnText(over);
        ct.setLeading(fixedLeading);
        String service = "";
        if (license.getSpecificServiceCode() != null
                && StringUtils.isNotBlank(license.getSpecificServiceCode().getValue())
                && DV_TREATMENT.equalsIgnoreCase(license.getSpecificServiceCode().getValue())) {
            service += DOMESTIC_VIOLENCE;
        }
        if (!license.getProgramCodeIds().isEmpty()) { // redmine 25410
            mentalHealthLoop: for (PickListValue pkv : license.getProgramCodeIds()) {
                String program = pkv.getValue();
                int idx = program.indexOf(" -");
                if (idx >= 0) {
                    String code = program.substring(0, idx);
                    if (MENTAL_HEALTH_CODES.indexOf(code + ":") >= 0) {
                        if (service.length() > 0) {
                            service += " / ";
                        }
                        service += MENTAL_HEALTH;
                        break mentalHealthLoop;
                    }
                }
            }
            substanceAbuseLoop: for (PickListValue pkv : license.getProgramCodeIds()) {
                String program = pkv.getValue();
                int idx = program.indexOf(" -");
                if (idx >= 0) {
                    String code = program.substring(0, idx);
                    if (SUBSTANCE_ABUSE_CODES.indexOf(code + ":") >= 0) {
                        if (service.length() > 0) {
                            service += " / ";
                        }
                        service += SUBSTANCE_ABUSE;
                        break substanceAbuseLoop;
                    }
                }
            }
        }
        if (StringUtils.isNotBlank(license.getServiceCodeDesc())) {
            if (service.length() > 0) {
                service += " / ";
            }
            service += license.getServiceCodeDesc();
        }
        if (StringUtils.isNotEmpty(service)) {
            phrase = new Phrase(service.toUpperCase(), mediumfont);
            phrase.setLeading(noLeading);
            ct.addText(phrase);
            ct.addText(Chunk.NEWLINE);
        }

        // Add CLIENTS Info to column
        sb = new StringBuilder("FOR ");
        if (license.getAgeGroup() == null
                || license.getAgeGroup().getValue().equalsIgnoreCase("Adult & Youth")) {
            // Adult & Youth
            if (license.getAdultTotalSlots() != null) {
                sb.append(license.getAdultTotalSlots().toString());
            }
            sb.append(" ADULT AND YOUTH CLIENTS");
        } else if (license.getAgeGroup().getValue().equalsIgnoreCase("Adult")) {
            // Adult
            if (license.getAdultTotalSlots() != null) {
                // Are male or female counts specified?
                sb.append(license.getAdultTotalSlots().toString());
                sb.append(" ADULT");
                if (license.getAdultFemaleCount() != null || license.getAdultMaleCount() != null) {
                    // Does either the male or female count equal the total slot count?
                    if ((license.getAdultFemaleCount() != null
                            && license.getAdultFemaleCount().equals(license.getAdultTotalSlots()))) {
                        sb.append(" FEMALE CLIENTS");
                    } else if (license.getAdultMaleCount() != null
                            && license.getAdultMaleCount().equals(license.getAdultTotalSlots())) {
                        sb.append(" MALE CLIENTS");
                    } else {
                        sb.append(" CLIENTS, ");
                        if (license.getAdultMaleCount() != null) {
                            sb.append(license.getAdultMaleCount().toString() + " MALE");
                        }
                        if (license.getAdultFemaleCount() != null) {
                            if (license.getAdultMaleCount() != null) {
                                sb.append(" AND ");
                            }
                            sb.append(license.getAdultFemaleCount().toString() + " FEMALE");
                        }
                        if (license.getFromAge() != null || license.getToAge() != null) {
                            sb.append(",");
                        }
                    }
                } else {
                    sb.append(" CLIENTS");
                }
            } else {
                sb.append(" ADULT CLIENTS");
            }
        } else {
            // Youth
            if (license.getYouthTotalSlots() != null) {
                // Are male or female counts specified?
                sb.append(license.getYouthTotalSlots().toString());
                sb.append(" YOUTH");
                if (license.getYouthFemaleCount() != null || license.getYouthMaleCount() != null) {
                    // Does either the male or female count equal the total slot count?
                    if ((license.getYouthFemaleCount() != null
                            && license.getYouthFemaleCount().equals(license.getYouthTotalSlots()))) {
                        sb.append(" FEMALE CLIENTS");
                    } else if (license.getYouthMaleCount() != null
                            && license.getYouthMaleCount().equals(license.getYouthTotalSlots())) {
                        sb.append(" MALE CLIENTS");
                    } else {
                        sb.append(" CLIENTS, ");
                        if (license.getYouthMaleCount() != null) {
                            sb.append(license.getYouthMaleCount().toString() + " MALE");
                        }
                        if (license.getYouthFemaleCount() != null) {
                            if (license.getYouthMaleCount() != null) {
                                sb.append(" AND ");
                            }
                            sb.append(license.getYouthFemaleCount().toString() + " FEMALE");
                        }
                        if (license.getFromAge() != null || license.getToAge() != null) {
                            sb.append(",");
                        }
                    }
                } else {
                    sb.append(" CLIENTS");
                }
            } else {
                sb.append(" YOUTH CLIENTS");
            }
        }
        if (license.getFromAge() != null || license.getToAge() != null) {
            sb.append(" AGES ");
            if (license.getFromAge() != null) {
                sb.append(license.getFromAge().toString());
                if (license.getToAge() != null) {
                    sb.append(" TO " + license.getToAge().toString());
                } else {
                    sb.append(" AND OLDER");
                }
            } else {
                sb.append("TO " + license.getToAge().toString());
            }
        }
        phrase = new Phrase(sb.toString(), mediumfont);
        phrase.setLeading(noLeading);
        ct.addText(phrase);
        ct.addText(Chunk.NEWLINE);

        // Add Certificate Comments
        if (StringUtils.isNotBlank(license.getCertificateComment())) {
            phrase = new Phrase(license.getCertificateComment().toUpperCase(), mediumfont);
            phrase.setLeading(noLeading);
            ct.addText(phrase);
        }

        // Write column to document
        ct.setAlignment(Element.ALIGN_CENTER);
        ct.setSimpleColumn(COLUMNS[1][0], COLUMNS[1][1], COLUMNS[1][2], COLUMNS[1][3]);
        ct.go();

        // Add Certificate Start Date
        if (license.getStartDate() != null) {
            phrase = new Phrase(df.format(license.getStartDate()), mediumfont);
            phrase.setLeading(noLeading);
            ct = new ColumnText(over);
            ct.setSimpleColumn(phrase, COLUMNS[2][0], COLUMNS[2][1], COLUMNS[2][2], COLUMNS[2][3], fixedLeading,
                    Element.ALIGN_RIGHT);
            ct.go();
        }

        // Add Certificate End Date
        if (license.getEndDate() != null) {
            phrase = new Phrase(df.format(license.getEndDate()), mediumfont);
            phrase.setLeading(noLeading);
            ct = new ColumnText(over);
            ct.setSimpleColumn(phrase, COLUMNS[3][0], COLUMNS[3][1], COLUMNS[3][2], COLUMNS[3][3], fixedLeading,
                    Element.ALIGN_LEFT);
            ct.go();
        }

        // Add License Number
        if (license.getLicenseNumber() != null) {
            phrase = new Phrase(license.getLicenseNumber().toString(), largefontB);
            phrase.setLeading(noLeading);
            ct = new ColumnText(over);
            ct.setSimpleColumn(phrase, COLUMNS[4][0], COLUMNS[4][1], COLUMNS[4][2], COLUMNS[4][3],
                    numberLeading, Element.ALIGN_CENTER);
            ct.go();
        }
        document.close();
    }
}

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

/**
 * Return the list of FileItems stored in session.
 * /*from   ww  w . ja va  2s .  com*/
 * @param request
 * @return FileItems stored in session
 */
@SuppressWarnings("unchecked")
public static List<FileItem> getSessionFileItems(HttpServletRequest request) {
    return (Vector<FileItem>) request.getSession().getAttribute(SESSION_FILES);
}

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

/**
 * Removes all FileItems stored in session, but in this case 
 * the user can specify whether the temporary data is removed from disk.
 * //  w w  w .j ava2 s .  c  o  m
 * @param request
 * @param removeData 
 *                    true: the file data is deleted.
 *                    false: use it when you are referencing file items 
 *                    instead of copying them.
 */
public static void removeSessionFileItems(HttpServletRequest request, boolean removeData) {
    logger.debug("UPLOAD-SERVLET (" + request.getSession().getId() + ") removeSessionFileItems: removeData="
            + removeData);
    @SuppressWarnings("unchecked")
    Vector<FileItem> sessionFiles = (Vector<FileItem>) request.getSession().getAttribute(SESSION_FILES);
    if (removeData && sessionFiles != null) {
        for (FileItem fileItem : sessionFiles) {
            if (fileItem != null && !fileItem.isFormField()) {
                fileItem.delete();
            }
        }
    }
    request.getSession().removeAttribute(SESSION_FILES);
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.harvester.FileHarvestController.java

/**
 * Returns the ID of the current session between server and browser.
 * @param request the request coming in from the browser
 * @return the session ID/* ww w  .  j  ava 2s  . c o  m*/
 */
private static String getSessionId(HttpServletRequest request) {
    return request.getSession().getId();
}