# Cookie.java

    /*
    ** Module   : Cookie.java
    ** Abstract : Implementation of the builtin class.
    **
    ** Copyright (c) 2019-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- -------------------------------Description--------------------------------
    ** 001 CA  20190526 First version, stubs taken by converting the skeleton using FWD.
    **     RFB 20191022 Added LegacyResource annotation
    ** 002 CA  20191024 Added method support levels and updated the class support level.
    ** 003 ME  20200902 Add implementation for methods as per OE12.2.
    **         20201028 Use 'now' and 'addInterval', time zone issue in datetime constructor with Calendar.
    ** 004 CA  20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy
    **                  signature.
    **     VVT 20210917 Javadoc fixed.
    **     ME  20210929 Fix return object on parse.
    **     CA  20220923 Variable definitions (including associated with parameters) must be done always outside of
    **                  the BlockManager API
    ** 005 CA  20231113 The 'execute' method must be annotated with LegacySignature Type.Execute, and also can be
    **                  dropped if is a no-op.
    */

    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */

    package com.goldencode.p2j.oo.net.http;

    import static com.goldencode.p2j.report.ReportConstants.CVT_LVL_FULL;
    import static com.goldencode.p2j.report.ReportConstants.RT_LVL_FULL;
    import static com.goldencode.p2j.util.BlockManager.externalProcedure;
    import static com.goldencode.p2j.util.BlockManager.function;
    import static com.goldencode.p2j.util.BlockManager.internalProcedure;
    import static com.goldencode.p2j.util.BlockManager.onBlockLevel;
    import static com.goldencode.p2j.util.BlockManager.returnNormal;

    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.List;
    import java.util.TimeZone;

    import org.apache.http.cookie.ClientCookie;
    import org.apache.http.cookie.CookieOrigin;
    import org.apache.http.cookie.CookieSpec;
    import org.apache.http.impl.cookie.BasicClientCookie;
    import org.apache.http.impl.cookie.RFC6265CookieSpecProvider;
    import org.apache.http.message.BasicHeader;
    import org.apache.http.protocol.BasicHttpContext;

    import com.goldencode.p2j.oo.core.Assert;
    import com.goldencode.p2j.oo.lang.BaseObject;
    import com.goldencode.p2j.oo.lang._BaseObject_;
    import com.goldencode.p2j.oo.net.Uri;
    import com.goldencode.p2j.util.Block;
    import com.goldencode.p2j.util.BlockManager.Action;
    import com.goldencode.p2j.util.BlockManager.Condition;
    import com.goldencode.p2j.util.Body;
    import com.goldencode.p2j.util.DateOps;
    import com.goldencode.p2j.util.InternalEntry.Type;
    import com.goldencode.p2j.util.LegacyParameter;
    import com.goldencode.p2j.util.LegacyResource;
    import com.goldencode.p2j.util.LegacyResourceSupport;
    import com.goldencode.p2j.util.LegacySignature;
    import com.goldencode.p2j.util.ObjectOps;
    import com.goldencode.p2j.util.TypeFactory;
    import com.goldencode.p2j.util.character;
    import com.goldencode.p2j.util.datetimetz;
    import com.goldencode.p2j.util.decimal;
    import com.goldencode.p2j.util.integer;
    import com.goldencode.p2j.util.logical;
    import com.goldencode.p2j.util.object;

    /**
     * Business logic (converted to Java from the 4GL source code
     * in OpenEdge/Net/HTTP/Cookie.cls).
     */
    @LegacyResource(resource = "OpenEdge.Net.HTTP.Cookie")
    @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
    public class Cookie
    extends BaseObject
    {
       private static CookieSpec cookieSpec;
       private static CookieOrigin cookieOrigin;

       private static final String HTTP_ONLY_ATTR = "httponly";

       private BasicClientCookie _cookie = null;

       /** 'domain' attribute value. */
       private character domain = new character();

       /** 'expires' attribute value. */
       private datetimetz expiresAt = new datetimetz();

       /** 'HttpOnly' attribute value. */
       private logical httpOnly = new logical();

       /** 'Max-Age' attribute value. */
       private integer maxAge = new integer();

       /** 'name' attribute value. */
       private character name = new character();

       /** 'path' attribute value. */
       private character path = new character();

       /** 'secure' attribute value. */
       private logical secure = new logical();

       /** 'value' attribute value. */
       private character value = new character();

       /** 'version' attribute value. */
       private decimal version = new decimal();

       /**
        * Execute method.
        */
       @LegacySignature(type = Type.EXECUTE)
       public void __net_http_Cookie_execute__()
       {
          onBlockLevel(Condition.ERROR, Action.THROW);
       }

       @LegacySignature(type = Type.CONSTRUCTOR)
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
       public static void __net_http_Cookie_constructor__static__()
       {
          externalProcedure(Cookie.class, new Block((Body) () ->
          {
             onBlockLevel(Condition.ERROR, Action.THROW);
          }));
       }

       /**
        * Get 'domain' attribute value.
        *
        * @return 'domain' attribute value.
        */
       @LegacySignature(returns = "CHARACTER", type = Type.GETTER, name = "Domain")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public character getDomain()
       {
          return domain;
       }

       /**
        * Get 'expires' attribute value.
        *
        * @return 'expires' attribute value.
        */
       @LegacySignature(returns = "DATETIMETZ", type = Type.GETTER, name = "ExpiresAt")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public datetimetz getExpiresAt()
       {
          return expiresAt;
       }

       /**
        * Get 'HttpOnly' attribute value.
        *
        * @return 'HttpOnly' attribute value.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.GETTER, name = "HttpOnly")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical getHttpOnly()
       {
          return httpOnly;
       }

       /**
        * Get 'Max-Age' attribute value.
        *
        * @return 'Max-Age' attribute value.
        */
       @LegacySignature(returns = "INTEGER", type = Type.GETTER, name = "MaxAge")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public integer getMaxAge()
       {
          return maxAge;
       }

       /**
        * Get 'name' attribute value.
        *
        * @return 'name' attribute value.
        */
       @LegacySignature(returns = "CHARACTER", type = Type.GETTER, name = "Name")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public character getName()
       {
          return name;
       }

       /**
        * Get 'path' attribute value.
        *
        * @return 'path' attribute value.
        */
       @LegacySignature(returns = "CHARACTER", type = Type.GETTER, name = "Path")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public character getPath()
       {
          return path;
       }

       /**
        * Get 'secure' attribute value.
        *
        * @return 'secure' attribute value.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.GETTER, name = "Secure")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical getSecure()
       {
          return secure;
       }

       /**
        * Get 'value' attribute value.
        *
        * @return 'value' attribute value.
        */
       @LegacySignature(returns = "CHARACTER", type = Type.GETTER, name = "Value")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public character getValue()
       {
          return value;
       }

       /**
        * Get 'version' attribute value.
        *
        * @return 'version' attribute value.
        */
       @LegacySignature(returns = "DECIMAL", type = Type.GETTER, name = "Version")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public decimal getVersion()
       {
          return version;
       }

       /**
        * Constructor.
        *
        * @param _p1 'name' attribute value.
        * @param _p2 'domain' attribute value.
        * @param _p3 'path' attribute value.
        * @param _p4 'value' attribute value.
        */
       @LegacySignature(type = Type.CONSTRUCTOR, parameters =
       {
          @LegacyParameter(name = "p1", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "p2", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "p3", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "p4", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __net_http_Cookie_constructor__(final character _p1, final character _p2,
             final character _p3, final character _p4)
       {
          __net_http_Cookie_constructor__(_p1, _p2, _p3, _p4, new integer(), new datetimetz(), new logical(), new logical(), new decimal());
       }

       /**
        * Constructor.
        *
        * @param _p1 'name' attribute value.
        * @param _p2 'domain' attribute value.
        * @param _p3 'path' attribute value.
        * @param _p4 'value' attribute value.
        * @param _p5 'Max-Age' attribute value.
        * @param _p6 'expires' attribute value.
        * @param _p7 'secure' attribute value.
        * @param _p8 'Http-Only' attribute value.
        * @param _p9 'Version' attribute value.
        */
       @LegacySignature(type = Type.CONSTRUCTOR, parameters =
       {
          @LegacyParameter(name = "p1", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "p2", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "p3", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "p4", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "p5", type = "INTEGER", mode = "INPUT"),
          @LegacyParameter(name = "p6", type = "DATETIMETZ", mode = "INPUT"),
          @LegacyParameter(name = "p7", type = "LOGICAL", mode = "INPUT"),
          @LegacyParameter(name = "p8", type = "LOGICAL", mode = "INPUT"),
          @LegacyParameter(name = "p9", type = "DECIMAL", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __net_http_Cookie_constructor__(final character _p1, final character _p2,
             final character _p3, final character _p4, final integer _p5, final datetimetz _p6,
             final logical _p7, final logical _p8, final decimal _p9)
       {
          character name = TypeFactory.initInput(_p1);
          character domain = TypeFactory.initInput(_p2);
          character path = TypeFactory.initInput(_p3);
          character value = TypeFactory.initInput(_p4);

          integer maxAge = TypeFactory.initInput(_p5);
          datetimetz expiresAt = TypeFactory.initInput(_p6);
          logical secureOnly = TypeFactory.initInput(_p7);
          logical httpOnly = TypeFactory.initInput(_p8);
          decimal version = TypeFactory.initInput(_p9);

          internalProcedure(this, "__net_http_Cookie_constructor__", new Block((Body) () ->
          {
             __lang_BaseObject_constructor__();

             Assert.notNullOrEmpty(name, new character("Cookie name"));
             Assert.notNull(domain, new character("Cookie domain"));
             Assert.notNull(path, new character("Cookie path"));

             this.name.assign(name);
             this.domain.assign(domain);
             this.path.assign(path);
             this.value.assign(value);

             this.secure.assign(secureOnly);
             this.httpOnly.assign(httpOnly);

             if (!maxAge.isUnknown())
             {
                Assert.isZeroOrPositive(maxAge, new character("Cookie max age"));
                this.maxAge.assign(maxAge);
                expiresAt.assign(DateOps.addInterval(datetimetz.now(), maxAge.longValue(), "seconds"));
             }

             if (!expiresAt.isUnknown())
             {
                this.expiresAt.assign(expiresAt);
             }

             if (!version.isUnknown())
             {
                Assert.isPositive(version, new character("Cookie Version"));
                this.version.assign(version);
             }

          }));
       }

       /**
        * Compare with other object, seems to be always false even when comparing with itself.
        *
        * @param _p1 other object.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Equals", parameters =
       {
          @LegacyParameter(name = "p1", type = "OBJECT",
                qualified = "progress.lang.object", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       @Override
       public logical legacyEquals(final object<? extends _BaseObject_> _p1)
       {
          return new logical(false);
       }

       /**
        * Creates a Cookie object from the string representation of a cookie.
        *
        * @param p1 a string representation of a cookie.
        *
        * @return Cookie instance
        */
       @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "Parse", qualified = "openedge.net.http.cookie", parameters = {
                @LegacyParameter(name = "p1", type = "CHARACTER", mode = "INPUT") })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
       public static object<? extends Cookie> parse(final character p1)
       {
          object<? extends Cookie> returnedCookie = TypeFactory.object(Cookie.class);
          character name = TypeFactory.character();
          character domain = TypeFactory.character();
          character path = new character();
          character value = new character();
          integer maxAge = new integer();
          decimal version = new decimal();
          datetimetz expires = new datetimetz();
          logical httpOnly = TypeFactory.logical();
          logical secure = TypeFactory.logical();

          return function(Cookie.class, "Parse", object.class, new Block((Body) () -> {
             Assert.notNullOrEmpty(p1, new character("Cookie"));

             if (cookieSpec == null)
             {
                cookieSpec = new RFC6265CookieSpecProvider().create(new BasicHttpContext());
                cookieOrigin = new CookieOrigin("__host__", 80, "/", false);
             }

             String cookieHeader = p1.getValue();

             // 4GL accepts only the name, oddly enough the value is the same as name in this case
             // This definitively not valid so it can probably just be removed, kept only for 100% compatibility
             if (!cookieHeader.contains("="))
             {
                name.assign(cookieHeader);
                value.assign(cookieHeader);
                path.assign("/");
             }
             else
             {
                try
                {
                   List<org.apache.http.cookie.Cookie> cookies = cookieSpec
                            .parse(new BasicHeader("SET-COOKIE", cookieHeader), cookieOrigin);

                   if (cookies.size() > 0)
                   {
                      org.apache.http.cookie.Cookie cookie = cookies.get(0);

                      if (!isRestrictedName(cookie.getName()))
                      {
                         name.assign(cookie.getName());

                         if (!cookie.getDomain().equals(cookieOrigin.getHost()))
                            domain.assign(cookie.getDomain());

                         path.assign(cookie.getPath());
                         value.assign(cookie.getValue());

                         if (cookie.getVersion() > 0)
                            version.assign(cookie.getVersion());

                         if (cookie.getExpiryDate() != null)
                            expires.assign(new datetimetz(cookie.getExpiryDate()));

                         secure.assign(cookie.isSecure());

                         if (cookie instanceof ClientCookie)
                         {
                            ClientCookie clientCookie = (ClientCookie) cookie;
                            if (clientCookie.containsAttribute(ClientCookie.MAX_AGE_ATTR))
                               maxAge.assign(clientCookie.getAttribute(ClientCookie.MAX_AGE_ATTR));

                            // version is obsolete in RFC 6265, still this is parsed (albeit not validated) in 4GL
                            if (clientCookie.containsAttribute(ClientCookie.VERSION_ATTR))
                               version.assign(clientCookie.getAttribute(ClientCookie.VERSION_ATTR));

                            httpOnly.assign(clientCookie.containsAttribute(HTTP_ONLY_ATTR));
                         }
                      }
                   }
                }
                catch (Exception e)
                {
                   // if anything goes wrong the name remains empty and error is being thrown
                }

             }

            returnedCookie.assign(ObjectOps.newInstance(Cookie.class,
                      "IIIIIIIII", name, domain, path, value, maxAge, expires, secure, httpOnly,
                      version));

             returnNormal(returnedCookie);

          }));
       }

       /**
        * Return a stringified representation of the Cookie.
        *
        * @return a stringified representation of the Cookie.
        */
       @LegacySignature(returns = "CHARACTER", type = Type.METHOD, name = "ToString")
       @Override
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public character toLegacyString()
       {
          StringBuilder sb = new StringBuilder(name.getValue());

          sb.append("=").append(Uri.encodeCookie(value.getValue(), null));

          if (!domain.getValue().isEmpty())
             sb.append("; Domain=").append(domain.getValue());

          if (!path.getValue().isEmpty())
             sb.append("; Path=").append(Uri.encodeCookie(path.getValue(), null));

          if (!expiresAt.isUnknown()) {
             SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
             sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

             sb.append("; Expires=").append(sdf.format(expiresAt.calendarValue().getTime()));
          }

          if (!maxAge.isUnknown())
             sb.append("; Max-Age=").append(String.valueOf(maxAge.intValue()));

          if (secure.booleanValue())
             sb.append("; Secure");

          if (httpOnly.booleanValue())
             sb.append("; HttpOnly");

          if (!version.isUnknown())
             sb.append("; Version=").append(String.valueOf(version.doubleValue()));

          return new character(sb.toString());
       }

       public ClientCookie getCookie () {
          if (_cookie == null) {
             _cookie = new BasicClientCookie(name.getValue(), value.getValue());

             _cookie.setDomain(domain.getValue());
             _cookie.setPath(path.getValue());

             if (!maxAge.isUnknown())
                _cookie.setAttribute(ClientCookie.MAX_AGE_ATTR, String.valueOf(maxAge.intValue()));

             if (!expiresAt.isUnknown())
                _cookie.setExpiryDate(expiresAt.dateValue());

             if (secure.booleanValue())
                _cookie.setSecure(secure.booleanValue());

             if (httpOnly.booleanValue())
                _cookie.setAttribute(HTTP_ONLY_ATTR, "");

             // this is obsolete and should only be 0, 1 anyway not any decimal value
             if (!version.isUnknown())
                _cookie.setAttribute(ClientCookie.VERSION_ATTR, String.valueOf(version.doubleValue()));
          }

          return _cookie;
       }

       // Although not restricted by RFC the 4GL does not allow cookie names that match valid attributes
       private static boolean isRestrictedName(String name)
       {
          return ClientCookie.DOMAIN_ATTR.equalsIgnoreCase(name)
                   || ClientCookie.PATH_ATTR.equalsIgnoreCase(name)
                   || ClientCookie.EXPIRES_ATTR.equalsIgnoreCase(name)
                   || ClientCookie.VERSION_ATTR.equalsIgnoreCase(name)
                   || ClientCookie.MAX_AGE_ATTR.equalsIgnoreCase(name)
                   || ClientCookie.SECURE_ATTR.equalsIgnoreCase(name)
                   || HTTP_ONLY_ATTR.equalsIgnoreCase(name);
       }

    }