# Echo.java

    /*
    ** Module   : Echo.java
    ** Abstract : provides a simple mechanism to test a session's connectivity
    **
    ** Copyright (c) 2006-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- -T- --JPRM-- ----------------Description-----------------
    ** 001 GES 20060725 NEW   @28195 First version which provides a simple
    **                               mechanism to test a session's connectivity.
    ** 002 ECF 20071106 CHG   @35880 Replaced Queue with Session.
    ** 003 GBB 20230512 Logging methods replaced by CentralLogger/ConversionStatus.
    */
    /*
    ** 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.net;

    import java.io.*;
    import java.util.logging.*;
    import com.goldencode.p2j.util.*;
    import com.goldencode.p2j.util.logging.*;

    /**
     * Helper class which provides a simple mechanism to test a session's
     * connectivity.
     *
     * @author   GES
     */
    public class Echo
    {
       /** Logger (safe as a JVM-wide value rather than as context-local). */
       private static final CentralLogger LOG =
          CentralLogger.get(Echo.class.getName());

       /** Tracing flag (enabled at logging level <code>FINEST</code>). */
       private static final boolean tracing = LOG.isLoggable(Level.FINEST);

       /**
        * Test a do-nothing round trip to the other side of this session and
        * back with the given data as a payload.  If logging is enabled at the
        * <code>FINEST</code> level, then details of the payload and the
        * elapsed time will be logged.
        * <p>
        * The protocol's built-in support for <code>ECHO</code> and
        * <code>ECHO_REPLY</code> messages is used to implement this feature.
        * No special server registration is needed on the other side as long
        * as there is a valid session open.
        *
        * @param    payload
        *           The data to send (and which will be sent back unchanged).
        *           It may be <code>null</code> (which represents an empty
        *           payload).
        *
        * @return   Round trip time in milliseconds or -1 if a failure occurred.
        */
       public static long ping(Serializable payload)
       {
          return ping(payload, 0);
       }

       /**
        * Test a do-nothing round trip to the other side of this session and
        * back with the given data as a payload.  If logging is enabled at the
        * <code>FINEST</code> level, then details of the payload and the
        * elapsed time will be logged.
        * <p>
        * The protocol's built-in support for <code>ECHO</code> and
        * <code>ECHO_REPLY</code> messages is used to implement this feature.
        * No special server registration is needed on the other side as long
        * as there is a valid session open.
        *
        * @param    payload
        *           The data to send (and which will be sent back unchanged).
        *           It may be <code>null</code> (which represents an empty
        *           payload).
        * @param    timeout
        *           Maximum number of milliseconds to wait for a response. Use
        *           0 for an indefinite wait.
        *
        * @return   Round trip time in milliseconds or -1 if a failure occurred.
        */
       public static long ping(Serializable payload, int timeout)
       {
          Session session = SessionManager.get().getSession();

          long result = -1;

          try
          {
             Invoker  inv  = new Invoker(session, timeout);
             Object[] args = new Object[] { payload };

             if (tracing)
             {
                TraceHelper.trace(inv, args, LOG, "Echo");
             }
             else
             {
                inv.invoke(args);
             }

             result = inv.getElapsed();
          }

          catch (Throwable t)
          {
             // silently ignore failures and return false below
             LOG.logp(Level.FINE, Echo.class.getSimpleName(), "ping", "", t);
          }

          return result;
       }

       /**
        * Helper class to delegate execution of the <code>transactEcho</code>
        * method.
        */
       private static class Invoker
       implements Invocable
       {
          /** Represents our network session. */
          private Session session = null;

          /** Timeout in milliseconds. */
          private int timeout = 0;

          /** Elapsed time in milliseconds. */
          private long elapsed = -1;

          /**
           * Construct an instance that can make an invocation of an echo
           * transaction using the given queue.
           *
           * @param    session
           *           The connection to test.
           * @param    timeout
           *           The maximum number of milliseconds to wait for a reply.
           */
          public Invoker(Session session, int timeout)
          {
             this.session = session;
             this.timeout = timeout;
          }

          /**
           * Return a text description of the method being invoked.
           *
           * @return   The description.
           */
          public String describe()
          {
             return "ping";
          }

          /**
           * Returns the number of milliseconds of elapsed time during ping
           * invocation.
           *
           * @return   The number of elapsed milliseconds or -1 if there was no
           *           invocation or any error during invocation.
           */
          public long getElapsed()
          {
             return elapsed;
          }

          /**
           * Execute or "run" the object's functionality.
           *
           * @param    args
           *           The method arguments or <code>null</code> for no arguments.
           *
           * @return   The called method's return value or <code>null</code> if
           *           there is no return value.  Note that this design does not
           *           allow the caller to determine the difference between a
           *           <code>void</code> return and a return of a genuine
           *           <code>null</code>.
           *
           * @throws   Throwable
           *           If the called method generates any exception or error.
           */
          public Object invoke(Object[] args)
          throws Throwable
          {
             Serializable payload = args == null ? null : (Serializable) args[0];

             long millis = -1;
             Object result = null;

             try
             {
                millis = System.currentTimeMillis();
                result = session.echo(payload, timeout, null);
             }

             finally
             {
                if (millis != -1)
                   elapsed = System.currentTimeMillis() - millis;
             }

             return result;
          }
       }
    }