Example usage for javax.servlet.http HttpServletRequest getCookies

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

Introduction

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

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

/**
 * Overridden doFilter method.//from  w w  w. j  a  va  2  s.  c o m
 * @param request ServletRequest representing the incoming user http(s)
 *                request.
 * @param request ServletResponse representing the associated response
 *                                that will eventually be passed on to the
 *                                next servlet.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    // Output HttpServletRequest diagnostic information
    logger.info("Request URL: " + req.getMethod() + " - " + req.getRequestURL().toString());

    doDiagnostics(req);

    try {
        boolean hasAuthToken = hasAuthToken(req.getCookies());
        Cookie internalCookie = hasAuthToken ? doCookie(req) : doHeader(req, res);
        chain.doFilter(new PastaRequestWrapper(req, internalCookie), res);
    } catch (IllegalStateException e) {
        res.setStatus(BAD_REQUEST_CODE);
        PrintWriter out = res.getWriter();
        out.println(e);
    } catch (UnauthorizedException e) {
        res.setStatus(UNAUTHORIZED_CODE);
        PrintWriter out = res.getWriter();
        out.println(e.getMessage());
    } catch (IllegalArgumentException e) {
        res.setStatus(UNAUTHORIZED_CODE);
        PrintWriter out = res.getWriter();
        out.println(e.getMessage());
    }

}

From source file:org.apache.felix.webconsole.internal.servlet.OsgiManager.java

private final Locale getConfiguredLocale(HttpServletRequest request) {
    Locale locale = null;/*from   www  .j  a v  a 2 s .c om*/

    Cookie[] cookies = request.getCookies();
    for (int i = 0; cookies != null && i < cookies.length; i++) {
        if (COOKIE_LOCALE.equals(cookies[i].getName())) {
            locale = Util.parseLocaleString(cookies[i].getValue());
            break;
        }
    }

    // TODO: check UserAdmin ?

    if (locale == null)
        locale = configuredLocale;
    if (locale == null)
        locale = request.getLocale();

    return locale;
}

From source file:com.example.web.Create_story.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    int count = 1;
    String storyid, storystep;/*from   w ww . j a  v  a2s  .  co  m*/
    String fileName = "";
    int f = 0;
    String action = "";
    String first = request.getParameter("first");
    String user = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("user"))
                user = cookie.getValue();
        }
    }
    String title = request.getParameter("title");
    String header = request.getParameter("header");
    String text_field = request.getParameter("text_field");

    String latitude = request.getParameter("lat");
    String longitude = request.getParameter("lng");
    storyid = (request.getParameter("storyid"));
    storystep = (request.getParameter("storystep"));
    String message = "";
    int valid = 1;
    String query;
    ResultSet rs;
    Connection conn;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "tworld";
    String driver = "com.mysql.jdbc.Driver";

    isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/"));
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    fileName = fi.getName();
                    String contentType = fi.getContentType();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    String[] spliting = fileName.split("\\.");
                    // Write the file
                    System.out.println(sizeInBytes + " " + maxFileSize);
                    System.out.println(spliting[spliting.length - 1]);
                    if (!fileName.equals("")) {
                        if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg")
                                || spliting[spliting.length - 1].equals("png")
                                || spliting[spliting.length - 1].equals("jpeg"))) {

                            if (fileName.lastIndexOf("\\") >= 0) {
                                file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                            } else {
                                file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                            }
                            fi.write(file);
                            System.out.println("Uploaded Filename: " + fileName + "<br>");
                        } else {
                            valid = 0;
                            message = "not a valid image";
                        }
                    }
                }
                BufferedReader br = null;
                StringBuilder sb = new StringBuilder();

                String line;
                try {
                    br = new BufferedReader(new InputStreamReader(fi.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                } catch (IOException e) {
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                        }
                    }
                }
                if (f == 0)
                    action = sb.toString();
                else if (f == 1)
                    storyid = sb.toString();
                else if (f == 2)
                    storystep = sb.toString();
                else if (f == 3)
                    title = sb.toString();
                else if (f == 4)
                    header = sb.toString();
                else if (f == 5)
                    text_field = sb.toString();
                else if (f == 6)
                    latitude = sb.toString();
                else if (f == 7)
                    longitude = sb.toString();
                else if (f == 8)
                    first = sb.toString();
                f++;

            }
        } catch (Exception ex) {
            System.out.println("hi");
            System.out.println(ex);

        }
    }
    if (latitude == null)
        latitude = "";
    if (latitude.equals("") && first == null) {

        request.setAttribute("message", "please enter a marker");
        request.setAttribute("storyid", storyid);
        request.setAttribute("s_page", "3");
        request.setAttribute("storystep", storystep);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    } else if (valid == 1) {
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, "admin", "admin");
            if (first != null) {
                if (first.equals("first_step")) {
                    do {
                        query = "select * from story_database where story_id='" + count + "' ";
                        Statement st = conn.createStatement();
                        rs = st.executeQuery(query);
                        count++;
                    } while (rs.next());

                    int a = count - 1;
                    request.setAttribute("storyid", a);
                    storyid = Integer.toString(a);
                    request.setAttribute("storystep", 2);

                }
            }
            query = "select * from story_database where `story_id`='" + storyid + "' && `step_num`='"
                    + storystep + "' ";
            Statement st = conn.createStatement();
            rs = st.executeQuery(query);

            if (!rs.next()) {

                PreparedStatement pst = (PreparedStatement) conn.prepareStatement(
                        "insert into `tworld`.`story_database`(`story_id`, `step_num`, `content`, `latitude`, `longitude`, `title`, `header`, `max_steps`, `username`,`image_name`) values(?,?,?,?,?,?,?,?,?,?)");

                pst.setInt(1, Integer.parseInt(storyid));
                pst.setInt(2, Integer.parseInt(storystep));
                pst.setString(3, text_field);
                pst.setString(4, latitude);
                pst.setString(5, longitude);
                pst.setString(6, title);
                pst.setString(7, header);
                pst.setInt(8, Integer.parseInt(storystep));
                pst.setString(9, user);
                if (fileName.equals(""))
                    pst.setString(10, "");
                else
                    pst.setString(10, fileName);
                pst.executeUpdate();
                pst.close();

                pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?");
                pst.setInt(1, Integer.parseInt(storystep));
                pst.setInt(2, Integer.parseInt(storyid));
                pst.executeUpdate();
                pst.close();
            } else {
                PreparedStatement pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `content`=?, `latitude`=?, `longitude`=?, `title`=?, `header`=?, `max_steps`=?, `username`=? WHERE `story_id` = ? && `step_num`=?");

                pst.setString(1, text_field);
                pst.setString(2, latitude);
                pst.setString(3, longitude);
                pst.setString(4, title);
                pst.setString(5, header);

                pst.setInt(6, Integer.parseInt(storystep));
                pst.setString(7, user);
                pst.setInt(8, Integer.parseInt(storyid));
                pst.setInt(9, Integer.parseInt(storystep));

                pst.executeUpdate();
                pst.close();

                pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?");
                pst.setInt(1, Integer.parseInt(storystep));
                pst.setInt(2, Integer.parseInt(storyid));
                pst.executeUpdate();
                pst.close();
            }
            request.setAttribute("storyid", storyid);
            storystep = Integer.toString(Integer.parseInt(storystep) + 1);
            request.setAttribute("storystep", storystep);

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {

            //            Logger.getLogger(MySignInServlet.class.getName()).log(Level.SEVERE, null, ex);  
        }
        request.setAttribute("s_page", "3");
        request.getRequestDispatcher("/index.jsp").forward(request, response);

    } else {
        request.setAttribute("storyid", storyid);
        request.setAttribute("message", message);
        request.setAttribute("storystep", storystep);

        request.setAttribute("s_page", "3");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

From source file:com.jolira.testing.CachingRESTProxy.java

private boolean cacheResponse(final String query, final File queryDir, final HttpServletRequest request)
        throws IOException {
    if (backend == null) {
        return false;
    }//from w  ww. j a v a 2  s  .co m

    final String protocol = ssl ? "https" : "http";
    final String _url = protocol + "://" + backend + query;
    final URL url = new URL(_url);
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    final Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        final StringBuilder cookieVal = new StringBuilder();

        for (final Cookie cookie : cookies) {
            final String value = cookie.getValue();
            final String name = cookie.getName();

            cookieVal.append(name);
            cookieVal.append('=');
            cookieVal.append(value);
            cookieVal.append(';');
        }

        connection.setRequestProperty("Cookie", cookieVal.toString());
    }

    final InputStream in = connection.getInputStream();

    try {
        cacheResponse(queryDir, connection, in);
    } finally {
        in.close();
    }

    return true;
}

From source file:nl.nn.adapterframework.webcontrol.action.ShowIbisstoreSummary.java

public ActionForward executeSub(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    IniDynaActionForm showIbisstoreSummaryForm = (IniDynaActionForm) form;
    // Initialize action
    initAction(request);//from  ww w.j a va  2  s  .c  om

    String jmsRealm = (String) showIbisstoreSummaryForm.get("jmsRealm");
    String cookieName = AppConstants.getInstance().getString(SHOWIBISSTORECOOKIE, SHOWIBISSTORECOOKIE);

    if (StringUtils.isEmpty(jmsRealm)) {
        // get jmsRealm value from cookie
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie aCookie = cookies[i];

                if (aCookie.getName().equals(cookieName)) {
                    jmsRealm = aCookie.getValue();
                    log.debug("jmsRealm from cookie [" + jmsRealm + "]");
                }
            }
        }
    }

    for (IAdapter iAdapter : ibisManager.getRegisteredAdapters()) {
        Adapter adapter = (Adapter) iAdapter;
        for (Iterator receiverIt = adapter.getReceiverIterator(); receiverIt.hasNext();) {
            ReceiverBase receiver = (ReceiverBase) receiverIt.next();
            ITransactionalStorage errorStorage = receiver.getErrorStorage();
            if (errorStorage != null) {
                String slotId = errorStorage.getSlotId();
                if (StringUtils.isNotEmpty(slotId)) {
                    SlotIdRecord sir = new SlotIdRecord(adapter.getName(), receiver.getName(), null);
                    String type = errorStorage.getType();
                    slotmap.put(type + "/" + slotId, sir);
                }
            }
            ITransactionalStorage messageLog = receiver.getMessageLog();
            if (messageLog != null) {
                String slotId = messageLog.getSlotId();
                if (StringUtils.isNotEmpty(slotId)) {
                    SlotIdRecord sir = new SlotIdRecord(adapter.getName(), receiver.getName(), null);
                    String type = messageLog.getType();
                    slotmap.put(type + "/" + slotId, sir);
                }
            }
        }
        PipeLine pipeline = adapter.getPipeLine();
        if (pipeline != null) {
            for (int i = 0; i < pipeline.getPipeLineSize(); i++) {
                IPipe pipe = pipeline.getPipe(i);
                if (pipe instanceof MessageSendingPipe) {
                    MessageSendingPipe msp = (MessageSendingPipe) pipe;
                    ITransactionalStorage messageLog = msp.getMessageLog();
                    if (messageLog != null) {
                        String slotId = messageLog.getSlotId();
                        if (StringUtils.isNotEmpty(slotId)) {
                            SlotIdRecord sir = new SlotIdRecord(adapter.getName(), null, msp.getName());
                            String type = messageLog.getType();
                            slotmap.put(type + "/" + slotId, sir);
                            slotmap.put(slotId, sir);
                        }
                    }
                }
            }
        }
    }

    List jmsRealms = JmsRealmFactory.getInstance().getRegisteredRealmNamesAsList();
    if (jmsRealms.size() == 0) {
        jmsRealms.add("no realms defined");
    } else {
        if (StringUtils.isEmpty(jmsRealm)) {
            jmsRealm = (String) jmsRealms.get(0);
        }
    }
    showIbisstoreSummaryForm.set("jmsRealms", jmsRealms);

    if (StringUtils.isNotEmpty(jmsRealm)) {

        String formQuery = AppConstants.getInstance().getProperty(SHOWIBISSTOREQUERYKEY);

        String result = "<none/>";

        try {
            IbisstoreSummaryQuerySender qs;
            qs = (IbisstoreSummaryQuerySender) ibisManager.getIbisContext()
                    .createBeanAutowireByName(IbisstoreSummaryQuerySender.class);
            qs.setSlotmap(slotmap);
            try {
                qs.setName("QuerySender");
                qs.setJmsRealm(jmsRealm);
                qs.setQueryType("select");
                qs.setBlobSmartGet(true);
                qs.configure(true);
                qs.open();
                result = qs.sendMessage("dummy", formQuery);
            } catch (Throwable t) {
                error("error occured on executing jdbc query", t);
            } finally {
                qs.close();
            }
        } catch (Exception e) {
            error("error occured on creating or closing connection", e);
        }
        if (log.isDebugEnabled())
            log.debug("result [" + result + "]");
        request.setAttribute("result", result);

    }

    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        return (mapping.findForward("success"));
    }

    //Successfull: store cookie
    String cookieValue = jmsRealm;
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setMaxAge(Integer.MAX_VALUE);
    log.debug("Store cookie for " + request.getServletPath() + " cookieName[" + cookieName + "] "
            + " cookieValue[" + cookieValue + "]");
    try {
        response.addCookie(cookie);
    } catch (Throwable t) {
        log.warn("unable to add cookie to request. cookie value [" + cookie.getValue() + "]", t);
    }

    log.debug("forward to success");
    return (mapping.findForward("success"));

}

From source file:org.apache.ranger.security.web.filter.RangerKRBAuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    String authtype = PropertiesUtil.getProperty(RANGER_AUTH_TYPE);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (isSpnegoEnable(authtype)) {
        KerberosName.setRules(PropertiesUtil.getProperty(NAME_RULES, "DEFAULT"));
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        String userName = null;//from   w w w  . j  a v  a  2  s .  com
        Cookie[] cookie = httpRequest.getCookies();
        if (cookie != null) {
            for (Cookie c : cookie) {
                String cname = c.getName();
                if (cname != null && cname.equalsIgnoreCase("u")) {
                    int ustr = cname.indexOf("u=");
                    if (ustr != -1) {
                        int andStr = cname.indexOf("&", ustr);
                        if (andStr != -1) {
                            userName = cname.substring(ustr + 2, andStr);
                        }
                    }
                } else if (cname != null && cname.equalsIgnoreCase(AUTH_COOKIE_NAME)) {
                    int ustr = cname.indexOf("u=");
                    if (ustr != -1) {
                        int andStr = cname.indexOf("&", ustr);
                        if (andStr != -1) {
                            userName = cname.substring(ustr + 2, andStr);
                        }
                    }
                }
            }
        }
        if ((existingAuth == null || !existingAuth.isAuthenticated()) && (!StringUtils.isEmpty(userName))) {
            //--------------------------- To Create Ranger Session --------------------------------------         
            String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
            //if we get the userName from the token then log into ranger using the same user
            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
            final UserDetails principal = new User(userName, "", grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "",
                    grantedAuths);
            WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
            ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
            RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider();
            Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
            authentication = getGrantedAuthority(authentication);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            request.setAttribute("spnegoEnabled", true);
            LOG.info("Logged into Ranger as = " + userName);
        } else {
            try {
                super.doFilter(request, response, filterChain);
            } catch (Exception e) {
                throw restErrorUtil
                        .createRESTException("RangerKRBAuthenticationFilter Failed : " + e.getMessage());
            }
        }
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:com.glaf.core.util.RequestUtils.java

public static String getCurrentSystem(HttpServletRequest request) {
    String currentSystem = null;//from  w  w  w  .ja  v a  2  s.  c om
    String paramValue = request.getParameter(Constants.SYSTEM_NAME);
    if (StringUtils.isNotEmpty(paramValue)) {
        return paramValue;
    }
    String ip = getIPAddress(request);
    ip = DigestUtils.md5Hex(ip);
    HttpSession session = request.getSession(false);
    if (session != null) {
        String value = (String) session.getAttribute(Constants.LOGIN_INFO);
        Map<String, String> cookieMap = decodeValues(ip, value);
        if (StringUtils.equals(cookieMap.get(Constants.LOGIN_IP), ip)) {
            currentSystem = cookieMap.get(Constants.SYSTEM_NAME);
        }
    }

    if (currentSystem == null) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equals(cookie.getName(), Constants.COOKIE_NAME)) {
                    String value = cookie.getValue();
                    Map<String, String> cookieMap = decodeValues(ip, value);
                    if (StringUtils.equals(cookieMap.get(Constants.LOGIN_IP), ip)) {
                        String time = cookieMap.get(Constants.TS);
                        long now = Long.MAX_VALUE - System.currentTimeMillis();
                        if (StringUtils.isNumeric(time)
                                && (Long.parseLong(time) - now) < COOKIE_LIVING_SECONDS * 1000) {
                            currentSystem = cookieMap.get(Constants.SYSTEM_NAME);
                            break;
                        }
                    }
                }
            }
        }
    }

    return currentSystem;
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

private HttpSession locateSession(UrlHolder holder, HttpServletRequest request, ServletContext ctx,
        String cookieName, HttpServletResponse resp) throws Exception {
    Cookie sessionCookie = null;/* ww  w. j  a  v  a  2  s.co m*/

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equalsIgnoreCase(cookieName)) {
                sessionCookie = cookie;
                break;
            }
        }
    }

    ConfigManager cfg = (ConfigManager) ctx.getAttribute(ProxyConstants.TREMOLO_CONFIG);

    ApplicationType app;

    if (holder != null) {
        app = holder.getApp();
    } else {
        app = null;

        String appName = null;
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals("autoIdmAppName")) {
                    appName = URLDecoder.decode(cookies[i].getValue(), "UTF-8");
                    break;
                }
            }
        }

        if (appName == null) {
            // TODO create open session
            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++) {
                    if (cookies[i].getName()
                            .equals(cfg.getCfg().getApplications().getOpenSessionCookieName())) {
                        String sessionID = cookies[i].getValue();
                        TremoloHttpSession tsession = this.sessions.get(sessionID);
                        // TODO add timeouts
                        if (tsession == null) {
                            return this.createOpenSession(request, resp, ctx);
                        } else {
                            return tsession;
                        }

                    }
                }
            }

            return createOpenSession(request, resp, ctx);
        } else {
            app = cfg.getApp(appName);

            if (app == null) {
                throw new Exception("No application named '" + appName + "' found");
            }

        }
    }

    SecretKey encKey = cfg.getSecretKey(app.getCookieConfig().getKeyAlias());

    // TremoloHttpSession tsession = (TremoloHttpSession)
    // request.getSession().getAttribute(app.getCookieConfig().getSessionCookieName());

    if (sessionCookie == null) {
        // if (tsession != null) tsession.invalidate();
        return createSession(app, request, resp, ctx, encKey);
    } else {

        HttpSession session = null;

        try {

            try {

                TremoloHttpSession tsession = findSessionFromCookie(sessionCookie, encKey, this);

                if (tsession == null) {
                    return createSession(app, request, resp, ctx, encKey);
                }

                String fromSessionID = (String) tsession.getAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID);

                if (app.getCookieConfig().getTimeout() > 0) {
                    DateTime lastAccessed = (DateTime) tsession
                            .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED);
                    DateTime now = new DateTime();
                    if (now.minusSeconds(app.getCookieConfig().getTimeout()).isAfter(lastAccessed)) {
                        tsession.invalidate();
                        return createSession(app, request, resp, ctx, encKey);
                    } else {
                        tsession.setAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED, now);
                        session = tsession;
                    }
                } else {
                    session = tsession;
                }

            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Exception loading session", e);
                }
                return createSession(app, request, resp, ctx, encKey);

            }

            // this.sessions.put(session.getSessionID(), key);
            // }

        } catch (Exception e) {
            logger.error("Error generating session", e);
        }
        if (session == null) {
            // session.invalidate();
            return createSession(app, request, resp, ctx, encKey);
        }

        // session.resetAccess();

        return session;

    }
}

From source file:com.yahoo.yos.YahooFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    String yap_appid = getParam(request, "yap_appid");
    SESSION_TYPE sessionType;/*from w  w w  .j  av a 2s .co  m*/
    if ("POST".equals(request.getMethod()) && yap_appid != null && yap_appid.length() > 0) {
        sessionType = SESSION_TYPE.YAHOO_YAP_SESSION_TYPE;
    } else if (cookieExists(request.getCookies(), "yosdk_at")) {
        sessionType = SESSION_TYPE.YAHOO_OAUTH_AT_SESSION_TYPE;
    } else if (cookieExists(request.getCookies(), "yosdk_rt")) {
        sessionType = SESSION_TYPE.YAHOO_OAUTH_RT_SESSION_TYPE;
    } else {
        sessionType = null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("sessionType: {}", sessionType);
    }

    OAuthAccessor accessor = new OAuthAccessor(consumer);

    if (sessionType == null) {
        if (redirect) {
            if (logger.isDebugEnabled()) {
                logger.debug("redirecting user to yahoo acquire access token");
            }
            redirectForAuthorization(accessor, request, response);
            return;
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("inserting YahooSession suitable for 2-legged oauth calls into request attribute");
            }
            String appId = oauthConfig.getProperty("yos.appid");
            request.setAttribute("yahooSession", new YahooSession(client, consumer, null, appId));
        }
    } else if (sessionType == SESSION_TYPE.YAHOO_YAP_SESSION_TYPE) {
        if (logger.isDebugEnabled()) {
            logger.debug("inserting YahooSession suitable for 2-legged oauth calls into request attribute");
        }
        if (consumer.consumerKey == null
                || !consumer.consumerKey.equals(getParam(request, "yap_consumer_key"))) {
            logger.error("Consumer key from YAP does not match config.");
            clearSession(request, response);
            if (redirect) {
                redirectForAuthorization(accessor, request, response);
                return;
            }
        }
        try {
            OAuthSignatureMethod method = OAuthSignatureMethod.newMethod("HMAC-SHA1", accessor);
            OAuthMessage msg = OAuthServlet.getMessage(request, null);
            method.validate(msg);
        } catch (OAuthProblemException ex) {
            logger.error("Signature from YAP failed.", ex);
            clearSession(request, response);
            if (redirect) {
                redirectForAuthorization(accessor, request, response);
                return;
            }
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
        AccessToken at = new AccessToken();
        at.setKey(getParam(request, "yap_viewer_access_token"));
        at.setSecret(getParam(request, "yap_viewer_access_token_secret"));
        at.setGuid(getParam(request, "yap_viewer_guid"));
        at.setOwner(getParam(request, "yap_owner_guid"));
        at.setTokenExpires(-1);
        String appId = getParam(request, "yap_appid");
        YahooSession yahooSession = new YahooSession(client, consumer, at, appId);
        request.setAttribute("yahooSession", yahooSession);
    } else if (sessionType == SESSION_TYPE.YAHOO_OAUTH_AT_SESSION_TYPE) {
        long now = System.currentTimeMillis() / 1000;
        try {
            AccessToken accessToken = new AccessToken(cookie(request.getCookies(), "yosdk_at"));
            if (consumer.consumerKey == null || !consumer.consumerKey.equals(accessToken.getConsumer())) {
                logger.error(
                        "Consumer key for token does not match the defined Consumer Key.  The Consumer Key has probably changed since the user last authorized the application.");
                clearSession(request, response);
                if (redirect) {
                    redirectForAuthorization(accessor, request, response);
                    return;
                }
            }
            if (accessToken.getTokenExpires() >= 0 && logger.isDebugEnabled()) {
                logger.debug("AT Expires in: {}", (accessToken.getTokenExpires() - now));
            }
            if (accessToken.getTokenExpires() >= 0 && (accessToken.getTokenExpires() - now) < 30) {
                try {
                    accessTokenExpired(accessor, request, response, accessToken, filterChain);
                } catch (OAuthException ex) {
                    if (ex instanceof OAuthProblemException) {
                        OAuthProblemException oape = (OAuthProblemException) ex;
                        String s = oape.getProblem() + oape.getParameters();
                        throw new ServletException(s, ex);
                    }
                    throw new ServletException(ex);
                } catch (URISyntaxException ex) {
                    throw new ServletException(ex);
                }
                return;
            } else {
                String appId = oauthConfig.getProperty("yos.appid");
                YahooSession yahooSession = new YahooSession(client, consumer, accessToken, appId);
                request.setAttribute("yahooSession", yahooSession);
            }
        } catch (JSONException e) {
            throw new ServletException(e);
        }
    } else if (sessionType == SESSION_TYPE.YAHOO_OAUTH_RT_SESSION_TYPE) {
        try {
            RequestToken rt = new RequestToken(cookie(request.getCookies(), "yosdk_rt"));
            accessor.tokenSecret = rt.getSecret();

            String verifier = getParam(request, "oauth_verifier");
            if (logger.isDebugEnabled()) {
                logger.debug("got oauth_verifier {}", verifier);
            }

            try {
                if (logger.isDebugEnabled()) {
                    logger.error("request token found, fetching access token for user");
                }
                AccessToken at = fetchAccessToken(accessor, rt, verifier);
                Cookie yosdk_at = at.getCookie();
                Cookie yosdk_rt = new Cookie("yosdk_rt", "");
                yosdk_at.setMaxAge(30 * 24 * 60 * 60);
                yosdk_rt.setMaxAge(0);
                response.addCookie(yosdk_at);
                response.addCookie(yosdk_rt);
                String appId = oauthConfig.getProperty("yos.appid");
                YahooSession yahooSession = new YahooSession(client, consumer, at, appId);
                request.setAttribute("yahooSession", yahooSession);
            } catch (URISyntaxException ex) {
                throw new ServletException(ex);
            } catch (OAuthException ex) {
                clearSession(request, response);
                if (redirect) {
                    redirectForAuthorization(accessor, request, response);
                    return;
                } else {
                    throw new ServletException(ex);
                }
            }
        } catch (JSONException e) {
            throw new ServletException(e);
        }
    }

    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:com.mmj.app.web.controller.manage.ManageController.java

/**
 * Cookie?????//from   w  ww .j  a va2 s  .com
 * 
 * @param request
 * @return
 */
private List<String> getShowMenuBar(HttpServletRequest request) {
    Cookie cookies[] = request.getCookies();
    Cookie sCookie = null;
    String svalue = null;
    String sname = null;
    for (int i = 0; i < cookies.length; i++) {
        sCookie = cookies[i];
        sname = sCookie.getName();
        if ("menuConfig".equals(sname)) {
            svalue = sCookie.getValue();
            if (svalue != null) {
                return Arrays.asList(svalue.split("-_-"));
            }
            return Collections.<String>emptyList();
        }
    }
    return Collections.<String>emptyList();
}