Example usage for com.google.common.math DoubleMath roundToLong

List of usage examples for com.google.common.math DoubleMath roundToLong

Introduction

In this page you can find the example usage for com.google.common.math DoubleMath roundToLong.

Prototype

@GwtIncompatible("#roundIntermediate")
public static long roundToLong(double x, RoundingMode mode) 

Source Link

Document

Returns the long value that is equal to x rounded with the specified rounding mode, if possible.

Usage

From source file:com.digitalpetri.opcua.sdk.server.SessionManager.java

@Override
public void onCreateSession(ServiceRequest<CreateSessionRequest, CreateSessionResponse> serviceRequest)
        throws UaException {
    CreateSessionRequest request = serviceRequest.getRequest();

    long maxSessionCount = server.getConfig().getLimits().getMaxSessionCount().longValue();
    if (createdSessions.size() + activeSessions.size() >= maxSessionCount) {
        serviceRequest.setServiceFault(StatusCodes.Bad_TooManySessions);
        return;//from  w  ww.  j  a  v a2 s.co  m
    }

    ByteString serverNonce = NonceUtil.generateNonce(32);
    NodeId authenticationToken = new NodeId(0, NonceUtil.generateNonce(32));
    long maxRequestMessageSize = serviceRequest.getServer().getChannelConfig().getMaxMessageSize();
    double revisedSessionTimeout = Math.max(5000,
            Math.min(MAX_SESSION_TIMEOUT_MS, request.getRequestedSessionTimeout()));

    ServerSecureChannel secureChannel = serviceRequest.getSecureChannel();

    ByteString serverCertificate = serviceRequest.getSecureChannel().getEndpointDescription()
            .getServerCertificate();
    SignedSoftwareCertificate[] serverSoftwareCertificates = server.getSoftwareCertificates();
    EndpointDescription[] serverEndpoints = server.getEndpointDescriptions();

    ByteString clientNonce = request.getClientNonce();
    if (clientNonce.isNotNull() && clientNonce.length() < 32) {
        throw new UaException(StatusCodes.Bad_NonceInvalid);
    }

    ByteString clientCertificate = request.getClientCertificate();
    if (clientCertificate.isNotNull()) {
        if (secureChannel.getSecurityPolicy() != SecurityPolicy.None) {
            String applicationUri = request.getClientDescription().getApplicationUri();
            X509Certificate certificate = CertificateUtil.decodeCertificate(clientCertificate.bytes());

            validateApplicationUri(applicationUri, certificate);
        }
    }

    SecurityPolicy securityPolicy = secureChannel.getSecurityPolicy();
    SignatureData serverSignature = getServerSignature(clientNonce, clientCertificate, securityPolicy,
            secureChannel.getKeyPair());

    NodeId sessionId = new NodeId(1, "Session:" + UUID.randomUUID());
    String sessionName = request.getSessionName();
    String endpointUrl = request.getEndpointUrl();
    Duration sessionTimeout = Duration.ofMillis(DoubleMath.roundToLong(revisedSessionTimeout, RoundingMode.UP));
    Session session = new Session(server, sessionId, sessionName, sessionTimeout, secureChannel.getChannelId());
    createdSessions.put(authenticationToken, session);

    session.addLifecycleListener((s, remove) -> {
        createdSessions.remove(authenticationToken);
        activeSessions.remove(authenticationToken);
    });

    session.setLastNonce(serverNonce);

    CreateSessionResponse response = new CreateSessionResponse(serviceRequest.createResponseHeader(), sessionId,
            authenticationToken, revisedSessionTimeout, serverNonce, serverCertificate, serverEndpoints,
            serverSoftwareCertificates, serverSignature, uint(maxRequestMessageSize));

    serviceRequest.setResponse(response);
}

From source file:com.inductiveautomation.opcua.sdk.server.SessionManager.java

@Override
public void onCreateSession(ServiceRequest<CreateSessionRequest, CreateSessionResponse> serviceRequest)
        throws UaException {
    CreateSessionRequest request = serviceRequest.getRequest();

    long maxSessionCount = server.getConfig().getLimits().getMaxSessionCount().longValue();
    if (createdSessions.size() + activeSessions.size() >= maxSessionCount) {
        serviceRequest.setServiceFault(StatusCodes.Bad_TooManySessions);
        return;/*from w  w w.j  a  v  a2  s  .  c o  m*/
    }

    ByteString serverNonce = NonceUtil.generateNonce(32);
    NodeId authenticationToken = new NodeId(0, NonceUtil.generateNonce(32));
    long maxRequestMessageSize = serviceRequest.getServer().getChannelConfig().getMaxMessageSize();
    double revisedSessionTimeout = Math.max(5000, Math.min(30000, request.getRequestedSessionTimeout()));

    ServerSecureChannel secureChannel = serviceRequest.getSecureChannel();

    ByteString serverCertificate = serviceRequest.getSecureChannel().getEndpointDescription()
            .getServerCertificate();
    SignedSoftwareCertificate[] serverSoftwareCertificates = server.getSoftwareCertificates();
    EndpointDescription[] serverEndpoints = server.getEndpointDescriptions();

    ByteString clientNonce = request.getClientNonce();
    if (clientNonce.isNotNull() && clientNonce.length() < 32) {
        throw new UaException(StatusCodes.Bad_NonceInvalid);
    }

    ByteString clientCertificate = request.getClientCertificate();
    if (clientCertificate.isNotNull()) {
        String applicationUri = request.getClientDescription().getApplicationUri();
        X509Certificate certificate = CertificateUtil.decodeCertificate(clientCertificate.bytes());

        validateApplicationUri(applicationUri, certificate);
    }

    SecurityPolicy securityPolicy = secureChannel.getSecurityPolicy();
    SignatureData serverSignature = getServerSignature(clientNonce, clientCertificate, securityPolicy,
            secureChannel.getKeyPair());

    NodeId sessionId = new NodeId(1, "Session:" + UUID.randomUUID());
    Duration sessionTimeout = Duration.ofMillis(DoubleMath.roundToLong(revisedSessionTimeout, RoundingMode.UP));
    Session session = new Session(server, sessionId, sessionTimeout, secureChannel.getChannelId());
    createdSessions.put(authenticationToken, session);

    session.addLifecycleListener((s, remove) -> {
        createdSessions.remove(authenticationToken);
        activeSessions.remove(authenticationToken);
    });

    session.setLastNonce(serverNonce);

    CreateSessionResponse response = new CreateSessionResponse(serviceRequest.createResponseHeader(), sessionId,
            authenticationToken, revisedSessionTimeout, serverNonce, serverCertificate, serverEndpoints,
            serverSoftwareCertificates, serverSignature, uint(maxRequestMessageSize));

    serviceRequest.setResponse(response);
}

From source file:org.locationtech.geogig.storage.datastream.FormatCommonV2.java

private static long toFixedPrecision(double ordinate, RoundingMode mode) {
    long fixedPrecisionOrdinate = DoubleMath.roundToLong(ordinate * FIXED_PRECISION_FACTOR, mode);
    return fixedPrecisionOrdinate;
}

From source file:com.github.rinde.rinsim.pdptw.common.RouteFollowingVehicle.java

/**
 * Computes the travel time for this vehicle to any point.
 * @param p The point to calculate travel time to.
 * @param timeUnit The time unit used in the simulation.
 * @return The travel time in the used time unit.
 */// w  w w .j a  v a2s.c o  m
protected long computeTravelTimeTo(Point p, Unit<Duration> timeUnit) {
    final Measure<Double, Length> distance = Measure
            .valueOf(Point.distance(getRoadModel().getPosition(this), p), getRoadModel().getDistanceUnit());

    return DoubleMath.roundToLong(RoadModels.computeTravelTime(speed.get(), distance, timeUnit),
            RoundingMode.CEILING);
}

From source file:com.digitalpetri.opcua.sdk.server.subscriptions.Subscription.java

synchronized void startPublishingTimer() {
    if (state.get() == State.Closed)
        return;/*from   w w  w. jav  a 2 s .c  o  m*/

    lifetimeCounter--;

    if (lifetimeCounter < 1) {
        logger.debug("[id={}] lifetime expired.", subscriptionId);

        setState(State.Closing);
    } else {
        long interval = DoubleMath.roundToLong(publishingInterval, RoundingMode.UP);

        subscriptionManager.getServer().getScheduledExecutorService().schedule(this::onPublishingTimer,
                interval, TimeUnit.MILLISECONDS);
    }
}

From source file:org.eclipse.milo.opcua.sdk.server.subscriptions.Subscription.java

/**
 * The publishing timer has elapsed./*from  w  w  w  .  j  a v  a2  s.c o  m*/
 */
synchronized void onPublishingTimer() {
    State state = this.state.get();

    if (logger.isTraceEnabled()) {
        logger.trace("[id={}] onPublishingTimer(), state={}, keep-alive={}, lifetime={}", subscriptionId, state,
                keepAliveCounter, lifetimeCounter);
    }

    long startNanos = System.nanoTime();

    if (state == State.Normal) {
        timerHandler.whenNormal();
    } else if (state == State.KeepAlive) {
        timerHandler.whenKeepAlive();
    } else if (state == State.Late) {
        timerHandler.whenLate();
    } else if (state == State.Closed) {
        logger.debug("[id={}] onPublish(), state={}", subscriptionId, state); // No-op.
    } else {
        throw new RuntimeException("unhandled subscription state: " + state);
    }

    long elapsedNanos = System.nanoTime() - startNanos;

    long intervalNanos = TimeUnit.NANOSECONDS
            .convert(DoubleMath.roundToLong(publishingInterval, RoundingMode.UP), TimeUnit.MILLISECONDS);

    long adjustedIntervalNanos = Math.max(0, intervalNanos - elapsedNanos);

    startPublishingTimer(adjustedIntervalNanos);
}

From source file:org.eclipse.milo.opcua.sdk.server.subscriptions.Subscription.java

synchronized void startPublishingTimer() {
    long intervalNanos = TimeUnit.NANOSECONDS
            .convert(DoubleMath.roundToLong(publishingInterval, RoundingMode.UP), TimeUnit.MILLISECONDS);

    startPublishingTimer(intervalNanos);
}

From source file:com.facebook.presto.sql.planner.DomainTranslator.java

private static Expression coerceDoubleToLongComparison(NormalizedSimpleComparison normalized) {
    checkArgument(normalized.getValue().getType().equals(DOUBLE), "Value should be of DOUBLE type");
    checkArgument(!normalized.getValue().isNull(), "Value should not be null");
    QualifiedNameReference reference = normalized.getNameReference();
    Double value = (Double) normalized.getValue().getValue();

    switch (normalized.getComparisonType()) {
    case GREATER_THAN_OR_EQUAL:
    case LESS_THAN:
        return new ComparisonExpression(normalized.getComparisonType(), reference,
                toExpression(DoubleMath.roundToLong(value, CEILING), BIGINT));

    case GREATER_THAN:
    case LESS_THAN_OR_EQUAL:
        return new ComparisonExpression(normalized.getComparisonType(), reference,
                toExpression(DoubleMath.roundToLong(value, FLOOR), BIGINT));

    case EQUAL:/*from w w  w .  ja v a 2  s .  c  o m*/
        Long equalValue = DoubleMath.roundToLong(value, FLOOR);
        if (equalValue.doubleValue() != value) {
            // Return something that is false for all non-null values
            return and(new ComparisonExpression(EQUAL, reference, new LongLiteral("0")),
                    new ComparisonExpression(NOT_EQUAL, reference, new LongLiteral("0")));
        }
        return new ComparisonExpression(normalized.getComparisonType(), reference,
                toExpression(equalValue, BIGINT));

    case NOT_EQUAL:
        Long notEqualValue = DoubleMath.roundToLong(value, FLOOR);
        if (notEqualValue.doubleValue() != value) {
            // Return something that is true for all non-null values
            return or(new ComparisonExpression(EQUAL, reference, new LongLiteral("0")),
                    new ComparisonExpression(NOT_EQUAL, reference, new LongLiteral("0")));
        }
        return new ComparisonExpression(normalized.getComparisonType(), reference,
                toExpression(notEqualValue, BIGINT));

    case IS_DISTINCT_FROM:
        Long distinctValue = DoubleMath.roundToLong(value, FLOOR);
        if (distinctValue.doubleValue() != value) {
            return TRUE_LITERAL;
        }
        return new ComparisonExpression(normalized.getComparisonType(), reference,
                toExpression(distinctValue, BIGINT));

    default:
        throw new AssertionError("Unhandled type: " + normalized.getComparisonType());
    }
}

From source file:org.smartdeveloperhub.harvesters.it.testing.generator.ProjectActivityGenerator.java

private boolean mustCloseIssue(final Issue issue, final LocalDateTime now) {
    long threshold = 80;
    final DateTime dueTo = issue.getDueTo();
    if (dueTo != null) {
        final double mark = toPOSIXMillis(now);
        final double opened = toPOSIXMillis(issue.getOpened().toLocalDateTime());
        final double deadline = toPOSIXMillis(dueTo.toLocalDateTime());
        final double maxDeadline = toPOSIXMillis(dueTo.toLocalDateTime().plusDays(14));
        final long onTime = DoubleMath.roundToLong(90 * ((mark - opened) / (deadline - opened)),
                RoundingMode.CEILING);
        final long delayed = DoubleMath.roundToLong(
                10 * (Math.max(0, mark - deadline) / (maxDeadline - deadline)), RoundingMode.CEILING);
        threshold = onTime + delayed;//from   w w w  .  ja  va  2  s  . c o m
    }
    return this.random.nextInt(100) < threshold;
}