Example usage for org.joda.time Years yearsBetween

List of usage examples for org.joda.time Years yearsBetween

Introduction

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

Prototype

public static Years yearsBetween(ReadablePartial start, ReadablePartial end) 

Source Link

Document

Creates a Years representing the number of whole years between the two specified partial datetimes.

Usage

From source file:org.patientview.model.Patient.java

License:Open Source License

public Integer getAge() {
    // Return the difference between now and the date of birth
    if (dateofbirth != null) {
        return Years.yearsBetween(new DateTime(dateofbirth), new DateTime(new Date())).getYears();
    }//from www  . j av  a 2 s  .co  m
    return null;
}

From source file:org.patientview.radar.web.panels.DiagnosisPanel.java

License:Open Source License

public DiagnosisPanel(String id, final IModel<Long> radarNumberModel) {
    super(id);/*  w  w w .j a v  a  2 s.c  o  m*/
    setOutputMarkupId(true);
    setOutputMarkupPlaceholderTag(true);

    // Set up model
    // Set up loadable detachable, working for null radar numbers (new patients) and existing
    final CompoundPropertyModel<Diagnosis> model = new CompoundPropertyModel<Diagnosis>(
            new LoadableDetachableModel<Diagnosis>() {
                @Override
                protected Diagnosis load() {
                    if (radarNumberModel.getObject() != null) {
                        Long radarNumber;
                        try {
                            radarNumber = radarNumberModel.getObject();
                        } catch (ClassCastException e) {
                            Object obj = radarNumberModel.getObject();
                            radarNumber = Long.parseLong((String) obj);
                        }
                        Diagnosis diagnosis = diagnosisManager.getDiagnosisByRadarNumber(radarNumber);
                        if (diagnosis != null) {
                            return diagnosis;
                        } else {
                            return new Diagnosis();
                        }
                    } else {
                        return new Diagnosis();
                    }
                }
            });

    // Clinical presentation A - goes here in the file as referenced in form submit
    final DropDownChoice<ClinicalPresentation> clinicalPresentationA = new ClinicalPresentationDropDownChoice(
            "clinicalPresentationA");
    clinicalPresentationA.setOutputMarkupId(true);
    clinicalPresentationA.setOutputMarkupPlaceholderTag(true);

    final Form<Diagnosis> form = new Form<Diagnosis>("form", model) {
        @Override
        protected void onValidateModelObjects() {
            super.onValidateModelObjects();
            Diagnosis diagnosis = getModelObject();
            ClinicalPresentation presentationA = diagnosis.getClinicalPresentationA();
            ClinicalPresentation presentationB = diagnosis.getClinicalPresentationB();

            // Validate that the two aren't the same
            if (presentationA != null && presentationB != null && presentationA.equals(presentationB)) {
                clinicalPresentationA.error("A and B cannot be the same");
            }
        }

        @Override
        protected void onSubmit() {
            Diagnosis diagnosis = getModelObject();
            Date dateOfDiagnosis = diagnosis.getBiopsyDate();
            Long radarNumber;
            try {
                radarNumber = radarNumberModel.getObject();
            } catch (ClassCastException e) {
                Object obj = radarNumberModel.getObject();
                radarNumber = Long.parseLong((String) obj);
            }

            Patient patient = patientManager.getPatientByRadarNumber(radarNumber);
            Date dob = patient.getDob();
            if (dateOfDiagnosis != null && dob != null) {
                int age = Years.yearsBetween(new DateTime(dob), new DateTime(dateOfDiagnosis)).getYears();
                diagnosis.setAgeAtDiagnosis(age);
            }
            diagnosisManager.saveDiagnosis(diagnosis);

            // additional significant diagnosis needs to carry through to clinical data
            List<ClinicalData> clinicalDataList = clinicalDataManager
                    .getClinicalDataByRadarNumber(diagnosis.getRadarNumber());
            if (clinicalDataList.isEmpty()) {
                ClinicalData clinicalData = new ClinicalData();
                clinicalData.setSequenceNumber(1);
                clinicalData.setRadarNumber(diagnosis.getRadarNumber());
                clinicalDataList.add(clinicalData);
            }

            for (ClinicalData clinicalData : clinicalDataList) {
                clinicalData.setSignificantDiagnosis1(diagnosis.getSignificantDiagnosis1());
                clinicalData.setSignificantDiagnosis2(diagnosis.getSignificantDiagnosis2());
                clinicalDataManager.saveClinicalDate(clinicalData);
            }

        }
    };
    add(form);

    final List<Component> componentsToUpdate = new ArrayList<Component>();

    Label successLabel = RadarComponentFactory.getSuccessMessageLabel("successMessage", form,
            componentsToUpdate);
    Label successLabelDown = RadarComponentFactory.getSuccessMessageLabel("successMessageDown", form,
            componentsToUpdate);

    Label errorLabel = RadarComponentFactory.getErrorMessageLabel("errorMessage", form, componentsToUpdate);
    Label errorLabelDown = RadarComponentFactory.getErrorMessageLabel("errorMessageDown", form,
            componentsToUpdate);

    TextField<Long> radarNumber = new TextField<Long>("radarNumber");
    radarNumber.setEnabled(false);
    form.add(radarNumber);

    TextField hospitalNumber = new TextField("hospitalNumber",
            RadarModelFactory.getHospitalNumberModel(radarNumberModel, patientManager));
    form.add(hospitalNumber);

    TextField firstName = new TextField("firstName",
            RadarModelFactory.getFirstNameModel(radarNumberModel, patientManager));
    form.add(firstName);

    TextField surname = new TextField("surname",
            RadarModelFactory.getSurnameModel(radarNumberModel, patientManager));
    form.add(surname);

    TextField dob = new DateTextField("dateOfBirth",
            RadarModelFactory.getDobModel(radarNumberModel, patientManager), RadarApplication.DATE_PATTERN);
    form.add(dob);

    DropDownChoice<DiagnosisCode> diagnosisCodeDropDownChoice = new DropDownChoice<DiagnosisCode>(
            "diagnosisCode", diagnosisManager.getDiagnosisCodes(),
            new ChoiceRenderer<DiagnosisCode>("abbreviation", "id"));
    diagnosisCodeDropDownChoice.setEnabled(false);
    form.add(diagnosisCodeDropDownChoice);

    form.add(new TextArea("text"));

    form.add(new Label("diagnosisOrBiopsy", new LoadableDetachableModel<Object>() {
        @Override
        protected Object load() {
            Diagnosis diagnosis = model.getObject();
            if (diagnosis.getDiagnosisCode() != null) {
                return diagnosis.getDiagnosisCode().getId().equals(SRNS_ID) ? "diagnosis" : "original biopsy";
            }
            return "";
        }
    }));

    // this field is also used for date of diagnosis
    RadarDateTextField biopsyDate = new RadarDateTextField("biopsyDate", form, componentsToUpdate);

    form.add(biopsyDate);

    RadarDateTextField esrfDate = new RadarDateTextField("esrfDate", form, componentsToUpdate);
    form.add(esrfDate);

    TextField ageAtDiagnosis = new TextField("ageAtDiagnosis");
    ageAtDiagnosis.setOutputMarkupId(true);
    ageAtDiagnosis.setOutputMarkupPlaceholderTag(true);
    form.add(ageAtDiagnosis);
    componentsToUpdate.add(ageAtDiagnosis);
    form.add(new CheckBox("prepubertalAtDiagnosis"));

    final RadarTextFieldWithValidation heightAtDiagnosis = new RadarTextFieldWithValidation("heightAtDiagnosis",
            new RangeValidator<Double>(RadarApplication.MIN_HEIGHT, RadarApplication.MAX_HEIGHT), form,
            componentsToUpdate);
    form.add(heightAtDiagnosis);

    // Clinical presentation B - A is further up the file
    final DropDownChoice<ClinicalPresentation> clinicalPresentationB = new ClinicalPresentationDropDownChoice(
            "clinicalPresentationB");
    clinicalPresentationB.setOutputMarkupId(true);
    clinicalPresentationB.setOutputMarkupPlaceholderTag(true);

    form.add(clinicalPresentationA, clinicalPresentationB);
    form.add(new RadarDateTextField("onsetSymptomsDate", form, componentsToUpdate));

    ComponentFeedbackPanel clinicalPresentationFeedback = new ComponentFeedbackPanel(
            "clinicalPresentationFeedback", clinicalPresentationA);
    clinicalPresentationFeedback.setOutputMarkupId(true);
    clinicalPresentationFeedback.setOutputMarkupPlaceholderTag(true);
    form.add(clinicalPresentationFeedback);

    // Steroid resistance radio groups
    RadioGroup steroidRadioGroup = new RadioGroup("steroidResistance") {
        @Override
        public boolean isVisible() {
            DiagnosisCode diagnosisCode = model.getObject().getDiagnosisCode();
            if (diagnosisCode != null) {
                return diagnosisCode.getId().equals(SRNS_ID);
            } else {
                return false;
            }

        }
    };
    steroidRadioGroup.setRequired(true);
    steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("primarySteroidResistance",
            new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.PRIMARY)));
    steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("secondarySteroidResistance",
            new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.SECONDARY)));
    steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("presumedSteroidResistance",
            new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.PRESUMED)));
    steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("biopsyProven",
            new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.BPS)));
    form.add(steroidRadioGroup);

    // Construct feedback panel
    final ComponentFeedbackPanel steroidFeedbackPanel = new ComponentFeedbackPanel("steroidResistanceFeedback",
            steroidRadioGroup);
    steroidFeedbackPanel.setOutputMarkupPlaceholderTag(true);
    form.add(steroidFeedbackPanel);
    steroidRadioGroup.setOutputMarkupPlaceholderTag(true);
    steroidRadioGroup.add(steroidFeedbackPanel);
    componentsToUpdate.add(steroidFeedbackPanel);

    // Additional significant diagnosis
    form.add(new TextField("significantDiagnosis1"));
    form.add(new TextField("significantDiagnosis2"));

    // Biopsy Diagnosis visibilities
    IModel<String> biopsyLabelModel = new LoadableDetachableModel<String>() {
        @Override
        protected String load() {
            Diagnosis diagnosis = model.getObject();
            if (diagnosis.getDiagnosisCode() != null) {
                if (diagnosis.getDiagnosisCode().getId().equals(SRNS_ID)) {
                    return "Biopsy Diagnosis";
                } else {
                    return "Biopsy Proven Diagnosis";
                }
            } else {
                return "";
            }
        }
    };

    IModel<List> biopsyDiagnosisModel = new LoadableDetachableModel<List>() {
        @Override
        protected List load() {
            Diagnosis diagnosis = model.getObject();
            if (diagnosis.getDiagnosisCode() != null) {
                if (diagnosis.getDiagnosisCode().getId().equals(SRNS_ID)) {
                    return Arrays.asList(Diagnosis.BiopsyDiagnosis.MINIMAL_CHANGE,
                            Diagnosis.BiopsyDiagnosis.FSGS, Diagnosis.BiopsyDiagnosis.MESANGIAL_HYPERTROPHY,
                            Diagnosis.BiopsyDiagnosis.OTHER);
                } else {
                    return Arrays.asList(Diagnosis.BiopsyDiagnosis.YES, Diagnosis.BiopsyDiagnosis.NO);
                }
            }
            return Collections.emptyList();
        }
    };

    DropDownChoice biopsyDiagnosis = new DropDownChoice("biopsyProvenDiagnosis", biopsyDiagnosisModel,
            new ChoiceRenderer("label", "id"));

    Label biopsyDiagnosisLabel = new Label("biopsyDiagnosisLabel", biopsyLabelModel);

    form.add(biopsyDiagnosis, biopsyDiagnosisLabel);

    Diagnosis diagnosis = model.getObject();
    boolean showOtherDetailsOnInit;
    showOtherDetailsOnInit = diagnosis.getMutationYorN9() == Diagnosis.MutationYorN.Y;
    final IModel<Boolean> otherDetailsVisibilityModel = new Model<Boolean>(showOtherDetailsOnInit);

    boolean showMoreDetailsOnInit = false;
    if (diagnosis.getMutationYorN1() == Diagnosis.MutationYorN.Y
            || diagnosis.getMutationYorN2() == Diagnosis.MutationYorN.Y
            || diagnosis.getMutationYorN3() == Diagnosis.MutationYorN.Y
            || diagnosis.getMutationYorN4() == Diagnosis.MutationYorN.Y
            || diagnosis.getMutationYorN5() == Diagnosis.MutationYorN.Y
            || diagnosis.getMutationYorN6() == Diagnosis.MutationYorN.Y
            || diagnosis.getMutationYorN7() == Diagnosis.MutationYorN.Y
            || diagnosis.getMutationYorN8() == Diagnosis.MutationYorN.Y) {

        showMoreDetailsOnInit = true;
    }

    final IModel<Boolean> moreDetailsVisibilityModel = new Model<Boolean>(showMoreDetailsOnInit);

    WebMarkupContainer geneMutationContainer = new WebMarkupContainer("geneMutationContainer") {
        @Override
        public boolean isVisible() {
            Diagnosis diagnosis = model.getObject();
            if (diagnosis.getDiagnosisCode() != null) {
                return diagnosis.getDiagnosisCode().getId().equals(SRNS_ID);
            }
            return false;
        }
    };

    WebMarkupContainer mutationContainer = new WebMarkupContainer("mutationContainer");

    form.add(geneMutationContainer);

    Label geneMutationLabel = new Label("geneMutationLabel", "Gene Mutation");

    geneMutationContainer.add(geneMutationLabel);
    geneMutationContainer.add(mutationContainer);

    // Gene mutations
    mutationContainer
            .add(new DiagnosisGeneMutationPanel("nphs1Container", 1, (CompoundPropertyModel) form.getModel(),
                    otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate));

    mutationContainer
            .add(new DiagnosisGeneMutationPanel("nphs2Container", 2, (CompoundPropertyModel) form.getModel(),
                    otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate));

    mutationContainer
            .add(new DiagnosisGeneMutationPanel("nphs3Container", 3, (CompoundPropertyModel) form.getModel(),
                    otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate));

    mutationContainer
            .add(new DiagnosisGeneMutationPanel("wt1Container", 4, (CompoundPropertyModel) form.getModel(),
                    otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate));

    mutationContainer
            .add(new DiagnosisGeneMutationPanel("cd2apContainer", 5, (CompoundPropertyModel) form.getModel(),
                    otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate));

    mutationContainer
            .add(new DiagnosisGeneMutationPanel("trpc6Container", 6, (CompoundPropertyModel) form.getModel(),
                    otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate));

    mutationContainer
            .add(new DiagnosisGeneMutationPanel("actn4Container", 7, (CompoundPropertyModel) form.getModel(),
                    otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate));

    mutationContainer
            .add(new DiagnosisGeneMutationPanel("lamb2Container", 8, (CompoundPropertyModel) form.getModel(),
                    otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate));

    mutationContainer
            .add(new DiagnosisGeneMutationPanel(OTHER_CONTAINER_ID, 9, (CompoundPropertyModel) form.getModel(),
                    otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate));

    // Other gene mutation container
    MarkupContainer otherGeneMutationContainer = new WebMarkupContainer("otherGeneMutationContainer") {

        @Override
        public boolean isVisible() {
            return otherDetailsVisibilityModel.getObject();
        }
    };

    otherGeneMutationContainer.setOutputMarkupId(true);
    otherGeneMutationContainer.setOutputMarkupPlaceholderTag(true);

    otherGeneMutationContainer.add(new TextArea("otherGeneMutation"));

    geneMutationContainer.add(otherGeneMutationContainer);

    // more details
    MarkupContainer moreDetailsContainer = new WebMarkupContainer("moreDetailsContainer") {

        @Override
        public boolean isVisible() {
            return moreDetailsVisibilityModel.getObject();
        }
    };
    moreDetailsContainer.setOutputMarkupId(true);
    moreDetailsContainer.setOutputMarkupPlaceholderTag(true);
    moreDetailsContainer.add(new TextArea("moreDetails", new Model()));
    geneMutationContainer.add(moreDetailsContainer);
    componentsToUpdate.add(moreDetailsContainer);

    componentsToUpdate.add(otherGeneMutationContainer);

    boolean showKaroTypeOtherOnInit = false;
    if (diagnosis.getKarotype() != null) {
        showKaroTypeOtherOnInit = diagnosis.getKarotype().getId().equals(KAROTYPE_OTHER_ID);
    }
    final IModel<Boolean> karoTypeOtherVisibilityModel = new Model<Boolean>(showKaroTypeOtherOnInit);

    // Add Karotype
    DropDownChoice<Karotype> karotypeDropDownChoice = new DropDownChoice<Karotype>("karotype",
            diagnosisManager.getKarotypes(), new ChoiceRenderer<Karotype>("description", "id"));

    WebMarkupContainer karoTypeContainer = new WebMarkupContainer("karoTypeContainer") {
        @Override
        public boolean isVisible() {
            Diagnosis diagnosis = model.getObject();
            if (diagnosis.getDiagnosisCode() != null) {
                return diagnosis.getDiagnosisCode().getId().equals(SRNS_ID);
            }
            return false;
        }
    };
    karoTypeContainer.add(karotypeDropDownChoice);
    form.add(karoTypeContainer);

    karotypeDropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onChange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            Diagnosis diagnosis = model.getObject();
            Karotype karotype = diagnosis.getKarotype();
            if (karotype != null) {
                karoTypeOtherVisibilityModel.setObject(karotype.getId().equals(KAROTYPE_OTHER_ID));
                ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdate);
            }
        }
    });

    // karotype other
    MarkupContainer karoTypeOtherContainer = new WebMarkupContainer("karoTypeOtherContainer") {
        @Override
        public boolean isVisible() {
            return karoTypeOtherVisibilityModel.getObject();
        }
    };
    karoTypeOtherContainer.setOutputMarkupId(true);
    karoTypeOtherContainer.setOutputMarkupPlaceholderTag(true);
    karoTypeOtherContainer.add(new TextArea("karoTypeOtherText"));
    componentsToUpdate.add(karoTypeOtherContainer);
    form.add(karoTypeOtherContainer);

    // Parental consanguinity and family history
    form.add(new YesNoDropDownChoice("parentalConsanguinity"));

    YesNoDropDownChoice familyHistory = new YesNoDropDownChoice("familyHistory");

    boolean showFamilyOnInit = false;
    showFamilyOnInit = diagnosis.getFamilyHistory() == Diagnosis.YesNo.YES;
    final IModel<Boolean> familyVisibilityModel = new Model<Boolean>(showFamilyOnInit);

    familyHistory.add(new AjaxFormComponentUpdatingBehavior("onChange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            Diagnosis diagnosis = model.getObject();
            if (diagnosis.getFamilyHistory() != null) {
                familyVisibilityModel.setObject(diagnosis.getFamilyHistory() == Diagnosis.YesNo.YES);
            }
            ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdate);
        }
    });

    form.add(familyHistory);
    // Family history containers
    form.add(new DiagnosisRelativePanel("relative1Container", 1, (CompoundPropertyModel) form.getModel(),
            familyVisibilityModel, componentsToUpdate));
    form.add(new DiagnosisRelativePanel("relative2Container", 2, (CompoundPropertyModel) form.getModel(),
            familyVisibilityModel, componentsToUpdate));
    form.add(new DiagnosisRelativePanel("relative3Container", 3, (CompoundPropertyModel) form.getModel(),
            familyVisibilityModel, componentsToUpdate));
    form.add(new DiagnosisRelativePanel("relative4Container", 4, (CompoundPropertyModel) form.getModel(),
            familyVisibilityModel, componentsToUpdate));
    form.add(new DiagnosisRelativePanel("relative5Container", 5, (CompoundPropertyModel) form.getModel(),
            familyVisibilityModel, componentsToUpdate));
    form.add(new DiagnosisRelativePanel("relative6Container", 6, (CompoundPropertyModel) form.getModel(),
            familyVisibilityModel, componentsToUpdate));

    componentsToUpdate.add(clinicalPresentationFeedback);

    Label radarFamilyLabel = new Label("radarFamilyLabel", "RaDaR No") {

        @Override
        public boolean isVisible() {
            return familyVisibilityModel.getObject();
        }
    };
    radarFamilyLabel.setOutputMarkupId(true);
    radarFamilyLabel.setOutputMarkupPlaceholderTag(true);
    componentsToUpdate.add(radarFamilyLabel);
    form.add(radarFamilyLabel);

    DiagnosisAjaxSubmitLink save = new DiagnosisAjaxSubmitLink("save") {
        @Override
        protected List<? extends Component> getComponentsToUpdate() {
            return componentsToUpdate;
        }
    };

    DiagnosisAjaxSubmitLink saveDown = new DiagnosisAjaxSubmitLink("saveDown") {

        @Override
        protected List<? extends Component> getComponentsToUpdate() {
            return componentsToUpdate;
        }
    };

    form.add(save, saveDown);
}

From source file:org.springframework.analytics.metrics.memory.InMemoryAggregateCounter.java

License:Apache License

public AggregateCounter getCounts(Interval interval, AggregateCounterResolution resolution) {
    DateTime start = interval.getStart();
    DateTime end = interval.getEnd();/*from   w  w w . j a va 2 s .  c  o  m*/
    Chronology c = interval.getChronology();

    long[] counts;
    if (resolution == AggregateCounterResolution.minute) {
        List<long[]> days = accumulateDayCounts(minuteCountsByDay, start, end, 60 * 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getMinuteOfDay(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);
    } else if (resolution == AggregateCounterResolution.hour) {
        List<long[]> days = accumulateDayCounts(hourCountsByDay, start, end, 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);
    } else if (resolution == AggregateCounterResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(start.getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearDays = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] dayCounts = dayCountsByYear.get(cursor.getYear());
            if (dayCounts == null) {
                // Querying where we have no data
                dayCounts = new long[daysInYear(cursor.getYear())];
            }
            yearDays.add(dayCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearDays, startDay.getDayOfYear() - 1, nDays);

    } else if (resolution == AggregateCounterResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearMonths = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] monthCounts = monthCountsByYear.get(cursor.getYear());
            if (monthCounts == null) {
                monthCounts = new long[12];
            }
            yearMonths.add(monthCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearMonths, startMonth.getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCounterResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            long[] monthCounts = monthCountsByYear.get(startYear.plusYears(i).getYear());
            counts[i] = MetricUtils.sum(monthCounts);
        }

    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCounter(this.name, interval, counts, resolution);
}

From source file:org.springframework.analytics.metrics.redis.RedisAggregateCounterRepository.java

License:Apache License

/**
 * For each query, we need to convert the interval into two variations. One is the start and end points rounded to
 * the resolution (used to calculate the number of entries to be returned from the query). The second is the start
 * and end buckets we have to retrieve which may contain entries for the interval. For example, when querying
 * at day resolution, the number of entries is the number of Joda time days between the start (rounded down to a
 * day boundary) and the end plus one day (also rounded down). However, we need load the data from the buckets
 * from the month the start day occurs in to the month end day occurs in. These are then concatenated, using the
 * start day as the start index into the first array, and writing the total number of entries in sequence from that
 * point into the combined result counts array.
 *//*from w w  w .  jav a2  s  .  com*/
@Override
public AggregateCounter getCounts(String name, Interval interval, AggregateCounterResolution resolution) {

    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();

    long[] counts;

    if (resolution == AggregateCounterResolution.minute) {
        // Iterate through each hour in the interval and load the minutes for it
        MutableDateTime dt = new MutableDateTime(interval.getStart());
        dt.setRounding(c.hourOfDay());
        Duration step = Duration.standardHours(1);
        List<long[]> hours = new ArrayList<long[]>();
        while (dt.isBefore(end) || dt.isEqual(end)) {
            hours.add(getMinCountsForHour(name, dt));
            dt.add(step);
        }
        counts = MetricUtils.concatArrays(hours, interval.getStart().getMinuteOfHour(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);

    } else if (resolution == AggregateCounterResolution.hour) {
        DateTime cursor = new DateTime(c.dayOfMonth().roundFloor(interval.getStart().getMillis()));
        List<long[]> days = new ArrayList<long[]>();
        Duration step = Duration.standardHours(24);
        while (cursor.isBefore(end)) {
            days.add(getHourCountsForDay(name, cursor));
            cursor = cursor.plus(step);
        }

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);

    } else if (resolution == AggregateCounterResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(interval.getStart().getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.monthOfYear().roundFloor(interval.getStart().getMillis()));
        List<long[]> months = new ArrayList<long[]>();
        DateTime endMonth = new DateTime(
                c.monthOfYear().roundCeiling(interval.getEnd().plusMonths(1).getMillis()));
        while (cursor.isBefore(endMonth)) {
            months.add(getDayCountsForMonth(name, cursor));
            cursor = cursor.plusMonths(1);
        }

        counts = MetricUtils.concatArrays(months, interval.getStart().getDayOfMonth() - 1, nDays);
    } else if (resolution == AggregateCounterResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> years = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(interval.getEnd().plusYears(1).getMillis()));
        while (cursor.isBefore(endYear)) {
            years.add(getMonthCountsForYear(name, cursor));
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(years, interval.getStart().getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCounterResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        Map<String, Long> yearCounts = getYearCounts(name);
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            int year = startYear.plusYears(i).getYear();
            Long count = yearCounts.get(Integer.toString(year));
            if (count == null) {
                count = 0L;
            }
            counts[i] = count;
        }
    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCounter(name, interval, counts, resolution);
}

From source file:org.springframework.xd.analytics.metrics.memory.InMemoryAggregateCounter.java

License:Apache License

public AggregateCount getCounts(Interval interval, AggregateCountResolution resolution) {
    DateTime start = interval.getStart();
    DateTime end = interval.getEnd();// w w w .  j a v a 2  s. co  m
    Chronology c = interval.getChronology();

    long[] counts;
    if (resolution == AggregateCountResolution.minute) {
        List<long[]> days = accumulateDayCounts(minuteCountsByDay, start, end, 60 * 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getMinuteOfDay(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);
    } else if (resolution == AggregateCountResolution.hour) {
        List<long[]> days = accumulateDayCounts(hourCountsByDay, start, end, 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);
    } else if (resolution == AggregateCountResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(start.getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearDays = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] dayCounts = dayCountsByYear.get(cursor.getYear());
            if (dayCounts == null) {
                // Querying where we have no data
                dayCounts = new long[daysInYear(cursor.getYear())];
            }
            yearDays.add(dayCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearDays, startDay.getDayOfYear() - 1, nDays);

    } else if (resolution == AggregateCountResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearMonths = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] monthCounts = monthCountsByYear.get(cursor.getYear());
            if (monthCounts == null) {
                monthCounts = new long[12];
            }
            yearMonths.add(monthCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearMonths, startMonth.getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCountResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            long[] monthCounts = monthCountsByYear.get(startYear.plusYears(i).getYear());
            counts[i] = MetricUtils.sum(monthCounts);
        }

    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCount(getName(), interval, counts, resolution);
}

From source file:org.springframework.xd.analytics.metrics.redis.RedisAggregateCounterRepository.java

License:Apache License

/**
 * For each query, we need to convert the interval into two variations. One is the start and end points rounded to
 * the resolution (used to calculate the number of entries to be returned from the query). The second is the start
 * and end buckets we have to retrieve which may contain entries for the interval. For example, when querying
 * at day resolution, the number of entries is the number of Joda time days between the start (rounded down to a
 * day boundary) and the end plus one day (also rounded down). However, we need load the data from the buckets
 * from the month the start day occurs in to the month end day occurs in. These are then concatenated, using the
 * start day as the start index into the first array, and writing the total number of entries in sequence from that
 * point into the combined result counts array.
 *///from  w  w  w. j ava2  s  .com
@Override
public AggregateCount getCounts(String name, Interval interval, AggregateCountResolution resolution) {

    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();

    long[] counts;

    if (resolution == AggregateCountResolution.minute) {
        // Iterate through each hour in the interval and load the minutes for it
        MutableDateTime dt = new MutableDateTime(interval.getStart());
        dt.setRounding(c.hourOfDay());
        Duration step = Duration.standardHours(1);
        List<long[]> hours = new ArrayList<long[]>();
        while (dt.isBefore(end) || dt.isEqual(end)) {
            hours.add(getMinCountsForHour(name, dt));
            dt.add(step);
        }
        counts = MetricUtils.concatArrays(hours, interval.getStart().getMinuteOfHour(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);

    } else if (resolution == AggregateCountResolution.hour) {
        DateTime cursor = new DateTime(c.dayOfMonth().roundFloor(interval.getStart().getMillis()));
        List<long[]> days = new ArrayList<long[]>();
        Duration step = Duration.standardHours(24);
        while (cursor.isBefore(end)) {
            days.add(getHourCountsForDay(name, cursor));
            cursor = cursor.plus(step);
        }

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);

    } else if (resolution == AggregateCountResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(interval.getStart().getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.monthOfYear().roundFloor(interval.getStart().getMillis()));
        List<long[]> months = new ArrayList<long[]>();
        DateTime endMonth = new DateTime(
                c.monthOfYear().roundCeiling(interval.getEnd().plusMonths(1).getMillis()));
        while (cursor.isBefore(endMonth)) {
            months.add(getDayCountsForMonth(name, cursor));
            cursor = cursor.plusMonths(1);
        }

        counts = MetricUtils.concatArrays(months, interval.getStart().getDayOfMonth() - 1, nDays);
    } else if (resolution == AggregateCountResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> years = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(interval.getEnd().plusYears(1).getMillis()));
        while (cursor.isBefore(endYear)) {
            years.add(getMonthCountsForYear(name, cursor));
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(years, interval.getStart().getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCountResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        Map<String, Long> yearCounts = getYearCounts(name);
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            int year = startYear.plusYears(i).getYear();
            Long count = yearCounts.get(Integer.toString(year));
            if (count == null) {
                count = 0L;
            }
            counts[i] = count;
        }
    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCount(name, interval, counts, resolution);
}

From source file:PersonClass.Person.java

public int getAge() {
    LocalDate Date1 = LocalDate.parse(DOB, DateTimeFormat.forPattern("dd/MM/yyyy"));
    LocalDate now = new LocalDate();
    Years Age_1 = Years.yearsBetween(Date1, now);
    Age = Age_1.getYears();/*from www .  j a va2s  .  co  m*/
    return Age;
}

From source file:pl.kodujdlapolski.na4lapy.service.user.UserServiceImpl.java

License:Apache License

@Override
public int getPreferencesComplianceLevel(Animal animal) {
    if (mUserPreferences == null) {
        return 0;
    }//from ww  w  .ja va 2  s .  c  o m

    int result = 0;

    if ((mUserPreferences.isTypeDog() && Species.DOG.equals(animal.getSpecies()))
            || (mUserPreferences.isTypeCat() && Species.CAT.equals(animal.getSpecies()))
            || (mUserPreferences.isTypeOther() && Species.OTHER.equals(animal.getSpecies()))) {
        ++result;
    } else {
        return 0;
    }

    if ((mUserPreferences.isGenderMan() && mUserPreferences.isGenderWoman()
            && Gender.UNKNOWN.equals(animal.getGender()))
            || (mUserPreferences.isGenderMan() && Gender.MALE.equals(animal.getGender()))
            || (mUserPreferences.isGenderWoman() && Gender.FEMALE.equals(animal.getGender()))) {
        ++result;
    }

    if (animal.getBirthDate() != null) {
        int age = Years.yearsBetween(animal.getBirthDate(), LocalDate.now()).getYears();
        if (age >= mUserPreferences.getAgeMin() && age <= mUserPreferences.getAgeMax()) {
            ++result;
        }
    }

    if ((mUserPreferences.isSizeSmall() && mUserPreferences.isSizeMedium() && mUserPreferences.isSizeLarge()
            && Size.UNKNOWN.equals(animal.getSize()))
            || (mUserPreferences.isSizeSmall() && Size.SMALL.equals(animal.getSize()))
            || (mUserPreferences.isSizeMedium() && Size.MEDIUM.equals(animal.getSize()))
            || (mUserPreferences.isSizeLarge() && Size.LARGE.equals(animal.getSize()))) {
        ++result;
    }

    if ((mUserPreferences.isActivityLow() && mUserPreferences.isActivityHigh()
            && ActivityAnimal.UNKNOWN.equals(animal.getActivity()))
            || (mUserPreferences.isActivityLow() && ActivityAnimal.LOW.equals(animal.getActivity()))
            || (mUserPreferences.isActivityHigh() && ActivityAnimal.HIGH.equals(animal.getActivity()))) {
        ++result;
    }

    return result;
}

From source file:pl.kodujdlapolski.na4lapy.ui.details.ContentDetailsView.java

License:Apache License

private String getShortDateTextFrom(@NonNull LocalDate date) {
    int age = Years.yearsBetween(date, LocalDate.now()).getYears();
    int fromStringRes = R.plurals.years_from;
    if (age == 0) {
        age = Months.monthsBetween(date, LocalDate.now()).getMonths();
        fromStringRes = R.plurals.months_from;
    }//  w  ww. ja  v  a  2  s . c  om
    return ctx.getResources().getQuantityString(fromStringRes, age, age);
}

From source file:pl.kodujdlapolski.na4lapy.ui.details.DetailsActivity.java

License:Apache License

public static String getAgeTextShort(Context context, @NonNull LocalDate date) {
    int age = Years.yearsBetween(date, LocalDate.now()).getYears();
    int fromStringRes = R.plurals.years_short;
    if (age == 0) {
        age = Months.monthsBetween(date, LocalDate.now()).getMonths();
        fromStringRes = R.plurals.months_short;
    }// w w w. j  av a  2  s  .co m
    return context.getResources().getQuantityString(fromStringRes, age, age);
}