@Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    HttpSession session = req.getSession();
    String exitParam = req.getParameter("exit");
    String deleteParam = req.getParameter("delete");
    String settingsParam = req.getParameter("settings");

    if ("settings".equals(settingsParam)) {
      resp.sendRedirect("/profileSettings");
      return;
    }

    if ("exit".equals(exitParam)) {
      // обнуляем куку
      Cookie[] cookies = req.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember")) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            break;
          }
        }
      }
      session.setAttribute("user_a", null);
      resp.sendRedirect("/login");
    }

    if ("delete".equals(deleteParam)) {
      // обнуляем куку
      Cookie[] cookies = req.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember")) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            break;
          }
        }
      }
      try {
        UserRepository.deleteUser((User) session.getAttribute("user_a"));
      } catch (SQLException e) {
        req.setAttribute("message", "Some problems with server");
        resp.sendRedirect("/profile");

        e.printStackTrace();
      }
      session.setAttribute("user_a", null);
      resp.sendRedirect("/welcome");
    }
  }
示例#2
0
  public static void addCookie(
      HttpServletRequest request, HttpServletResponse response, Cookie cookie, boolean secure) {

    if (!_SESSION_ENABLE_PERSISTENT_COOKIES || _TCK_URL) {
      return;
    }

    // LEP-5175

    String name = cookie.getName();

    String originalValue = cookie.getValue();
    String encodedValue = originalValue;

    if (isEncodedCookie(name)) {
      encodedValue = UnicodeFormatter.bytesToHex(originalValue.getBytes());

      if (_log.isDebugEnabled()) {
        _log.debug("Add encoded cookie " + name);
        _log.debug("Original value " + originalValue);
        _log.debug("Hex encoded value " + encodedValue);
      }
    }

    cookie.setSecure(secure);
    cookie.setValue(encodedValue);
    cookie.setVersion(0);

    // Setting a cookie will cause the TCK to lose its ability to track
    // sessions

    response.addCookie(cookie);
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Cookie[] cookies = request.getCookies();
    Cookie requestCountCookie = null;
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        if ("requestCount".equals(cookies[i].getName())) {
          requestCountCookie = cookies[i];
          break;
        }
      }
    }
    int count = 1;
    if (requestCountCookie == null) {
      requestCountCookie = new Cookie("requestCount", count + "");
    } else {
      count = Integer.parseInt(requestCountCookie.getValue());
      count++;
    }
    requestCountCookie.setValue(count + "");
    requestCountCookie.setMaxAge(9999999);
    response.addCookie(requestCountCookie);

    PrintWriter out = response.getWriter();
    out.println("<h1>Request Count : " + count + "</h1>");
  }
示例#4
0
  public void json(RequestInfoHttp reqInfo, String content, List<Cookie> cookies)
      throws IOException {

    if (cookies.size() > 0) {
      HttpServletResponse res = reqInfo.getRes();

      Cookie[] exists = reqInfo.getReq().getCookies();

      for (Cookie ck : cookies) {
        Cookie found = null;
        for (Cookie eck : exists) {
          if (eck.getName().equals(ck.getName())) {
            found = eck;
            break;
          }
        }
        if (found == null) {
          res.addCookie(ck);
        } else {
          found.setValue(ck.getValue());
          found.setMaxAge(ck.getMaxAge());
          found.setPath(ck.getPath());
          res.addCookie(found);
        }
      }
    }

    json(reqInfo, content);
  }
示例#5
0
 public static void removeToken(
     HttpServletRequest request, HttpServletResponse response, String name) {
   Cookie cookie = CookieUtil.getCookie(request, name);
   cookie.setMaxAge(0);
   cookie.setValue(null);
   CookieUtil.addCookie(response, cookie);
 }
示例#6
0
 public static void removeCookie(HttpServletResponse response, Cookie cookie) {
   if (cookie != null) {
     cookie.setPath("/");
     cookie.setValue("");
     cookie.setMaxAge(0);
     response.addCookie(cookie);
   }
 }
  /**
   * Convenience method for deleting a cookie by name. Delete the cookie by setting its maximum age
   * to zero.
   *
   * @param cookie The cookie to delete
   */
  protected static void clear(final Cookie cookie) {
    if (cookie != null) {
      // Delete the cookie by setting its maximum age to zero
      cookie.setMaxAge(0);
      cookie.setValue(null);

      save(cookie);
    }
  }
示例#8
0
 private void refreshCookie(Cookie cookie, HttpServletResponse response) {
   cookie.setValue(values[index++]);
   if (index == 8) {
     index = 0;
   }
   int minutes = 10;
   cookie.setMaxAge(60 * minutes);
   response.addCookie(cookie);
 }
 @Override
 public Cookie[] getCookies() {
   Cookie[] existingCookies = super.getCookies();
   if (existingCookies != null) {
     for (int i = 0; i < existingCookies.length; ++i) {
       Cookie cookie = existingCookies[i];
       cookie.setValue(filterParamString(cookie.getValue()));
     }
   }
   return existingCookies;
 }
示例#10
0
 @RequestMapping(value = "/logout", method = RequestMethod.GET)
 public String logout(HttpServletRequest request) {
   securityUserService.logout();
   Cookie[] cookies = request.getCookies();
   for (Cookie cookie : cookies) {
     if (cookie.getName().equals("AuthToken")) {
       cookie.setValue(null);
     }
   }
   return "index";
 }
示例#11
0
  /**
   * 把用户名写入cookie
   *
   * @param userName userName
   * @param response response
   * @throws UnsupportedEncodingException UnsupportedEncodingException
   */
  private void writeCookieWithName(final String userName, final HttpServletResponse response)
      throws UnsupportedEncodingException {
    // "UN"的Cookie记录着用户登录后的用户名信息(只会在session中存在)
    Cookie cookie = new Cookie("UN", null);
    cookie.setDomain(DomainConstant.DOMAIN);
    cookie.setMaxAge(
        StringUtils.isNotEmpty(keepLogin)
            ? Integer.parseInt(app.getInitParameter("UNCookieTimeOut"))
            : -1);
    cookie.setPath("/");
    cookie.setValue(URLEncoder.encode(userName, "UTF-8"));
    response.addCookie(cookie);

    // "unUserName"保存了用户的登录名,不论用户是否登录状态都会保留
    cookie = new Cookie("unUserName", null);
    cookie.setDomain(DomainConstant.DOMAIN);
    cookie.setMaxAge(Integer.parseInt(app.getInitParameter("userNameCookieTimeOut")));
    cookie.setPath("/");
    String unUserName = userName;
    String userId = userName;
    if (unUserName.indexOf("^!^") != -1) {
      unUserName = unUserName.substring(0, unUserName.indexOf("^!^"));
      userId = userName.substring(userName.indexOf("^!^") + ID_POS, userName.length());
    }
    cookie.setValue(URLEncoder.encode(unUserName, "UTF-8"));
    response.addCookie(cookie);

    // 临时保持原样LSTA cookie给攻略用。
    // LvmamaMd5Key这个类是原来老LVMAMA COMMON里的类,我在新LVMAMA COMMON里没找到,也不敢移进去
    // 暂时保留在PET SSO项目里,到时采用新方法后一起移除
    // TODO BY liuyi
    cookie = new Cookie("LSTA", null);
    cookie.setDomain(DomainConstant.DOMAIN);
    cookie.setMaxAge(
        StringUtils.isNotEmpty(keepLogin)
            ? Integer.parseInt(app.getInitParameter("UNCookieTimeOut"))
            : -1);
    cookie.setPath("/");
    cookie.setValue(LvmamaMd5Key.encode(userId));
    response.addCookie(cookie);
  }
示例#12
0
 /**
  * 设置 Cookie
  *
  * @param name 名称
  * @param value 值
  * @param maxAge 生存时间(单位秒)
  * @param uri 路径
  */
 public static void setCookie(
     HttpServletResponse response, String name, String value, String path, int maxAge) {
   Cookie cookie = new Cookie(name, null);
   cookie.setPath(path);
   cookie.setMaxAge(maxAge);
   try {
     cookie.setValue(URLEncoder.encode(value, "utf-8"));
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   response.addCookie(cookie);
 }
示例#13
0
 @RequestMapping(value = "/delete", method = RequestMethod.POST)
 public String deleteUser(@RequestParam("userId") Integer userId, HttpServletRequest request)
     throws IOException {
   userService.deleteUser(userId);
   Cookie[] cookies = request.getCookies();
   for (Cookie cookie : cookies) {
     if (cookie.getName().equals("AuthToken")) {
       cookie.setValue(null);
     }
   }
   return "index";
 }
 protected void clearCookieValue() {
   Cookie cookie = getCookie();
   if (cookie != null) {
     HttpServletResponse response =
         (HttpServletResponse)
             FacesContext.getCurrentInstance().getExternalContext().getResponse();
     cookie.setValue(null);
     cookie.setPath(cookiePath);
     cookie.setMaxAge(0);
     response.addCookie(cookie);
   }
 }
 private void clearGarbage(
     HttpServletRequest servletRequest,
     HttpServletResponse servletResponse,
     String cookieName,
     int startNum,
     String path,
     String domain) {
   Pattern namePattern = Pattern.compile(cookieName + COOKIE_NAME_PATTERN_SUFFIX);
   javax.servlet.http.Cookie[] cookies = servletRequest.getCookies();
   if (ArrayUtil.isEmpty(cookies)) {
     return;
   }
   for (javax.servlet.http.Cookie cookie : cookies) {
     if (cookieName.equals(cookie.getName()) && startNum != 0) {
       cookie.setMaxAge(0);
       cookie.setValue(null);
       cookie.setPath(path);
       if (StringUtil.isEmpty(domain) == false) {
         cookie.setDomain(domain);
       }
       servletResponse.addCookie(cookie);
     }
     Matcher matcher = namePattern.matcher(cookie.getName());
     if (matcher.matches()) {
       int index = Integer.parseInt(matcher.group(1));
       if (index > startNum) {
         cookie.setMaxAge(0);
         cookie.setValue(null);
         cookie.setPath(path);
         if (StringUtil.isEmpty(domain) == false) {
           cookie.setDomain(domain);
         }
         servletResponse.addCookie(cookie);
       }
     }
   }
 }
示例#16
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String name = request.getParameter("Login_Name");
    String password = request.getParameter("Password");

    System.out.println(name);
    System.out.println(password);

    User user = model.getUser(name);

    if (user != null) {
      if (user.getPassword().equals(password)) {

        HttpSession session = request.getSession();
        if (!session.isNew()) {
          session.invalidate();
          session = request.getSession();
        }

        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
          if (containsCookie(cookies, name)) {
            for (Cookie cookie : cookies) {
              if (cookie.getName().equals(user.getName())) {
                cookie.setValue(null);
              }
            }
            System.out.println("old cookie: " + request.getCookies().length);
          } else {
            UserCookie cookie = new UserCookie(user.getName(), null);
            System.out.println("adding cookie with name: " + user.getName());
            cookie.setMaxAge(99999);
            response.addCookie(cookie);
            System.out.println("new cookie: " + request.getCookies().length);
          }
        }

        session.setAttribute("name", name);

        if (user.getRol() == User.ADMIN) {
          response.sendRedirect("/Webtechnologie_Opdracht1/ShowPersonServlet");
        } else if (user.getRol() == User.HUURDER) {
          request
              .getServletContext()
              .getRequestDispatcher("/WEB-INF/huurder.html")
              .forward(request, response);
        } else if (user.getRol() == User.VERHUURDER) {
          response.sendRedirect("/Webtechnologie_Opdracht1/ShowRoomsServlet");
        }
      } else {
        request
            .getServletContext()
            .getRequestDispatcher("/WEB-INF/fouteInlog.html")
            .forward(request, response);
      }
    } else {
      request
          .getServletContext()
          .getRequestDispatcher("/WEB-INF/fouteInlog.html")
          .forward(request, response);
    }

    System.out.println(model == null);

    System.out.println(model.getUsers());
  }
示例#17
0
  /**
   * Redirects the HTTP request to the Authentication module. It gets the authentication url from
   * <code>SystemProperties</code>.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception IOException If an input or output exception occurs
   */
  private void redirectForAuthentication(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.redirectForAuthentication: " + "requestURL=" + request.getRequestURL());
    }
    StringBuffer redirectURL = new StringBuffer(100);
    StringBuffer gotoURL = new StringBuffer(100);

    // Check if user has authenticated to another OpenSSO
    // instance
    String authURL = null;
    Cookie authCookie = CookieUtils.getCookieFromReq(request, authURLCookieName);
    if (authCookie != null) {
      authURL = CookieUtils.getCookieValue(authCookie);
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication: "
                + "got an authenticated URL= "
                + authURL);
      }
    }
    try {
      if (authURL == null
          || authURL.length() == 0
          || !authURL.toLowerCase().startsWith("http")
          || policyAdviceList != null) {
        String finalURL = request.getParameter(GOTO_PARAMETER);

        if (finalURL == null || finalURL.equals("")) {
          finalURL = request.getParameter(TARGET_PARAMETER);
        }

        if (finalURL == null || finalURL.equals("")) {
          showError(response, "GOTO or TARGET parameter is missing" + " in the request");
          return;
        }

        gotoURL
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(TARGET_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(finalURL))
            .append(AMPERSAND)
            .append(requestParams);

        // Construct the login URL
        String cdcurl = SystemProperties.get(Constants.CDCSERVLET_LOGIN_URL);
        if (cdcurl != null && cdcurl.length() > 0) {
          if (cdcurl.indexOf("?") == -1) {
            redirectURLStr = cdcurl + QUESTION_MARK;
          } else {
            redirectURLStr = cdcurl + AMPERSAND;
          }
        } else {
          redirectURLStr = AUTHURI + QUESTION_MARK;
        }
        if (debug.messageEnabled()) {
          debug.message("CDCClientServlet init redirect URL is" + "set to= " + redirectURLStr);
        }

        redirectURL.append(redirectURLStr);
        if (policyAdviceList != null) {
          redirectURL.append(policyAdviceList).append(AMPERSAND);
        }
        redirectURL
            .append(GOTO_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(gotoURL.toString()));

        // Check for policy advices
        if (policyAdviceList != null) {
          redirectURL.append(AMPERSAND).append(policyAdviceList);
        }
        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication"
                  + ":redirectURL before dispatching is="
                  + redirectURL);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(redirectURL.toString());
        dispatcher.forward(request, response);
      } else {
        // Redirect the user to the authenticated URL
        redirectURL
            .append(authURL)
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(request.getQueryString());
        // Reset the cookie value to null, to avoid continous loop
        // when a load balancer is used
        if (authCookie != null) {
          authCookie.setValue("");
          response.addCookie(authCookie);
        }
        response.sendRedirect(redirectURL.toString());
      }

      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication:"
                + "Forwarding for authentication to= "
                + redirectURL);
      }
    } catch (IOException ex) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication: Failed "
              + "in forwarding to Authentication service. IOException",
          ex);
      showError(response, "Could for forward to authentication service:" + ex.getMessage());
    } catch (ServletException se) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. ServletException",
          se);
      showError(response, "Could for forward to authentication service:" + se.getMessage());
    } catch (IllegalStateException ie) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. Illegal state",
          ie);
      showError(response, "Could for forward to authentication service:" + ie.getMessage());
    }
  }
示例#18
0
  /**
   * Grants a service ticket for the given service, using the given TicketGrantingTicket. If no
   * 'service' is specified, simply forward to message conveying generic success.
   *
   * @param request request
   * @param response response
   * @param t t
   * @param serviceId serviceId
   * @param first first
   * @throws ServletException ServletException
   * @throws IOException IOException
   */
  private void grantForService(
      final HttpServletRequest request,
      final HttpServletResponse response,
      final TicketGrantingTicket t,
      final String serviceId,
      final boolean first)
      throws ServletException, IOException {
    try {
      String actualServiceId = serviceId != null ? serviceId : "http://www.lvmama.com/";
      if (actualServiceId.contains("&amp;")) {
        // log("service=="+actualServiceId);
        actualServiceId = actualServiceId.replaceAll("&amp;", "&");
      }
      ServiceTicket st = new ServiceTicket(t, actualServiceId, first);
      String token = stCache.addTicket(st);
      request.setAttribute("serviceId", actualServiceId);
      request.setAttribute("token", token);
      if (!first) {
        if (privacyRequested(request)) {
          app.getRequestDispatcher(confirmService).forward(request, response);
        } else {
          request.setAttribute("first", "false");
          Cookie unCookie = null;
          Cookie[] cookies = request.getCookies();
          if (null != cookies) {
            for (int i = 0; i < cookies.length; i++) {
              if (cookies[i].getName().equals("UN")) {
                unCookie = cookies[i];
              }
            }
          }
          if (null == unCookie) {
            unCookie = new Cookie("UN", null);
            unCookie.setDomain(DomainConstant.DOMAIN);
            unCookie.setMaxAge(
                StringUtils.isNotEmpty(keepLogin)
                    ? Integer.parseInt(app.getInitParameter("UNCookieTimeOut"))
                    : -1);
            unCookie.setPath("/");

            unCookie.setValue(
                URLEncoder.encode(new String(InfoBase64Coding.decrypt(t.getUsername())), "UTF-8"));

            response.addCookie(unCookie);
          }

          app.getRequestDispatcher(serviceSuccess).forward(request, response);
        }
      } else {
        request.setAttribute("first", "true");
        Cookie unCookie = null;
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
          for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("UN")) {
              unCookie = cookies[i];
            }
          }
        }
        if (null == unCookie) {
          unCookie = new Cookie("UN", null);
          unCookie.setDomain(DomainConstant.DOMAIN);
          unCookie.setMaxAge(
              StringUtils.isNotEmpty(keepLogin)
                  ? Integer.parseInt(app.getInitParameter("UNCookieTimeOut"))
                  : -1);
          unCookie.setPath("/");
          unCookie.setValue(
              URLEncoder.encode(new String(InfoBase64Coding.decrypt(t.getUsername())), "UTF-8"));
          response.addCookie(unCookie);
        }
        app.getRequestDispatcher(serviceSuccess).forward(request, response);
      }
    } catch (TicketException ex) {
      throw new ServletException(ex.toString());
    }
  }
示例#19
0
  /**
   * Redirects the HTTP request to the Authentication module. It gets the authentication url from
   * <code>SystemProperties</code>.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception IOException If an input or output exception occurs
   */
  private void redirectForAuthentication(
      HttpServletRequest request,
      HttpServletResponse response,
      String policyAdviceList,
      String requestParams)
      throws IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.redirectForAuthentication: " + "requestURL=" + request.getRequestURL());
    }
    StringBuilder redirectURL = new StringBuilder(100);
    StringBuilder gotoURL = new StringBuilder(100);

    // Check if user has authenticated to another OpenAM
    // instance
    String authURL = null;
    Cookie authCookie = CookieUtils.getCookieFromReq(request, authURLCookieName);
    if (authCookie != null) {
      authURL = CookieUtils.getCookieValue(authCookie);
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication: "
                + "got an authenticated URL= "
                + authURL);
      }
    }
    try {
      if (authURL == null
          || authURL.length() == 0
          || !authURL.toLowerCase().startsWith("http")
          || policyAdviceList != null) {
        String finalURL = request.getParameter(GOTO_PARAMETER);

        if (finalURL == null || finalURL.equals("")) {
          finalURL = request.getParameter(TARGET_PARAMETER);
        }

        if (finalURL == null || finalURL.equals("")) {
          if (debug.messageEnabled()) {
            debug.message(
                "CDCClientServlet.redirectForAuthentication: "
                    + "goto or target parameter is missing in the request.");
          }

          showError(response, SERVER_ERROR_STR_MATCH);
          return;
        }

        gotoURL
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(TARGET_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(finalURL))
            .append(AMPERSAND)
            .append(requestParams);

        // Construct the login URL
        String loginURI = request.getParameter(LOGIN_URI);
        String cdcUri;

        if (loginURI != null && !loginURI.isEmpty() && isValidCDCURI(loginURI)) {
          if (debug.messageEnabled()) {
            debug.message(
                "CDCClientServlet.redirectForAuthentication:found " + LOGIN_URI + "=" + loginURI);
          }

          cdcUri = loginURI;
        } else {
          cdcUri = cdcAuthURI;
        }

        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication: Login URI is set to = " + cdcUri);
        }

        if (cdcUri.indexOf(QUESTION_MARK) == -1) {
          redirectURL.append(cdcUri).append(QUESTION_MARK);
        } else {
          redirectURL.append(cdcUri).append(AMPERSAND);
        }

        if (policyAdviceList != null) {
          redirectURL.append(policyAdviceList).append(AMPERSAND);
        }
        redirectURL
            .append(GOTO_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(gotoURL.toString()));

        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication"
                  + ":redirectURL before dispatching is="
                  + redirectURL);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(redirectURL.toString());
        dispatcher.forward(request, response);
      } else {
        // Redirect the user to the authenticated URL
        redirectURL
            .append(authURL)
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(request.getQueryString());
        // Reset the cookie value to null, to avoid continuous loop
        // when a load balancer is used
        if (authCookie != null) {
          authCookie.setValue("");
          response.addCookie(authCookie);
        }
        response.sendRedirect(redirectURL.toString());
      }

      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication:"
                + "Forwarding for authentication to= "
                + redirectURL);
      }
    } catch (IOException ex) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication: Failed "
              + "in forwarding to Authentication service. IOException",
          ex);
      showError(response, "Could for forward to authentication service:" + ex.getMessage());
    } catch (ServletException se) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. ServletException",
          se);
      showError(response, "Could for forward to authentication service:" + se.getMessage());
    } catch (IllegalStateException ie) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. Illegal state",
          ie);
      showError(response, "Could for forward to authentication service:" + ie.getMessage());
    }
  }
示例#20
0
 public void setValue(String value) {
   cookie.setValue(value);
 }
示例#21
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    // UserService userService = UserServiceFactory.getUserService();
    // User user = userService.getCurrentUser();

    // este try se usa por posibles problemas del server de google
    try {

      String texto = req.getParameter("texto");
      String latitud = req.getParameter("latitud");
      String longitud = req.getParameter("longitud");

      PersistenceManager pm = PMF.get().getPersistenceManager();

      String usuario = "";
      int i = 0;
      Cookie[] cookies = req.getCookies();
      // se recorren las cookies en busca del nombre de usuario para buscar en la tabla
      for (i = 0; i < cookies.length; i++) {

        if (cookies[i].getName().equalsIgnoreCase("username")) {
          usuario = cookies[i].getValue();
        }
      }

      Query query = pm.newQuery(Usuarios.class, "name == '" + usuario + "'");

      try {
        List<Usuarios> results = (List<Usuarios>) query.execute();
        if (!results.isEmpty()) {
          for (Usuarios u : results) {

            float x = Float.parseFloat(latitud);
            float y = Float.parseFloat(longitud);

            u.addPendX(x);
            u.addPendY(y);
            u.setTexto(texto);
            // codigo html para ver que todo ha ido bien
            /*
            resp.setContentType("text/html");
            PrintWriter pw = resp.getWriter();
            pw.println("<HTML><HEAD><TITLE>Coordenadas almacenadas correctamente</TITLE></HEAD>");
            pw.println("<BODY>");
            pw.println("<H2>Leyendo parámetros desde un formulario html</H2>");

            pw.println("<H3>X: "+x+"</H3>");
            pw.println("<H3>Y: "+y+"</H3>");
            pw.println("<H3>TEXTO: "+texto+"</H3>");
            pw.println("</BODY></HTML>");


                  pw.close();*/

            // creo cookie con las coordenadas recuperadas
            Cookie coordenadas = new Cookie("coordPend", u.getCoordPend().toString());
            coordenadas.setValue(u.getCoordPend().toString());
            coordenadas.setComment("coordenadas pendientes del usuario");
            coordenadas.setPath("/");
            resp.addCookie(coordenadas);

            resp.sendRedirect("/php/quieroIr.php");
          }
        } else {
          // no persistent object found
          resp.sendRedirect("/mensajesFallo/coordInvalid.html");
        }

      } catch (Exception e) {
        resp.sendRedirect("/mensajesFallo/coordInvalid.html");
      } finally {
        query.closeAll();
        pm.close();
      }

    } catch (Exception e) {
      resp.sendRedirect("/mensajesFallo/falloBaseDatos.html");
    }
  }
示例#22
0
 @Override
 public void setValue(final String value) {
   cookie.setValue(value);
 }
 /**
  * Assigns a new value to a cookie after the cookie is created. If you use a binary value, you may
  * want to use BASE64 encoding.
  *
  * <p>With Version 0 cookies, values should not contain white space, brackets, parentheses, equals
  * signs, commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty
  * values may not behave the same way on all browsers.
  *
  * @param newValue a <code>String</code> specifying the new value
  * @see #getValue
  * @see Cookie
  */
 @Override
 public void setValue(String newValue) {
   wrappedCookie.setValue(newValue);
 }