All Downloads are FREE. Search and download functionalities are using the official Maven repository.

nl.praegus.fitnesse.slim.fixtures.playwright.CookieManager Maven / Gradle / Ivy

There is a newer version: 1.8.4
Show newest version
package nl.praegus.fitnesse.slim.fixtures.playwright;

import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.options.Cookie;
import com.microsoft.playwright.options.SameSiteAttribute;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CookieManager {

    public void setCookie(Map cookieMap, BrowserContext browserContext) {
        List cookies = new ArrayList<>();
        var cookie = new Cookie(cookieMap.get("name"), cookieMap.get("value"));

        if (cookieMap.get("domain") != null) {
            cookie.setDomain(cookieMap.get("domain"))
                    .setPath(cookieMap.getOrDefault("path", "/"));
        } else  {
            cookie.setUrl(cookieMap.get("url"));
        }

        cookie.setExpires(timestampToEpoch(cookieMap.getOrDefault("expires", "2080-11-15 21:12")))
                .setSecure(Boolean.parseBoolean(cookieMap.getOrDefault("secure", "false")))
                .setHttpOnly(Boolean.parseBoolean(cookieMap.getOrDefault("httpOnly", "false")))
                .setSameSite(SameSiteAttribute.valueOf(cookieMap.getOrDefault("sameSite", "NONE")));
        cookies.add(cookie);
        browserContext.addCookies(cookies);
    }

    public void setCookies(List> cookiesList, BrowserContext browserContext) {
        cookiesList.stream().forEach(cookie -> setCookie(cookie, browserContext));
    }

    Map getCookies(BrowserContext browserContext) {
        Map cookieStrings = new HashMap<>();
        browserContext.cookies().forEach(cookie -> cookieStrings.put(cookie.name, this.formatCookieString(cookie)));
        return cookieStrings;
    }

    public void deleteCookies(BrowserContext browserContext) {
        browserContext.clearCookies();
    }

    private double timestampToEpoch(String timestamp) {
        return LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")).toEpochSecond(ZoneOffset.UTC);
    }

    private String formatCookieString(Cookie cookie) {
        return String.format("%s;%s;%s;%s;%s", cookie.value, cookie.expires, cookie.secure, cookie.httpOnly, cookie.sameSite);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy