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:io.renren.common.utils.DateUtils.java

License:Apache License

/**
 * ?/?/*from   ww w. ja v  a 2  s  . com*/
 *
 * @param date 
 * @param seconds ?
 * @return /??
 */
public static Date addDateSeconds(Date date, int seconds) {
    DateTime dateTime = new DateTime(date);
    return dateTime.plusSeconds(seconds).toDate();
}

From source file:io.spikex.core.helper.Variables.java

License:Apache License

public static DateTime createDateTimeNow(final String var) {

    DateTime dt;

    // #now//from ww w . jav  a  2 s. com
    // #now(UTC)
    // #now(UTC,0h,-10m,0s)
    // #now(0h,-10m,0s)
    // #now(30m)
    Matcher m = REGEXP_NOW.matcher(var);
    //
    // Timezone
    //
    String tz = null;
    boolean found = m.find();
    if (found) {
        tz = m.group(1);
    }
    //
    // Hours
    //
    int hours = 0;
    if (found) {
        String val = m.group(2);
        if (val != null) {
            hours = Integer.parseInt(val.substring(0, val.length() - 1));
        }
    }
    //
    // Minutes
    //
    int mins = 0;
    if (found) {
        String val = m.group(3);
        if (val != null) {
            mins = Integer.parseInt(val.substring(0, val.length() - 1));
        }
    }
    //
    // Seconds
    //
    int secs = 0;
    if (found) {
        String val = m.group(4);
        if (val != null) {
            secs = Integer.parseInt(val.substring(0, val.length() - 1));
        }
    }

    System.out.println("var: " + var + " tz: " + tz + " hours: " + hours + " mins: " + mins + " secs: " + secs);

    if (tz != null) {
        dt = new DateTime(DateTimeZone.forID(tz));
    } else {
        dt = new DateTime();
    }

    dt = dt.plusHours(hours);
    dt = dt.plusMinutes(mins);
    dt = dt.plusSeconds(secs);

    return dt;
}

From source file:io.tilt.minka.business.leader.distributor.Distributor.java

License:Apache License

private void checkExpiration(final long now, final Reallocation currentRealloc) {
    final DateTime created = currentRealloc.getCreation();
    final int maxSecs = config.getDistributorReallocationExpirationSec();
    final DateTime expiration = created.plusSeconds(maxSecs);
    if (expiration.isBefore(now)) {
        if (currentRealloc.getRetryCount() == config.getDistributorReallocationMaxRetries()) {
            logger.info("{}: Abandoning change expired ! (max secs:{}) ", getClass().getSimpleName(), maxSecs);
            createChangeAndSendIssues(currentRealloc);
        } else {/* w ww.j ava  2 s.  c o  m*/
            currentRealloc.incrementRetry();
            logger.info("{}: ReSending change expired: Retry {} (max secs:{}) ", getClass().getSimpleName(),
                    currentRealloc.getRetryCount(), maxSecs);
            sendCurrentIssues();
        }
    } else {
        logger.info("{}: balancing posponed: an existing change in progress ({}'s to expire)",
                getClass().getSimpleName(), (expiration.getMillis() - now) / 1000);
    }
}

From source file:kr.debop4j.timeperiod.tools.Times.java

License:Apache License

/**  ?  (seconds) ??  */
public static TimeRange getRelativeSecondPeriod(DateTime start, int seconds) {
    return getTimeRange(start, start.plusSeconds(seconds));
}

From source file:net.shibboleth.idp.cas.flow.BuildSamlValidationSuccessMessageAction.java

License:Open Source License

@Nonnull
@Override//from w w w  .  j  ava  2  s. c o  m
protected Response buildSamlResponse(final @Nonnull RequestContext springRequestContext,
        final @Nonnull ProfileRequestContext<SAMLObject, SAMLObject> profileRequestContext) {

    final DateTime now = DateTime.now();

    final TicketValidationRequest request = FlowStateSupport.getTicketValidationRequest(springRequestContext);
    if (request == null) {
        log.info("TicketValidationRequest not found in flow state.");
        throw new IllegalStateException("TicketValidationRequest not found in flow state.");
    }

    final TicketValidationResponse ticketResponse = FlowStateSupport
            .getTicketValidationResponse(springRequestContext);
    if (ticketResponse == null) {
        log.info("TicketValidationResponse not found in flow state.");
        throw new IllegalStateException("TicketValidationResponse not found in flow state.");
    }

    final SessionContext sessionCtx = profileRequestContext.getSubcontext(SessionContext.class, false);
    if (sessionCtx == null || sessionCtx.getIdPSession() == null) {
        log.info("Cannot locate IdP session");
        throw new IllegalStateException("Cannot locate IdP session");
    }
    final IdPSession session = sessionCtx.getIdPSession();

    final Response response = newSAMLObject(Response.class, Response.DEFAULT_ELEMENT_NAME);
    final Status status = newSAMLObject(Status.class, Status.DEFAULT_ELEMENT_NAME);
    final StatusCode code = newSAMLObject(StatusCode.class, StatusCode.DEFAULT_ELEMENT_NAME);
    code.setValue(StatusCode.SUCCESS);
    status.setStatusCode(code);
    response.setStatus(status);

    final Assertion assertion = newSAMLObject(Assertion.class, Assertion.DEFAULT_ELEMENT_NAME);
    assertion.setID(identifierGenerationStrategy.generateIdentifier());
    assertion.setIssueInstant(now);
    assertion.setVersion(SAMLVersion.VERSION_11);
    assertion.setIssuer(entityID);

    final Conditions conditions = newSAMLObject(Conditions.class, Conditions.DEFAULT_ELEMENT_NAME);
    conditions.setNotBefore(now);
    conditions.setNotOnOrAfter(now.plusSeconds(60));
    final AudienceRestrictionCondition audienceRestriction = newSAMLObject(AudienceRestrictionCondition.class,
            AudienceRestrictionCondition.DEFAULT_ELEMENT_NAME);
    final Audience audience = newSAMLObject(Audience.class, Audience.DEFAULT_ELEMENT_NAME);
    audience.setUri(request.getService());
    audienceRestriction.getAudiences().add(audience);
    conditions.getAudienceRestrictionConditions().add(audienceRestriction);
    assertion.setConditions(conditions);

    // Create an AuthenticationStatement for every authentication bound to the IdP session
    // Use flow ID for authentication method
    for (AuthenticationResult result : session.getAuthenticationResults()) {
        assertion.getAuthenticationStatements().add(
                newAuthenticationStatement(now, result.getAuthenticationFlowId(), session.getPrincipalName()));
    }

    final AttributeStatement attrStatement = newSAMLObject(AttributeStatement.class,
            AttributeStatement.DEFAULT_ELEMENT_NAME);
    attrStatement.setSubject(newSubject(session.getPrincipalName()));
    for (final String attrName : ticketResponse.getAttributes().keySet()) {
        final Attribute attribute = newSAMLObject(Attribute.class, Attribute.DEFAULT_ELEMENT_NAME);
        attribute.setAttributeName(attrName);
        attribute.setAttributeNamespace(NAMESPACE);
        for (String value : ticketResponse.getAttributes().get(attrName)) {
            attribute.getAttributeValues().add(newAttributeValue(value));
        }
        attrStatement.getAttributes().add(attribute);
    }
    assertion.getAttributeStatements().add(attrStatement);

    response.getAssertions().add(assertion);
    return response;
}

From source file:net.shibboleth.idp.cas.flow.impl.BuildSamlValidationSuccessMessageAction.java

License:Open Source License

@Nonnull
@Override/*from   w  w w.j  a  va 2  s  .com*/
protected Response buildSamlResponse(@Nonnull final RequestContext springRequestContext,
        @Nonnull final ProfileRequestContext<SAMLObject, SAMLObject> profileRequestContext) {

    final DateTime now = DateTime.now();

    final TicketValidationRequest request = getCASRequest(profileRequestContext);
    final TicketValidationResponse ticketResponse = getCASResponse(profileRequestContext);
    final IdPSession session = getIdPSession(profileRequestContext);
    log.debug("Building SAML response for {} in IdP session {}", request.getService(), session.getId());

    final Response response = newSAMLObject(Response.class, Response.DEFAULT_ELEMENT_NAME);
    response.setID(request.getTicket());
    response.setIssueInstant(DateTime.now());
    final Status status = newSAMLObject(Status.class, Status.DEFAULT_ELEMENT_NAME);
    final StatusCode code = newSAMLObject(StatusCode.class, StatusCode.DEFAULT_ELEMENT_NAME);
    code.setValue(StatusCode.SUCCESS);
    status.setStatusCode(code);
    response.setStatus(status);

    final Assertion assertion = newSAMLObject(Assertion.class, Assertion.DEFAULT_ELEMENT_NAME);
    assertion.setID(identifierGenerationStrategy.generateIdentifier());
    assertion.setIssueInstant(now);
    assertion.setVersion(SAMLVersion.VERSION_11);
    assertion.setIssuer(entityID);

    final Conditions conditions = newSAMLObject(Conditions.class, Conditions.DEFAULT_ELEMENT_NAME);
    conditions.setNotBefore(now);
    conditions.setNotOnOrAfter(now.plusSeconds(60));
    final AudienceRestrictionCondition audienceRestriction = newSAMLObject(AudienceRestrictionCondition.class,
            AudienceRestrictionCondition.DEFAULT_ELEMENT_NAME);
    final Audience audience = newSAMLObject(Audience.class, Audience.DEFAULT_ELEMENT_NAME);
    audience.setUri(request.getService());
    audienceRestriction.getAudiences().add(audience);
    conditions.getAudienceRestrictionConditions().add(audienceRestriction);
    assertion.setConditions(conditions);

    // Create an AuthenticationStatement for every authentication bound to the IdP session
    // Use flow ID for authentication method
    for (AuthenticationResult result : session.getAuthenticationResults()) {
        assertion.getAuthenticationStatements().add(
                newAuthenticationStatement(now, result.getAuthenticationFlowId(), session.getPrincipalName()));
    }

    final AttributeStatement attrStatement = newSAMLObject(AttributeStatement.class,
            AttributeStatement.DEFAULT_ELEMENT_NAME);
    attrStatement.setSubject(newSubject(session.getPrincipalName()));
    for (final String attrName : ticketResponse.getAttributes().keySet()) {
        final Attribute attribute = newSAMLObject(Attribute.class, Attribute.DEFAULT_ELEMENT_NAME);
        attribute.setAttributeName(attrName);
        attribute.setAttributeNamespace(NAMESPACE);
        for (String value : ticketResponse.getAttributes().get(attrName)) {
            attribute.getAttributeValues().add(newAttributeValue(value));
        }
        attrStatement.getAttributes().add(attribute);
    }
    assertion.getAttributeStatements().add(attrStatement);

    response.getAssertions().add(assertion);
    return response;
}

From source file:net.tourbook.device.polar.hrm.PolarHRMDataReader.java

License:Open Source License

/**
 * Converts {@link HRDataSlice} into {@link TimeData}
 * // w  w  w  .  j  a va2s. c  o m
 * @param dtTourStart
 * @return
 */
private ArrayList<TimeData> createTourData10CreateTimeSeries(final DateTime dtTourStart) {

    final boolean isImperial = _sectionParams.isUSUnit;
    final int sliceTimeInterval = _sectionParams.interval;

    int relativeTime = 0;
    float absoluteDistance = 0;

    final ArrayList<TimeData> timeDataList = new ArrayList<TimeData>();

    for (final HRDataSlice hrSlice : _sectionHRData) {

        final TimeData tourSlice = new TimeData();

        tourSlice.relativeTime = relativeTime;
        tourSlice.absoluteTime = dtTourStart.plusSeconds(relativeTime).getMillis();

        if (hrSlice.pulse != Integer.MIN_VALUE) {
            tourSlice.pulse = hrSlice.pulse;
        }

        if (hrSlice.speed != Integer.MIN_VALUE) {

            // convert speed into distance, speed is computed internally and not saved

            final float speed = (float) hrSlice.speed / SPEED_SCALING * 1000 / 3600;

            final float distanceDiff = speed * sliceTimeInterval;

            absoluteDistance += distanceDiff;

            tourSlice.absoluteDistance = absoluteDistance;
        }

        if (hrSlice.altitude != Integer.MIN_VALUE) {
            tourSlice.absoluteAltitude = hrSlice.altitude / (isImperial ? UI.UNIT_FOOT : 1);
        }

        if (hrSlice.cadence != Integer.MIN_VALUE) {
            tourSlice.cadence = hrSlice.cadence;
        }

        timeDataList.add(tourSlice);

        relativeTime += sliceTimeInterval;
    }

    return timeDataList;
}

From source file:net.tourbook.export.gpx.DialogExportTour.java

License:Open Source License

private void createUI16OptionTourPart(final Composite parent) {

    /*//from  w ww  .  ja va  2 s .c  om
     * checkbox: tour range
     */
    String tourRangeUI = null;

    if ((_tourDataList.size() == 1) && (_tourStartIndex != -1) && (_tourEndIndex != -1)) {

        final TourData tourData = _tourDataList.get(0);
        final int[] timeSerie = tourData.timeSerie;
        if (timeSerie != null) {

            final int[] distanceSerie = tourData.distanceSerie;
            final boolean isDistance = distanceSerie != null;

            final int startTime = timeSerie[_tourStartIndex];
            final int endTime = timeSerie[_tourEndIndex];

            final DateTime dtTour = new DateTime(tourData.getStartYear(), tourData.getStartMonth(),
                    tourData.getStartDay(), tourData.getStartHour(), tourData.getStartMinute(),
                    tourData.getStartSecond(), 0);

            final String uiStartTime = _timeFormatter.format(dtTour.plusSeconds(startTime).toDate());
            final String uiEndTime = _timeFormatter.format(dtTour.plusSeconds(endTime).toDate());

            if (isDistance) {

                _numberFormatter.setMinimumFractionDigits(3);
                _numberFormatter.setMaximumFractionDigits(3);

                tourRangeUI = NLS.bind(Messages.dialog_export_chk_tourRangeWithDistance,
                        new Object[] { uiStartTime, uiEndTime,

                                _numberFormatter.format(((float) distanceSerie[_tourStartIndex]) / 1000
                                        / UI.UNIT_VALUE_DISTANCE),

                                _numberFormatter.format(
                                        ((float) distanceSerie[_tourEndIndex]) / 1000 / UI.UNIT_VALUE_DISTANCE),

                                UI.UNIT_LABEL_DISTANCE,

                                // adjust by 1 to corresponds to the number in the tour editor
                                _tourStartIndex + 1, _tourEndIndex + 1 });

            } else {

                tourRangeUI = NLS.bind(Messages.dialog_export_chk_tourRangeWithoutDistance,
                        new Object[] { uiStartTime, uiEndTime, _tourStartIndex + 1, _tourEndIndex + 1 });
            }
        }
    }

    _chkExportTourRange = new Button(parent, SWT.CHECK);
    GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(_chkExportTourRange);

    _chkExportTourRange
            .setText(tourRangeUI != null ? tourRangeUI : Messages.dialog_export_chk_tourRangeDisabled);

    _chkExportTourRange.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(final SelectionEvent e) {
            enableFields();
        }
    });
}

From source file:net.tourbook.export.gpx.DialogExportTour.java

License:Open Source License

private GarminTrack getTrack(final TourData tourData, final DateTime trackDateTime,
        final boolean isCamouflageSpeed, final float camouflageSpeed) {

    final GarminTrack track = new GarminTrack();

    final int[] timeSerie = tourData.timeSerie;
    final int[] altitudeSerie = tourData.altitudeSerie;
    final int[] distanceSerie = tourData.distanceSerie;
    final int[] cadenceSerie = tourData.cadenceSerie;
    final int[] pulseSerie = tourData.pulseSerie;
    final double[] latitudeSerie = tourData.latitudeSerie;
    final double[] longitudeSerie = tourData.longitudeSerie;

    // check if all dataseries are available
    if ((timeSerie == null) || (latitudeSerie == null) || (longitudeSerie == null)) {
        return null;
    }/*from   w w w . j av a 2 s. c o m*/

    final boolean isAltitude = (altitudeSerie != null) && (altitudeSerie.length > 0);
    final boolean isDistance = (distanceSerie != null) && (distanceSerie.length > 0);
    final boolean isPulse = (pulseSerie != null) && (pulseSerie.length > 0);
    final boolean isCadence = (cadenceSerie != null) && (cadenceSerie.length > 0);

    int prevTime = -1;
    DateTime lastTrackDateTime = null;

    // default is to use all trackpoints
    int startIndex = 0;
    int endIndex = timeSerie.length - 1;

    // adjust start/end when a part is exported
    if (isExportTourPart()) {
        startIndex = _tourStartIndex;
        endIndex = _tourEndIndex;
    }

    // set track name
    if (StringUtils.isNotBlank(tourData.getTourTitle())) {
        track.setIdentification(tourData.getTourTitle());
    }

    /*
     * loop: trackpoints
     */
    for (int serieIndex = startIndex; serieIndex <= endIndex; serieIndex++) {

        final GarminTrackpointD304 tp304 = new GarminTrackpointD304();
        final GarminTrackpointAdapter trackPoint = new GarminTrackpointAdapter(tp304);

        // mark as a new track to create the <trkseg>...</trkseg> tags
        if (serieIndex == startIndex) {
            trackPoint.setNewTrack(true);
        }

        if (isAltitude) {
            trackPoint.setAltitude(altitudeSerie[serieIndex]);
        }

        trackPoint.setLongitude(longitudeSerie[serieIndex]);
        trackPoint.setLatitude(latitudeSerie[serieIndex]);

        int currentTime;

        if (isCamouflageSpeed && isDistance) {

            // camouflage speed

            currentTime = (int) (distanceSerie[serieIndex] / camouflageSpeed);

        } else {

            // keep recorded speed

            currentTime = timeSerie[serieIndex];
        }

        if (isDistance) {
            trackPoint.setDistance(distanceSerie[serieIndex]);
        }

        if (isCadence) {
            tp304.setCadence((short) cadenceSerie[serieIndex]);
        }

        if (isPulse) {
            tp304.setHeartrate((short) pulseSerie[serieIndex]);
        }

        // ignore trackpoints which have the same time
        if (currentTime != prevTime) {

            lastTrackDateTime = trackDateTime.plusSeconds(currentTime);
            trackPoint.setDate(lastTrackDateTime.toDate());

            track.addWaypoint(trackPoint);
        }

        prevTime = currentTime;
    }

    // keep last date/time for the next merged tour
    _trackStartDateTime = lastTrackDateTime;

    return track;
}

From source file:net.tourbook.export.gpx.DialogExportTour.java

License:Open Source License

/**
 * Set filename with the first tour date/time, when tour is merged "<#default>" is displayed
 *///from   w w  w.j a v a2 s  . c  om
private void setFileName() {

    // search for the first tour
    TourData minTourData = null;
    final long minTourMillis = 0;

    for (final TourData tourData : _tourDataList) {
        final DateTime checkingTourDate = TourManager.getTourDateTime(tourData);

        if (minTourData == null) {
            minTourData = tourData;
        } else {

            final long tourMillis = checkingTourDate.getMillis();
            if (tourMillis < minTourMillis) {
                minTourData = tourData;
            }
        }
    }

    if (_isMultipleTourAndMultipleFile) {

        // use default file name for each exported tour

        _comboFile.setText(Messages.dialog_export_label_DefaultFileName);

    } else if ((_tourDataList.size() == 1) && (_tourStartIndex != -1) && (_tourEndIndex != -1)) {

        // display the start date/time

        final DateTime dtTour = new DateTime(minTourData.getStartYear(), minTourData.getStartMonth(),
                minTourData.getStartDay(), minTourData.getStartHour(), minTourData.getStartMinute(),
                minTourData.getStartSecond(), 0);

        // adjust start time
        final int startTime = minTourData.timeSerie[_tourStartIndex];
        final DateTime tourTime = dtTour.plusSeconds(startTime);

        _comboFile.setText(UI.format_yyyymmdd_hhmmss(tourTime.getYear(), tourTime.getMonthOfYear(),
                tourTime.getDayOfMonth(), tourTime.getHourOfDay(), tourTime.getMinuteOfHour(),
                tourTime.getSecondOfMinute()));
    } else {

        // display the tour date/time

        _comboFile.setText(UI.format_yyyymmdd_hhmmss(minTourData));
    }
}