001/*
002 * JPPF.
003 * Copyright (C) 2005-2018 JPPF Team.
004 * http://www.jppf.org
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.jppf.discovery;
020
021import java.util.List;
022import java.util.concurrent.CopyOnWriteArrayList;
023
024/**
025 * Abstract superclass for custom driver discovery mechanisms.
026 * @param <E> the type of notifications sent by this discovery.
027 * @since 5.2.1
028 */
029public abstract class DriverDiscovery<E extends DriverConnectionInfo> {
030  /**
031   * The registered listeners to this discovery source.
032   */
033  private List<DriverDiscoveryListener<E>> listeners = new CopyOnWriteArrayList<>();
034
035  /**
036   * Perform the driver discovery. This method runs in its own separate thread.
037   * <p>To notify the client that a new driver is discovered, the {@link #newConnection(DriverConnectionInfo)} method must be called.
038   * @throws InterruptedException if the thread running this method is still alive when the component that started it (a JPPF client or driver) is closed or shut down.
039   */
040  public abstract void discover() throws InterruptedException;
041
042  /**
043   * Notify that a new driver was discovered.
044   * @param info encapsulates the driver connection information and configuration,
045   */
046  protected void newConnection(final E info) {
047    for (DriverDiscoveryListener<E> listener: listeners) listener.onNewConnection(info);
048  }
049
050  /**
051   * Add the specified listener to the list of listeners.
052   * @param listener the listener to add.
053   */
054  void addListener(final DriverDiscoveryListener<E> listener) {
055    if (listener != null) listeners.add(listener);
056  }
057
058  /**
059   * Remove the specified listener from the list of listeners.
060   * @param listener the listener to remove.
061   */
062  void removeListener(final DriverDiscoveryListener<E> listener) {
063    if (listener != null) listeners.remove(listener);
064  }
065
066  /**
067   * Closes this discovery and releases any resource it uses.
068   */
069  void stop() {
070    listeners.clear();
071    shutdown();
072  }
073
074  /**
075   * Shut this discovery down. This method is intended to be overriden in subclasses to allow user-defined cleanup operations.
076   * <p>Caution: this method is called in a different thread from the one that runs the {@link #discover()} method.
077   */
078  public void shutdown() {
079  }
080}