# AdminCallback.java

    /*
    ** Module   : AdminCallback.java
    ** Abstract : GWT AsyncCallback with extra features.
    **
    ** Copyright (c) 2017, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- --------------------------------Description-----------------------------------
    ** 001 HC  20170612 Initial version.
    */
    /*
    ** 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.admin.client;

    import com.goldencode.p2j.admin.client.application.*;
    import com.goldencode.p2j.admin.shared.*;
    import com.google.gwt.core.client.*;
    import com.google.gwt.user.client.*;
    import com.google.gwt.user.client.rpc.*;

    import javax.inject.*;
    import java.util.*;
    import java.util.function.*;
    import java.util.logging.*;

    /**
     * This class implements the standard {@link AsyncCallback} and provides some extended features
     * on top - namely Admin specific error handling.
     */
    public abstract class AdminCallback<T>
    implements AsyncCallback<T>
    {
       /** Logger */
       private static final Logger log = Logger.getLogger(AdminCallback.class.getSimpleName());

       /** Reference to the admin service */
       @Inject
       private AdminServiceAsync adm;

       /** Reference to the alarm service */
       @Inject
       private Alarm alarm;

       /** Callback result */
       private T result;

       /** An exception thrown during the call */
       private Throwable exception;

       /** Server messages fetched from the backend on failure */
       private List<String> serverMessages;

       /**
        * A default ctor to satisfy GWT.
        */
       public AdminCallback()
       {
       }

       /**
        * Ctor.
        *
        * @param   adm
        *          Reference to the admin service.
        * @param   alarm
        *          Reference to the alarm service.
        */
       public AdminCallback(AdminServiceAsync adm, Alarm alarm)
       {
          this.adm = adm;
          this.alarm = alarm;
       }

       /**
        * Returns <code>true</code> when the call has finished and the result value is a success.
        * "Is success" in this implementation means Boolean result value and result == true, but
        * this can be overridden by the extending classes.
        *
        * @return  <code>true</code> when the call has finished and the result value is a success,
        *          <code>false</code> otherwise.
        */
       public boolean isSuccess()
       {
          return result != null && (!(result instanceof Boolean) || (Boolean) result);
       }

       /**
        * Returns the callback result.
        *
        * @return  callback result
        */
       public T getResult()
       {
          return result;
       }

       /**
        * Returns messages fetched from the admin service on failure.
        *
        * @return  list of messages or an empty list if no messages
        */
       public List<String> getServerMessages()
       {
          return serverMessages == null ? Collections.emptyList() : serverMessages;
       }

       /**
        * Returns the exception thrown during the backend call.
        *
        * @return  an exception instance or <code>null</code> if no exception
        */
       public Throwable getException()
       {
          return exception;
       }

       /**
        * Called when an asynchronous call fails to complete normally.
        * {@link IncompatibleRemoteServiceException}s, {@link InvocationException}s,
        * or checked exceptions thrown by the service method are examples of the type
        * of failures that can be passed to this method.
        * <p>
        * If <code>caught</code> is an instance of an
        * {@link IncompatibleRemoteServiceException} the application should try to
        * get into a state where a browser refresh can be safely done.
        * </p>
        *
        * @param   caught
        *          failure encountered while executing a remote procedure call
        */
       @Override
       public void onFailure(Throwable caught)
       {
          if (caught instanceof StatusCodeException &&
              ((StatusCodeException) caught).getStatusCode() == 401)
          {
             Window.Location.replace(GWT.getHostPageBaseURL());
             return;
          }

          exception = caught;

          String msg = "Request error: " + caught.getMessage();
          log.log(Level.SEVERE, "Request error:", caught);
          if (alarm != null)
          {
             alarm.ring(msg, () -> onDone(null));
          }
          else
          {
             onDone(null);
          }
       }

       /**
        * Called when an asynchronous call completes successfully.
        *
        * @param   result
        *          the return value of the remote produced call
        */
       @Override
       public void onSuccess(T result)
       {
          this.result = result;
          if (adm != null && !isSuccess())
          {
             adm.getMessages(false, new AsyncCallback<String[][]>()
             {
                @Override
                public void onFailure(Throwable caught)
                {
                   log.log(Level.SEVERE, "Error retrieving messages from server", caught);
                   onDone(null);
                }

                @Override
                public void onSuccess(String[][] result)
                {
                   onDone(result);
                }

                private void onDone(String[][] messages)
                {
                   if (messages != null)
                   {
                      serverMessages = new ArrayList<>();
                      for (String[] msgs : messages)
                      {
                         serverMessages.addAll(Arrays.asList(msgs));
                      }

                      if (alarm != null && !serverMessages.isEmpty())
                      {
                         alarm.ring(serverMessages, () -> AdminCallback.this.onDone(result));
                         return;
                      }
                   }

                   AdminCallback.this.onDone(result);
                }
             });
          }
          else
          {
             onDone(result);
          }
       }

       /**
        * Called when the service call has finished, regardless whether with success or failure.
        *
        * @param   result
        *          The call result, <code>null</code> when failure.
        */
       public abstract void onDone(T result);
    }