text:
package com.datastax.oss.driver.core.metadata;

import static com.datastax.oss.driver.assertions.Assertions.assertThat;
import static com.datastax.oss.driver.assertions.Assertions.fail;
import static org.awaitility.Awaitility.await;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.config.DriverExecutionProfile;
import com.datastax.oss.driver.api.core.context.DriverContext;
import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy;
import com.datastax.oss.driver.api.core.loadbalancing.NodeDistance;
import com.datastax.oss.driver.api.core.metadata.EndPoint;
import com.datastax.oss.driver.api.core.metadata.Metadata;
import com.datastax.oss.driver.api.core.metadata.Node;
import com.datastax.oss.driver.api.core.metadata.NodeState;
import com.datastax.oss.driver.api.core.metadata.NodeStateListener;
import com.datastax.oss.driver.api.core.session.Request;
import com.datastax.oss.driver.api.core.session.Session;
import com.datastax.oss.driver.api.testinfra.session.SessionRule;
import com.datastax.oss.driver.api.testinfra.session.SessionUtils;
import com.datastax.oss.driver.api.testinfra.simulacron.SimulacronRule;
import com.datastax.oss.driver.categories.ParallelizableTests;
import com.datastax.oss.driver.internal.core.context.InternalDriverContext;
import com.datastax.oss.driver.internal.core.metadata.DefaultEndPoint;
import com.datastax.oss.driver.internal.core.metadata.DefaultNode;
import com.datastax.oss.driver.internal.core.metadata.NodeStateEvent;
import com.datastax.oss.driver.internal.core.metadata.TopologyEvent;
import com.datastax.oss.simulacron.common.cluster.ClusterSpec;
import com.datastax.oss.simulacron.common.cluster.NodeConnectionReport;
import com.datastax.oss.simulacron.common.stubbing.CloseType;
import com.datastax.oss.simulacron.server.BoundNode;
import com.datastax.oss.simulacron.server.RejectScope;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.time.Duration;
import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.junit.MockitoJUnitRunner;

@Category(ParallelizableTests.class)
@RunWith(MockitoJUnitRunner.class)
public class NodeStateIT {

  private SimulacronRule simulacron = new SimulacronRule(ClusterSpec.builder().withNodes(2));

  private NodeStateListener nodeStateListener = mock(NodeStateListener.class);
  private InOrder inOrder;

  private SessionRule<CqlSession> sessionRule =
      SessionRule.builder(simulacron)
          .withConfigLoader(
              SessionUtils.configLoaderBuilder()
                  .withInt(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE, 2)
                  .withDuration(DefaultDriverOption.RECONNECTION_MAX_DELAY, Duration.ofSeconds(1))
                  .withClass(
                      DefaultDriverOption.LOAD_BALANCING_POLICY_CLASS,
                      NodeStateIT.ConfigurableIgnoresPolicy.class)
                  .build())
          .withNodeStateListener(nodeStateListener)
          .build();

  @Rule public TestRule chain = RuleChain.outerRule(simulacron).around(sessionRule);

  private @Captor ArgumentCaptor<DefaultNode> nodeCaptor;

  private InternalDriverContext driverContext;
  private ConfigurableIgnoresPolicy defaultLoadBalancingPolicy;
  private final BlockingQueue<NodeStateEvent> stateEvents = new LinkedBlockingDeque<>();

  private BoundNode simulacronControlNode;
  private BoundNode simulacronRegularNode;
  private DefaultNode metadataControlNode;
  private DefaultNode metadataRegularNode;

  @Before
  public void setup() {
    inOrder = inOrder(nodeStateListener);

    AtomicBoolean nonInitialEvent = new AtomicBoolean(false);
    driverContext = (InternalDriverContext) sessionRule.session().getContext();
    driverContext
        .getEventBus()
        .register(
            NodeStateEvent.class,
            (e) -> {
              // Skip transition from unknown to up if we haven't received any other events,
              // these may just be the initial events that have typically fired by now, but
              // may not have depending on timing.
              if (!nonInitialEvent.get()
                  && e.oldState == NodeState.UNKNOWN
                  && e.newState == NodeState.UP) {
                return;
              }
              nonInitialEvent.set(true);
              stateEvents.add(e);
            });

    defaultLoadBalancingPolicy =
        (ConfigurableIgnoresPolicy)
            driverContext.getLoadBalancingPolicy(DriverExecutionProfile.DEFAULT_NAME);

    // Sanity check: the driver should have connected to simulacron
    await()
        .alias("Connections established")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .until(
            () ->
                // 1 control connection + 2 pooled connections per node
                simulacron.cluster().getActiveConnections() == 5);

    // Find out which node is the control node, and identify the corresponding Simulacron and driver
    // metadata objects.
    simulacronControlNode = simulacronRegularNode = null;
    for (BoundNode boundNode : simulacron.cluster().getNodes()) {
      if (boundNode.getActiveConnections() == 3) {
        simulacronControlNode = boundNode;
      } else {
        simulacronRegularNode = boundNode;
      }
    }
    assertThat(simulacronControlNode).isNotNull();
    assertThat(simulacronRegularNode).isNotNull();

    Metadata metadata = sessionRule.session().getMetadata();
    metadataControlNode =
        (DefaultNode)
            metadata
                .findNode(simulacronControlNode.inetSocketAddress())
                .orElseThrow(AssertionError::new);
    metadataRegularNode =
        (DefaultNode)
            metadata
                .findNode(simulacronRegularNode.inetSocketAddress())
                .orElseThrow(AssertionError::new);

    // SessionRule uses all nodes as contact points, so we only get onUp notifications for them (no
    // onAdd)
    inOrder.verify(nodeStateListener, timeout(500)).onUp(metadataControlNode);
    inOrder.verify(nodeStateListener, timeout(500)).onUp(metadataRegularNode);
  }

  @After
  public void teardown() {
    reset(nodeStateListener);
  }

  @Test
  public void should_report_connections_for_healthy_nodes() {
    await()
        .alias("Node metadata up-to-date")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () -> {
              assertThat(metadataControlNode).isUp().hasOpenConnections(3).isNotReconnecting();
              assertThat(metadataRegularNode).isUp().hasOpenConnections(2).isNotReconnecting();
            });
  }

  @Test
  public void should_keep_regular_node_up_when_still_one_connection() {
    simulacronRegularNode.rejectConnections(0, RejectScope.UNBIND);
    NodeConnectionReport report = simulacronRegularNode.getConnections();
    simulacron.cluster().closeConnection(report.getConnections().get(0), CloseType.DISCONNECT);

    await()
        .alias("Reconnection started")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () -> assertThat(metadataRegularNode).isUp().hasOpenConnections(1).isReconnecting());
    inOrder.verify(nodeStateListener, never()).onDown(metadataRegularNode);
  }

  @Test
  public void should_mark_regular_node_down_when_no_more_connections() {
    simulacronRegularNode.stop();

    await()
        .alias("Node going down")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () -> assertThat(metadataRegularNode).isDown().hasOpenConnections(0).isReconnecting());

    expect(NodeStateEvent.changed(NodeState.UP, NodeState.DOWN, metadataRegularNode));
    inOrder.verify(nodeStateListener, timeout(500)).onDown(metadataRegularNode);
  }

  @Test
  public void should_mark_control_node_down_when_control_connection_is_last_connection_and_dies() {
    simulacronControlNode.rejectConnections(0, RejectScope.UNBIND);

    // Identify the control connection and close the two other ones
    SocketAddress controlAddress = driverContext.getControlConnection().channel().localAddress();
    NodeConnectionReport report = simulacronControlNode.getConnections();
    for (SocketAddress address : report.getConnections()) {
      if (!address.equals(controlAddress)) {
        simulacron.cluster().closeConnection(address, CloseType.DISCONNECT);
      }
    }
    await()
        .alias("Control node lost its non-control connections")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () -> assertThat(metadataControlNode).isUp().hasOpenConnections(1).isReconnecting());
    inOrder.verify(nodeStateListener, never()).onDown(metadataRegularNode);

    simulacron.cluster().closeConnection(controlAddress, CloseType.DISCONNECT);
    await()
        .alias("Control node going down")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () -> assertThat(metadataControlNode).isDown().hasOpenConnections(0).isReconnecting());
    inOrder.verify(nodeStateListener, timeout(500)).onDown(metadataControlNode);

    expect(NodeStateEvent.changed(NodeState.UP, NodeState.DOWN, metadataControlNode));
  }

  @Test
  public void should_bring_node_back_up_when_reconnection_succeeds() {
    simulacronRegularNode.stop();

    await()
        .alias("Node going down")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () -> assertThat(metadataRegularNode).isDown().hasOpenConnections(0).isReconnecting());
    inOrder.verify(nodeStateListener, timeout(500)).onDown(metadataRegularNode);

    simulacronRegularNode.acceptConnections();

    await()
        .alias("Connections re-established")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () -> assertThat(metadataRegularNode).isUp().hasOpenConnections(2).isNotReconnecting());
    inOrder.verify(nodeStateListener, timeout(500)).onUp(metadataRegularNode);

    expect(
        NodeStateEvent.changed(NodeState.UP, NodeState.DOWN, metadataRegularNode),
        NodeStateEvent.changed(NodeState.DOWN, NodeState.UP, metadataRegularNode));
  }

  @Test
  public void should_apply_up_and_down_topology_events_when_ignored() {
    defaultLoadBalancingPolicy.ignore(metadataRegularNode);

    await()
        .alias("Driver closed all connections to ignored node")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () ->
                assertThat(metadataRegularNode)
                    .isUp()
                    .isIgnored()
                    .hasOpenConnections(0)
                    .isNotReconnecting());

    driverContext
        .getEventBus()
        .fire(TopologyEvent.suggestDown(metadataRegularNode.getBroadcastRpcAddress().get()));
    await()
        .alias("SUGGEST_DOWN event applied")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () ->
                assertThat(metadataRegularNode)
                    .isDown()
                    .isIgnored()
                    .hasOpenConnections(0)
                    .isNotReconnecting());
    inOrder.verify(nodeStateListener, timeout(500)).onDown(metadataRegularNode);

    driverContext
        .getEventBus()
        .fire(TopologyEvent.suggestUp(metadataRegularNode.getBroadcastRpcAddress().get()));
    await()
        .alias("SUGGEST_UP event applied")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () ->
                assertThat(metadataRegularNode)
                    .isUp()
                    .isIgnored()
                    .hasOpenConnections(0)
                    .isNotReconnecting());
    inOrder.verify(nodeStateListener, timeout(500)).onUp(metadataRegularNode);

    defaultLoadBalancingPolicy.stopIgnoring(metadataRegularNode);
  }

  @Test
  public void should_ignore_down_topology_event_when_still_connected() throws InterruptedException {
    driverContext
        .getEventBus()
        .fire(TopologyEvent.suggestDown(metadataRegularNode.getBroadcastRpcAddress().get()));
    TimeUnit.MILLISECONDS.sleep(500);
    assertThat(metadataRegularNode).isUp().hasOpenConnections(2).isNotReconnecting();
  }

  @Test
  public void should_force_immediate_reconnection_when_up_topology_event()
      throws InterruptedException {
    // This test requires a longer reconnection interval, so create a separate driver instance
    DriverConfigLoader loader =
        SessionUtils.configLoaderBuilder()
            .withDuration(DefaultDriverOption.RECONNECTION_BASE_DELAY, Duration.ofHours(1))
            .withDuration(DefaultDriverOption.RECONNECTION_MAX_DELAY, Duration.ofHours(1))
            .build();
    NodeStateListener localNodeStateListener = mock(NodeStateListener.class);
    try (CqlSession session =
        SessionUtils.newSession(simulacron, null, localNodeStateListener, null, null, loader)) {

      BoundNode localSimulacronNode = simulacron.cluster().getNodes().iterator().next();
      assertThat(localSimulacronNode).isNotNull();

      DefaultNode localMetadataNode =
          (DefaultNode)
              session
                  .getMetadata()
                  .findNode(localSimulacronNode.inetSocketAddress())
                  .orElseThrow(AssertionError::new);
      // UP fired a first time as part of the init process
      verify(localNodeStateListener, timeout(500)).onUp(localMetadataNode);

      localSimulacronNode.stop();

      await()
          .alias("Node going down")
          .pollInterval(500, TimeUnit.MILLISECONDS)
          .untilAsserted(
              () -> assertThat(localMetadataNode).isDown().hasOpenConnections(0).isReconnecting());
      verify(localNodeStateListener, timeout(500)).onDown(localMetadataNode);

      expect(NodeStateEvent.changed(NodeState.UP, NodeState.DOWN, localMetadataNode));

      localSimulacronNode.acceptConnections();
      ((InternalDriverContext) session.getContext())
          .getEventBus()
          .fire(TopologyEvent.suggestUp(localMetadataNode.getBroadcastRpcAddress().get()));

      await()
          .alias("Node coming back up")
          .pollInterval(500, TimeUnit.MILLISECONDS)
          .untilAsserted(() -> assertThat(localMetadataNode).isUp().isNotReconnecting());
      verify(localNodeStateListener, timeout(500).times(2)).onUp(localMetadataNode);

      expect(NodeStateEvent.changed(NodeState.DOWN, NodeState.UP, localMetadataNode));
    }
  }

  @Test
  public void should_force_down_when_not_ignored() throws InterruptedException {
    driverContext
        .getEventBus()
        .fire(TopologyEvent.forceDown(metadataRegularNode.getBroadcastRpcAddress().get()));
    await()
        .alias("Node forced down")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () ->
                assertThat(metadataRegularNode)
                    .isForcedDown()
                    .hasOpenConnections(0)
                    .isNotReconnecting());
    inOrder.verify(nodeStateListener, timeout(500)).onDown(metadataRegularNode);

    // Should ignore up/down topology events while forced down
    driverContext
        .getEventBus()
        .fire(TopologyEvent.suggestUp(metadataRegularNode.getBroadcastRpcAddress().get()));
    TimeUnit.MILLISECONDS.sleep(500);
    assertThat(metadataRegularNode).isForcedDown();

    driverContext
        .getEventBus()
        .fire(TopologyEvent.suggestDown(metadataRegularNode.getBroadcastRpcAddress().get()));
    TimeUnit.MILLISECONDS.sleep(500);
    assertThat(metadataRegularNode).isForcedDown();

    // Should only come back up on a FORCE_UP event
    driverContext
        .getEventBus()
        .fire(TopologyEvent.forceUp(metadataRegularNode.getBroadcastRpcAddress().get()));
    await()
        .alias("Node forced back up")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () -> assertThat(metadataRegularNode).isUp().hasOpenConnections(2).isNotReconnecting());
    inOrder.verify(nodeStateListener, timeout(500)).onUp(metadataRegularNode);
  }

  @Test
  public void should_force_down_when_ignored() throws InterruptedException {
    defaultLoadBalancingPolicy.ignore(metadataRegularNode);

    driverContext
        .getEventBus()
        .fire(TopologyEvent.forceDown(metadataRegularNode.getBroadcastRpcAddress().get()));
    await()
        .alias("Node forced down")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () ->
                assertThat(metadataRegularNode)
                    .isForcedDown()
                    .hasOpenConnections(0)
                    .isNotReconnecting());
    inOrder.verify(nodeStateListener, timeout(500)).onDown(metadataRegularNode);

    // Should ignore up/down topology events while forced down
    driverContext
        .getEventBus()
        .fire(TopologyEvent.suggestUp(metadataRegularNode.getBroadcastRpcAddress().get()));
    TimeUnit.MILLISECONDS.sleep(500);
    assertThat(metadataRegularNode).isForcedDown();

    driverContext
        .getEventBus()
        .fire(TopologyEvent.suggestDown(metadataRegularNode.getBroadcastRpcAddress().get()));
    TimeUnit.MILLISECONDS.sleep(500);
    assertThat(metadataRegularNode).isForcedDown();

    // Should only come back up on a FORCE_UP event, will not reopen connections since it is still
    // ignored
    driverContext
        .getEventBus()
        .fire(TopologyEvent.forceUp(metadataRegularNode.getBroadcastRpcAddress().get()));
    await()
        .alias("Node forced back up")
        .pollInterval(500, TimeUnit.MILLISECONDS)
        .untilAsserted(
            () ->
                assertThat(metadataRegularNode)
                    .isUp()
                    .isIgnored()
                    .hasOpenConnections(0)
                    .isNotReconnecting());
    inOrder.verify(nodeStateListener, timeout(500)).onUp(metadataRegularNode);

    defaultLoadBalancingPolicy.stopIgnoring(metadataRegularNode);
  }

  @Test
  public void should_signal_non_contact_points_as_added() {
    // Since we need to observe the behavior of non-contact points, build a dedicated session with
    // just one contact point.
    Iterator<EndPoint> contactPoints = simulacron.getContactPoints().iterator();
    EndPoint endPoint1 = contactPoints.next();
    EndPoint endPoint2 = contactPoints.next();
    NodeStateListener localNodeStateListener = mock(NodeStateListener.class);
    DriverConfigLoader loader =
        SessionUtils.configLoaderBuilder()
            .withDuration(DefaultDriverOption.RECONNECTION_BASE_DELAY, Duration.ofHours(1))
            .withDuration(DefaultDriverOption.RECONNECTION_MAX_DELAY, Duration.ofHours(1))
            .withInt(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE, 0)
            .build();
    try (CqlSession localSession =
        (CqlSession)
            SessionUtils.baseBuilder()
                .addContactEndPoint(endPoint1)
                .withNodeStateListener(localNodeStateListener)
                .withConfigLoader(loader)
                .build()) {

      Metadata metadata = localSession.getMetadata();
      Node localMetadataNode1 = metadata.findNode(endPoint1).orElseThrow(AssertionError::new);
      Node localMetadataNode2 = metadata.findNode(endPoint2).orElseThrow(AssertionError::new);

      // Successful contact point goes to up directly
      verify(localNodeStateListener, timeout(500)).onUp(localMetadataNode1);
      // Non-contact point only added since we don't have a connection or events for it yet
      verify(localNodeStateListener, timeout(500)).onAdd(localMetadataNode2);
    }
  }

  @Test
  public void should_remove_invalid_contact_point() {

    Iterator<EndPoint> contactPoints = simulacron.getContactPoints().iterator();
    EndPoint endPoint1 = contactPoints.next();
    EndPoint endPoint2 = contactPoints.next();
    NodeStateListener localNodeStateListener = mock(NodeStateListener.class);

    // Initialize the driver with 1 wrong address and 1 valid address
    EndPoint wrongContactPoint = withUnusedPort(endPoint1);
    DriverConfigLoader loader =
        SessionUtils.configLoaderBuilder()
            .withDuration(DefaultDriverOption.RECONNECTION_BASE_DELAY, Duration.ofHours(1))
            .withDuration(DefaultDriverOption.RECONNECTION_MAX_DELAY, Duration.ofHours(1))
            .build();
    try (CqlSession localSession =
        (CqlSession)
            SessionUtils.baseBuilder()
                .addContactEndPoint(endPoint1)
                .addContactEndPoint(wrongContactPoint)
                .withNodeStateListener(localNodeStateListener)
                .withConfigLoader(loader)
                .build()) {

      Metadata metadata = localSession.getMetadata();
      assertThat(metadata.findNode(wrongContactPoint)).isEmpty();
      Node localMetadataNode1 = metadata.findNode(endPoint1).orElseThrow(AssertionError::new);
      Node localMetadataNode2 = metadata.findNode(endPoint2).orElseThrow(AssertionError::new);

      // The order of the calls is not deterministic because contact points are shuffled, but it
      // does not matter here since Mockito.verify does not enforce order.
      verify(localNodeStateListener, timeout(500)).onRemove(nodeCaptor.capture());
      assertThat(nodeCaptor.getValue().getEndPoint()).isEqualTo(wrongContactPoint);
      verify(localNodeStateListener, timeout(500)).onUp(localMetadataNode1);
      verify(localNodeStateListener, timeout(500)).onAdd(localMetadataNode2);

      // Note: there might be an additional onDown for wrongContactPoint if it was hit first at
      // init. This is hard to test since the node was removed later, so we simply don't call
      // verifyNoMoreInteractions.
    }
  }

  @Test
  public void should_mark_unreachable_contact_point_down() {
    // This time we connect with two valid contact points, but is unresponsive, it should be marked
    // down
    Iterator<BoundNode> simulacronNodes = simulacron.cluster().getNodes().iterator();
    BoundNode localSimulacronNode1 = simulacronNodes.next();
    BoundNode localSimulacronNode2 = simulacronNodes.next();

    InetSocketAddress address1 = localSimulacronNode1.inetSocketAddress();
    InetSocketAddress address2 = localSimulacronNode2.inetSocketAddress();

    NodeStateListener localNodeStateListener = mock(NodeStateListener.class);

    localSimulacronNode2.stop();
    try {
      // Since contact points are shuffled, we have a 50% chance that our bad contact point will be
      // hit first. So we retry the scenario a few times if needed.
      DriverConfigLoader loader =
          SessionUtils.configLoaderBuilder()
              .withDuration(DefaultDriverOption.RECONNECTION_BASE_DELAY, Duration.ofHours(1))
              .withDuration(DefaultDriverOption.RECONNECTION_MAX_DELAY, Duration.ofHours(1))
              .build();
      for (int i = 0; i < 10; i++) {
        try (CqlSession localSession =
            (CqlSession)
                SessionUtils.baseBuilder()
                    .addContactPoint(address1)
                    .addContactPoint(address2)
                    .withNodeStateListener(localNodeStateListener)
                    .withConfigLoader(loader)
                    .build()) {

          Metadata metadata = localSession.getMetadata();
          Node localMetadataNode1 = metadata.findNode(address1).orElseThrow(AssertionError::new);
          Node localMetadataNode2 = metadata.findNode(address2).orElseThrow(AssertionError::new);
          if (localMetadataNode2.getState() == NodeState.DOWN) {
            // Stopped node was tried first and marked down, that's our target scenario
            verify(localNodeStateListener, timeout(500)).onDown(localMetadataNode2);
            verify(localNodeStateListener, timeout(500)).onUp(localMetadataNode1);
            verify(localNodeStateListener, timeout(500)).onSessionReady(localSession);
            verifyNoMoreInteractions(localNodeStateListener);
            return;
          } else {
            // Stopped node was not tried
            assertThat(localMetadataNode2).isUnknown();
            verify(localNodeStateListener, timeout(500)).onUp(localMetadataNode1);
            verifyNoMoreInteractions(localNodeStateListener);
          }
        }
        reset(localNodeStateListener);
      }
      fail("Couldn't get the driver to try stopped node first (tried 5 times)");
    } finally {
      localSimulacronNode2.acceptConnections();
    }
  }

  private void expect(NodeStateEvent... expectedEvents) {
    for (NodeStateEvent expected : expectedEvents) {
      try {
        NodeStateEvent actual = stateEvents.poll(10, TimeUnit.SECONDS);
        assertThat(actual).isNotNull();

        // Don't compare events directly: some tests call this method with nodes obtained from
        // another session instance, and nodes are compared by reference.
        assertThat(actual.oldState).isEqualTo(expected.oldState);
        assertThat(actual.newState).isEqualTo(expected.newState);
        assertThat(actual.node.getHostId()).isEqualTo(expected.node.getHostId());
      } catch (InterruptedException e) {
        fail("Interrupted while waiting for event");
      }
    }
  }

  // Generates an endpoint that is not the connect address of one of the nodes in the cluster
  private EndPoint withUnusedPort(EndPoint endPoint) {
    InetSocketAddress address = (InetSocketAddress) endPoint.resolve();
    return new DefaultEndPoint(new InetSocketAddress(address.getAddress(), findAvailablePort()));
  }

  /**
   * Finds an available port in the ephemeral range. This is loosely inspired by Apache MINA's
   * AvailablePortFinder.
   */
  private static synchronized int findAvailablePort() throws RuntimeException {
    // let the system pick an ephemeral port
    try (ServerSocket ss = new ServerSocket(0)) {
      ss.setReuseAddress(true);
      return ss.getLocalPort();
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }

  /**
   * A load balancing policy that can be told to ignore a node temporarily (the rest of the
   * implementation uses a simple round-robin, non DC-aware shuffle).
   */
  public static class ConfigurableIgnoresPolicy implements LoadBalancingPolicy {

    private final CopyOnWriteArraySet<Node> liveNodes = new CopyOnWriteArraySet<>();
    private final AtomicInteger offset = new AtomicInteger();
    private final Set<Node> ignoredNodes = new CopyOnWriteArraySet<>();

    private volatile DistanceReporter distanceReporter;

    public ConfigurableIgnoresPolicy(
        @SuppressWarnings("unused") DriverContext context,
        @SuppressWarnings("unused") String profileName) {
      // nothing to do
    }

    @Override
    public void init(@NonNull Map<UUID, Node> nodes, @NonNull DistanceReporter distanceReporter) {
      this.distanceReporter = distanceReporter;
      for (Node node : nodes.values()) {
        liveNodes.add(node);
        distanceReporter.setDistance(node, NodeDistance.LOCAL);
      }
    }

    public void ignore(Node node) {
      if (ignoredNodes.add(node)) {
        liveNodes.remove(node);
        distanceReporter.setDistance(node, NodeDistance.IGNORED);
      }
    }

    public void stopIgnoring(Node node) {
      if (ignoredNodes.remove(node)) {
        distanceReporter.setDistance(node, NodeDistance.LOCAL);
        // There might be a short delay until the node's pool becomes usable, but clients know how
        // to deal with that.
        liveNodes.add(node);
      }
    }

    @NonNull
    @Override
    public Queue<Node> newQueryPlan(@NonNull Request request, @NonNull Session session) {
      Object[] snapshot = liveNodes.toArray();
      Queue<Node> queryPlan = new ConcurrentLinkedQueue<>();
      int start = offset.getAndIncrement(); // Note: offset overflow won't be an issue in tests
      for (int i = 0; i < snapshot.length; i++) {
        queryPlan.add((Node) snapshot[(start + i) % snapshot.length]);
      }
      return queryPlan;
    }

    @Override
    public void onAdd(@NonNull Node node) {
      if (ignoredNodes.contains(node)) {
        distanceReporter.setDistance(node, NodeDistance.IGNORED);
      } else {
        // Setting to a non-ignored distance triggers the session to open a pool, which will in turn
        // set the node UP when the first channel gets opened.
        distanceReporter.setDistance(node, NodeDistance.LOCAL);
      }
    }

    @Override
    public void onUp(@NonNull Node node) {
      if (!ignoredNodes.contains(node)) {
        liveNodes.add(node);
      }
    }

    @Override
    public void onDown(@NonNull Node node) {
      liveNodes.remove(node);
    }

    @Override
    public void onRemove(@NonNull Node node) {
      liveNodes.remove(node);
    }

    @Override
    public void close() {
      // nothing to do
    }
  }
}


text:
   This file implements Batch Normalization as described in the paper:
   "Batch Normalization: Accelerating Deep Network Training
                         by Reducing Internal Covariate Shift"
                   by Sergey Ioffe, Christian Szegedy

   This implementation is useful for inputs NOT coming from convolution layers.
   For convolution layers, use nn.SpatialBatchNormalization.

   The operation implemented is:
   y =     ( x - mean(x) )
        -------------------- * gamma + beta
        standard-deviation(x)
   where gamma and beta are learnable parameters.

   The learning of gamma and beta is optional.

   Usage:
   with    learnable parameters: nn.BatchNormalization(N [,eps] [,momentum])
                                 where N = dimensionality of input
   without learnable parameters: nn.BatchNormalization(N [,eps] [,momentum], false)

   eps is a small value added to the standard-deviation to avoid divide-by-zero.
       Defaults to 1e-5

   In training time, this layer keeps a running estimate of it's computed mean and std.
   The running sum is kept with a default momentum of 0.1 (unless over-ridden)
   In test time, this running mean/std is used to normalize.
]]--
local BN,parent = torch.class('nn.BatchNormalization', 'nn.Module')
local THNN = require 'nn.THNN'

BN.__version = 2

-- expected dimension of input
BN.nDim = 2

function BN:__init(nOutput, eps, momentum, affine)
   parent.__init(self)
   assert(nOutput and type(nOutput) == 'number',
          'Missing argument #1: dimensionality of input. ')
   assert(nOutput ~= 0, 'To set affine=false call BatchNormalization'
     .. '(nOutput,  eps, momentum, false) ')
   if affine ~= nil then
      assert(type(affine) == 'boolean', 'affine has to be true/false')
      self.affine = affine
   else
      self.affine = true
   end
   self.eps = eps or 1e-5
   self.train = true
   self.momentum = momentum or 0.1
   self.running_mean = torch.zeros(nOutput)
   self.running_var = torch.ones(nOutput)

   if self.affine then
      self.weight = torch.Tensor(nOutput)
      self.bias = torch.Tensor(nOutput)
      self.gradWeight = torch.Tensor(nOutput)
      self.gradBias = torch.Tensor(nOutput)
      self:reset()
   end
end

function BN:reset()
   if self.weight then
      self.weight:uniform()
   end
   if self.bias then
      self.bias:zero()
   end
   self.running_mean:zero()
   self.running_var:fill(1)
end

function BN:checkInputDim(input)
   local iDim = input:dim()
   assert(iDim == self.nDim or
              (iDim == self.nDim - 1 and self.train == false), string.format(
      'only mini-batch supported (%dD tensor), got %dD tensor instead',
      self.nDim, iDim))
   local featDim = (iDim == self.nDim - 1) and 1 or 2
   assert(input:size(featDim) == self.running_mean:nElement(), string.format(
      'got %d-feature tensor, expected %d',
      input:size(featDim), self.running_mean:nElement()))
end

local function makeContiguous(self, input, gradOutput)
   if not input:isContiguous() then
      self._input = self._input or input.new()
      self._input:resizeAs(input):copy(input)
      input = self._input
   end
   if gradOutput then
      if not gradOutput:isContiguous() then
         self._gradOutput = self._gradOutput or gradOutput.new()
         self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
         gradOutput = self._gradOutput
      end
   end
   return input, gradOutput
end

local function makeBatch(self, input)
    local iDim = input:dim()
    if self.train == false and iDim == self.nDim - 1 then
        return nn.utils.addSingletonDimension(input, input, 1)
    else
        return input
    end
end

function BN:updateOutput(input)
   self:checkInputDim(input)

   input = makeContiguous(self, input)
   input = makeBatch(self, input)

   self.save_mean = self.save_mean or input.new()
   self.save_mean:resizeAs(self.running_mean)
   self.save_std = self.save_std or input.new()
   self.save_std:resizeAs(self.running_var)

   input.THNN.BatchNormalization_updateOutput(
      input:cdata(),
      self.output:cdata(),
      THNN.optionalTensor(self.weight),
      THNN.optionalTensor(self.bias),
      self.running_mean:cdata(),
      self.running_var:cdata(),
      self.save_mean:cdata(),
      self.save_std:cdata(),
      self.train,
      self.momentum,
      self.eps)

   return self.output
end

local function backward(self, input, gradOutput, scale, gradInput, gradWeight, gradBias)
   self:checkInputDim(input)
   self:checkInputDim(gradOutput)
   assert(self.save_mean and self.save_std, 'must call :updateOutput() first')

   input, gradOutput = makeContiguous(self, input, gradOutput)
   input = makeBatch(self, input)
   gradOutput = makeBatch(self, gradOutput)

   scale = scale or 1
   if gradInput then
      gradInput:resizeAs(gradOutput)
   end

   input.THNN.BatchNormalization_backward(
      input:cdata(),
      gradOutput:cdata(),
      THNN.optionalTensor(gradInput),
      THNN.optionalTensor(gradWeight),
      THNN.optionalTensor(gradBias),
      THNN.optionalTensor(self.weight),
      self.running_mean:cdata(),
      self.running_var:cdata(),
      self.save_mean:cdata(),
      self.save_std:cdata(),
      self.train,
      scale,
      self.eps)

   return self.gradInput
end

function BN:backward(input, gradOutput, scale)
   return backward(self, input, gradOutput, scale, self.gradInput, self.gradWeight, self.gradBias)
end

function BN:updateGradInput(input, gradOutput)
   return backward(self, input, gradOutput, 1, self.gradInput)
end

function BN:accGradParameters(input, gradOutput, scale)
   return backward(self, input, gradOutput, scale, nil, self.gradWeight, self.gradBias)
end

function BN:read(file, version)
   parent.read(self, file)
   if version < 2 then
      if self.running_std then
         self.running_var = self.running_std:pow(-2):add(-self.eps)
         self.running_std = nil
      end
   end
end

function BN:clearState()
   -- first 5 buffers are not present in the current implementation,
   -- but we keep them for cleaning old saved models
   nn.utils.clear(self, {
      'buffer',
      'buffer2',
      'centered',
      'std',
      'normalized',
      '_input',
      '_gradOutput',
      'save_mean',
      'save_std',
   })
   return parent.clearState(self)
end

function BN:__tostring__()
   return string.format('%s (%dD) (%d)', torch.type(self), self.nDim, self.running_mean:nElement())
end

redpajama_set_name: RedPajamaGithub


text:
What issue is this PR targeting? If there is no issue that addresses the problem, please open a corresponding issue and link it here.

Please read our [documentation](https://github.com/Project-OSRM/osrm-backend/blob/master/docs/releasing.md) on release and version management.
If your PR is still work in progress please attach the relevant label.

## Tasklist

 - [ ] CHANGELOG.md entry ([How to write a changelog entry](http://keepachangelog.com/en/1.0.0/#how))
 - [ ] update relevant [Wiki pages](https://github.com/Project-OSRM/osrm-backend/wiki)
 - [ ] add tests (see [testing documentation](https://github.com/Project-OSRM/osrm-backend/blob/master/docs/testing.md))
 - [ ] review
 - [ ] adjust for comments
 - [ ] cherry pick to release branch

## Requirements / Relations

 Link any requirements here. Other pull requests this PR is based on?


text:
Plugin.define "Infinet-Wireless-WANFleX-Router" do
author "Brendan Coles <bcoles@gmail.com>" # 2011-08-13
version "0.1"
description "Infinet Wireless WANFleX Router"
website "http://www.infinetwireless.com/products"

# ShodanHQ results as at 2011-08-13 #
# 554 for WANFlex HTTP Daemon

# Google results as at 2011-08-13 #
# intitle:"Login Page" "InfiNet Wireless" "All rights reserved." "User Name" +Password

# Dorks #
dorks [
'intitle:"Login Page" "InfiNet Wireless" "All rights reserved." "User Name" "Password"'
]

# Matches #
matches [

# Meta Generator
{ :text=>'<meta name="generator" content="InfiNet Wireless Company" />' },

# Version Detection # Server Header
{ :search=>"headers[server]", :version=>/^WANFlex HTTP Daemon v([^\s]+)$/ },

]

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>red5-client</artifactId>
    <packaging>jar</packaging>
    <name>Red5 :: Client</name>
    <description>The Red5 client</description>
    <groupId>org.red5</groupId>
    <version>1.0.7-SNAPSHOT</version>
    <url>https://github.com/Red5/red5-client</url>
    <inceptionYear>2005</inceptionYear>
    <organization>
        <name>Red5</name>
        <url>https://github.com/Red5</url>
    </organization>
    <licenses>
        <license>
            <name>Apache 2</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
            <comments>A business-friendly OSS license</comments>
        </license>
    </licenses>
    <mailingLists>
        <mailingList>
            <name>red5-interest</name>
            <post>https://groups.google.com/forum/?fromgroups#!forum/red5interest</post>
        </mailingList>
    </mailingLists>
    <issueManagement>
        <system>github</system>
        <url>https://github.com/Red5/red5-client/issues</url>
    </issueManagement>
    <scm>
        <url>https://github.com/Red5/red5-client.git</url>
        <connection>scm:git:git@github.com:Red5/red5-client.git</connection>
        <developerConnection>scm:git:git@github.com:Red5/red5-client.git</developerConnection>
    </scm>
    <developers>
        <developer>
            <id>Dominick Accattato</id>
            <email>dominick@red5.org</email>
        </developer>
        <developer>
            <id>Paul Gregoire</id>
            <email>mondain@gmail.com</email>
        </developer>
        <developer>
            <id>Dan Rossi</id>
            <email>electroteque@gmail.com</email>
        </developer>
        <developer>
            <id>Tiago Jacobs</id>
            <email>tiago.jacobs@gmail.com</email>
        </developer>
    </developers>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <red5-common.version>1.0.7-SNAPSHOT</red5-common.version>
        <red5-io.version>1.0.7-SNAPSHOT</red5-io.version>
        <spring.version>4.1.7.RELEASE</spring.version>
        <mina.version>2.0.9</mina.version>
        <slf4j.version>1.7.9</slf4j.version>
        <logback.version>1.1.2</logback.version>
        <bc.version>1.52</bc.version>
        <junit.version>4.12</junit.version>
    </properties>
    <repositories>
        <repository>
            <id>sonatype-snapshots</id>
            <name>Sonatype Snapshots</name>
            <url>http://oss.sonatype.org/content/repositories/snapshots</url>
        </repository>
        <repository>
            <id>sonatype-releases</id>
            <name>Sonatype Releases</name>
            <url>http://oss.sonatype.org/content/repositories/releases</url>
        </repository>
    </repositories>
    <build>
        <defaultGoal>install</defaultGoal>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/java</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </testResource>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
            <testResource>
                <directory>src/test/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </testResource>
        </testResources>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <compilerVersion>1.6</compilerVersion>
                    <fork>true</fork>
                    <source>1.6</source>
                    <target>1.6</target>
                    <executable>${maven.compiler.executable}</executable>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.1</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <verbose>true</verbose>
                    <failOnError>false</failOnError>
                    <sourcepath>${basedir}/src/main/java</sourcepath>
                    <includeDependencySources>false</includeDependencySources>
                    <dependencySourceIncludes>
                        <dependencySourceInclude>org.red5:*</dependencySourceInclude>
                    </dependencySourceIncludes>
                    <detectOfflineLinks>false</detectOfflineLinks>
                    <stylesheetfile>javadoc.css</stylesheetfile>
                    <links>
                        <link>http://download.oracle.com/javase/6/docs/api</link>
                        <link>http://jetty.codehaus.org/jetty/jetty-6/apidocs</link>
                        <link>http://docs.spring.io/spring/docs/4.0.x/javadoc-api</link>
                        <link>http://www.slf4j.org/api</link>
                        <link>http://logging.apache.org/log4j/1.2/apidocs</link>
                        <link>http://groovy.codehaus.org/api</link>
                        <link>http://tomcat.apache.org/tomcat-6.0-doc/api</link>
                        <link>http://ehcache.org/apidocs</link>
                    </links>
                    <tags>
                        <tag>
                            <name>todo</name>
                            <!-- todo tag for all places -->
                            <placement>a</placement>
                            <head>To do:</head>
                        </tag>
                    </tags>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                        </manifest>
                        <manifestEntries>
                            <SCM-Revision>${buildNumber}</SCM-Revision>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>2.7</version>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>2.3.7</version>
                <extensions>true</extensions>
            </plugin>
            <plugin>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                    <useReleaseProfile>false</useReleaseProfile>
                    <releaseProfiles>release</releaseProfiles>
                    <goals>deploy</goals>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.red5</groupId>
                <artifactId>red5-server-common</artifactId>
                <version>${red5-common.version}</version>
            </dependency>
            <dependency>
                <groupId>org.red5</groupId>
                <artifactId>red5-io</artifactId>
                <version>${red5-io.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.red5</groupId>
            <artifactId>red5-server-common</artifactId>
        </dependency>
        <dependency>
            <groupId>org.red5</groupId>
            <artifactId>red5-io</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.mina</groupId>
            <artifactId>mina-core</artifactId>
            <version>${mina.version}</version>
            <type>bundle</type>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>${bc.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.2</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
                <exclusion>
                    <artifactId>commons-codec</artifactId>
                    <groupId>commons-codec</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>
    <profiles>
        <profile>
            <id>release</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.sonatype.plugins</groupId>
                        <artifactId>nexus-staging-maven-plugin</artifactId>
                        <version>1.6.3</version>
                        <extensions>true</extensions>
                        <configuration>
                            <serverId>ossrh</serverId>
                            <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                            <autoReleaseAfterClose>true</autoReleaseAfterClose>
                        </configuration>
                    </plugin>
                    <plugin>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
            <distributionManagement>
                <snapshotRepository>
                    <id>ossrh</id>
                    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
                </snapshotRepository>
                <repository>
                    <id>ossrh</id>
                    <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
                </repository>
            </distributionManagement>
        </profile>
        <profile>
            <id>updatebuildnumber</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>buildnumber-maven-plugin</artifactId>
                        <version>1.2</version>
                        <executions>
                            <execution>
                                <phase>validate</phase>
                                <goals>
                                    <goal>create</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <doCheck>false</doCheck>
                            <doUpdate>false</doUpdate>
                            <shortRevisionLength>5</shortRevisionLength>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
package billing

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/tracing"
	"net/http"
)

// RoleDefinitionsClient is the billing client provides access to billing resources for Azure subscriptions.
type RoleDefinitionsClient struct {
	BaseClient
}

// NewRoleDefinitionsClient creates an instance of the RoleDefinitionsClient client.
func NewRoleDefinitionsClient(subscriptionID string) RoleDefinitionsClient {
	return NewRoleDefinitionsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewRoleDefinitionsClientWithBaseURI creates an instance of the RoleDefinitionsClient client.
func NewRoleDefinitionsClientWithBaseURI(baseURI string, subscriptionID string) RoleDefinitionsClient {
	return RoleDefinitionsClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// GetByBillingAccountName gets the role definition for a role
// Parameters:
// billingAccountName - billing Account Id.
// billingRoleDefinitionName - role definition id.
func (client RoleDefinitionsClient) GetByBillingAccountName(ctx context.Context, billingAccountName string, billingRoleDefinitionName string) (result RoleDefinition, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/RoleDefinitionsClient.GetByBillingAccountName")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.GetByBillingAccountNamePreparer(ctx, billingAccountName, billingRoleDefinitionName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "GetByBillingAccountName", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetByBillingAccountNameSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "GetByBillingAccountName", resp, "Failure sending request")
		return
	}

	result, err = client.GetByBillingAccountNameResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "GetByBillingAccountName", resp, "Failure responding to request")
	}

	return
}

// GetByBillingAccountNamePreparer prepares the GetByBillingAccountName request.
func (client RoleDefinitionsClient) GetByBillingAccountNamePreparer(ctx context.Context, billingAccountName string, billingRoleDefinitionName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName":        autorest.Encode("path", billingAccountName),
		"billingRoleDefinitionName": autorest.Encode("path", billingRoleDefinitionName),
	}

	const APIVersion = "2018-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/providers/Microsoft.Billing/billingRoleDefinitions/{billingRoleDefinitionName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetByBillingAccountNameSender sends the GetByBillingAccountName request. The method will close the
// http.Response Body if it receives an error.
func (client RoleDefinitionsClient) GetByBillingAccountNameSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// GetByBillingAccountNameResponder handles the response to the GetByBillingAccountName request. The method always
// closes the http.Response Body.
func (client RoleDefinitionsClient) GetByBillingAccountNameResponder(resp *http.Response) (result RoleDefinition, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// GetByBillingProfileName gets the role definition for a role
// Parameters:
// billingAccountName - billing Account Id.
// billingProfileName - billing Profile Id.
// billingRoleDefinitionName - role definition id.
func (client RoleDefinitionsClient) GetByBillingProfileName(ctx context.Context, billingAccountName string, billingProfileName string, billingRoleDefinitionName string) (result RoleDefinition, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/RoleDefinitionsClient.GetByBillingProfileName")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.GetByBillingProfileNamePreparer(ctx, billingAccountName, billingProfileName, billingRoleDefinitionName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "GetByBillingProfileName", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetByBillingProfileNameSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "GetByBillingProfileName", resp, "Failure sending request")
		return
	}

	result, err = client.GetByBillingProfileNameResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "GetByBillingProfileName", resp, "Failure responding to request")
	}

	return
}

// GetByBillingProfileNamePreparer prepares the GetByBillingProfileName request.
func (client RoleDefinitionsClient) GetByBillingProfileNamePreparer(ctx context.Context, billingAccountName string, billingProfileName string, billingRoleDefinitionName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName":        autorest.Encode("path", billingAccountName),
		"billingProfileName":        autorest.Encode("path", billingProfileName),
		"billingRoleDefinitionName": autorest.Encode("path", billingRoleDefinitionName),
	}

	const APIVersion = "2018-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/providers/Microsoft.Billing/billingRoleDefinitions/{billingRoleDefinitionName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetByBillingProfileNameSender sends the GetByBillingProfileName request. The method will close the
// http.Response Body if it receives an error.
func (client RoleDefinitionsClient) GetByBillingProfileNameSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// GetByBillingProfileNameResponder handles the response to the GetByBillingProfileName request. The method always
// closes the http.Response Body.
func (client RoleDefinitionsClient) GetByBillingProfileNameResponder(resp *http.Response) (result RoleDefinition, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// GetByInvoiceSectionName gets the role definition for a role
// Parameters:
// billingAccountName - billing Account Id.
// invoiceSectionName - invoiceSection Id.
// billingRoleDefinitionName - role definition id.
func (client RoleDefinitionsClient) GetByInvoiceSectionName(ctx context.Context, billingAccountName string, invoiceSectionName string, billingRoleDefinitionName string) (result RoleDefinition, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/RoleDefinitionsClient.GetByInvoiceSectionName")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.GetByInvoiceSectionNamePreparer(ctx, billingAccountName, invoiceSectionName, billingRoleDefinitionName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "GetByInvoiceSectionName", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetByInvoiceSectionNameSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "GetByInvoiceSectionName", resp, "Failure sending request")
		return
	}

	result, err = client.GetByInvoiceSectionNameResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "GetByInvoiceSectionName", resp, "Failure responding to request")
	}

	return
}

// GetByInvoiceSectionNamePreparer prepares the GetByInvoiceSectionName request.
func (client RoleDefinitionsClient) GetByInvoiceSectionNamePreparer(ctx context.Context, billingAccountName string, invoiceSectionName string, billingRoleDefinitionName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName":        autorest.Encode("path", billingAccountName),
		"billingRoleDefinitionName": autorest.Encode("path", billingRoleDefinitionName),
		"invoiceSectionName":        autorest.Encode("path", invoiceSectionName),
	}

	const APIVersion = "2018-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoiceSections/{invoiceSectionName}/providers/Microsoft.Billing/billingRoleDefinitions/{billingRoleDefinitionName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetByInvoiceSectionNameSender sends the GetByInvoiceSectionName request. The method will close the
// http.Response Body if it receives an error.
func (client RoleDefinitionsClient) GetByInvoiceSectionNameSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// GetByInvoiceSectionNameResponder handles the response to the GetByInvoiceSectionName request. The method always
// closes the http.Response Body.
func (client RoleDefinitionsClient) GetByInvoiceSectionNameResponder(resp *http.Response) (result RoleDefinition, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// ListByBillingAccountName lists the role definition for a billing account
// Parameters:
// billingAccountName - billing Account Id.
func (client RoleDefinitionsClient) ListByBillingAccountName(ctx context.Context, billingAccountName string) (result RoleDefinitionListResult, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/RoleDefinitionsClient.ListByBillingAccountName")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.ListByBillingAccountNamePreparer(ctx, billingAccountName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "ListByBillingAccountName", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByBillingAccountNameSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "ListByBillingAccountName", resp, "Failure sending request")
		return
	}

	result, err = client.ListByBillingAccountNameResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "ListByBillingAccountName", resp, "Failure responding to request")
	}

	return
}

// ListByBillingAccountNamePreparer prepares the ListByBillingAccountName request.
func (client RoleDefinitionsClient) ListByBillingAccountNamePreparer(ctx context.Context, billingAccountName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName": autorest.Encode("path", billingAccountName),
	}

	const APIVersion = "2018-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/providers/Microsoft.Billing/billingRoleDefinitions", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListByBillingAccountNameSender sends the ListByBillingAccountName request. The method will close the
// http.Response Body if it receives an error.
func (client RoleDefinitionsClient) ListByBillingAccountNameSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// ListByBillingAccountNameResponder handles the response to the ListByBillingAccountName request. The method always
// closes the http.Response Body.
func (client RoleDefinitionsClient) ListByBillingAccountNameResponder(resp *http.Response) (result RoleDefinitionListResult, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// ListByBillingProfileName lists the role definition for a Billing Profile
// Parameters:
// billingAccountName - billing Account Id.
// billingProfileName - billing Profile Id.
func (client RoleDefinitionsClient) ListByBillingProfileName(ctx context.Context, billingAccountName string, billingProfileName string) (result RoleDefinitionListResult, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/RoleDefinitionsClient.ListByBillingProfileName")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.ListByBillingProfileNamePreparer(ctx, billingAccountName, billingProfileName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "ListByBillingProfileName", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByBillingProfileNameSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "ListByBillingProfileName", resp, "Failure sending request")
		return
	}

	result, err = client.ListByBillingProfileNameResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "ListByBillingProfileName", resp, "Failure responding to request")
	}

	return
}

// ListByBillingProfileNamePreparer prepares the ListByBillingProfileName request.
func (client RoleDefinitionsClient) ListByBillingProfileNamePreparer(ctx context.Context, billingAccountName string, billingProfileName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName": autorest.Encode("path", billingAccountName),
		"billingProfileName": autorest.Encode("path", billingProfileName),
	}

	const APIVersion = "2018-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/providers/Microsoft.Billing/billingRoleDefinitions", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListByBillingProfileNameSender sends the ListByBillingProfileName request. The method will close the
// http.Response Body if it receives an error.
func (client RoleDefinitionsClient) ListByBillingProfileNameSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// ListByBillingProfileNameResponder handles the response to the ListByBillingProfileName request. The method always
// closes the http.Response Body.
func (client RoleDefinitionsClient) ListByBillingProfileNameResponder(resp *http.Response) (result RoleDefinitionListResult, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// ListByInvoiceSectionName lists the role definition for an invoice Section
// Parameters:
// billingAccountName - billing Account Id.
// invoiceSectionName - invoiceSection Id.
func (client RoleDefinitionsClient) ListByInvoiceSectionName(ctx context.Context, billingAccountName string, invoiceSectionName string) (result RoleDefinitionListResult, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/RoleDefinitionsClient.ListByInvoiceSectionName")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.ListByInvoiceSectionNamePreparer(ctx, billingAccountName, invoiceSectionName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "ListByInvoiceSectionName", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByInvoiceSectionNameSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "ListByInvoiceSectionName", resp, "Failure sending request")
		return
	}

	result, err = client.ListByInvoiceSectionNameResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.RoleDefinitionsClient", "ListByInvoiceSectionName", resp, "Failure responding to request")
	}

	return
}

// ListByInvoiceSectionNamePreparer prepares the ListByInvoiceSectionName request.
func (client RoleDefinitionsClient) ListByInvoiceSectionNamePreparer(ctx context.Context, billingAccountName string, invoiceSectionName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName": autorest.Encode("path", billingAccountName),
		"invoiceSectionName": autorest.Encode("path", invoiceSectionName),
	}

	const APIVersion = "2018-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoiceSections/{invoiceSectionName}/providers/Microsoft.Billing/billingRoleDefinitions", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListByInvoiceSectionNameSender sends the ListByInvoiceSectionName request. The method will close the
// http.Response Body if it receives an error.
func (client RoleDefinitionsClient) ListByInvoiceSectionNameSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// ListByInvoiceSectionNameResponder handles the response to the ListByInvoiceSectionName request. The method always
// closes the http.Response Body.
func (client RoleDefinitionsClient) ListByInvoiceSectionNameResponder(resp *http.Response) (result RoleDefinitionListResult, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}


text:
/**
 * Jabber-RPC plugin (XEP-0009)
 * Allow the management of RPC
 */
Strophe.addConnectionPlugin("rpc", {

  _connection : undefined,

  _whitelistEnabled : false,

  jidWhiteList : [],
  nodeWhiteList : [],
  domainWhiteList : [],

  /**
   * Plugin init
   *
   * @param  {Strophe.Connection} connection Strophe connection
   */
  init: function(connection) {

    this._connection = connection;

    this._whitelistEnabled = false;

    this.jidWhiteList    = [];
    this.nodeWhiteList   = [];
    this.domainWhiteList = [];

    Strophe.addNamespace("RPC", "jabber:iq:rpc");

    if (!connection.hasOwnProperty("disco")) {
      Strophe.warn("You need the discovery plugin " +
                   "to have Jabber-RPC fully implemented.");
    }
    else {
      this._connection.disco.addIdentity("automation", "rpc");
      this._connection.disco.addFeature(Strophe.NS.RPC);
    }
  },

  /**
   * Add a jid or an array of jids to
   * the whitelist.
   * It's possible to use wildecards for the domain
   * or the node. ie:
   *   *@*
   *   myname@*
   *   *@jabber.org
   *
   * @param {String|Array} jid
   */
  addJidToWhiteList: function(jids) {
    if (typeof(jids.sort) !== "function") {
      jids = [jids];
    }

    for (var i = 0; i < jids.length; i++) {
      var jid = jids[i];

      if (jid === "*@*") {
        this._whitelistEnabled = false;
        return;
      }

      var node   = Strophe.getNodeFromJid(jid);
      var domain = Strophe.getDomainFromJid(jid);
      if (jid) {
        if (node === "*") {
          this.domainWhiteList.push(domain);
        } else if (domain === "*") {
          this.nodeWhiteList.push(node);
        } else {
          this.jidWhiteList.push(jid);
        }
        this._whitelistEnabled = true;
      }
    }
  },

  /**
   * Helper to filter out Jid outside of the whitelists
   *
   * @param  {String} jid Jid to test
   * @return {Boolean}
   */
  _jidInWhitelist: function(jid) {
    if (!this._whitelistEnabled)
      return true;

    if (jid === this._connection.jid)
      return true;

    return (
      this.domainWhiteList.indexOf(Strophe.getDomainFromJid(jid)) !== -1  ||
      this.nodeWhiteList.indexOf(Strophe.getNodeFromJid(jid))     !== -1  ||
      this.jidWhiteList.indexOf(jid) !== -1
    );
  },

  /**
   * Send a request message
   *
   * @param  {Object} id     ID of the request
   * @param  {String} to     JID of the recipient
   * @param  {String} method name of the method
   * @param  {Array}  params Array of parameters
   */
  sendRequest: function(id, to, method, params) {
    params = (typeof(params.sort) === "function") ? params : [params];

    var element = new Strophe.Builder("methodCall")
      .c("methodName").t(method)
      .up()
      .c("params");

    for (var i = 0; i < params.length; i++) {
      element.c("param")
        .cnode(this._convertToXML(params[i]))
        .up().up();
    }

    this.sendXMLElement(id, to, "set", element.tree());
  },

  /**
   * Send a response message
   *
   * @param  {String} id     ID of the request
   * @param  {String} to     JID of the recipient
   * @param  {Object} result Result of the function call
   */
  sendResponse: function(id, to, result) {
    var element = new Strophe.Builder("methodResponse")
      .c("params")
      .c("param")
      .cnode(this._convertToXML(result));

    this.sendXMLElement(id, to, "result", element.tree());
  },

  /**
   * Send an error response (or fault)
   *
   * @param  {String} id      ID of the faulted request
   * @param  {String} to      JID of the recipient
   * @param  {Number} code    Code of the error
   * @param  {String} message Error message
   */
  sendError: function(id, to, code, message) {
    if (isNaN(code)) {
      Strophe.error(code + " is not a number");
      return;
    }

    var element = new Strophe.Builder("methodResponse")
      .c("fault")
      .cnode(this._convertToXML({
        faultCode: code,
        faultString: String(message)
      }));

    this.sendXMLElement(id, to, "result", element.tree());
  },

  /**
   * Send a XMLElement as the request
   * Does not check whether it is properly formed or not
   *
   * @param  {String}  id      ID of the request or response
   * @param  {String}  to      JID of the recipient
   * @param  {String}  type    Type of the request ('set' for a request and 'result' for a response)
   * @param  {Element} element The XMLElement to send
   */
  sendXMLElement: function(id, to, type, element) {
    if (typeof element.tree === 'function') {
      element = element.tree();
    }

    var iq = $iq({type: type, id: id, from: this._connection.jid, to: to})
      .c("query", {xmlns: Strophe.NS.RPC})
      .cnode(element);

    this._connection.send(iq.tree());
  },

  _sendForbiddenAccess: function(id, to) {
    var iq = $iq({type: "error", id: id, from: this._connection.jid, to: to})
      .c("error", {code: 403, type: "auth"})
      .c("forbidden", {xmlns: Strophe.NS.STANZAS});

    this._connection.send(iq.tree());
  },

  /**
   * Add a request and response handlers
   *
   * @param {Function} request_h  Request handler
   * @param {Function} response_h Response handler
   * @param {Object} context Context of the handlers
   */
  addHandlers: function(request_h, response_h, context) {
    this.addRequestHandler(request_h, context);
    this.addResponseHandler(response_h, context);
  },

  /**
   * Add a request handler
   * called every time a request is received
   *
   * @param {Function} handler The handler function
   * @param {Object} context Context of the handler
   */
  addRequestHandler: function(handler, context) {
    this._connection.addHandler(this._filteredRequestHandler(handler, context), Strophe.NS.RPC, "iq", "set");
  },

  /**
   * Add a response handler
   * called every time a response is received
   *
   * @param {Function} handler The handler function called every time a response is received
   * @param {Object} context Context of the handler
   */
  addResponseHandler: function(handler, context) {
    this._connection.addHandler(this._filteredResponseHandler(handler, context), Strophe.NS.RPC, "iq", "result");
  },

  /**
   * Add a raw XML handler for every RPC message incoming
   * @param {Function} handler The handler function called every time a rpc is received
   * @param {Object} context Context of the handler
   */
  addXMLHandler: function(handler, context) {
    this._connection.addHandler(this._filteredHandler(handler, context), Strophe.NS.RPC, "iq");
  },

  _filter: function(xml) {
    var from = xml.getAttribute("from");
    if (!this._jidInWhitelist(from)) {
      this._sendForbiddenAccess(xml.getAttribute("id"), from);
      return false;
    }
    return true;
  },

  _filteredHandler: function(handler, context) {
    context = context || this;
    var self = this;
    return function(xml) {
      if (self._filter(xml)) {
        return handler.apply(context, arguments);
      }
      return true;
    };
  },

  _filteredResponseHandler: function(handler, context) {
    context = context || this;
    var self = this;
    return function(xml) {
      if (self._filter(xml)) {
        var rpc = self._parseResponseMessage(xml);
        if (rpc.result || rpc.result === null)
          return handler.call(context, rpc.id, rpc.from, rpc.result, false);
        else if (rpc.fault || rpc.fault === null)
          return handler.call(context, rpc.id, rpc.from, rpc.fault, true);
      }
      return true;
    };
  },

  _filteredRequestHandler: function(handler, context) {
    context = context || this;
    var self = this;
    return function(xml) {
      if (self._filter(xml)) {
        var rpc = self._parseRequestMessage(xml);
        return handler.call(context, rpc.id, rpc.from, rpc.method, rpc.params);
      }
      return true;
    };
  },

  /**
   * Helper to transform a Javascript object
   * into its XML representation as described in
   * the XML-RPC spec
   *
   * @param  {Object} obj The object to convert
   * @return {Element} A <value> element
   */
  _convertToXML: function(obj) {
    var key;

    var xml   = new Strophe.Builder("value");
    var regex = new RegExp("function (.*?)\\(\\) \\{.*");
    var _ref, _ref1;
    var type = (_ref = regex.exec(typeof obj !== "undefined" && obj !== null ? (_ref1 = obj.constructor) != null ? _ref1.toString() : void 0 : void 0)) != null ? _ref[1] : void 0;

    switch (type) {
      case "Number":
        // Numbers can only be sent as integers or doubles.
        var number = (Math.floor(obj) !== obj) ? "double" : "i4";
        xml.c(number).t(obj.toString());
        break;
      case "String":
        xml.c("string").t(obj);
        break;
      case "Boolean":
        xml.c("boolean").t((obj*1).toString());
        break;
      case "Object":
        xml.c("struct");
        for (key in obj) {
          if (obj.hasOwnProperty(key) && typeof(obj[key]) !== "function") {
            xml.c("member").c("name").t(key);
            xml.up().cnode(this._convertToXML(obj[key]));
            xml.up().up();
          }
        }
        break;
      case "Date":
        var datetext = obj.getFullYear() +
                       this._padNumber(obj.getMonth()+1) +
                       this._padNumber(obj.getDate())    + "T" +
                       this._padNumber(obj.getHours())   + ":" +
                       this._padNumber(obj.getMinutes()) + ":" +
                       this._padNumber(obj.getSeconds());
        xml.c("dateTime.iso8601").t(datetext);
        break;
      case "Array":
        xml.c("array").c("data");
        for (key in obj) {
          if (obj.hasOwnProperty(key) && typeof(obj[key]) !== "function") {
            xml.cnode(this._convertToXML(obj[key]));
            xml.up();
          }
        }
        break;
      default:
        break;
    }

    return xml.tree();
  },

  _padNumber: function(num) {
    if (num < 10) {
      num = "0" + num;
    }
    return num;
  },

  _parseRequestMessage: function(iq) {
    var rpc  = {};
    rpc.from = iq.getAttribute("from");
    rpc.id   = iq.getAttribute("id") || null;

    // Method name
    var method = iq.getElementsByTagName("methodName")[0];
    rpc.method = method ? Strophe.getText(method) : null;

    // Parameters
    rpc.params = null;
    try {
      var params = iq.getElementsByTagName("params")[0]
                     .childNodes;
      if (params && params.length > 0) {
        rpc.params = [];
        for (var i = 0; i < params.length; i++) {
          rpc.params.push(this._convertFromXML(params[i].firstChild));
        }
      }
    } catch(e) {
      rpc.params = null;
    }
    return rpc;
  },

  _parseResponseMessage: function(iq) {
    var rpc  = {};
    rpc.from = iq.getAttribute("from");
    rpc.id   = iq.getAttribute("id") || null;

    try {
      var result = iq.getElementsByTagName("methodResponse")[0].firstChild;

      // Response
      var tag = result.tagName;
      if (tag === "params") {
        rpc.result = this._convertFromXML(result.firstChild.firstChild);
      }
      // Error
      else if (tag === "fault") {
        rpc.fault  = this._convertFromXML(result.firstChild);
      }
    } catch(e) {
      rpc.result = null;
    }
    return rpc;
  },

  _convertFromXML: function(obj) {
    if (!obj)
      return null;

    var data;
    var tag = obj.tagName.toLowerCase();

    try {
      switch (tag) {
        case "value":
          return this._convertFromXML(obj.firstChild);
        case "double":
        case "i4":
        case "int":
          var number = Strophe.getText(obj);
          data = number * 1;
          break;
        case "boolean":
          var bool = Strophe.getText(obj);
          data = (bool === "1" || bool === "true") ? true : false;
          break;
        case "datetime.iso8601":
          var date = Strophe.getText(obj);
          data = new Date();
          data.setFullYear(date.substring(0,4), date.substring(4,6) - 1, date.substring(6,8));
          data.setHours(date.substring(9,11), date.substring(12,14), date.substring(15,17));
          break;
        case "array":
          data = [];
          var datatag = obj.firstChild;
          for (var k = 0; k < datatag.childNodes.length; k++) {
            var value = datatag.childNodes[k];
            data.push(this._convertFromXML(value.firstChild));
          }
          break;
        case "struct":
          data = {};
          for (var j = 0; j < obj.childNodes.length; j++) {
            var membername  = Strophe.getText(obj.childNodes[j].getElementsByTagName("name")[0]);
            var membervalue = obj.childNodes[j].getElementsByTagName("value")[0].firstChild;
            data[membername] = membervalue ? this._convertFromXML(membervalue) : null;
          }
          break;
        case "string":
          data = Strophe.getText(obj);
          break;
        default:
          data = null;
          break;
      }
    } catch(e) {
      data = null;
    }
    return data;
  }

});


text:
package org.goldenorb.server;

import java.util.List;
import java.util.Set;

import org.goldenorb.zookeeper.OrbZKFailure;
import org.goldenorb.zookeeper.ZookeeperUtils;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

/**
 * An implementation of Watcher to watch either the JobQueue node or JobsInProgress node and update an
 * OrbTrackerMemberDataServiceImpl servlet when the number of child nodes changes.
 */
public class JobsMonitor implements Watcher {

  private String jobsPath;
  private OrbTrackerMemberDataServiceImpl statusServer;
  private List<String> jobs;
  private ZooKeeper zk;
  private String nodeName;

  public JobsMonitor(String jobQueuePath, OrbTrackerMemberDataServiceImpl statusServer, ZooKeeper zk) throws OrbZKFailure {
    this.jobsPath = jobQueuePath;
    this.statusServer = statusServer;
    this.zk = zk;
    String splitPath[] = jobQueuePath.split("/");
    this.nodeName = splitPath[splitPath.length - 1];
    jobs = ZookeeperUtils.getChildren(zk, jobQueuePath, this);
    statusServer.updateJobs(jobs.toArray(new String[0]), nodeName);
  }

  @Override
  public void process(WatchedEvent event) {
    if (event.getType() != Event.EventType.NodeDeleted) {
      try {
        jobs = ZookeeperUtils.getChildren(zk, jobsPath, this);
        if (event.getType() == Event.EventType.NodeChildrenChanged) {
          statusServer.updateJobs(jobs.toArray(new String[0]), nodeName);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else { // node was deleted return null
      String[] tmp = null;
      statusServer.updateJobs(tmp, nodeName);
      statusServer.watcherNodeDeleted(nodeName);
    }
  }

}


text:
class AddIndexUpdatedAt < ActiveRecord::Migration
  def change
    add_index :projects, :updated_at
  end
end