Registry.java [src/csip] Revision: default  Date:
/*
 * $Id$
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API and application suite.
 *
 * 2012-2022, Olaf David and others, OMSLab, Colorado State University.
 *
 * OMSLab licenses this file to you under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
package csip;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.Path;

/**
 * Services classes registry.
 *
 * @author od
 */
class Registry {

  List<Class<?>> s;


  synchronized public void register(Set<Class<?>> service) {
    if (s != null)  // one time registration only
      return;

    s = new ArrayList<>();
    List<Class<?>> sortedServices = new ArrayList<>(service);
    Collections.sort(sortedServices, (Class<?> c1, Class<?> o2)
        -> c1.getCanonicalName().compareTo(o2.getCanonicalName()));

    AtomicInteger no = new AtomicInteger();
    sortedServices.forEach((Class<?> c) -> {
      if (Utils.isCsipService(c)) {
        Config.LOG.info("        (" + (no.incrementAndGet()) + ") " + c.getCanonicalName()
            + " ('" + Utils.getServiceName(c) + "', " + c.getAnnotation(Path.class).value() + ")");
        s.add(c);
        Utils.callStaticMethodIfExist(c, "onContextInit");
      }
    });
    Collections.sort(s, (Class<?> c1, Class<?> c2)
        -> Utils.getServiceName(c1).compareTo(Utils.getServiceName(c2)));
    Config.LOG.info(">>>>>>> Registered " + s.size() + " CSIP Services.");
  }


  synchronized void unregister() {
    if (s == null) 
      return;
    
    s.forEach((Class<?> c) -> {
      Config.LOG.info("        Unregister: " + c.getCanonicalName());
      Utils.callStaticMethodIfExist(c, "onContextDestroy");
    });
    Config.LOG.info(">>>>>>> Unregistered " + s.size() + " CSIP Services.");
    s.clear();
    s = null;
  }


  List<Class<?>> getServices() {
    return s;
  }
}