Example usage for org.joda.time.format DateTimeFormatter parseLocalDate

List of usage examples for org.joda.time.format DateTimeFormatter parseLocalDate

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter parseLocalDate.

Prototype

public LocalDate parseLocalDate(String text) 

Source Link

Document

Parses only the local date from the given text, returning a new LocalDate.

Usage

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

License:Open Source License

@Transactional
public void updateCustomer(Customer pojoCustomer, int prestashopId) {
    DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern("yyyy-MM-dd");
    LocalDate dateOfBirth = dateTimeFormat.parseLocalDate(pojoCustomer.getBirthday());
    Partner prestashopCustomer = Partner.filter("prestashopid=?", prestashopId).fetchOne();
    prestashopCustomer.setPrestashopid(prestashopId);
    prestashopCustomer.setFirstName(pojoCustomer.getFirstname());
    prestashopCustomer.setName(pojoCustomer.getLastname());
    prestashopCustomer.setFullName(pojoCustomer.getLastname() + " " + pojoCustomer.getFirstname());
    prestashopCustomer.setEmail(pojoCustomer.getEmail());
    prestashopCustomer.setCompany(pojoCustomer.getCompany());
    prestashopCustomer.setPassword(pojoCustomer.getPasswd());
    prestashopCustomer.setBirthdate(dateOfBirth);
    prestashopCustomer.setActive(BooleanUtils.toBoolean(pojoCustomer.getActive()));
    prestashopCustomer.setArchived(BooleanUtils.toBoolean(pojoCustomer.getDeleted()));
    System.out.println(pojoCustomer.getId_default_group());
    prestashopCustomer.setPrestashopCustomerGroup(
            PrestashopCustomerGroup.all().filter("id_group=?", pojoCustomer.getId_default_group()).fetchOne());
    System.out.println(prestashopCustomer.getPrestashopCustomerGroup().getId_group());
    System.out.println("ASSOCIATIONS : " + pojoCustomer.getAssociations());
    prestashopCustomer.save();/*w  w w .  j av a  2  s  . c om*/
}

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

License:Open Source License

@SuppressWarnings("null")
@Transactional/*from w w w .  ja  v  a  2s  . c  o m*/
public void insertCustomer(int customerId) {
    com.axelor.pojo.Customer pojoCustomer = getCustomer(customerId);
    Partner prestashopCustomer = new Partner();
    DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern("yyyy-MM-dd");
    LocalDate dateOfBirth = dateTimeFormat.parseLocalDate(pojoCustomer.getBirthday());
    // add this customer into ERP
    prestashopCustomer.setPrestashopid(customerId);
    prestashopCustomer.setFirstName(pojoCustomer.getFirstname());
    prestashopCustomer.setName(pojoCustomer.getLastname());
    prestashopCustomer.setFullName(pojoCustomer.getLastname() + " " + pojoCustomer.getFirstname());
    prestashopCustomer.setEmail(pojoCustomer.getEmail());
    prestashopCustomer.setCompany(pojoCustomer.getCompany());
    prestashopCustomer.setPassword(pojoCustomer.getPasswd());
    prestashopCustomer.setBirthdate(dateOfBirth);
    prestashopCustomer.setActive(BooleanUtils.toBoolean(pojoCustomer.getActive()));
    prestashopCustomer.setArchived(BooleanUtils.toBoolean(pojoCustomer.getDeleted()));
    System.out.println(pojoCustomer.getId_default_group());
    prestashopCustomer.setPrestashopCustomerGroup(
            PrestashopCustomerGroup.all().filter("id_group=?", pojoCustomer.getId_default_group()).fetchOne());
    System.out.println(prestashopCustomer.getPrestashopCustomerGroup().getId_group());
    System.out.println("ASSOCIATIONS : " + pojoCustomer.getAssociations());
    prestashopCustomer.save();
}

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   w  w w. j a v a  2s  .  co  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.example.weatherforecast.utils.JsonUtils.java

License:Open Source License

/**
 * Converts the date string from the jsonNode with the given key to a LocalDate.
 * @param jsonNode holding the date string for the given key
 * @param key key of the json node which value should contain the date string
 * @param dtf pattern that should match the date string in the json node
 * @return//w  w w  .  j  a  v  a2 s  .c o  m
 */
public static LocalDate localDateFromJsonNode(JsonNode jsonNode, String key, DateTimeFormatter dtf) {
    if (jsonNode == null)
        return null;
    JsonNode value = jsonNode.get(key);
    if (value == null)
        return null;
    return dtf.parseLocalDate(value.textValue());
}

From source file:com.fatboyindustrial.gsonjodatime.LocalDateConverter.java

License:Open Source License

/**
 * Gson invokes this call-back method during deserialization when it encounters a field of the
 * specified type. <p>//from w ww  .j av  a2 s .  c o  m
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link com.google.gson.JsonDeserializationContext#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type)} method to create objects
 * for any non-trivial field of the returned object. However, you should never invoke it on the
 * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
 * call-back method again).
 *
 * @param json The Json data being deserialized
 * @param typeOfT The type of the Object to deserialize to
 * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
 * @throws com.google.gson.JsonParseException if json is not in the expected format of {@code typeOfT}
 */
@Override
public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(PATTERN);
    return fmt.parseLocalDate(json.getAsString());
}

From source file:com.github.fauu.natrank.service.MatchDataImportServiceImpl.java

License:Open Source License

@Override
public ProcessedMatchData processMatchData(String rawMatchData) {
    ProcessedMatchData matchData = new ProcessedMatchData();
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd/MM/yyyy");

    int lineNo = 1;
    BufferedReader reader = new BufferedReader(new StringReader(rawMatchData));
    try {//from w w  w .  j  a  v a  2 s .c  om
        String line;
        while ((line = reader.readLine()) != null) {
            String[] splitLine = line.split(";");
            int numFields = splitLine.length;

            if (numFields == 6) {
                for (int i = 0; i < numFields; i++) {
                    if (splitLine[i] == null || splitLine[i].trim().length() == 0) {
                        MatchDataError error = new MatchDataError(lineNo, line,
                                MatchDataError.Type.ERROR_MISSING_FIELD);

                        matchData.getErrors().add(error);
                    }
                }

                ParsedRawMatchDatum match = new ParsedRawMatchDatum();
                LocalDate matchDate;
                try {
                    matchDate = dateTimeFormatter.parseLocalDate(splitLine[0]);
                } catch (IllegalArgumentException e) {
                    MatchDataError error = new MatchDataError(lineNo, line,
                            MatchDataError.Type.ERROR_INCORRECT_DATE_FORMAT);
                    matchData.getErrors().add(error);
                    e.printStackTrace();

                    matchDate = null;
                }

                String matchType = splitLine[1];
                String matchCity = splitLine[2];
                String matchTeam1 = splitLine[3];
                String matchTeam2 = splitLine[4];
                String matchResult = splitLine[5];

                Country team1Country = countryRepository.findByName(matchTeam1);
                Country team2Country = countryRepository.findByName(matchTeam2);
                if ((team1Country != null) && (team2Country != null)) {
                    List<Match> duplicates = matchRepository.findByDateAndTeam1AndTeam2(matchDate,
                            team1Country.getTeam(), team2Country.getTeam());
                    if (duplicates.size() > 0) {
                        continue;
                    }
                }

                match.setDate(matchDate);
                match.setType(matchType);
                match.setCity(matchCity);
                match.setTeam1(matchTeam1);
                match.setTeam2(matchTeam2);
                match.setResult(matchResult);

                matchData.getMatches().add(match);
            } else {
                MatchDataError error = new MatchDataError(lineNo, line,
                        MatchDataError.Type.ERROR_INCORRECT_LINE_FORMAT);

                matchData.getErrors().add(error);
            }

            lineNo++;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    if (matchData.getErrors().size() == 0) {
        List<String> existingCountryNames = countryRepository.findAllNames();
        Set<String> processedNewCountryNames = new HashSet<>();
        List<String> existingCityNames = cityRepository.findAllNames();
        Set<String> processedNewCityNames = new HashSet<>();
        List<String> existingMatchTypesFifaNames = matchTypeRepository.findAllFifaNames();
        Set<String> processedNewMatchTypeFifaNames = new HashSet<>();

        List<String> countryNamesTemp = new LinkedList<>();

        for (ParsedRawMatchDatum parsedRawMatchDatum : matchData.getMatches()) {
            String matchTypeFifaName = parsedRawMatchDatum.getType();
            if (!processedNewMatchTypeFifaNames.contains(matchTypeFifaName)
                    && !existingMatchTypesFifaNames.contains(matchTypeFifaName)) {
                MatchType newType = new MatchType();
                newType.setFifaName(matchTypeFifaName);

                processedNewMatchTypeFifaNames.add(matchTypeFifaName);
                matchData.getTypes().add(newType);
            }

            countryNamesTemp.add(parsedRawMatchDatum.getTeam1());
            countryNamesTemp.add(parsedRawMatchDatum.getTeam2());
            for (String countryName : countryNamesTemp) {
                if (!processedNewCountryNames.contains(countryName)
                        && !existingCountryNames.contains(countryName)) {
                    Country newCountry = new Country();
                    newCountry.setName(countryName);
                    newCountry.setPeriod(new Period());
                    newCountry.getPeriod().setFromDate(parsedRawMatchDatum.getDate());
                    List<CountryCode> matchingCountryCodes = countryCodeRepository
                            .findByCountryName(newCountry.getName());
                    String inferredCountryCode = "";
                    if (matchingCountryCodes.size() > 0) {
                        inferredCountryCode = matchingCountryCodes.get(0).getCode();
                    }
                    newCountry.setCode(inferredCountryCode);

                    processedNewCountryNames.add(newCountry.getName());
                    matchData.getCountries().add(newCountry);
                }
            }
            countryNamesTemp.clear();

            String cityName = parsedRawMatchDatum.getCity();
            if (!processedNewCityNames.contains(cityName) && !existingCityNames.contains(cityName)) {
                City newCity = new City();
                newCity.setName(cityName);

                CityCountryAssoc cityCountryAssoc = new CityCountryAssoc();
                cityCountryAssoc.setCity(newCity);
                cityCountryAssoc.setPeriod(new Period());
                cityCountryAssoc.getPeriod().setFromDate(parsedRawMatchDatum.getDate());

                newCity.getCityCountryAssocs().add(cityCountryAssoc);

                processedNewCityNames.add(cityName);
                matchData.getCities().add(newCity);
                matchData.getCitiesInferredCountryNames().add(parsedRawMatchDatum.getTeam1());
            }

        }
    }

    return matchData;
}

From source file:com.google.api.ads.adwords.awreporting.model.util.DateUtil.java

License:Open Source License

/**
 * Attempts to parse the given {@code String} to a {@code LocalDate} using one of the known
 * formatters./*from www  . j  a v  a  2  s .  com*/
 *
 * The attempt falls back to all the formatters, and if the format is unknown, {@code null} is
 * returned.
 *
 * @param timestamp the time stamp in {@code String} format.
 * @return the parsed {@code LocalDate}, or {@code null} in case that the format is unknown.
 */
public static LocalDate parseLocalDate(String timestamp) {
    if (timestamp != null) {
        for (DateTimeFormatter formatter : DateUtil.formatters) {
            try {
                return formatter.parseLocalDate(timestamp);
            } catch (IllegalArgumentException e) {
                // Silently skips to the next formatter.
            }
        }
    }
    return null;
}

From source file:com.manydesigns.elements.util.Util.java

License:Open Source License

public static DateTime parseDateTime(DateTimeFormatter dateTimeFormatter, String input, boolean withTime) {
    if (withTime) {
        return dateTimeFormatter.parseDateTime(input);
    } else {/*ww w  .j  av a2  s  .c  om*/
        LocalDate localDate = dateTimeFormatter.parseLocalDate(input);
        return localDate.toDateTimeAtStartOfDay();
    }
}

From source file:com.sandata.lab.common.utils.date.DateUtil.java

License:Open Source License

public static LocalDate formatEvvDateToLocalDate(String date) {
    try {//from  ww w  .j a v a  2 s . c  om
        final DateTimeFormatter dtf = DateTimeFormat.forPattern("MMddyyyy");
        return dtf.parseLocalDate(date);
    } catch (Exception e) {
        agencyExceptionLogger.info("formatEvvDateToLocalDate Exception" + e.toString());
        return null;
    }
}

From source file:com.simopuve.helper.POIHelper.java

public static Integer getMonthNumber(Date currentDate) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(currentDate);//  ww w  .j av a  2s . c om
    org.joda.time.format.DateTimeFormatter fmt = DateTimeFormat.forPattern("dd-MM-yyy");
    DateTime nowDate = fmt.parseLocalDate(
            cal.get(Calendar.DAY_OF_MONTH) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.YEAR))
            .toDateTimeAtCurrentTime();
    Months m = Months.monthsBetween(initDate, nowDate);
    return m.getMonths();
}