package md.curs.servlets;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * This Servlet presents an example of working with Cookies
 * @author MG
 */
@WebServlet(urlPatterns = {"/cookies"})
public class CookiesServlet extends HttpServlet {

    private static final String COOKIES = "cookies_count";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // get all received cookies
        Cookie[] cookies = req.getCookies();

        if (cookies != null) {

            // Filter cookies that have the COOKIES name and get an optional of one
            Optional<Cookie> optionalCookie = Arrays.stream(cookies)
                    .filter(c -> c.getName().equals(COOKIES))
                    .findAny();

            // Get the cookie if exists, else create a new one
            Cookie cookie = optionalCookie.orElseGet(() -> new Cookie(COOKIES, "0"));

            // Increment the cookie value
            cookie.setValue(increment(cookie.getValue()));

            // write cookie value as response
            resp.getWriter().println(String.format("<h1>You have %s cookies!</h1>", cookie.getValue()));

            // add the updated cookie to response
            resp.addCookie(cookie);
        }
    }

    private String increment(String number) {
        // bad code :P
        // never trust client data, this code should handle cases when number is NAN (Not A Number)
        return String.valueOf(Integer.parseInt(number) + 1);
    }

}

@@ -330,16 +330,19 @@
 Cookies%0A
+ *%0A
  * @auth
@@ -708,25 +708,24 @@
 tCookies();%0A
-%0A
         if (
@@ -736,17 +736,17 @@
 ies 
-!
+=
 = null) 
 %7B%0A%0A 
@@ -741,23 +741,42 @@
 = null) 
-%7B%0A%0A    
+cookies = new Cookie%5B0%5D;%0A%0A
         
@@ -855,20 +855,16 @@
         
-  
-  
 Optional
@@ -928,20 +928,16 @@
         
-    
 .filter(
@@ -970,20 +970,16 @@
 OKIES))%0A
-    
         
@@ -1007,20 +1007,16 @@
         
-    
 // Get t
@@ -1054,28 +1054,24 @@
 e a new one%0A
-    
         Cook
@@ -1149,20 +1149,16 @@
         
-   
- 
 // Incre
@@ -1179,20 +1179,16 @@
 e value%0A
-    
         
@@ -1243,20 +1243,16 @@
         
-    
 // write
@@ -1281,28 +1281,24 @@
 nse%0A        
- 
-   
 resp.getWrit
@@ -1387,20 +1387,16 @@
         
-    
 // add t
@@ -1429,28 +1429,24 @@
 nse%0A        
-    
 resp.addCook
@@ -1461,18 +1461,8 @@
 e);%0A
-        %7D%0A
     

Fix cookies servlet