001/* 002 * This file is part of the JDrupes non-blocking HTTP Codec 003 * Copyright (C) 2022 Michael N. Lipp 004 * 005 * This program is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU Lesser General Public License as published 007 * by the Free Software Foundation; either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, but 011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 013 * License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public License along 016 * with this program; if not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jdrupes.httpcodec.types; 020 021import java.net.HttpCookie; 022import java.text.ParseException; 023 024import org.jdrupes.httpcodec.types.Converters.SameSiteAttribute; 025 026/** 027 * Converts a {@link HttpCookie} to the representation used in 028 * a "Set-Cookie" header. 029 * 030 * @see "[Set-Cookie](https://www.rfc-editor.org/rfc/rfc6265#section-4.1)" 031 */ 032public class SetCookieStringConverter implements Converter<HttpCookie> { 033 034 private SameSiteAttribute sameSiteAttribute = SameSiteAttribute.UNSET; 035 036 /** 037 * Returns the same site attribute. 038 * 039 * @return the same site attribute 040 */ 041 public SameSiteAttribute sameSiteAttribute() { 042 return sameSiteAttribute; 043 } 044 045 /** 046 * Controls if and which same site attribute is added to the string. 047 * 048 * @param sameSiteAttribute the new same site attribute 049 */ 050 public SetCookieStringConverter 051 setSameSiteAttribute(SameSiteAttribute sameSiteAttribute) { 052 this.sameSiteAttribute = sameSiteAttribute; 053 return this; 054 } 055 056 @Override 057 public String asFieldValue(HttpCookie cookie) { 058 StringBuilder result = new StringBuilder(); 059 result.append(cookie.getName()).append('='); 060 if (cookie.getValue() != null) { 061 result.append(cookie.getValue()); 062 } 063 if (cookie.getMaxAge() > -1) { 064 result.append("; Max-Age="); 065 result.append(Long.toString(cookie.getMaxAge())); 066 } 067 if (cookie.getDomain() != null) { 068 result.append("; Domain="); 069 result.append(cookie.getDomain()); 070 } 071 if (cookie.getPath() != null) { 072 result.append("; Path="); 073 result.append(cookie.getPath()); 074 } 075 if (cookie.getSecure()) { 076 result.append("; Secure"); 077 } 078 if (cookie.isHttpOnly()) { 079 result.append("; HttpOnly"); 080 } 081 if (sameSiteAttribute != SameSiteAttribute.UNSET) { 082 result.append("; SameSite=").append(sameSiteAttribute.value()); 083 } 084 return result.toString(); 085 } 086 087 @Override 088 public HttpCookie fromFieldValue(String text) 089 throws ParseException { 090 throw new UnsupportedOperationException(); 091 } 092 093}