org.agrona.collections.ArrayUtil Java Examples

The following examples show how to use org.agrona.collections.ArrayUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NetworkPublication.java    From aeron with Apache License 2.0 6 votes vote down vote up
public void addSubscriber(final SubscriptionLink subscriptionLink, final ReadablePosition position)
{
    spyPositions = ArrayUtil.add(spyPositions, position);
    hasSpies = true;

    if (!subscriptionLink.isTether())
    {
        untetheredSubscriptions.add(new UntetheredSubscription(subscriptionLink, position, nanoClock.nanoTime()));
    }

    if (spiesSimulateConnection)
    {
        LogBufferDescriptor.isConnected(metaDataBuffer, true);
        isConnected = true;
    }
}
 
Example #2
Source File: PublicationImage.java    From aeron with Apache License 2.0 6 votes vote down vote up
/**
 * Add a destination to this image so it can merge streams.
 *
 * @param transportIndex from which packets will arrive.
 * @param transport      from which packets will arrive.
 */
void addDestination(final int transportIndex, final ReceiveDestinationTransport transport)
{
    imageConnections = ArrayUtil.ensureCapacity(imageConnections, transportIndex + 1);

    if (transport.isMulticast())
    {
        imageConnections[transportIndex] = new ImageConnection(
            cachedNanoClock.nanoTime(), transport.udpChannel().remoteControl());
    }
    else if (transport.hasExplicitControl())
    {
        imageConnections[transportIndex] = new ImageConnection(
            cachedNanoClock.nanoTime(), transport.explicitControlAddress());
    }
}
 
Example #3
Source File: SampleAuthenticator.java    From aeron with Apache License 2.0 6 votes vote down vote up
public void onChallengedSession(final SessionProxy sessionProxy, final long nowMs)
{
    final SessionState sessionState = sessionIdToStateMap.get(sessionProxy.sessionId());

    if (null != sessionState)
    {
        switch (sessionState)
        {
            case AUTHENTICATED:
                sessionProxy.authenticate(ArrayUtil.EMPTY_BYTE_ARRAY);
                break;

            case REJECT:
                sessionProxy.reject();
                break;
        }
    }
}
 
Example #4
Source File: SampleAuthenticator.java    From aeron with Apache License 2.0 6 votes vote down vote up
public void onConnectedSession(final SessionProxy sessionProxy, final long nowMs)
{
    final SessionState sessionState = sessionIdToStateMap.get(sessionProxy.sessionId());

    if (null != sessionState)
    {
        switch (sessionState)
        {
            case CHALLENGE:
                sessionProxy.challenge((CHALLENGE_STRING.getBytes()));
                break;

            case AUTHENTICATED:
                sessionProxy.authenticate(ArrayUtil.EMPTY_BYTE_ARRAY);
                break;

            case REJECT:
                sessionProxy.reject();
                break;
        }
    }
}
 
Example #5
Source File: Subscription.java    From aeron with Apache License 2.0 6 votes vote down vote up
Image removeImage(final long correlationId)
{
    final Image[] oldArray = images;
    Image removedImage = null;

    int i = 0;
    for (final Image image : oldArray)
    {
        if (image.correlationId() == correlationId)
        {
            removedImage = image;
            break;
        }

        i++;
    }

    if (null != removedImage)
    {
        removedImage.close();
        images = ArrayUtil.remove(oldArray, i);
        conductor.releaseLogBuffers(removedImage.logBuffers(), correlationId);
    }

    return removedImage;
}
 
Example #6
Source File: DataTransportPoller.java    From aeron with Apache License 2.0 6 votes vote down vote up
public SelectionKey registerForRead(
    final ReceiveChannelEndpoint channelEndpoint, final UdpChannelTransport transport, final int transportIndex)
{
    SelectionKey key = null;
    try
    {
        final ChannelAndTransport channelAndTransport = new ChannelAndTransport(
            channelEndpoint, transport, transportIndex);

        key = transport.receiveDatagramChannel().register(selector, SelectionKey.OP_READ, channelAndTransport);
        channelAndTransports = ArrayUtil.add(channelAndTransports, channelAndTransport);
    }
    catch (final ClosedChannelException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }

    return key;
}
 
Example #7
Source File: DataTransportPoller.java    From aeron with Apache License 2.0 6 votes vote down vote up
public void cancelRead(final ReceiveChannelEndpoint channelEndpoint, final UdpChannelTransport transport)
{
    final ChannelAndTransport[] transports = this.channelAndTransports;
    int index = ArrayUtil.UNKNOWN_INDEX;

    for (int i = 0, length = transports.length; i < length; i++)
    {
        if (channelEndpoint == transports[i].channelEndpoint && transport == transports[i].transport)
        {
            index = i;
            break;
        }
    }

    if (index != ArrayUtil.UNKNOWN_INDEX)
    {
        channelAndTransports = ArrayUtil.remove(transports, index);
    }
}
 
Example #8
Source File: ClusterTool.java    From aeron with Apache License 2.0 6 votes vote down vote up
private static ClusterMarkFile[] openServiceMarkFiles(final File clusterDir, final Consumer<String> logger)
{
    String[] clusterMarkFileNames =
        clusterDir.list((dir, name) ->
            name.startsWith(ClusterMarkFile.SERVICE_FILENAME_PREFIX) &&
                name.endsWith(ClusterMarkFile.FILE_EXTENSION));

    if (null == clusterMarkFileNames)
    {
        clusterMarkFileNames = ArrayUtil.EMPTY_STRING_ARRAY;
    }

    final ClusterMarkFile[] clusterMarkFiles = new ClusterMarkFile[clusterMarkFileNames.length];

    for (int i = 0, length = clusterMarkFiles.length; i < length; i++)
    {
        clusterMarkFiles[i] = new ClusterMarkFile(
            clusterDir, clusterMarkFileNames[i], System::currentTimeMillis, TIMEOUT_MS, logger);
    }

    return clusterMarkFiles;
}
 
Example #9
Source File: MultiRcvDestination.java    From aeron with Apache License 2.0 6 votes vote down vote up
int addDestination(final ReceiveDestinationTransport transport)
{
    int index = transports.length;

    for (int i = 0, length = transports.length; i < length; i++)
    {
        if (null == transports[i])
        {
            index = i;
            break;
        }
    }

    transports = ArrayUtil.ensureCapacity(transports, index + 1);
    transports[index] = transport;
    numDestinations++;

    return index;
}
 
Example #10
Source File: PublicationImage.java    From aeron with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void removeSubscriber(final SubscriptionLink subscriptionLink, final ReadablePosition subscriberPosition)
{
    subscriberPositions = ArrayUtil.remove(subscriberPositions, subscriberPosition);
    subscriberPosition.close();

    if (!subscriptionLink.isTether())
    {
        for (int lastIndex = untetheredSubscriptions.size() - 1, i = lastIndex; i >= 0; i--)
        {
            if (untetheredSubscriptions.get(i).subscriptionLink == subscriptionLink)
            {
                ArrayListUtil.fastUnorderedRemove(untetheredSubscriptions, i, lastIndex);
                break;
            }
        }
    }

    if (subscriberPositions.length == 0)
    {
        isRebuilding = false;
    }
}
 
Example #11
Source File: ClusterMember.java    From aeron with Apache License 2.0 6 votes vote down vote up
/**
 * Find the index at which a member id is present.
 *
 * @param clusterMembers to be searched.
 * @param memberId       to search for.
 * @return the index at which the member id is found otherwise {@link ArrayUtil#UNKNOWN_INDEX}.
 */
public static int findMemberIndex(final ClusterMember[] clusterMembers, final int memberId)
{
    final int length = clusterMembers.length;
    int index = ArrayUtil.UNKNOWN_INDEX;

    for (int i = 0; i < length; i++)
    {
        if (clusterMembers[i].id() == memberId)
        {
            index = i;
        }
    }

    return index;
}
 
Example #12
Source File: NetworkPublication.java    From aeron with Apache License 2.0 6 votes vote down vote up
public void removeSubscriber(final SubscriptionLink subscriptionLink, final ReadablePosition position)
{
    spyPositions = ArrayUtil.remove(spyPositions, position);
    hasSpies = spyPositions.length > 0;
    position.close();

    if (!subscriptionLink.isTether())
    {
        for (int lastIndex = untetheredSubscriptions.size() - 1, i = lastIndex; i >= 0; i--)
        {
            if (untetheredSubscriptions.get(i).subscriptionLink == subscriptionLink)
            {
                ArrayListUtil.fastUnorderedRemove(untetheredSubscriptions, i, lastIndex);
                break;
            }
        }
    }
}
 
Example #13
Source File: Receiver.java    From aeron with Apache License 2.0 6 votes vote down vote up
public void onRemoveDestination(final ReceiveChannelEndpoint channelEndpoint, final UdpChannel udpChannel)
{
    final int transportIndex = channelEndpoint.destination(udpChannel);

    if (ArrayUtil.UNKNOWN_INDEX != transportIndex)
    {
        final ReceiveDestinationTransport transport = channelEndpoint.destination(transportIndex);

        dataTransportPoller.cancelRead(channelEndpoint, transport);
        channelEndpoint.removeDestination(transportIndex);
        CloseHelper.close(transport);
        dataTransportPoller.selectNowWithoutProcessing();

        for (final PublicationImage image : publicationImages)
        {
            if (channelEndpoint == image.channelEndpoint())
            {
                image.removeDestination(transportIndex);
            }
        }
    }
}
 
Example #14
Source File: IpcPublication.java    From aeron with Apache License 2.0 6 votes vote down vote up
public void removeSubscriber(final SubscriptionLink subscriptionLink, final ReadablePosition subscriberPosition)
{
    consumerPosition = Math.max(consumerPosition, subscriberPosition.getVolatile());
    subscriberPositions = ArrayUtil.remove(subscriberPositions, subscriberPosition);
    subscriberPosition.close();

    if (subscriberPositions.length == 0)
    {
        LogBufferDescriptor.isConnected(metaDataBuffer, false);
    }

    if (!subscriptionLink.isTether())
    {
        for (int lastIndex = untetheredSubscriptions.size() - 1, i = lastIndex; i >= 0; i--)
        {
            if (untetheredSubscriptions.get(i).subscriptionLink == subscriptionLink)
            {
                ArrayListUtil.fastUnorderedRemove(untetheredSubscriptions, i, lastIndex);
                break;
            }
        }
    }
}
 
Example #15
Source File: DynamicCompositeAgent.java    From agrona with Apache License 2.0 6 votes vote down vote up
private void add(final Agent agent)
{
    addAgent.lazySet(null);

    try
    {
        agent.onStart();
    }
    catch (final RuntimeException ex)
    {
        agent.onClose();
        throw ex;
    }

    agents = ArrayUtil.add(agents, agent);
}
 
Example #16
Source File: DynamicCompositeAgent.java    From agrona with Apache License 2.0 6 votes vote down vote up
private void remove(final Agent agent)
{
    removeAgent.lazySet(null);
    final Agent[] newAgents = ArrayUtil.remove(agents, agent);

    try
    {
        if (newAgents != agents)
        {
            agent.onClose();
        }
    }
    finally
    {
        agents = newAgents;
    }
}
 
Example #17
Source File: LibraryPoller.java    From artio with Apache License 2.0 6 votes vote down vote up
private int pollPendingInitiatorSessions(final long timeInMs)
{
    InternalSession[] pendingSessions = this.pendingInitiatorSessions;
    int total = 0;

    for (int i = 0, size = pendingSessions.length; i < size;)
    {
        final InternalSession session = pendingSessions[i];
        total += session.poll(timeInMs);
        if (session.state() == ACTIVE)
        {
            this.pendingInitiatorSessions = pendingSessions = ArrayUtil.remove(pendingSessions, i);
            size--;
            sessions = ArrayUtil.add(sessions, session);
        }
        else
        {
            i++;
        }
    }

    return total;
}
 
Example #18
Source File: ReceiverEndPoints.java    From artio with Apache License 2.0 6 votes vote down vote up
void receiverEndPointPollingOptional(final long connectionId)
{
    final ReceiverEndPoint[] requiredPollingEndPoints = this.requiredPollingEndPoints;
    final int index = findEndPoint(connectionId, requiredPollingEndPoints);
    if (index != UNKNOWN_INDEX)
    {
        final ReceiverEndPoint endPoint = requiredPollingEndPoints[index];
        this.requiredPollingEndPoints = ArrayUtil.remove(requiredPollingEndPoints, index);
        addToNormalEndpoints(endPoint);
    }
    else
    {
        errorHandler.onError(new Exception(String.format(
            "Unable to make endpoint no longer required for polling due to it not being found, connectionId=%d",
            connectionId)));
    }
}
 
Example #19
Source File: ReceiverEndPoints.java    From artio with Apache License 2.0 6 votes vote down vote up
void removeConnection(final long connectionId, final DisconnectReason reason)
{
    final ReceiverEndPoint[] endPoints = this.endPoints;
    int index = findAndCloseEndPoint(connectionId, reason, endPoints);

    if (index != UNKNOWN_INDEX)
    {
        this.endPoints = ArrayUtil.remove(endPoints, index);
    }
    else
    {
        index = findAndCloseEndPoint(connectionId, reason, requiredPollingEndPoints);
        this.requiredPollingEndPoints = ArrayUtil.remove(requiredPollingEndPoints, index);
    }

    selectNowToForceProcessing();
}
 
Example #20
Source File: NioSelectedKeySet.java    From agrona with Apache License 2.0 6 votes vote down vote up
private void ensureCapacity(final int requiredCapacity)
{
    if (requiredCapacity < 0)
    {
        throw new IllegalStateException(
            "Insufficient capacity: length=" + keys.length + " required=" + requiredCapacity);
    }

    final int currentCapacity = keys.length;
    if (requiredCapacity > currentCapacity)
    {
        int newCapacity = currentCapacity + (currentCapacity >> 1);

        if (newCapacity < 0 || newCapacity > ArrayUtil.MAX_CAPACITY)
        {
            if (currentCapacity == ArrayUtil.MAX_CAPACITY)
            {
                throw new IllegalStateException("max capacity reached: " + ArrayUtil.MAX_CAPACITY);
            }

            newCapacity = ArrayUtil.MAX_CAPACITY;
        }

        keys = Arrays.copyOf(keys, newCapacity);
    }
}
 
Example #21
Source File: PublicationImage.java    From aeron with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void addSubscriber(final SubscriptionLink subscriptionLink, final ReadablePosition subscriberPosition)
{
    subscriberPositions = ArrayUtil.add(subscriberPositions, subscriberPosition);
    if (!subscriptionLink.isTether())
    {
        untetheredSubscriptions.add(new UntetheredSubscription(
            subscriptionLink, subscriberPosition, timeOfLastStatusMessageScheduleNs));
    }
}
 
Example #22
Source File: IpcPublication.java    From aeron with Apache License 2.0 5 votes vote down vote up
public void addSubscriber(final SubscriptionLink subscriptionLink, final ReadablePosition subscriberPosition)
{
    subscriberPositions = ArrayUtil.add(subscriberPositions, subscriberPosition);
    if (!subscriptionLink.isTether())
    {
        untetheredSubscriptions.add(new UntetheredSubscription(
            subscriptionLink, subscriberPosition, timeOfLastConsumerPositionUpdateNs));
    }

    LogBufferDescriptor.isConnected(metaDataBuffer, true);
}
 
Example #23
Source File: PublicationImage.java    From aeron with Apache License 2.0 5 votes vote down vote up
private void trackConnection(final int transportIndex, final InetSocketAddress srcAddress, final long nowNs)
{
    imageConnections = ArrayUtil.ensureCapacity(imageConnections, transportIndex + 1);
    ImageConnection imageConnection = imageConnections[transportIndex];

    if (null == imageConnection)
    {
        imageConnection = new ImageConnection(nowNs, srcAddress);
        imageConnections[transportIndex] = imageConnection;
    }

    imageConnection.timeOfLastActivityNs = nowNs;
    imageConnection.timeOfLastFrameNs = nowNs;
}
 
Example #24
Source File: ControlTransportPoller.java    From aeron with Apache License 2.0 5 votes vote down vote up
public SelectionKey registerForRead(final SendChannelEndpoint transport)
{
    SelectionKey key = null;
    try
    {
        key = transport.receiveDatagramChannel().register(selector, SelectionKey.OP_READ, transport);
        transports = ArrayUtil.add(transports, transport);
    }
    catch (final ClosedChannelException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }

    return key;
}
 
Example #25
Source File: MultiRcvDestination.java    From aeron with Apache License 2.0 5 votes vote down vote up
void updateControlAddress(final int transportIndex, final InetSocketAddress newAddress)
{
    if (ArrayUtil.UNKNOWN_INDEX != transportIndex)
    {
        final ReceiveDestinationTransport transport = transports[transportIndex];

        if (null != transport)
        {
            transport.currentControlAddress(newAddress);
        }
    }
}
 
Example #26
Source File: ExpandableRingBuffer.java    From agrona with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new ring buffer providing configuration for initial and max capacity, plus whether it is direct or not.
 *
 * @param initialCapacity required in the buffer.
 * @param maxCapacity     the the buffer can expand to.
 * @param isDirect        is the {@link ByteBuffer} allocated direct or heap based.
 */
public ExpandableRingBuffer(final int initialCapacity, final int maxCapacity, final boolean isDirect)
{
    this.isDirect = isDirect;
    this.maxCapacity = maxCapacity;

    if (maxCapacity < 0 || maxCapacity > MAX_CAPACITY || !BitUtil.isPowerOfTwo(maxCapacity))
    {
        throw new IllegalArgumentException("illegal max capacity: " + maxCapacity);
    }

    if (0 == initialCapacity)
    {
        buffer.wrap(ArrayUtil.EMPTY_BYTE_ARRAY);
        return;
    }

    if (initialCapacity < 0)
    {
        throw new IllegalArgumentException("initial capacity < 0 : " + initialCapacity);
    }

    capacity = BitUtil.findNextPositivePowerOfTwo(initialCapacity);
    if (capacity < 0)
    {
        throw new IllegalArgumentException("invalid initial capacity: " + initialCapacity);
    }

    mask = capacity - 1;
    buffer.wrap(isDirect ? ByteBuffer.allocateDirect(capacity) : ByteBuffer.allocate(capacity));
}
 
Example #27
Source File: NioSelectedKeySet.java    From agrona with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a key set with the given capacity.
 *
 * @param initialCapacity for the key set
 */
public NioSelectedKeySet(final int initialCapacity)
{
    if (initialCapacity < 0 || initialCapacity > ArrayUtil.MAX_CAPACITY)
    {
        throw new IllegalArgumentException("invalid initial capacity: " + initialCapacity);
    }

    keys = new SelectionKey[Math.max(initialCapacity, INITIAL_CAPACITY)];
}
 
Example #28
Source File: ReceiverEndPoints.java    From artio with Apache License 2.0 5 votes vote down vote up
private void addToNormalEndpoints(final ReceiverEndPoint endPoint)
{
    try
    {
        endPoints = ArrayUtil.add(endPoints, endPoint);
        endPoint.register(selector);
    }
    catch (final IOException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example #29
Source File: ReceiverEndPoints.java    From artio with Apache License 2.0 5 votes vote down vote up
void add(final ReceiverEndPoint endPoint)
{
    if (endPoint.requiresAuthentication())
    {
        requiredPollingEndPoints = ArrayUtil.add(requiredPollingEndPoints, endPoint);
    }
    else
    {
        addToNormalEndpoints(endPoint);
    }
}
 
Example #30
Source File: LibraryPoller.java    From artio with Apache License 2.0 5 votes vote down vote up
private void insertSession(
    final InternalSession session, final ConnectionType connectionType, final SessionState sessionState)
{
    if (connectionType == INITIATOR && sessionState != ACTIVE)
    {
        pendingInitiatorSessions = ArrayUtil.add(pendingInitiatorSessions, session);
    }
    else
    {
        sessions = ArrayUtil.add(sessions, session);
    }
}