Example usage for org.joda.time DateTime getMonthOfYear

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

Introduction

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

Prototype

public int getMonthOfYear() 

Source Link

Document

Get the month of year field value.

Usage

From source file:net.tourbook.ui.views.calendar.CalendarGraph.java

License:Open Source License

private void drawCalendar(GC gc) {

    final int dayLabelXOffset = 1;

    final int XX = getSize().x;
    final int YY = getSize().y;

    //      System.out.println(_graphClean ? "clean!" : "NOT clean!");
    //      System.out.println(_highlightChanged ? "HL changed!" : "HL NOT changed");
    //      System.out.println("-----------");

    _fontHeight = gc.getFontMetrics().getHeight();

    if (_graphClean && _image != null) {

        final GC oldGc = gc;
        _highlight = new Image(getDisplay(), XX, YY);
        gc = new GC(_highlight);
        gc.drawImage(_image, 0, 0);//from w  w w . j a v  a 2 s  .c o  m

        drawSelection(gc);

        if (_highlightChanged) {
            drawHighLight(gc);
            _highlightChanged = false;
        }

        gc.dispose();
        oldGc.drawImage(_highlight, 0, 0);
        _highlight.dispose();
        return;
    }

    if (_scrollDebug) {
        System.out.println("Drawing year: " + _dt.getYear() + " week: " + _dt.getWeekOfWeekyear()); //$NON-NLS-1$ //$NON-NLS-2$
    }

    if (_image != null && !_image.isDisposed()) {
        _image.dispose();
    }

    DateTime date = new DateTime(_dt);
    _image = new Image(getDisplay(), XX, YY);

    // update month/year dropdown box
    // look at the 1st day of the week after the first day displayed because if we go to
    // a specific month we ensure that the first day of the month is displayed in
    // the first line, meaning the first day in calendar normally contains a day
    // of the *previous* month
    if (_calendarYearMonthContributor.getSelectedYear() != date.plusDays(7).getYear()) {
        _calendarYearMonthContributor.selectYear(date.getYear());
    }
    if (_calendarYearMonthContributor.getSelectedMonth() != date.plusDays(7).getMonthOfYear()) {
        _calendarYearMonthContributor.selectMonth(date.getMonthOfYear());
    }

    final GC oldGc = gc;
    gc = new GC(_image);

    _refTextExtent = gc.stringExtent(_refText);
    final boolean oldLayout = _tinyLayout;
    _tinyLayout = (_refTextExtent.x > XX / 9); // getNumOfWeeks needs the _tinuLayout set

    if (oldLayout != _tinyLayout) { // the layout style changed, try to restore weeks and make selection visible
        if (_tinyLayout) {
            _dt_normal = _dt;
            _dt = _dt_tiny;
        } else {
            _dt_tiny = _dt;
            _dt = _dt_normal;
        }
        scrollBarUpdate();
        if (_selectedItem.id > 0) {
            switch (_selectedItem.type) {
            case DAY:
                gotoDate(new DateTime(0).plusDays(_selectedItem.id.intValue()));
                return;
            case TOUR:
                gotoTourId(_selectedItem.id);
                return;
            }
        }
    }

    final int numCols = 9; // one col left and right of the week + 7 week days
    final int numRows = getNumOfWeeks(); // number of weeks per month displayed (make sure _tinyLayout is already defined!)

    final Color alternate = _colorCache.getColor(0xf0f0f0);

    _tourFocus = new ArrayList<ObjectLocation>();
    _dayFocus = new ArrayList<ObjectLocation>();

    CalendarTourData[] data;

    final Font normalFont = gc.getFont();
    final FontData fd[] = normalFont.getFontData();
    fd[0].setStyle(SWT.BOLD);
    final Font boldFont = new Font(_display, fd[0]);

    final Rectangle area = getClientArea();
    gc.setBackground(_white);
    gc.setForeground(_black);
    gc.fillRectangle(area);

    final float dY = (float) YY / (float) numRows;
    float dX = (float) XX / (float) numCols;

    // keep the summary column at a minimal width and hide it completely if height goes blow usable value
    final int minSummaryWidth = _refTextExtent.x;
    final int minSummaryHeigth = (_refTextExtent.y * 2) / 3;
    int summaryWidth = 0;
    if (dY > minSummaryHeigth) {
        if (dX < minSummaryWidth) {
            summaryWidth = minSummaryWidth;
        } else {
            summaryWidth = (int) dX;
        }
    }

    final int minInfoWidth = _refTextExtent.x / 2;
    final int minInfoHeigth = (_refTextExtent.y / 3);
    int infoWidth = 0;
    if (dY > minInfoHeigth) {
        if (dX < minInfoWidth) {
            infoWidth = minInfoWidth;
        } else {
            infoWidth = (int) dX;
        }
    }

    dX = (float) (XX - summaryWidth - infoWidth) / (numCols - 2);

    _calendarAllDaysRectangle = new Rectangle(infoWidth, 0, (int) (7 * dX), YY);
    //      _calendarFirstWeekRectangle = new Rectangle(infoWidth, 0, (int) (7 * dX), (int) dY);
    //      _calendarLastWeekRectangle = new Rectangle( infoWidth, (int) ((getNumOfWeeks() - 1) * dY), (int) (7 * dX), (int) dY);

    // first draw the horizontal lines
    gc.setBackground(_white);
    gc.setForeground(_gray);
    for (int i = 0; i <= numRows; i++) {
        gc.drawLine(0, (int) (i * dY), XX, (int) (i * dY));
    }

    //      final Rectangle selectedRec = null;
    //      final CalendarTourData selectedTour = null;
    //      final boolean doSelection = false;

    final long todayDayId = (new Day(new DateTime())).dayId;

    gc.setFont(boldFont);
    // a rough guess about the max size of the label
    final Point[] headerSizes = { gc.stringExtent("22. May 99"), //$NON-NLS-1$
            gc.stringExtent("22. May"), //$NON-NLS-1$
            gc.stringExtent("22") }; //$NON-NLS-1$
    gc.setFont(normalFont);

    final String[] headerFormats = { "dd. MMM yy", "dd. MMM", "dd" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    String headerFormat = UI.EMPTY_STRING;

    // Find a format for the day header which fits into the rectangle available;
    int g = 0;
    while (g < headerSizes.length && headerSizes[g].x > (dX - dayLabelXOffset)) {
        g++;
    }
    g = Math.min(g, headerSizes.length - 1); // if the cell is smaller than the shortest format (no index 'g' was found) we use the shortest format and relay on clipping
    // if (headerSizes[g].y < dY) {
    //    headerFormat = headerFormats[g];
    // }
    headerFormat = headerFormats[g];
    final int dayLabelWidht = headerSizes[g].x;
    int dayLabelHeight = headerSizes[g].y;

    // _tinyLayout = (refTextExtent.x > dX || refTextExtent.y > dY - dayLabelHeight) ? true : false;

    DateTime weekDate;
    long dayId = (new Day(date)).dayId; // we use simple ids

    // Weeks
    for (int i = 0; i < numRows; i++) {

        final int Y1 = (int) (i * dY);
        final int Y2 = (int) ((i + 1) * dY);

        // Days per week
        Rectangle dayRec = null;
        weekDate = date; // save the first day of this week as a pointer to this week

        if (infoWidth > 0) {
            final Rectangle infoRec = new Rectangle(0, Y1, infoWidth, (Y2 - Y1));
            drawWeekInfo(gc, date, infoRec);
        }

        for (int j = 0; j < 7; j++) {
            final int X1 = infoWidth + (int) (j * dX);
            final int X2 = infoWidth + (int) ((j + 1) * dX);
            //            final Rectangle dayRec = new Rectangle(X1, Y1, (X2 - X1), (Y2 - Y1));
            dayRec = new Rectangle(X1, Y1, (X2 - X1), (Y2 - Y1));
            final Day day = new Day(dayId);
            _dayFocus.add(new ObjectLocation(dayRec, dayId, day));
            dayId = day.dayId + 1;
            final int weekDay = date.getDayOfWeek();

            gc.setBackground(_white);

            // Day background rectangle
            if ((date.getMonthOfYear() % 2) == 1) {
                gc.setBackground(alternate);
                gc.fillRectangle(dayRec.x, dayRec.y + 1, dayRec.width, dayRec.height - 1);
            }

            data = _dataProvider.getCalendarDayData(date.getYear(), date.getMonthOfYear(),
                    date.getDayOfMonth());

            // Day header box
            if (!_tinyLayout) {
                gc.setForeground(_gray);
                gc.fillGradientRectangle(X1, Y1, dayRec.width + 1, dayLabelHeight, true); // no clue why I've to add 1 to the width, looks like a bug on Linux and does not hurt as we overwrite with the vertial line at the end anyway

                // Day header label
                gc.setFont(boldFont);
                if (day.dayId == todayDayId) {
                    gc.setForeground(_blue);
                } else if (weekDay == DateTimeConstants.SATURDAY || weekDay == DateTimeConstants.SUNDAY) {
                    gc.setForeground(_red);
                } else {
                    gc.setForeground(_darkGray);
                }
                gc.setClipping(X1, Y1, dayRec.width, dayLabelHeight); // this clipping should only kick in if shortest label format is still longer than the cell width
                gc.drawText(date.toString(headerFormat), X2 - dayLabelWidht - dayLabelXOffset, Y1, true);
                gc.setFont(normalFont);
                gc.setClipping(_nullRec);

            } else {
                dayLabelHeight = 0;
            }

            drawDayTours(gc, data, new Rectangle(dayRec.x, dayRec.y + dayLabelHeight, dayRec.width,
                    dayRec.height - dayLabelHeight));

            if (_tinyLayout && _showDayNumberInTinyView) {
                if (day.dayId == todayDayId) {
                    gc.setForeground(_blue);
                } else if (weekDay == DateTimeConstants.SATURDAY || weekDay == DateTimeConstants.SUNDAY) {
                    gc.setForeground(_red);
                } else {
                    gc.setForeground(_darkGray);
                }
                gc.setAlpha(0x50);
                gc.setFont(boldFont);
                gc.setClipping(dayRec);
                gc.drawText(date.toString(headerFormat), X2 - dayLabelWidht - dayLabelXOffset, Y1, true);
                gc.setFont(normalFont);
                gc.setClipping(_nullRec);
                gc.setAlpha(0xFF);
            }

            date = date.plusDays(1);
        }

        if (summaryWidth > 0) {
            final int X1 = infoWidth + (int) (7 * dX);
            final int X2 = X1 + summaryWidth;
            final Rectangle weekRec = new Rectangle(X1, Y1, (X2 - X1), (Y2 - Y1));
            final CalendarTourData weekSummary = _dataProvider.getCalendarWeekSummaryData(weekDate.getYear(),
                    weekDate.getWeekOfWeekyear());
            if (weekSummary.numTours > 0) {
                drawWeekSummary(gc, weekSummary, weekRec);
            }
        }

    }
    gc.setFont(normalFont);

    // and finally the vertical lines
    gc.setForeground(_display.getSystemColor(SWT.COLOR_GRAY));
    for (int i = 0; i <= 7; i++) {
        gc.drawLine(infoWidth + (int) (i * dX), 0, infoWidth + (int) (i * dX), YY);
    }

    // draw the selection on top of our calendar graph image so we can reuse that image
    _highlight = new Image(getDisplay(), XX, YY);
    gc = new GC(_highlight);
    gc.drawImage(_image, 0, 0);
    drawSelection(gc);
    oldGc.drawImage(_highlight, 0, 0);
    _highlight.dispose();

    boldFont.dispose();
    oldGc.dispose();
    gc.dispose();

    _graphClean = true;

}

From source file:net.tourbook.ui.views.calendar.CalendarYearMonthContributionItem.java

License:Open Source License

private void fillMonthComboBox() {

    DateTime dt = new DateTime();
    final int thisMonth = dt.getMonthOfYear();
    dt = dt.withMonthOfYear(DateTimeConstants.JANUARY);

    _cboMonthValues = new ArrayList<Integer>();
    _cboMonthKeys = new HashMap<Integer, Integer>();

    for (int i = 0; i < 12; i++) {
        // _cboMonth.add(dt.toString("MMMM"));
        _cboMonth.add(dt.toString("MMM")); // make the toolbar fit more likely into one line //$NON-NLS-1$
        _cboMonthValues.add(dt.getMonthOfYear());
        _cboMonthKeys.put(dt.getMonthOfYear(), i);
        dt = dt.plusMonths(1);/*from   w w  w . j  a v a  2  s. c o  m*/
    }

    _cboMonth.select(thisMonth - 1);

}

From source file:nl.mpcjanssen.simpletask.AddTask.java

License:Open Source License

private void insertDate(final int dateType) {
    Dialog d = Util.createDeferDialog(this, dateType, false, new Util.InputDialogListener() {
        @Override//from   ww w .ja  v  a 2 s.  c o m
        public void onClick(String selected) {
            if (selected.equals("pick")) {
                /* Note on some Android versions the OnDateSetListener can fire twice
                 * https://code.google.com/p/android/issues/detail?id=34860
                 * With the current implementation which replaces the dates this is not an
                 * issue. The date is just replaced twice
                 */
                final DateTime today = new DateTime();
                DatePickerDialog dialog = new DatePickerDialog(AddTask.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                                month++;
                                DateTime date = ISODateTimeFormat.date()
                                        .parseDateTime(year + "-" + month + "-" + day);
                                insertDateAtSelection(dateType, date);
                            }
                        }, today.getYear(), today.getMonthOfYear() - 1, today.getDayOfMonth());

                dialog.show();
            } else {
                insertDateAtSelection(dateType, Util.addInterval(new DateTime(), selected));
            }
        }
    });
    d.show();
}

From source file:nl.mpcjanssen.simpletask.Simpletask.java

License:GNU General Public License

private void deferTasks(List<Task> tasks, final int dateType) {
    final List<Task> tasksToDefer = tasks;
    Dialog d = Util.createDeferDialog(this, dateType, true, new Util.InputDialogListener() {
        @Override//from  w  w w.j  a  v a  2  s .c om
        public void onClick(String selected) {
            if (selected != null && selected.equals("pick")) {
                final DateTime today = new DateTime();
                DatePickerDialog dialog = new DatePickerDialog(Simpletask.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                                month++;

                                DateTime date = ISODateTimeFormat.date()
                                        .parseDateTime(year + "-" + month + "-" + day);
                                deferTasks(date, tasksToDefer, dateType);

                            }
                        }, today.getYear(), today.getMonthOfYear() - 1, today.getDayOfMonth());

                dialog.show();
            } else {
                deferTasks(selected, tasksToDefer, dateType);
            }
        }
    });
    d.show();
}

From source file:nl.mpi.oai.harvester.cycle.EndpointAdapter.java

License:Open Source License

@Override
public void doneHarvesting(Boolean done) {

    /* Store the current date in a XMLGregorianCalendar object. Note: at
       the XML level, the date will be represented in ISO8601 format.
     *//*from  ww w  . j  a  v  a2  s .c  o m*/
    XMLGregorianCalendar xmlGregorianCalendar;

    try {
        // get current time in the UTC zone
        DateTime dateTime = new DateTime(DateTimeZone.UTC);

        // create XML calendar
        xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar();

        // set the date related fields
        xmlGregorianCalendar.setDay(dateTime.getDayOfMonth());
        xmlGregorianCalendar.setMonth(dateTime.getMonthOfYear());
        xmlGregorianCalendar.setYear(dateTime.getYear());

        // set the calendar to UTC, this zone sets off 0 minutes from UTC
        xmlGregorianCalendar.setTimezone(0);

        // set the time related fields
        xmlGregorianCalendar.setHour(dateTime.getHourOfDay());
        xmlGregorianCalendar.setMinute(dateTime.getMinuteOfHour());
        xmlGregorianCalendar.setSecond(dateTime.getSecondOfMinute());

        // represent milliseconds as a fraction of a second
        BigDecimal s = BigDecimal.valueOf(dateTime.getMillisOfSecond());
        s = s.divide(BigDecimal.valueOf(1000));

        xmlGregorianCalendar.setFractionalSecond(s);

        // set the property representing the date of the attempt
        endpointType.setAttempted(xmlGregorianCalendar);

        if (done) {
            // successful attempt, also set attribute representing this
            endpointType.setHarvested(xmlGregorianCalendar);
        }

        xmlOverview.save();

    } catch (DatatypeConfigurationException e) {
        // report the error, we cannot continue
        Logger.getLogger(EndpointAdapter.class.getName()).log(Level.SEVERE, null, endpointType);
    }
}

From source file:op.allowance.PnlAllowance.java

License:Open Source License

private JPanel createContentPanel4(final Resident resident, LocalDate month) {
    final String key = getKey(resident, month);

    if (!contentmap.containsKey(key)) {

        JPanel pnlMonth = new JPanel(new VerticalLayout());

        pnlMonth.setBackground(getBG(resident, 11));
        pnlMonth.setOpaque(false);/*from  w w w  . j  av a2s .  c o m*/

        //            final String prevKey = resident.getRID() + "-" + SYSCalendar.eom(month.minusMonths(1)).getYear() + "-" + SYSCalendar.eom(month.minusMonths(1)).getMonthOfYear();
        if (!carrySums.containsKey(key)) {
            carrySums.put(key, AllowanceTools.getSUM(resident, SYSCalendar.eom(month.minusMonths(1))));
        }

        BigDecimal rowsum = carrySums.get(key);

        if (!cashmap.containsKey(key)) {
            cashmap.put(key, AllowanceTools.getMonth(resident, month.toDate()));
        }

        JLabel lblEOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMaximumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.endofmonth") + "</td>"
                + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        pnlMonth.add(lblEOM);

        for (final Allowance allowance : cashmap.get(key)) {

            String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                    + DateFormat.getDateInstance().format(allowance.getPit()) + "</td>"
                    + "<td width=\"400\" align=\"left\">" + allowance.getText() + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "")
                    + cf.format(allowance.getAmount())
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>"
                    +

                    "</font></html>";

            DefaultCPTitle cptitle = new DefaultCPTitle(title, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                }
            });
            cptitle.getButton().setIcon(
                    allowance.isReplaced() || allowance.isReplacement() ? SYSConst.icon22eraser : null);

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
                /***
                 *      _____    _ _ _
                 *     | ____|__| (_) |_
                 *     |  _| / _` | | __|
                 *     | |__| (_| | | |_
                 *     |_____\__,_|_|\__|
                 *
                 */
                final JButton btnEdit = new JButton(SYSConst.icon22edit3);
                btnEdit.setPressedIcon(SYSConst.icon22edit3Pressed);
                btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnEdit.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnEdit.setContentAreaFilled(false);
                btnEdit.setBorder(null);
                btnEdit.setToolTipText(SYSTools.xx("admin.residents.cash.btnedit.tooltip"));
                btnEdit.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        final JidePopup popupTX = new JidePopup();
                        popupTX.setMovable(false);
                        PnlTX pnlTX = getPnlTX(resident, allowance);
                        popupTX.setContentPane(pnlTX);
                        popupTX.removeExcludedComponent(pnlTX);
                        popupTX.setDefaultFocusComponent(pnlTX);

                        popupTX.setOwner(btnEdit);
                        GUITools.showPopup(popupTX, SwingConstants.WEST);

                    }
                });
                cptitle.getRight().add(btnEdit);
                // you can edit your own entries or you are a manager. once they are replaced or a replacement record, its over.
                btnEdit.setEnabled((OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, internalClassID)
                        || allowance.getUser().equals(OPDE.getLogin().getUser())) && !allowance.isReplaced()
                        && !allowance.isReplacement());

                /***
                 *      _   _           _         _______  __
                 *     | | | |_ __   __| | ___   |_   _\ \/ /
                 *     | | | | '_ \ / _` |/ _ \    | |  \  /
                 *     | |_| | | | | (_| | (_) |   | |  /  \
                 *      \___/|_| |_|\__,_|\___/    |_| /_/\_\
                 *
                 */
                final JButton btnUndoTX = new JButton(SYSConst.icon22undo);
                btnUndoTX.setPressedIcon(SYSConst.icon22Pressed);
                btnUndoTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnUndoTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnUndoTX.setContentAreaFilled(false);
                btnUndoTX.setBorder(null);
                btnUndoTX.setToolTipText(SYSTools.xx("admin.residents.cash.btnundotx.tooltip"));
                btnUndoTX.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        new DlgYesNo(
                                SYSTools.xx("misc.questions.undo1") + "<br/><i>" + "<br/><i>"
                                        + allowance.getText() + "&nbsp;" + cf.format(allowance.getAmount())
                                        + "</i><br/>" + SYSTools.xx("misc.questions.undo2"),
                                SYSConst.icon48undo, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();

                                                Allowance myOldAllowance = em.merge(allowance);
                                                Allowance myCancelAllowance = em
                                                        .merge(new Allowance(myOldAllowance));
                                                em.lock(em.merge(myOldAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);
                                                em.lock(myOldAllowance, LockModeType.OPTIMISTIC);
                                                myOldAllowance.setReplacedBy(myCancelAllowance,
                                                        em.merge(OPDE.getLogin().getUser()));

                                                em.getTransaction().commit();

                                                DateTime txDate = new DateTime(myCancelAllowance.getPit());

                                                final String keyMonth = myCancelAllowance.getResident().getRID()
                                                        + "-" + txDate.getYear() + "-"
                                                        + txDate.getMonthOfYear();
                                                contentmap.remove(keyMonth);
                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(allowance);
                                                cashmap.get(keyMonth).add(myOldAllowance);
                                                cashmap.get(keyMonth).add(myCancelAllowance);
                                                Collections.sort(cashmap.get(keyMonth));

                                                updateCarrySums(myCancelAllowance);

                                                createCP4(myCancelAllowance.getResident());

                                                try {
                                                    cpMap.get(keyMonth).setCollapsed(false);
                                                } catch (PropertyVetoException e) {
                                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                                }

                                                buildPanel();

                                            } catch (OptimisticLockException ole) {
                                                OPDE.warn(ole);
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                if (ole.getMessage()
                                                        .indexOf("Class> entity.info.Resident") > -1) {
                                                    OPDE.getMainframe().emptyFrame();
                                                    OPDE.getMainframe().afterLogin();
                                                }
                                                OPDE.getDisplayManager()
                                                        .addSubMessage(DisplayManager.getLockMessage());
                                            } catch (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });
                    }
                });
                cptitle.getRight().add(btnUndoTX);
                btnUndoTX.setEnabled(!allowance.isReplaced() && !allowance.isReplacement());
            }

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) {
                /***
                 *      ____       _      _
                 *     |  _ \  ___| | ___| |_ ___
                 *     | | | |/ _ \ |/ _ \ __/ _ \
                 *     | |_| |  __/ |  __/ ||  __/
                 *     |____/ \___|_|\___|\__\___|
                 *
                 */
                final JButton btnDelete = new JButton(SYSConst.icon22delete);
                btnDelete.setPressedIcon(SYSConst.icon22deletePressed);
                btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnDelete.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnDelete.setContentAreaFilled(false);
                btnDelete.setBorder(null);
                btnDelete.setToolTipText(SYSTools.xx("admin.residents.cash.btndelete.tooltip"));
                btnDelete.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        new DlgYesNo(
                                SYSTools.xx("misc.questions.delete1") + "<br/><i>" + allowance.getText()
                                        + "&nbsp;" + cf.format(allowance.getAmount()) + "</i><br/>"
                                        + SYSTools.xx("misc.questions.delete2"),
                                SYSConst.icon48delete, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();
                                                Allowance myAllowance = em.merge(allowance);
                                                em.lock(em.merge(myAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);

                                                Allowance theOtherOne = null;
                                                // Check for special cases
                                                if (myAllowance.isReplacement()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacementFor());
                                                    theOtherOne.setReplacedBy(null);
                                                    theOtherOne.setEditedBy(null);
                                                    myAllowance.setEditPit(null);
                                                }
                                                if (myAllowance.isReplaced()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacedBy());
                                                    theOtherOne.setReplacementFor(null);
                                                }

                                                em.remove(myAllowance);
                                                em.getTransaction().commit();

                                                DateTime txDate = new DateTime(myAllowance.getPit());
                                                final String keyMonth = myAllowance.getResident().getRID() + "-"
                                                        + txDate.getYear() + "-" + txDate.getMonthOfYear();

                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(myAllowance);
                                                if (theOtherOne != null) {
                                                    cashmap.get(keyMonth).remove(theOtherOne);
                                                    cashmap.get(keyMonth).add(theOtherOne);
                                                    Collections.sort(cashmap.get(keyMonth));
                                                }

                                                // only to update the carrysums. myAllowance will be discarded soon.
                                                myAllowance.setAmount(myAllowance.getAmount().negate());
                                                updateCarrySums(myAllowance);

                                                createCP4(myAllowance.getResident());

                                                try {
                                                    if (cpMap.containsKey(keyMonth)) {
                                                        cpMap.get(keyMonth).setCollapsed(false);
                                                    }
                                                } catch (PropertyVetoException e) {
                                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                                }

                                                buildPanel();
                                            } catch (OptimisticLockException ole) {
                                                OPDE.warn(ole);
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                if (ole.getMessage()
                                                        .indexOf("Class> entity.info.Resident") > -1) {
                                                    OPDE.getMainframe().emptyFrame();
                                                    OPDE.getMainframe().afterLogin();
                                                }
                                                OPDE.getDisplayManager()
                                                        .addSubMessage(DisplayManager.getLockMessage());
                                            } catch (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });
                    }
                });
                cptitle.getRight().add(btnDelete);
            }
            pnlMonth.add(cptitle.getMain());
            linemap.put(allowance, cptitle.getMain());

            rowsum = rowsum.subtract(allowance.getAmount());
        }

        JLabel lblBOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMinimumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.startofmonth")
                + "</td>" + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        lblBOM.setBackground(getBG(resident, 11));
        pnlMonth.add(lblBOM);
        contentmap.put(key, pnlMonth);
    }

    return contentmap.get(key);
}

From source file:op.allowance.PnlAllowance.java

License:Open Source License

private PnlTX getPnlTX(Resident resident, final Allowance allowance) {
    final BigDecimal editAmount = allowance != null ? allowance.getAmount() : null;
    final Allowance allow = (allowance == null ? new Allowance(resident) : allowance);

    return new PnlTX(allow, new Closure() {
        @Override/*from  w w  w  .  j  av a  2s  .c o  m*/
        public void execute(Object o) {
            if (o != null) {

                EntityManager em = OPDE.createEM();
                try {
                    em.getTransaction().begin();
                    final Allowance myAllowance = em.merge((Allowance) o);
                    em.lock(em.merge(myAllowance.getResident()), LockModeType.OPTIMISTIC);
                    em.getTransaction().commit();

                    DateTime txDate = new DateTime(myAllowance.getPit());

                    final String keyResident = myAllowance.getResident().getRID();
                    final String keyYear = myAllowance.getResident().getRID() + "-" + txDate.getYear();
                    final String keyMonth = myAllowance.getResident().getRID() + "-" + txDate.getYear() + "-"
                            + txDate.getMonthOfYear();

                    if (!lstResidents.contains(myAllowance.getResident())) {
                        lstResidents.add(myAllowance.getResident());
                        Collections.sort(lstResidents);
                    }

                    if (!cashmap.containsKey(keyMonth)) {
                        cashmap.put(keyMonth,
                                AllowanceTools.getMonth(myAllowance.getResident(), myAllowance.getPit()));
                    } else {

                        if (cashmap.get(keyMonth).contains(myAllowance)) {
                            cashmap.get(keyMonth).remove(myAllowance);
                        }
                        cashmap.get(keyMonth).add(myAllowance);

                        Collections.sort(cashmap.get(keyMonth));
                    }

                    // little trick to fix the carries
                    if (editAmount != null) {
                        updateCarrySums(myAllowance.getResident(), new LocalDate(myAllowance.getPit()),
                                editAmount.negate());
                    }
                    // add the new / edited amount
                    updateCarrySums(myAllowance);

                    createCP4(myAllowance.getResident());

                    try {
                        if (cpMap.get(keyResident).isCollapsed())
                            cpMap.get(keyResident).setCollapsed(false);
                        if (cpMap.get(keyYear).isCollapsed())
                            cpMap.get(keyYear).setCollapsed(false);
                        if (cpMap.get(keyMonth).isCollapsed())
                            cpMap.get(keyMonth).setCollapsed(false);
                    } catch (PropertyVetoException e) {
                        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                    }

                    buildPanel();

                    GUITools.scroll2show(jspCash, cpMap.get(keyMonth), cpsCash, new Closure() {
                        @Override
                        public void execute(Object o) {
                            GUITools.flashBackground(linemap.get(myAllowance), Color.YELLOW, 2);
                        }
                    });

                } catch (OptimisticLockException ole) {
                    OPDE.warn(ole);
                    if (em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                        OPDE.getMainframe().emptyFrame();
                        OPDE.getMainframe().afterLogin();
                    }
                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                } catch (Exception e) {
                    if (em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                    OPDE.fatal(e);
                } finally {
                    em.close();
                }

            }
        }
    });
}

From source file:orc.lib.orchard.forms.DateTimeRangesField.java

License:Open Source License

private static String toTimeID(final DateTime date) {
    return date.getYear() + "_" + date.getMonthOfYear() + "_" + date.getDayOfMonth() + "_"
            + date.getHourOfDay();/*from w w w . j a  v a  2s . c  o  m*/
}

From source file:org.adl.datamodels.datatypes.DateTimeValidatorImpl.java

/**
 * Compares two valid data model elements for equality.
 * //from w w  w.  j  a  v  a  2 s. c o  m
 * @param iFirst  The first value being compared.
 * 
 * @param iSecond The second value being compared.
 * 
 * @param iDelimiters The common set of delimiters associated with the
 * values being compared.
 * 
 * @return Returns <code>true</code> if the two values are equal, otherwise
 *         <code>false</code>.
 */
@Override
public boolean compare(String iFirst, String iSecond, List<DMDelimiter> iDelimiters) {

    boolean equal = true;

    DateTimeFormatter dtp = ISODateTimeFormat.dateTimeParser();

    try {
        // Parse the first string and remove the sub-seconds
        DateTime dt1 = dtp.parseDateTime(iFirst);
        dt1 = new DateTime(dt1.getYear(), dt1.getMonthOfYear(), dt1.getDayOfMonth(), dt1.getHourOfDay(),
                dt1.getMinuteOfHour(), dt1.getSecondOfMinute(), 0);

        // Parse the second string and remove the sub-seconds
        DateTime dt2 = dtp.parseDateTime(iSecond);
        dt2 = new DateTime(dt2.getYear(), dt2.getMonthOfYear(), dt2.getDayOfMonth(), dt2.getHourOfDay(),
                dt2.getMinuteOfHour(), dt2.getSecondOfMinute(), 0);

        equal = dt1.equals(dt2);
    } catch (Exception e) {
        // String format error -- these cannot be equal
        equal = false;
    }

    return equal;
}

From source file:org.akop.crosswords.fragment.DatePickerFragment.java

License:Open Source License

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    DateTime dateTime = null;
    Bundle args = getArguments();//from w  w  w  . ja v  a  2  s. c o m
    if (args != null) {
        long dateMillis = args.getLong("dateMillis", -1);
        if (dateMillis != -1) {
            dateTime = new DateTime(dateMillis);
        }
    }

    if (dateTime == null) {
        dateTime = DateTime.now();
    }

    final DatePickerDialog pickerDialog = new DatePickerDialog(getActivity(),
            R.style.Theme_Crosswords_Default_Dialog, null, dateTime.getYear(), dateTime.getMonthOfYear() - 1,
            dateTime.getDayOfMonth());

    // Workaround for the JellyBean bug
    // http://stackoverflow.com/questions/11444238/jelly-bean-datepickerdialog-is-there-a-way-to-cancel
    pickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(android.R.string.ok),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    notifyListener(pickerDialog.getDatePicker());
                }
            });
    pickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(android.R.string.cancel),
            (DialogInterface.OnClickListener) null);

    return pickerDialog;
}