Example usage for org.joda.time DateTime plusSeconds

List of usage examples for org.joda.time DateTime plusSeconds

Introduction

In this page you can find the example usage for org.joda.time DateTime plusSeconds.

Prototype

public DateTime plusSeconds(int seconds) 

Source Link

Document

Returns a copy of this datetime plus the specified number of seconds.

Usage

From source file:de.hpi.bpmn2_0.animation.AnimationJSONBuilder.java

License:Open Source License

/**
 * Generate json for the progress bar/*from w  w w .j av  a2  s  . co  m*/
 * @param animationLog
 * @return
 * @throws JSONException 
 * Bruce 24.08.2015: fix bug of start time and duration of the progress bar
 * Add begin and duration attribute for the progress log tag, similar to SequenceFlow
 */
protected JSONObject parseLogProgress(AnimationLog animationLog) throws JSONException {
    String keyTimes = "";
    String values = "";
    final int PROGRESS_BAR_LEVELS = 100; //divide the progress bar into 100 levels
    final int TOTAL_TRACES = animationLog.getTraces().size();

    DateTime logStart = animationLog.getStartDate();
    DateTime logEnd = animationLog.getEndDate();
    double begin = Seconds.secondsBetween(totalRealInterval.getStart(), logStart).getSeconds()
            * this.getTimeConversionRatio();
    double durEngine = (logEnd.getMillis() - logStart.getMillis()) * this.getTimeConversionRatio(); // in milliseconds  
    double durData = logEnd.getMillis() - logStart.getMillis(); // in milliseconds  
    double levelTime = 1.0 * durData / (1000 * PROGRESS_BAR_LEVELS); //number of seconds for every movement level

    //-------------------------------------------
    // The progress bar is divided into PROGRESS_BAR_LEVELS levels
    // Remember: keyTimes is the percentage relative to begin and duration value, within 0-1 range,
    // values are relative to the length of the progress bar and must start from 0.        
    // Calculate keyTimes: the percentage of the current level number over the total number of levels
    // Calculate values: move to every level, calculate the level timestamp, then count
    // the total number of traces that end after that timestamp
    //-------------------------------------------
    DateTime currentLevelTimestamp;
    int traceCount;
    double keyTimeVal;
    double totalVal = 2 * Math.PI * params.getProgressCircleBarRadius(); //the perimeter of the progress circle bar
    DecimalFormat df = new DecimalFormat("#.##");

    for (int i = 1; i <= PROGRESS_BAR_LEVELS; i++) {
        keyTimeVal = 1.0 * i / PROGRESS_BAR_LEVELS; //params.getTimelineSlots();
        currentLevelTimestamp = logStart.plusSeconds(Double.valueOf(i * levelTime).intValue());
        traceCount = 0;
        for (ReplayTrace trace : animationLog.getTraces()) {
            if (trace.getInterval().getEnd().isBefore(currentLevelTimestamp)
                    || trace.getInterval().getEnd().isEqual(currentLevelTimestamp)) {
                traceCount++;
            }
        }
        if (i == 1) {
            keyTimes += "0;"; //required by SVG keytimes specification
            values += "0;"; //required by SVG values specification
        } else if (i == PROGRESS_BAR_LEVELS) {
            keyTimes += "1;"; //required by SVG keyTimes specification
            values += (df.format(totalVal) + ";"); //(Math.round((1.0*traceCount/animationLog.getTraces().size())*totalVal) + ";");
        } else {
            keyTimes += (df.format(keyTimeVal) + ";");
            double value = (1.0 * traceCount / TOTAL_TRACES) * totalVal;
            values += (df.format(value) + ";");
        }
    }
    if (keyTimes.length() > 0) {
        keyTimes = keyTimes.substring(0, keyTimes.length() - 1);
    }
    if (values.length() > 0) {
        values = values.substring(0, values.length() - 1);
    }

    JSONObject json = new JSONObject();
    json.put("keyTimes", keyTimes);
    json.put("values", values);

    df.applyPattern("#.#####");
    json.put("begin", df.format(begin));
    json.put("dur", df.format(1.0 * durEngine / 1000));

    return json;
}

From source file:de.rwth.idsg.xsharing.router.core.routing.strategy.inavailability.bike.WithReturnBikeInavailabilityStrategy.java

License:Open Source License

/**
 *  start   | end    | overlaps?/*from w  w w . j  a v  a  2 s  . c o m*/
 * ---------+--------+--------------------------------------------------
 *  now     | now    | check inavailability at both stations
 *  now     | future | check inavailability at start station, be optimistic about end station
 *  future  | now    | false. cannot happen, chronologically not possible
 *  future  | future | false. both in future => be optimistic, no check
 */
@Override
public boolean overlaps(int stayTime, RouteLegList legs, SharingStation startStation,
        RouteLegWrapper bikeWrapper, SharingStation endStation, RouteLegWrapper walkWrapper) {

    // We always set stay time. Depending on DurationCheckStrategy it will be used or not.
    walkWrapper.setStayTime(stayTime);

    // -------------------------------------------------------------------------
    // 1) If in future, be optimistic and assume always available
    // -------------------------------------------------------------------------

    Interval nowTimeWindow = getNowTimeWindow();

    DateTime timeAtStartStation = legs.getAfterLastLeg();
    boolean startIsNow = nowTimeWindow.contains(timeAtStartStation);

    if (!startIsNow) {
        return false;
    }

    // -------------------------------------------------------------------------
    // 2) Check actual intervals for availability
    // -------------------------------------------------------------------------

    int bikeLegDuration = bikeWrapper.getLeg().getDuration();
    int durationAfterStartStation = bikeLegDuration + durationCheckStrategy.getDurationToCheck(walkWrapper);

    DateTime timeAtReturnStation = timeAtStartStation.plusSeconds(durationAfterStartStation);
    boolean endIsNow = nowTimeWindow.contains(timeAtReturnStation);

    if (endIsNow) {
        // Check bike availability for "HinFahrt" at start station and "RckFahrt" at end station
        return overlapsAtStation(legs, startStation, bikeLegDuration)
                || overlapsAtStation(legs, endStation, durationAfterStartStation);
    } else {
        // Check bike availability for "HinFahrt" at start station
        return overlapsAtStation(legs, startStation, bikeLegDuration);
    }
}

From source file:de.rwth.idsg.xsharing.router.core.routing.util.MinimalRouteFactory.java

License:Open Source License

public static RouteMinimalRepresentation getMinRep(GeoCoord from, GeoCoord to, DateTime time, boolean isArrival,
        RouteContext sm) {/*from w  ww .j av  a  2  s  . c  o m*/
    List<RouteLegWrapper> legs = sm.getLegs();

    if (checkNullOrEmpty(legs)) {
        return null;
    }

    RouteMinimalRepresentation route = new RouteMinimalRepresentation();
    route.setFrom(from);
    route.setTo(to);
    route.setTotalDurationCached(sm.getTotalDurationInSeconds());
    route.setTotalDistance(sm.getTotalDistance());

    LinkedList<LegMinimalRepresentation> legList = new LinkedList<>();
    for (RouteLegWrapper l : legs) {
        legList.add(getSingleLeg(l));
    }
    route.setLegs(legList);
    route.setArrivalTime(isArrival);

    // internal duration in seconds !!!
    //
    if (isArrival) {
        route.setArrival(time);
        route.setDeparture(time.minusSeconds(route.getTotalDuration()));
    } else {
        route.setDeparture(time);
        route.setArrival(time.plusSeconds(route.getTotalDuration()));
    }
    return route;
}

From source file:de.rwth.idsg.xsharing.router.persistence.domain.routes.representation.factory.RouteRepresentationFactory.java

License:Open Source License

public static RouteMinimalRepresentation getMinRep(GeoCoord from, GeoCoord to, DateTime time, boolean isArrival,
        List<RouteLeg> legs) {
    if (checkNullOrEmpty(legs)) {
        return null;
    }//ww w. j a  va2 s  .  c  om

    RouteMinimalRepresentation route = new RouteMinimalRepresentation();
    route.setFrom(from);
    route.setTo(to);

    LinkedList<LegMinimalRepresentation> legList = new LinkedList<>();
    for (RouteLeg l : legs) {
        legList.add(RouteLegFactory.getMinRep(l));
    }
    route.setLegs(legList);
    route.setArrivalTime(isArrival);

    // internal duration in seconds !!!
    //
    if (isArrival) {
        route.setArrival(time);
        route.setDeparture(time.minusSeconds(route.getTotalDuration()));
    } else {
        route.setDeparture(time);
        route.setArrival(time.plusSeconds(route.getTotalDuration()));
    }
    return route;
}

From source file:demos.AsynchronousInsert.java

License:Apache License

@Override
public void run() {
    try {/*from   www  .ja v a  2  s  .  c  om*/
        logger.info("Preparing to insert metric data points");

        Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
        Session session = cluster.connect("demo");
        PreparedStatement insert = session
                .prepare("insert into metric_data (metric_id, time, value) values (?, ?, ?)");
        Random random = new Random();
        DateTime time = DateTime.now().minusYears(1);
        final CountDownLatch latch = new CountDownLatch(NUM_INSERTS);

        FutureCallback<ResultSet> callback = new FutureCallback<ResultSet>() {
            @Override
            public void onSuccess(ResultSet result) {
                latch.countDown();
            }

            @Override
            public void onFailure(Throwable t) {
                logger.warn("There was an error inserting data", t);
                latch.countDown();
            }
        };

        Stopwatch stopwatch = new Stopwatch().start();
        for (int i = 0; i < NUM_INSERTS; ++i) {
            String metricId = "metric-" + Math.abs(random.nextInt() % NUM_METRICS);
            double value = random.nextDouble();
            ResultSetFuture future = session.executeAsync(insert.bind(metricId, time.toDate(), value));
            time = time.plusSeconds(10);
            Futures.addCallback(future, callback);
        }
        latch.await();
        stopwatch.stop();

        logger.info("Finished inserting {} data points in {} ms", NUM_INSERTS,
                stopwatch.elapsed(TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
        logger.info("There was an interrupt while waiting for inserts to complete");
    }
}

From source file:demos.BatchInsert.java

License:Apache License

public void run() {
    try {//from   ww  w  .jav a2s. c o m
        logger.info("Preparing to insert metric data points");

        Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
        Session session = cluster.connect("demo");
        PreparedStatement insert = session
                .prepare("insert into metric_data (metric_id, time, value) values (?, ?, ?)");
        Random random = new Random();
        DateTime time = DateTime.now().minusYears(1);
        final CountDownLatch latch = new CountDownLatch(NUM_INSERTS / BATCH_SIZE);

        FutureCallback<ResultSet> callback = new FutureCallback<ResultSet>() {
            @Override
            public void onSuccess(ResultSet result) {
                latch.countDown();
            }

            @Override
            public void onFailure(Throwable t) {
                logger.warn("There was an error inserting data", t);
                latch.countDown();
            }
        };

        Stopwatch stopwatch = new Stopwatch().start();
        BatchStatement batch = new BatchStatement();
        for (int i = 0; i < NUM_INSERTS; ++i) {
            String metricId = "metric-" + Math.abs(random.nextInt() % NUM_METRICS);
            double value = random.nextDouble();
            batch.add(insert.bind(metricId, time.toDate(), value));
            time = time.plusSeconds(10);
            if (batch.size() == BATCH_SIZE) {
                ResultSetFuture future = session.executeAsync(batch);
                Futures.addCallback(future, callback);
                batch = new BatchStatement();
            }
        }
        latch.await();
        stopwatch.stop();

        logger.info("Finished inserting {} data points in {} ms", NUM_INSERTS,
                stopwatch.elapsed(TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
        logger.info("There was an interrupt while waiting for inserts to complete");
    }
}

From source file:demos.SynchronousInsert.java

License:Apache License

public void run() {
    logger.info("Preparing to insert metric data points");

    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    Session session = cluster.connect("demo");
    PreparedStatement insert = session
            .prepare("insert into metric_data (metric_id, time, value) values (?, ?, ?)");
    Random random = new Random();
    DateTime time = DateTime.now().minusYears(1);

    Stopwatch stopwatch = new Stopwatch().start();
    for (int i = 0; i < NUM_INSERTS; ++i) {
        String metricId = "metric-" + Math.abs(random.nextInt() % NUM_METRICS);
        double value = random.nextDouble();
        session.execute(insert.bind(metricId, time.toDate(), value));
        time = time.plusSeconds(10);
    }//w w w  . j  av  a 2s  .  c om
    stopwatch.stop();

    logger.info("Finished inserting {} data points in {} ms", NUM_INSERTS,
            stopwatch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:eu.eidas.auth.engine.core.stork.StorkExtensionProcessor.java

License:EUPL

@Nonnull
@Override/* ww  w.  j  a v a2s.  c  o m*/
public Response marshallErrorResponse(@Nonnull IAuthenticationRequest request,
        @Nonnull IAuthenticationResponse response, @Nonnull String ipAddress,
        @Nonnull SamlEngineCoreProperties coreProperties) throws EIDASSAMLEngineException {

    LOG.trace("generateResponseMessageFail");
    validateParamResponseFail(request, response);

    // Mandatory
    StatusCode statusCode = BuilderFactoryUtil.generateStatusCode(response.getStatusCode());

    // Mandatory SAML
    LOG.trace("Generate StatusCode.");
    // Subordinate code is optional in case not covered into next codes:
    // - urn:oasis:names:tc:SAML:2.0:status:AuthnFailed
    // - urn:oasis:names:tc:SAML:2.0:status:InvalidAttrNameOrValue
    // - urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy
    // - urn:oasis:names:tc:SAML:2.0:status:RequestDenied
    // - http://www.stork.gov.eu/saml20/statusCodes/QAANotSupported

    if (StringUtils.isNotBlank(response.getSubStatusCode())) {
        StatusCode newStatusCode = BuilderFactoryUtil.generateStatusCode(response.getSubStatusCode());
        statusCode.setStatusCode(newStatusCode);
    }

    LOG.debug("Generate Status.");
    Status status = BuilderFactoryUtil.generateStatus(statusCode);

    if (StringUtils.isNotBlank(response.getStatusMessage())) {
        StatusMessage statusMessage = BuilderFactoryUtil.generateStatusMessage(response.getStatusMessage());

        status.setStatusMessage(statusMessage);
    }

    LOG.trace("Generate Response.");
    // RESPONSE
    Response responseFail = newResponse(status, request.getAssertionConsumerServiceURL(), request.getId(),
            coreProperties);

    String responseIssuer = response.getIssuer();
    if (responseIssuer != null && !responseIssuer.isEmpty()) {
        responseFail.getIssuer().setValue(responseIssuer);
    }
    DateTime notOnOrAfter = new DateTime();

    notOnOrAfter = notOnOrAfter.plusSeconds(coreProperties.getTimeNotOnOrAfter());

    Assertion assertion = AssertionUtil.generateResponseAssertion(true, ipAddress, request,
            responseFail.getIssuer(), ImmutableAttributeMap.of(), notOnOrAfter,
            coreProperties.getFormatEntity(), coreProperties.getResponder(), getFormat(),
            coreProperties.isOneTimeUse());
    addResponseAuthnContextClassRef(response, assertion);
    responseFail.getAssertions().add(assertion);

    return responseFail;

}

From source file:eu.eidas.auth.engine.core.stork.StorkExtensionProcessor.java

License:EUPL

/**
 * Generates authentication response in one of the supported formats.
 *
 * @param request the request/*ww  w.j a  va 2s .  co  m*/
 * @param response the authentication response from the IdP
 * @param ipAddress the IP address
 * @return the authentication response
 * @throws EIDASSAMLEngineException the EIDASSAML engine exception
 */
@Override
@Nonnull
public Response marshallResponse(@Nonnull IAuthenticationRequest request,
        @Nonnull IAuthenticationResponse response, @Nonnull String ipAddress,
        @Nonnull SamlEngineCoreProperties coreProperties) throws EIDASSAMLEngineException {
    LOG.trace("marshallResponse");

    // At this point the assertion consumer service URL is mandatory (and must have been replaced by the value from the metadata if needed)
    if (StringUtils.isBlank(request.getAssertionConsumerServiceURL())) {
        throw new EIDASSAMLEngineException(EidasErrorKey.MESSAGE_VALIDATION_ERROR.errorCode(),
                EidasErrorKey.MESSAGE_VALIDATION_ERROR.errorCode(),
                "Request AssertionConsumerServiceURL must not be blank.");
    }

    // Mandatory SAML
    LOG.trace("Generate StatusCode");
    StatusCode statusCode = BuilderFactoryUtil.generateStatusCode(StatusCode.SUCCESS_URI);

    LOG.trace("Generate Status");
    Status status = BuilderFactoryUtil.generateStatus(statusCode);

    LOG.trace("Generate StatusMessage");
    StatusMessage statusMessage = BuilderFactoryUtil.generateStatusMessage(StatusCode.SUCCESS_URI);

    status.setStatusMessage(statusMessage);

    LOG.trace("Generate Response");

    Response samlResponse = newResponse(status, request.getAssertionConsumerServiceURL(), request.getId(),
            coreProperties);

    if (StringUtils.isNotBlank(response.getIssuer()) && null != samlResponse.getIssuer()) {
        samlResponse.getIssuer().setValue(SAMLEngineUtils.getValidIssuerValue(response.getIssuer()));
    }
    DateTime notOnOrAfter = new DateTime();

    notOnOrAfter = notOnOrAfter.plusSeconds(coreProperties.getTimeNotOnOrAfter().intValue());

    Assertion assertion = AssertionUtil.generateResponseAssertion(false, ipAddress, request,
            samlResponse.getIssuer(), response.getAttributes(), notOnOrAfter, coreProperties.getFormatEntity(),
            coreProperties.getResponder(), getFormat(), coreProperties.isOneTimeUse());

    AttributeStatement attrStatement = generateResponseAttributeStatement(response.getAttributes());

    assertion.getAttributeStatements().add(attrStatement);

    addResponseAuthnContextClassRef(response, assertion);

    samlResponse.getAssertions().add(assertion);

    return samlResponse;
}

From source file:eu.eidas.auth.engine.core.stork.StorkProtocolProcessor.java

License:EUPL

@Nonnull
@Override//from   w  w  w.  j  a  va  2s. c  om
public Response marshallErrorResponse(@Nonnull IAuthenticationRequest request,
        @Nonnull IAuthenticationResponse response, @Nonnull String ipAddress,
        @Nonnull SamlEngineCoreProperties coreProperties) throws EIDASSAMLEngineException {
    LOG.trace("generateResponseMessageFail");
    validateParamResponseFail(request, response);

    // Mandatory
    StatusCode statusCode = BuilderFactoryUtil.generateStatusCode(response.getStatusCode());

    // Mandatory SAML
    LOG.trace("Generate StatusCode.");
    // Subordinate code is optional in case not covered into next codes:
    // - urn:oasis:names:tc:SAML:2.0:status:AuthnFailed
    // - urn:oasis:names:tc:SAML:2.0:status:InvalidAttrNameOrValue
    // - urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy
    // - urn:oasis:names:tc:SAML:2.0:status:RequestDenied
    // - http://www.stork.gov.eu/saml20/statusCodes/QAANotSupported

    if (StringUtils.isNotBlank(response.getSubStatusCode())) {
        StatusCode newStatusCode = BuilderFactoryUtil.generateStatusCode(response.getSubStatusCode());
        statusCode.setStatusCode(newStatusCode);
    }

    LOG.debug("Generate Status.");
    Status status = BuilderFactoryUtil.generateStatus(statusCode);

    if (StringUtils.isNotBlank(response.getStatusMessage())) {
        StatusMessage statusMessage = BuilderFactoryUtil.generateStatusMessage(response.getStatusMessage());

        status.setStatusMessage(statusMessage);
    }

    LOG.trace("Generate Response.");
    // RESPONSE
    Response responseFail = newResponse(status, request.getAssertionConsumerServiceURL(), request.getId(),
            coreProperties);

    String responseIssuer = response.getIssuer();
    if (responseIssuer != null && !responseIssuer.isEmpty()) {
        responseFail.getIssuer().setValue(responseIssuer);
    }
    DateTime notOnOrAfter = new DateTime();

    notOnOrAfter = notOnOrAfter.plusSeconds(coreProperties.getTimeNotOnOrAfter());

    Assertion assertion = AssertionUtil.generateResponseAssertion(true, ipAddress, request,
            responseFail.getIssuer(), ImmutableAttributeMap.of(), notOnOrAfter,
            coreProperties.getFormatEntity(), coreProperties.getResponder(), getFormat(),
            coreProperties.isOneTimeUse());
    addResponseAuthnContextClassRef(response, assertion);
    responseFail.getAssertions().add(assertion);

    return responseFail;
}