text:
#include "sdk/android/src/jni/pc/androidnetworkmonitor.h"

#include <dlfcn.h>
#ifndef RTLD_NOLOAD
// This was added in Lollipop to dlfcn.h
#define RTLD_NOLOAD 4
#endif

#include BOSS_WEBRTC_U_rtc_base__bind_h //original-code:"rtc_base/bind.h"
#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h"
#include BOSS_WEBRTC_U_rtc_base__ipaddress_h //original-code:"rtc_base/ipaddress.h"
#include "sdk/android/generated_peerconnection_jni/jni/NetworkMonitorAutoDetect_jni.h"
#include "sdk/android/generated_peerconnection_jni/jni/NetworkMonitor_jni.h"
#include "sdk/android/src/jni/jni_helpers.h"

namespace webrtc {
namespace jni {

enum AndroidSdkVersion {
  SDK_VERSION_LOLLIPOP = 21,
  SDK_VERSION_MARSHMALLOW = 23
};

static NetworkType GetNetworkTypeFromJava(
    JNIEnv* jni,
    const JavaRef<jobject>& j_network_type) {
  std::string enum_name = GetJavaEnumName(jni, j_network_type);
  if (enum_name == "CONNECTION_UNKNOWN") {
    return NetworkType::NETWORK_UNKNOWN;
  }
  if (enum_name == "CONNECTION_ETHERNET") {
    return NetworkType::NETWORK_ETHERNET;
  }
  if (enum_name == "CONNECTION_WIFI") {
    return NetworkType::NETWORK_WIFI;
  }
  if (enum_name == "CONNECTION_4G") {
    return NetworkType::NETWORK_4G;
  }
  if (enum_name == "CONNECTION_3G") {
    return NetworkType::NETWORK_3G;
  }
  if (enum_name == "CONNECTION_2G") {
    return NetworkType::NETWORK_2G;
  }
  if (enum_name == "CONNECTION_UNKNOWN_CELLULAR") {
    return NetworkType::NETWORK_UNKNOWN_CELLULAR;
  }
  if (enum_name == "CONNECTION_BLUETOOTH") {
    return NetworkType::NETWORK_BLUETOOTH;
  }
  if (enum_name == "CONNECTION_NONE") {
    return NetworkType::NETWORK_NONE;
  }
  RTC_NOTREACHED();
  return NetworkType::NETWORK_UNKNOWN;
}

static rtc::AdapterType AdapterTypeFromNetworkType(NetworkType network_type) {
  switch (network_type) {
    case NETWORK_UNKNOWN:
      return rtc::ADAPTER_TYPE_UNKNOWN;
    case NETWORK_ETHERNET:
      return rtc::ADAPTER_TYPE_ETHERNET;
    case NETWORK_WIFI:
      return rtc::ADAPTER_TYPE_WIFI;
    case NETWORK_4G:
    case NETWORK_3G:
    case NETWORK_2G:
    case NETWORK_UNKNOWN_CELLULAR:
      return rtc::ADAPTER_TYPE_CELLULAR;
    case NETWORK_BLUETOOTH:
      // There is no corresponding mapping for bluetooth networks.
      // Map it to VPN for now.
      return rtc::ADAPTER_TYPE_VPN;
    default:
      RTC_NOTREACHED() << "Invalid network type " << network_type;
      return rtc::ADAPTER_TYPE_UNKNOWN;
  }
}

static rtc::IPAddress JavaToNativeIpAddress(
    JNIEnv* jni,
    const JavaRef<jobject>& j_ip_address) {
  ScopedJavaLocalRef<jbyteArray> j_addresses =
      Java_IPAddress_getAddress(jni, j_ip_address);
  size_t address_length = jni->GetArrayLength(j_addresses.obj());
  jbyte* addr_array = jni->GetByteArrayElements(j_addresses.obj(), nullptr);
  CHECK_EXCEPTION(jni) << "Error during JavaToNativeIpAddress";
  if (address_length == 4) {
    // IP4
    struct in_addr ip4_addr;
    memcpy(&ip4_addr.s_addr, addr_array, 4);
    jni->ReleaseByteArrayElements(j_addresses.obj(), addr_array, JNI_ABORT);
    return rtc::IPAddress(ip4_addr);
  }
  // IP6
  RTC_CHECK(address_length == 16);
  struct in6_addr ip6_addr;
  memcpy(ip6_addr.s6_addr, addr_array, address_length);
  jni->ReleaseByteArrayElements(j_addresses.obj(), addr_array, JNI_ABORT);
  return rtc::IPAddress(ip6_addr);
}

static NetworkInformation GetNetworkInformationFromJava(
    JNIEnv* jni,
    const JavaRef<jobject>& j_network_info) {
  NetworkInformation network_info;
  network_info.interface_name = JavaToStdString(
      jni, Java_NetworkInformation_getName(jni, j_network_info));
  network_info.handle = static_cast<NetworkHandle>(
      Java_NetworkInformation_getHandle(jni, j_network_info));
  network_info.type = GetNetworkTypeFromJava(
      jni, Java_NetworkInformation_getConnectionType(jni, j_network_info));
  ScopedJavaLocalRef<jobjectArray> j_ip_addresses =
      Java_NetworkInformation_getIpAddresses(jni, j_network_info);
  network_info.ip_addresses = JavaToNativeVector<rtc::IPAddress>(
      jni, j_ip_addresses, &JavaToNativeIpAddress);
  return network_info;
}

std::string NetworkInformation::ToString() const {
  std::stringstream ss;
  ss << "NetInfo[name " << interface_name << "; handle " << handle << "; type "
     << type << "; address";
  for (const rtc::IPAddress address : ip_addresses) {
    ss << " " << address.ToString();
  }
  ss << "]";
  return ss.str();
}

AndroidNetworkMonitor::AndroidNetworkMonitor(JNIEnv* env)
    : android_sdk_int_(Java_NetworkMonitor_androidSdkInt(env)),
      j_network_monitor_(env, Java_NetworkMonitor_getInstance(env)) {}

void AndroidNetworkMonitor::Start() {
  RTC_CHECK(thread_checker_.CalledOnValidThread());
  if (started_) {
    return;
  }
  started_ = true;

  // This is kind of magic behavior, but doing this allows the SocketServer to
  // use this as a NetworkBinder to bind sockets on a particular network when
  // it creates sockets.
  worker_thread()->socketserver()->set_network_binder(this);

  JNIEnv* env = AttachCurrentThreadIfNeeded();
  Java_NetworkMonitor_startMonitoring(env, j_network_monitor_,
                                      jlongFromPointer(this));
}

void AndroidNetworkMonitor::Stop() {
  RTC_CHECK(thread_checker_.CalledOnValidThread());
  if (!started_) {
    return;
  }
  started_ = false;

  // Once the network monitor stops, it will clear all network information and
  // it won't find the network handle to bind anyway.
  if (worker_thread()->socketserver()->network_binder() == this) {
    worker_thread()->socketserver()->set_network_binder(nullptr);
  }

  JNIEnv* env = AttachCurrentThreadIfNeeded();
  Java_NetworkMonitor_stopMonitoring(env, j_network_monitor_,
                                     jlongFromPointer(this));

  network_handle_by_address_.clear();
  network_info_by_handle_.clear();
}

// The implementation is largely taken from UDPSocketPosix::BindToNetwork in
// https://cs.chromium.org/chromium/src/net/udp/udp_socket_posix.cc
rtc::NetworkBindingResult AndroidNetworkMonitor::BindSocketToNetwork(
    int socket_fd,
    const rtc::IPAddress& address) {
  RTC_CHECK(thread_checker_.CalledOnValidThread());

  // Android prior to Lollipop didn't have support for binding sockets to
  // networks. This may also occur if there is no connectivity manager service.
  JNIEnv* env = AttachCurrentThreadIfNeeded();
  const bool network_binding_supported =
      Java_NetworkMonitor_networkBindingSupported(env, j_network_monitor_);
  if (!network_binding_supported) {
    RTC_LOG(LS_WARNING)
        << "BindSocketToNetwork is not supported on this platform "
        << "(Android SDK: " << android_sdk_int_ << ")";
    return rtc::NetworkBindingResult::NOT_IMPLEMENTED;
  }

  auto iter = network_handle_by_address_.find(address);
  if (iter == network_handle_by_address_.end()) {
    return rtc::NetworkBindingResult::ADDRESS_NOT_FOUND;
  }
  NetworkHandle network_handle = iter->second;

  if (network_handle == 0 /* NETWORK_UNSPECIFIED */) {
    return rtc::NetworkBindingResult::NOT_IMPLEMENTED;
  }

  int rv = 0;
  if (android_sdk_int_ >= SDK_VERSION_MARSHMALLOW) {
    // See declaration of android_setsocknetwork() here:
    // http://androidxref.com/6.0.0_r1/xref/development/ndk/platforms/android-M/include/android/multinetwork.h#65
    // Function cannot be called directly as it will cause app to fail to load
    // on pre-marshmallow devices.
    typedef int (*MarshmallowSetNetworkForSocket)(NetworkHandle net,
                                                  int socket);
    static MarshmallowSetNetworkForSocket marshmallowSetNetworkForSocket;
    // This is not thread-safe, but we are running this only on the worker
    // thread.
    if (!marshmallowSetNetworkForSocket) {
      const std::string android_native_lib_path = "libandroid.so";
      void* lib = dlopen(android_native_lib_path.c_str(), RTLD_NOW);
      if (lib == nullptr) {
        RTC_LOG(LS_ERROR) << "Library " << android_native_lib_path
                          << " not found!";
        return rtc::NetworkBindingResult::NOT_IMPLEMENTED;
      }
      marshmallowSetNetworkForSocket =
          reinterpret_cast<MarshmallowSetNetworkForSocket>(
              dlsym(lib, "android_setsocknetwork"));
    }
    if (!marshmallowSetNetworkForSocket) {
      RTC_LOG(LS_ERROR) << "Symbol marshmallowSetNetworkForSocket is not found";
      return rtc::NetworkBindingResult::NOT_IMPLEMENTED;
    }
    rv = marshmallowSetNetworkForSocket(network_handle, socket_fd);
  } else {
    // NOTE: This relies on Android implementation details, but it won't change
    // because Lollipop is already released.
    typedef int (*LollipopSetNetworkForSocket)(unsigned net, int socket);
    static LollipopSetNetworkForSocket lollipopSetNetworkForSocket;
    // This is not threadsafe, but we are running this only on the worker
    // thread.
    if (!lollipopSetNetworkForSocket) {
      // Android's netd client library should always be loaded in our address
      // space as it shims libc functions like connect().
      const std::string net_library_path = "libnetd_client.so";
      // Use RTLD_NOW to match Android's prior loading of the library:
      // http://androidxref.com/6.0.0_r5/xref/bionic/libc/bionic/NetdClient.cpp#37
      // Use RTLD_NOLOAD to assert that the library is already loaded and
      // avoid doing any disk IO.
      void* lib = dlopen(net_library_path.c_str(), RTLD_NOW | RTLD_NOLOAD);
      if (lib == nullptr) {
        RTC_LOG(LS_ERROR) << "Library " << net_library_path << " not found!";
        return rtc::NetworkBindingResult::NOT_IMPLEMENTED;
      }
      lollipopSetNetworkForSocket =
          reinterpret_cast<LollipopSetNetworkForSocket>(
              dlsym(lib, "setNetworkForSocket"));
    }
    if (!lollipopSetNetworkForSocket) {
      RTC_LOG(LS_ERROR) << "Symbol lollipopSetNetworkForSocket is not found ";
      return rtc::NetworkBindingResult::NOT_IMPLEMENTED;
    }
    rv = lollipopSetNetworkForSocket(network_handle, socket_fd);
  }

  // If |network| has since disconnected, |rv| will be ENONET.  Surface this as
  // ERR_NETWORK_CHANGED, rather than MapSystemError(ENONET) which gives back
  // the less descriptive ERR_FAILED.
  if (rv == 0) {
    return rtc::NetworkBindingResult::SUCCESS;
  }
  if (rv == ENONET) {
    return rtc::NetworkBindingResult::NETWORK_CHANGED;
  }
  return rtc::NetworkBindingResult::FAILURE;
}

void AndroidNetworkMonitor::OnNetworkConnected(
    const NetworkInformation& network_info) {
  worker_thread()->Invoke<void>(
      RTC_FROM_HERE, rtc::Bind(&AndroidNetworkMonitor::OnNetworkConnected_w,
                               this, network_info));
  // Fire SignalNetworksChanged to update the list of networks.
  OnNetworksChanged();
}

void AndroidNetworkMonitor::OnNetworkConnected_w(
    const NetworkInformation& network_info) {
  RTC_LOG(LS_INFO) << "Network connected: " << network_info.ToString();
  adapter_type_by_name_[network_info.interface_name] =
      AdapterTypeFromNetworkType(network_info.type);
  network_info_by_handle_[network_info.handle] = network_info;
  for (const rtc::IPAddress& address : network_info.ip_addresses) {
    network_handle_by_address_[address] = network_info.handle;
  }
}

void AndroidNetworkMonitor::OnNetworkDisconnected(NetworkHandle handle) {
  RTC_LOG(LS_INFO) << "Network disconnected for handle " << handle;
  worker_thread()->Invoke<void>(
      RTC_FROM_HERE,
      rtc::Bind(&AndroidNetworkMonitor::OnNetworkDisconnected_w, this, handle));
}

void AndroidNetworkMonitor::OnNetworkDisconnected_w(NetworkHandle handle) {
  auto iter = network_info_by_handle_.find(handle);
  if (iter != network_info_by_handle_.end()) {
    for (const rtc::IPAddress& address : iter->second.ip_addresses) {
      network_handle_by_address_.erase(address);
    }
    network_info_by_handle_.erase(iter);
  }
}

void AndroidNetworkMonitor::SetNetworkInfos(
    const std::vector<NetworkInformation>& network_infos) {
  RTC_CHECK(thread_checker_.CalledOnValidThread());
  network_handle_by_address_.clear();
  network_info_by_handle_.clear();
  RTC_LOG(LS_INFO) << "Android network monitor found " << network_infos.size()
                   << " networks";
  for (NetworkInformation network : network_infos) {
    OnNetworkConnected_w(network);
  }
}

rtc::AdapterType AndroidNetworkMonitor::GetAdapterType(
    const std::string& if_name) {
  auto iter = adapter_type_by_name_.find(if_name);
  rtc::AdapterType type = (iter == adapter_type_by_name_.end())
                              ? rtc::ADAPTER_TYPE_UNKNOWN
                              : iter->second;
  if (type == rtc::ADAPTER_TYPE_UNKNOWN) {
    RTC_LOG(LS_WARNING) << "Get an unknown type for the interface " << if_name;
  }
  return type;
}

rtc::NetworkMonitorInterface*
AndroidNetworkMonitorFactory::CreateNetworkMonitor() {
  return new AndroidNetworkMonitor(AttachCurrentThreadIfNeeded());
}

void AndroidNetworkMonitor::NotifyConnectionTypeChanged(
    JNIEnv* env,
    const JavaRef<jobject>& j_caller) {
  OnNetworksChanged();
}

void AndroidNetworkMonitor::NotifyOfActiveNetworkList(
    JNIEnv* env,
    const JavaRef<jobject>& j_caller,
    const JavaRef<jobjectArray>& j_network_infos) {
  std::vector<NetworkInformation> network_infos =
      JavaToNativeVector<NetworkInformation>(env, j_network_infos,
                                             &GetNetworkInformationFromJava);
  SetNetworkInfos(network_infos);
}

void AndroidNetworkMonitor::NotifyOfNetworkConnect(
    JNIEnv* env,
    const JavaRef<jobject>& j_caller,
    const JavaRef<jobject>& j_network_info) {
  NetworkInformation network_info =
      GetNetworkInformationFromJava(env, j_network_info);
  OnNetworkConnected(network_info);
}

void AndroidNetworkMonitor::NotifyOfNetworkDisconnect(
    JNIEnv* env,
    const JavaRef<jobject>& j_caller,
    jlong network_handle) {
  OnNetworkDisconnected(static_cast<NetworkHandle>(network_handle));
}

}  // namespace jni
}  // namespace webrtc


text:
package org.apache.qpid.jms.provider.failover;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

import javax.jms.JMSException;
import javax.jms.JMSSecurityException;

import org.apache.qpid.jms.message.JmsInboundMessageDispatch;
import org.apache.qpid.jms.message.JmsMessageFactory;
import org.apache.qpid.jms.message.JmsOutboundMessageDispatch;
import org.apache.qpid.jms.meta.JmsConnectionInfo;
import org.apache.qpid.jms.meta.JmsConsumerId;
import org.apache.qpid.jms.meta.JmsResource;
import org.apache.qpid.jms.meta.JmsSessionId;
import org.apache.qpid.jms.provider.AsyncResult;
import org.apache.qpid.jms.provider.DefaultProviderListener;
import org.apache.qpid.jms.provider.Provider;
import org.apache.qpid.jms.provider.ProviderConstants.ACK_TYPE;
import org.apache.qpid.jms.provider.ProviderFactory;
import org.apache.qpid.jms.provider.ProviderFuture;
import org.apache.qpid.jms.provider.ProviderListener;
import org.apache.qpid.jms.provider.ProviderRedirectedException;
import org.apache.qpid.jms.provider.WrappedAsyncResult;
import org.apache.qpid.jms.util.IOExceptionSupport;
import org.apache.qpid.jms.util.ThreadPoolUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A Provider Facade that provides services for detection dropped Provider connections
 * and attempting to reconnect to a different remote peer.  Upon establishment of a new
 * connection the FailoverProvider will initiate state recovery of the active JMS
 * framework resources.
 */
public class FailoverProvider extends DefaultProviderListener implements Provider {

    private static final Logger LOG = LoggerFactory.getLogger(FailoverProvider.class);

    public static final int UNLIMITED = -1;
    private static final int UNDEFINED = -1;

    public static final int DEFAULT_MAX_RECONNECT_ATTEMPTS = UNLIMITED;
    public static final int DEFAULT_STARTUP_MAX_RECONNECT_ATTEMPTS = UNDEFINED;
    public static final long DEFAULT_INITIAL_RECONNECT_DELAY = 0;
    public static final long DEFAULT_RECONNECT_DELAY = 10;
    public static final long DEFAULT_MAX_RECONNECT_DELAY = TimeUnit.SECONDS.toMillis(30);
    public static final boolean DEFAULT_USE_RECONNECT_BACKOFF = true;
    public static final double DEFAULT_RECONNECT_BACKOFF_MULTIPLIER = 2.0d;
    public static final int DEFAULT_WARN_AFTER_RECONNECT_ATTEMPTS = 10;

    private ProviderListener listener;
    private Provider provider;
    private final FailoverUriPool uris;

    private final ExecutorService serializer;
    private final ScheduledExecutorService connectionHub;
    private final AtomicBoolean closed = new AtomicBoolean();
    private final AtomicBoolean failed = new AtomicBoolean();
    private final AtomicBoolean closingConnection = new AtomicBoolean(false);
    private final AtomicLong requestId = new AtomicLong();
    private final Map<Long, FailoverRequest> requests = new LinkedHashMap<Long, FailoverRequest>();
    private final DefaultProviderListener closedListener = new DefaultProviderListener();
    private final AtomicReference<JmsMessageFactory> messageFactory = new AtomicReference<JmsMessageFactory>();

    // Current state of connection / reconnection
    private boolean firstAttempt = true;
    private boolean firstConnection = true;
    private long reconnectAttempts;
    private long nextReconnectDelay = -1;
    private IOException failureCause;
    private URI connectedURI;

    // Timeout values configured via JmsConnectionInfo
    private long connectTimeout = JmsConnectionInfo.DEFAULT_CONNECT_TIMEOUT;
    private long closeTimeout = JmsConnectionInfo.DEFAULT_CLOSE_TIMEOUT;
    private long sendTimeout =  JmsConnectionInfo.DEFAULT_SEND_TIMEOUT;
    private long requestTimeout = JmsConnectionInfo.DEFAULT_REQUEST_TIMEOUT;

    // Configuration values.
    private long initialReconnectDelay = DEFAULT_INITIAL_RECONNECT_DELAY;
    private long reconnectDelay = DEFAULT_RECONNECT_DELAY;
    private long maxReconnectDelay = DEFAULT_MAX_RECONNECT_DELAY;
    private boolean useReconnectBackOff = DEFAULT_USE_RECONNECT_BACKOFF;
    private double reconnectBackOffMultiplier = DEFAULT_RECONNECT_BACKOFF_MULTIPLIER;
    private int maxReconnectAttempts = DEFAULT_MAX_RECONNECT_ATTEMPTS;
    private int startupMaxReconnectAttempts = DEFAULT_STARTUP_MAX_RECONNECT_ATTEMPTS;
    private int warnAfterReconnectAttempts = DEFAULT_WARN_AFTER_RECONNECT_ATTEMPTS;

    public FailoverProvider(Map<String, String> nestedOptions) {
        this(null, nestedOptions);
    }

    public FailoverProvider(List<URI> uris) {
        this(uris, null);
    }

    public FailoverProvider(List<URI> uris, Map<String, String> nestedOptions) {
        this.uris = new FailoverUriPool(uris, nestedOptions);

        this.serializer = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {

            @Override
            public Thread newThread(Runnable runner) {
                Thread serial = new Thread(runner);
                serial.setDaemon(true);
                serial.setName("FailoverProvider: serialization thread");
                return serial;
            }
        });

        // All Connection attempts happen in this schedulers thread.  Once a connection
        // is established it will hand the open connection back to the serializer thread
        // for state recovery.
        this.connectionHub = Executors.newScheduledThreadPool(1, new ThreadFactory() {

            @Override
            public Thread newThread(Runnable runner) {
                Thread serial = new Thread(runner);
                serial.setDaemon(true);
                serial.setName("FailoverProvider: connect thread");
                return serial;
            }
        });
    }

    @Override
    public void connect() throws IOException {
        checkClosed();
        LOG.debug("Initiating initial connection attempt task");
        triggerReconnectionAttempt();
    }

    @Override
    public void start() throws IOException, IllegalStateException {
        checkClosed();

        if (listener == null) {
            throw new IllegalStateException("No ProviderListener registered.");
        }
    }

    @Override
    public void close() {
        if (closed.compareAndSet(false, true)) {
            final ProviderFuture request = new ProviderFuture();
            serializer.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        IOException error = failureCause != null ? failureCause : new IOException("Connection closed");
                        List<FailoverRequest> pending = new ArrayList<FailoverRequest>(requests.values());
                        for (FailoverRequest request : pending) {
                            request.onFailure(error);
                        }

                        if (provider != null) {
                            provider.close();
                        }
                    } catch (Exception e) {
                        LOG.debug("Caught exception while closing connection");
                    } finally {
                        ThreadPoolUtils.shutdownGraceful(connectionHub);
                        if (serializer != null) {
                            serializer.shutdown();
                        }
                        request.onSuccess();
                    }
                }
            });

            try {
                if (this.closeTimeout < 0) {
                    request.sync();
                } else {
                    request.sync(closeTimeout, TimeUnit.MILLISECONDS);
                }
            } catch (IOException e) {
                LOG.warn("Error caught while closing Provider: ", e.getMessage());
            }
        }
    }

    @Override
    public void create(final JmsResource resource, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException {
        checkClosed();
        FailoverRequest pending = null;
        if (resource instanceof JmsConnectionInfo) {
            pending = new CreateConnectionRequest(request) {
                @Override
                public void doTask() throws Exception {
                    JmsConnectionInfo connectionInfo = (JmsConnectionInfo) resource;
                    connectTimeout = connectionInfo.getConnectTimeout();
                    closeTimeout = connectionInfo.getCloseTimeout();
                    sendTimeout = connectionInfo.getSendTimeout();
                    requestTimeout = connectionInfo.getRequestTimeout();

                    provider.create(resource, this);
                }

                @Override
                public String toString() {
                    return "create -> " + resource;
                }
            };
        } else {
            pending = new FailoverRequest(request) {
                @Override
                public void doTask() throws Exception {
                    provider.create(resource, this);
                }

                @Override
                public String toString() {
                    return "create -> " + resource;
                }
            };
        }

        serializer.execute(pending);
    }

    @Override
    public void start(final JmsResource resource, final AsyncResult request) throws IOException, JMSException {
        checkClosed();
        final FailoverRequest pending = new FailoverRequest(request) {
            @Override
            public void doTask() throws Exception {
                provider.start(resource, this);
            }

            @Override
            public String toString() {
                return "start -> " + resource;
            }
        };

        serializer.execute(pending);
    }

    @Override
    public void stop(final JmsResource resource, final AsyncResult request) throws IOException, JMSException {
        checkClosed();
        final FailoverRequest pending = new FailoverRequest(request) {
            @Override
            public void doTask() throws Exception {
                provider.stop(resource, this);
            }

            @Override
            public String toString() {
                return "stop -> " + resource;
            }
        };

        serializer.execute(pending);
    }

    @Override
    public void destroy(final JmsResource resourceId, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException {
        checkClosed();
        final FailoverRequest pending = new FailoverRequest(request) {
            @Override
            public void doTask() throws IOException, JMSException, UnsupportedOperationException {
                if (resourceId instanceof JmsConnectionInfo) {
                   closingConnection.set(true);
                }
                provider.destroy(resourceId, this);
            }

            @Override
            public boolean succeedsWhenOffline() {
                // Allow this to succeed, resource won't get recreated on reconnect.
                return true;
            }

            @Override
            public String toString() {
                return "destroy -> " + resourceId;
            }
        };

        serializer.execute(pending);
    }

    @Override
    public void send(final JmsOutboundMessageDispatch envelope, AsyncResult request) throws IOException, JMSException {
        checkClosed();
        final FailoverRequest pending = new FailoverRequest(request) {
            @Override
            public void doTask() throws Exception {
                provider.send(envelope, this);
            }

            @Override
            public String toString() {
                return "send -> " + envelope;
            }
        };

        serializer.execute(pending);
    }

    @Override
    public void acknowledge(final JmsSessionId sessionId, final ACK_TYPE ackType, AsyncResult request) throws IOException, JMSException {
        checkClosed();
        final FailoverRequest pending = new FailoverRequest(request) {
            @Override
            public void doTask() throws Exception {
                provider.acknowledge(sessionId, ackType, this);
            }

            @Override
            public boolean succeedsWhenOffline() {
                // Allow this to succeed, acks would be stale.
                return true;
            }

            @Override
            public String toString() {
                return "session acknowledge -> " + sessionId;
            }
        };

        serializer.execute(pending);
    }

    @Override
    public void acknowledge(final JmsInboundMessageDispatch envelope, final ACK_TYPE ackType, AsyncResult request) throws IOException, JMSException {
        checkClosed();
        final FailoverRequest pending = new FailoverRequest(request) {
            @Override
            public void doTask() throws Exception {
                provider.acknowledge(envelope, ackType, this);
            }

            @Override
            public boolean succeedsWhenOffline() {
                // Allow this to succeed, acks would be stale.
                return true;
            }

            @Override
            public String toString() {
                return "message acknowledge -> " + envelope + " ackType: " + ackType;
            }
        };

        serializer.execute(pending);
    }

    @Override
    public void commit(final JmsSessionId sessionId, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException {
        checkClosed();
        final FailoverRequest pending = new FailoverRequest(request) {
            @Override
            public void doTask() throws Exception {
                provider.commit(sessionId, this);
            }

            @Override
            public boolean failureWhenOffline() {
                return true;
            }

            @Override
            public String toString() {
                return "TX commit -> " + sessionId;
            }
        };

        serializer.execute(pending);
    }

    @Override
    public void rollback(final JmsSessionId sessionId, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException {
        checkClosed();
        final FailoverRequest pending = new FailoverRequest(request) {
            @Override
            public void doTask() throws Exception {
                provider.rollback(sessionId, this);
            }

            @Override
            public boolean failureWhenOffline() {
                return true;
            }

            @Override
            public String toString() {
                return "TX rollback -> " + sessionId;
            }
        };

        serializer.execute(pending);
    }

    @Override
    public void recover(final JmsSessionId sessionId, final AsyncResult request) throws IOException, UnsupportedOperationException {
        checkClosed();
        final FailoverRequest pending = new FailoverRequest(request) {
            @Override
            public void doTask() throws Exception {
                provider.recover(sessionId, this);
            }

            @Override
            public boolean succeedsWhenOffline() {
                return true;
            }

            @Override
            public String toString() {
                return "recover -> " + sessionId;
            }
        };

        serializer.execute(pending);
    }

    @Override
    public void unsubscribe(final String subscription, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException {
        checkClosed();
        final FailoverRequest pending = new FailoverRequest(request) {
            @Override
            public void doTask() throws Exception {
                provider.unsubscribe(subscription, this);
            }

            @Override
            public String toString() {
                return "unsubscribe -> " + subscription;
            }
        };

        serializer.execute(pending);
    }

    @Override
    public void pull(final JmsConsumerId consumerId, final long timeout, final AsyncResult request) throws IOException, UnsupportedOperationException {
        checkClosed();
        final FailoverRequest pending = new FailoverRequest(request) {
            @Override
            public void doTask() throws Exception {
                provider.pull(consumerId, timeout, this);
            }

            @Override
            public String toString() {
                return "message pull -> " + consumerId;
            }
        };

        serializer.execute(pending);
    }

    @Override
    public JmsMessageFactory getMessageFactory() {
        return messageFactory.get();
    }

    //--------------- Connection Error and Recovery methods ------------------//

    /**
     * This method is always called from within the FailoverProvider's serialization thread.
     *
     * When a failure is encountered either from an outgoing request or from an error fired
     * from the underlying Provider instance this method is called to determine if a reconnect
     * is allowed and if so a new reconnect cycle is triggered on the connection thread.
     *
     * @param cause
     *        the error that triggered the failure of the provider.
     */
    private void handleProviderFailure(final IOException cause) {
        LOG.debug("handling Provider failure: {}", cause.getMessage());
        LOG.trace("stack", cause);

        provider.setProviderListener(closedListener);
        URI failedURI = this.provider.getRemoteURI();
        try {
            provider.close();
        } catch (Throwable error) {
            LOG.trace("Caught exception while closing failed provider: {}", error.getMessage());
        }
        provider = null;

        if (reconnectAllowed(cause)) {

            if (cause instanceof ProviderRedirectedException) {
                ProviderRedirectedException redirect = (ProviderRedirectedException) cause;
                try {
                    uris.addFirst(new URI(failedURI.getScheme() + "://" + redirect.getNetworkHost() + ":" + redirect.getPort()));
                } catch (URISyntaxException ex) {
                    LOG.warn("Could not construct redirection URI from remote provided information");
                }
            }

            ProviderListener listener = this.listener;
            if (listener != null) {
                listener.onConnectionInterrupted(failedURI);
            }
            triggerReconnectionAttempt();
        } else {
            ProviderListener listener = this.listener;
            if (listener != null) {
                listener.onConnectionFailure(cause);
            }
        }
    }

    /**
     * Called from the reconnection thread.  This method enqueues a new task that
     * will attempt to recover connection state, once successful, normal operations
     * will resume.  If an error occurs while attempting to recover the JMS framework
     * state then a reconnect cycle is again triggered on the connection thread.
     *
     * @param provider
     *        The newly connect Provider instance that will become active.
     */
    private void initializeNewConnection(final Provider provider) {
        this.serializer.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    FailoverProvider.this.provider = provider;
                    provider.setProviderListener(FailoverProvider.this);

                    if (!firstConnection) {
                        LOG.debug("Signalling connection recovery: {}", provider);

                        // Stage 1: Allow listener to recover its resources
                        listener.onConnectionRecovery(provider);

                        // Stage 2: Connection state recovered, get newly configured message factory.
                        FailoverProvider.this.messageFactory.set(provider.getMessageFactory());

                        // Stage 3: Restart consumers, send pull commands, etc.
                        listener.onConnectionRecovered(provider);

                        // Stage 4: Let the client know that connection has restored.
                        listener.onConnectionRestored(provider.getRemoteURI());
                    }

                    // Last step: Send pending actions.
                    List<FailoverRequest> pending = new ArrayList<FailoverRequest>(requests.values());
                    for (FailoverRequest request : pending) {
                        request.run();
                    }

                    nextReconnectDelay = reconnectDelay;
                    reconnectAttempts = 0;
                    connectedURI = provider.getRemoteURI();
                    uris.connected();
                } catch (Throwable error) {
                    handleProviderFailure(IOExceptionSupport.create(error));
                }
            }
        });
    }

    /**
     * Called when the Provider was either first created or when a connection failure has
     * been reported.  A reconnection attempt is immediately executed on the connection
     * thread.  If a new Provider is able to be created and connected then a recovery task
     * is scheduled on the main serializer thread.  If the connect attempt fails another
     * attempt is scheduled based on the configured delay settings until a max attempts
     * limit is hit, if one is set.
     *
     * Since the initialize is put on the serializer thread this thread stops and does
     * not queue another connect task.  This allows for the reconnect delay to be reset
     * and a failure to initialize a new connection restarts the connect process from the
     * point of view that connection was lost and an immediate attempt cycle should start.
     */
    private void triggerReconnectionAttempt() {
        if (closingConnection.get() || closed.get() || failed.get()) {
            return;
        }

        connectionHub.execute(new Runnable() {
            boolean delayed = false;

            @Override
            public void run() {
                if (provider != null || closingConnection.get() || closed.get() || failed.get()) {
                    return;
                }

                int reconnectLimit = reconnectAttemptLimit();
                if (reconnectLimit != UNLIMITED && reconnectAttempts >= reconnectLimit) {
                    return;
                }

                boolean first = firstAttempt;
                firstAttempt = false;

                if (!delayed && !first && initialReconnectDelay > 0 && reconnectAttempts == 0) {
                    delayed = true;
                    LOG.trace("Delayed initial reconnect attempt will be in {} milliseconds", initialReconnectDelay);
                    connectionHub.schedule(this, initialReconnectDelay, TimeUnit.MILLISECONDS);
                    return;
                }

                reconnectAttempts++;
                Throwable failure = null;
                URI target = uris.getNext();
                if (target != null) {
                    Provider provider = null;
                    try {
                        LOG.debug("Connection attempt:[{}] to: {} in-progress", reconnectAttempts, target);
                        provider = ProviderFactory.create(target);
                        provider.connect();
                        initializeNewConnection(provider);
                        return;
                    } catch (Throwable e) {
                        LOG.info("Connection attempt:[{}] to: {} failed", reconnectAttempts, target);
                        failure = e;
                        try {
                            provider.close();
                        } catch (Throwable ex) {}
                    }
                } else {
                    LOG.debug("No target URI available to connect to");
                }

                if (reconnectLimit != UNLIMITED && reconnectAttempts >= reconnectLimit) {
                    LOG.error("Failed to connect after: " + reconnectAttempts + " attempt(s)");
                    failed.set(true);
                    if (failure == null) {
                        failureCause = new IOException("Failed to connect after: " + reconnectAttempts + " attempt(s)");
                    } else {
                        failureCause = IOExceptionSupport.create(failure);
                    }
                    if (listener != null) {
                        listener.onConnectionFailure(failureCause);
                    };

                    return;
                }

                int warnInterval = getWarnAfterReconnectAttempts();
                if (warnInterval > 0 && (reconnectAttempts % warnInterval) == 0) {
                    LOG.warn("Failed to connect after: {} attempt(s) continuing to retry.", reconnectAttempts);
                }

                long delay = nextReconnectDelay();
                LOG.trace("Next reconnect attempt will be in {} milliseconds", delay);
                connectionHub.schedule(this, delay, TimeUnit.MILLISECONDS);
            }
        });
    }

    private boolean reconnectAllowed(IOException cause) {
        // If a connection attempts fail due to Security errors than
        // we abort reconnection as there is a configuration issue and
        // we want to avoid a spinning reconnect cycle that can never
        // complete.
        if (cause.getCause() instanceof JMSSecurityException) {
            return false;
        }

        return reconnectAttemptLimit() != 0;
    }

    private int reconnectAttemptLimit() {
        int maxReconnectValue = this.maxReconnectAttempts;
        if (firstConnection && this.startupMaxReconnectAttempts != UNDEFINED) {
            // If this is the first connection and a specific startup retry limit
            // is configured then use it, otherwise use the main reconnect limit
            maxReconnectValue = this.startupMaxReconnectAttempts;
        }
        return maxReconnectValue;
    }

    private long nextReconnectDelay() {

        if (nextReconnectDelay == -1) {
            nextReconnectDelay = reconnectDelay;
        }

        if (isUseReconnectBackOff() && reconnectAttempts > 1) {
            // Exponential increment of reconnect delay.
            nextReconnectDelay *= getReconnectBackOffMultiplier();
            if (nextReconnectDelay > maxReconnectDelay) {
                nextReconnectDelay = maxReconnectDelay;
            }
        }

        return nextReconnectDelay;
    }

    protected void checkClosed() throws IOException {
        if (closed.get()) {
            throw new IOException("The Provider is already closed");
        }
    }

    //--------------- DefaultProviderListener overrides ----------------------//

    @Override
    public void onInboundMessage(final JmsInboundMessageDispatch envelope) {
        if (closingConnection.get() || closed.get() || failed.get()) {
            return;
        }

        listener.onInboundMessage(envelope);
    }

    @Override
    public void onConnectionFailure(final IOException ex) {
        if (closingConnection.get() || closed.get() || failed.get()) {
            return;
        }
        serializer.execute(new Runnable() {
            @Override
            public void run() {
                if (!closingConnection.get() && !closed.get() && !failed.get()) {
                    LOG.debug("Failover: the provider reports failure: {}", ex.getMessage());
                    handleProviderFailure(ex);
                }
            }
        });
    }

    @Override
    public void onProviderException(final Exception ex) {
        if (closingConnection.get() || closed.get() || failed.get()) {
            return;
        }
        serializer.execute(new Runnable() {
            @Override
            public void run() {
                if (!closingConnection.get() && !closed.get() && !failed.get()) {
                    LOG.debug("Failover: the provider reports an async error: {}", ex.getMessage());
                    listener.onProviderException(ex);
                }
            }
        });
    }

    //--------------- URI update and rebalance methods -----------------------//

    public void add(final URI uri) {
        serializer.execute(new Runnable() {
            @Override
            public void run() {
                uris.add(uri);
            }
        });
    }

    public void remove(final URI uri) {
        serializer.execute(new Runnable() {
            @Override
            public void run() {
                uris.remove(uri);
            }
        });
    }

    //--------------- Property Getters and Setters ---------------------------//

    @Override
    public URI getRemoteURI() {
        Provider provider = this.provider;
        if (provider != null) {
            return provider.getRemoteURI();
        }
        return null;
    }

    @Override
    public void setProviderListener(ProviderListener listener) {
        this.listener = listener;
    }

    @Override
    public ProviderListener getProviderListener() {
        return listener;
    }

    public boolean isRandomize() {
        return uris.isRandomize();
    }

    public void setRandomize(boolean value) {
        this.uris.setRandomize(value);
    }

    public long getInitialReconnectDelay() {
        return initialReconnectDelay;
    }

    public void setInitialReconnectDelay(long initialReconnectDelay) {
        this.initialReconnectDelay = initialReconnectDelay;
    }

    public long getReconnectDelay() {
        return reconnectDelay;
    }

    public void setReconnectDelay(long reconnectDealy) {
        this.reconnectDelay = reconnectDealy;
    }

    public long getMaxReconnectDelay() {
        return maxReconnectDelay;
    }

    public void setMaxReconnectDelay(long maxReconnectDelay) {
        this.maxReconnectDelay = maxReconnectDelay;
    }

    public int getMaxReconnectAttempts() {
        return maxReconnectAttempts;
    }

    public void setMaxReconnectAttempts(int maxReconnectAttempts) {
        this.maxReconnectAttempts = maxReconnectAttempts;
    }

    public int getStartupMaxReconnectAttempts() {
        return startupMaxReconnectAttempts;
    }

    public void setStartupMaxReconnectAttempts(int startupMaxReconnectAttempts) {
        this.startupMaxReconnectAttempts = startupMaxReconnectAttempts;
    }

    /**
     * Gets the current setting controlling how many Connect / Reconnect attempts must occur
     * before a warn message is logged.  A value of {@literal <= 0} indicates that there will be
     * no warn message logged regardless of how many reconnect attempts occur.
     *
     * @return the current number of connection attempts before warn logging is triggered.
     */
    public int getWarnAfterReconnectAttempts() {
        return warnAfterReconnectAttempts;
    }

    /**
     * Sets the number of Connect / Reconnect attempts that must occur before a warn message
     * is logged indicating that the transport is not connected.  This can be useful when the
     * client is running inside some container or service as it gives an indication of some
     * problem with the client connection that might not otherwise be visible.  To disable the
     * log messages this value should be set to a value {@literal <= 0}
     *
     * @param warnAfterReconnectAttempts
     *        The number of failed connection attempts that must happen before a warning is logged.
     */
    public void setWarnAfterReconnectAttempts(int warnAfterReconnectAttempts) {
        this.warnAfterReconnectAttempts = warnAfterReconnectAttempts;
    }

    public double getReconnectBackOffMultiplier() {
        return reconnectBackOffMultiplier;
    }

    public void setReconnectBackOffMultiplier(double reconnectBackOffMultiplier) {
        this.reconnectBackOffMultiplier = reconnectBackOffMultiplier;
    }

    public boolean isUseReconnectBackOff() {
        return useReconnectBackOff;
    }

    public void setUseReconnectBackOff(boolean useReconnectBackOff) {
        this.useReconnectBackOff = useReconnectBackOff;
    }

    public long getConnectTimeout() {
        return this.connectTimeout;
    }

    public long getCloseTimeout() {
        return this.closeTimeout;
    }

    public long getSendTimeout() {
        return this.sendTimeout;
    }

    public long getRequestTimeout() {
        return this.requestTimeout;
    }

    public Map<String, String> getNestedOptions() {
        return uris.getNestedOptions();
    }

    @Override
    public String toString() {
        return "FailoverProvider: " +
               (connectedURI == null ? "unconnected" : connectedURI.toString());
    }

    //--------------- FailoverProvider Asynchronous Request --------------------//

    /**
     * For all requests that are dispatched from the FailoverProvider to a connected
     * Provider instance an instance of FailoverRequest is used to handle errors that
     * occur during processing of that request and trigger a reconnect.
     */
    protected abstract class FailoverRequest extends WrappedAsyncResult implements Runnable {

        private final long id = requestId.incrementAndGet();

        public FailoverRequest(AsyncResult watcher) {
            super(watcher);
            LOG.trace("Created Failover Task: {} ({})", this, id);
        }

        @Override
        public void run() {
            requests.put(id, this);
            if (provider == null) {
                whenOffline(new IOException("Connection failed."));
            } else {
                try {
                    LOG.debug("Executing Failover Task: {} ({})", this, id);
                    doTask();
                } catch (UnsupportedOperationException e) {
                    requests.remove(id);
                    getWrappedRequest().onFailure(e);
                } catch (JMSException jmsEx) {
                    requests.remove(id);
                    getWrappedRequest().onFailure(jmsEx);
                } catch (Throwable e) {
                    LOG.debug("Caught exception while executing task: {} - {}", this, e.getMessage());
                    whenOffline(IOExceptionSupport.create(e));
                    handleProviderFailure(IOExceptionSupport.create(e));
                }
            }
        }

        @Override
        public void onFailure(final Throwable result) {
            if (result instanceof JMSException || closingConnection.get() || closed.get() || failed.get()) {
                requests.remove(id);
                super.onFailure(result);
            } else {
                LOG.debug("Request received error: {}", result.getMessage());
                serializer.execute(new Runnable() {
                    @Override
                    public void run() {
                        handleProviderFailure(IOExceptionSupport.create(result));
                    }
                });
            }
        }

        @Override
        public void onSuccess() {
            requests.remove(id);
            super.onSuccess();
        }

        /**
         * Called to execute the specific task that was requested.
         *
         * @throws Exception if an error occurs during task execution.
         */
        public abstract void doTask() throws Exception;

        /**
         * Should the request just succeed when the Provider is not connected.
         *
         * @return true if the request is marked as successful when not connected.
         */
        public boolean succeedsWhenOffline() {
            return false;
        }

        /**
         * When the transport is not connected should this request automatically fail.
         *
         * @return true if the task should fail when the Provider is not connected.
         */
        public boolean failureWhenOffline() {
            return false;
        }

        private void whenOffline(IOException error) {
            if (failureWhenOffline()) {
                requests.remove(id);
                getWrappedRequest().onFailure(IOExceptionSupport.create(error));
            } else if (succeedsWhenOffline()) {
                onSuccess();
            } else {
                LOG.trace("Failover task held until connection recovered: {} ({})", this, id);
            }
        }
    }

    /**
     * Captures the initial request to create a JmsConnectionInfo based resources and ensures
     * that if the connection is successfully established that the connection established event
     * is triggered once before moving on to sending only connection interrupted and restored
     * events.
     *
     * The connection state events must all be triggered from the FailoverProvider's serialization
     * thread, this class ensures that the connection established event follows that pattern.
     */
    protected abstract class CreateConnectionRequest extends FailoverRequest {

        /**
         * @param watcher
         */
        public CreateConnectionRequest(AsyncResult watcher) {
            super(watcher);
        }

        @Override
        public void onSuccess() {
            serializer.execute(new Runnable() {
                @Override
                public void run() {
                    if (firstConnection) {
                        LOG.trace("First connection requst has completed:");
                        FailoverProvider.this.messageFactory.set(provider.getMessageFactory());
                        listener.onConnectionEstablished(provider.getRemoteURI());
                        firstConnection = false;
                    } else {
                        LOG.warn("A second call to a CreateConnectionRequest not expected.");
                    }

                    CreateConnectionRequest.this.signalConnected();
                }
            });
        }

        public void signalConnected() {
            super.onSuccess();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef __itkClosingByReconstructionImageFilter_h
#define __itkClosingByReconstructionImageFilter_h

#include "itkImageToImageFilter.h"

namespace itk
{
/** \class ClosingByReconstructionImageFilter
 * \brief Closing by reconstruction of an image
 *
 * This filter is similar to the morphological closing, but contrary
 * to the mophological closing, the closing by reconstruction
 * preserves the shape of the components.  The closing by
 * reconstruction of an image "f" is defined as:
 *
 * ClosingByReconstruction(f) = ErosionByReconstruction(f, Dilation(f)).
 *
 * Closing by reconstruction not only preserves structures preserved by
 * the dilation, but also levels raises the contrast of the darkest
 * regions. If PreserveIntensities is on, a subsequent reconstruction
 * by dilation using a marker image that is the original image for all
 * unaffected pixels.
 *
 * Closing by reconstruction is described in Chapter 6.3.9 of Pierre
 * Soille's book "Morphological Image Analysis: Principles and
 * Applications", Second Edition, Springer, 2003.
 *
 * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.
 *
 * \sa GrayscaleMorphologicalClosingImageFilter
 * \ingroup ImageEnhancement  MathematicalMorphologyImageFilters
 * \ingroup ITKMathematicalMorphology
 */
template< class TInputImage, class TOutputImage, class TKernel >
class ITK_EXPORT ClosingByReconstructionImageFilter:
  public ImageToImageFilter< TInputImage, TOutputImage >
{
public:
  /** Standard class typedefs. */
  typedef ClosingByReconstructionImageFilter              Self;
  typedef ImageToImageFilter< TInputImage, TOutputImage > Superclass;
  typedef SmartPointer< Self >                            Pointer;
  typedef SmartPointer< const Self >                      ConstPointer;

  /** Some convenient typedefs. */
  typedef TInputImage                           InputImageType;
  typedef typename InputImageType::Pointer      InputImagePointer;
  typedef typename InputImageType::ConstPointer InputImageConstPointer;
  typedef typename InputImageType::RegionType   InputImageRegionType;
  typedef typename InputImageType::PixelType    InputImagePixelType;

  typedef TOutputImage                           OutputImageType;
  typedef typename OutputImageType::Pointer      OutputImagePointer;
  typedef typename OutputImageType::ConstPointer OutputImageConstPointer;
  typedef typename OutputImageType::RegionType   OutputImageRegionType;
  typedef typename OutputImageType::PixelType    OutputImagePixelType;

  /** Kernel typedef. */
  typedef TKernel KernelType;

  /** ImageDimension constants */
  itkStaticConstMacro(InputImageDimension, unsigned int,
                      TInputImage::ImageDimension);
  itkStaticConstMacro(OutputImageDimension, unsigned int,
                      TOutputImage::ImageDimension);

  /** Standard New method. */
  itkNewMacro(Self);

  /** Runtime information support. */
  itkTypeMacro(ClosingByReconstructionImageFilter,
               ImageToImageFilter);

  /** Set kernel (structuring element). */
  itkSetMacro(Kernel, KernelType);

  /** Get the kernel (structuring element). */
  itkGetConstReferenceMacro(Kernel, KernelType);

  /**
   * Set/Get whether the connected components are defined strictly by
   * face connectivity or by face+edge+vertex connectivity.  Default is
   * FullyConnectedOff.  For objects that are 1 pixel wide, use
   * FullyConnectedOn.
   */
  itkSetMacro(FullyConnected, bool);
  itkGetConstReferenceMacro(FullyConnected, bool);
  itkBooleanMacro(FullyConnected);

  /**
   * Set/Get whether the original intensities of the image retained for
   * those pixels unaffected by the opening by reconstrcution. If Off,
   * the output pixel contrast will be reduced. */
  itkSetMacro(PreserveIntensities, bool);
  itkGetConstReferenceMacro(PreserveIntensities, bool);
  itkBooleanMacro(PreserveIntensities);

#ifdef ITK_USE_CONCEPT_CHECKING
  /** Begin concept checking */
  itkConceptMacro( InputConvertibleToOutputCheck,
                   ( Concept::Convertible< InputImagePixelType, OutputImagePixelType > ) );
  /** End concept checking */
#endif

protected:
  ClosingByReconstructionImageFilter();
  ~ClosingByReconstructionImageFilter() {}
  void PrintSelf(std::ostream & os, Indent indent) const;

  /** ClosingByReconstructionImageFilter needs the entire input be
   * available. Thus, it needs to provide an implementation of
   * GenerateInputRequestedRegion(). */
  void GenerateInputRequestedRegion();

  /** ClosingByReconstructionImageFilter will produce the entire output. */
  void EnlargeOutputRequestedRegion( DataObject *itkNotUsed(output) );

  void GenerateData();

private:
  ClosingByReconstructionImageFilter(const Self &); //purposely not implemented
  void operator=(const Self &);                     //purposely not implemented

  /** kernel or structuring element to use. */
  KernelType m_Kernel;
  bool       m_FullyConnected;
  bool       m_PreserveIntensities;
}; // end of class
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkClosingByReconstructionImageFilter.hxx"
#endif

#endif


text:
#region License

#endregion

#region Imports

using System;
using Common.Logging;
using Spring.Objects.Factory;

#endregion

namespace Spring.Dao.Support
{
	///
	/// Generic base class for DAOs, defining template methods for DAO initialization.
	///
	/// <remarks>
    /// Extended by Spring's specific DAO support classes, such as:
    ///  AdoDaoSupport, HibernateDaoSupport, etc.
	/// </remarks>
	/// <author>Mark Pollack (.NET)</author>
	public abstract class DaoSupport : IInitializingObject
	{
		#region Fields

		#endregion

		#region Constants

		///
		/// The shared <see cref="Common.Logging.ILog"/> instance for this class (and derived classes).
		///
		protected static readonly ILog log =
			LogManager.GetLogger(typeof (DaoSupport));

		#endregion

		#region Constructor (s)
		///
		/// Initializes a new instance of the <see cref="DaoSupport"/> class.
                ///
		public 	DaoSupport()
		{

		}

		#endregion

		#region Properties

		#endregion

		#region Methods

        ///
        /// Abstract subclasses must override this to check their configuration.
        ///
        /// <remarks>
        ///
Implementors should be marked as sealed, to make it clear that
        /// concrete subclasses are not supposed to override this template method themselves.
        ///

        /// </remarks>
        protected abstract void CheckDaoConfig();

        ///
        /// Concrete subclasses can override this for custom initialization behavior.
        ///
        /// <remarks>
        /// Gets called after population of this instance's object properties.
        /// Exception thrown if InitDao fails will be rethrown as
        /// a ObjectInitializationException.
        /// </remarks>
        protected virtual void InitDao()
        {

        }

		#endregion

	    public void AfterPropertiesSet()
	    {
            // Let abstract subclasses check their configuration.
            CheckDaoConfig();

            // Let concrete implementations initialize themselves.
            try
            {
                InitDao();
            }
            catch (Exception ex)
            {
                throw new ObjectInitializationException("Initialization of DAO failed: " + ex.Message, ex);
            }
	    }
	}
}


text:
package org.reactor.request.parser;

import static java.lang.String.format;
import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
import org.reactor.AbstractUnitTest;
import org.reactor.request.ReactorRequest;
import org.reactor.request.ReactorRequestInput;
import org.reactor.request.ReactorRequestParsingException;

public class ReactorRequestComplexDataParserTest extends AbstractUnitTest {

    private static final String SENDER = "sender";
    private static final String TRIGGER = "trigger";

    private static final String VALUE_STRING = "string";
    private static final String VALUE_INTEGER = "123";
    private static final String VALUE_BOOLEAN = "true";

    @Test
    public void shouldParseAllGivenParameters() {
        // given
        ReactorRequestComplexDataParser<ReactorRequestComplexDataWithAnnotations> dataParser = givenDataParser(ReactorRequestComplexDataWithAnnotations.class);

        // when
        ReactorRequest<ReactorRequestComplexDataWithAnnotations> reactorRequest = dataParser.parseRequestWithData(
            SENDER, TRIGGER, new ReactorRequestInput(format("--f1 %s --f3 %s --f2 %s", VALUE_STRING, VALUE_INTEGER, VALUE_BOOLEAN)));

        // then
        ReactorRequestComplexDataWithAnnotations requestData = reactorRequest.getRequestData();
        assertThat(requestData.getField1()).isEqualTo(VALUE_STRING);
        assertThat(requestData.isField2()).isEqualTo(Boolean.valueOf(VALUE_BOOLEAN));
        assertThat(requestData.getField3()).isEqualTo(Integer.valueOf(VALUE_INTEGER));
    }

    @Test
    public void shouldThrowAnExceptionWhenRequiredParameterIsMissing() {
        // given
        ReactorRequestComplexDataParser<ReactorRequestComplexDataWithAnnotations> dataParser = givenDataParser(ReactorRequestComplexDataWithAnnotations.class);

        // then
        expectedException.expect(ReactorRequestParsingException.class);

        // when
        dataParser.parseRequestWithData(
                SENDER, TRIGGER, new ReactorRequestInput(format("--f1 %s --f2 %s", VALUE_STRING, VALUE_BOOLEAN)));
    }

    private <T> ReactorRequestComplexDataParser<T> givenDataParser(Class<T> dataType) {
        return new ReactorRequestComplexDataParser(dataType);
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class Layout : System.Web.UI.MasterPage {
    protected void Page_Init(object sender, EventArgs e) {
    }

    protected void Page_Load(object sender, EventArgs e) {
        var controlDocBlocks = GetControlsByType<HtmlGenericControl>(this).Where(c => c.Attributes["data-control-type"] != null);
        FillDescription(controlDocBlocks.Where(b => b.Attributes["data-content-type"] == "description"));
        FillProperties(controlDocBlocks.Where(b => b.Attributes["data-content-type"] == "members"));
    }

    void FillProperties(IEnumerable<HtmlGenericControl> controlDocBlocks) {
        foreach(var block in controlDocBlocks) {
            var filePath = Server.MapPath("~/App_Data/ControlReference/" + block.Attributes["data-control-type"] + ".Members.html");
            var text = File.ReadAllText(filePath);
            block.InnerHtml = text;
        }
    }

    void FillDescription(IEnumerable<HtmlGenericControl> controlDocBlocks) {
        foreach(var block in controlDocBlocks) {
            var filePath = Server.MapPath("~/App_Data/ControlReference/" + block.Attributes["data-control-type"] + ".Description.html");
            var text = File.ReadAllText(filePath);
            block.InnerHtml = text;
        }
    }

    IEnumerable<T> GetControlsByType<T>(Control root, Func<T, bool> predicate = null) where T : Control {
        if(root == null)
            throw new ArgumentNullException("root");

        var stack = new Stack<Control>(new Control[] { root });
        var result = new List<T>();

        while(stack.Count > 0) {
            var control = stack.Pop();
            T match = control as T;

            if(match != null && (predicate == null || predicate(match)))
                result.Add(match);

            foreach(Control childControl in control.Controls)
                stack.Push(childControl);
        }

        return result;
    }
}


text:
<?php

namespace Anthem\Nav;

use Anthem\Core\Module;

/**
 * Nav module.  Doesn't do much yet.
 */
class NavModule extends Module
{
}


text:
<wicket:panel>

	<div wicket:id="sjaxContainer">
		<form wicket:id="sjaxForm">
			<input wicket:id="commitcall" type="hidden"/>
			<input wicket:id="getdiagnosticcall" type="hidden"/>
			<input wicket:id="geterrorstringcall" type="hidden"/>
			<input wicket:id="getlasterrorcall" type="hidden"/>
			<input wicket:id="getvaluecall" type="hidden"/>
			<input wicket:id="initializecall" type="hidden"/>
			<input wicket:id="setvaluecall" type="hidden"/>
			<input wicket:id="terminatecall" type="hidden"/>
		</form>
	</div>

</wicket:panel>


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.compositor.layouts.content;

import static java.lang.Math.min;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.view.View;
import android.view.ViewGroup.MarginLayoutParams;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;

import org.chromium.base.Callback;
import org.chromium.base.CommandLine;
import org.chromium.base.PathUtils;
import org.chromium.base.ThreadUtils;
import org.chromium.base.TraceEvent;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.base.task.AsyncTask;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.flags.BooleanCachedFieldTrialParameter;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tab.TabUtils;
import org.chromium.chrome.browser.tasks.tab_management.TabUiFeatureUtilities;
import org.chromium.chrome.browser.ui.native_page.FrozenNativePage;
import org.chromium.chrome.browser.ui.native_page.NativePage;
import org.chromium.ui.base.DeviceFormFactor;
import org.chromium.ui.display.DisplayAndroid;
import org.chromium.url.GURL;

import java.io.File;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * The TabContentManager is responsible for serving tab contents to the UI components. Contents
 * could be live or static thumbnails.
 */
@JNINamespace("android")
public class TabContentManager {
    // These are used for UMA logging, so append only. Please update the
    // GridTabSwitcherThumbnailFetchingResult enum in enums.xml if these change.
    @IntDef({ThumbnailFetchingResult.GOT_JPEG, ThumbnailFetchingResult.GOT_ETC1,
            ThumbnailFetchingResult.GOT_NOTHING,
            ThumbnailFetchingResult.GOT_DIFFERENT_ASPECT_RATIO_JPEG})
    @Retention(RetentionPolicy.SOURCE)
    public @interface ThumbnailFetchingResult {
        int GOT_JPEG = 0;
        int GOT_ETC1 = 1;
        int GOT_NOTHING = 2;
        int GOT_DIFFERENT_ASPECT_RATIO_JPEG = 3;
        int NUM_ENTRIES = 4;
    }
    public static final double ASPECT_RATIO_PRECISION = 0.01;

    // Whether to allow to refetch tab thumbnail if the aspect ratio is not matching.
    public static final BooleanCachedFieldTrialParameter ALLOW_TO_REFETCH_TAB_THUMBNAIL_VARIATION =
            new BooleanCachedFieldTrialParameter(
                    ChromeFeatureList.TAB_GRID_LAYOUT_ANDROID, "allow_to_refetch", true);

    @VisibleForTesting
    public static final String UMA_THUMBNAIL_FETCHING_RESULT =
            "GridTabSwitcher.ThumbnailFetchingResult";
    private final Set<Integer> mRefectchedTabIds = new HashSet<>();

    private float mThumbnailScale;
    private int mFullResThumbnailsMaxSize;
    private final ContentOffsetProvider mContentOffsetProvider;
    private int[] mPriorityTabIds;
    private long mNativeTabContentManager;

    private final ArrayList<ThumbnailChangeListener> mListeners =
            new ArrayList<ThumbnailChangeListener>();

    private boolean mSnapshotsEnabled;
    private final TabFinder mTabFinder;
    private final Context mContext;

    /**
     * Listener to receive the "Last Thumbnail" event. "Last Thumbnail" is the first time
     * in the Activity life cycle that all the thumbnails in the Grid Tab Switcher are shown.
     */
    public interface LastThumbnailListener { void onLastThumbnail(int numOfThumbnails); }
    private boolean mLastThumbnailHappened;
    private List<LastThumbnailListener> mLastThumbnailListeners;
    private int mOnTheFlyRequests;
    private int mRequests;
    private int mNumOfThumbnailsForLastThumbnail;
    private float mExpectedThumbnailAspectRatio;

    /**
     * The Java interface for listening to thumbnail changes.
     */
    public interface ThumbnailChangeListener {
        /**
         * @param id The tab id.
         */
        public void onThumbnailChange(int id);
    }

    /**
     * The interface to get a {@link Tab} from a tab ID.
     */
    public interface TabFinder { Tab getTabById(int id); }

    /**
     * @param context               The context that this cache is created in.
     * @param resourceId            The resource that this value might be defined in.
     * @param commandLineSwitch     The switch for which we would like to extract value from.
     * @return the value of an integer resource.  If the value is overridden on the command line
     * with the given switch, return the override instead.
     */
    private static int getIntegerResourceWithOverride(Context context, int resourceId,
            String commandLineSwitch) {
        int val = -1;
        // TODO(crbug/959054): Convert this to Finch config.
        if (TabUiFeatureUtilities.isGridTabSwitcherEnabled(context)) {
            // With Grid Tab Switcher, we can greatly reduce the capacity of thumbnail cache.
            // See crbug.com/959054 for more details.
            if (resourceId == R.integer.default_thumbnail_cache_size) val = 2;
            if (resourceId == R.integer.default_approximation_thumbnail_cache_size) val = 8;
            assert val != -1;
        } else {
            val = context.getResources().getInteger(resourceId);
        }
        String switchCount = CommandLine.getInstance().getSwitchValue(commandLineSwitch);
        if (switchCount != null) {
            int count = Integer.parseInt(switchCount);
            val = count;
        }
        return val;
    }

    /**
     * @param context               The context that this cache is created in.
     * @param contentOffsetProvider The provider of content parameter.
     * @param tabFinder             The helper function to get tab from an ID.
     */
    public TabContentManager(Context context, ContentOffsetProvider contentOffsetProvider,
            boolean snapshotsEnabled, TabFinder tabFinder) {
        mContext = context;
        mContentOffsetProvider = contentOffsetProvider;
        mTabFinder = tabFinder;
        mSnapshotsEnabled = snapshotsEnabled;

        // Override the cache size on the command line with --thumbnails=100
        int defaultCacheSize = getIntegerResourceWithOverride(
                mContext, R.integer.default_thumbnail_cache_size, ChromeSwitches.THUMBNAILS);

        mFullResThumbnailsMaxSize = defaultCacheSize;

        float thumbnailScale = 1.f;
        DisplayAndroid display = DisplayAndroid.getNonMultiDisplay(mContext);
        float deviceDensity = display.getDipScale();
        if (DeviceFormFactor.isNonMultiDisplayContextOnTablet(mContext)) {
            // Scale all tablets to MDPI.
            thumbnailScale = 1.f / deviceDensity;
        } else {
            // For phones, reduce the amount of memory usage by capturing a lower-res thumbnail for
            // devices with resolution higher than HDPI (crbug.com/357740).
            if (deviceDensity > 1.5f) {
                thumbnailScale = 1.5f / deviceDensity;
            }
        }
        mThumbnailScale = thumbnailScale;

        mPriorityTabIds = new int[mFullResThumbnailsMaxSize];

        if (ALLOW_TO_REFETCH_TAB_THUMBNAIL_VARIATION.getValue()) {
            mExpectedThumbnailAspectRatio = TabUtils.getTabThumbnailAspectRatio(context);
        }
    }

    /**
     * Called after native library is loaded.
     */
    public void initWithNative() {
        int compressionQueueMaxSize =
                mContext.getResources().getInteger(R.integer.default_compression_queue_size);
        int writeQueueMaxSize =
                mContext.getResources().getInteger(R.integer.default_write_queue_size);

        // Override the cache size on the command line with
        // --approximation-thumbnails=100
        int approximationCacheSize = getIntegerResourceWithOverride(mContext,
                R.integer.default_approximation_thumbnail_cache_size,
                ChromeSwitches.APPROXIMATION_THUMBNAILS);

        boolean useApproximationThumbnails =
                !DeviceFormFactor.isNonMultiDisplayContextOnTablet(mContext);
        boolean saveJpegThumbnails = TabUiFeatureUtilities.isGridTabSwitcherEnabled(mContext);

        mNativeTabContentManager = TabContentManagerJni.get().init(TabContentManager.this,
                mFullResThumbnailsMaxSize, approximationCacheSize, compressionQueueMaxSize,
                writeQueueMaxSize, useApproximationThumbnails, saveJpegThumbnails,
                mExpectedThumbnailAspectRatio);
    }

    /**
     * Destroy the native component.
     */
    public void destroy() {
        if (mRefectchedTabIds != null) mRefectchedTabIds.clear();
        if (mNativeTabContentManager != 0) {
            TabContentManagerJni.get().destroy(mNativeTabContentManager);
            mNativeTabContentManager = 0;
        }
    }

    @CalledByNative
    private long getNativePtr() {
        return mNativeTabContentManager;
    }

    /**
     * Attach the given Tab's cc layer to this {@link TabContentManager}.
     * @param tab Tab whose cc layer will be attached.
     */
    public void attachTab(Tab tab) {
        if (mNativeTabContentManager == 0) return;
        TabContentManagerJni.get().attachTab(
                mNativeTabContentManager, TabContentManager.this, tab, tab.getId());
    }

    /**
     * Detach the given Tab's cc layer from this {@link TabContentManager}.
     * @param tab Tab whose cc layer will be detached.
     */
    public void detachTab(Tab tab) {
        if (mNativeTabContentManager == 0) return;
        TabContentManagerJni.get().detachTab(
                mNativeTabContentManager, TabContentManager.this, tab, tab.getId());
    }

    /**
     * Add a listener to thumbnail changes.
     * @param listener The listener of thumbnail change events.
     */
    public void addThumbnailChangeListener(ThumbnailChangeListener listener) {
        if (!mListeners.contains(listener)) {
            mListeners.add(listener);
        }
    }

    /**
     * Remove a listener to thumbnail changes.
     * @param listener The listener of thumbnail change events.
     */
    public void removeThumbnailChangeListener(ThumbnailChangeListener listener) {
        mListeners.remove(listener);
    }

    private Bitmap readbackNativeBitmap(final Tab tab, float scale) {
        NativePage nativePage = tab.getNativePage();
        boolean isNativeViewShowing = isNativeViewShowing(tab);
        if (nativePage == null && !isNativeViewShowing) {
            return null;
        }

        View viewToDraw = null;
        if (isNativeViewShowing) {
            viewToDraw = tab.getView();
        } else if (!(nativePage instanceof FrozenNativePage)) {
            viewToDraw = nativePage.getView();
        }
        if (viewToDraw == null || viewToDraw.getWidth() == 0 || viewToDraw.getHeight() == 0) {
            return null;
        }

        if (nativePage != null && nativePage instanceof InvalidationAwareThumbnailProvider) {
            if (!((InvalidationAwareThumbnailProvider) nativePage).shouldCaptureThumbnail()) {
                return null;
            }
        }

        return readbackNativeView(viewToDraw, scale, nativePage);
    }

    private Bitmap readbackNativeView(View viewToDraw, float scale, NativePage nativePage) {
        Bitmap bitmap = null;
        float overlayTranslateY = mContentOffsetProvider.getOverlayTranslateY();

        float leftMargin = 0.f;
        float topMargin = 0.f;
        if (viewToDraw.getLayoutParams() instanceof MarginLayoutParams) {
            MarginLayoutParams params = (MarginLayoutParams) viewToDraw.getLayoutParams();
            leftMargin = params.leftMargin;
            topMargin = params.topMargin;
        }

        try {
            bitmap = Bitmap.createBitmap(
                    (int) ((viewToDraw.getMeasuredWidth() + leftMargin) * mThumbnailScale),
                    (int) ((viewToDraw.getMeasuredHeight() + topMargin - overlayTranslateY)
                            * mThumbnailScale),
                    Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError ex) {
            return null;
        }

        Canvas c = new Canvas(bitmap);
        c.scale(scale, scale);
        c.translate(leftMargin, -overlayTranslateY + topMargin);
        if (nativePage != null && nativePage instanceof InvalidationAwareThumbnailProvider) {
            ((InvalidationAwareThumbnailProvider) nativePage).captureThumbnail(c);
        } else {
            viewToDraw.draw(c);
        }

        return bitmap;
    }

    /**
     * @param tabId The id of the {@link Tab} to check for a full sized thumbnail of.
     * @return      Whether or not there is a full sized cached thumbnail for the {@link Tab}
     *              identified by {@code tabId}.
     */
    public boolean hasFullCachedThumbnail(int tabId) {
        if (mNativeTabContentManager == 0) return false;
        return TabContentManagerJni.get().hasFullCachedThumbnail(
                mNativeTabContentManager, TabContentManager.this, tabId);
    }

    /**
     * Call to get a thumbnail for a given tab through a {@link Callback}. If there is
     * no up-to-date thumbnail on disk for the given tab, callback returns null.
     * @param tabId The ID of the tab to get the thumbnail for.
     * @param callback The callback to send the {@link Bitmap} with. Can be called up to twice when
     *                 {@code forceUpdate}; otherwise always called exactly once.
     * @param forceUpdate Whether to obtain the thumbnail from the live content.
     * @param writeBack When {@code forceUpdate}, whether to write the thumbnail to cache.
     */
    public void getTabThumbnailWithCallback(@NonNull int tabId, @NonNull Callback<Bitmap> callback,
            boolean forceUpdate, boolean writeBack) {
        if (!mSnapshotsEnabled) return;

        if (!forceUpdate) {
            assert !writeBack : "writeBack is ignored if not forceUpdate";
            getTabThumbnailFromDisk(tabId, callback);
            return;
        }

        if (mNativeTabContentManager == 0) return;

        // Reading thumbnail from disk is faster than taking screenshot from live Tab, so fetch
        // that first even if |forceUpdate|.
        getTabThumbnailFromDisk(tabId, (diskBitmap) -> {
            if (diskBitmap != null) callback.onResult(diskBitmap);

            if (mTabFinder == null) return;

            Tab tab = mTabFinder.getTabById(tabId);
            if (tab == null) return;

            captureThumbnail(tab, writeBack, (bitmap) -> {
                // Null check to avoid having a Bitmap from getTabThumbnailFromDisk() but
                // cleared here.
                // If invalidation is not needed, readbackNativeBitmap() might not do anything
                // and send back null.
                if (bitmap != null) {
                    callback.onResult(bitmap);
                }
            });
        });
    }

    /**
     * @param tab The {@link Tab} the thumbnail is for.
     * @return The file storing the thumbnail in ETC1 format of a certain {@link Tab}.
     */
    public static File getTabThumbnailFileEtc1(Tab tab) {
        return new File(PathUtils.getThumbnailCacheDirectory(), String.valueOf(tab.getId()));
    }

    /**
     * @param tabId The ID of the {@link Tab} the thumbnail is for.
     * @return The file storing the thumbnail in JPEG format of a certain {@link Tab}.
     */
    public static File getTabThumbnailFileJpeg(int tabId) {
        return new File(PathUtils.getThumbnailCacheDirectory(), tabId + ".jpeg");
    }

    /**
     * Add a listener to receive the "Last Thumbnail" event.
     * Note that this should not be called when there are no tabs.
     * @param listener A {@link LastThumbnailListener} to be called at the event. Must post the
     *                 real task and finish immediately.
     */
    public void addOnLastThumbnailListener(LastThumbnailListener listener) {
        ThreadUtils.assertOnUiThread();

        if (mLastThumbnailListeners == null) mLastThumbnailListeners = new ArrayList<>();
        mLastThumbnailListeners.add(listener);
        if (mLastThumbnailHappened) notifyOnLastThumbnail();
    }

    private void notifyOnLastThumbnail() {
        ThreadUtils.assertOnUiThread();

        if (mLastThumbnailListeners != null) {
            for (LastThumbnailListener c : mLastThumbnailListeners) {
                c.onLastThumbnail(mNumOfThumbnailsForLastThumbnail);
            }
            mLastThumbnailListeners = null;
        }
    }

    @VisibleForTesting
    public static Bitmap getJpegForTab(int tabId) {
        File file = getTabThumbnailFileJpeg(tabId);
        if (!file.isFile()) return null;
        return BitmapFactory.decodeFile(file.getPath());
    }

    private void getTabThumbnailFromDisk(@NonNull int tabId, @NonNull Callback<Bitmap> callback) {
        mOnTheFlyRequests++;
        mRequests++;
        // Try JPEG thumbnail first before using the more costly
        // TabContentManagerJni.get().getEtc1TabThumbnail.
        TraceEvent.startAsync("GetTabThumbnailFromDisk", tabId);
        new AsyncTask<Bitmap>() {
            @Override
            public Bitmap doInBackground() {
                return getJpegForTab(tabId);
            }

            @Override
            public void onPostExecute(Bitmap jpeg) {
                TraceEvent.finishAsync("GetTabThumbnailFromDisk", tabId);
                mOnTheFlyRequests--;
                if (mOnTheFlyRequests == 0 && !mLastThumbnailHappened) {
                    mLastThumbnailHappened = true;
                    mNumOfThumbnailsForLastThumbnail = mRequests;
                    notifyOnLastThumbnail();
                }
                if (jpeg != null) {
                    if (ALLOW_TO_REFETCH_TAB_THUMBNAIL_VARIATION.getValue()) {
                        double jpegAspectRatio = jpeg.getHeight() == 0
                                ? 0
                                : 1.0 * jpeg.getWidth() / jpeg.getHeight();
                        // Retry fetching thumbnail once for all tabs that are:
                        //  * Thumbnail's aspect ratio is different from the expected ratio.
                        if (!mRefectchedTabIds.contains(tabId)
                                && Math.abs(jpegAspectRatio - mExpectedThumbnailAspectRatio)
                                        >= ASPECT_RATIO_PRECISION) {
                            recordThumbnailFetchingResult(
                                    ThumbnailFetchingResult.GOT_DIFFERENT_ASPECT_RATIO_JPEG);

                            if (mNativeTabContentManager == 0) {
                                callback.onResult(jpeg);
                                return;
                            }
                            if (!mSnapshotsEnabled) return;

                            mRefectchedTabIds.add(tabId);
                            TabContentManagerJni.get().getEtc1TabThumbnail(mNativeTabContentManager,
                                    TabContentManager.this, tabId, mExpectedThumbnailAspectRatio,
                                    callback);
                            return;
                        }
                    }
                    recordThumbnailFetchingResult(ThumbnailFetchingResult.GOT_JPEG);

                    callback.onResult(jpeg);
                    return;
                }
                if (mNativeTabContentManager == 0 || !mSnapshotsEnabled) return;
                TabContentManagerJni.get().getEtc1TabThumbnail(mNativeTabContentManager,
                        TabContentManager.this, tabId, mExpectedThumbnailAspectRatio, (etc1) -> {
                            if (etc1 != null) {
                                recordThumbnailFetchingResult(ThumbnailFetchingResult.GOT_ETC1);
                            } else {
                                recordThumbnailFetchingResult(ThumbnailFetchingResult.GOT_NOTHING);
                            }
                            callback.onResult(etc1);
                        });
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    private static void recordThumbnailFetchingResult(@ThumbnailFetchingResult int result) {
        RecordHistogram.recordEnumeratedHistogram(
                UMA_THUMBNAIL_FETCHING_RESULT, result, ThumbnailFetchingResult.NUM_ENTRIES);
    }

    /**
     * Cache the content of a tab as a thumbnail.
     * @param tab The tab whose content we will cache.
     */
    public void cacheTabThumbnail(@NonNull final Tab tab) {
        if (mNativeTabContentManager == 0 || !mSnapshotsEnabled) return;

        captureThumbnail(tab, true, null);
    }

    private Bitmap cacheNativeTabThumbnail(final Tab tab) {
        assert tab.getNativePage() != null || isNativeViewShowing(tab);

        Bitmap nativeBitmap = readbackNativeBitmap(tab, mThumbnailScale);
        if (nativeBitmap == null) return null;
        TabContentManagerJni.get().cacheTabWithBitmap(mNativeTabContentManager,
                TabContentManager.this, tab, nativeBitmap, mThumbnailScale,
                mExpectedThumbnailAspectRatio);
        return nativeBitmap;
    }

    /**
     * Capture the content of a tab as a thumbnail.
     * @param tab The tab whose content we will capture.
     * @param writeToCache Whether write the captured thumbnail to cache. If not, a downsampled
     *                     thumbnail is captured instead.
     * @param callback The callback to send the {@link Bitmap} with.
     */
    private void captureThumbnail(
            @NonNull final Tab tab, boolean writeToCache, @Nullable Callback<Bitmap> callback) {
        assert mNativeTabContentManager != 0;
        assert mSnapshotsEnabled;

        if (tab.getNativePage() != null || isNativeViewShowing(tab)) {
            final float downsamplingScale = 0.5f;
            // If we use readbackNativeBitmap() with a downsampled scale and not saving it through
            // TabContentManagerJni.get().cacheTabWithBitmap( TabContentManager.this, ), the logic
            // of InvalidationAwareThumbnailProvider might prevent captureThumbnail() from getting
            // the latest thumbnail. Therefore, we have to also call cacheNativeTabThumbnail(), and
            // do the downsampling here ourselves. This is less efficient than capturing a
            // downsampled bitmap, but the performance here is not the bottleneck.
            Bitmap bitmap = cacheNativeTabThumbnail(tab);
            if (callback == null) return;
            if (bitmap == null) {
                callback.onResult(null);
                return;
            }
            // In portrait mode, we want to show thumbnails in squares.
            // Therefore, the thumbnail saved in portrait mode needs to be cropped to
            // a square, or it would become too tall and break the layout.
            Matrix matrix = new Matrix();
            matrix.setScale(downsamplingScale, downsamplingScale);
            Bitmap resized = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    Math.min(bitmap.getHeight(),
                            (int) (bitmap.getWidth() * 1.0 / mExpectedThumbnailAspectRatio)),
                    matrix, true);
            callback.onResult(resized);
        } else {
            if (tab.getWebContents() == null) return;
            // If we don't have to write the thumbnail back to the cache, we can use the faster
            // path of capturing a downsampled copy.
            // This faster path is essential to Tab-to-Grid animation to be smooth.
            final float downsamplingScale = writeToCache ? 1 : 0.5f;
            TabContentManagerJni.get().captureThumbnail(mNativeTabContentManager,
                    TabContentManager.this, tab, mThumbnailScale * downsamplingScale,
                    mExpectedThumbnailAspectRatio, writeToCache, callback);
        }
    }

    /**
     * Invalidate a thumbnail if the content of the tab has been changed.
     * @param tabId The id of the {@link Tab} thumbnail to check.
     * @param url   The current URL of the {@link Tab}.
     */
    public void invalidateIfChanged(int tabId, GURL url) {
        if (mNativeTabContentManager != 0) {
            TabContentManagerJni.get().invalidateIfChanged(
                    mNativeTabContentManager, TabContentManager.this, tabId, url);
        }
    }

    /**
     * Invalidate a thumbnail of the tab whose id is |id|.
     * @param id The id of the {@link Tab} thumbnail to check.
     * @param url   The current URL of the {@link Tab}.
     */
    public void invalidateTabThumbnail(int id, GURL url) {
        invalidateIfChanged(id, url);
    }

    /**
     * Update the priority-ordered list of visible tabs.
     * @param priority The list of tab ids ordered in terms of priority.
     */
    public void updateVisibleIds(List<Integer> priority, int primaryTabId) {
        if (mNativeTabContentManager != 0) {
            int idsSize = min(mFullResThumbnailsMaxSize, priority.size());

            if (idsSize != mPriorityTabIds.length) {
                mPriorityTabIds = new int[idsSize];
            }

            for (int i = 0; i < idsSize; i++) {
                mPriorityTabIds[i] = priority.get(i);
            }
            TabContentManagerJni.get().updateVisibleIds(mNativeTabContentManager,
                    TabContentManager.this, mPriorityTabIds, primaryTabId);
        }
    }

    /**
     * Removes a thumbnail of the tab whose id is |tabId|.
     * @param tabId The Id of the tab whose thumbnail is being removed.
     */
    public void removeTabThumbnail(int tabId) {
        if (mNativeTabContentManager != 0) {
            TabContentManagerJni.get().removeTabThumbnail(
                    mNativeTabContentManager, TabContentManager.this, tabId);
        }
    }

    @VisibleForTesting
    public void setCaptureMinRequestTimeForTesting(int timeMs) {
        TabContentManagerJni.get().setCaptureMinRequestTimeForTesting(
                mNativeTabContentManager, TabContentManager.this, timeMs);
    }

    @VisibleForTesting
    public int getPendingReadbacksForTesting() {
        return TabContentManagerJni.get().getPendingReadbacksForTesting(
                mNativeTabContentManager, TabContentManager.this);
    }

    @CalledByNative
    protected void notifyListenersOfThumbnailChange(int tabId) {
        for (ThumbnailChangeListener listener : mListeners) {
            listener.onThumbnailChange(tabId);
        }
    }

    private boolean isNativeViewShowing(Tab tab) {
        return tab != null && tab.isShowingCustomView();
    }

    @NativeMethods
    interface Natives {
        // Class Object Methods
        long init(TabContentManager caller, int defaultCacheSize, int approximationCacheSize,
                int compressionQueueMaxSize, int writeQueueMaxSize,
                boolean useApproximationThumbnail, boolean saveJpegThumbnails, float aspectRatio);

        void attachTab(long nativeTabContentManager, TabContentManager caller, Tab tab, int tabId);
        void detachTab(long nativeTabContentManager, TabContentManager caller, Tab tab, int tabId);
        boolean hasFullCachedThumbnail(
                long nativeTabContentManager, TabContentManager caller, int tabId);
        void captureThumbnail(long nativeTabContentManager, TabContentManager caller, Object tab,
                float thumbnailScale, float aspectRatio, boolean writeToCache,
                Callback<Bitmap> callback);
        void cacheTabWithBitmap(long nativeTabContentManager, TabContentManager caller, Object tab,
                Object bitmap, float thumbnailScale, float aspectRatio);
        void invalidateIfChanged(
                long nativeTabContentManager, TabContentManager caller, int tabId, GURL url);
        void updateVisibleIds(long nativeTabContentManager, TabContentManager caller,
                int[] priority, int primaryTabId);
        void removeTabThumbnail(long nativeTabContentManager, TabContentManager caller, int tabId);
        void getEtc1TabThumbnail(long nativeTabContentManager, TabContentManager caller, int tabId,
                float aspectRatio, Callback<Bitmap> callback);
        void setCaptureMinRequestTimeForTesting(
                long nativeTabContentManager, TabContentManager caller, int timeMs);
        int getPendingReadbacksForTesting(long nativeTabContentManager, TabContentManager caller);
        void destroy(long nativeTabContentManager);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Manage seasons | SCFGC Ranking System</title>
    <link href="/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="/style.css" rel="stylesheet">

    <?php include("fragments/topbar.php") ?>

        <?php include("fragments/sidebar.php") ?>

Manage seasons

                		Season Name
                		Start Date
                		End Date

             		<?php
                /* Print all seasons in database */
                include("db/sql.php");
                $sql_get_seasons = "SELECT * FROM rs_seasons ORDER BY id DESC";
                $seasons = dbQuery($sql_get_seasons);

                foreach($seasons as $season) {
                  echo "
";
                  echo "" . $season["season_name"] . "	";
                  echo "" . $season["date_start"] . "	";
                  echo "" . $season["date_end"] . "	";
                  echo "<button type=\"button\" class=\"btn btn-default\">Edit</button>	";
                  echo "<button type=\"button\" class=\"btn btn-default\">View</button>	";
                  echo "
";
                }
                ?>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:orientation="vertical"
	android:paddingBottom="@dimen/list_entry_padding_vertical"
	android:paddingLeft="@dimen/list_entry_padding_horizontal"
	android:paddingRight="@dimen/list_entry_padding_horizontal"
	android:paddingTop="@dimen/list_entry_padding_vertical" >

	<LinearLayout
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:orientation="horizontal" >

		<TextView
			android:id="@+id/block_list_row_height"
			android:layout_width="0px"
			android:layout_height="wrap_content"
			android:layout_weight="1"
			android:textSize="@dimen/font_size_normal"
			android:textStyle="bold" />

		<TextView
			android:id="@+id/block_list_row_time"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:textSize="@dimen/font_size_normal" />
	</LinearLayout>

	<TextView
		android:id="@+id/block_list_row_hash"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:textSize="@dimen/font_size_normal" />

</LinearLayout>


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32446E_EVAL_CAMERA_H
#define __STM32446E_EVAL_CAMERA_H

#ifdef __cplusplus
 extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
/* Include Camera component Driver */
#include "../Components/s5k5cag/s5k5cag.h"

/* Include IO Driver */
#include "stm32446e_eval_io.h"

/** @addtogroup BSP
  * @{
  */

/** @addtogroup STM32446E_EVAL
  * @{
  */

/** @addtogroup STM32446E_EVAL_CAMERA
  * @{
  */

/** @defgroup STM32446E_EVAL_CAMERA_Exported_Types STM32446E EVAL CAMERA Exported Types
  * @{
  */

/**
  * @brief  Camera State structures definition
  */
typedef enum
{
  CAMERA_OK       = 0x00,
  CAMERA_ERROR    = 0x01,
  CAMERA_TIMEOUT  = 0x02
}Camera_StatusTypeDef;

#define RESOLUTION_R160x120      CAMERA_R160x120      /* QQVGA Resolution     */
#define RESOLUTION_R320x240      CAMERA_R320x240      /* QVGA Resolution      */
#define RESOLUTION_R480x272      CAMERA_R480x272      /* 480x272 Resolution   */
#define RESOLUTION_R640x480      CAMERA_R640x480      /* VGA Resolution       */
/**
  * @}
  */

/** @defgroup STM32446E_EVAL_CAMERA_Exported_Constants STM32446E EVAL CAMERA Exported Constants
  * @{
  */
/**
  * @}
  */

/** @defgroup STM32446E_EVAL_CAMERA_Exported_Functions STM32446E EVAL CAMERA Exported Functions
  * @{
  */
uint8_t BSP_CAMERA_Init(uint32_t Resolution);
uint8_t BSP_CAMERA_DeInit(void);
void    BSP_CAMERA_ContinuousStart(uint8_t *buff);
void    BSP_CAMERA_SnapshotStart(uint8_t *buff);
void    BSP_CAMERA_Suspend(void);
void    BSP_CAMERA_Resume(void);
uint8_t BSP_CAMERA_Stop(void);
void    BSP_CAMERA_HwReset(void);
void    BSP_CAMERA_PwrDown(void);
void    BSP_CAMERA_LineEventCallback(void);
void    BSP_CAMERA_VsyncEventCallback(void);
void    BSP_CAMERA_FrameEventCallback(void);
void    BSP_CAMERA_ErrorCallback(void);

/* Camera features functions prototype */
void    BSP_CAMERA_ContrastBrightnessConfig(uint32_t contrast_level, uint32_t brightness_level);
void    BSP_CAMERA_BlackWhiteConfig(uint32_t Mode);
void    BSP_CAMERA_ColorEffectConfig(uint32_t Effect);

/* To be called in DCMI_IRQHandler function */
void    BSP_CAMERA_IRQHandler(void);
/* To be called in DMA2_Stream1_IRQHandler function */
void    BSP_CAMERA_DMA_IRQHandler(void);

/* These functions can be modified in case the current settings (e.g. DMA stream)
   need to be changed for specific application needs */
void BSP_CAMERA_MspInit(DCMI_HandleTypeDef *hdcmi, void *Params);
void BSP_CAMERA_MspDeInit(DCMI_HandleTypeDef *hdcmi, void *Params);

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

#ifdef __cplusplus
}
#endif

#endif /* __STM32446E_EVAL_CAMERA_H */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/