text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.microsoft.azure.eventhubs;

import com.microsoft.azure.eventhubs.impl.EventHubClientImpl;
import com.microsoft.azure.eventhubs.impl.ExceptionUtil;

import java.io.IOException;
import java.net.URI;
import java.nio.channels.UnresolvedAddressException;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;

/**
 * Anchor class - all EventHub client operations STARTS here.
 *
 * @see EventHubClient#createFromConnectionString(String, ScheduledExecutorService)
 */
public interface EventHubClient {

    String DEFAULT_CONSUMER_GROUP_NAME = "$Default";

    /**
     * Synchronous version of {@link #createFromConnectionString(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 createFromConnectionStringSync(final String connectionString, final ScheduledExecutorService executor)
            throws EventHubException, IOException {
        return createFromConnectionStringSync(connectionString, null, executor);
    }

    /**
     * Synchronous version of {@link #createFromConnectionString(String, ScheduledExecutorService)}.
     *
     * @param connectionString The connection string to be used. See {@link ConnectionStringBuilder} to construct a connectionString.
     * @param retryPolicy      A custom {@link RetryPolicy} to be used when communicating with EventHub.
     * @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 createFromConnectionStringSync(final String connectionString, final RetryPolicy retryPolicy, final ScheduledExecutorService executor)
            throws EventHubException, IOException {
        return ExceptionUtil.syncWithIOException(() -> createFromConnectionString(connectionString, retryPolicy, executor).get());
    }

    /**
     * Synchronous version of {@link #createFromConnectionString(String, RetryPolicy, ScheduledExecutorService, ProxyConfiguration)}.
     *
     * @param connectionString The connection string to be used. See {@link ConnectionStringBuilder} to construct a connectionString.
     * @param retryPolicy      A custom {@link RetryPolicy} to be used when communicating with EventHub.
     * @param executor         An {@link ScheduledExecutorService} to run all tasks performed by {@link EventHubClient}.
     * @param configuration    The proxy configuration for this EventHubClient connection; {@code null} or
     *      {@link ProxyConfiguration#SYSTEM_DEFAULTS} if the system configured proxy settings should be used.
     * @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 createFromConnectionStringSync(final String connectionString, final RetryPolicy retryPolicy,
                                                         final ScheduledExecutorService executor,
                                                         final ProxyConfiguration configuration)
        throws EventHubException, IOException {
        return ExceptionUtil.syncWithIOException(() -> createFromConnectionString(connectionString, retryPolicy, executor, configuration).get());
    }

    /**
     * Synchronous version of {@link #createFromConnectionString(String, RetryPolicy, ScheduledExecutorService, ProxyConfiguration, Duration)}.
     *
     * @param connectionString The connection string to be used. See {@link ConnectionStringBuilder} to construct a connectionString.
     * @param retryPolicy      A custom {@link RetryPolicy} to be used when communicating with EventHub.
     * @param executor         An {@link ScheduledExecutorService} to run all tasks performed by {@link EventHubClient}.
     * @param configuration    The proxy configuration for this EventHubClient connection; {@code null} or
     *      {@link ProxyConfiguration#SYSTEM_DEFAULTS} if the system configured proxy settings should be used.
     * @param maximumSilentTime Use {@link EventHubClientOptions#SILENT_OFF} except on recommendation from the product group.
     * @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 createFromConnectionStringSync(final String connectionString, final RetryPolicy retryPolicy,
                                                         final ScheduledExecutorService executor,
                                                         final ProxyConfiguration configuration,
                                                         final Duration maximumSilentTime)
        throws EventHubException, IOException {
        return ExceptionUtil.syncWithIOException(() -> createFromConnectionString(connectionString, retryPolicy, executor, configuration, maximumSilentTime).get());
    }

    /**
     * Factory method to create an instance of {@link EventHubClient} using the supplied connectionString.
     * In a normal scenario (when re-direct is not enabled) - one EventHubClient instance maps to one Connection to the Azure ServiceBus EventHubs service.
     *
The {@link EventHubClient} created from this method creates a Sender instance internally, which is used by the {@link #send(EventData)} methods.
     *
     * @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 CompletableFuture{@literal <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 CompletableFuture<EventHubClient> createFromConnectionString(final String connectionString, final ScheduledExecutorService executor)
            throws EventHubException, IOException {
        return createFromConnectionString(connectionString, null, executor);
    }

    /**
     * Factory method to create an instance of {@link EventHubClient} using the supplied connectionString.
     * In a normal scenario (when re-direct is not enabled) - one EventHubClient instance maps to one Connection to the Azure ServiceBus EventHubs service.
     *
The {@link EventHubClient} created from this method creates a Sender instance internally, which is used by the {@link #send(EventData)} methods.
     *
     * @param connectionString The connection string to be used. See {@link ConnectionStringBuilder} to construct a connectionString.
     * @param retryPolicy      A custom {@link RetryPolicy} to be used when communicating with EventHub.
     * @param executor         An {@link ScheduledExecutorService} to run all tasks performed by {@link EventHubClient}.
     * @return CompletableFuture{@literal <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 CompletableFuture<EventHubClient> createFromConnectionString(
            final String connectionString, final RetryPolicy retryPolicy, final ScheduledExecutorService executor)
            throws EventHubException, IOException {
        return EventHubClientImpl.create(connectionString, retryPolicy, executor, null);
    }

    /**
     * Factory method to create an instance of {@link EventHubClient} using the supplied {@code connectionString}. One
     * EventHubClient instance maps to one connection to the Event Hubs service.
     *
     *

     * The {@link EventHubClient} created from this method creates a Sender instance internally, which is used by
     * the {@link #send(EventData)} methods.
     *

     * @param connectionString The connection string to be used. See {@link ConnectionStringBuilder} to construct a connectionString.
     * @param retryPolicy      A custom {@link RetryPolicy} to be used when communicating with EventHub.
     * @param executor         An {@link ScheduledExecutorService} to run all tasks performed by {@link EventHubClient}.
     * @param proxyConfiguration The proxy configuration for this EventHubClient connection; {@code null} or
     *      {@link ProxyConfiguration#SYSTEM_DEFAULTS} if the system configured proxy settings should be used.
     * @return CompletableFuture{@literal <EventHubClient>} which can be used to create Senders and Receivers to EventHub.
     * @throws IOException       If the underlying Proton-J layer encounter network errors.
     */
    static CompletableFuture<EventHubClient> createFromConnectionString(
        final String connectionString, final RetryPolicy retryPolicy, final ScheduledExecutorService executor,
        final ProxyConfiguration proxyConfiguration) throws IOException {
        return EventHubClientImpl.create(connectionString, retryPolicy, executor, proxyConfiguration);
    }

    /**
     * Factory method to create an instance of {@link EventHubClient} using the supplied {@code connectionString}. One
     * EventHubClient instance maps to one connection to the Event Hubs service.
     *
     *

     * The {@link EventHubClient} created from this method creates a Sender instance internally, which is used by
     * the {@link #send(EventData)} methods.
     *

     * @param connectionString The connection string to be used. See {@link ConnectionStringBuilder} to construct a connectionString.
     * @param retryPolicy      A custom {@link RetryPolicy} to be used when communicating with EventHub.
     * @param executor         An {@link ScheduledExecutorService} to run all tasks performed by {@link EventHubClient}.
     * @param proxyConfiguration The proxy configuration for this EventHubClient connection; {@code null} or
     *      {@link ProxyConfiguration#SYSTEM_DEFAULTS} if the system configured proxy settings should be used.
     * @param maximumSilentTime Use {@link EventHubClientOptions#SILENT_OFF} except on recommendation from the product group.
     * @return CompletableFuture{@literal <EventHubClient>} which can be used to create Senders and Receivers to EventHub.
     * @throws IOException       If the underlying Proton-J layer encounter network errors.
     */
    static CompletableFuture<EventHubClient> createFromConnectionString(
        final String connectionString, final RetryPolicy retryPolicy, final ScheduledExecutorService executor,
        final ProxyConfiguration proxyConfiguration, final Duration maximumSilentTime) throws IOException {
        return EventHubClientImpl.create(connectionString, retryPolicy, executor, proxyConfiguration, maximumSilentTime);
    }

    /**
     * Factory method to create an instance of {@link EventHubClient} using the supplied namespace endpoint address, eventhub name and authentication mechanism.
     * In a normal scenario (when re-direct is not enabled) - one EventHubClient instance maps to one Connection to the Azure ServiceBus EventHubs service.
     *
The {@link EventHubClient} created from this method creates a Sender instance internally, which is used by the {@link #send(EventData)} methods.
     *
     * @param endpointAddress namespace level endpoint. This needs to be in the format of scheme://fullyQualifiedServiceBusNamespaceEndpointName
     * @param eventHubName  EventHub name
     * @param authCallback  A callback which returns a JSON Web Token obtained from AAD.
     * @param authority        Address of the AAD authority to issue the token.
     * @param executor      An {@link ScheduledExecutorService} to run all tasks performed by {@link EventHubClient}.
     * @param options        Options {@link EventHubClientOptions} for creating the client. Uses all defaults if null.
     * @return EventHubClient which can be used to create Senders and Receivers to EventHub
     * @throws EventHubException If the EventHubs service encountered problems during connection creation.
     * @throws IOException If the underlying Proton-J layer encounter network errors.
     */
    static CompletableFuture<EventHubClient> createWithAzureActiveDirectory(
            final URI endpointAddress,
            final String eventHubName,
            final AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback,
            final String authority,
            final ScheduledExecutorService executor,
            final EventHubClientOptions options) throws EventHubException, IOException {
        ITokenProvider tokenProvider = new AzureActiveDirectoryTokenProvider(authCallback, authority, null);
        return createWithTokenProvider(endpointAddress, eventHubName, tokenProvider, executor, options);
    }

    /**
     * Factory method to create an instance of {@link EventHubClient} using the supplied namespace endpoint address, eventhub name and authentication mechanism.
     * In a normal scenario (when re-direct is not enabled) - one EventHubClient instance maps to one Connection to the Azure ServiceBus EventHubs service.
     *
The {@link EventHubClient} created from this method creates a Sender instance internally, which is used by the {@link #send(EventData)} methods.
     *
     * @param endpointAddress namespace level endpoint. This needs to be in the format of scheme://fullyQualifiedServiceBusNamespaceEndpointName
     * @param eventHubName  EventHub name
     * @param tokenProvider The {@link ITokenProvider} implementation to be used to authenticate
     * @param executor      An {@link ScheduledExecutorService} to run all tasks performed by {@link EventHubClient}.
     * @param options        Options {@link EventHubClientOptions} for creating the client. Uses all defaults if null.
     * @return EventHubClient which can be used to create Senders and Receivers to EventHub
     * @throws EventHubException If the EventHubs service encountered problems during connection creation.
     * @throws IOException If the underlying Proton-J layer encounter network errors.
     */
    static CompletableFuture<EventHubClient> createWithTokenProvider(
            final URI endpointAddress,
            final String eventHubName,
            final ITokenProvider tokenProvider,
            final ScheduledExecutorService executor,
            final EventHubClientOptions options) throws EventHubException, IOException {
        return EventHubClientImpl.create(endpointAddress, eventHubName, tokenProvider, executor, options);
    }

    /**
     * @return the name of the Event Hub this client is connected to.
     */
    String getEventHubName();

    /**
     * Creates an Empty Collection of {@link EventData}.
     * The same partitionKey must be used while sending these events using {@link EventHubClient#send(EventDataBatch)}.
     *
     * @param options see {@link BatchOptions} for more details
     * @return the empty {@link EventDataBatch}, after negotiating maximum message size with EventHubs service
     * @throws EventHubException if the Microsoft Azure Event Hubs service encountered problems during the operation.
     */
    EventDataBatch createBatch(BatchOptions options) throws EventHubException;

    /**
     * Creates an Empty Collection of {@link EventData}.
     * The same partitionKey must be used while sending these events using {@link EventHubClient#send(EventDataBatch)}.
     *
     * @return the empty {@link EventDataBatch}, after negotiating maximum message size with EventHubs service
     * @throws EventHubException if the Microsoft Azure Event Hubs service encountered problems during the operation.
     */
    default EventDataBatch createBatch() throws EventHubException {
        return this.createBatch(new BatchOptions());
    }

    /**
     * Synchronous version of {@link #send(EventData)}.
     *
     * @param data the {@link EventData} to be sent.
     * @throws PayloadSizeExceededException if the total size of the {@link EventData} exceeds a predefined limit set by the service. Default is 256k bytes.
     * @throws EventHubException            if Service Bus service encountered problems during the operation.
     * @throws UnresolvedAddressException   if there are Client to Service network connectivity issues, if the Azure DNS resolution of the ServiceBus Namespace fails (ex: namespace deleted etc.)
     */
    default void sendSync(final EventData data) throws EventHubException {
        ExceptionUtil.syncVoid(() -> this.send(data).get());
    }

    /**
     * Send {@link EventData} to EventHub. The sent {@link EventData} will land on any arbitrarily chosen EventHubs partition.
     *
There are 3 ways to send to EventHubs, each exposed as a method (along with its sendBatch overload):
     *

     *
 {@link #send(EventData)}, {@link #send(Iterable)}, or {@link #send(EventDataBatch)}
     *
 {@link #send(EventData, String)} or {@link #send(Iterable, String)}
     *
 {@link PartitionSender#send(EventData)}, {@link PartitionSender#send(Iterable)}, or {@link PartitionSender#send(EventDataBatch)}
     *

     *
Use this method to Send, if:
     *

     * a)  the send({@link EventData}) operation should be highly available and
     * b)  the data needs to be evenly distributed among all partitions; exception being, when a subset of partitions are unavailable
     *

     *

     * {@link #send(EventData)} send's the {@link EventData} to a Service Gateway, which in-turn will forward the {@link EventData} to one of the EventHubs' partitions. Here's the message forwarding algorithm:
     *

     * i.  Forward the {@link EventData}'s to EventHub partitions, by equally distributing the data among all partitions (ex: Round-robin the {@link EventData}'s to all EventHubs' partitions)
     * ii. If one of the EventHub partitions is unavailable for a moment, the Service Gateway will automatically detect it and forward the message to another available partition - making the Send operation highly-available.
     *

     *
     * @param data the {@link EventData} to be sent.
     * @return a CompletableFuture that can be completed when the send operations is done..
     * @see #send(EventData, String)
     * @see PartitionSender#send(EventData)
     */
    CompletableFuture<Void> send(EventData data);

    /**
     * Synchronous version of {@link #send(Iterable)}.
     *
     * @param eventDatas batch of events to send to EventHub
     * @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.
     * @throws UnresolvedAddressException   if there are Client to Service network connectivity issues, if the Azure DNS resolution of the ServiceBus Namespace fails (ex: namespace deleted etc.)
     */
    default void sendSync(final Iterable<EventData> eventDatas) throws EventHubException {
        ExceptionUtil.syncVoid(() -> this.send(eventDatas).get());
    }

    /**
     * Send a batch of {@link EventData} to EventHub. The sent {@link EventData} will land on any arbitrarily chosen EventHubs partition.
     * This is the most recommended way to Send to EventHubs.
     *
There are 3 ways to send to EventHubs, to understand this particular type of Send refer to the overload {@link #send(EventData)}, which is used to send single {@link EventData}.
     * Use this overload versus {@link #send(EventData)}, if you need to send a batch of {@link EventData}.
     *
 Sending a batch of {@link EventData}'s is useful in the following cases:
     *

     * i.   Efficient send - sending a batch of {@link EventData} maximizes the overall throughput by optimally using the number of sessions created to EventHubs' service.
     * ii.  Send multiple {@link EventData}'s in a Transaction. To achieve ACID properties, the Gateway Service will forward all {@link EventData}'s in the batch to a single EventHubs' partition.
     *

     *

     * Sample code (sample uses sync version of the api but concept are identical):
     *

     * Gson gson = new GsonBuilder().create();
     * EventHubClient client = EventHubClient.createSync("__connection__");
     *
     * while (true)
     * {
     *     LinkedList{@literal<}EventData{@literal>} events = new LinkedList{@literal<}EventData{@literal>}();}
     *     for (int count = 1; count {@literal<} 11; count++)
     *     {
     *         PayloadEvent payload = new PayloadEvent(count);
     *         byte[] payloadBytes = gson.toJson(payload).getBytes(Charset.defaultCharset());
     *         EventData sendEvent = new EventData(payloadBytes);
     *         sendEvent.getProperties().put("from", "javaClient");
     *         events.add(sendEvent);
     *     }
     *
     *     client.sendSync(events);
     *     System.out.println(String.format("Sent Batch... Size: %s", events.size()));
     * }
     *

     *
 for Exceptions refer to {@link #sendSync(Iterable)}
     *
     * @param eventDatas batch of events to send to EventHub
     * @return a CompletableFuture that can be completed when the send operations is done..
     * @see #send(EventData, String)
     * @see PartitionSender#send(EventData)
     */
    CompletableFuture<Void> send(Iterable<EventData> eventDatas);

    /**
     * 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());
    }

    /**
     * Send {@link EventDataBatch} to EventHub. The sent {@link EventDataBatch} will land according the partition key
     * set in the {@link EventDataBatch}. If a partition key is not set, then we will Round-robin the {@link EventData}'s
     * to all EventHubs' partitions.
     *
     * @param eventDatas EventDataBatch to send to EventHub
     * @return a CompleteableFuture that can be completed when the send operations are done
     * @see #send(Iterable)
     * @see EventDataBatch
     */
    CompletableFuture<Void> send(EventDataBatch eventDatas);

    /**
     * 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());
    }

    /**
     * Send an '{@link EventData} with a partitionKey' to EventHub. All {@link EventData}'s with a partitionKey are guaranteed to land on the same partition.
     * This send pattern emphasize data correlation over general availability and latency.
     *

     * There are 3 ways to send to EventHubs, each exposed as a method (along with its sendBatch overload):
     *

     * i.   {@link #send(EventData)} or {@link #send(Iterable)}
     * ii.  {@link #send(EventData, String)} or {@link #send(Iterable, String)}
     * iii. {@link PartitionSender#send(EventData)} or {@link PartitionSender#send(Iterable)}
     *

     *

     * Use this type of Send, if:
     *

     * i.  There is a need for correlation of events based on Sender instance; The sender can generate a UniqueId and set it as partitionKey - which on the received Message can be used for correlation
     * ii. The client wants to take control of distribution of data across partitions.
     *

     *

     * Multiple PartitionKey's could be mapped to one Partition. EventHubs service uses a proprietary Hash algorithm to map the PartitionKey to a PartitionId.
     * Using this type of Send (Sending using a specific partitionKey), could sometimes result in partitions which are not evenly distributed.
     *
     * @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()}
     * @return a CompletableFuture that can be completed when the send operations is done..
     * @see #send(EventData)
     * @see PartitionSender#send(EventData)
     */
    CompletableFuture<Void> send(EventData eventData, String partitionKey);

    /**
     * Synchronous version of {@link #send(Iterable, String)}.
     *
     * @param eventDatas   the batch of events to send to EventHub
     * @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.
     * @throws UnresolvedAddressException   if there are Client to Service network connectivity issues, if the Azure DNS resolution of the ServiceBus Namespace fails (ex: namespace deleted etc.)
     */
    default void sendSync(final Iterable<EventData> eventDatas, final String partitionKey) throws EventHubException {
        ExceptionUtil.syncVoid(() -> this.send(eventDatas, partitionKey).get());
    }

    /**
     * Send a 'batch of {@link EventData} with the same partitionKey' to EventHub. All {@link EventData}'s with a partitionKey are guaranteed to land on the same partition.
     * Multiple PartitionKey's will be mapped to one Partition.
     *
There are 3 ways to send to EventHubs, to understand this particular type of Send refer to the overload {@link #send(EventData, String)}, which is the same type of Send and is used to send single {@link EventData}.
     *
Sending a batch of {@link EventData}'s is useful in the following cases:
     *

     * i.   Efficient send - sending a batch of {@link EventData} maximizes the overall throughput by optimally using the number of sessions created to EventHubs service.
     * ii.  Send multiple events in One Transaction. This is the reason why all events sent in a batch needs to have same partitionKey (so that they are sent to one partition only).
     *

     *
     * @param eventDatas   the batch of events to send to EventHub
     * @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()}
     * @return a CompletableFuture that can be completed when the send operations is done..
     * @see #send(EventData)
     * @see PartitionSender#send(EventData)
     */
    CompletableFuture<Void> send(Iterable<EventData> eventDatas, String partitionKey);

    /**
     * Synchronous version of {@link #createPartitionSender(String)}.
     *
     * @param partitionId partitionId of EventHub to send the {@link EventData}'s to
     * @return PartitionSenderImpl which can be used to send events to a specific partition.
     * @throws EventHubException if Service Bus service encountered problems during connection creation.
     */
    default PartitionSender createPartitionSenderSync(final String partitionId) throws EventHubException, IllegalArgumentException {
        return ExceptionUtil.syncWithIllegalArgException(() -> this.createPartitionSender(partitionId).get());
    }

    /**
     * Create a {@link PartitionSender} which can publish {@link EventData}'s directly to a specific EventHub partition (sender type iii. in the below list).
     *

     * There are 3 patterns/ways to send to EventHubs:
     *

     * i.   {@link #send(EventData)} or {@link #send(Iterable)}
     * ii.  {@link #send(EventData, String)} or {@link #send(Iterable, String)}
     * iii. {@link PartitionSender#send(EventData)} or {@link PartitionSender#send(Iterable)}
     *

     *
     * @param partitionId partitionId of EventHub to send the {@link EventData}'s to
     * @return a CompletableFuture that would result in a PartitionSenderImpl when it is completed.
     * @throws EventHubException if Service Bus service encountered problems during connection creation.
     * @see PartitionSender
     */
    CompletableFuture<PartitionSender> createPartitionSender(String partitionId) throws EventHubException;

    /**
     * Synchronous version of {@link #createReceiver(String, String, EventPosition)}.
     *
     * @param consumerGroupName the consumer group name that this receiver should be grouped under.
     * @param partitionId       the partition Id that the receiver belongs to. All data received will be from this partition only.
     * @param eventPosition     the position to start receiving the events from. See {@link EventPosition}
     * @return PartitionReceiver instance which can be used for receiving {@link EventData}.
     * @throws EventHubException if Service Bus service encountered problems during the operation.
     */
    default PartitionReceiver createReceiverSync(final String consumerGroupName, final String partitionId, final EventPosition eventPosition) throws EventHubException {
        return ExceptionUtil.sync(() -> this.createReceiver(consumerGroupName, partitionId, eventPosition).get());
    }

    /**
     * Create the EventHub receiver with given partition id and start receiving from the specified starting offset.
     * The receiver is created for a specific EventHub Partition from the specific consumer group.
     *
     * @param consumerGroupName the consumer group name that this receiver should be grouped under.
     * @param partitionId       the partition Id that the receiver belongs to. All data received will be from this partition only.
     * @param eventPosition     the position to start receiving the events from. See {@link EventPosition}
     * @return a CompletableFuture that would result in a PartitionReceiver instance when it is completed.
     * @throws EventHubException if Service Bus service encountered problems during the operation.
     * @see PartitionReceiver
     */
    CompletableFuture<PartitionReceiver> createReceiver(String consumerGroupName, String partitionId, EventPosition eventPosition) throws EventHubException;

    /**
     * Synchronous version of {@link #createReceiver(String, String, EventPosition)}.
     *
     * @param consumerGroupName the consumer group name that this receiver should be grouped under.
     * @param partitionId       the partition Id that the receiver belongs to. All data received will be from this partition only.
     * @param eventPosition     the position to start receiving the events from. See {@link EventPosition}
     * @param receiverOptions   the set of options to enable on the event hubs receiver
     * @return PartitionReceiver instance which can be used for receiving {@link EventData}.
     * @throws EventHubException if Service Bus service encountered problems during the operation.
     */
    default PartitionReceiver createReceiverSync(final String consumerGroupName, final String partitionId, final EventPosition eventPosition, final ReceiverOptions receiverOptions) throws EventHubException {
        return ExceptionUtil.sync(() -> this.createReceiver(consumerGroupName, partitionId, eventPosition, receiverOptions).get());
    }

    /**
     * Create the EventHub receiver with given partition id and start receiving from the specified starting offset.
     * The receiver is created for a specific EventHub Partition from the specific consumer group.
     *
     * @param consumerGroupName the consumer group name that this receiver should be grouped under.
     * @param partitionId       the partition Id that the receiver belongs to. All data received will be from this partition only.
     * @param eventPosition     the position to start receiving the events from. See {@link EventPosition}
     * @param receiverOptions   the set of options to enable on the event hubs receiver
     * @return a CompletableFuture that would result in a PartitionReceiver instance when it is completed.
     * @throws EventHubException if Service Bus service encountered problems during the operation.
     * @see PartitionReceiver
     */
    CompletableFuture<PartitionReceiver> createReceiver(String consumerGroupName, String partitionId, EventPosition eventPosition, ReceiverOptions receiverOptions) throws EventHubException;

    /**
     * Synchronous version of {@link #createEpochReceiver(String, String, EventPosition, long)}.
     *
     * @param consumerGroupName the consumer group name that this receiver should be grouped under.
     * @param partitionId       the partition Id that the receiver belongs to. All data received will be from this partition only.
     * @param eventPosition     the position to start receiving the events from. See {@link EventPosition}
     * @param epoch             an unique identifier (epoch value) that the service uses, to enforce partition/lease ownership.
     * @return PartitionReceiver instance which can be used for receiving {@link EventData}.
     * @throws EventHubException if Service Bus service encountered problems during the operation.
     */
    default PartitionReceiver createEpochReceiverSync(final String consumerGroupName, final String partitionId, final EventPosition eventPosition, final long epoch) throws EventHubException {
        return ExceptionUtil.sync(() -> this.createEpochReceiver(consumerGroupName, partitionId, eventPosition, epoch).get());
    }

    /**
     * Create a Epoch based EventHub receiver with given partition id and start receiving from the beginning of the partition stream.
     * The receiver is created for a specific EventHub Partition from the specific consumer group.
     *

     * It is important to pay attention to the following when creating epoch based receiver:
     *

     *
 Ownership enforcement - Once you created an epoch based receiver, you cannot create a non-epoch receiver to the same consumerGroup-Partition combo until all receivers to the combo are closed.
     *
 Ownership stealing - If a receiver with higher epoch value is created for a consumerGroup-Partition combo, any older epoch receiver to that combo will be force closed.
     *
 Any receiver closed due to lost of ownership to a consumerGroup-Partition combo will get ReceiverDisconnectedException for all operations from that receiver.
     *

     *
     * @param consumerGroupName the consumer group name that this receiver should be grouped under.
     * @param partitionId       the partition Id that the receiver belongs to. All data received will be from this partition only.
     * @param eventPosition     the position to start receiving the events from. See {@link EventPosition}
     * @param epoch             an unique identifier (epoch value) that the service uses, to enforce partition/lease ownership.
     * @return a CompletableFuture that would result in a PartitionReceiver when it is completed.
     * @throws EventHubException if Service Bus service encountered problems during the operation.
     * @see PartitionReceiver
     * @see ReceiverDisconnectedException
     */
    CompletableFuture<PartitionReceiver> createEpochReceiver(String consumerGroupName, String partitionId, EventPosition eventPosition, long epoch) throws EventHubException;

    /**
     * Synchronous version of {@link #createEpochReceiver(String, String, EventPosition, long)}.
     *
     * @param consumerGroupName the consumer group name that this receiver should be grouped under.
     * @param partitionId       the partition Id that the receiver belongs to. All data received will be from this partition only.
     * @param eventPosition     the position to start receiving the events from. See {@link EventPosition}
     * @param epoch             an unique identifier (epoch value) that the service uses, to enforce partition/lease ownership.
     * @param receiverOptions   the set of options to enable on the event hubs receiver
     * @return PartitionReceiver instance which can be used for receiving {@link EventData}.
     * @throws EventHubException if Service Bus service encountered problems during the operation.
     */
    default PartitionReceiver createEpochReceiverSync(final String consumerGroupName, final String partitionId, final EventPosition eventPosition, final long epoch, final ReceiverOptions receiverOptions) throws EventHubException {
        return ExceptionUtil.sync(() -> this.createEpochReceiver(consumerGroupName, partitionId, eventPosition, epoch, receiverOptions).get());
    }

    /**
     * Create a Epoch based EventHub receiver with given partition id and start receiving from the beginning of the partition stream.
     * The receiver is created for a specific EventHub Partition from the specific consumer group.
     *

     * It is important to pay attention to the following when creating epoch based receiver:
     *

     *
 Ownership enforcement - Once you created an epoch based receiver, you cannot create a non-epoch receiver to the same consumerGroup-Partition combo until all receivers to the combo are closed.
     *
 Ownership stealing - If a receiver with higher epoch value is created for a consumerGroup-Partition combo, any older epoch receiver to that combo will be force closed.
     *
 Any receiver closed due to lost of ownership to a consumerGroup-Partition combo will get ReceiverDisconnectedException for all operations from that receiver.
     *

     *
     * @param consumerGroupName the consumer group name that this receiver should be grouped under.
     * @param partitionId       the partition Id that the receiver belongs to. All data received will be from this partition only.
     * @param eventPosition     the position to start receiving the events from. See {@link EventPosition}
     * @param epoch             an unique identifier (epoch value) that the service uses, to enforce partition/lease ownership.
     * @param receiverOptions   the set of options to enable on the event hubs receiver
     * @return a CompletableFuture that would result in a PartitionReceiver when it is completed.
     * @throws EventHubException if Service Bus service encountered problems during the operation.
     * @see PartitionReceiver
     * @see ReceiverDisconnectedException
     */
    CompletableFuture<PartitionReceiver> createEpochReceiver(String consumerGroupName, String partitionId, EventPosition eventPosition, long epoch, ReceiverOptions receiverOptions) throws EventHubException;

    /**
     * Retrieves general information about an event hub (see {@link EventHubRuntimeInformation} for details).
     * Retries until it reaches the operation timeout, then either rethrows the last error if available or
     * returns null to indicate timeout.
     *
     * @return CompletableFuture which returns an EventHubRuntimeInformation on success, or null on timeout.
     */
    CompletableFuture<EventHubRuntimeInformation> getRuntimeInformation();

    /**
     * Retrieves dynamic information about a partition of an event hub (see {@link PartitionRuntimeInformation} for
     * details. Retries until it reaches the operation timeout, then either rethrows the last error if available or
     * returns null to indicate timeout.
     *
     * @param partitionId Partition to get information about. Must be one of the partition ids returned by {@link #getRuntimeInformation}.
     * @return CompletableFuture which returns an PartitionRuntimeInformation on success, or null on timeout.
     */
    CompletableFuture<PartitionRuntimeInformation> getPartitionRuntimeInformation(String partitionId);

    CompletableFuture<Void> close();

    void closeSync() throws EventHubException;
}


text:
package rest

import (
	"strconv"
	"strings"
	"time"

	"github.com/ligato/cn-infra/config"
	"github.com/ligato/cn-infra/infra"
	"github.com/namsral/flag"
)

const (
	// DefaultHost is a host used by default
	DefaultHost = "0.0.0.0"
	// DefaultHTTPPort is a port used by default
	DefaultHTTPPort = "9191"
	// DefaultEndpoint 0.0.0.0:9191
	DefaultEndpoint = DefaultHost + ":" + DefaultHTTPPort
)

// Config is a configuration for HTTP server
// It is meant to be extended with security (TLS...)
type Config struct {
	// Endpoint is an address of HTTP server
	Endpoint string

	// ReadTimeout is the maximum duration for reading the entire
	// request, including the body.
	//
	// Because ReadTimeout does not let Handlers make per-request
	// decisions on each request body's acceptable deadline or
	// upload rate, most users will prefer to use
	// ReadHeaderTimeout. It is valid to use them both.
	ReadTimeout time.Duration

	// ReadHeaderTimeout is the amount of time allowed to read
	// request headers. The connection's read deadline is reset
	// after reading the headers and the Handler can decide what
	// is considered too slow for the body.
	ReadHeaderTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset whenever a new
	// request's header is read. Like ReadTimeout, it does not
	// let Handlers make decisions on a per-request basis.
	WriteTimeout time.Duration

	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alives are enabled. If IdleTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, there is no timeout.
	IdleTimeout time.Duration

	// MaxHeaderBytes controls the maximum number of bytes the
	// server will read parsing the request header's keys and
	// values, including the request line. It does not limit the
	// size of the request body.
	// If zero, DefaultMaxHeaderBytes is used.
	MaxHeaderBytes int

	// ServerCertfile is path to the server certificate. If the certificate and corresponding
	// key (see config item below) is defined server uses HTTPS instead of HTTP.
	ServerCertfile string `json:"server-cert-file"`

	// ServerKeyfile is path to the server key file.
	ServerKeyfile string `json:"server-key-file"`

	// ClientBasicAuth is a slice of credentials in form "username:password"
	// used for basic HTTP authentication. If defined only authenticated users are allowed
	// to access the server.
	ClientBasicAuth []string `json:"client-basic-auth"`

	// ClientCerts is a slice of the root certificate authorities
	// that servers uses to verify a client certificate
	ClientCerts []string `json:"client-cert-files"`
}

// DefaultConfig returns new instance of config with default endpoint
func DefaultConfig() *Config {
	return &Config{
		Endpoint: DefaultEndpoint,
	}
}

// PluginConfig tries :
// - to load flag <plugin-name>-port and then FixConfig() just in case
// - alternatively <plugin-name>-config and then FixConfig() just in case
// - alternatively DefaultConfig()
func PluginConfig(pluginCfg config.PluginConfig, cfg *Config, pluginName infra.PluginName) error {
	portFlag := flag.Lookup(httpPortFlag(pluginName))

	if portFlag != nil && portFlag.Value != nil && portFlag.Value.String() != "" && cfg != nil {
		cfg.Endpoint = DefaultHost + ":" + portFlag.Value.String()
	}

	if pluginCfg != nil {
		_, err := pluginCfg.LoadValue(cfg)
		if err != nil {
			return err
		}
	}

	FixConfig(cfg)

	return nil
}

// FixConfig fill default values for empty fields
func FixConfig(cfg *Config) {
	if cfg == nil {
		return
	}
	if cfg.Endpoint == "" {
		cfg.Endpoint = DefaultEndpoint
	}
}

// GetPort parses suffix from endpoint & returns integer after last ":" (otherwise it returns 0)
func (cfg *Config) GetPort() int {
	if cfg.Endpoint != "" && cfg.Endpoint != ":" {
		index := strings.LastIndex(cfg.Endpoint, ":")
		if index >= 0 {
			port, err := strconv.Atoi(cfg.Endpoint[index+1:])
			if err == nil {
				return port
			}
		}
	}

	return 0
}

// UseHTTPS returns true if server certificate and key is defined.
func (cfg *Config) UseHTTPS() bool {
	return cfg.ServerCertfile != "" && cfg.ServerKeyfile != ""
}

// DeclareHTTPPortFlag declares http port (with usage & default value) a flag for a particular plugin name
func DeclareHTTPPortFlag(pluginName infra.PluginName, defaultPortOpts ...uint) {
	var defaultPort string
	if len(defaultPortOpts) > 0 {
		defaultPort = string(defaultPortOpts[0])
	} else {
		defaultPort = DefaultHTTPPort
	}

	plugNameUpper := strings.ToUpper(string(pluginName))

	usage := "Configure Agent' " + plugNameUpper + " server (port & timeouts); also set via '" +
		plugNameUpper + config.EnvSuffix + "' env variable."
	flag.String(httpPortFlag(pluginName), defaultPort, usage)
}

func httpPortFlag(pluginName infra.PluginName) string {
	return strings.ToLower(string(pluginName)) + "-port"
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?><project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>parent-parse-xex</artifactId>
    <groupId>org.apache.maven.errortest</groupId>
    <version>1</version>
  </parent>
  <artifactId>parent-parse-xex-child</artifactId>

</project>


text:
// this defines the base class for dialogs used in HeeksCAD

#pragma once

class HControl
{
public:
	wxWindow *m_w;
	wxSizer *m_s;
	int m_add_flag; // flag for wxBoxSizer.Add( , ,flag)

	HControl(wxWindow* w, int flag):m_w(w), m_s(NULL), m_add_flag(flag){}
	HControl(wxSizer* s, int flag):m_w(NULL), m_s(s), m_add_flag(flag){}

	wxSizerItem* AddToSizer(wxSizer* s);
};

class HTypeObjectDropDown: public wxComboBox
{
public:
	int m_object_type;
	HeeksObj* m_obj_list;
	std::vector< std::pair< int, wxString > > m_ids_for_combo;

	HTypeObjectDropDown(wxWindow *parent, wxWindowID id, int object_type, HeeksObj* obj_list);
	int GetSelectedId();
	void SelectById(int id);
	void Recreate();

	static wxArrayString GetObjectArrayString(int object_type, HeeksObj* obj_list, std::vector< std::pair< int, wxString > > &ids_for_combo);
};

class CLengthCtrl;
class HDialog;

class XYZBoxes: public wxStaticBoxSizer
{
public:
	CLengthCtrl *m_lgthX;
	CLengthCtrl *m_lgthY;
	CLengthCtrl *m_lgthZ;
	wxStaticText *m_sttcX;
	wxStaticText *m_sttcY;
	wxStaticText *m_sttcZ;

	XYZBoxes(HDialog *dlg, const wxString& label, const wxString &xstr, const wxString &ystr, const wxString &zstr);
};

class HDialog : public wxDialog
{
public:
	static const int control_border; // the border around controls

	bool m_ignore_event_functions;

	HControl MakeLabelAndControl(const wxString& label, wxWindow* control, wxStaticText** static_text = NULL);
	HControl MakeLabelAndControl(const wxString& label, wxWindow* control1, wxWindow* control2, wxStaticText** static_text = NULL);
	wxStaticText *AddLabelAndControl(wxBoxSizer* sizer, const wxString& label, wxWindow* control);
	HControl MakeOkAndCancel(int orient);

	HDialog(wxWindow *parent, wxWindowID id = wxID_ANY, const wxString& title = wxString(_T("")), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE, const wxString& name = wxDialogNameStr);
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phyllosticta bufonii Oudem.

### Remarks
null


text:
package com.huassit.imenu.android.parser;

/**
 * Created by Sylar on 14-7-15.
 */
public class VersionParser {
}


text:
using Microsoft.Phone.BackgroundAudio;
using Microsoft.Phone.Controls;
using Mle.ViewModels;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Navigation;
using Mle.MusicPimp.Network;

namespace Mle {
    public partial class PivotPage1 : PhoneApplicationPage {
        public PivotPage1() {
            InitializeComponent();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e) {
            if (DataContext == null) {
                DataContext = TestModel.Instance;
            }
        }

    }
}


text:
<?php

use org\bovigo\vfs\vfsStream;

abstract class TestCase extends \PHPUnit_Framework_TestCase {
    /**
     * @var  vfsStreamDirectory
     */
    protected $root;

    /**
     * Set up for each test
     */
    public function setUp()
    {
        // setup
        $this->root = vfsStream::setup('assets');

        // Copy directory structure from file system
        vfsStream::copyFromFileSystem(__DIR__ . '/assets');
    }
}


text:
<?php //print_r($product_details);die;  ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Find The Best || Home</title>
        <link href="<?php echo base_url(); ?>assets/frontend/css/bootstrap.css" type="text/css" rel="stylesheet" />
        <link href="<?php echo base_url(); ?>assets/frontend/css/bootstrap-theme.css" type="text/css" rel="stylesheet" />
        <link href="<?php echo base_url(); ?>assets/frontend/css/style.css" type="text/css" rel="stylesheet" />
        <link href="<?php echo base_url(); ?>assets/frontend/fonts/stylesheet.css" type="text/css" rel="stylesheet" />

                <?php $this->load->view('users/include/inner_category_dropdown.php'); ?>

Home

Electronics

Headphones

Detail

                            <img id="main" src="<?php echo base_url(); ?>images/products/<?php echo $product_details->thumb_image; ?>" alt="Alt title of image" >

                                    <a href="<?php echo base_url(); ?>images/products/<?php echo $product_details->image; ?>"><img src="<?php echo base_url(); ?>images/products/headphone.jpg" width="91" height="73" alt="Headphone">
                                    <a href="<?php echo base_url(); ?>images/products/<?php echo $product_details->thumb_image; ?>"><img src="<?php echo base_url(); ?>images/products/headphonetwo.jpg" width="91" height="73" alt="Headphone2">

<?php echo $product_details->name; ?>

                                        <input type="checkbox" id="inlineCheckbox1" value="option1">Add to Compare

                                    <img src="<?php echo base_url(); ?>assets/img/comment_ico.png" alt="Comment" class="img-responsive" />
                                    Write a review

As Low As

                            <select class="form-control">
                                <option selected="selected">$ 1350</option>
                            </select>

                                    Style: On Ear

                                    Category: Gaming

                                    Color(s): Black

                                    MSRP: $ <?php echo $product_details->price; ?>

Smart Rating

                                                <?php echo $avg_review->totalrate; ?>

What's This ?

Add Your Ratings

                                            <img src="<?php echo base_url(); ?>assets/img/review_ico.png" alt="Review" class="img-responsive" />
                                            <img src="<?php echo base_url(); ?>assets/img/review_ico.png" alt="Review" class="img-responsive" />
                                            <img src="<?php echo base_url(); ?>assets/img/review_ico.png" alt="Review" class="img-responsive" />
                                            <img src="<?php echo base_url(); ?>assets/img/review_ico.png" alt="Review" class="img-responsive" />
                                            <img src="<?php echo base_url(); ?>assets/img/review_ico.png" alt="Review" class="img-responsive" />

Review

Experts Say

                            <?php foreach ($review_details as $reviews) { ?>

<?php echo $reviews->name ?>

                                        <?php for ($i = 1; $i <= ($reviews->rate); $i++) { ?>
                                            <img src="<?php echo base_url(); ?>assets/img/review_active_ico.png" alt="Review" class="img-responsive" />
                                        <?php } ?>
                                        <?php for ($j = 1; $j <= 5 - ($reviews->rate); $j++) { ?>
                                            <img src="<?php echo base_url(); ?>assets/img/review_ico.png" alt="Review" class="img-responsive" />
                                        <?php } ?>

<?php echo $reviews->rate . '.0'; ?>

                                        <?php echo $reviews->review; ?>

                            <?php } ?>

                                <img src="<?php echo base_url(); ?>images/products/headphone.jpg" alt="Headphone" width="30px" height="30px" />
                                Review <?php echo $product_details->name; ?>

                            <form class="form-horizontal" role="form" action="" method="post">

                                    Rate this <?php echo $product_details->name; ?>

                                    Click stars to rate

                                <?php $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>

                                    <input type="hidden" name="pageurl" value="<?php echo $actual_link; ?>">

                                            Write your review

                                                <textarea class="form-control" name="review" rows="5" style="resize:none;"></textarea>

                                        <button class="price_btn pull-right" type="submit">Post Review</button>
                                        </form>

Related Topics

                                    <img src="<?php echo base_url(); ?>assets/img/related_product1.png" alt="Related Products" class="img-responsive" />

Laptop and Notebooks

                                    <img src="<?php echo base_url(); ?>assets/img/related_product2.png" alt="Related Products" class="img-responsive" />

Digital Pianos and Keyboards

                                    <img src="<?php echo base_url(); ?>assets/img/related_product3.png" alt="Related Products" class="img-responsive" />

Tablets

                                    <img src="<?php echo base_url(); ?>assets/img/related_product4.png" alt="Related Products" class="img-responsive" />

Mp3 Players

                                    <img src="<?php echo base_url(); ?>assets/img/related_product1.png" alt="Related Products" class="img-responsive" />

Laptop and Notebooks

                                    <img src="<?php echo base_url(); ?>assets/img/related_product2.png" alt="Related Products" class="img-responsive" />

Digital Pianos and Keyboards

                                    <img src="<?php echo base_url(); ?>assets/img/related_product3.png" alt="Related Products" class="img-responsive" />

Tablets

                                    <img src="<?php echo base_url(); ?>assets/img/related_product4.png" alt="Related Products" class="img-responsive" />

Mp3 Players

About Support

Advertising

Publisher Tools

Stories

Companies

Homes

MooseRoots

Software

Electronics

Terms

Privacy

Cookies

2014 FindTheBest.com, Inc. All Rights Reserved.

<img src="<?php echo base_url(); ?>assets/img/facebook.png" alt="Facebook" />

<img src="<?php echo base_url(); ?>assets/img/twitter.png" alt="Twitter" />

<img src="<?php echo base_url(); ?>assets/img/google_plush.png" alt="Google Plush" />

<img src="<?php echo base_url(); ?>assets/img/instragram.png" alt="Instragram" />


text:
using System.Threading.Tasks;
using Xunit;

namespace System.Threading.Tests
{
    public class MutexTests
    {
        private const int FailedWaitTimeout = 30000;

        [Fact]
        public void Ctor_ConstructWaitRelease()
        {
            using (Mutex m = new Mutex())
            {
                Assert.True(m.WaitOne(FailedWaitTimeout));
                m.ReleaseMutex();
            }

            using (Mutex m = new Mutex(false))
            {
                Assert.True(m.WaitOne(FailedWaitTimeout));
                m.ReleaseMutex();
            }

            using (Mutex m = new Mutex(true))
            {
                Assert.True(m.WaitOne(FailedWaitTimeout));
                m.ReleaseMutex();
                m.ReleaseMutex();
            }
        }

        [PlatformSpecific(PlatformID.AnyUnix)]
        [Fact]
        public void Ctor_NamesNotSupported_Unix()
        {
            Assert.Throws<PlatformNotSupportedException>(() => new Mutex(false, "anyname"));
        }

        [PlatformSpecific(PlatformID.Windows)]
        [Fact]
        public void Ctor_InvalidName()
        {
            Assert.Throws<ArgumentException>(() => new Mutex(false, new string('a', 1000)));
        }

        [PlatformSpecific(PlatformID.Windows)]
        [Fact]
        public void Ctor_ValidName_Windows()
        {
            string name = Guid.NewGuid().ToString("N");
            bool createdNew;
            using (Mutex m1 = new Mutex(false, name, out createdNew))
            {
                Assert.True(createdNew);
                using (Mutex m2 = new Mutex(false, name, out createdNew))
                {
                    Assert.False(createdNew);
                }
            }
        }

        [PlatformSpecific(PlatformID.Windows)]
        [Fact]
        public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows()
        {
            string name = Guid.NewGuid().ToString("N");
            using (Semaphore s = new Semaphore(1, 1, name))
            {
                Assert.Throws<WaitHandleCannotBeOpenedException>(() => new Mutex(false, name));
            }
        }

        [PlatformSpecific(PlatformID.Windows)]
        [Fact]
        public void OpenExisting_Windows()
        {
            string name = Guid.NewGuid().ToString("N");

            Mutex resultHandle;
            Assert.False(Mutex.TryOpenExisting(name, out resultHandle));

            using (Mutex m1 = new Mutex(false, name))
            {
                using (Mutex m2 = Mutex.OpenExisting(name))
                {
                    Assert.True(m1.WaitOne(FailedWaitTimeout));
                    Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
                    m1.ReleaseMutex();

                    Assert.True(m2.WaitOne(FailedWaitTimeout));
                    Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
                    m2.ReleaseMutex();
                }

                Assert.True(Mutex.TryOpenExisting(name, out resultHandle));
                Assert.NotNull(resultHandle);
                resultHandle.Dispose();
            }
        }

        [PlatformSpecific(PlatformID.AnyUnix)]
        [Fact]
        public void OpenExisting_NotSupported_Unix()
        {
            Assert.Throws<PlatformNotSupportedException>(() => Mutex.OpenExisting("anything"));
            Mutex ewh;
            Assert.Throws<PlatformNotSupportedException>(() => Mutex.TryOpenExisting("anything", out ewh));
        }

        [PlatformSpecific(PlatformID.Windows)]
        [Fact]
        public void OpenExisting_InvalidNames_Windows()
        {
            Assert.Throws<ArgumentNullException>("name", () => Mutex.OpenExisting(null));
            Assert.Throws<ArgumentException>(() => Mutex.OpenExisting(string.Empty));
            Assert.Throws<ArgumentException>(() => Mutex.OpenExisting(new string('a', 10000)));
        }

        [PlatformSpecific(PlatformID.Windows)]
        [Fact]
        public void OpenExisting_UnavailableName_Windows()
        {
            string name = Guid.NewGuid().ToString("N");
            Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
            Mutex ignored;
            Assert.False(Mutex.TryOpenExisting(name, out ignored));
        }

        [PlatformSpecific(PlatformID.Windows)]
        [Fact]
        public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows()
        {
            string name = Guid.NewGuid().ToString("N");
            using (Semaphore sema = new Semaphore(1, 1, name))
            {
                Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
                Mutex ignored;
                Assert.False(Mutex.TryOpenExisting(name, out ignored));
            }
        }

        [Fact]
        public void AbandonExisting()
        {
            using (Mutex m = new Mutex())
            {
                Task t = Task.Factory.StartNew(() =>
                {
                    Assert.True(m.WaitOne(FailedWaitTimeout));
                // don't release the mutex; abandon it on this thread
            }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
                t.Wait();
                Assert.Throws<AbandonedMutexException>(() => m.WaitOne(FailedWaitTimeout));
            }

            using (Mutex m = new Mutex())
            {
                Task t = Task.Factory.StartNew(() =>
                {
                    Assert.True(m.WaitOne(FailedWaitTimeout));
                }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
                t.Wait();
                AbandonedMutexException ame = Assert.Throws<AbandonedMutexException>(() => WaitHandle.WaitAny(new[] { m }, FailedWaitTimeout));
                Assert.Equal(0, ame.MutexIndex);
                Assert.Equal(m, ame.Mutex);
            }
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>

    </title>
    <meta http-Equiv="Cache-Control" Content="no-cache">
    <meta http-Equiv="Pragma" Content="no-cache">
    <meta http-Equiv="Expires" Content="0">
    <link rel="stylesheet" type="text/css" href="https://brunelvis.org/js/brunel.2.0.css" charset="utf-8"></link>
    <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"
          charset="utf-8"></link>
    <link rel="stylesheet" type="text/css" href="https://brunelvis.org/js/sumoselect.css" charset="utf-8"></link>

Brunel Javascript Demo

The content on this page is dynamically generated by the Brunel service.

    <svg id="visualization" width="375" height="375"></svg>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
P. H. Lecomte & H. Humbert, Fl. Indo-Chine 5:1092. 1931

#### Original name
null

### Remarks
null


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.dertroglodyt.scribeop;

import de.dertroglodyt.scribeop.json.JSONArray;
import de.dertroglodyt.scribeop.json.JSONException;
import de.dertroglodyt.scribeop.json.JSONObject;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author dertroglodyt
 */
public class OPUser {

    private static final String URL = "http://api.obsidianportal.com/v1/users/$id.json";
    private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    public final String id;
    public final String userName;
    public final String avatarImageUrl;
    public final String profileUrl;
    public final OPCampaignMini[] campaigns;
    public final boolean isAscendant;
    public final Date lastSeenAt;
    public final String utcOffset;
    public final String locale;
    public final Date createdAt;
    public final Date updatedAt;

    public OPUser(OPService service, String userID) throws JSONException, ParseException {
        this(new JSONObject(service.get(URL.replace("$id", (userID == null)?"me":userID)).getBody()));
    }

    public OPUser(JSONObject json) throws JSONException, ParseException {
        super();
        id = json.getString("id");
        userName = json.getString("username");
        avatarImageUrl = json.getString("avatar_image_url");
        profileUrl = json.getString("profile_url");
        JSONArray camp = json.getJSONArray("campaigns");
        campaigns = new OPCampaignMini[camp.length()];
        for (int i = 0; i < camp.length(); i++) {
            JSONObject jsonObj = camp.getJSONObject(i);
            campaigns[i] = new OPCampaignMini(jsonObj);
        }
        isAscendant = json.getBoolean("is_ascendant");
        lastSeenAt = df.parse(json.getString("last_seen_at"));
        utcOffset = json.getString("utc_offset");
        locale = json.getString("locale");
        createdAt = df.parse(json.getString("created_at"));
        updatedAt = df.parse(json.getString("updated_at"));
    }

    @Override
    public String toString() {
        return userName;
    }

    public String toLongString() {
        StringBuilder sb = new StringBuilder("User: (").append('\n');
        sb.append("  ").append(userName).append('\n');
        sb.append(", ID: ").append(id).append('\n');
        sb.append(", ImageURL: ").append(avatarImageUrl).append('\n');
        sb.append(", ProfileURL: ").append(profileUrl).append('\n');
        sb.append(", Campaigns: (").append('\n');
        for (OPCampaignMini camp : campaigns) {
            sb.append("  , ").append(camp.toLongString()).append('\n');
        }
        sb.append("  )").append('\n');
        sb.append(", Ascendant: ").append(isAscendant).append('\n');
        sb.append(", LastSeen: ").append(lastSeenAt).append('\n');
        sb.append(", UTC-Offset: ").append(utcOffset).append('\n');
        sb.append(", Locale: ").append(locale).append('\n');
        sb.append(", Created: ").append(createdAt).append('\n');
        sb.append(", Updated: ").append(updatedAt).append('\n');
        sb.append(")").append('\n');
        return sb.toString();
    }
}


text:
package org.wso2.carbon.identity.tenant.resource.manager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.event.publisher.core.config.EventPublisherConfiguration;
import org.wso2.carbon.event.publisher.core.exception.EventPublisherConfigurationException;
import org.wso2.carbon.event.stream.core.EventStreamConfiguration;
import org.wso2.carbon.event.stream.core.exception.EventStreamConfigurationException;
import org.wso2.carbon.identity.configuration.mgt.core.constant.ConfigurationConstants;
import org.wso2.carbon.identity.configuration.mgt.core.exception.ConfigurationManagementException;
import org.wso2.carbon.identity.configuration.mgt.core.model.Resource;
import org.wso2.carbon.identity.configuration.mgt.core.model.ResourceFile;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants;
import org.wso2.carbon.identity.tenant.resource.manager.exception.TenantResourceManagementException;
import org.wso2.carbon.identity.tenant.resource.manager.internal.TenantResourceManagerDataHolder;
import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

import java.util.List;

import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_ADDING_EVENT_PUBLISHER_CONFIGURATION;
import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_CREATING_TENANT_EVENT_PUBLISHER_CONFIGURATION_USING_SUPER_TENANT_CONFIG;
import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_CREATING_TENANT_EVENT_STREAM_CONFIGURATION;
import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_FETCHING_TENANT_SPECIFIC_PUBLISHER_FILES;
import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.PUBLISHER;
import static org.wso2.carbon.identity.tenant.resource.manager.util.ResourceUtils.populateMessageWithData;

/**
 * Axis2Observer for generating tenant wise publisher configurations.
 */
public class TenantAwareAxis2ConfigurationContextObserver extends AbstractAxis2ConfigurationContextObserver {

    private static final Log log = LogFactory.getLog(TenantAwareAxis2ConfigurationContextObserver.class);

    /**
     * Add the tenant wise publisher and stream Configuration in tenant loading.
     *
     * @param tenantId tenant ID.
     */
    @Override
    public void creatingConfigurationContext(int tenantId) {

        String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        log.info("Loading configuration context for tenant domain: " + tenantDomain);
        loadEventStreamAndPublisherConfigurations(tenantId);
    }

    /**
     * This method loads event stream and publisher configurations for a specific tenant.
     *
     * @param tenantId     tenant id.
     */
    private void loadEventStreamAndPublisherConfigurations(int tenantId) {

        List<EventPublisherConfiguration> activeEventPublisherConfigurations;
        List<EventStreamConfiguration> eventStreamConfigurationList;
        try {
            startSuperTenantFlow();
            activeEventPublisherConfigurations = getSuperTenantEventPublisherConfigurations();
            eventStreamConfigurationList = getSuperTenantEventStreamConfigurations();
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
        try {
            startTenantFlow(tenantId);
            loadTenantEventStreams(eventStreamConfigurationList);
            loadTenantPublisherConfigurationFromConfigStore();

            if (activeEventPublisherConfigurations != null) {
                loadTenantPublisherConfigurationFromSuperTenantConfig(activeEventPublisherConfigurations);
            }
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }

    /**
     * This method loads publisher configurations tenant wise by fetching them from configuration store.
     */
    private void loadTenantPublisherConfigurationFromConfigStore() {

        try {
            List<Resource> resourcesByTypePublisher = TenantResourceManagerDataHolder.getInstance()
                    .getConfigurationManager().getResourcesByType(PUBLISHER).getResources();
            for (Resource resource : resourcesByTypePublisher) {
                ResourceFile tenantSpecificPublisherFile = resource.getFiles().get(0);
                if (tenantSpecificPublisherFile != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("File for publisher name: " + tenantSpecificPublisherFile.getName()
                                + " is available in the configuration store.");
                    }
                    TenantResourceManagerDataHolder.getInstance().getResourceManager()
                            .addEventPublisherConfiguration(tenantSpecificPublisherFile);
                }
            }
        } catch (ConfigurationManagementException e) {
            if (e.getErrorCode()
                    .equals(ConfigurationConstants.ErrorMessages.ERROR_CODE_FEATURE_NOT_ENABLED.getCode())) {
                log.warn("Configuration store is disabled. Super tenant configuration will be used for the tenant "
                        + "domain: " + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
            } else if (e.getErrorCode()
                    .equals(ConfigurationConstants.ErrorMessages.ERROR_CODE_RESOURCES_DOES_NOT_EXISTS.getCode())) {
                log.warn("Configuration store does not contain any resources under resource type publisher. Super "
                        + "tenant configurations will be used for the tenant domain: " + PrivilegedCarbonContext
                        .getThreadLocalCarbonContext().getTenantDomain());
            } else if (e.getErrorCode()
                    .equals(ConfigurationConstants.ErrorMessages.ERROR_CODE_RESOURCE_TYPE_DOES_NOT_EXISTS.getCode())) {
                log.warn("Configuration store does not contain  publisher resource type. Super "
                        + "tenant configurations will be used for the tenant domain: " + PrivilegedCarbonContext
                        .getThreadLocalCarbonContext().getTenantDomain());
            } else {
                log.error(populateMessageWithData(ERROR_CODE_ERROR_WHEN_FETCHING_TENANT_SPECIFIC_PUBLISHER_FILES,
                        PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()), e);
            }
        } catch (TenantResourceManagementException e) {
            log.error(populateMessageWithData(ERROR_CODE_ERROR_WHEN_ADDING_EVENT_PUBLISHER_CONFIGURATION,
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()), e);
        }
    }

    /**
     * This method returns super tenant event publisher configurations.
     *
     * @return list of event publisher configurations.
     */
    private List<EventPublisherConfiguration> getSuperTenantEventPublisherConfigurations() {

        List<EventPublisherConfiguration> activeEventPublisherConfigurations = null;
        try {
            activeEventPublisherConfigurations = TenantResourceManagerDataHolder.getInstance()
                    .getCarbonEventPublisherService().getAllActiveEventPublisherConfigurations();
        } catch (EventPublisherConfigurationException e) {
            log.error(populateMessageWithData(
                    TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_FETCHING_SUPER_TENANT_EVENT_PUBLISHER_CONFIGURATION,
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()), e);
        }
        return activeEventPublisherConfigurations;
    }

    /**
     * This method returns super tenant event stream configurations.
     *
     * @return list of event stream configurations.
     */
    private List<EventStreamConfiguration> getSuperTenantEventStreamConfigurations() {

        List<EventStreamConfiguration> eventStreamConfigurationList = null;
        try {
            eventStreamConfigurationList = TenantResourceManagerDataHolder.getInstance().getCarbonEventStreamService()
                    .getAllEventStreamConfigurations();
        } catch (EventStreamConfigurationException e) {
            log.error(populateMessageWithData(
                    TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_FETCHING_SUPER_TENANT_EVENT_STREAM_CONFIGURATION,
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()), e);
        }
        return eventStreamConfigurationList;
    }

    private void startTenantFlow(int tenantId) {

        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .setTenantDomain(IdentityTenantUtil.getTenantDomain(tenantId));
    }

    private void startSuperTenantFlow() {

        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    }

    /**
     * This method creates event publisher configurations tenant wise by using super tenant publisher configurations.
     *
     * @param activeEventPublisherConfigurations list of active super tenant publisher configurations.
     */
    private void loadTenantPublisherConfigurationFromSuperTenantConfig(
            List<EventPublisherConfiguration> activeEventPublisherConfigurations) {

        for (EventPublisherConfiguration eventPublisherConfiguration : activeEventPublisherConfigurations) {
            try {
                if (TenantResourceManagerDataHolder.getInstance().getCarbonEventPublisherService()
                        .getActiveEventPublisherConfiguration(eventPublisherConfiguration.getEventPublisherName())
                        == null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Super tenant event publisher configuration for the: " + eventPublisherConfiguration
                                .getEventPublisherName() + " will be used for the tenant domain: "
                                + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
                    }
                    TenantResourceManagerDataHolder.getInstance().getCarbonEventPublisherService()
                            .addEventPublisherConfiguration(eventPublisherConfiguration);
                }
            } catch (EventPublisherConfigurationException e) {
                log.error(populateMessageWithData(
                        ERROR_CODE_ERROR_WHEN_CREATING_TENANT_EVENT_PUBLISHER_CONFIGURATION_USING_SUPER_TENANT_CONFIG,
                        PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()), e);
            }
        }
    }

    /**
     * This method loads event stream configurations tenant wise by using super tenant publisher configurations.
     *
     * @param eventStreamConfigurationList list of active super tenant stream configurations.
     */
    private void loadTenantEventStreams(List<EventStreamConfiguration> eventStreamConfigurationList) {

        if (eventStreamConfigurationList != null) {
            for (EventStreamConfiguration eventStreamConfiguration : eventStreamConfigurationList) {
                if (TenantResourceManagerDataHolder.getInstance().getCarbonEventStreamService()
                        .getEventStreamConfiguration(eventStreamConfiguration.getStreamDefinition().getStreamId())
                        == null) {
                    try {
                        TenantResourceManagerDataHolder.getInstance().getCarbonEventStreamService()
                                .addEventStreamConfig(eventStreamConfiguration);
                    } catch (EventStreamConfigurationException e) {
                        log.error(populateMessageWithData(
                                ERROR_CODE_ERROR_WHEN_CREATING_TENANT_EVENT_STREAM_CONFIGURATION,
                                PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()), e);
                    }
                }
            }
        }
    }
}


text:
FROM node:6-slim

# User management
# Make sure we switch to the correct user/group before doing anything else
ARG user
RUN adduser --disabled-login --gecos "" --uid 1000 --home /home/purescript $user
RUN echo 'export PS1="\W\$ "' >> /home/purescript/.bashrc

RUN apt-get -qq update && apt-get install -qy curl make jq git
RUN npm install -qg bower pulp purescript

USER $user
WORKDIR /home/purescript
ENV USER $user
CMD ["bash"]