Example usage for org.joda.time LocalDate toDate

List of usage examples for org.joda.time LocalDate toDate

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public Date toDate() 

Source Link

Document

Get the date time as a java.util.Date.

Usage

From source file:op.controlling.PnlControlling.java

License:Open Source License

public static String getWounds(int monthsback, Closure progress) {
    StringBuilder html = new StringBuilder(1000);

    int p = -1;//from   w ww .j  a va2s .  c  o  m
    progress.execute(new Pair<Integer, Integer>(p, 100));

    LocalDate from = new LocalDate().minusMonths(monthsback).dayOfMonth().withMinimumValue();
    EntityManager em = OPDE.createEM();
    DateFormat df = DateFormat.getDateInstance();

    String jpql1 = " SELECT b FROM ResInfo b WHERE b.from > :from AND b.resident.adminonly <> 2 AND b.bwinfotyp.type = :type ORDER BY b.resident.rid, b.from DESC ";
    Query query1 = em.createQuery(jpql1);
    query1.setParameter("type", ResInfoTypeTools.TYPE_WOUNDS);
    query1.setParameter("from", from.toDate());
    ArrayList<QProcessElement> listVal = new ArrayList<QProcessElement>(query1.getResultList());

    String jpql2 = " " + " SELECT n FROM NReport n " + " JOIN n.commontags ct " + " WHERE n.pit > :from "
            + " AND n.resident.adminonly <> 2 " + " AND n.replacedBy IS NULL " + " AND ct.type = :type "
            + " ORDER BY n.resident.rid, n.pit DESC ";
    Query query2 = em.createQuery(jpql2);
    query2.setParameter("type", CommontagsTools.TYPE_SYS_WOUNDS);
    query2.setParameter("from", from.toDate());
    listVal.addAll(new ArrayList<QProcessElement>(query2.getResultList()));

    em.close();

    HashMap<Resident, ArrayList<QProcessElement>> listData = new HashMap<Resident, ArrayList<QProcessElement>>();
    for (QProcessElement element : listVal) {
        if (!listData.containsKey(element.getResident())) {
            listData.put(element.getResident(), new ArrayList<QProcessElement>());
        }
        listData.get(element.getResident()).add(element);
    }

    ArrayList<Resident> listResident = new ArrayList<Resident>(listData.keySet());
    Collections.sort(listResident);

    html.append(SYSConst.html_h1(SYSTools.xx("opde.controlling.nursing.wounds") + ": "
            + df.format(from.toDate()) + " &raquo;&raquo; " + df.format(new Date())));
    //        html.append(SYSConst.html_h2(SYSTools.xx("misc.msg.analysis") + ": " + );

    p = 0;

    for (Resident resident : listResident) {
        progress.execute(new Pair<Integer, Integer>(p, listResident.size()));
        p++;

        html.append(SYSConst.html_h2(ResidentTools.getTextCompact(resident)));

        StringBuffer table = new StringBuffer(1000);

        table.append(SYSConst.html_table_tr(
                SYSConst.html_table_th("misc.msg.Date") + SYSConst.html_table_th("misc.msg.details")));

        Collections.sort(listData.get(resident), new Comparator<QProcessElement>() {
            @Override
            public int compare(QProcessElement o1, QProcessElement o2) {
                return new Long(o1.getPITInMillis()).compareTo(new Long(o2.getPITInMillis())) * -1;
            }
        });

        for (QProcessElement element : listData.get(resident)) {
            table.append(SYSConst.html_table_tr(SYSConst.html_table_td(element.getPITAsHTML(), "left", "top")
                    + SYSConst.html_table_td(element.getContentAsHTML())));
        }

        html.append(SYSConst.html_table(table.toString(), "1"));
    }
    return html.toString();
}

From source file:op.tools.SYSCalendar.java

License:Open Source License

public static void handleDateFocusLost(FocusEvent evt, LocalDate min, LocalDate max) {
    LocalDate dt;
    if (max == null) {
        max = new LocalDate();
    }/* w  w w. ja v a2  s . co  m*/
    try {
        dt = new LocalDate(parseDate(((JTextField) evt.getSource()).getText()));
    } catch (NumberFormatException ex) {
        OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("misc.msg.wrongdate")));
        dt = new LocalDate();
    }
    if (dt.isAfter(max)) {
        dt = new LocalDate();
        DisplayMessage dm = new DisplayMessage(
                dt.isAfter(max) ? SYSTools.xx("misc.msg.futuredate") : SYSTools.xx("misc.msg.wrongdate"));
        OPDE.getDisplayManager().addSubMessage(dm);
    }
    if (dt.isBefore(min)) {
        dt = new LocalDate();
        OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("misc.msg.DateTooOld")));
    }

    ((JTextField) evt.getSource()).setText(DateFormat.getDateInstance().format(dt.toDate()));
}

From source file:org.activiti.dmn.engine.impl.mvel.extension.DateUtil.java

License:Apache License

public static Date toDate(String dateString) {

    if (StringUtils.isEmpty(dateString)) {
        throw new IllegalArgumentException("date string cannot be empty");
    }//from   ww  w.  ja v a2 s  . c  o  m

    DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd");
    LocalDate dateTime = dtf.parseLocalDate(dateString);

    return dateTime.toDate();
}

From source file:org.activiti.dmn.engine.impl.mvel.extension.DateUtil.java

License:Apache License

public static Date addDate(Date startDate, Integer years, Integer months, Integer days) {

    LocalDate currentDate = new LocalDate(startDate);

    currentDate = currentDate.plusYears(years);
    currentDate = currentDate.plusMonths(months);
    currentDate = currentDate.plusDays(days);

    return currentDate.toDate();
}

From source file:org.activiti.dmn.engine.impl.mvel.extension.DateUtil.java

License:Apache License

public static Date subtractDate(Date startDate, Integer years, Integer months, Integer days) {

    LocalDate currentDate = new LocalDate(startDate);

    currentDate = currentDate.minusYears(years);
    currentDate = currentDate.minusMonths(months);
    currentDate = currentDate.minusDays(days);

    return currentDate.toDate();
}

From source file:org.alexlg.bankit.controllers.AccountController.java

License:Open Source License

/**
 * Initialize binder to handle specific type.
 * @param binder Binder to initialize.//from  www  .j  a va2s.c om
 */
@InitBinder
public void binder(WebDataBinder binder) {
    final SimpleDateFormat dateFormatFull = new SimpleDateFormat("dd/MM/yyyy");
    final SimpleDateFormat dateFormatShort = new SimpleDateFormat("dd/MM");

    binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
        @Override
        public String getAsText() {
            if (getValue() == null)
                return "";
            return dateFormatFull.format((Date) getValue());
        }

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            //short format
            try {
                Date date = dateFormatShort.parse(text);
                //setting current year
                LocalDate lDate = new LocalDate(date).withYear(new LocalDate().getYear());
                setValue(lDate.toDate());
                return;
            } catch (ParseException e) {
                setValue(null);
            }
            //full format
            try {
                setValue(dateFormatFull.parse(text));
                return;
            } catch (ParseException e) {
                setValue(null);
            }
        }
    });
}

From source file:org.alexlg.bankit.controllers.AccountController.java

License:Open Source License

/**
 * Display operations list for history and future.
 * @param model Model to fill with operations list
 * @return view name// www  .  j  ava 2s .  co m
 */
@RequestMapping("/list")
@Transactional(readOnly = true)
public String list(@RequestParam(required = false) String startDate,
        @RequestParam(required = false) String endDate, ModelMap model) {

    //start/end date of operations displayed
    LocalDate startDay = null;
    LocalDate endDay = null;
    boolean buildFuture = false;

    //parse dates if present
    if (startDate != null)
        startDay = parseMonth(startDate);
    if (endDate != null)
        endDay = parseMonth(endDate);

    //select start/end day from parsing or default
    if (startDay == null)
        startDay = calculateFirstHistoDay();
    if (endDay == null) {
        endDay = new LocalDate();
        buildFuture = true;
    } else {
        //select the last day of the endMonth
        endDay = endDay.dayOfMonth().withMaximumValue();

        //force endDay to not go beyond today
        LocalDate today = new LocalDate();
        if (endDay.isAfter(today)) {
            endDay = today;
            buildFuture = true;
        }
    }

    //switch start/end if not in correct order
    if (startDay.isAfter(endDay)) {
        LocalDate tmp = endDay;
        endDay = startDay;
        startDay = tmp;
    }

    //getting history operations
    List<Operation> ops = operationDao.getHistory(startDay, endDay);

    //calculating balance for history
    //current balance
    BigDecimal current = operationDao.getBalanceHistory(startDay);
    //difference between planned and real
    BigDecimal currentDiff = new BigDecimal("0");
    //balance for planned op but not debited
    BigDecimal plannedWaiting = new BigDecimal("0");

    //checking if a balance exists or init the account
    if (current == null && ops.size() == 0) {
        return "redirect:/account/init";
    }

    if (current == null)
        current = new BigDecimal("0");
    BigDecimal initialBalance = current;

    //calculating total for old operations
    for (Operation op : ops) {
        BigDecimal amount = op.getAmount();
        BigDecimal planned = op.getPlanned();

        if (amount != null) {
            //operation done
            current = current.add(amount);
            op.setTotal(current);
            if (planned != null) {
                currentDiff = currentDiff.add(amount).subtract(planned);
            }
        }
    }

    //calculating total for planned undebit operations
    for (Operation op : ops) {
        if (op.getAmount() == null) {
            plannedWaiting = plannedWaiting.add(op.getPlanned());
            op.setTotal(current.add(plannedWaiting));
        }
    }

    if (buildFuture) {
        //getting future operations
        Set<MonthOps> futureOps = buildFutureOps(endDay, operationDao.getFuture(endDay), costDao.getList(),
                current.add(plannedWaiting), NB_FUTURE_MONTH);

        model.put("futureOps", futureOps);
    }

    model.put("startDay", startDay.toDate());
    model.put("endDay", endDay.toDate());
    model.put("ops", ops);
    model.put("current", current);
    model.put("currentDiff", currentDiff);
    model.put("periodBalance", current.subtract(initialBalance));
    model.put("plannedWaiting", plannedWaiting);
    model.put("currentWaiting", current.add(plannedWaiting));
    model.put("lastSyncDate", optionsService.getDate(SyncService.OP_SYNC_OPT));
    model.put("categories", categoryDao.getList());
    //get categories summary (for previous and current month)
    model.put("categoriesSummary", buildCategories(startDay, endDay));

    return "account/list";
}

From source file:org.alexlg.bankit.controllers.AccountController.java

License:Open Source License

/**
 * Init accout by adding initial amount operation
 * @param model Model to fill with current operation object
 * @return View/* www  .ja v a2 s. c o  m*/
 */
@RequestMapping(value = "/init", method = RequestMethod.GET)
public String initAccount(ModelMap model) {
    //creating the init operation, one month before
    Operation op = new Operation();
    LocalDate date = new LocalDate();
    op.setOperationDate(date.toDate());
    op.setLabel("Solde initial");

    model.addAttribute("operation", op);
    return "account/init";
}

From source file:org.alexlg.bankit.controllers.AccountController.java

License:Open Source License

/**
 * Build a set of MonthOps for all future ops : "manual" or costs (beyond 2 days of current)
 * @param day Current day/* w ww .jav a  2s .c  o  m*/
 * @param futurePlannedOps List of manual future operations
 * @param costs List of costs
 * @param balance Start balance
 * @param nbMonth Number of month to build in addition to the current month.
 * @return A set of MonthOps for each month planned
 */
protected Set<MonthOps> buildFutureOps(LocalDate day, List<Operation> futurePlannedOps, List<Cost> costs,
        BigDecimal balance, int nbMonth) {

    Set<MonthOps> futureOps = new TreeSet<MonthOps>();
    //going through all months
    for (int i = 0; i < nbMonth + 1; i++) {
        LocalDate monthDate = day.monthOfYear().addToCopy(i);
        int lastDayOfMonth = monthDate.dayOfMonth().getMaximumValue();

        MonthOps monthOps = new MonthOps(monthDate, balance);
        futureOps.add(monthOps);

        //adding "manual" operation of the current month
        if (futurePlannedOps.size() > 0) {
            //loop an add all operation of the month
            for (Operation op : futurePlannedOps) {
                if (new LocalDate(op.getOperationDate()).getMonthOfYear() == monthDate.getMonthOfYear()) {
                    op.setAuto(false);
                    monthOps.addOp(op);
                }
            }
        }

        //adding costs of the current month
        LocalDate costStartDay = day.plusDays(2);
        for (Cost cost : costs) {
            int costDay = cost.getDay();

            //if the operation is planned after the last day of month
            //set it to the last day
            if (costDay > lastDayOfMonth)
                costDay = lastDayOfMonth;

            LocalDate opDate = new LocalDate(monthDate.getYear(), monthDate.getMonthOfYear(), costDay);
            //checking if we add the cost (the date is after current+2)
            if (opDate.isAfter(costStartDay)) {
                Operation op = new Operation();
                //setting a fake id for comparison (as we put the operation in the set)
                op.setOperationId(cost.getCostId() + i);
                op.setOperationDate(opDate.toDate());
                op.setPlanned(cost.getAmount());
                op.setLabel(cost.getLabel());
                op.setCategory(cost.getCategory());
                op.setAuto(true);
                monthOps.addOp(op);
            }
        }

        //saving current balance for next monthOp
        balance = monthOps.getBalance();
    }
    return futureOps;
}

From source file:org.alexlg.bankit.dao.CategoryDao.java

License:Open Source License

/**
 * Calculate the amount of operations for all categories on a specific month
 * @param yearMonth Year and month of the summary to calculate
 * @return Map containing the Category and the amount for the month
 *//*  w ww . j a  va  2s . c o  m*/
public Map<Category, BigDecimal> getMonthSummary(YearMonth yearMonth) {
    CriteriaBuilder b = getBuilder();

    //SELECT PASSED OPERATION
    //create criteria and join
    CriteriaQuery<Tuple> q = b.createTupleQuery();
    Root<Operation> operation = q.from(Operation.class);
    //we left join to get operation with no categories
    Join<Operation, Category> category = operation.join(Operation_.category, JoinType.LEFT);

    //select
    //sum all amount operation for operation imported from the bank
    Expression<BigDecimal> sum = b.sum(operation.get(Operation_.amount));

    //sum only planned amount if the amount is not set (as we have a planned operation)
    //we use a sum(case when xx end) for that
    //in sql, it will be translated into : sum(case when o.amount is null then o.planned otherwise 0 end)
    Expression<BigDecimal> sumPlanned = b.sum(b.<BigDecimal>selectCase()
            .when(b.isNull(operation.get(Operation_.amount)), operation.get(Operation_.planned))
            .otherwise(BigDecimal.ZERO));

    //select the 3 fields into a tuple
    q.select(b.tuple(category, sum, sumPlanned));

    //where clause : between the start/end date, and for operation with no category, only < 0
    LocalDate startDate = yearMonth.toLocalDate(1);
    LocalDate endDate = startDate.withDayOfMonth(startDate.dayOfMonth().getMaximumValue());
    q.where(b.between(operation.get(Operation_.operationDate), startDate.toDate(), endDate.toDate()),
            b.or(b.isNotNull(operation.get(Operation_.category)), b.lt(operation.get(Operation_.amount), 0),
                    b.lt(operation.get(Operation_.planned), 0)));

    //group by
    q.groupBy(category.get(Category_.categoryId));

    //order by
    q.orderBy(b.asc(category.get(Category_.name)));

    //execute query
    List<Tuple> results = getEm().createQuery(q).getResultList();

    //put in map
    Map<Category, BigDecimal> resMap = new LinkedHashMap<Category, BigDecimal>(results.size());
    //saving null category for adding at the end
    BigDecimal noCatAmount = null;
    for (Tuple res : results) {
        Category resCat = res.get(category);

        BigDecimal sumVal = res.get(sum);
        BigDecimal sumPlannedVal = res.get(sumPlanned);
        if (sumVal == null)
            sumVal = BigDecimal.ZERO;
        if (sumPlannedVal == null)
            sumPlannedVal = BigDecimal.ZERO;
        BigDecimal sumTotal = sumVal.add(sumPlannedVal);

        if (!sumTotal.equals(BigDecimal.ZERO)) {
            if (resCat != null) {
                resMap.put(resCat, sumTotal);
            } else {
                noCatAmount = sumTotal;
            }
        }
    }

    //adding operation with no categories at the end of the list
    if (noCatAmount != null) {
        Category noCat = new Category();
        noCat.setCategoryId(-1);
        noCat.setName("");
        resMap.put(noCat, noCatAmount);
    }

    return resMap;
}