Java Code Examples for org.agrona.LangUtil#rethrowUnchecked()

The following examples show how to use org.agrona.LangUtil#rethrowUnchecked() . 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: ReceiverEndPointTest.java    From artio with Apache License 2.0 6 votes vote down vote up
private void endpointBufferUpdatedWith(final ToIntFunction<ByteBuffer> bufferUpdater)
{
    try
    {
        doAnswer(
            (invocation) ->
            {
                final ByteBuffer buffer = (ByteBuffer)invocation.getArguments()[0];
                return bufferUpdater.applyAsInt(buffer);
            }).when(mockChannel).read(any(ByteBuffer.class));
    }
    catch (final IOException ex)
    {
        // Should never happen, test in error
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example 2
Source File: ClusterTest.java    From aeron with Apache License 2.0 6 votes vote down vote up
@Test
@Timeout(40)
public void shouldTerminateLeaderWhenServiceStops(final TestInfo testInfo)
{
    cluster = startThreeNodeStaticCluster(NULL_VALUE);
    try
    {
        final TestNode leader = cluster.awaitLeader();

        leader.terminationExpected(true);
        leader.container().close();

        while (!leader.hasMemberTerminated())
        {
            Tests.sleep(1);
        }
    }
    catch (final Throwable ex)
    {
        cluster.dumpData(testInfo);
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example 3
Source File: MappedFile.java    From artio with Apache License 2.0 6 votes vote down vote up
public static MappedFile map(final File bufferFile, final int size)
{
    final FileChannel fileChannel;
    try
    {
        if (bufferFile.exists())
        {
            // NB: closing RAF or FileChannel closes them both
            fileChannel = new RandomAccessFile(bufferFile, "rw").getChannel();
        }
        else
        {
            fileChannel = IoUtil.createEmptyFile(bufferFile, size);
        }

        final MappedByteBuffer mappedBuffer = fileChannel.map(READ_WRITE, 0, fileChannel.size());
        return new MappedFile(bufferFile, fileChannel, new UnsafeBuffer(mappedBuffer));
    }
    catch (final IOException ex)
    {
        LangUtil.rethrowUnchecked(ex);
        return null;
    }
}
 
Example 4
Source File: SamplesUtil.java    From aeron with Apache License 2.0 6 votes vote down vote up
/**
 * Map an existing file as a read only buffer.
 *
 * @param location of file to map.
 * @return the mapped file.
 */
public static MappedByteBuffer mapExistingFileReadOnly(final File location)
{
    if (!location.exists())
    {
        final String msg = "file not found: " + location.getAbsolutePath();
        throw new IllegalStateException(msg);
    }

    MappedByteBuffer mappedByteBuffer = null;
    try (RandomAccessFile file = new RandomAccessFile(location, "r");
        FileChannel channel = file.getChannel())
    {
        mappedByteBuffer = channel.map(READ_ONLY, 0, channel.size());
    }
    catch (final IOException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }

    return mappedByteBuffer;
}
 
Example 5
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 6
Source File: ClusterTest.java    From aeron with Apache License 2.0 6 votes vote down vote up
@Test
@Timeout(40)
public void shouldStopLeaderAndRestartAsFollower(final TestInfo testInfo)
{
    cluster = startThreeNodeStaticCluster(NULL_VALUE);
    try
    {
        final TestNode originalLeader = cluster.awaitLeader();

        cluster.stopNode(originalLeader);
        cluster.awaitLeader(originalLeader.index());

        final TestNode follower = cluster.startStaticNode(originalLeader.index(), false);

        awaitElectionClosed(follower);
        assertEquals(FOLLOWER, follower.role());
    }
    catch (final Throwable ex)
    {
        cluster.dumpData(testInfo);
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example 7
Source File: GrpcConfig.java    From benchmarks with Apache License 2.0 6 votes vote down vote up
public static NettyServerBuilder getServerBuilder()
{
    final NettyServerBuilder serverBuilder =
        NettyServerBuilder.forAddress(new InetSocketAddress(getServerHost(), getServerPort()));
    if (getBoolean(TLS))
    {
        final Path certificatesDir = Configuration.certificatesDirectory();
        final SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(
            certificatesDir.resolve("server.pem").toFile(), certificatesDir.resolve("server.key").toFile())
            .trustManager(certificatesDir.resolve("ca.pem").toFile())
            .clientAuth(ClientAuth.REQUIRE);
        GrpcSslContexts.configure(sslClientContextBuilder);

        try
        {
            serverBuilder.sslContext(sslClientContextBuilder.build());
        }
        catch (final SSLException ex)
        {
            LangUtil.rethrowUnchecked(ex);
        }
    }
    return serverBuilder;
}
 
Example 8
Source File: HistogramLogReader.java    From artio with Apache License 2.0 5 votes vote down vote up
private void openFile(final File file)
{
    checkFileExists(file, file.getName());

    try
    {
        final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        channel = randomAccessFile.getChannel();
        map(channel.size());
    }
    catch (final IOException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example 9
Source File: ClusterTest.java    From aeron with Apache License 2.0 5 votes vote down vote up
@Test
@Timeout(40)
public void shouldCallOnRoleChangeOnBecomingLeader(final TestInfo testInfo)
{
    cluster = startThreeNodeStaticCluster(NULL_VALUE);
    try
    {
        TestNode leader = cluster.awaitLeader();
        List<TestNode> followers = cluster.followers();
        final TestNode followerA = followers.get(0);
        final TestNode followerB = followers.get(1);

        assertEquals(LEADER, leader.service().roleChangedTo());
        assertNull(followerA.service().roleChangedTo());
        assertNull(followerB.service().roleChangedTo());

        cluster.stopNode(leader);

        leader = cluster.awaitLeader(leader.index());
        followers = cluster.followers();
        final TestNode follower = followers.get(0);

        assertEquals(LEADER, leader.service().roleChangedTo());
        assertNull(follower.service().roleChangedTo());
    }
    catch (final Throwable ex)
    {
        cluster.dumpData(testInfo);
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example 10
Source File: ArchiveConductor.java    From aeron with Apache License 2.0 5 votes vote down vote up
private boolean eraseRemainingSegment(
    final long correlationId,
    final ControlSession controlSession,
    final long position,
    final int segmentLength,
    final int segmentOffset,
    final int termLength,
    final File file)
{
    try (FileChannel channel = FileChannel.open(file.toPath(), FILE_OPTIONS, NO_ATTRIBUTES))
    {
        final int termOffset = (int)(position & (termLength - 1));
        final int termCount = (int)(position >> LogBufferDescriptor.positionBitsToShift(termLength));
        final int termId = recordingSummary.initialTermId + termCount;
        final UnsafeBuffer dataBuffer = ctx.dataBuffer();

        if (ReplaySession.notHeaderAligned(
            channel, dataBuffer, segmentOffset, termOffset, termId, recordingSummary.streamId))
        {
            final String msg = position + " position not aligned to data header";
            controlSession.sendErrorResponse(correlationId, msg, controlResponseProxy);
            return false;
        }

        channel.truncate(segmentOffset);
        dataBuffer.byteBuffer().put(0, (byte)0).limit(1).position(0);
        channel.write(dataBuffer.byteBuffer(), segmentLength - 1);
    }
    catch (final IOException ex)
    {
        controlSession.sendErrorResponse(correlationId, ex.getMessage(), controlResponseProxy);
        LangUtil.rethrowUnchecked(ex);
    }

    return true;
}
 
Example 11
Source File: DriverNameResolver.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static String getCanonicalName()
{
    String canonicalName = null;

    try
    {
        canonicalName = InetAddress.getLocalHost().getHostName();
    }
    catch (final UnknownHostException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }

    return canonicalName;
}
 
Example 12
Source File: StreamingMessageTransceiver.java    From benchmarks with Apache License 2.0 5 votes vote down vote up
public void init(final Configuration configuration)
{
    serverChannel = getServerChannel();

    final StreamObserver<EchoMessage> responseObserver = new StreamObserver<EchoMessage>()
    {
        public void onNext(final EchoMessage response)
        {
            onMessageReceived(response.getTimestamp(), response.getChecksum());
        }

        public void onError(final Throwable t)
        {
            t.printStackTrace();
            LangUtil.rethrowUnchecked(t);
        }

        public void onCompleted()
        {
        }
    };

    final EchoBenchmarksStub asyncClient = EchoBenchmarksGrpc.newStub(serverChannel);
    requestObserver = (ClientCallStreamObserver<EchoMessage>)asyncClient.echoStream(responseObserver);

    messageBuilder = EchoMessage.newBuilder();
    final int payloadLength = configuration.messageLength() - MIN_MESSAGE_LENGTH;
    if (payloadLength == 0)
    {
        payload = ByteString.EMPTY;
    }
    else
    {
        final byte[] bytes = new byte[payloadLength];
        ThreadLocalRandom.current().nextBytes(bytes);
        payload = copyFrom(bytes);
    }
}
 
Example 13
Source File: TcpChannel.java    From artio with Apache License 2.0 5 votes vote down vote up
public void close()
{
    if (socketChannel.isOpen())
    {
        try
        {
            socketChannel.close();
        }
        catch (final IOException ex)
        {
            LangUtil.rethrowUnchecked(ex);
        }
    }
}
 
Example 14
Source File: Tests.java    From aeron with Apache License 2.0 5 votes vote down vote up
/**
 * Same as {@link Thread#sleep(long)} but without the checked exception.
 *
 * @param durationMs      to sleep.
 * @param messageSupplier of message to be reported on interrupt.
 */
public static void sleep(final long durationMs, final Supplier<String> messageSupplier)
{
    try
    {
        Thread.sleep(durationMs);
    }
    catch (final InterruptedException ex)
    {
        unexpectedInterruptStackTrace(messageSupplier.get());
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example 15
Source File: FileReceiver.java    From aeron with Apache License 2.0 5 votes vote down vote up
private void createFile(final long correlationId, final long length, final String filename)
{
    if (fileSessionByIdMap.containsKey(correlationId))
    {
        throw new IllegalStateException("correlationId is in use: " + correlationId);
    }

    final File file = new File(storageDir, filename);
    if (file.exists() && !file.delete())
    {
        throw new IllegalStateException("failed to delete existing file: " + file);
    }

    if (length == 0)
    {
        try
        {
            if (!file.createNewFile())
            {
                throw new IllegalStateException("failed to create " + filename);
            }
        }
        catch (final IOException ex)
        {
            LangUtil.rethrowUnchecked(ex);
        }
    }
    else
    {
        fileSessionByIdMap.put(correlationId, new UnsafeBuffer(IoUtil.mapNewFile(file, length, false)));
    }
}
 
Example 16
Source File: ControlTransportPoller.java    From aeron with Apache License 2.0 5 votes vote down vote up
public int pollTransports()
{
    int bytesReceived = 0;
    try
    {
        if (transports.length <= ITERATION_THRESHOLD)
        {
            for (final SendChannelEndpoint transport : transports)
            {
                bytesReceived += poll(transport);
            }
        }
        else
        {
            selector.selectNow();

            final SelectionKey[] keys = selectedKeySet.keys();
            for (int i = 0, length = selectedKeySet.size(); i < length; i++)
            {
                bytesReceived += poll((SendChannelEndpoint)keys[i].attachment());
            }

            selectedKeySet.reset();
        }
    }
    catch (final IOException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }

    return bytesReceived;
}
 
Example 17
Source File: FramerTest.java    From artio with Apache License 2.0 5 votes vote down vote up
private void doWork()
{
    try
    {
        framer.doWork();
    }
    catch (final Exception ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example 18
Source File: ClusterTest.java    From aeron with Apache License 2.0 5 votes vote down vote up
@Test
@Timeout(40)
public void shouldStopLeaderAndRestartAsFollowerWithSendingAfter(final TestInfo testInfo)
{
    cluster = startThreeNodeStaticCluster(NULL_VALUE);
    try
    {
        final TestNode originalLeader = cluster.awaitLeader();

        cluster.stopNode(originalLeader);
        cluster.awaitLeader(originalLeader.index());

        final TestNode follower = cluster.startStaticNode(originalLeader.index(), false);

        awaitElectionClosed(follower);
        assertEquals(FOLLOWER, follower.role());

        cluster.connectClient();

        final int messageCount = 10;
        cluster.sendMessages(messageCount);
        cluster.awaitResponseMessageCount(messageCount);
    }
    catch (final Throwable ex)
    {
        cluster.dumpData(testInfo);
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example 19
Source File: ClusterTest.java    From aeron with Apache License 2.0 4 votes vote down vote up
@Test
@Timeout(40)
public void shouldEchoMessagesThenContinueOnNewLeader(final TestInfo testInfo)
{
    cluster = startThreeNodeStaticCluster(NULL_VALUE);
    try
    {
        final TestNode originalLeader = cluster.awaitLeader();
        cluster.connectClient();

        final int preFailureMessageCount = 10;
        final int postFailureMessageCount = 7;

        cluster.sendMessages(preFailureMessageCount);
        cluster.awaitResponseMessageCount(preFailureMessageCount);
        cluster.awaitServiceMessageCount(cluster.node(0), preFailureMessageCount);
        cluster.awaitServiceMessageCount(cluster.node(1), preFailureMessageCount);
        cluster.awaitServiceMessageCount(cluster.node(2), preFailureMessageCount);

        assertEquals(originalLeader.index(), cluster.client().leaderMemberId());

        cluster.stopNode(originalLeader);

        final TestNode newLeader = cluster.awaitLeader(originalLeader.index());
        cluster.awaitLeadershipEvent(1);
        assertEquals(newLeader.index(), cluster.client().leaderMemberId());

        cluster.sendMessages(postFailureMessageCount);
        cluster.awaitResponseMessageCount(preFailureMessageCount + postFailureMessageCount);

        final TestNode follower = cluster.followers().get(0);

        cluster.awaitServiceMessageCount(newLeader, preFailureMessageCount + postFailureMessageCount);
        cluster.awaitServiceMessageCount(follower, preFailureMessageCount + postFailureMessageCount);
    }
    catch (final Throwable ex)
    {
        cluster.dumpData(testInfo);
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example 20
Source File: RecordingLog.java    From aeron with Apache License 2.0 4 votes vote down vote up
private boolean restoreSnapshotMarkedWithInvalid(
    final long recordingId,
    final long leadershipTermId,
    final long termBaseLogPosition,
    final long logPosition,
    final long timestamp,
    final int serviceId)
{
    for (int i = invalidSnapshots.size() - 1; i >= 0; i--)
    {
        final int entryCacheIndex = invalidSnapshots.getInt(i);
        final Entry entry = entriesCache.get(entryCacheIndex);

        if (entryMatches(entry, leadershipTermId, termBaseLogPosition, logPosition, serviceId))
        {
            final Entry validatedEntry = new Entry(
                recordingId,
                leadershipTermId,
                termBaseLogPosition,
                logPosition,
                timestamp,
                serviceId,
                ENTRY_TYPE_SNAPSHOT,
                true,
                entry.entryIndex);

            writeEntryToBuffer(validatedEntry, buffer, byteBuffer);
            final long position = (entry.entryIndex * (long)ENTRY_LENGTH);
            try
            {
                if (ENTRY_LENGTH != fileChannel.write(byteBuffer, position))
                {
                    throw new ClusterException("failed to write entry atomically");
                }
            }
            catch (final IOException ex)
            {
                LangUtil.rethrowUnchecked(ex);
            }

            entriesCache.set(entryCacheIndex, validatedEntry);
            invalidSnapshots.fastUnorderedRemove(i);

            return true;
        }
    }

    return false;
}