# Broker.java

    /*
    ** Module   : Broker.java
    ** Abstract : server side broker implementation.
    **
    ** Copyright (c) 2014-2023, Golden Code Development Corporation.

    **
    ** -#- -I- --Date-- ---------------------------------Description----------------------------------
    ** 001 MAG 20140715 Implements remote launcher (broker).
    ** 002 GES 20150423 Fixed incorrect logging text.
    ** 003 SBI 20171023 Changed to release resources allocated for registered broker clients.
    ** 004 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.main;

    import java.util.*;
    import java.util.concurrent.*;
    import java.util.logging.*;

    import com.goldencode.p2j.net.Session;
    import com.goldencode.p2j.util.logging.*;

    /**
     * Broker implementation. Holds brokers attributes read from directory as well as
     * parameters for remote broker instances linked to application server broker.
     */
    public class Broker
    {
       /** Logger. */
       private static final CentralLogger LOG = CentralLogger.get(Broker.class.getName());

       /** List of accounts for this broker */
       private List<String> accounts;

       /** Remote broker instances registered for this broker */
       private Map<String, BrokerParameters> instances = new ConcurrentHashMap<>();

       /**
        * Constructor.
        *
        * @param   accounts
        *          Accounts list or null if no accounts are defined for this broker.
        */
       public Broker(List<String> accounts)
       {
          this.accounts = accounts;
       }

       /**
        * Add an account for this broker.
        *
        * @param   account
        *          P2J or OS account.
        */
       public void addAccount(String account)
       {
          accounts.add(account);
       }

       /**
        * Register a new remote broker instance.
        *
        * @param   params
        *          Remote broker parameters.
        */
       public void addBroker(BrokerParameters params)
       {
          params.setUuid(UUID.randomUUID().toString());
          instances.put(params.getUuid(), params);
       }

       /**
        * Close brokers session on server shutdown.
        */
       public void shutdown()
       {
          synchronized (instances)
          {
             for (Map.Entry<String, BrokerParameters> entry : instances.entrySet())
             {
                BrokerParameters params = entry.getValue();
                if (params != null && params.getSession() != null)
                {
                   params.getSession().terminate();
                }
             }
          }
       }

       /**
        * Remove a broker instance based on session.
        *
        * @param    session
        *           Broker session.
        *
        * @return   <code>true</code> on successful remove.
        */
       public boolean removeBroker(Session session)
       {
          synchronized (instances)
          {
             for (Map.Entry<String, BrokerParameters> entry : instances.entrySet())
             {
                BrokerParameters params = entry.getValue();

                if (session != null && session.equals(params.getSession()))
                {
                   params.close();
                   instances.remove(entry.getKey());

                   BrokerManager.deregisterBroker(params);

                   LOG.logp(Level.INFO,
                            "Broker.removeBroker()",
                            "",
                            CentralLogger.generate("Broker user=%s uuid=%s removed.",
                                                   params.getUserId(),
                                                   params.getUuid()));
                   return true;
                }
             }

             return false;
          }
       }

       /**
        * Check if a specific account is define for this broker.
        *
        * @param   account
        *          P2J or OS account.
        *
        * @return  <code>true</code> if account is defined.
        */
       public boolean hasAccount(String account)
       {
          return accounts != null && accounts.contains(account);
       }

       /**
        * Check if broker has no accounts.
        *
        * @return  <code>true</code> if no accounts are defined.
        */
       public boolean noAccounts()
       {
          return accounts == null || accounts.isEmpty();
       }

       /**
        * Get broker instances.
        *
        * @return  A map containing the registered brokers.
        */
       public Map<String, BrokerParameters> getBrokers()
       {
          return instances;
       }

       /**
        * Find a broker based on UUID
        *
        * @param   uuid
        *          Broker UUID.
        *
        * @return  <code>true</code> when broker is found.
        */
       public boolean findBroker(String uuid)
       {
          return instances.containsKey(uuid);
       }

       /**
        * Get a broker instance based on UUID
        *
        * @param   uuid
        *          Broker UUID.
        *
        * @return  A broker instance.
        */
       public BrokerParameters getBroker(String uuid)
       {
          return instances.get(uuid);
       }
    }