Example usage for org.joda.time DateTime getYear

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

Introduction

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

Prototype

public int getYear() 

Source Link

Document

Get the year field value.

Usage

From source file:net.sourceforge.fenixedu.util.renderer.GanttDiagram.java

License:Open Source License

private void generateYearsViewMonthsViewAndDays() {

    DateTime firstMonthDateTime = getFirstInstant();
    DateTime lastMontDateTime = getLastInstant();

    if (firstMonthDateTime != null && lastMontDateTime != null) {
        while ((firstMonthDateTime.getYear() < lastMontDateTime.getYear())
                || (firstMonthDateTime.getYear() == lastMontDateTime.getYear()
                        && firstMonthDateTime.getDayOfYear() <= lastMontDateTime.getDayOfYear())) {

            getDays().add(firstMonthDateTime);

            YearMonthDay day = firstMonthDateTime.toYearMonthDay().withDayOfMonth(1);
            if (getMonthsView().containsKey(day)) {
                getMonthsView().put(day, getMonthsView().get(day) + 1);
            } else {
                getMonthsView().put(day, 1);
            }/*from w  w  w.  ja va  2 s. co m*/

            if (getYearsView().containsKey(Integer.valueOf(firstMonthDateTime.getYear()))) {
                getYearsView().put(Integer.valueOf(firstMonthDateTime.getYear()),
                        getYearsView().get(Integer.valueOf(firstMonthDateTime.getYear())) + 1);
            } else {
                getYearsView().put(Integer.valueOf(firstMonthDateTime.getYear()), 1);
            }

            firstMonthDateTime = firstMonthDateTime.plusDays(1);
        }
    }
}

From source file:net.sourceforge.fenixedu.util.renderer.GanttDiagram.java

License:Open Source License

private void generateYearsViewAndMonths() {

    DateTime firstMonthDateTime = getFirstInstant();
    DateTime lastMontDateTime = getLastInstant();

    if (firstMonthDateTime != null && lastMontDateTime != null) {
        while ((firstMonthDateTime.getYear() < lastMontDateTime.getYear())
                || (firstMonthDateTime.getYear() == lastMontDateTime.getYear()
                        && firstMonthDateTime.getMonthOfYear() <= lastMontDateTime.getMonthOfYear())) {

            getMonths().add(firstMonthDateTime);

            if (getYearsView().containsKey(Integer.valueOf(firstMonthDateTime.getYear()))) {
                getYearsView().put(Integer.valueOf(firstMonthDateTime.getYear()),
                        getYearsView().get(Integer.valueOf(firstMonthDateTime.getYear())) + 1);
            } else {
                getYearsView().put(Integer.valueOf(firstMonthDateTime.getYear()), 1);
            }// ww  w .  j a  va 2 s  . co  m

            firstMonthDateTime = firstMonthDateTime.plusMonths(1);
        }
    }
}

From source file:net.tourbook.chart.ChartComponents.java

License:Open Source License

private void createDrawingData_X_History(final GraphDrawingData graphDrawingData,
        final double graphDefaultUnitD) {

    final ChartDataXSerie xData = graphDrawingData.getXData();
    final double scaleX = graphDrawingData.getScaleX();

    final long graphMaxValue = (long) xData.getOriginalMaxValue();
    final long graphDefaultUnit = (long) graphDefaultUnitD;

    // get start time without mills
    final DateTime tourStartTime = xData.getStartDateTime().minus(xData.getStartDateTime().getMillisOfSecond());
    final DateTime tourEndTime = tourStartTime.plus(graphMaxValue * 1000);

    long unitStart = tourStartTime.getMillis();
    long unitEnd = graphMaxValue;
    long firstUnitYear = tourStartTime.getYear();
    long lastUnitYear = tourEndTime.getYear();

    long roundedYearUnit = 0;
    long majorRoundedYearUnit = 0;
    final double dev1Year = scaleX * YEAR_IN_SECONDS;
    final double dev1Month = scaleX * MONTH_IN_SECONDS;

    //      System.out.println(UI.timeStampNano() + " \t");
    //      System.out.println(UI.timeStampNano() + " createDrawingData_X_History\t" + " start: " + tourStartTime);
    //      // TODO remove SYSTEM.OUT.PRINTLN

    final double devTitleVisibleUnit = _devAllMonthLabelWidth * 1.2;

    final boolean isYearRounded = dev1Year < _devYearLabelWidth * 4;
    if (isYearRounded) {

        /*/*w  w w  .  j a v a 2 s .co  m*/
         * adjust years to the rounded values
         */

        final double unitYears = (double) graphDefaultUnit / YEAR_IN_SECONDS;

        roundedYearUnit = Util.roundSimpleNumberUnits((long) unitYears);
        majorRoundedYearUnit = Util.getMajorSimpleNumberValue(roundedYearUnit);

        final long firstHistoryYear = tourStartTime.getYear();

        // decrease min value when it does not fit to unit borders
        final long yearMinRemainder = firstHistoryYear % roundedYearUnit;
        final long yearMinValue = firstHistoryYear - yearMinRemainder;

        final long yearMaxValue = lastUnitYear - (lastUnitYear % roundedYearUnit) + roundedYearUnit;

        unitStart = new DateTime((int) yearMinValue, 1, 1, 0, 0, 0, 0).getMillis();
        unitEnd = new DateTime((int) yearMaxValue, 12, 31, 23, 59, 59, 999).getMillis();
        firstUnitYear = yearMinValue;
        lastUnitYear = yearMaxValue;
    }

    /*
     * check if history units must be created, this is done only once for a tour to optimize it
     */
    if (unitStart != _historyUnitStart || unitEnd != _historyUnitDuration) {

        _historyUnitStart = unitStart;
        _historyUnitDuration = unitEnd;

        createHistoryUnits((int) firstUnitYear, (int) lastUnitYear);
    }

    graphDrawingData.setXUnitTextPos(GraphDrawingData.X_UNIT_TEXT_POS_CENTER);
    graphDrawingData.setIsXUnitOverlapChecked(true);
    graphDrawingData.setIsCheckUnitBorderOverlap(false);

    final HistoryTitle historyTitle = new HistoryTitle();
    xData.setHistoryTitle(historyTitle);

    // hide default unit
    xData.setUnitLabel(UI.EMPTY_STRING);

    final double devGraphXOffset = componentGraph.getXXDevViewPortLeftBorder();
    final int devVisibleWidth = getDevVisibleChartWidth();

    final long graphLeftBorder = (long) (devGraphXOffset / scaleX);
    final long graphRightBorder = (long) ((devGraphXOffset + devVisibleWidth) / scaleX);

    final ArrayList<ChartUnit> xUnits = graphDrawingData.getXUnits();
    final ArrayList<ChartUnit> xUnitTitles = new ArrayList<ChartUnit>();

    final ArrayList<Long> titleValueStart = historyTitle.graphStart = new ArrayList<Long>();
    final ArrayList<Long> titleValueEnd = historyTitle.graphEnd = new ArrayList<Long>();
    final ArrayList<String> titleText = historyTitle.titleText = new ArrayList<String>();

    final boolean isTimeSerieWithTimeZoneAdjustment = xData.isTimeSerieWithTimeZoneAdjustment();

    //      DateTime graphTime = tourStartTime.plus(graphLeftBorder * 1000);
    //      if (isTimeSerieWithTimeZoneAdjustment) {
    //         if (graphTime.getMillis() > UI.beforeCET) {
    //            graphTime = graphTime.minus(UI.BERLIN_HISTORY_ADJUSTMENT * 1000);
    //         }
    //      }
    //
    ////      final int graphSecondsOfDay = graphTime.getSecondOfDay();
    ////      final DateTime graphNextDay = graphTime.plus((DAY_IN_SECONDS - graphSecondsOfDay) * 1000);
    //
    //      System.out.println(UI.timeStampNano());
    //      System.out.println(UI.timeStampNano() + " tourStartTime " + tourStartTime);
    //      System.out.println(UI.timeStampNano() + " graphTime     " + graphTime);
    ////      System.out.println(UI.timeStampNano() + " graphNextDay  " + graphNextDay);
    //      System.out.println(UI.timeStampNano());
    //      // TODO remove SYSTEM.OUT.PRINTLN

    if (isYearRounded) {

        /*
         * create units for rounded years
         */

        //         System.out.println(UI.timeStampNano() + "\trounded years\t");
        //         // TODO remove SYSTEM.OUT.PRINTLN

        graphDrawingData.setXUnitTextPos(GraphDrawingData.X_UNIT_TEXT_POS_LEFT);

        int historyYearIndex = 0;

        /*
         * start unit at the first day of the first year at 0:00:00, this is necessary that the
         * unit is positioned exactly
         */
        final int startDOY = tourStartTime.getDayOfYear();
        final int startDaySeconds = tourStartTime.secondOfDay().get();

        final int startYear = tourStartTime.getYear();

        int yearIndex = 0;
        long graphYearOffset = 0;
        while (startYear > _historyYears[yearIndex]) {
            graphYearOffset += _historyDOY[yearIndex++] * DAY_IN_SECONDS;
        }

        long graphValue = -startDOY * DAY_IN_SECONDS - startDaySeconds - graphYearOffset;

        // loop: years
        while (graphValue <= graphMaxValue) {

            long graphUnit = 0;

            for (int unitIndex = 0; unitIndex < roundedYearUnit; unitIndex++) {

                final int unitYearIndex = historyYearIndex + unitIndex;

                // graph unit = rounded years
                graphUnit += _historyDOY[unitYearIndex] * DAY_IN_SECONDS;
            }

            if (graphValue < graphLeftBorder - graphUnit //
            //
            // ensure it's 366 days
                    - DAY_IN_SECONDS) {

                // advance to the next unit
                graphValue += graphUnit;
                historyYearIndex += roundedYearUnit;

                continue;
            }

            if (graphValue > graphRightBorder) {
                break;
            }

            /*
             * draw year tick
             */
            final int yearValue = _historyYears[historyYearIndex];

            final boolean isMajorValue = yearValue % majorRoundedYearUnit == 0;

            xUnits.add(new ChartUnit(graphValue + DAY_IN_SECONDS, UI.EMPTY_STRING, isMajorValue));

            /*
             * draw title
             */
            titleValueStart.add(graphValue);
            titleValueEnd.add(graphValue + graphUnit - 1);
            titleText.add(Integer.toString(yearValue));

            // advance to the next rounded unit
            graphValue += graphUnit;
            historyYearIndex += roundedYearUnit;
        }

    } else if (dev1Year < _devAllMonthLabelWidth * 12) {

        /*
         * create units for year/month
         */

        //         System.out.println(UI.timeStampNano() + "\tyear/month\t");
        //         // TODO remove SYSTEM.OUT.PRINTLN

        graphDrawingData.setTitleTextPos(GraphDrawingData.X_UNIT_TEXT_POS_CENTER);
        graphDrawingData.setXUnitTextPos(GraphDrawingData.X_UNIT_TEXT_POS_CENTER);

        int historyYearIndex = 0;

        // start unit at the first day of the first year at 0:00:00
        final int startDOY = tourStartTime.getDayOfYear();
        final int startSeconds = tourStartTime.secondOfDay().get();
        long graphValue = -startDOY * DAY_IN_SECONDS - startSeconds;

        // loop: years
        while (graphValue <= graphMaxValue) {

            // graph unit = 1 year
            final long graphUnit = _historyDOY[historyYearIndex] * DAY_IN_SECONDS;

            if (graphValue < graphLeftBorder - graphUnit //
            //
            // ensure it's 366 days
                    - DAY_IN_SECONDS) {

                // advance to the next unit
                graphValue += graphUnit;
                historyYearIndex++;

                continue;
            }

            if (graphValue > graphRightBorder) {
                break;
            }

            final int devUnitWidth = (int) (scaleX * graphUnit);
            final int[] historyMonthDays = _historyMonths[historyYearIndex];

            /*
             * draw year tick
             */
            xUnits.add(new ChartUnit(graphValue + DAY_IN_SECONDS, UI.EMPTY_STRING, true));

            /*
             * draw year title
             */
            {
                final String yearLabel = Integer.toString(_historyYears[historyYearIndex]);

                /*
                 * get number of repeated year labels within a year unit
                 */
                int repeatedMonths = 1;

                while (true) {
                    if (devUnitWidth / repeatedMonths < devTitleVisibleUnit) {
                        break;
                    }
                    repeatedMonths++;
                }

                // ensure array size is big enough (*2)
                final int[] monthStarts = new int[repeatedMonths * 2];
                final int[] monthEnds = new int[repeatedMonths * 2];
                final int monthRepeats = 12 / repeatedMonths;

                int yearMonthDOY = 0;
                int repeatIndex = 0;

                for (int monthIndex = 0; monthIndex < 12; monthIndex++) {

                    final int monthDays = historyMonthDays[monthIndex];

                    if (monthIndex % monthRepeats == 0) {

                        if (repeatIndex > 0) {
                            monthEnds[repeatIndex - 1] = yearMonthDOY;
                        }

                        monthStarts[repeatIndex] = yearMonthDOY;

                        repeatIndex++;
                    }

                    yearMonthDOY += monthDays;
                }
                monthEnds[repeatIndex - 1] = yearMonthDOY;

                for (int repeatIndex2 = 0; repeatIndex2 < monthStarts.length; repeatIndex2++) {

                    final int monthStart = monthStarts[repeatIndex2];
                    final int monthEnd = monthEnds[repeatIndex2];

                    // skip invalid entries
                    if (monthStart == 0 && monthEnd == 0) {
                        break;
                    }

                    titleValueStart.add(graphValue + monthStart * DAY_IN_SECONDS + DAY_IN_SECONDS);
                    titleValueEnd.add(graphValue + monthEnd * DAY_IN_SECONDS + DAY_IN_SECONDS);

                    titleText.add(yearLabel);
                }
            }

            /*
             * draw x-axis units
             */

            if (devUnitWidth >= _devAllMonthLabelWidth * 1.2) {

                createHistoryMonthUnits_Months(xUnits, historyMonthDays, graphValue, 1, 12, true);

            } else if (devUnitWidth >= _devAllMonthLabelWidth * 1) {

                createHistoryMonthUnits_Months(xUnits, historyMonthDays, graphValue, 3, 0, false);

            } else if (devUnitWidth >= _devAllMonthLabelWidth * 0.7) {

                createHistoryMonthUnits_Months(xUnits, historyMonthDays, graphValue, 6, 0, false);
            }

            // advance to the next unit
            graphValue += graphUnit;
            historyYearIndex++;
        }

    } else if (dev1Month < _devAllMonthLabelWidth * 30) {

        /*
         * create units for month/day
         */

        //         System.out.println(UI.timeStampNano() + "\tmonth/day");
        //         // TODO remove SYSTEM.OUT.PRINTLN

        graphDrawingData.setTitleTextPos(GraphDrawingData.X_UNIT_TEXT_POS_CENTER);

        int historyYearIndex = 0;

        // start unit at the first day of the first year at 0:00:00
        final int startDOY = tourStartTime.getDayOfYear();
        final int startSeconds = tourStartTime.secondOfDay().get();
        long graphValue = -startDOY * DAY_IN_SECONDS - startSeconds;

        monthLoop:

        // loop: months
        while (graphValue <= graphMaxValue) {

            final int[] yearMonths = _historyMonths[historyYearIndex];

            for (int monthIndex = 0; monthIndex < yearMonths.length; monthIndex++) {

                final int monthDays = yearMonths[monthIndex];

                // graph unit = 1 month
                final long graphUnit = monthDays * DAY_IN_SECONDS;

                if (graphValue < graphLeftBorder - graphUnit) {

                    // advance to the next month unit
                    graphValue += graphUnit;

                    continue;
                }

                if (graphValue > graphRightBorder) {
                    break monthLoop;
                }

                /*
                 * draw month tick
                 */
                xUnits.add(new ChartUnit(graphValue + DAY_IN_SECONDS, UI.EMPTY_STRING, true));

                /*
                 * create title units
                 */
                {
                    final String monthTitle = _monthLabels[monthIndex] + UI.SPACE2
                            + Integer.toString(_historyYears[historyYearIndex]);

                    // get number of repeated labels within one graph unit
                    int repeatedDays = 1;
                    final int devUnitWidth = (int) (scaleX * graphUnit);

                    while (true) {
                        if (devUnitWidth / repeatedDays < devTitleVisibleUnit) {
                            break;
                        }
                        repeatedDays++;
                    }

                    // ensure array size is big enough (*2)
                    final int[] dayStarts = new int[repeatedDays * 2];
                    final int[] dayEnds = new int[repeatedDays * 2];
                    final int repeatedDayUnit = monthDays / repeatedDays;

                    int dayStartEnd = 0;
                    int repeatIndex = 0;

                    for (int dayIndex = 0; dayIndex < monthDays; dayIndex++) {

                        if (dayIndex % repeatedDayUnit == 0) {

                            if (repeatIndex > 0) {
                                dayEnds[repeatIndex - 1] = dayStartEnd;
                            }

                            dayStarts[repeatIndex] = dayStartEnd;

                            repeatIndex++;
                        }

                        dayStartEnd += 1;
                    }
                    dayEnds[repeatIndex - 1] = dayStartEnd;

                    for (int repeatIndex2 = 0; repeatIndex2 < dayStarts.length; repeatIndex2++) {

                        final int dayStart = dayStarts[repeatIndex2];
                        final int dayEnd = dayEnds[repeatIndex2];

                        // skip invalid entries
                        if (dayStart == 0 && dayEnd == 0) {
                            break;
                        }

                        titleValueStart.add(graphValue + dayStart * DAY_IN_SECONDS + DAY_IN_SECONDS);
                        titleValueEnd.add(graphValue + dayEnd * DAY_IN_SECONDS + DAY_IN_SECONDS);
                        titleText.add(monthTitle);
                    }
                }

                /*
                 * draw x-axis units: day number in month
                 */
                final double unitDays = (double) graphDefaultUnit / DAY_IN_SECONDS;

                final int roundedDayUnit = Util.roundSimpleNumberUnits((long) unitDays);

                if (roundedDayUnit == 1) {
                    graphDrawingData.setXUnitTextPos(GraphDrawingData.X_UNIT_TEXT_POS_CENTER);
                } else {
                    graphDrawingData.setXUnitTextPos(GraphDrawingData.X_UNIT_TEXT_POS_LEFT);
                }

                int dayNo = roundedDayUnit;
                while (dayNo <= monthDays) {

                    xUnits.add(new ChartUnit(//
                            graphValue + (dayNo * DAY_IN_SECONDS), Integer.toString(dayNo), false));

                    dayNo += roundedDayUnit;
                }

                // advance to the next month unit
                graphValue += graphUnit;
            }

            historyYearIndex++;
        }

    } else {

        /*
         * create units for day/seconds
         */

        //         System.out.println(UI.timeStampNano() + " day/seconds");
        //         // TODO remove SYSTEM.OUT.PRINTLN

        graphDrawingData.setTitleTextPos(GraphDrawingData.X_UNIT_TEXT_POS_CENTER);
        graphDrawingData.setXUnitTextPos(GraphDrawingData.X_UNIT_TEXT_POS_LEFT);

        final long graphUnit = Util.roundTime24h(graphDefaultUnit);
        final long majorUnit = Util.getMajorTimeValue24(graphUnit);

        final int startSeconds = tourStartTime.secondOfDay().get();
        final long startUnitOffset = startSeconds % graphUnit;

        // decrease min value when it does not fit to unit borders, !!! VERY IMPORTANT !!!
        final long graphValueStart = graphLeftBorder - graphLeftBorder % graphUnit;

        final long graphMaxVisibleValue = graphRightBorder + graphUnit;
        long graphValue = graphValueStart;

        /*
         * create x-axis units
         */
        while (graphValue <= graphMaxVisibleValue) {

            // create unit value/label
            final long unitValueAdjusted = graphValue - startUnitOffset;
            final long unitValueStart = unitValueAdjusted + startSeconds;

            final long unitValue = unitValueStart % DAY_IN_SECONDS;

            final String unitLabel = net.tourbook.chart.Util.format_hh_mm_ss_Optional(unitValue);

            final boolean isMajorValue = unitValue % majorUnit == 0;

            xUnits.add(new ChartUnit(unitValueAdjusted, unitLabel, isMajorValue));

            graphValue += graphUnit;
        }

        /*
         * create dummy units before and after the real units that the title is displayed also
         * at the border, title is displayed between major units
         */
        final int numberOfSmallUnits = (int) (majorUnit / graphUnit);
        long titleUnitStart = (long) xUnits.get(0).value;

        for (int unitIndex = numberOfSmallUnits; unitIndex > 0; unitIndex--) {

            final long unitValueAdjusted = titleUnitStart - (graphUnit * unitIndex);

            final long unitValue = (unitValueAdjusted + startSeconds) % DAY_IN_SECONDS;
            final boolean isMajorValue = unitValue % majorUnit == 0;

            final String unitLabel = net.tourbook.chart.Util.format_hh_mm_ss_Optional(unitValue);

            xUnitTitles.add(new ChartUnit(unitValueAdjusted, unitLabel, isMajorValue));
        }

        xUnitTitles.addAll(xUnits);

        titleUnitStart = (long) xUnitTitles.get(xUnitTitles.size() - 1).value;

        for (int unitIndex = 1; unitIndex < numberOfSmallUnits * 1; unitIndex++) {

            final long unitValueAdjusted = titleUnitStart + (graphUnit * unitIndex);

            final long unitValue = (unitValueAdjusted + startSeconds) % DAY_IN_SECONDS;
            final boolean isMajorValue = unitValue % majorUnit == 0;

            final String unitLabel = net.tourbook.chart.Util.format_hh_mm_ss_Optional(unitValue);

            xUnitTitles.add(new ChartUnit(unitValueAdjusted, unitLabel, isMajorValue));
        }

        /*
         * create title units
         */
        long prevGraphUnitValue = Long.MIN_VALUE;

        for (int unitIndex = 0; unitIndex < xUnitTitles.size(); unitIndex++) {

            final ChartUnit chartUnit = xUnitTitles.get(unitIndex);
            if (chartUnit.isMajorValue) {

                final long currentGraphUnitValue = (long) chartUnit.value;

                if (prevGraphUnitValue != Long.MIN_VALUE) {

                    titleValueStart.add(prevGraphUnitValue);
                    titleValueEnd.add(currentGraphUnitValue - 1);

                    long graphDay = tourStartTime.getMillis() + prevGraphUnitValue * 1000;

                    if (isTimeSerieWithTimeZoneAdjustment) {

                        if (graphDay > UI.beforeCET) {
                            graphDay -= UI.BERLIN_HISTORY_ADJUSTMENT * 1000;
                        }
                    }

                    final String dayTitle = _dtFormatter.print(graphDay);

                    titleText.add(dayTitle);
                }

                prevGraphUnitValue = currentGraphUnitValue;
            }
        }
    }

    //      System.out.println(UI.timeStampNano() + " \t");
    //
    //      for (final ChartUnit xUnit : xUnits) {
    //         System.out.println(UI.timeStampNano() + " \t" + xUnit);
    //         // TODO remove SYSTEM.OUT.PRINTLN
    //      }
    //
    //
    //      for (final ChartUnit xUnit : xUnitTitles) {
    //         System.out.println(UI.timeStampNano() + " \t" + xUnit);
    //         // TODO remove SYSTEM.OUT.PRINTLN
    //      }
    //
    //      for (int unitIndex = 0; unitIndex < titleText.size(); unitIndex++) {
    //
    //         System.out.println(UI.timeStampNano()
    //               + ("\t" + titleText.get(unitIndex))
    //               + ("\t" + (long) ((long) (titleValueStart.get(unitIndex) * scaleX) - devGraphXOffset))
    //               + ("\t" + (long) ((long) (titleValueEnd.get(unitIndex) * scaleX) - devGraphXOffset))
    //               + ("\t" + titleValueStart.get(unitIndex))
    //               + ("\t" + titleValueEnd.get(unitIndex))
    //         //
    //               );
    //         // TODO remove SYSTEM.OUT.PRINTLN
    //      }
}

From source file:net.tourbook.data.TourData.java

License:Open Source License

public void setWeek(final DateTime dt) {

    final int firstDayOfWeek = _prefStore.getInt(ITourbookPreferences.CALENDAR_WEEK_FIRST_DAY_OF_WEEK);
    final int minimalDaysInFirstWeek = _prefStore
            .getInt(ITourbookPreferences.CALENDAR_WEEK_MIN_DAYS_IN_FIRST_WEEK);

    _calendar.setFirstDayOfWeek(firstDayOfWeek);
    _calendar.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek);

    _calendar.set(dt.getYear(), dt.getMonthOfYear() - 1, dt.getDayOfMonth());

    startWeek = (short) _calendar.get(Calendar.WEEK_OF_YEAR);
    startWeekYear = (short) Util.getYearForWeek(_calendar);
}

From source file:net.tourbook.database.TourDatabase.java

License:Open Source License

/**
 * Persist {@link TourData} in the database and updates the tour data cache with the persisted
 * tour<br>/*from www .j  av a  2s.  c  om*/
 * <br>
 * When a tour has no person the tour will not be saved, a person must be set first before the
 * tour can be saved
 * 
 * @param tourData
 * @return persisted {@link TourData} or <code>null</code> when saving fails
 */
public static TourData saveTour(final TourData tourData) {

    /*
     * prevent saving a tour which was deleted before
     */
    if (tourData.isTourDeleted) {
        return null;
    }

    /*
     * prevent saving a tour when a person is not set, this check is for internal use that all
     * data are valid
     */
    if (tourData.getTourPerson() == null) {
        StatusUtil.log("Cannot save a tour without a person: " + tourData); //$NON-NLS-1$
        return null;
    }

    /*
     * check size of varcar fields
     */
    if (tourData.isValidForSave() == false) {
        return null;
    }

    final DateTime dtNow = new DateTime();

    final long dtSaved = (dtNow.getYear() * 10000000000L) + (dtNow.getMonthOfYear() * 100000000L)
            + (dtNow.getDayOfMonth() * 1000000L) + (dtNow.getHourOfDay() * 10000L)
            + (dtNow.getMinuteOfHour() * 100L) + dtNow.getSecondOfMinute();

    EntityManager em = TourDatabase.getInstance().getEntityManager();

    TourData persistedEntity = null;

    if (em != null) {

        final EntityTransaction ts = em.getTransaction();

        try {

            tourData.onPrePersist();

            ts.begin();
            {
                final TourData tourDataEntity = em.find(TourData.class, tourData.getTourId());
                if (tourDataEntity == null) {

                    // tour is not yet persisted

                    tourData.setDateTimeCreated(dtSaved);

                    em.persist(tourData);

                    persistedEntity = tourData;

                } else {

                    tourData.setDateTimeModified(dtSaved);

                    persistedEntity = em.merge(tourData);
                }
            }
            ts.commit();

        } catch (final Exception e) {

            StatusUtil.showStatus(Messages.Tour_Database_TourSaveError, e);

        } finally {
            if (ts.isActive()) {
                ts.rollback();
            }
            em.close();
        }
    }

    if (persistedEntity != null) {

        em = TourDatabase.getInstance().getEntityManager();
        try {

            persistedEntity = em.find(TourData.class, tourData.getTourId());

        } catch (final Exception e) {
            StatusUtil.log(e);
        }

        em.close();

        TourManager.getInstance().updateTourInCache(persistedEntity);
    }

    return persistedEntity;
}

From source file:net.tourbook.device.garmin.GarminSAXHandler.java

License:Open Source License

/**
 * Check if date time starts with the date 2007-04-01, this can happen when the tcx file is
 * partly corrupt. When tour starts with the date 2007-04-01, move forward in the list until
 * another date occures and use this as the start date.
 *//* www  .j  a  v a 2 s . co m*/
private void adjustTourStart() {

    int validIndex = 0;
    DateTime checkedTourStart = null;

    for (final TimeData timeData : _dtList) {

        checkedTourStart = new DateTime(timeData.absoluteTime);

        if (checkedTourStart.getYear() == 2007 && checkedTourStart.getMonthOfYear() == 4
                && checkedTourStart.getDayOfMonth() == 1) {

            // this is an invalid time slice

            validIndex++;
            continue;

        } else {

            // this is a valid time slice
            break;
        }
    }

    if (validIndex == 0) {

        // date is not 2007-04-01

        return;

    } else {

        if (validIndex == _dtList.size()) {

            // all time slices have the same "invalid" date 2007-04-01 but the date also could be valid

            return;
        }
    }

    /*
     * the date starts with 2007-04-01 but it changes to another date
     */

    final TimeData[] timeSlices = _dtList.toArray(new TimeData[_dtList.size()]);

    /*
     * get average time slice duration
     */
    long sliceAvgDuration;
    if (validIndex == 1) {

        sliceAvgDuration = 8;

    } else {

        long prevSliceTime = 0;
        long sliceDuration = 0;

        for (int sliceIndex = 0; sliceIndex < validIndex; sliceIndex++) {

            final long currentTime = timeSlices[sliceIndex].absoluteTime / 1000;

            if (sliceIndex > 0) {
                sliceDuration += currentTime - prevSliceTime;
            }

            prevSliceTime = currentTime;
        }

        sliceAvgDuration = sliceDuration / validIndex;
    }

    long validTime = timeSlices[validIndex].absoluteTime / 1000;
    long prevInvalidTime = 0;

    for (int sliceIndex = validIndex - 1; sliceIndex >= 0; sliceIndex--) {

        final TimeData timeSlice = timeSlices[sliceIndex];
        final long currentInvalidTime = timeSlice.absoluteTime / 1000;

        if (sliceIndex == validIndex - 1) {

            /*
             * this is the time slice before the valid time slices, use the average time slice
             * diff to get the time, because this time cannot be evaluated it is estimated
             */

            validTime = validTime - sliceAvgDuration;

        } else {

            final long timeDiff = prevInvalidTime - currentInvalidTime;
            validTime = validTime - timeDiff;
        }

        timeSlice.absoluteTime = validTime * 1000;
        prevInvalidTime = currentInvalidTime;
    }

    StatusUtil.log(//
            NLS.bind(//
                    Messages.Garmin_SAXHandler_InvalidDate_2007_04_01, _importFilePath,
                    new DateTime(_dtList.get(0).absoluteTime).toString()));
}

From source file:net.tourbook.device.garmin.GarminSAXHandler.java

License:Open Source License

private void finalizeTour() {

    // check if data are available
    if (_dtList.size() == 0) {
        return;//from www.  ja  v a  2  s .com
    }

    validateTimeSeries();

    // create data object for each tour
    final TourData tourData = new TourData();

    // set tour notes
    setTourNotes(tourData);

    /*
     * set tour start date/time
     */
    adjustTourStart();
    final DateTime dtTourStart = new DateTime(_dtList.get(0).absoluteTime);

    tourData.setStartHour((short) dtTourStart.getHourOfDay());
    tourData.setStartMinute((short) dtTourStart.getMinuteOfHour());
    tourData.setStartSecond((short) dtTourStart.getSecondOfMinute());

    tourData.setStartYear((short) dtTourStart.getYear());
    tourData.setStartMonth((short) dtTourStart.getMonthOfYear());
    tourData.setStartDay((short) dtTourStart.getDayOfMonth());

    tourData.setWeek(dtTourStart);

    tourData.setIsDistanceFromSensor(_isDistanceFromSensor);
    tourData.setDeviceTimeInterval((short) -1);
    tourData.importRawDataFile = _importFilePath;
    tourData.setTourImportFilePath(_importFilePath);

    tourData.createTimeSeries(_dtList, true);

    tourData.setDeviceModeName(_activitySport);

    tourData.setCalories(_tourCalories);

    // after all data are added, the tour id can be created
    final int[] distanceSerie = tourData.getMetricDistanceSerie();
    String uniqueKey;

    if (_deviceDataReader.isCreateTourIdWithRecordingTime) {

        /*
         * 25.5.2009: added recording time to the tour distance for the unique key because tour
         * export and import found a wrong tour when exporting was done with camouflage speed ->
         * this will result in a NEW tour
         */
        final int tourRecordingTime = tourData.getTourRecordingTime();

        if (distanceSerie == null) {
            uniqueKey = Integer.toString(tourRecordingTime);
        } else {

            final long tourDistance = distanceSerie[(distanceSerie.length - 1)];

            uniqueKey = Long.toString(tourDistance + tourRecordingTime);
        }

    } else {

        /*
         * original version to create tour id
         */
        if (distanceSerie == null) {
            uniqueKey = Util.UNIQUE_ID_SUFFIX_GARMIN_TCX;
        } else {
            uniqueKey = Integer.toString(distanceSerie[distanceSerie.length - 1]);
        }
    }

    final Long tourId = tourData.createTourId(uniqueKey);

    // check if the tour is already imported
    if (_tourDataMap.containsKey(tourId) == false) {

        tourData.computeAltitudeUpDown();
        tourData.computeTourDrivingTime();
        tourData.computeComputedValues();

        final String deviceName = _sport.creatorName;
        final String majorVersion = _sport.creatorVersionMajor;
        final String minorVersion = _sport.creatorVersionMinor;

        tourData.setDeviceId(_deviceDataReader.deviceId);

        tourData.setDeviceName(
                _deviceDataReader.visibleName + (deviceName == null ? UI.EMPTY_STRING : UI.SPACE + deviceName));

        tourData.setDeviceFirmwareVersion(majorVersion == null //
                ? UI.EMPTY_STRING
                : majorVersion + (minorVersion == null //
                        ? UI.EMPTY_STRING
                        : UI.DOT + minorVersion));

        // add new tour to other tours
        _tourDataMap.put(tourId, tourData);
    }

    _isImported = true;
}

From source file:net.tourbook.device.gpx.GPX_SAX_Handler.java

License:Open Source License

private void finalizeTour() {

    if (_timeDataList.size() == 0) {
        // there is not data
        return;/* w  w  w  . j a va 2s  .com*/
    }

    final TimeData firstTimeData = _timeDataList.get(0);

    // create data object for each tour
    final TourData tourData = new TourData();

    tourData.setTourTitle(_trkName);

    /*
     * set tour start date/time
     */
    final DateTime dtTourStart = new DateTime(firstTimeData.absoluteTime);

    tourData.setStartYear((short) dtTourStart.getYear());
    tourData.setStartMonth((short) dtTourStart.getMonthOfYear());
    tourData.setStartDay((short) dtTourStart.getDayOfMonth());

    tourData.setStartHour((short) dtTourStart.getHourOfDay());
    tourData.setStartMinute((short) dtTourStart.getMinuteOfHour());
    tourData.setStartSecond((short) dtTourStart.getSecondOfMinute());

    tourData.setWeek(tourData.getStartYear(), tourData.getStartMonth(), tourData.getStartDay());

    tourData.setDeviceTimeInterval((short) -1);
    tourData.setTemperatureScale(TourbookDevice.TEMPERATURE_SCALE);

    tourData.importRawDataFile = _importFilePath;
    tourData.setTourImportFilePath(_importFilePath);

    tourData.createTimeSeries(_timeDataList, true);
    tourData.computeAltitudeUpDown();

    tourData.setWayPoints(_wptList);

    /*
     * adjust default marker which are created in tourData.createTimeSeries()
     */
    for (final TourMarker tourMarker : tourData.getTourMarkers()) {

        tourMarker.setVisualPosition(ChartLabel.VISUAL_VERTICAL_BOTTOM_CHART);

        // disable time/distance
        tourMarker.setTime(-1);
        tourMarker.setDistance(-1);
    }

    // after all data are added, the tour id can be created
    final int[] distanceSerie = tourData.getMetricDistanceSerie();
    String uniqueKey;

    if (_deviceDataReader.isCreateTourIdWithRecordingTime) {

        /*
         * 23.3.2009: added recording time to the tour distance for the unique key because tour
         * export and import found a wrong tour when exporting was done with camouflage speed ->
         * this will result in a NEW tour
         */
        final int tourRecordingTime = tourData.getTourRecordingTime();

        if (distanceSerie == null) {
            uniqueKey = Integer.toString(tourRecordingTime);
        } else {

            final long tourDistance = distanceSerie[(distanceSerie.length - 1)];

            uniqueKey = Long.toString(tourDistance + tourRecordingTime);
        }

    } else {

        /*
         * original version to create tour id
         */
        if (distanceSerie == null) {
            uniqueKey = Util.UNIQUE_ID_SUFFIX_GPX;
        } else {
            uniqueKey = Integer.toString(distanceSerie[distanceSerie.length - 1]);
        }
    }

    final Long tourId = tourData.createTourId(uniqueKey);

    // check if the tour is already imported
    if (_tourDataMap.containsKey(tourId) == false) {

        tourData.computeTourDrivingTime();
        tourData.computeComputedValues();

        tourData.setDeviceId(_deviceDataReader.deviceId);
        tourData.setDeviceName(_deviceDataReader.visibleName);

        // add new tour to other tours
        _tourDataMap.put(tourId, tourData);
    }

    _isImported = true;
}

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

License:Open Source License

private void createTourData(final HashMap<Long, TourData> tourDataMap) {

    // create data object for each tour
    final TourData tourData = new TourData();

    /*/*from  w  ww. j  a  v  a 2  s .  c  o m*/
     * set tour start date/time
     */
    final DateTime dtTourStart = new DateTime(_sectionParams.startYear, _sectionParams.startMonth,
            _sectionParams.startDay, _sectionParams.startHour, _sectionParams.startMinute,
            _sectionParams.startSecond, 0);

    tourData.setStartHour((short) dtTourStart.getHourOfDay());
    tourData.setStartMinute((short) dtTourStart.getMinuteOfHour());
    tourData.setStartSecond((short) dtTourStart.getSecondOfMinute());

    tourData.setStartYear((short) dtTourStart.getYear());
    tourData.setStartMonth((short) dtTourStart.getMonthOfYear());
    tourData.setStartDay((short) dtTourStart.getDayOfMonth());

    tourData.setWeek(dtTourStart);

    tourData.setDeviceTimeInterval((short) _sectionParams.mtInterval);

    tourData.importRawDataFile = _importFilePath;
    tourData.setTourImportFilePath(_importFilePath);

    //      tourData.setCalories(_calories);
    tourData.setRestPulse(_sectionParams.restHR == Integer.MIN_VALUE ? 0 : _sectionParams.restHR);

    if (_sectionTrip != null) {
        tourData.setStartDistance(_sectionTrip.odometer == Integer.MIN_VALUE ? 0 : _sectionTrip.odometer);
    }

    final ArrayList<TimeData> timeSeries = createTourData10CreateTimeSeries(dtTourStart);
    createTourData20SetTemperature(tourData, timeSeries);

    tourData.createTimeSeries(timeSeries, true);

    createTourData30CreateMarkers(tourData);
    tourData.computeAltitudeUpDown();

    // after all data are added, the tour id can be created
    final Long tourId = tourData.createTourId(createUniqueId(tourData, Util.UNIQUE_ID_SUFFIX_POLAR_HRM));

    // check if the tour is already imported
    if (tourDataMap.containsKey(tourId) == false) {

        tourData.computeTourDrivingTime();
        tourData.computeComputedValues();

        tourData.setDeviceId(deviceId);
        tourData.setDeviceName(_sectionParams.monitorName);
        tourData.setDeviceFirmwareVersion(Integer.toString(_hrmVersion));

        // add new tour to other tours
        tourDataMap.put(tourId, tourData);
    }
}

From source file:net.tourbook.device.polartrainer.PolarTrainerSAXHandler.java

License:Open Source License

private void finalizeTour() throws InvalidDeviceSAXException {

    if (finalizeTour10CreateTimeSlices() == false) {
        _isImported = false;/*from   w w w  . j  a v a 2s.c  om*/
        return;
    }

    // create data object for each tour
    final TourData tourData = new TourData();

    /*
     * set tour start date/time
     */
    final DateTime tourStart = _currentExercise.tourStart;

    tourData.setStartHour((short) tourStart.getHourOfDay());
    tourData.setStartMinute((short) tourStart.getMinuteOfHour());
    tourData.setStartSecond((short) tourStart.getSecondOfMinute());

    tourData.setStartYear((short) tourStart.getYear());
    tourData.setStartMonth((short) tourStart.getMonthOfYear());
    tourData.setStartDay((short) tourStart.getDayOfMonth());

    tourData.setWeek(tourStart);

    tourData.setDeviceTimeInterval(_currentExercise.timeInterval);

    tourData.setTemperatureScale(TourbookDevice.TEMPERATURE_SCALE);
    tourData.importRawDataFile = _importFilePath;

    tourData.setTourImportFilePath(_importFilePath);

    tourData.setTourTitle(_currentExercise.tourTitle);
    tourData.setCalories(_currentExercise.calories);
    tourData.setRestPulse(_currentExercise.restPulse);

    tourData.createTimeSeries(_timeSlices, true);

    finalizeTour20CreateMarkers(tourData);
    finalizeTour30SetTourType(tourData);

    tourData.computeAltitudeUpDown();

    // after all data are added, the tour id can be created
    final Long tourId = tourData
            .createTourId(_device.createUniqueId(tourData, Util.UNIQUE_ID_SUFFIX_POLAR_TRAINER));

    // check if the tour is already imported
    if (_tourDataMap.containsKey(tourId) == false) {

        tourData.computeTourDrivingTime();
        tourData.computeComputedValues();

        tourData.setDeviceId(_device.deviceId);
        tourData.setDeviceName(DEVICE_NAME_POLAR_PERSONALTRAINER);

        tourData.setDeviceFirmwareVersion(_dataVersion == 1 ? TAG_ROOT_VERSION_1 : UI.EMPTY_STRING);

        // add new tour to other tours
        _tourDataMap.put(tourId, tourData);
    }

    _isImported = true;
}