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:boundary.AuctionUserFacade.java

/**
 * Method returns a list of auctions. If '@isOver' is true and the user
 * is a customer, it returns a list of auctions the customer has won, else if
 * false it returns auctions ongoing the customer has bid on. 
 * If '@isOver' is true and user is seller, method returns a list of finished
 * auctions published by the seller, else a list of ongoing auctions. 
 * /*  w  ww. j av a2 s.  com*/
 * @param isOver
 *        boolean variable to check if auction is finished
 * @return 
 *      LinkedList of auctions
 */
public List getAuctions(boolean isOver) {
    LinkedList<Integer> list = new LinkedList<Integer>();
    HashSet<Auction> auctionList = new HashSet<Auction>();
    Auction auction;
    DateTime nowDate = new DateTime();
    DateTime dateTime = new DateTime();

    AuctionUser user = getAuctionUser();

    if (user != null) {
        if (user.getRole().equals("customer")) {
            list.addAll(em.createQuery( //query to retrieve all auctions with bids
                    "SELECT b.auction.id FROM Bid as b WHERE b.auctionUser.id =" + user.getId())
                    .getResultList());

        } else if (user.getRole().equals("seller")) {
            list.addAll(em.createQuery( //query to retrieve all auctions
                    "SELECT a.id FROM Auction as a WHERE a.user.id =" + user.getId()).getResultList());
        }
    } else {
        list.addAll(em.createQuery( //query to retrieve all auctions
                "SELECT a.id FROM Auction as a WHERE a.user.id =" + user.getId()).getResultList());
    }

    //Adding winning auctions to the winningList
    for (int i = 0; i < list.size(); i++) {
        auction = em.find(Auction.class, list.get(i));
        dateTime = new DateTime(auction.getStartTime().clone());
        dateTime = dateTime.plusSeconds(Math.toIntExact(auction.getDuration()));

        if (isOver) { //if auction is done
            if (dateTime.compareTo(nowDate) <= 0) {
                auctionList.add(auction);
            }
        } else { //if auction is still ongoing
            if (dateTime.compareTo(nowDate) > 0) {
                auctionList.add(auction);
            }
        }
    }

    LinkedList<Auction> listOfAuctions = new LinkedList<Auction>();
    listOfAuctions.addAll(auctionList);
    return listOfAuctions;
}

From source file:brickhouse.udf.date.AddISOPeriodUDF.java

License:Apache License

public String evaluate(String dateString, String dateFormat, String periodString) {
    if (dateString == null) {
        return null;
    }/*from   w  ww  . j  a va2 s.c o m*/

    if (dateFormat == null) {
        dateFormat = "YYYY-MM-dd HH:mm:ss";
    }

    DateTimeFormatter dateFormatter = org.joda.time.format.DateTimeFormat.forPattern(dateFormat);
    DateTime input = dateFormatter.parseDateTime(dateString);

    Duration duration = periodFormatter.parsePeriod(periodString).toStandardDuration();
    long seconds = duration.getStandardSeconds();

    DateTime output = input.plusSeconds(Long.valueOf(seconds).intValue());
    return dateFormatter.print(output);
}

From source file:ch.emad.business.schuetu.zeit.Countdown.java

License:Apache License

public Countdown(final DateTime jetzt, final int dauerInSeconds) {
    super();//from  w  w w .ja  v a 2s. com
    this.dauer = dauerInSeconds;
    this.ablauf = jetzt.plusSeconds(dauerInSeconds);
    this.letzte = jetzt;

    this.sekundenToGo = dauerInSeconds;

}

From source file:com.bazaarvoice.dropwizard.caching.ResponseCache.java

License:Apache License

public void put(CacheRequestContext request, CacheResponseContext response, byte[] content) {
    if (isResponseCacheable(request) && isResponseCacheable(response)) {
        DateTime responseDate = response.getDate().orNull();

        if (responseDate == null) {
            responseDate = DateTime.now();
            response.setDate(responseDate);
            response.setAge(0);//from   w  w  w  .  j  a va  2  s.  c  o  m
        } else {
            response.setAge(responseDate, DateTime.now());
        }

        response.setExpires(responseDate.plusSeconds(response.getSharedCacheMaxAge()));

        CachedResponse cachedResponse = CachedResponse.build(response.getStatusCode(),
                response.getHttpContext().getHttpHeaders(), content);
        String cacheKey = buildKey(request);

        _localCache.put(cacheKey, cachedResponse);
        _store.put(cacheKey, cachedResponse);
    }
}

From source file:com.boundary.metrics.vmware.poller.VMwarePerfPoller.java

License:Apache License

/**
 * Extracts performance metrics from Managed Objects on the monitored entity
 * /* ww w . ja  va 2s .c o m*/
 * @throws MalformedURLException Bad URL
 * @throws RemoteException Endpoint exception
 * @throws InvalidPropertyFaultMsg Bad Property
 * @throws RuntimeFaultFaultMsg Runtime error
 * @throws SOAPFaultException WebServer error
 */
public void collectPerformanceData() throws MalformedURLException, RemoteException, InvalidPropertyFaultMsg,
        RuntimeFaultFaultMsg, SOAPFaultException {

    ManagedObjectReference root = client.getServiceContent().getRootFolder();

    // 'now' according to the server
    DateTime now = TimeUtils.toDateTime(client.getVimPort().currentTime(client.getServiceInstanceReference()));
    Duration serverSkew = new Duration(now, new DateTime());
    if (serverSkew.isLongerThan(Duration.standardSeconds(1))
            && (skew == null || skew.getStandardSeconds() != serverSkew.getStandardSeconds())) {
        LOG.warn("Server {} and local time skewed by {} seconds", client.getHost(),
                serverSkew.getStandardSeconds());
        skew = serverSkew;
    }
    if (lastPoll == null) {
        lastPoll = now.minusSeconds(20);
    }

    // Holder for all our newly found measurements
    // TODO set an upper size limit on measurements list
    List<Measurement> measurements = Lists.newArrayList();

    /*
    * A {@link PerfMetricId} consistents of the performance counter and
    * the instance it applies to.
    * 
    * In our particular case we are requesting for all of the instances
    * associated with the performance counter.
    * 
    * Will this work when we have a mix of VirtualMachine, HostSystem, and DataSource
    * managed objects.
    * 
    */
    List<PerfMetricId> perfMetricIds = Lists.newArrayList();
    for (String counterName : metrics.keySet()) {
        if (this.performanceCounterMap.containsKey(counterName)) {
            PerfMetricId metricId = new PerfMetricId();
            /* Get the ID for this counter. */
            metricId.setCounterId(this.performanceCounterMap.get(counterName));
            metricId.setInstance("*");
            perfMetricIds.add(metricId);
        }
    }

    GetMOREF getMOREFs = new GetMOREF(client);
    Map<String, ManagedObjectReference> entities = getMOREFs.inFolderByType(root, "VirtualMachine");

    for (Map.Entry<String, ManagedObjectReference> entity : entities.entrySet()) {
        ManagedObjectReference mor = entity.getValue();
        String entityName = entity.getKey();

        /*
        * Create the query specification for queryPerf().
        * Specify 5 minute rollup interval and CSV output format.
        */
        PerfQuerySpec querySpec = new PerfQuerySpec();
        querySpec.setEntity(mor);
        querySpec.setIntervalId(20);
        querySpec.setFormat("normal");
        querySpec.setStartTime(TimeUtils.toXMLGregorianCalendar(lastPoll));
        querySpec.setEndTime(TimeUtils.toXMLGregorianCalendar(now));
        querySpec.getMetricId().addAll(perfMetricIds);

        LOG.info("Entity: {}, MOR: {}-{}, Interval: {}, Format: {}, MetricIds: {}, Start: {}, End: {}",
                entityName, mor.getType(), mor.getValue(), querySpec.getIntervalId(), querySpec.getFormat(),
                FluentIterable.from(perfMetricIds).transform(toStringFunction), lastPoll, now);

        List<PerfEntityMetricBase> retrievedStats = client.getVimPort()
                .queryPerf(client.getServiceContent().getPerfManager(), ImmutableList.of(querySpec));

        /*
        * Cycle through the PerfEntityMetricBase objects. Each object contains
        * a set of statistics for a single ManagedEntity.
        */
        for (PerfEntityMetricBase singleEntityPerfStats : retrievedStats) {
            if (singleEntityPerfStats instanceof PerfEntityMetric) {
                PerfEntityMetric entityStats = (PerfEntityMetric) singleEntityPerfStats;
                List<PerfMetricSeries> metricValues = entityStats.getValue();
                List<PerfSampleInfo> sampleInfos = entityStats.getSampleInfo();

                for (int x = 0; x < metricValues.size(); x++) {
                    PerfMetricIntSeries metricReading = (PerfMetricIntSeries) metricValues.get(x);
                    PerfCounterInfo metricInfo = performanceCounterInfoMap
                            .get(metricReading.getId().getCounterId());
                    String metricFullName = toFullName.apply(metricInfo);
                    if (!sampleInfos.isEmpty()) {
                        PerfSampleInfo sampleInfo = sampleInfos.get(0);
                        DateTime sampleTime = TimeUtils.toDateTime(sampleInfo.getTimestamp());
                        Number sampleValue = metricReading.getValue().iterator().next();

                        if (skew != null) {
                            sampleTime = sampleTime.plusSeconds((int) skew.getStandardSeconds());
                        }

                        if (metricReading.getValue().size() > 1) {
                            LOG.warn("Metric {} has more than one value, only using the first", metricFullName);
                        }

                        String source = client.getName() + "-" + entityName;

                        if (metricInfo.getUnitInfo().getKey().equalsIgnoreCase("kiloBytes")) {
                            sampleValue = (long) sampleValue * 1024; // Convert KB to Bytes
                        } else if (metricInfo.getUnitInfo().getKey().equalsIgnoreCase("percent")) {
                            // Convert hundredth of a percent to a decimal percent
                            sampleValue = new Long((long) sampleValue).doubleValue() / 10000.0;
                        }
                        String name = metrics.get(metricFullName).getName();
                        if (name != null) {
                            Measurement measurement = Measurement.builder().setMetric(name).setSource(source)
                                    .setTimestamp(sampleTime).setMeasurement(sampleValue).build();
                            measurements.add(measurement);

                            LOG.info("{} @ {} = {} {}", metricFullName, sampleTime, sampleValue,
                                    metricInfo.getUnitInfo().getKey());
                        } else {
                            LOG.warn("Skipping collection of metric: {}", metricFullName);
                        }
                    } else {
                        LOG.warn("Didn't receive any samples when polling for {} on {} between {} and {}",
                                metricFullName, client.getHost(), lastPoll, now);
                    }
                }
            } else {
                LOG.error("Unrecognized performance entry type received: {}, ignoring",
                        singleEntityPerfStats.getClass().getName());
            }
        }
    }

    // Send metrics
    if (!measurements.isEmpty()) {
        metricsClient.addMeasurements(measurements);
    } else {
        LOG.warn("No measurements collected in last poll for {}", client.getHost());
    }

    // Reset lastPoll time
    lastPoll = now;
}

From source file:com.cisco.dvbu.ps.utils.date.DateAddDate.java

License:Open Source License

/**
 * Called to invoke the stored procedure.  Will only be called a
 * single time per instance.  Can throw CustomProcedureException or
 * SQLException if there is an error during invoke.
 *///from  w  ww .  j av a2  s  .c om
@Override
public void invoke(Object[] inputValues) throws CustomProcedureException, SQLException {
    java.util.Date startDate = null;
    Calendar startCal = null;
    DateTime startDateTime = null;
    DateTime endDateTime = null;
    String datePart = null;
    int dateLength = 0;

    try {
        result = null;
        if (inputValues[0] == null || inputValues[1] == null || inputValues[2] == null) {
            return;
        }

        datePart = (String) inputValues[0];
        dateLength = (Integer) inputValues[1];

        startDate = (java.util.Date) inputValues[2];
        startCal = Calendar.getInstance();
        startCal.setTime(startDate);
        startDateTime = new DateTime(startCal.get(Calendar.YEAR), startCal.get(Calendar.MONTH) + 1,
                startCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0, 0);

        if (datePart.equalsIgnoreCase("second")) {
            endDateTime = startDateTime.plusSeconds(dateLength);
        }

        if (datePart.equalsIgnoreCase("minute")) {
            endDateTime = startDateTime.plusMinutes(dateLength);
        }

        if (datePart.equalsIgnoreCase("hour")) {
            endDateTime = startDateTime.plusHours(dateLength);
        }

        if (datePart.equalsIgnoreCase("day")) {
            endDateTime = startDateTime.plusDays(dateLength);
        }

        if (datePart.equalsIgnoreCase("week")) {
            endDateTime = startDateTime.plusWeeks(dateLength);
        }

        if (datePart.equalsIgnoreCase("month")) {
            endDateTime = startDateTime.plusMonths(dateLength);
        }

        if (datePart.equalsIgnoreCase("year")) {
            endDateTime = startDateTime.plusYears(dateLength);
        }

        result = new java.sql.Date(endDateTime.getMillis());
    } catch (Throwable t) {
        throw new CustomProcedureException(t);
    }
}

From source file:com.cisco.dvbu.ps.utils.date.DateAddTimestamp.java

License:Open Source License

/**
 * Called to invoke the stored procedure.  Will only be called a
 * single time per instance.  Can throw CustomProcedureException or
 * SQLException if there is an error during invoke.
 */// ww  w  .j av a2 s. com
@Override
public void invoke(Object[] inputValues) throws CustomProcedureException, SQLException {
    Timestamp startDate = null;
    Calendar startCal = null;
    DateTime startDateTime = null;
    DateTime endDateTime = null;
    String datePart = null;
    int dateLength = 0;

    try {
        result = null;
        if (inputValues[0] == null || inputValues[1] == null || inputValues[2] == null) {
            return;
        }

        datePart = (String) inputValues[0];
        dateLength = (Integer) inputValues[1];

        startDate = (Timestamp) inputValues[2];
        startCal = Calendar.getInstance();
        startCal.setTime(startDate);
        startDateTime = new DateTime(startCal.get(Calendar.YEAR), startCal.get(Calendar.MONTH) + 1,
                startCal.get(Calendar.DAY_OF_MONTH), startCal.get(Calendar.HOUR_OF_DAY),
                startCal.get(Calendar.MINUTE), startCal.get(Calendar.SECOND),
                startCal.get(Calendar.MILLISECOND));

        if (datePart.equalsIgnoreCase("second")) {
            endDateTime = startDateTime.plusSeconds(dateLength);
        }

        if (datePart.equalsIgnoreCase("minute")) {
            endDateTime = startDateTime.plusMinutes(dateLength);
        }

        if (datePart.equalsIgnoreCase("hour")) {
            endDateTime = startDateTime.plusHours(dateLength);
        }

        if (datePart.equalsIgnoreCase("day")) {
            endDateTime = startDateTime.plusDays(dateLength);
        }

        if (datePart.equalsIgnoreCase("week")) {
            endDateTime = startDateTime.plusWeeks(dateLength);
        }

        if (datePart.equalsIgnoreCase("month")) {
            endDateTime = startDateTime.plusMonths(dateLength);
        }

        if (datePart.equalsIgnoreCase("year")) {
            endDateTime = startDateTime.plusYears(dateLength);
        }

        result = new Timestamp(endDateTime.toDate().getTime());
    } catch (Throwable t) {
        throw new CustomProcedureException(t);
    }
}

From source file:com.cognitivabrasil.repositorio.services.DocumentServiceImpl.java

License:Open Source License

private DateTime add1Second(DateTime dateTime) {
    return dateTime.plusSeconds(1);
}

From source file:com.cronutils.model.time.ExecutionTime.java

License:Apache License

/**
 * Provide nearest date for next execution.
 * @param date - jodatime DateTime instance. If null, a NullPointerException will be raised.
 * @return DateTime instance, never null. Next execution time.
 *///from  w ww.  j av a2 s . co m
public DateTime nextExecution(DateTime date) {
    Validate.notNull(date);
    try {
        DateTime nextMatch = nextClosestMatch(date);
        if (nextMatch.equals(date)) {
            nextMatch = nextClosestMatch(date.plusSeconds(1));
        }
        return nextMatch;
    } catch (NoSuchValueException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.enonic.cms.business.portal.rendering.PageRenderer.java

License:Open Source License

private RenderedPageResult doRenderPageAndWindows(final PageTemplateEntity pageTemplate) {
    RenderedPageResult renderedPageResult = doRenderPageTemplate(pageTemplate);

    String renderedPageContentIncludingRenderedWindows = executePostProcessInstructions(pageTemplate,
            renderedPageResult.getContent(), renderedPageResult.getOutputMethod());

    renderedPageContentIncludingRenderedWindows = renderedPageContentIncludingRenderedWindows
            .replace(Ticket.getPlaceholder(), context.getTicketId());

    renderedPageResult.setContent(renderedPageContentIncludingRenderedWindows);

    CacheSettings normalizedPageCacheSettings = tightestCacheSettingsResolver
            .resolveTightestCacheSettingsForPage(context.getMenuItem(), context.getRegionsInPage(),
                    pageTemplate);// w  ww . j  a  v  a2s . co m
    DateTime requestTime = context.getRequestTime();
    DateTime expirationTime = requestTime.plusSeconds(normalizedPageCacheSettings.getSpecifiedSecondsToLive());
    renderedPageResult.setExpirationTime(expirationTime);
    return renderedPageResult;
}