org.agrona.LangUtil Java Examples

The following examples show how to use org.agrona.LangUtil. 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: RecordingReader.java    From aeron with Apache License 2.0 6 votes vote down vote up
private void openRecordingSegment()
{
    final String segmentFileName = segmentFileName(recordingId, segmentFilePosition);
    final File segmentFile = new File(archiveDir, segmentFileName);

    if (!segmentFile.exists())
    {
        throw new IllegalArgumentException("failed to open recording segment file " + segmentFileName);
    }

    try (FileChannel channel = FileChannel.open(segmentFile.toPath(), FILE_OPTIONS, NO_ATTRIBUTES))
    {
        mappedSegmentBuffer = channel.map(READ_ONLY, 0, segmentLength);
    }
    catch (final IOException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example #2
Source File: Configuration.java    From aeron with Apache License 2.0 6 votes vote down vote up
/**
 * Get the supplier of {@link SendChannelEndpoint}s which can be used for
 * debugging, monitoring, or modifying the behaviour when sending to the channel.
 *
 * @return the {@link SendChannelEndpointSupplier}.
 */
public static SendChannelEndpointSupplier sendChannelEndpointSupplier()
{
    SendChannelEndpointSupplier supplier = null;
    try
    {
        final String className = getProperty(SEND_CHANNEL_ENDPOINT_SUPPLIER_PROP_NAME);
        if (null == className)
        {
            return new DefaultSendChannelEndpointSupplier();
        }

        supplier = (SendChannelEndpointSupplier)Class.forName(className).getConstructor().newInstance();
    }
    catch (final Exception ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }

    return supplier;
}
 
Example #3
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 #4
Source File: DefaultTcpChannelSupplier.java    From artio with Apache License 2.0 6 votes vote down vote up
public DefaultTcpChannelSupplier(final EngineConfiguration configuration)
{
    hasBindAddress = configuration.hasBindAddress();
    this.configuration = configuration;
    try
    {
        selector = Selector.open();
        if (configuration.bindAtStartup() && configuration.initialAcceptedSessionOwner() != SOLE_LIBRARY)
        {
            bind();
        }
    }
    catch (final IOException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example #5
Source File: Configuration.java    From aeron with Apache License 2.0 6 votes vote down vote up
/**
 * Get the {@link TerminationValidator} implementations which can be used for validating a termination request
 * sent to the driver to ensure the client has the right to terminate a driver.
 *
 * @return the {@link TerminationValidator}
 */
public static TerminationValidator terminationValidator()
{
    TerminationValidator validator = null;
    try
    {
        final String className = getProperty(TERMINATION_VALIDATOR_PROP_NAME);
        if (null == className)
        {
            return new DefaultDenyTerminationValidator();
        }

        validator = (TerminationValidator)Class.forName(className).getConstructor().newInstance();
    }
    catch (final Exception ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }

    return validator;
}
 
Example #6
Source File: CountersManager.java    From agrona with Apache License 2.0 6 votes vote down vote up
/**
 * Allocate a new counter with a given label.
 * <p>
 * The key function will be called with a buffer with the exact length of available key space
 * in the record for the user to store what they want for the key. No offset is required.
 *
 * @param label   to describe the counter.
 * @param typeId  for the type of counter.
 * @param keyFunc for setting the key value for the counter.
 * @return the id allocated for the counter.
 */
public int allocate(final String label, final int typeId, final Consumer<MutableDirectBuffer> keyFunc)
{
    final int counterId = nextCounterId();
    checkCountersCapacity(counterId);

    final int recordOffset = metaDataOffset(counterId);
    checkMetaDataCapacity(recordOffset);

    try
    {
        metaDataBuffer.putInt(recordOffset + TYPE_ID_OFFSET, typeId);
        keyFunc.accept(new UnsafeBuffer(metaDataBuffer, recordOffset + KEY_OFFSET, MAX_KEY_LENGTH));
        metaDataBuffer.putLong(recordOffset + FREE_FOR_REUSE_DEADLINE_OFFSET, NOT_FREE_TO_REUSE);
        putLabel(recordOffset, label);

        metaDataBuffer.putIntOrdered(recordOffset, RECORD_ALLOCATED);
    }
    catch (final Exception ex)
    {
        freeList.pushInt(counterId);
        LangUtil.rethrowUnchecked(ex);
    }

    return counterId;
}
 
Example #7
Source File: UdpChannel.java    From aeron with Apache License 2.0 6 votes vote down vote up
private static InetSocketAddress getExplicitControlAddress(final ChannelUri uri, final NameResolver nameResolver)
{
    InetSocketAddress address = null;
    final String controlValue = uri.get(CommonContext.MDC_CONTROL_PARAM_NAME);
    if (null != controlValue)
    {
        try
        {
            address = SocketAddressParser.parse(
                controlValue, CommonContext.MDC_CONTROL_PARAM_NAME, false, nameResolver);
        }
        catch (final UnknownHostException ex)
        {
            LangUtil.rethrowUnchecked(ex);
        }
    }

    return address;
}
 
Example #8
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 #9
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 #10
Source File: AgentRunnerTest.java    From agrona with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotReportRethrownClosedByInterruptException() throws Exception
{
    when(mockAgent.doWork()).thenAnswer(
        (inv) ->
        {
            try
            {
                throw new ClosedByInterruptException();
            }
            catch (final ClosedByInterruptException ex)
            {
                LangUtil.rethrowUnchecked(ex);
            }

            return null;
        });

    assertExceptionNotReported();
}
 
Example #11
Source File: SequenceNumberIndexReader.java    From artio with Apache License 2.0 6 votes vote down vote up
private RandomAccessFile openMetaDataFile(final String metaDataDir)
{
    if (metaDataDir != null)
    {
        final File metaDataFile = metaDataFile(metaDataDir);

        try
        {
            return new RandomAccessFile(metaDataFile, "r");
        }
        catch (final FileNotFoundException e)
        {
            LangUtil.rethrowUnchecked(e);
        }
    }
    return null;
}
 
Example #12
Source File: ClusterTest.java    From aeron with Apache License 2.0 6 votes vote down vote up
@Test
@Timeout(40)
public void shouldNotifyClientOfNewLeader(final TestInfo testInfo)
{
    cluster = startThreeNodeStaticCluster(NULL_VALUE);
    try
    {
        final TestNode leader = cluster.awaitLeader();

        cluster.connectClient();
        cluster.awaitActiveSessionCount(cluster.followers().get(0), 1);

        cluster.stopNode(leader);
        cluster.awaitLeadershipEvent(1);
    }
    catch (final Throwable ex)
    {
        cluster.dumpData(testInfo);
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example #13
Source File: AgentInvokerTest.java    From agrona with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotReportRethrownClosedByInterruptException() throws Exception
{
    when(mockAgent.doWork()).thenAnswer(
        (inv) ->
        {
            try
            {
                throw new ClosedByInterruptException();
            }
            catch (final ClosedByInterruptException ex)
            {
                LangUtil.rethrowUnchecked(ex);
            }

            return null;
        });

    assertExceptionNotReported();
    assertTrue(Thread.interrupted()); // by throwing ClosedByInterruptException
}
 
Example #14
Source File: CountersManager.java    From agrona with Apache License 2.0 6 votes vote down vote up
/**
 * Allocate a new counter with a given label and type.
 *
 * @param label  to describe the counter.
 * @param typeId for the type of counter.
 * @return the id allocated for the counter.
 */
public int allocate(final String label, final int typeId)
{
    final int counterId = nextCounterId();
    checkCountersCapacity(counterId);

    final int recordOffset = metaDataOffset(counterId);
    checkMetaDataCapacity(recordOffset);

    try
    {
        metaDataBuffer.putInt(recordOffset + TYPE_ID_OFFSET, typeId);
        metaDataBuffer.putLong(recordOffset + FREE_FOR_REUSE_DEADLINE_OFFSET, NOT_FREE_TO_REUSE);
        putLabel(recordOffset, label);

        metaDataBuffer.putIntOrdered(recordOffset, RECORD_ALLOCATED);
    }
    catch (final Exception ex)
    {
        freeList.pushInt(counterId);
        LangUtil.rethrowUnchecked(ex);
    }

    return counterId;
}
 
Example #15
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 #16
Source File: MigrationUtils.java    From aeron with Apache License 2.0 6 votes vote down vote up
public static FileChannel createMigrationTimestampFile(
    final File directory, final int fromVersion, final int toVersion)
{
    final String filename =
        MIGRATION_TIMESTAMP_FILE_PREFIX + fromVersion + "-to-" + toVersion + MIGRATION_TIMESTAMP_FILE_SUFFIX;
    final File timestampFile = new File(directory, filename);

    FileChannel fileChannel = null;

    try
    {
        fileChannel = FileChannel.open(timestampFile.toPath(), CREATE_NEW, READ, WRITE, SPARSE);
        fileChannel.force(true);
    }
    catch (final Exception ex)
    {
        System.err.println("Could not create migration timestamp file:" + timestampFile);
        LangUtil.rethrowUnchecked(ex);
    }

    return fileChannel;
}
 
Example #17
Source File: Configuration.java    From aeron with Apache License 2.0 6 votes vote down vote up
/**
 * Get the supplier of {@link CongestionControl} implementations which can be used for receivers.
 *
 * @return the {@link CongestionControlSupplier}
 */
public static CongestionControlSupplier congestionControlSupplier()
{
    CongestionControlSupplier supplier = null;
    try
    {
        final String className = getProperty(CONGESTION_CONTROL_STRATEGY_SUPPLIER_PROP_NAME);
        if (null == className)
        {
            return new DefaultCongestionControlSupplier();
        }

        supplier = (CongestionControlSupplier)Class.forName(className).getConstructor().newInstance();
    }
    catch (final Exception ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }

    return supplier;
}
 
Example #18
Source File: EchoService.java    From benchmarks with Apache License 2.0 6 votes vote down vote up
public StreamObserver<EchoMessage> echoStream(final StreamObserver<EchoMessage> responseObserver)
{
    return new StreamObserver<EchoMessage>()
    {
        public void onNext(final EchoMessage message)
        {
            responseObserver.onNext(message);
        }

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

        public void onCompleted()
        {
            responseObserver.onCompleted();
        }
    };
}
 
Example #19
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 #20
Source File: Reflection.java    From artio with Apache License 2.0 6 votes vote down vote up
private static void set(
    final Object object,
    final String setterName,
    final Class<?> type,
    final Object value) throws Exception
{
    try
    {
        object.getClass()
            .getMethod(setterName, type)
            .invoke(object, value);
    }
    catch (final InvocationTargetException e)
    {
        LangUtil.rethrowUnchecked(e.getCause());
    }
}
 
Example #21
Source File: DecoderGenerator.java    From artio with Apache License 2.0 6 votes vote down vote up
private void wrappedForEachEntry(
    final Aggregate aggregate, final Writer out, final ResourceConsumer<Entry> consumer)
    throws IOException
{
    out.append("\n");
    aggregate
        .entries()
        .forEach(t ->
        {
            try
            {
                consumer.accept(t);
            }
            catch (final IOException ex)
            {
                LangUtil.rethrowUnchecked(ex);
            }
        });
    out.append("\n");
}
 
Example #22
Source File: InternalILink3Connection.java    From artio with Apache License 2.0 6 votes vote down vote up
private byte[] calculateHMAC(final String canonicalRequest)
{
    final String userKey = configuration.userKey();

    try
    {
        final Mac sha256HMAC = getHmac();

        // Decode the key first, since it is base64url encoded
        final byte[] decodedUserKey = Base64.getUrlDecoder().decode(userKey);
        final SecretKeySpec secretKey = new SecretKeySpec(decodedUserKey, "HmacSHA256");
        sha256HMAC.init(secretKey);

        // Calculate HMAC
        return sha256HMAC.doFinal(canonicalRequest.getBytes(StandardCharsets.UTF_8));
    }
    catch (final InvalidKeyException | IllegalStateException e)
    {
        LangUtil.rethrowUnchecked(e);
        return null;
    }
}
 
Example #23
Source File: ILink3Offsets.java    From artio with Apache License 2.0 6 votes vote down vote up
public static Ir loadSbeIr()
{
    try
    {
        final InputStream stream = Negotiate500Encoder.class.getResourceAsStream(SBE_IR_FILE);
        final int length = stream.available();
        final byte[] bytes = new byte[length];
        int remaining = length;
        while (remaining > 0)
        {
            remaining -= stream.read(bytes, length - remaining, remaining);
        }
        try (IrDecoder irDecoder = new IrDecoder(ByteBuffer.wrap(bytes)))
        {
            return irDecoder.decode();
        }
    }
    catch (final Exception e)
    {
        LangUtil.rethrowUnchecked(e);
        return null;
    }
}
 
Example #24
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 #25
Source File: GatewayProcess.java    From artio with Apache License 2.0 6 votes vote down vote up
protected Aeron.Context configureAeronContext(final CommonConfiguration configuration)
{
    final Aeron.Context ctx = configuration.aeronContext();
    ctx.errorHandler(
        (throwable) ->
        {
            if (shouldRethrowExceptionInErrorHandler())
            {
                LangUtil.rethrowUnchecked(throwable);
            }

            if (!(throwable instanceof ClosedByInterruptException))
            {
                errorHandler.onError(throwable);
            }
        });

    return ctx;
}
 
Example #26
Source File: Crc32c.java    From aeron with Apache License 2.0 5 votes vote down vote up
public int compute(final long address, final int offset, final int length)
{
    try
    {
        return (int)UPDATE_DIRECT_BYTE_BUFFER.invokeExact(address, offset, offset + length /* end */);
    }
    catch (final Throwable throwable)
    {
        LangUtil.rethrowUnchecked(throwable);
        return -1;
    }
}
 
Example #27
Source File: DataCollector.java    From aeron with Apache License 2.0 5 votes vote down vote up
private void copyData(final String destinationDir)
{
    final List<Path> locations = this.locations.stream().filter(Files::exists).collect(toList());
    if (locations.isEmpty())
    {
        return;
    }

    try
    {
        final Path destination = createUniqueDirectory(destinationDir);
        final Map<Path, Set<Path>> groups = groupByParent(locations);
        for (final Map.Entry<Path, Set<Path>> group : groups.entrySet())
        {
            final Set<Path> files = group.getValue();
            final Path parent = adjustParentToEnsureUniqueContext(destination, files, group.getKey());
            for (final Path srcFile : files)
            {
                final Path dstFile = destination.resolve(parent.relativize(srcFile));
                copyFiles(srcFile, dstFile);
            }
        }
    }
    catch (final IOException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example #28
Source File: ReplaySession.java    From aeron with Apache License 2.0 5 votes vote down vote up
public int doWork()
{
    int workCount = 0;

    if (isAborted)
    {
        state(State.INACTIVE);
    }

    try
    {
        if (State.INIT == state)
        {
            workCount += init();
        }

        if (State.REPLAY == state)
        {
            workCount += replay();
        }
    }
    catch (final IOException ex)
    {
        onError("IOException - " + ex.getMessage() + " - " + segmentFile.getName());
        LangUtil.rethrowUnchecked(ex);
    }

    if (State.INACTIVE == state)
    {
        closeRecordingSegment();
        state(State.DONE);
    }

    return workCount;
}
 
Example #29
Source File: AeronArchive.java    From aeron with Apache License 2.0 5 votes vote down vote up
private void checkDeadline()
{
    if (Thread.interrupted())
    {
        LangUtil.rethrowUnchecked(new InterruptedException());
    }

    if (deadlineNs - nanoClock.nanoTime() < 0)
    {
        throw new TimeoutException(
            "Archive connect timeout for correlation id: " + correlationId + " step " + step);
    }
}
 
Example #30
Source File: ClusterTest.java    From aeron with Apache License 2.0 5 votes vote down vote up
@Test
@Timeout(20)
public void shouldCloseClientOnTimeout(final TestInfo testInfo)
{
    cluster = startThreeNodeStaticCluster(NULL_VALUE);
    try
    {
        final TestNode leader = cluster.awaitLeader();

        final AeronCluster client = cluster.connectClient();
        final ConsensusModule.Context context = leader.consensusModule().context();
        assertEquals(0, context.timedOutClientCounter().get());
        assertFalse(client.isClosed());

        Tests.sleep(NANOSECONDS.toMillis(context.sessionTimeoutNs()));

        while (!client.isClosed())
        {
            Tests.sleep(1);
            client.pollEgress();
        }

        assertEquals(1, context.timedOutClientCounter().get());
    }
    catch (final Throwable ex)
    {
        cluster.dumpData(testInfo);
        LangUtil.rethrowUnchecked(ex);
    }
}