Example usage for org.joda.time Period Period

List of usage examples for org.joda.time Period Period

Introduction

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

Prototype

private Period(int[] values, PeriodType type) 

Source Link

Document

Constructor used when we trust ourselves.

Usage

From source file:ru.codemine.ccms.entity.Task.java

License:Open Source License

public String getProgressTimeStr() {
    if (!isClosed() || getCloseTime() == null)
        return "";

    PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix(" ", " ")
            .appendSeparator(" ").appendHours().appendSuffix(" ?", " ?").appendSeparator(" ")
            .appendMinutes().appendSuffix(" ", " ").toFormatter();

    Period progressPeriod = new Period(getCreationTime(), getCloseTime());

    return formatter.print(progressPeriod);
}

From source file:se.toxbee.sleepfighter.text.DateTextUtils.java

License:Open Source License

/**
 * Builds and returns text for the time to an alarm given resources, current time, and AlarmTimestamp when given a resources bundle.
 *
 * @param res Android resources.//from ww w  .ja v a  2  s.  c  om
 * @param now current time in unix epoch timestamp.
 * @param ats an AlarmTimestamp: the information about the alarm & its timestamp.
 * @return the built time-to string.
 */
public static final String getTimeToText(Resources res, long now, AlarmTimestamp ats) {
    Period diff = null;

    // ats is invalid when all the alarms have been turned off. INVALID has the value null. 
    // therefore, we must do a nullcheck, otherwise we get an exception. 
    if (ats != AlarmTimestamp.INVALID) {
        diff = new Period(now, ats.getMillis());
    }

    String[] formats = res.getStringArray(R.array.earliest_time_formats);
    String[] partFormats = res.getStringArray(R.array.earliest_time_formats_parts);

    return getTimeToText(formats, partFormats, diff, ats);
}

From source file:tgs.Task.java

@Override
public void run() {
    try {//from   w  w w .  jav  a2 s. co  m
        oos = new ObjectOutputStream(cSock.getOutputStream());
        ois = new ObjectInputStream(cSock.getInputStream());

        // Chargement cl symtrique KTGS
        SecretKey KTGS = new SecretKeySpec("cisco123".getBytes(), "DES");

        // Rcupration de l'objet
        TGSRequest TGSreq = (TGSRequest) ois.readObject();

        // Dcryptage de l'objet TGSRequest avec la cl symtrique KTGS
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, KTGS);
        TicketTCTGS ticket = (TicketTCTGS) TGSreq.getTicket().getObject(cipher);

        // Rcupration cl de session KCTGS
        KCTGS = ticket.getKctgsSessionKey();

        // Reinitialisation du cipher avec la KCTGS
        cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, KCTGS);

        // Dcryptage de l'authentificateur
        AuthenticatorTGS auth = (AuthenticatorTGS) TGSreq.getAuthenticator().getObject(cipher);

        // Vrification checksum
        if (auth.getClientName().hashCode() != auth.getChecksum())
            throw new BadChecksumException();

        // Verification timestamp
        DateTime valid = new DateTime(ticket.getTimeValid().getTime());
        DateTime current = new DateTime(auth.getCurrentTime().getTime());
        Period diff = new Period(valid, current);
        if (diff.getHours() > 8)
            throw new BadTimestampException();

        // Construction TGS Reply
        SecretKey kcsKey = new SecretKeySpec("cisco456".getBytes(), "DES");
        SecretKey KS = new SecretKeySpec("cisco789".getBytes(), "DES");

        KCS kcs = new KCS();
        kcs.setClientName(auth.getClientName());
        kcs.setValidity(ticket.getTimeValid());
        kcs.setKcs(kcsKey);
        cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, KS);
        SealedObject soKCS = new SealedObject(kcs, cipher);

        TicketCS tick = new TicketCS();
        tick.setService(TGSreq.getService());
        tick.setKCS(soKCS);

        cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, KCTGS);

        SealedObject soKCSkeyOnly = new SealedObject(kcsKey, cipher);

        TGSReply TGSrep = new TGSReply();
        TGSrep.setKCSkey(soKCSkeyOnly);
        TGSrep.setTicket(tick);

        oos.writeObject(TGSrep);

    } catch (BadChecksumException ex) {
        System.out.println("BadCheckSumExc");
    } catch (BadTimestampException ex) {
        System.out.println("BadTimeStampExc");
    } catch (Exception ex) {
        Logger.getLogger(Task.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:trabalho.model.JodaMain.java

public int retornaTempo(RegistroPontoEntity registro) {
    RegistroPontoEntity registroPonto = registro;
    DateTime dataHoraEntrada = new DateTime(registroPonto.getDataInicial());
    DateTime dataHoraSaida = new DateTime(registroPonto.getDataFinal());
    Period tempoTrabalhado = new Period(dataHoraEntrada, dataHoraSaida);
    int horaLocal = tempoTrabalhado.getMinutes() + tempoTrabalhado.getHours() * 60
            + tempoTrabalhado.getDays() * 1440;
    System.out.println(horaLocal);
    return horaLocal;
}

From source file:uk.ac.ed.uportal.portlets.collaborateportlet.mvc.portlet.EditController.java

License:Apache License

/**
 * Perform manual model binding for Session start and end dates
 *
 * @param request The request to extract start and end dates from
 * @param session The session to add start and end dates to
 * @return Validation error messages generated by this binding. The list will be empty if binding was successful
 *///from  w ww .  j  a va 2 s  .  com
private List<String> addValidatedRequestDatesToSession(ActionRequest request, Session session) {
    List<String> errorMessage = new ArrayList<>();
    Date startTime = null;
    Date endTime = null;
    try {
        String startTimeString = request.getParameter("startdate") + " " + request.getParameter("startHour")
                + ":" + request.getParameter("startMinute");

        startTime = new SimpleDateFormat("dd-MM-yyyy HH:mm", Locale.ENGLISH).parse(startTimeString);
        session.setStartTime(startTime);
    } catch (Exception e) {
        errorMessage.add("error.startdateinvalid");
    }
    try {
        String endTimeString = request.getParameter("enddate") + " " + request.getParameter("endHour") + ":"
                + request.getParameter("endMinute");

        endTime = new SimpleDateFormat("dd-MM-yyyy HH:mm", Locale.ENGLISH).parse(endTimeString);
        session.setEndTime(endTime);
    } catch (Exception e) {
        errorMessage.add("error.enddateinvalid");
    }
    if (startTime != null && endTime != null) {
        if (endTime.before(startTime)) {
            errorMessage.add("error.startdatebeforeenddate");
        }
        Date now = new Date();
        if (startTime.before(now)) {
            errorMessage.add("error.startdatebeforenow");
        }
        Period sessionPeriod = new Period(new DateTime(startTime), new DateTime(endTime));
        if (sessionPeriod.getYears() > 0) {
            errorMessage.add("error.dateyearapart");
        }
    }

    return errorMessage;
}

From source file:uk.ac.imperial.lsds.seep.infrastructure.monitor.policy.evaluate.PolicyRuleEvaluator.java

License:Open Source License

/**
 * Prune old readings from the queue of readings required to evaluate all the
 * triggers associated to the scaling rule bound to this evaluator.
 * /* w w w  .j a  v a 2s.  c om*/
 * @param maximumAge Maximum age for metric readings in the queue. Any readings
 * which have a timestamp older than this age can be safely discarded as they
 * are no longer needed to evaluate the state of the rule triggers.
 */
private void pruneOldReadings(Period maximumAge) {
    boolean done = false;
    MetricReading reading = pastReadings.peek();

    while ((reading != null) && !done) {
        Period readingAge = new Period(reading.getTimestamp(), Instant.now());

        // Once we find a reading with an age less than the maximum age, we
        // stop prunning as readings in the queue are sorted. An evaluator
        // works based on the assumption that metrics readings are offered 
        // with always increasing timestamps.
        if (readingAge.toStandardSeconds().isLessThan(maximumAge.toStandardSeconds())
                || readingAge.toStandardSeconds().equals(maximumAge.toStandardSeconds())) {
            done = true;
        } else {
            pastReadings.poll();

            // Get the next element in the queue and continue pruning
            reading = pastReadings.peek();
        }
    }
}

From source file:uk.ac.imperial.lsds.seep.infrastructure.monitor.policy.trigger.ActionTrigger.java

License:Open Source License

/**
 * Evaluates the state of the trigger. Both the value and the time threshold
 * need to evaluate to true in order for the trigger state to change from
 * non-fired to fired./*from  www. j  a va2s .c om*/
 * @param readings metric readings to evaluate (all those that are within the
 * time threshold need to evaluate to true in terms of their value).
 */
public void evaluate(List<MetricReading> readings, TimeReference time) {

    logger.info(
            "Evaluating trigger for " + metricName.toString() + " - " + readings.size() + " readings provided");

    logger.debug("value threshold: " + valueThreshold.toString());
    logger.debug("time threshold: " + timeThreshold.toString());

    // Determine the new state of the trigger depending on the result of
    // evaluating boh thresholds. Need to mark flag if state changes.
    ActionTriggerState pastTriggerState = triggerState;

    boolean enoughReadings = true;

    // Check that we have enough readings to cover the entire time threshold
    if ((readings != null) && (readings.size() > 0)) {
        MetricReading mostRecentReading = readings.get(readings.size() - 1);
        MetricReading leastRecentReading = readings.get(0);

        logger.info("Most recent reading [" + mostRecentReading.getTimestamp() + "]");
        logger.info("Least recent reading [" + leastRecentReading.getTimestamp() + "]");

        Period readingsPeriod = new Period(leastRecentReading.getTimestamp(), mostRecentReading.getTimestamp());

        int toleranceSeconds = new Double(0.1 * timeThreshold.toPeriod().toStandardSeconds().getSeconds())
                .intValue();

        if (readingsPeriod.toStandardSeconds()
                .isLessThan(timeThreshold.toPeriod().toStandardSeconds().minus(toleranceSeconds))) {

            logger.info("Not enough readings, only for last period[" + readingsPeriod + "]");
            enoughReadings = false;
        }
    }

    // If we have enough readings, then we evaluate in detail
    if (enoughReadings) {
        int i = 0;
        for (MetricReading r : readings) {
            Period metricPeriod = new Period(r.getTimestamp(), time.now());
            MetricValue metricValue = r.getValues().get(metricName);

            logger.info("Evaluating reading[" + i + "] value[" + metricValue.toString() + "] period["
                    + metricPeriod.toString() + "]");

            // We evaluate the time threshold first, simple optimisation to be
            // able to abort the iteration sooner (readings are guaranteed to be
            // sorted by time of reception, from most recent to least recent).
            if (timeThreshold.evaluate(metricPeriod)) {
                triggerState = valueThreshold.evaluate(metricValue) ? ActionTriggerState.FIRED
                        : ActionTriggerState.NON_FIRED;

                // If there is a reading within the time threshold for which
                // the value evaluates to false (trigger is non-fired), then
                // we can break from the evaluation loop.
                if (triggerState.equals(ActionTriggerState.NON_FIRED)) {
                    break;
                }
            }

            i++;
        }
    }

    stateChanged = (triggerState != pastTriggerState);
    logger.info("New trigger state is [" + triggerState.toString() + "] changed[" + stateChanged + "]");
}

From source file:uk.org.rbc1b.roms.controller.volunteer.ldc.SubmitLDCFormVolunteerEmailGenerator.java

License:Open Source License

/**
 * Generate email for a volunteer with the correct message.
 *
 * @param volunteer the volunteer//from www.  j  a  v a2s . c  o m
 * @return Email object
 * @throws IOException if we can't find the email template
 * @throws TemplateException if Freemarker's had enough
 */
public Email generateEmailForVolunteers(Volunteer volunteer) throws IOException, TemplateException {
    Configuration conf = emailFreemarkerConfigurer.getConfiguration();
    Map<String, Object> model = new HashMap<>();
    model.put("volunteer", volunteer);

    Date date = volunteer.getFormDate();
    if (date == null) {
        model.put("message", SubmitLDCFormEmailMessageConstants.FORM_DATE_UNKNOWN.getMessage());
    } else {
        DateTime formDate = DataConverterUtil.toDateTime(date);
        DateTime todayDate = new DateTime();
        Period period = new Period(formDate, todayDate);

        if ((period.getYears() == 2) && (period.getMonths() >= 6)) {
            model.put("message", SubmitLDCFormEmailMessageConstants.FORM_DATE_TWO_HALF_YRS.getMessage());
        } else if (period.getYears() >= 3) {
            model.put("message", SubmitLDCFormEmailMessageConstants.FORM_DATE_THREE_YRS.getMessage());
        }
    }

    Email email = new Email();
    email.setRecipient(volunteer.getPerson().getEmail());
    email.setSubject(SUBJECT);
    email.setText(FreeMarkerTemplateUtils.processTemplateIntoString(conf.getTemplate(SUBMIT_LDC_FORM_TEMPLATE),
            model));

    return email;
}

From source file:us.repasky.microblog.domain.Post.java

License:Apache License

protected static String getAge(final Date fromDate, final Date createdDate) {
    DateTime now = new DateTime(fromDate);
    DateTime created = new DateTime(createdDate);

    Period period = new Period(created, now);
    String age = "";

    int weeksAgo = period.getWeeks();
    if (weeksAgo == 0) {
        age = PERIOD_FORMATTER.print(period.normalizedStandard());
    } else {//from w  w w .ja v  a2  s  . com
        age = "a long while ago";
    }

    return age;
}

From source file:webservice.CarInsurancePrice.java

private double checkAge(String dateNaissance, DateTime dateJour, double price) {
    DateTimeFormatter dft = DateTimeFormat.forPattern("dd/MM/yyyy");
    DateTime dtNaissance = dft.parseDateTime(dateNaissance);
    Period period = new Period(dtNaissance.getMillis(), dateJour.getMillis());
    int age = period.getYears();
    if (age < JEUNE_AGE) {
        price *= JEUNE_TAUX;//w ww. jav  a2 s.  co m
    }
    return price;
}