Example usage for org.joda.time LocalDate LocalDate

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

Introduction

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

Prototype

public LocalDate(Object instant) 

Source Link

Document

Constructs an instance from an Object that represents a datetime.

Usage

From source file:com.axelor.apps.hr.service.leave.LeaveService.java

License:Open Source License

public BigDecimal computeLeaveDaysByLeaveRequest(LocalDate fromDate, LocalDate toDate,
        LeaveRequest leaveRequest, Employee employee) throws AxelorException {
    BigDecimal leaveDays = BigDecimal.ZERO;
    WeeklyPlanning weeklyPlanning = employee.getPlanning();
    if (leaveRequest.getDateFrom().equals(fromDate)) {
        leaveDays = leaveDays.add(new BigDecimal(
                this.computeStartDateWithSelect(fromDate, leaveRequest.getStartOnSelect(), weeklyPlanning)));
    }/*  ww  w.  j a  v  a  2 s  . c om*/
    if (leaveRequest.getDateTo().equals(toDate)) {
        leaveDays = leaveDays.add(new BigDecimal(
                this.computeEndDateWithSelect(toDate, leaveRequest.getEndOnSelect(), weeklyPlanning)));
    }

    LocalDate itDate = new LocalDate(fromDate);
    if (fromDate.isBefore(leaveRequest.getDateFrom()) || fromDate.equals(leaveRequest.getDateFrom())) {
        itDate = new LocalDate(leaveRequest.getDateFrom().plusDays(1));
    }

    while (!itDate.isEqual(leaveRequest.getDateTo()) && !itDate.isAfter(toDate)) {
        leaveDays = leaveDays
                .add(new BigDecimal(weeklyPlanningService.workingDayValue(weeklyPlanning, itDate)));
        if (publicHolidayService.checkPublicHolidayDay(itDate, employee)) {
            leaveDays = leaveDays.subtract(BigDecimal.ONE);
        }
        itDate = itDate.plusDays(1);
    }

    return leaveDays;
}

From source file:com.axelor.apps.hr.service.leave.LeaveService.java

License:Open Source License

@Transactional
public void insertLeave(ActionRequest request, ActionResponse response) throws AxelorException {
    User user = AuthUtils.getUser();/* w w  w  .  j a  v  a2  s.  c o  m*/
    LeaveReason leaveReason = Beans.get(LeaveReasonRepository.class)
            .find(new Long(request.getData().get("reason").toString()));

    if (user != null && leaveReason != null) {
        LeaveRequest leave = new LeaveRequest();
        leave.setUser(user);
        leave.setCompany(user.getActiveCompany());
        leave.setReason(leaveReason);
        leave.setRequestDate(Beans.get(GeneralService.class).getTodayDate());
        leave.setDateFrom(new LocalDate(request.getData().get("fromDate").toString()));
        leave.setStartOnSelect(new Integer(request.getData().get("startOn").toString()));
        leave.setDateTo(new LocalDate(request.getData().get("toDate").toString()));
        leave.setEndOnSelect(new Integer(request.getData().get("endOn").toString()));
        leave.setDuration(this.computeDuration(leave));
        leave.setStatusSelect(LeaveRequestRepository.STATUS_SELECT_AWAITING_VALIDATION);
        if (request.getData().get("comment") != null) {
            leave.setComments(request.getData().get("comment").toString());
        }
        Beans.get(LeaveRequestRepository.class).save(leave);
    }
}

From source file:com.axelor.apps.hr.service.timesheet.TimesheetServiceImp.java

License:Open Source License

@Transactional
public void insertTSLine(ActionRequest request, ActionResponse response) {

    User user = AuthUtils.getUser();//w w w .ja  v a  2s.c om
    ProjectTask projectTask = Beans.get(ProjectTaskRepository.class)
            .find(new Long(request.getData().get("project").toString()));
    Product product = Beans.get(ProductRepository.class)
            .find(new Long(request.getData().get("activity").toString()));
    LocalDate date = new LocalDate(request.getData().get("date").toString());
    if (user != null) {
        Timesheet timesheet = Beans.get(TimesheetRepository.class).all()
                .filter("self.statusSelect = 1 AND self.user.id = ?1", user.getId()).order("-id").fetchOne();
        if (timesheet == null) {
            timesheet = new Timesheet();
            timesheet.setUser(user);
            timesheet.setCompany(user.getActiveCompany());
            timesheet.setFromDate(date);
            timesheet.setToDate(date);
            timesheet.setStatusSelect(TimesheetRepository.STATUS_DRAFT);
        }
        TimesheetLine timesheetLine = new TimesheetLine();
        timesheetLine.setDate(date);
        timesheetLine.setComments(request.getData().get("comments").toString());
        timesheetLine.setProduct(product);
        timesheetLine.setProjectTask(projectTask);
        timesheetLine.setUser(user);
        timesheetLine.setToInvoice(new Boolean(request.getData().get("toInvoice").toString()));
        BigDecimal durationHours = new BigDecimal(Hours
                .hoursBetween(new LocalTime(0, 0), new LocalTime(request.getData().get("duration").toString()))
                .getHours());
        timesheetLine.setDurationStored(durationHours);
        timesheetLine.setVisibleDuration(durationHours);
        timesheet.addTimesheetLineListItem(timesheetLine);

        Beans.get(TimesheetRepository.class).save(timesheet);
    }
}

From source file:com.axelor.apps.hr.service.timesheet.TimesheetServiceImpl.java

License:Open Source License

@Transactional
public void insertTSLine(ActionRequest request, ActionResponse response) {

    User user = AuthUtils.getUser();// w w w  .java2s  . co  m
    ProjectTask projectTask = Beans.get(ProjectTaskRepository.class)
            .find(new Long(request.getData().get("project").toString()));
    Product product = Beans.get(ProductRepository.class)
            .find(new Long(request.getData().get("activity").toString()));
    LocalDate date = new LocalDate(request.getData().get("date").toString());
    if (user != null) {
        Timesheet timesheet = Beans.get(TimesheetRepository.class).all()
                .filter("self.statusSelect = 1 AND self.user.id = ?1", user.getId()).order("-id").fetchOne();
        if (timesheet == null) {
            timesheet = createTimesheet(user, date, date);
        }
        BigDecimal minutes = new BigDecimal(Minutes.minutesBetween(new LocalTime(0, 0),
                new LocalTime(request.getData().get("duration").toString())).getMinutes());
        createTimesheetLine(projectTask, product, user, date, timesheet, minutes,
                request.getData().get("comments").toString());

        Beans.get(TimesheetRepository.class).save(timesheet);
    }
}

From source file:com.axelor.apps.hr.web.expense.ExpenseController.java

License:Open Source License

@Transactional
public void insertKMExpenses(ActionRequest request, ActionResponse response) {
    User user = AuthUtils.getUser();/*from   w  ww.  ja v a 2 s . c om*/
    if (user != null) {
        Expense expense = Beans.get(ExpenseRepository.class).all()
                .filter("self.statusSelect = 1 AND self.user.id = ?1", user.getId()).order("-id").fetchOne();
        if (expense == null) {
            expense = new Expense();
            expense.setUser(user);
            expense.setCompany(user.getActiveCompany());
            expense.setStatusSelect(TimesheetRepository.STATUS_DRAFT);
        }
        ExpenseLine expenseLine = new ExpenseLine();
        expenseLine.setDistance(new BigDecimal(request.getData().get("kmNumber").toString()));
        expenseLine.setFromCity(request.getData().get("locationFrom").toString());
        expenseLine.setToCity(request.getData().get("locationTo").toString());
        expenseLine
                .setKilometricTypeSelect(new Integer(request.getData().get("allowanceTypeSelect").toString()));
        expenseLine.setComments(request.getData().get("comments").toString());
        expenseLine.setExpenseDate(new LocalDate(request.getData().get("date").toString()));
        if (user.getEmployee() != null && user.getEmployee().getKilometricAllowParam() != null) {
            expenseLine.setKilometricAllowParam(user.getEmployee().getKilometricAllowParam());
            KilometricAllowanceRate kilometricAllowanceRate = Beans.get(KilometricAllowanceRateRepository.class)
                    .findByVehicleKillometricAllowanceParam(user.getEmployee().getKilometricAllowParam());
            if (kilometricAllowanceRate != null) {
                BigDecimal rate = kilometricAllowanceRate.getRate();
                if (rate != null) {
                    expenseLine.setTotalAmount(rate.multiply(expenseLine.getDistance()));
                }
            }
        }

        expense.addExpenseLineListItem(expenseLine);

        Beans.get(ExpenseRepository.class).save(expense);
    }
}

From source file:com.axelor.apps.hr.web.timesheet.TimesheetController.java

License:Open Source License

public void generateLines(ActionRequest request, ActionResponse response) throws AxelorException {
    Timesheet timesheet = request.getContext().asType(Timesheet.class);
    Context context = request.getContext();

    LocalDate fromGenerationDate = null;
    if (context.get("fromGenerationDate") != null)
        fromGenerationDate = new LocalDate(context.get("fromGenerationDate"));
    LocalDate toGenerationDate = null;
    if (context.get("toGenerationDate") != null)
        toGenerationDate = new LocalDate(context.get("toGenerationDate"));
    BigDecimal logTime = BigDecimal.ZERO;
    if (context.get("logTime") != null)
        logTime = new BigDecimal(context.get("logTime").toString());

    Map<String, Object> projectTaskContext = (Map<String, Object>) context.get("projectTask");
    ProjectTask projectTask = ProjectTaskRepo.find(((Integer) projectTaskContext.get("id")).longValue());

    Map<String, Object> productContext = (Map<String, Object>) context.get("product");
    Product product = null;//w ww .j  ava 2s  .  c  o  m
    if (productContext != null)
        product = productRepo.find(((Integer) productContext.get("id")).longValue());

    timesheet = timesheetService.generateLines(timesheet, fromGenerationDate, toGenerationDate, logTime,
            projectTask, product);
    response.setValue("timesheetLineList", timesheet.getTimesheetLineList());
}

From source file:com.axelor.apps.stock.web.LocationController.java

License:Open Source License

public void createInventory(ActionRequest request, ActionResponse response) throws Exception {
    Context context = request.getContext();
    LocalDate date = new LocalDate(context.get("inventoryDate"));
    String description = (String) context.get("description");

    boolean excludeOutOfStock = (Boolean) context.get("excludeOutOfStock");
    boolean includeObsolete = (Boolean) context.get("includeObsolete");

    // Rcupration de l'entrepot
    Map<String, Object> locationContext = (Map<String, Object>) context.get("location");

    Location location = null;//from   w  w  w  . j a  v  a 2  s .c o m

    if (locationContext != null) {
        location = locationRepo.find(((Integer) locationContext.get("id")).longValue());
    }

    // Rcupration de la famille de produit
    Map<String, Object> productFamilyContext = (Map<String, Object>) context.get("productFamily");

    ProductFamily productFamily = null;

    if (productFamilyContext != null) {
        productFamily = Beans.get(ProductFamilyRepository.class)
                .find(((Integer) productFamilyContext.get("id")).longValue());
    }

    // Rcupration de la catgorie de produit
    Map<String, Object> productCategoryContext = (Map<String, Object>) context.get("productCategory");

    ProductCategory productCategory = null;

    if (productCategoryContext != null) {
        productCategory = Beans.get(ProductCategoryRepository.class)
                .find(((Integer) productCategoryContext.get("id")).longValue());
    }

    Inventory inventory = inventoryService.createInventoryFromWizard(date, description, location,
            excludeOutOfStock, includeObsolete, productFamily, productCategory);
    response.setValue("inventoryId", inventory.getId());
}

From source file:com.axelor.controller.RetrievePrestrashopOrders.java

License:Open Source License

@Transactional
public void insertOrders(int prestashopOrderId) {
    System.out.println("Setting Default values...");
    com.axelor.pojo.Orders pojoOrder = new com.axelor.pojo.Orders();
    // SET DEFAULT VALUES
    pojoOrder.setPrestashopOrderId(0);//from  ww w .  j  av  a 2 s .  c  o  m
    pojoOrder.setId_address_delivery(0);
    pojoOrder.setId_address_invoice(0);
    pojoOrder.setId_cart(0);
    pojoOrder.setId_currency(0);
    pojoOrder.setId_lang(0);
    pojoOrder.setId_customer(0);
    pojoOrder.setId_carrier(0);
    pojoOrder.setCurrent_state(0);
    pojoOrder.setModule("cashondelivery");
    pojoOrder.setInvoice_date("1970-01-01");
    pojoOrder.setPayment("Cash on delivery (COD)");
    pojoOrder.setDate_add("1970-01-01");
    pojoOrder.setTotal_paid(new BigDecimal("00.00"));
    pojoOrder.setTotal_paid_tax_excl(new BigDecimal("00.00"));
    pojoOrder.setReference("REFERENCE");
    pojoOrder.setCompany(0);
    pojoOrder.setAssociations("associations");
    System.out.println("INserting............");
    try {
        URL url = new URL("http://localhost/client-lib/crud/action.php?resource=orders&action=retrieve&id="
                + prestashopOrderId + "&Akey=" + apiKey);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        JAXBContext jaxbContext = JAXBContext.newInstance(com.axelor.pojo.Orders.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        OutputStream outputStream = connection.getOutputStream();
        jaxbMarshaller.marshal(pojoOrder, outputStream);
        connection.connect();

        //InputStream inputStream = connection.getInputStream();
        //Scanner scan = new Scanner(inputStream);
        //String temp="";

        //         while (scan.hasNext()) {
        //            temp += scan.nextLine();            
        //         }
        //         scan.close();
        //   System.out.println(temp);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        pojoOrder = (com.axelor.pojo.Orders) jaxbUnmarshaller
                .unmarshal(new UnmarshalInputStream(connection.getInputStream()));

        SalesOrder prestashopSaleOrder = new SalesOrder();

        //Resolve invoiceFirstDAte and creationDate
        DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate invoiceFirstDate;
        LocalDate creationDate;
        try {
            invoiceFirstDate = dateTimeFormat.parseLocalDate(pojoOrder.getInvoice_date());
        } catch (IllegalFieldValueException e) {
            invoiceFirstDate = new LocalDate("1970-01-01");
        }
        creationDate = dateTimeFormat.parseLocalDate(pojoOrder.getDate_add());

        //Resolve Address

        Address baseAddress = Address.all().filter("prestashopid=?", pojoOrder.getId_address_delivery())
                .fetchOne();

        //Resolve Currency
        Currency baseCurrency = Currency.all().filter("prestashop_currency_id=?", pojoOrder.getId_currency())
                .fetchOne();

        //Resolve Partner
        Partner basePartner = Partner.all().filter("prestashopid=?", pojoOrder.getId_customer()).fetchOne();

        if (baseAddress == null || basePartner == null)
            return;
        System.out.println("Currency :: " + baseCurrency.getPrestashopCurrencyId());
        //Resolve Total Tax
        BigDecimal totalPaid, totalPaidExcl, totalTax;
        totalPaid = pojoOrder.getTotal_paid();
        totalPaidExcl = pojoOrder.getTotal_paid_tax_excl();
        totalTax = totalPaid.subtract(totalPaidExcl);

        //Resolve Current State / status_select
        int statusSelect;
        int prestashopCurentState = pojoOrder.getCurrent_state();
        switch (prestashopCurentState) {
        case 1:
        case 3:
        case 10:
        case 11:
            statusSelect = 1; //assign draft to statusSelect
            break;
        case 2:
        case 12:
            statusSelect = 2; //assign confirmed to statusSelect
            break;
        case 4:
        case 5:
        case 7:
        case 9:
            statusSelect = 3; //assign validated to statusSelect
            break;
        case 6:
        case 8:
            statusSelect = 4; //assign cancelled to statusSelect
            break;
        default:
            statusSelect = 0; //assign Error to statusSelect
        }

        //Resolve Payment Mode
        int erpPaymentMode = 0;
        String paymentMode = pojoOrder.getModule();
        if (paymentMode.equals("cashondelivery"))
            erpPaymentMode = 4;
        else if (paymentMode.equals("cheque"))
            erpPaymentMode = 6;
        else if (paymentMode.equals("bankwire"))
            erpPaymentMode = 8;
        PaymentMode basePaymentMode = PaymentMode.all().filter("id=?", erpPaymentMode).fetchOne();

        //Resolve Company, currently set to static value(1)
        Company baseCompany = Company.find(1L);

        // add this order into ERP
        prestashopSaleOrder.setPrestashopOrderId(prestashopOrderId);
        prestashopSaleOrder.setDeliveryAddress(baseAddress);
        prestashopSaleOrder.setMainInvoicingAddress(baseAddress);
        prestashopSaleOrder.setPrestashopCartId(pojoOrder.getId_cart());
        prestashopSaleOrder.setCurrency(baseCurrency);
        prestashopSaleOrder.setClientPartner(basePartner);
        prestashopSaleOrder.setPrestashopCarrierId(pojoOrder.getId_carrier());
        prestashopSaleOrder.setStatusSelect(statusSelect);
        prestashopSaleOrder.setPaymentMode(basePaymentMode);
        prestashopSaleOrder.setInvoicedFirstDate(invoiceFirstDate);
        prestashopSaleOrder.setPrestashopPayment(pojoOrder.getPayment());
        prestashopSaleOrder.setCreationDate(creationDate);
        prestashopSaleOrder.setTaxTotal(totalTax);
        prestashopSaleOrder.setInTaxTotal(pojoOrder.getTotal_paid());
        prestashopSaleOrder.setExTaxTotal(pojoOrder.getTotal_paid_tax_excl());
        prestashopSaleOrder.setExternalReference(pojoOrder.getReference());
        prestashopSaleOrder.setCompany(baseCompany);
        prestashopSaleOrder.save();
        String salesOrders = pojoOrder.getAssociations();
        System.out.println("POJO ASDS ::" + salesOrders);

        String association = "";
        int count = 0;
        Pattern associationsPattern = Pattern.compile("^count:(.*?);(.*?)/associations");
        Matcher associationsMatcher = associationsPattern.matcher(salesOrders);
        while (associationsMatcher.find()) {
            count = Integer.parseInt(associationsMatcher.group(1));
            association = associationsMatcher.group(2);
        }

        System.out.println("COUNT :: " + count);
        System.out.println("ASSO :: " + association);
        String[] salesOrderLineArray = new String[count];
        String[] salesOrderLine = new String[8];
        salesOrderLineArray = association.split(":::");
        for (int i = 0; i < salesOrderLineArray.length; i++) {
            System.out.println("ARRAY :: " + salesOrderLineArray[i]);
            salesOrderLine = salesOrderLineArray[i].split(";;;");

            BigDecimal price = new BigDecimal(salesOrderLine[5]);
            BigDecimal qty = new BigDecimal(salesOrderLine[3]);
            BigDecimal exTaxTotal = price.multiply(qty);

            SalesOrderLine orderLines = new SalesOrderLine();
            orderLines.setCompanyExTaxTotal(exTaxTotal);
            orderLines.setExTaxTotal(exTaxTotal);
            orderLines.setPrice(price);
            orderLines.setProductName(salesOrderLine[4]);
            orderLines.setQty(qty);
            orderLines.setSaleSupplySelect(1);
            orderLines.setSequence(i + 1);
            orderLines.setPrestashopSalesOrderLineId(Integer.parseInt(salesOrderLine[0]));
            orderLines.setTaxLine(TaxLine.find(1L));
            orderLines.setUnit(Unit.find(1L));

            orderLines.setSalesOrder(SalesOrder.find(prestashopSaleOrder.getId()));

            Product productOfSalesOrderLine = Product.all()
                    .filter("prestashopProductId=?", Integer.parseInt(salesOrderLine[1])).fetchOne();
            if (productOfSalesOrderLine != null) {
                System.out.println("Saving");
                orderLines.setProduct(productOfSalesOrderLine);
                orderLines.save();
            } else {
                System.out.println("Product is removed from prestashop.");
            }
            System.out.println("PRODUCT2 :: " + salesOrderLine[2]);
            System.out.println("PRODUCT3 :: " + salesOrderLine[3]);
            System.out.println("PRODUCT4 :: " + salesOrderLine[4]);
        }

    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.battlelancer.seriesguide.util.TimeTools.java

License:Apache License

/**
 * Calculates the current release date time. Adjusts for time zone effects on release time, e.g.
 * delays between time zones (e.g. in the United States) and DST. Adjusts for user-defined
 * offset./*from   w ww .jav  a  2s.c  om*/
 *
 * @param time See {@link #getShowReleaseTime(int)}.
 * @return The date is today or on the next day matching the given week day.
 */
public static Date getShowReleaseDateTime(@NonNull Context context, @NonNull LocalTime time, int weekDay,
        @Nullable String timeZone, @Nullable String country) {
    // determine show time zone (falls back to America/New_York)
    DateTimeZone showTimeZone = getDateTimeZone(timeZone);

    // create current date in show time zone, set local show release time
    LocalDateTime localDateTime = new LocalDate(showTimeZone).toLocalDateTime(time);

    // adjust day of week so datetime is today or within the next week
    // for daily shows (weekDay == 0) just use the current day
    if (weekDay >= 1 && weekDay <= 7) {
        // joda tries to preserve week
        // so if we want a week day earlier in the week, advance by 7 days first
        if (weekDay < localDateTime.getDayOfWeek()) {
            localDateTime = localDateTime.plusWeeks(1);
        }
        localDateTime = localDateTime.withDayOfWeek(weekDay);
    }

    localDateTime = handleHourPastMidnight(country, localDateTime);
    localDateTime = handleDstGap(showTimeZone, localDateTime);

    DateTime dateTime = localDateTime.toDateTime(showTimeZone);

    // handle time zone effects on release time for US shows (only if device is set to US zone)
    String localTimeZone = TimeZone.getDefault().getID();
    if (localTimeZone.startsWith(TIMEZONE_ID_PREFIX_AMERICA)) {
        dateTime = applyUnitedStatesCorrections(country, localTimeZone, dateTime);
    }

    dateTime = applyUserOffset(context, dateTime);

    return dateTime.toDate();
}

From source file:com.baulsupp.kolja.util.LocalDatePropertyEditor.java

License:Open Source License

public void setAsText(String text) throws IllegalArgumentException {
    setValue(new LocalDate(text));
}