Example usage for javax.servlet.http Cookie Cookie

List of usage examples for javax.servlet.http Cookie Cookie

Introduction

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

Prototype

public Cookie(String name, String value) 

Source Link

Document

Constructs a cookie with the specified name and value.

Usage

From source file:in.raster.oviyam.servlet.Validator.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();

    /*AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
    String loginId=principal.getName();*/

    /*??*//*from  ww w  .ja v  a 2s .  c o  m*/
    String pid = (String) request.getParameter("PatientID").trim();
    if (pid == null || "".equals(pid)) {
        out.println("??!");
        out.close();
        return;
    }

    /*?????*/
    String r = dataAccess.getReportAddress(pid);
    /*?dcmpacs?*/
    //String r=dataAccess.addDicom("x");

    /*?*/
    Boolean a = dataAccess.checsIsExist(pid);
    if (!a) {
        out.println("?!");
        out.close();
        return;
    }

    /*????*/
    //boolean b=dataAccess.checkCheckId(loginId,pid);
    //if(!b)return;

    /**/
    /*PacsQueryLogModel pqlm = new PacsQueryLogModel();
    pqlm.setApplicationId(pid);
    pqlm.setDoctorId(loginId);
    dataAccess.addPacsLog(pqlm);*/

    AE ae;
    ServletContext servletContext = getServletContext();
    ServerConfiguration serverConfiguration;
    EchoService echoService;

    String agree = request.getParameter("agree");

    if (agree != null && agree.equals("agree")) {
        Cookie agreeCookie = new Cookie("agree", "agree");
        agreeCookie.setMaxAge(60 * 60 * 24 * 365);
        response.addCookie(agreeCookie);
    }

    try {
        ae = new AE();
        //assigns the serverConfiguration instance.         
        serverConfiguration = ae.getServerConfiguration();
        /*
         * writes the serverConfiguration instance in the servletContext (application scope).
         * So all the SERVLET classes and JSP pages can access the serverConfig attribute.
         * User can use either <jsp:useBean> tag or ${applicationScope.serverConfig} EL 
         * to access the serverConfig attribute. From SERVLET classes the User can use
         * the getServletContext().getAttribute("serverConfig") to access the serverConfiguration attribute.
         */
        servletContext.setAttribute("serverConfig", serverConfiguration);

        echoService = new EchoService();
        echoService.checkEcho();
        /*If the status of EchoService is failed then the request will be forwarded to 
         * EchoFailed.jsp. Otherwise, request is forwarded to oviyam7.jsp
         * 
         */
        if (echoService.getStatus().equals("Echo failed")) {
            /*
             * writes the echoURL(dcmProtocol://aeTitle@hostName:port) attribute in request instance.
             * and forwards the request and response object to EchoFailed.jsp .
             * echoFailed attribute can be accessed through either ${request.echoURL} or 
             * <% request.getAttribute("echoURL")%>
             */
            request.setAttribute("echoURL", ae.toString());
            request.getRequestDispatcher("EchoFailed.jsp").forward(request, response);
        } else {
            // forwards the request and response to oviyam7.jsp
            String studyUID = request.getParameter("studyUID");
            String seriesUID = request.getParameter("seriesUID");
            String patientID = request.getParameter("patientID");
            if (studyUID != null && studyUID.length() <= 0) {
                request.setAttribute("param", "studyUID");
                request.getRequestDispatcher("InvalidParam.jsp").forward(request, response);
                log.error("Invalid studyUID parameter for Oviyam.");
            } else if (seriesUID != null && seriesUID.length() <= 0) {
                request.setAttribute("param", "seriesUID");
                request.getRequestDispatcher("InvalidParam.jsp").forward(request, response);
                log.error("Invalid seriesUID parameter for Oviyam.");
            } else if (patientID != null && patientID.length() <= 0) {
                request.setAttribute("param", "patientID");
                request.getRequestDispatcher("InvalidParam.jsp").forward(request, response);
                log.error("Invalid patientID parameter for Oviyam.");
            } else {
                request.getRequestDispatcher("oviyam7.jsp").forward(request, response);
            }
        }

    } catch (Exception e) {
        log.error(e.getMessage());

    }
}

From source file:it.cnr.isti.hpc.dexter.annotate.controller.SuccessController.java

@RequestMapping(value = "/authSuccess")
public ModelAndView getRedirectURL(final HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    SocialAuthManager manager = socialAuthTemplate.getSocialAuthManager();
    AuthProvider provider = manager.getCurrentAuthProvider();

    HttpSession session = request.getSession();

    System.out.println("session-id = " + session.getId());
    if (provider == null) {
        logger.error("cannot find provider");
        RedirectView view = new RedirectView("index.html");
        ModelAndView mv = new ModelAndView(view);
        return mv;

    }//ww  w.ja va  2 s  .c om
    Profile profile = provider.getUserProfile();
    System.out.println("profile: \n" + profile);
    User user = new User();
    String mail = profile.getEmail();
    if (mail == null) {
        mail = profile.getValidatedId() + "@" + profile.getProviderId() + ".app";
    }
    user.setEmail(mail);
    String first = profile.getFirstName();
    String last = profile.getLastName();
    String display = profile.getDisplayName();

    user.setFirstName((first == null) ? "" : first);

    user.setLastName((last == null || last.isEmpty()) ? mail : last);

    user.setDisplayName(display);
    if (display == null) {
        user.setDisplayName(mail);

    }
    String pwd = pswGenerator.nextSessionId();
    user.setPassword(pwd);

    User u = dao.getUserByMail(user.getEmail());
    System.out.println("------------success---------------");
    if (u != null)
        System.out.println(u.toString());
    System.out.println("----------------------------------");
    if (u != null) {
        logger.info("user ", user.getEmail() + " logged in");
        user = u;
    } else {
        logger.info("add user {}", user.getEmail());
        dao.addUser(user);
    }
    // String type = null;
    // if (session.getAttribute(Constants.REQUEST_TYPE) != null) {
    // type = (String) session.getAttribute(Constants.REQUEST_TYPE);
    // }
    // if (type != null) {
    // if (Constants.REGISTRATION.equals(type)) {
    // return registration(provider);
    // } else if (Constants.IMPORT_CONTACTS.equals(type)) {
    // return importContacts(provider);
    // } else if (Constants.SHARE.equals(type)) {
    // return new ModelAndView("shareForm", "connectedProvidersIds",
    // manager.getConnectedProvidersIds());
    // }
    // }

    RedirectView view = new RedirectView("index.html");
    ModelAndView mv = new ModelAndView(view);

    Cookie cookie = new Cookie("mail", user.getEmail());
    response.addCookie(cookie);
    cookie = new Cookie("psw", user.getPassword());
    response.addCookie(cookie);
    cookie = new Cookie("uid", String.valueOf(user.getId()));
    response.addCookie(cookie);

    // mv.addObject("uid", user.getId());
    // mv.addObject("pwd", user.getPassword());
    return mv;

}

From source file:org.eclipse.userstorage.tests.util.USSServer.java

protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Map<String, Object> requestObject = JSONUtil.parse(request.getInputStream(), null);

    String username = (String) requestObject.get("username");
    String password = (String) requestObject.get("password");

    User user = users.get(username);//from ww w.  ja  v a 2s  .co  m
    if (user == null || password == null || !password.equals(user.getPassword())) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/json");

    Session session = addSession(user);
    Cookie cookie = new Cookie("SESSION", session.getID());
    cookie.setPath("/");
    response.addCookie(cookie);

    Map<String, Object> responseObject = new LinkedHashMap<String, Object>();
    responseObject.put("sessid", session.getID());
    responseObject.put("token", session.getCSRFToken());
    InputStream body = JSONUtil.build(responseObject);

    try {
        ServletOutputStream out = response.getOutputStream();
        IOUtil.copy(body, out);
        out.flush();
    } finally {
        IOUtil.closeSilent(body);
    }
}

From source file:com.googlesource.gerrit.plugins.github.oauth.GitHubLogin.java

private String getScopesKey(HttpServletRequest request, HttpServletResponse response) {
    String scopeRequested = request.getParameter("scope");
    if (scopeRequested == null) {
        scopeRequested = getScopesKeyFromCookie(request);
    }/*from w w  w . j  a v a2s.c  o m*/

    if (scopeRequested != null) {
        Cookie scopeCookie = new Cookie("scope", scopeRequested);
        scopeCookie.setPath("/");
        scopeCookie.setMaxAge((int) SCOPE_COOKIE_NEVER_EXPIRES);
        response.addCookie(scopeCookie);
    }

    return Objects.firstNonNull(scopeRequested, "scopes");
}

From source file:com.boylesoftware.web.impl.auth.SessionlessAuthenticationService.java

/**
 * Create authentication token cookie.//w w  w .ja  va 2 s. c o  m
 *
 * @param request The request.
 * @param value Value for the cookie.
 *
 * @return The cookie.
 */
Cookie createAuthCookie(final HttpServletRequest request, final String value) {

    final Cookie authCookie = new Cookie(AUTH_COOKIE_NAME, value);
    authCookie.setPath(StringUtils.emptyIfNull(request.getContextPath()) + "/");

    return authCookie;
}

From source file:io.lavagna.web.helper.UserSession.java

private static void addRememberMeCookie(int userId, HttpServletRequest req, HttpServletResponse resp,
        UserRepository userRepository) {

    String token = userRepository.createRememberMeToken(userId);
    ///*from w  ww  .ja v a 2 s.  c o m*/
    Cookie c = new Cookie("LAVAGNA_REMEMBER_ME", userId + "," + token);
    c.setPath(req.getContextPath() + "/");
    c.setHttpOnly(true);
    c.setMaxAge(60 * 60 * 24 * 365); // 1 year
    if (req.getServletContext().getSessionCookieConfig().isSecure()) {
        c.setSecure(true);
    }
    resp.addCookie(c);
}

From source file:com.concursive.connect.web.modules.login.auth.session.SessionValidator.java

/**
 * Follow the current session validation schema and determine if there is a
 * valid session for the user. If there is a valid session, return the
 * <code>User</code> associated with that session, otherwise, return
 * <i>null</i>./*from   www  .j  a va2  s.  co  m*/
 *
 * @param request -
 *                The servlet request as provided by the
 *                <code>ControllerServlet</code>.
 * @return A valid <code>User</code> upon successful validation.<br>
 *         <code>Null</code> upon validation failure
 */
public User validateSession(ServletContext context, HttpServletRequest request, HttpServletResponse response) {
    User thisUser = (User) request.getSession(false).getAttribute(Constants.SESSION_USER);
    LOG.debug("Has user session: " + (thisUser != null));
    if (thisUser == null || !thisUser.isLoggedIn()) {
        LOG.debug("Checking for cookie...");
        // Check cookie for session info and generate a logged in user
        String guid = CookieUtils.getCookieValue(request, Constants.COOKIE_USER_GUID);
        if (guid == null) {
            LOG.debug("No cookie found.");
            return (thisUser == null ? null : thisUser);
        }
        LOG.debug("Cookie found with guid: " + guid);
        // Retrieve prefs to see if user with guid exists
        ApplicationPrefs prefs = (ApplicationPrefs) context.getAttribute(Constants.APPLICATION_PREFS);
        // Connection info
        ConnectionElement ce = new ConnectionElement();
        ce.setDriver(prefs.get("SITE.DRIVER"));
        ce.setUrl(prefs.get("SITE.URL"));
        ce.setUsername(prefs.get("SITE.USER"));
        ce.setPassword(prefs.get("SITE.PASSWORD"));
        ConnectionPool sqlDriver = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL);
        Connection db = null;
        try {
            db = sqlDriver.getConnection(ce);
            // Load the user record from the guid
            thisUser = UserUtils.loadUserFromGuid(db, guid);
            if (thisUser != null) {
                // Track the login
                thisUser.updateLogin(db, request, prefs, null);
                thisUser.setBrowserType(request.getHeader("USER-AGENT"));
                // Apply defaults
                UserUtils.createLoggedInUser(thisUser, db, prefs, context);
                // Extend the cookie
                Cookie userCookie = new Cookie(Constants.COOKIE_USER_GUID, UserUtils.generateGuid(thisUser));
                userCookie.setPath("/");
                // 14 day cookie
                userCookie.setMaxAge(14 * 24 * 60 * 60);
                response.addCookie(userCookie);
            }
        } catch (Exception e) {
            thisUser = null;
            e.printStackTrace();
        } finally {
            if (db != null) {
                sqlDriver.free(db);
            }
        }
        // Add to session
        request.getSession().setAttribute(Constants.SESSION_USER, thisUser);
        request.getSession().setAttribute(Constants.SESSION_CONNECTION_ELEMENT, ce);
    }
    return thisUser;
}

From source file:csns.web.controller.SectionController.java

@RequestMapping("/section/evaluated")
public String evaluated(@RequestParam(required = false) Quarter quarter, ModelMap models, HttpSession session,
        HttpServletResponse response) {/*from w  w w. j a v  a2  s  .c  o m*/
    Cookie cookie = new Cookie("default-home", "/section/evaluated");
    cookie.setPath("/");
    cookie.setMaxAge(100000000);
    response.addCookie(cookie);

    return list("evaluated", quarter, models, session);
}

From source file:org.syncope.console.commons.PreferenceManager.java

public void set(final Request request, final Response response, final String key, final String value) {

    Cookie prefCookie = ((WebRequest) request).getCookie(Constants.PREFS_COOKIE_NAME);

    final Map<String, String> prefs = new HashMap<String, String>();

    if (prefCookie == null || !StringUtils.hasText(prefCookie.getValue())) {
        prefCookie = new Cookie(Constants.PREFS_COOKIE_NAME, null);
    } else {//from   ww  w.  ja v  a  2  s.  c  o  m
        prefs.putAll(getPrefs(new String(Base64.decodeBase64(prefCookie.getValue().getBytes()))));
    }

    // after retrieved previous setting in order to overwrite the key ...
    prefs.put(key, value);

    try {
        prefCookie.setValue(new String(Base64.encodeBase64(setPrefs(prefs).getBytes())));
    } catch (IOException e) {
        LOG.error("Could not set preferences " + prefs, e);
    }

    prefCookie.setMaxAge(ONE_YEAR_TIME);
    ((WebResponse) response).addCookie(prefCookie);
}

From source file:com.adobe.acs.commons.forms.helpers.impl.PostRedirectGetWithCookiesFormHelperImpl.java

/**
 * Adds a cookie containing the serialised contents of the form to a cookie named after the GET lookup key
 * @param response//from   w ww .j av  a2  s. c o m
 * @param form
 * @throws JSONException
 */
protected void addFlashCookie(SlingHttpServletResponse response, Form form) throws JSONException {
    final String name = this.getGetLookupKey(form.getName());
    final String value = getQueryParameterValue(form);
    final Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(COOKIE_MAX_AGE);
    CookieUtil.addCookie(cookie, response);
}