Tabnine Logo
EventHubClient
Code IndexAdd Tabnine to your IDE (free)

How to use
EventHubClient
in
com.microsoft.azure.eventhubs

Best Java code snippets using com.microsoft.azure.eventhubs.EventHubClient (Showing top 20 results out of 315)

origin: apache/storm

@Override
public void prepare(Map<String, Object> config, TopologyContext context,
          OutputCollector collector) {
  this.collector = collector;
  String myPartitionId = null;
  if (boltConfig.getPartitionMode()) {
    // We can use the task index (starting from 0) as the partition ID
    myPartitionId = "" + context.getThisTaskIndex();
  }
  logger.info("creating sender: " + boltConfig.getConnectionString()
        + ", " + boltConfig.getEntityPath() + ", " + myPartitionId);
  try {
    ehClient = EventHubClient.createFromConnectionStringSync(boltConfig.getConnectionString());
    if (boltConfig.getPartitionMode()) {
      sender = ehClient.createPartitionSenderSync(Integer.toString(context.getThisTaskIndex()));
    }
  } catch (Exception ex) {
    collector.reportError(ex);
    throw new RuntimeException(ex);
  }
}
origin: apache/nifi

@OnStopped
public void tearDown() {
  EventHubClient sender;
  while ((sender = senderQueue.poll()) != null) {
    sender.close();
  }
}
origin: apache/storm

@Override
public void close() {
  if (receiver != null) {
    try {
      receiver.close().whenComplete((voidargs, error) -> {
        try {
          if (error != null) {
            logger.error("Exception during receiver close phase" + error.toString());
          }
          ehClient.closeSync();
        } catch (Exception e) {
          logger.error("Exception during ehclient close phase" + e.toString());
        }
      }).get();
    } catch (InterruptedException e) {
      logger.error("Exception occured during close phase" + e.toString());
    } catch (ExecutionException e) {
      logger.error("Exception occured during close phase" + e.toString());
    }
    logger.info("closed eventhub receiver: partitionId=" + partitionId);
    receiver = null;
    ehClient = null;
  }
}
origin: apache/samza

PowerMockito.when(mockEventHubClient.createReceiverSync(anyString(), anyString(), anyObject()))
    .then((Answer<PartitionReceiver>) invocationOnMock -> {
      String partitionId = invocationOnMock.getArgumentAt(1, String.class);
      return mockPartitionReceiver;
     });
PowerMockito.when(mockEventHubClient.createReceiverSync(anyString(), anyString(), anyObject()))
    .then((Answer<PartitionReceiver>) invocationOnMock -> {
      String partitionId = invocationOnMock.getArgumentAt(1, String.class);
      return mockPartitionReceiver;
     });
PowerMockito.when(mockEventHubClient.getPartitionRuntimeInformation(anyString())).thenReturn(partitionFuture);
PowerMockito.when(mockEventHubClient.createPartitionSenderSync("0")).thenReturn(mockPartitionSender0);
PowerMockito.when(mockEventHubClient.createPartitionSenderSync("1")).thenReturn(mockPartitionSender1);
PowerMockito.when(mockEventHubClient.getRuntimeInformation()).thenReturn(future);
PowerMockito.when(mockEventHubClient.send(any(EventData.class), anyString()))
    .then((Answer<CompletableFuture<Void>>) invocationOnMock -> {
      EventData data = invocationOnMock.getArgumentAt(0, EventData.class);
origin: Azure/azure-event-hubs-java

/**
 * Synchronous version of {@link #create(String, ScheduledExecutorService)}.
 *
 * @param connectionString The connection string to be used. See {@link ConnectionStringBuilder} to construct a connectionString.
 * @param executor         An {@link ScheduledExecutorService} to run all tasks performed by {@link EventHubClient}.
 * @return EventHubClient which can be used to create Senders and Receivers to EventHub
 * @throws EventHubException If Service Bus service encountered problems during connection creation.
 * @throws IOException       If the underlying Proton-J layer encounter network errors.
 */
static EventHubClient createSync(final String connectionString, final ScheduledExecutorService executor)
    throws EventHubException, IOException {
  return EventHubClient.createSync(connectionString, null, executor);
}
origin: sitewhere/sitewhere

@Test
public void doAzureEventSourceSendTest() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
final ConnectionStringBuilder connStr = new ConnectionStringBuilder().setNamespaceName("sitewhere")
  .setEventHubName("events").setSasKeyName("RootManageSharedAccessKey").setSasKey("xxx");
byte[] payloadBytes = EventsHelper.generateJsonMeasurementsMessage(DEVICE_TOKEN);
EventData sendEvent = EventData.create(payloadBytes);
final EventHubClient ehClient = EventHubClient.createSync(connStr.toString(), executor);
ehClient.sendSync(sendEvent);
ehClient.closeSync();
executor.shutdown();
}
origin: com.erudika/para-server

private static EventHubClient receiveEventsAsync(final String partitionId) {
  EventHubClient client = null;
  try {
    client = EventHubClient.createSync(EVENTHUB_CONN_STR, Para.getExecutorService());
    client.createReceiver(EventHubClient.DEFAULT_CONSUMER_GROUP_NAME, partitionId,
          EventPosition.fromEnqueuedTime(Instant.now())).
        thenAccept(new Receiver(partitionId));
  } catch (Exception e) {
    logger.warn("Couldn't start receiving messages from Azure cloud: {}", e.getMessage());
  }
  return client;
}
origin: Azure/azure-event-hubs-java

/**
 * Synchronous version of {@link #send(EventData, String)}.
 *
 * @param eventData    the {@link EventData} to be sent.
 * @param partitionKey the partitionKey will be hash'ed to determine the partitionId to send the eventData to. On the Received message this can be accessed at {@link EventData.SystemProperties#getPartitionKey()}
 * @throws PayloadSizeExceededException if the total size of the {@link EventData} exceeds a pre-defined limit set by the service. Default is 256k bytes.
 * @throws EventHubException            if Service Bus service encountered problems during the operation.
 */
default void sendSync(final EventData eventData, final String partitionKey) throws EventHubException {
  ExceptionUtil.syncVoid(() -> this.send(eventData, partitionKey).get());
}
origin: Azure/azure-event-hubs-java

retval = EventHubClient.create(this.hostContext.getEventHubConnectionString(), this.hostContext.getRetryPolicy(), this.hostContext.getExecutor())
      cleanupFuture.thenComposeAsync((empty) -> saveForCleanupClient.close(), this.hostContext.getExecutor());
      return ehClient;
    }, this.hostContext.getExecutor())
    .thenComposeAsync((ehClient) -> ehClient.getRuntimeInformation(), this.hostContext.getExecutor())
origin: apache/samza

@Override
public void close(long timeoutMS) {
 try {
  if (timeoutMS == EventHubClientManager.BLOCK_UNTIL_CLOSE) {
   eventHubClient.closeSync();
   eventHubClientExecutor.shutdown();
  } else {
   CompletableFuture<Void> future = eventHubClient.close();
   future.get(timeoutMS, TimeUnit.MILLISECONDS);
  }
 } catch (Exception e) {
  LOG.error("Closing the EventHub client failed", e);
 }
}
origin: apache/nifi

  protected void sendMessage(final byte[] buffer) throws ProcessException {

    final EventHubClient sender = senderQueue.poll();
    if(null != sender) {
      try {
        sender.sendSync(new EventData(buffer));
      } catch (final ServiceBusException sbe) {
        throw new ProcessException("Caught exception trying to send message to eventbus", sbe);
      } finally {
        senderQueue.offer(sender);
      }
    }else{
      throw new ProcessException("No EventHubClients are configured for sending");
    }

  }
}
origin: apache/samza

long timeoutMs = config.getRuntimeInfoWaitTimeMS(systemName);
Integer numPartitions =
  ehClient.getRuntimeInformation().get(timeoutMs, TimeUnit.MILLISECONDS).getPartitionCount();
   createOrGetEventHubClientManagerForPartition(streamId, i);
 PartitionSender partitionSender =
   perPartitionClientManager.getEventHubClient().createPartitionSenderSync(partitionId);
 partitionSenders.put(i, partitionSender);
origin: Microsoft/spring-cloud-azure

private PartitionSender createPartitionSender(EventHubClient client, String partitionId) {
  try {
    return client.createPartitionSenderSync(partitionId);
  } catch (EventHubException e) {
    throw new EventHubRuntimeException("Error when creating event hub partition sender", e);
  }
}
origin: apache/nifi

PartitionReceiver getReceiver(final ProcessContext context, final String partitionId) throws IOException, ServiceBusException, ExecutionException, InterruptedException {
  PartitionReceiver existingReceiver = partitionToReceiverMap.get(partitionId);
  if (existingReceiver != null) {
    return existingReceiver;
  }
  // we want to avoid allowing multiple threads to create Receivers simultaneously because that could result in
  // having multiple Receivers for the same partition. So if the map does not contain a receiver for this partition,
  // we will enter a synchronized block and check again (because once we enter the synchronized block, we know that no
  // other thread is creating a client). If within the synchronized block, we still do not have an entry in the map,
  // it is up to use to create the receiver, initialize it, and then put it into the map.
  // We do not use the putIfAbsent method in order to do a CAS operation here because we want to also initialize the
  // receiver if and only if it is not present in the map. As a result, we need to initialize the receiver and add it
  // to the map atomically. Hence, the synchronized block.
  synchronized (this) {
    existingReceiver = partitionToReceiverMap.get(partitionId);
    if (existingReceiver != null) {
      return existingReceiver;
    }
    final String consumerGroupName = context.getProperty(CONSUMER_GROUP).getValue();
    final PartitionReceiver receiver = eventHubClient.createReceiver(
        consumerGroupName,
        partitionId,
        configuredEnqueueTime == null ? Instant.now() : configuredEnqueueTime).get();
    receiver.setReceiveTimeout(receiverFetchTimeout == null ? Duration.ofMillis(60000) : receiverFetchTimeout);
    partitionToReceiverMap.put(partitionId, receiver);
    return receiver;
  }
}
origin: apache/samza

EventHubClient ehClient = eventHubClientManager.getEventHubClient();
CompletableFuture<EventHubRuntimeInformation> runtimeInfo = ehClient.getRuntimeInformation();
long timeoutMs = eventHubConfig.getRuntimeInfoWaitTimeMS(systemName);
EventHubRuntimeInformation ehInfo = runtimeInfo.get(timeoutMs, TimeUnit.MILLISECONDS);
origin: Azure/azure-event-hubs-java

  public void startup() throws EventHubException, IOException {
    this.eventHubSender = EventHubClient.createSync(this.eventHubConnectionString, EXECUTOR_SERVICE);
  }
}
origin: Erudika/para

private static EventHubClient receiveEventsAsync(final String partitionId) {
  EventHubClient client = null;
  try {
    client = EventHubClient.createSync(EVENTHUB_CONN_STR, Para.getExecutorService());
    client.createReceiver(EventHubClient.DEFAULT_CONSUMER_GROUP_NAME, partitionId,
          EventPosition.fromEnqueuedTime(Instant.now())).
        thenAccept(new Receiver(partitionId));
  } catch (Exception e) {
    logger.warn("Couldn't start receiving messages from Azure cloud: {}", e.getMessage());
  }
  return client;
}
origin: Azure/azure-event-hubs-java

/**
 * Synchronous version of {@link #send(EventDataBatch)}.
 *
 * @param eventDatas EventDataBatch to send to EventHub
 * @throws EventHubException if Service Bus service encountered problems during the operation.
 */
default void sendSync(final EventDataBatch eventDatas) throws EventHubException {
  ExceptionUtil.syncVoid(() -> this.send(eventDatas).get());
}
origin: apache/storm

@Override
public void execute(Tuple tuple) {
  try {
    EventData sendEvent = new EventData(boltConfig.getEventDataFormat().serialize(tuple));
    if (boltConfig.getPartitionMode() && sender != null) {
      sender.sendSync(sendEvent);
    } else if (boltConfig.getPartitionMode() && sender == null) {
      throw new EventHubException("Sender is null");
    } else if (!boltConfig.getPartitionMode() && ehClient != null) {
      ehClient.sendSync(sendEvent);
    } else if (!boltConfig.getPartitionMode() && ehClient == null) {
      throw new EventHubException("ehclient is null");
    }
    collector.ack(tuple);
  } catch (EventHubException ex) {
    collector.reportError(ex);
    collector.fail(tuple);
  } catch (ServiceBusException e) {
    collector.reportError(e);
    collector.fail(tuple);
  }
}
origin: com.microsoft.azure/spring-integration-eventhub

private PartitionSender createPartitionSender(EventHubClient client, String partitionId) {
  try {
    return client.createPartitionSenderSync(partitionId);
  } catch (EventHubException e) {
    throw new EventHubRuntimeException("Error when creating event hub partition sender", e);
  }
}
com.microsoft.azure.eventhubsEventHubClient

Javadoc

Anchor class - all EventHub client operations STARTS here.

Most used methods

  • createSync
    Synchronous version of #create(String,ScheduledExecutorService).
  • createPartitionSenderSync
  • send
  • close
  • closeSync
  • sendSync
    Synchronous version of #send(Iterable,String).
  • createReceiver
  • getRuntimeInformation
    Retrieves general information about an event hub (see EventHubRuntimeInformation for details). Retri
  • create
    Factory method to create an instance of EventHubClient using the supplied connectionString. In a nor
  • createEpochReceiver
    Create a Epoch based EventHub receiver with given partition id and start receiving from the beginnin
  • createReceiverSync
    Synchronous version of #createReceiver(String,String,EventPosition).
  • getPartitionRuntimeInformation
    Retrieves dynamic information about a partition of an event hub (see PartitionRuntimeInformation for
  • createReceiverSync,
  • getPartitionRuntimeInformation,
  • createBatch,
  • createEpochReceiverSync,
  • createFromConnectionString,
  • createFromConnectionStringSync,
  • createPartitionSender

Popular in Java

  • Reading from database using SQL prepared statement
  • setScale (BigDecimal)
  • scheduleAtFixedRate (Timer)
  • setContentView (Activity)
  • VirtualMachine (com.sun.tools.attach)
    A Java virtual machine. A VirtualMachine represents a Java virtual machine to which this Java vir
  • FlowLayout (java.awt)
    A flow layout arranges components in a left-to-right flow, much like lines of text in a paragraph. F
  • Window (java.awt)
    A Window object is a top-level window with no borders and no menubar. The default layout for a windo
  • LinkedList (java.util)
    Doubly-linked list implementation of the List and Dequeinterfaces. Implements all optional list oper
  • Collectors (java.util.stream)
  • Location (org.springframework.beans.factory.parsing)
    Class that models an arbitrary location in a Resource.Typically used to track the location of proble
  • Top 12 Jupyter Notebook extensions
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now