AuthenticationRequestFilter.java

/*
** Module   : AuthenticationRequestFilter.java
** Abstract : Implementation of the builtin class.
**
** Copyright (c) 2019-2023, Golden Code Development Corporation.
**
** -#- -I- --Date-- -------------------------------Description--------------------------------
** 001 IAS  20190923 First version.
** 002 ME   20200508 Implementation as of OE 11.7.4.
**          20201109 Throw 3135 error if listeners list not valid (initialize).
** 003 CA   20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy
**                   signature.
**     CA  20210609 Updated INPUT/INPUT-OUTPUT parameters to the new approach, where they are explicitly 
**                  initialized at the method's execution, and not at the caller's arguments.
**     VVT 20210917 Javadoc fixed, missing @Override annotations added.
** 004 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.filter.auth;

import com.goldencode.p2j.oo.core.*;
import com.goldencode.p2j.oo.lang.*;
import com.goldencode.p2j.oo.net.http.*;
import com.goldencode.p2j.oo.net.http.filter.*;
import com.goldencode.p2j.util.*;
import com.goldencode.p2j.util.BlockManager.Action;
import com.goldencode.p2j.util.BlockManager.Condition;
import com.goldencode.p2j.util.InternalEntry.*;

import static com.goldencode.p2j.report.ReportConstants.*;
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.util.Stack;

/**
 * 
 * Filter for handling authentication credential requests.
 *
 */
@LegacyResource(resource = "OpenEdge.Net.HTTP.Filter.Auth.AuthenticationRequestFilter")
@LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
public abstract class AuthenticationRequestFilter extends BaseObject
         implements IHttpMessageWriter, IFilterEvents, ISupportInitialize
{
   @LegacySignature(type = Type.EVENT, name = "HttpCredentialRequest", parameters = {
            @LegacyParameter(name = "poSender", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT"),
            @LegacyParameter(name = "poEventArgs", type = "OBJECT", qualified = "openedge.net.http.authenticationrequesteventargs", mode = "INPUT") })
   private ClassEvent httpCredentialRequest = new ClassEvent(AuthenticationRequestFilter.this,
            "HttpCredentialRequest", "httpCredentialRequest");

   @LegacySignature(type = Type.PROPERTY, name = "FilterEventListenerType")
   private object<? extends LegacyClass> filterEventListenerType = TypeFactory
            .object(LegacyClass.class);

   @LegacySignature(type = Type.PROPERTY, name = "Message")
   private object<? extends IhttpRequest> message = TypeFactory.object(IhttpRequest.class);

   @LegacySignature(type = Type.PROPERTY, name = "AuthenticatedRequest")
   private object<? extends IAuthenticatedRequest> authenticatedRequest = TypeFactory
            .object(IAuthenticatedRequest.class);

   private Stack<object> moListeners;

   @LegacySignature(type = Type.PUBLISH, name = "HttpCredentialRequest", parameters = {
            @LegacyParameter(name = "poSender", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT"),
            @LegacyParameter(name = "poEventArgs", type = "OBJECT", qualified = "openedge.net.http.authenticationrequesteventargs", mode = "INPUT") })
   private void publish_httpCredentialRequest(object poSender, object poEventArgs)
   {
      httpCredentialRequest.publish(poSender, poEventArgs);
   }

   @LegacySignature(type = Type.SUBSCRIBE, name = "HttpCredentialRequest", parameters = {
            @LegacyParameter(name = "p1", type = "handle", mode = "INPUT"),
            @LegacyParameter(name = "p2", type = "character", mode = "INPUT") })
   public void subscribe_httpCredentialRequest(handle h, character procName)
   {
      httpCredentialRequest.subscribe(h, procName);
   }

   @LegacySignature(type = Type.SUBSCRIBE, name = "HttpCredentialRequest", parameters = {
            @LegacyParameter(name = "p1", type = "object", mode = "INPUT", qualified = "progress.lang.object"),
            @LegacyParameter(name = "p2", type = "character", mode = "INPUT") })
   public void subscribe_httpCredentialRequest(
            object<? extends com.goldencode.p2j.oo.lang._BaseObject_> ref, character methName)
   {
      httpCredentialRequest.subscribe(ref, methName);
   }

   @LegacySignature(type = Type.UNSUBSCRIBE, name = "HttpCredentialRequest", parameters = {
            @LegacyParameter(name = "p1", type = "handle", mode = "INPUT"),
            @LegacyParameter(name = "p2", type = "character", mode = "INPUT") })
   public void unsubscribe_httpCredentialRequest(handle h, character procName)
   {
      httpCredentialRequest.unsubscribe(h, procName);
   }

   @LegacySignature(type = Type.UNSUBSCRIBE, name = "HttpCredentialRequest", parameters = {
            @LegacyParameter(name = "p1", type = "object", mode = "INPUT", qualified = "progress.lang.object"),
            @LegacyParameter(name = "p2", type = "character", mode = "INPUT") })
   public void unsubscribe_httpCredentialRequest(
            object<? extends com.goldencode.p2j.oo.lang._BaseObject_> ref, character methName)
   {
      httpCredentialRequest.unsubscribe(ref, methName);
   }

   @LegacySignature(type = Type.EXECUTE)
   public void __net_http_filter_auth_AuthenticationRequestFilter_execute__()
   {
      onBlockLevel(Condition.ERROR, Action.THROW);
   }

   @LegacySignature(type = Type.CONSTRUCTOR, parameters = {
            @LegacyParameter(name = "poRequest", type = "OBJECT", qualified = "openedge.net.http.iauthenticatedrequest", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void __net_http_filter_auth_AuthenticationRequestFilter_constructor__(
            final object<? extends IAuthenticatedRequest> _poRequest)
   {
      object<? extends IAuthenticatedRequest> poRequest = TypeFactory.initInput(_poRequest);

      internalProcedure(AuthenticationRequestFilter.class, this,
               "__net_http_filter_auth_AuthenticationRequestFilter_constructor__",
               new Block((Body) () ->
               {
                  __lang_BaseObject_constructor__();

                  Assert.notNull(_poRequest, new character("Request"));

                  authenticatedRequest.assign(poRequest);

                  if (poRequest.ref() instanceof IAdaptable)
                  {
                     message.assign(((IAdaptable) poRequest.ref()).getAdapter(
                              ObjectOps.getLegacyClass(IhttpRequest.class)));
                  }
                  else if (poRequest.ref() instanceof IhttpRequest)
                  {
                     message.assign(poRequest);
                  }
               }));
   }

   @LegacySignature(type = Type.DESTRUCTOR)
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void __net_http_filter_auth_AuthenticationRequestFilter_destructor__()
   {
      internalProcedure(AuthenticationRequestFilter.class, this,
               "__net_http_filter_auth_AuthenticationRequestFilter_destructor__",
               new Block((Body) () ->
               {
                  destroy();
               }));
   }

   /**
    *  Returns the type(class or interface) that an a potential listener must implement or 
    *  inherit in order to handle events from this filter
    *  
    *  @return type of the listener
    */
   @LegacySignature(returns = "OBJECT", qualified = "Progress.Lang.Class", type = Type.GETTER, name = "FilterEventListenerType")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public object<? extends LegacyClass> getFilterEventListenerType()
   {
      return function(AuthenticationRequestFilter.class, this, "FilterEventListenerType",
               object.class, new Block((Body) () ->
               {
                  returnNormal(ObjectOps.getLegacyClass(IauthFilterEventHandler.class));
               }));
   }

   @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.IAuthenticatedRequest", type = Type.GETTER, name = "AuthenticatedRequest")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   protected object<? extends IAuthenticatedRequest> getAuthenticatedRequest()
   {
      return function(AuthenticationRequestFilter.class, this, "AuthenticatedRequest",
               object.class, new Block((Body) () ->
               {
                  returnNormal(authenticatedRequest);
               }));
   }

   @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "GetCredentials", qualified = "openedge.net.http.credentials", parameters = {
            @LegacyParameter(name = "pcRealm", type = "CHARACTER", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   protected object<? extends com.goldencode.p2j.oo.net.http.Credentials> getCredentials(
            final character _pcRealm)
   {
      character pcRealm = TypeFactory.initInput(_pcRealm);
      object<? extends AuthenticationRequestEventArgs> oAuthReqArgs = TypeFactory.object(AuthenticationRequestEventArgs.class);
      
      return function(AuthenticationRequestFilter.class, this, "GetCredentials", object.class,
               new Block((Body) () ->
               {
                  Assert.notNull(pcRealm, new character("Realm"));

                  if (authenticatedRequest.ref().getCredentials()._isValid())
                     returnNormal(authenticatedRequest.ref().getCredentials());
                  
                  oAuthReqArgs.assign(ObjectOps.newInstance(AuthenticationRequestEventArgs.class,
                           "II", message, pcRealm));

                  onHttpCredentialRequest(oAuthReqArgs);

                  if (oAuthReqArgs.ref().getCancel().booleanValue())
                     returnNormal(new object());

                  returnNormal(oAuthReqArgs.ref().getCredentials());
               }));
   }

   /**
    * Subscribes a listener to events from the implementing filter. 
    * 
    * @param _poListener The prospective listener
    */
   @LegacySignature(type = Type.METHOD, name = "SubscribeListener", parameters = {
            @LegacyParameter(name = "poListener", type = "OBJECT", qualified = "Progress.Lang.Object", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public void subscribeListener(object<? extends _BaseObject_> _poListener)
   {
      object<? extends _BaseObject_> poListener = TypeFactory.initInput(_poListener);

      internalProcedure(AuthenticationRequestFilter.class, this, "SubscribeListener",
               new Block((Body) () ->
               {
                  Assert.isType(poListener, getFilterEventListenerType());
                  moListeners.push(poListener);
                  httpCredentialRequest.subscribe(poListener,
                           new character("AuthFilter_HttpCredentialRequestHandler"));
               }));
   }

   /**
    * Unsubsribes listeners from a writer, so that they can be GC'ed if needed. 
    * 
    * @param _poListener The listener to unsubscribe 
    */
   @LegacySignature(type = Type.METHOD, name = "UnsubscribeListener", parameters = {
            @LegacyParameter(name = "poListener", type = "OBJECT", qualified = "Progress.Lang.Object", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public void unsubscribeListener(object<? extends _BaseObject_> _poListener)
   {
      object<? extends _BaseObject_> poListener = TypeFactory.initInput(_poListener);

      internalProcedure(AuthenticationRequestFilter.class, this, "UnubscribeListener",
               new Block((Body) () ->
               {
                  Assert.isType(poListener, getFilterEventListenerType());
                  moListeners.remove(poListener);
                  httpCredentialRequest.unsubscribe(poListener,
                           new character("AuthFilter_HttpCredentialRequestHandler"));
               }));
   }

   /**
    * Get message.
    * 
    * @return message.
    */
   @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.IHttpMessage", type = Type.GETTER, name = "Message")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public object<? extends IhttpMessage> getMessage()
   {
      return function(AuthenticationRequestFilter.class, this, "Message", object.class,
               new Block((Body) () ->
               {
                  returnNormal(message);
               }));
   }

   /**
    * Build the actual authentication. To be implemented by concrete classes. 
    */
   @LegacySignature(type = Type.METHOD, name = "AddAuthentication")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   protected abstract void addAuthetication();

   /**
    * Destroy
    */
   @Override
   @LegacySignature(type = Type.METHOD, name = "Destroy")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void destroy()
   {
      internalProcedure(AuthenticationRequestFilter.class, this, "Destroy", new Block((Body) () ->
      {
         if (moListeners == null)
         {
            ErrorManager.recordOrThrowError(3135, "Invalid handle. Not initialized or points to a deleted object");
         }
         
         while (!moListeners.empty())
         {
            unsubscribeListener(moListeners.pop());
         }
      }));
   }

   /**
    * Initialize
    */
   @LegacySignature(type = Type.METHOD, name = "Initialize")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public void initialize()
   {
      internalProcedure(AuthenticationRequestFilter.class, this, "Initialize", new Block((Body) () ->
      {
         moListeners = new Stack<object>();
      }));
   }

   @LegacySignature(type = Type.METHOD, name = "OnHttpCredentialRequest", parameters = {
            @LegacyParameter(name = "poAuthRequestArgs", type = "OBJECT", qualified = "openedge.net.http.authenticationrequesteventargs", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   protected void onHttpCredentialRequest(
            final object<? extends AuthenticationRequestEventArgs> _poAuthRequestArgs)
   {
      object<? extends AuthenticationRequestEventArgs> poAuthRequestArgs = TypeFactory
               .initInput(_poAuthRequestArgs);

      internalProcedure(AuthenticationRequestFilter.class, this, "OnHttpCredentialRequest",
               new Block((Body) () ->
               {
                  Assert.notNull(poAuthRequestArgs,
                           new character("Authentication Request Event Args"));
                  httpCredentialRequest.publish(new object(this), poAuthRequestArgs);
               }));
   }

   /** 
    * Opens the writer for output. Open/Close allows us to write the same message multiple
    * times without requiring a new writer each time. 
    */
   @LegacySignature(type = Type.METHOD, name = "Open")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public void open()
   {
      internalProcedure(AuthenticationRequestFilter.class, this, "Open", new Block());
   }

   /** 
   * Write data to/from the message
   *   
   * @param _poData Data to write 
   */
   @LegacySignature(type = Type.METHOD, name = "Write", parameters = {
            @LegacyParameter(name = "poData", type = "OBJECT", qualified = "Progress.Lang.Object", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public void write(object<? extends _BaseObject_> _poData)
   {
      object<? extends com.goldencode.p2j.oo.lang._BaseObject_> poData = TypeFactory.initInput(_poData);
      
      internalProcedure(AuthenticationRequestFilter.class, this, "Write", new Block());
   }

   /** 
   * Write data to/from the message
   *   
   * @param _pcData Data to write 
   */
   @LegacySignature(type = Type.METHOD, name = "Write", parameters = {
            @LegacyParameter(name = "pcData", type = "LONGCHAR", mode = "INPUT-OUTPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public void write(longchar _pcData)
   {
      longchar pcData = TypeFactory.initInputOutput(_pcData);
      internalProcedure(AuthenticationRequestFilter.class, this, "Write", new Block());
   }

   /** 
   * Write data to/from the message
   *   
   * @param _phData Data to write 
   */
   @Override
   @LegacySignature(type = Type.METHOD, name = "Write", parameters = {
            @LegacyParameter(name = "phData", type = "HANDLE", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void write(handle _phData)
   {
      handle phData = TypeFactory.initInput(_phData);
      
      internalProcedure(AuthenticationRequestFilter.class, this, "Write", new Block());
   }

   /** 
   * Write data to/from the message
   *   
   * @param _pcData Data to write 
   */
   @Override
   @LegacySignature(type = Type.METHOD, name = "Write", parameters = {
            @LegacyParameter(name = "pcData", type = "CHARACTER", mode = "INPUT-OUTPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void write(character _pcData)
   {
      character pcData = TypeFactory.initInputOutput(_pcData);
      internalProcedure(AuthenticationRequestFilter.class, this, "Write", new Block());
   }

   /** 
   * Write data to/from the message
   *   
   * @param _pmData Data to write 
   */
   @LegacySignature(type = Type.METHOD, name = "Write", parameters = {
            @LegacyParameter(name = "pmData", type = "MEMPTR", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public void write(memptr _pmData)
   {
      memptr pmData = TypeFactory.initInput(_pmData);
      
      internalProcedure(AuthenticationRequestFilter.class, this, "Write", new Block());
   }

   /**  
    * Flushes data to the output location. What data is flushed depends on the implementation 
    */
   @Override
   @LegacySignature(type = Type.METHOD, name = "Flush")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void flush()
   {
      internalProcedure(AuthenticationRequestFilter.class, this, "Flush", new Block((Body) () ->
      {
         addAuthetication();
      }));
   }

   /**  
    * Closes the output. See Open() 
    */
   @Override
   @LegacySignature(type = Type.METHOD, name = "Close")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void close()
   {
      internalProcedure(AuthenticationRequestFilter.class, this, "Close", new Block());
   }
}