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:com.utest.webservice.util.SessionUtil.java

public static String extractSession(MessageContext context, boolean insertToResponze) {
    HttpServletRequest req = context.getHttpServletRequest();
    javax.servlet.http.Cookie[] available = req.getCookies();
    String sessionId = null;//from   w w  w  .  j a  va2s .c  om
    if (available != null) {
        for (javax.servlet.http.Cookie ck : available) {
            if (SESSION_NAME.equalsIgnoreCase(ck.getName())) {
                sessionId = ck.getValue();
            }
        }
    }
    if (sessionId == null) {
        HttpSession session = req.getSession();
        sessionId = session.getId();
        if (insertToResponze) {
            javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(SESSION_NAME, sessionId);
            context.getHttpServletResponse().addCookie(cookie);
        }
    }
    return sessionId;
}

From source file:edu.stanford.muse.webapp.Accounts.java

/** does account setup and login (and look up default folder if well-known account) from the given request.
 * request params are loginName<N>, password<N>, etc (see loginForm for details).
 * returns an object with {status: 0} if success, or {status: <non-zero>, errorMessage: '... '} if failure.
 * if success and account has a well-known sent mail folder, the returned object also has something like: 
 * {defaultFolder: '[Gmail]/Sent Mail', defaultFolderCount: 1033}
 * accounts on the login page are numbered 0 upwards. */
public static JSONObject login(HttpServletRequest request, int accountNum) throws IOException, JSONException {
    JSONObject result = new JSONObject();

    HttpSession session = request.getSession();
    // allocate the fetcher if it doesn't already exist
    MuseEmailFetcher m = null;//from   www  .  j ava2 s  . com
    synchronized (session) // synchronize, otherwise may lose the fetcher when multiple accounts are specified and are logged in to simult.
    {
        m = (MuseEmailFetcher) JSPHelper.getSessionAttribute(session, "museEmailFetcher");
        boolean doIncremental = request.getParameter("incremental") != null;

        if (m == null || !doIncremental) {
            m = new MuseEmailFetcher();
            session.setAttribute("museEmailFetcher", m);
        }
    }

    // note: the same params get posted with every accountNum
    // we'll update for all account nums, because sometimes account #0 may not be used, only #1 onwards. This should be harmless.
    // we used to do only altemailaddrs, but now also include the name.
    updateUserInfo(request);

    String accountType = request.getParameter("accountType" + accountNum);
    if (Util.nullOrEmpty(accountType)) {
        result.put("status", 1);
        result.put("errorMessage", "No information for account #" + accountNum);
        return result;
    }

    String loginName = request.getParameter("loginName" + accountNum);
    String password = request.getParameter("password" + accountNum);
    String protocol = request.getParameter("protocol" + accountNum);
    //   String port = request.getParameter("protocol" + accountNum);  // we don't support pop/imap on custom ports currently. can support server.com:port syntax some day
    String server = request.getParameter("server" + accountNum);
    String defaultFolder = request.getParameter("defaultFolder" + accountNum);

    if (server != null)
        server = server.trim();

    if (loginName != null)
        loginName = loginName.trim();

    // for these ESPs, the user may have typed in the whole address or just his/her login name
    if (accountType.equals("gmail") && loginName.indexOf("@") < 0)
        loginName = loginName + "@gmail.com";
    if (accountType.equals("yahoo") && loginName.indexOf("@") < 0)
        loginName = loginName + "@yahoo.com";
    if (accountType.equals("live") && loginName.indexOf("@") < 0)
        loginName = loginName + "@live.com";
    if (accountType.equals("stanford") && loginName.indexOf("@") < 0)
        loginName = loginName + "@stanford.edu";
    if (accountType.equals("gmail"))
        server = "imap.gmail.com";

    // add imapdb stuff here.
    boolean imapDBLookupFailed = false;
    String errorMessage = "";
    int errorStatus = 0;

    if (accountType.equals("email") && Util.nullOrEmpty(server)) {
        log.info("accountType = email");

        defaultFolder = "Sent";

        {
            // ISPDB from Mozilla
            imapDBLookupFailed = true;

            String emailDomain = loginName.substring(loginName.indexOf("@") + 1);
            log.info("Domain: " + emailDomain);

            // from http://suhothayan.blogspot.in/2012/05/how-to-install-java-cryptography.html
            // to get around the need for installingthe unlimited strength encryption policy files.
            try {
                Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
                field.setAccessible(true);
                field.set(null, java.lang.Boolean.FALSE);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            //            URL url = new URL("https://live.mozillamessaging.com/autoconfig/v1.1/" + emailDomain);
            URL url = new URL("https://autoconfig.thunderbird.net/v1.1/" + emailDomain);
            try {
                URLConnection urlConnection = url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(in);

                NodeList configList = doc.getElementsByTagName("incomingServer");
                log.info("configList.getLength(): " + configList.getLength());

                int i;
                for (i = 0; i < configList.getLength(); i++) {
                    Node config = configList.item(i);
                    NamedNodeMap attributes = config.getAttributes();
                    if (attributes.getNamedItem("type").getNodeValue().equals("imap")) {
                        log.info("[" + i + "] type: " + attributes.getNamedItem("type").getNodeValue());
                        Node param = config.getFirstChild();
                        String nodeName, nodeValue;
                        String paramHostName = "";
                        String paramUserName = "";
                        do {
                            if (param.getNodeType() == Node.ELEMENT_NODE) {
                                nodeName = param.getNodeName();
                                nodeValue = param.getTextContent();
                                log.info(nodeName + "=" + nodeValue);
                                if (nodeName.equals("hostname")) {
                                    paramHostName = nodeValue;
                                } else if (nodeName.equals("username")) {
                                    paramUserName = nodeValue;
                                }
                            }
                            param = param.getNextSibling();
                        } while (param != null);

                        log.info("paramHostName = " + paramHostName);
                        log.info("paramUserName = " + paramUserName);

                        server = paramHostName;
                        imapDBLookupFailed = false;
                        if (paramUserName.equals("%EMAILADDRESS%")) {
                            // Nothing to do with loginName
                        } else if (paramUserName.equals("%EMAILLOCALPART%")
                                || paramUserName.equals("%USERNAME%")) {
                            // Cut only local part
                            loginName = loginName.substring(0, loginName.indexOf('@') - 1);
                        } else {
                            imapDBLookupFailed = true;
                            errorMessage = "Invalid auto configuration";
                        }

                        break; // break after find first IMAP host name
                    }
                }
            } catch (Exception e) {
                Util.print_exception("Exception trying to read ISPDB", e, log);
                errorStatus = 2; // status code = 2 => ispdb lookup failed
                errorMessage = "No automatic configuration available for " + emailDomain
                        + ", please use the option to provide a private (IMAP) server. \nDetails: "
                        + e.getMessage()
                        + ". \nRunning with java -Djavax.net.debug=all may provide more details.";
            }
        }
    }

    if (imapDBLookupFailed) {
        log.info("ISPDB Fail");
        result.put("status", errorStatus);
        result.put("errorMessage", errorMessage);
        // add other fields here if needed such as server name attempted to be looked up in case the front end wants to give a message to the user
        return result;
    }

    boolean isServerAccount = accountType.equals("gmail") || accountType.equals("email")
            || accountType.equals("yahoo") || accountType.equals("live") || accountType.equals("stanford")
            || accountType.equals("gapps") || accountType.equals("imap") || accountType.equals("pop")
            || accountType.startsWith("Thunderbird");

    if (isServerAccount) {
        boolean sentOnly = "on".equals(request.getParameter("sent-messages-only"));
        return m.addServerAccount(server, protocol, defaultFolder, loginName, password, sentOnly);
    } else if (accountType.equals("mbox") || accountType.equals("tbirdLocalFolders")) {
        try {
            String mboxDir = request.getParameter("mboxDir" + accountNum);
            String emailSource = request.getParameter("emailSource" + accountNum);
            // for non-std local folders dir, tbird prefs.js has a line like: user_pref("mail.server.server1.directory-rel", "[ProfD]../../../../../../tmp/tb");
            log.info("adding mbox account: " + mboxDir);
            errorMessage = m.addMboxAccount(emailSource, mboxDir, accountType.equals("tbirdLocalFolders"));
            if (!Util.nullOrEmpty(errorMessage)) {
                result.put("errorMessage", errorMessage);
                result.put("status", 1);
            } else
                result.put("status", 0);
        } catch (MboxFolderNotReadableException e) {
            result.put("errorMessage", e.getMessage());
            result.put("status", 1);
        }
    } else {
        result.put("errorMessage", "Sorry, unknown account type: " + accountType);
        result.put("status", 1);
    }
    return result;
}

From source file:eu.eidas.node.utils.EidasNodeErrorUtil.java

/**
 * Method called by the EidasNode exception handler to manage properly the exception occured
 *
 * @param request - the current http request
 * @param exc     - the exception for which the saml response is to be prepared
 *                <p/>//from ww w . jav  a2s  .com
 *                side effect: exc's samlTokenFail is set to the saml response to return
 * @param source  Enum values defining ProxyService/Connector
 */
public static void prepareSamlResponseFail(final HttpServletRequest request, AbstractEIDASException exc,
        ErrorSource source) {

    try {
        IEIDASSession eidasSession = (IEIDASSession) request.getSession()
                .getAttribute("scopedTarget.serviceSession");
        if (eidasSession == null || eidasSession.isEmpty() || source == ErrorSource.CONNECTOR) {
            eidasSession = (IEIDASSession) request.getSession().getAttribute("scopedTarget.connectorSession");
            prepareSamlResponseFailConnector(request, exc, eidasSession);
            return;
        }
        prepareSamlResponseFailService(request, exc, eidasSession);

    } catch (final Exception e) {
        LOG.info("ERROR : Error while trying to generate error SAMLToken", e.getMessage());
        LOG.debug("ERROR : Error while trying to generate error SAMLToken", e);
    }

}

From source file:com.sapienter.jbilling.server.user.validator.NoUserInfoInPasswordValidator.java

/**
 * Struts validator. This method retrieves the parameters necessary for
 * validating the password passed and calls basicValidation() to verify
 * the value. As such, it only represents a struts wrapper to
 * the core validation routine./*from w  w  w.  ja va  2 s  .c om*/
 * @return
 */
public static boolean validateNoUserInfo(Object bean, ValidatorAction va, Field field, ActionErrors errors,
        HttpServletRequest request, ServletContext application) {

    boolean retVal = true;

    try {

        String value = ValidatorUtils.getValueAsString(bean, field.getProperty());

        if (!GenericValidator.isBlankOrNull(value)) {
            IUserSessionBean user = (IUserSessionBean) Context.getBean(Context.Name.USER_SESSION);
            ContactDTOEx dto = user.getPrimaryContactDTO(
                    (Integer) request.getSession().getAttribute(Constants.SESSION_USER_ID));
            if (dto != null) {
                retVal = basicValidation(dto, value);
            }
        }

    } catch (Exception e) {
        retVal = false;
    }
    if (retVal == false) {
        errors.add(field.getKey(), Resources.getActionError(request, va, field));
    }
    return retVal;
}

From source file:org.hdiv.util.HDIVUtil.java

/**
 * Return the <code>HttpSession</code> object.
 * //from w ww  .  j ava2 s.com
 * @return {@link HttpSession} instance
 */
public static HttpSession getHttpSession() {
    HttpServletRequest request = getHttpServletRequest();
    return request.getSession();
}

From source file:com.mockey.ui.Util.java

/**
 * Saves the LAST message.//from   w w  w .j a v a 2s . c  o  m
 * 
 * @param message
 * @param req
 */
private static void save(String message, String messageKey, HttpServletRequest req) {

    // HISTORY: This method use to save a List of messages
    // for the purpose to display to the end user. But since
    // this solution can be tweak by a head-less client,
    // the list of informative messages to the user became
    // perplexing.
    List<String> msgs = new ArrayList<String>();
    msgs.add(message);
    req.getSession().setAttribute(messageKey, msgs);
}

From source file:org.toobsframework.pres.util.ParameterUtil.java

public static Map buildParameterMap(HttpServletRequest request, boolean compCall) {
    Map params = new HashMap();
    HttpSession session = request.getSession();
    Enumeration attributes = session.getAttributeNames();
    // Session has lowest priority
    while (attributes.hasMoreElements()) {
        String thisAttribute = (String) attributes.nextElement();
        //if (session.getAttribute(thisAttribute) instanceof String) {
        params.put(thisAttribute, session.getAttribute(thisAttribute));
        //}/*from ww w .  j a  v  a 2  s.  c  o  m*/
    }
    // Parameters next highest
    params.putAll(request.getParameterMap());

    // Attributes rule all
    attributes = request.getAttributeNames();
    while (attributes.hasMoreElements()) {
        String thisAttribute = (String) attributes.nextElement();
        if (!excludedParameters.contains(thisAttribute)) {
            if (log.isDebugEnabled()) {
                log.debug("Putting " + thisAttribute + " As " + request.getAttribute(thisAttribute));
            }
            params.put(thisAttribute, request.getAttribute(thisAttribute));
        }
    }
    params.put("httpQueryString", request.getQueryString());
    if (compCall && request.getMethod().equals("POST")) {
        StringBuffer qs = new StringBuffer();
        Iterator iter = request.getParameterMap().entrySet().iterator();
        int i = 0;
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            String[] value = (String[]) entry.getValue();
            for (int j = 0; j < value.length; j++) {
                if (i > 0)
                    qs.append("&");
                qs.append(key).append("=").append(value[j]);
                i++;
            }
        }
        params.put("httpQueryString", qs.toString());
    }
    return params;
}

From source file:com.krawler.esp.handlers.AuthHandler.java

public static String getUserid(HttpServletRequest request) throws SessionExpiredException {
    String userId = NullCheckAndThrow(request.getSession().getAttribute("userid"),
            SessionExpiredException.USERID_NULL);
    return userId;
}

From source file:com.krawler.esp.handlers.AuthHandler.java

public static String getRole(HttpServletRequest request) throws SessionExpiredException {
    String roleid = NullCheckAndThrow(request.getSession().getAttribute("roleid"),
            SessionExpiredException.USERID_NULL);
    return roleid;
}

From source file:com.krawler.esp.handlers.AuthHandler.java

public static String getCompanyid(HttpServletRequest request) throws SessionExpiredException {
    String userId = NullCheckAndThrow(request.getSession().getAttribute("companyid"),
            SessionExpiredException.USERID_NULL);
    return userId;
}