Example usage for org.apache.ibatis.session SqlSession rollback

List of usage examples for org.apache.ibatis.session SqlSession rollback

Introduction

In this page you can find the example usage for org.apache.ibatis.session SqlSession rollback.

Prototype

void rollback();

Source Link

Document

Discards pending batch statements and rolls database connection back.

Usage

From source file:net.cbtltd.rest.AbstractReservationExt.java

/**
 * Gets the download./*from  ww w .  j a va 2  s .c  o  m*/
 *
 * @param pos the pos
 * @param xsl the xsl
 * @return the download
 */
protected static Downloads getDownload(String pos, String xsl) {

    Date timestamp = new Date();
    String message = "/reservation/download/" + "?pos=" + pos + "&xsl=" + xsl;
    LOG.debug(message);
    SqlSession sqlSession = RazorServer.openSession();
    Downloads result = null;
    try {
        String organizationid = Constants.decryptPos(pos);
        ArrayList<Download> downloads = sqlSession.getMapper(ReservationMapper.class).download(organizationid);
        //LOG.debug("downloads " + downloads);
        if (downloads == null || downloads.isEmpty()) {
            throw new ServiceException(Error.reservation_download, organizationid);
        }
        result = new Downloads(message, downloads, xsl);
        for (Download download : downloads) {
            RelationService.load(sqlSession, Downloaded.RESERVATION_DOWNLOAD, download.getReservationid(),
                    organizationid);
        }
        sqlSession.commit();
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(message + "\n" + x.getMessage());
        result = new Downloads(message + " " + x.getMessage(), null, xsl);
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractReservationExt.java

/**
 * Gets the downloads.//from   w ww .  j  a  v a  2s . com
 *
 * @param pos the pos
 * @param xsl the xsl
 * @return the downloads
 */
protected static Downloads getDownloads(String pos, String xsl) {

    Date timestamp = new Date();
    String message = "/reservation/downloads/" + "?pos=" + pos + "&xsl=" + xsl;
    LOG.debug(message);
    SqlSession sqlSession = RazorServer.openSession();
    Downloads result = null;
    try {
        String organizationid = Constants.decryptPos(pos);
        ArrayList<Download> downloads = sqlSession.getMapper(ReservationMapper.class).downloads(organizationid);
        if (downloads == null || downloads.isEmpty()) {
            throw new ServiceException(Error.reservation_download, organizationid);
        }
        result = new Downloads(message, downloads, xsl);
        for (Download download : downloads) {
            RelationService.load(sqlSession, Downloaded.RESERVATION_DOWNLOAD, download.getReservationid(),
                    organizationid);
        }
        sqlSession.commit();
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(message + "\n" + x.getMessage());
        result = new Downloads(message + " " + x.getMessage(), null, xsl);
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractReservationExt.java

/**
 * Gets the uploads./* w  ww  .  jav a2s. c  o m*/
 *
 * @param pos the pos
 * @param xsl the xsl
 * @return the uploads
 */
protected static Downloads getUploads(String pos, String xsl) {

    Date timestamp = new Date();
    String message = "/reservation/uploads/" + "?pos=" + pos + "&xsl=" + xsl;
    LOG.debug(message);
    SqlSession sqlSession = RazorServer.openSession();
    Downloads result = null;
    try {
        String organizationid = Constants.decryptPos(pos);
        ArrayList<Download> downloads = sqlSession.getMapper(ReservationMapper.class).uploads(organizationid);
        if (downloads == null || downloads.isEmpty()) {
            throw new ServiceException(Error.reservation_upload, organizationid);
        }
        result = new Downloads(message, downloads, xsl);
        sqlSession.commit();
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(message + "\n" + x.getMessage());
        result = new Downloads(message + " " + x.getMessage(), null, xsl);
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.interhome.A_Handler.java

License:Open Source License

/**
 * Transfer accommodation alerts./*  w w  w.  j ava  2 s  . c o m*/
 *
 * @param sqlSession the current SQL session.
 */
public synchronized void readAlerts() {
    Date timestamp = new Date();
    String message = "readAlerts " + getAltpartyid();
    LOG.debug(message);
    String fn = null;
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.alert");
        Unmarshaller um = jc.createUnmarshaller();

        fn = "alert_en.xml";
        Alerts alerts = (Alerts) um.unmarshal(ftp(fn));
        int i = 0;
        for (Alert alert : alerts.getAlert()) {
            LOG.debug(alert);
            net.cbtltd.shared.Alert action = new net.cbtltd.shared.Alert();
            Product product = sqlSession.getMapper(ProductMapper.class)
                    .altread(new NameId(getAltpartyid(), alert.getCode()));
            if (product == null) {
                LOG.error(Error.product_id.getMessage() + " " + alert.getCode());
            } else {
                action.setEntitytype(NameId.Type.Product.name());
                action.setEntityid(product.getId());
                action.setFromdate(alert.getStartdate().toGregorianCalendar().getTime());
                action.setTodate(alert.getEnddate().toGregorianCalendar().getTime());
                action.setName(alert.getText());
                net.cbtltd.shared.Alert duplicate = sqlSession.getMapper(AlertMapper.class).duplicate(action);
                if (duplicate == null) {
                    sqlSession.getMapper(AlertMapper.class).create(action);
                } else {
                    sqlSession.getMapper(AlertMapper.class).update(action);
                }
                sqlSession.commit();
                LOG.debug(i++ + " " + alert.getCode() + " = " + action.getId());
            }
            wait(getAlertwait());
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
        delete(fn);
    }
    MonitorService.monitor(message, timestamp);
}

From source file:net.cbtltd.rest.interhome.A_Handler.java

License:Open Source License

/**
 * Read property locations./* w  w  w  .  jav  a  2 s.  c  o m*/
 */
public synchronized void readLocations() {
    String message = "Interhome readLocations " + getAltpartyid();
    LOG.debug(message);
    String codeinterhome = null;
    String countrycode = null;
    String fn = null;
    final SqlSession sqlSession = RazorServer.openSession();
    try {

        StringBuilder sb = new StringBuilder();

        JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.countryregionplace");
        //Create unmarshaller
        Unmarshaller um = jc.createUnmarshaller();

        fn = "countryregionplace_en.xml";

        Countries countries = (Countries) um.unmarshal(ftp(fn));
        for (Country country : countries.getCountry()) {
            LOG.debug("Country " + country);
            countrycode = country.getCode();
            String usRegion = null;
            if (sqlSession.getMapper(CountryMapper.class).read(countrycode) == null) {
                throw new ServiceException(Error.country_code, countrycode);
            }
            int i = 0;
            for (RegionType region : country.getRegions().getRegion()) {
                if (region.getPlaces() != null && region.getPlaces().getPlace() != null) {
                    for (PlaceType place : region.getPlaces().getPlace()) {
                        codeinterhome = countrycode + "." + place.getCode();
                        if (countrycode.equals("US")) {
                            usRegion = region.getName();
                        }
                        setLocation(sqlSession, place.getName(), usRegion, countrycode, codeinterhome);
                        if (place.getSubplaces() != null && place.getSubplaces().getSubplace() != null) {
                            for (SubplaceType subplace : place.getSubplaces().getSubplace()) {
                                codeinterhome = countrycode + "." + subplace.getCode();
                                setLocation(sqlSession, subplace.getName(), usRegion, countrycode,
                                        codeinterhome);
                            }
                        }
                    }
                }

                if (region.getSubregions() != null && region.getSubregions().getSubregion() != null) {
                    for (SubregionType subregion : region.getSubregions().getSubregion()) {
                        if (subregion.getPlaces() != null && subregion.getPlaces().getPlace() != null) {
                            for (PlaceType place : subregion.getPlaces().getPlace()) {
                                codeinterhome = countrycode + "." + place.getCode();
                                if (countrycode.equals("US")) {
                                    usRegion = (region.getName() + "," + subregion.getName());
                                }
                                setLocation(sqlSession, place.getName(), usRegion, countrycode, codeinterhome);
                                if (place.getSubplaces() != null
                                        && place.getSubplaces().getSubplace() != null) {
                                    for (SubplaceType subplace : place.getSubplaces().getSubplace()) {
                                        codeinterhome = countrycode + "." + subplace.getCode();
                                        setLocation(sqlSession, subplace.getName(), usRegion, countrycode,
                                                codeinterhome);
                                    }
                                }
                            }
                        }
                    }
                }
                sqlSession.commit();
            }
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
        delete(fn);
    }
}

From source file:net.cbtltd.rest.interhome.A_Handler.java

License:Open Source License

/**
 * Transfer accommodation daily prices and weekly prices for each sales office.
 *
 * TODO: Vacando prices in EUR only must use exchange rate for other prices
 * /*from   w  w  w . j a  v a2 s  .  co  m*/
 * @param sqlSession the current SQL session.
 */
public void readPrices() {
    Date version = new Date();
    String altparty = getAltpartyid();
    boolean checkedVersion = false;
    String message = "Interhome readPrices " + altparty;
    LOG.debug(message);
    String fn = null;

    String salesoffice = getSalesOfficeCode(Currency.Code.EUR.name());
    Currency.Code currency = Currency.Code.EUR;

    final SqlSession sqlSession = RazorServer.openSession();
    try {
        fn = "dailyprice_" + salesoffice + "_" + currency.name().toLowerCase() + ".xml";

        //check version of svn file and last price database entry
        net.cbtltd.shared.Price action = new net.cbtltd.shared.Price();
        action.setState(net.cbtltd.shared.Price.CREATED);
        action.setPartyid("90640");
        action.setAvailable(1);

        Date priceVersion = sqlSession.getMapper(PriceMapper.class).maxVersion(action);
        checkedVersion = checkVersion(fn, priceVersion);
        if (checkedVersion) {
            JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.price");
            Unmarshaller um = jc.createUnmarshaller();

            Prices prices = (Prices) um.unmarshal(ftp(fn));

            if (prices != null && prices.getPrice() != null) {
                int count = prices.getPrice().size();
                LOG.debug("Total daily prices count: " + count);
            } else {
                LOG.debug("Error, no dailyprices file");
                return;
            }

            int i = 0;
            for (Price price : prices.getPrice()) {
                String altid = price.getCode();
                //               if (!altid.equals("CH3920.126.1") || !"CH3920.126.1".equalsIgnoreCase(altid)) continue;
                String productid = getProductId(altid);

                if (productid == null) {
                    Product product = sqlSession.getMapper(ProductMapper.class)
                            .altread(new NameId(altparty, altid));
                    if (product == null) {
                        LOG.error(Error.product_id.getMessage() + " " + price.getCode());
                        continue;
                    }
                    PRODUCTS.put(altid, product.getId());
                    productid = getProductId(altid);
                }

                //               if (!productid.equals("27077") || !String.valueOf(27077).equalsIgnoreCase(productid)) continue;

                action = new net.cbtltd.shared.Price();
                action.setPartyid(altparty);
                action.setEntitytype(NameId.Type.Product.name());
                action.setEntityid(productid);
                action.setCurrency(currency.name());
                action.setQuantity(1.0);
                action.setUnit(Unit.DAY);
                action.setName(net.cbtltd.shared.Price.RACK_RATE);
                action.setType(NameId.Type.Reservation.name());
                action.setDate(price.getStartdate().toGregorianCalendar().getTime());
                action.setTodate(price.getEnddate().toGregorianCalendar().getTime());

                net.cbtltd.shared.Price exists = sqlSession.getMapper(PriceMapper.class).exists(action);
                if (exists == null) {
                    sqlSession.getMapper(PriceMapper.class).create(action);
                } else {
                    action = exists;
                }

                action.setState(net.cbtltd.shared.Price.CREATED);
                action.setRule(net.cbtltd.shared.Price.Rule.AnyCheckIn.name());
                action.setFactor(1.0);
                //               Double rentalPrice = price.getRentalprice().doubleValue();
                //               Double value = duration > 0.0 ? NameId.round(rentalPrice / quantity) : rentalPrice;
                action.setValue(price.getRentalprice().doubleValue());
                //               action.setMinimum(price.getMinrentalprice().doubleValue());
                action.setVersion(version);
                action.setAvailable(1);
                sqlSession.getMapper(PriceMapper.class).update(action);
                sqlSession.getMapper(PriceMapper.class).cancelversion(action);

                LOG.debug(i++ + " DailyPrice: " + " " + price.getCode() + " " + productid + " " + salesoffice
                        + " " + action.getValue() + " " + currency + " daily");

                //               if (price.getFixprice().signum() != 0) {
                Adjustment adjust = setAdjustment(sqlSession, productid, 5, 999, currency.name(),
                        action.getDate(), action.getTodate(), price, Adjustment.WEEK, "fixprice", version);
                DAILYPRICES.put(adjust.getID(), price.getRentalprice().doubleValue());

                LOG.debug(i++ + " FixPrice: " + " " + price.getCode() + " " + productid + " " + salesoffice
                        + " " + adjust.getExtra() + " " + currency + " fixprice");
                //               }
                if (price.getMidweekrentalprice().signum() != 0) {
                    adjust = setAdjustment(sqlSession, productid, 1, 1, currency.name(), action.getDate(),
                            action.getTodate(), price, (byte) 0x1E, "midweek", version);
                    adjust = setAdjustment(sqlSession, productid, 2, 2, currency.name(), action.getDate(),
                            action.getTodate(), price, (byte) 0xE, "midweek", version);
                    adjust = setAdjustment(sqlSession, productid, 3, 3, currency.name(), action.getDate(),
                            action.getTodate(), price, (byte) 0x6, "midweek", version);
                    adjust = setAdjustment(sqlSession, productid, 4, 4, currency.name(), action.getDate(),
                            action.getTodate(), price, Adjustment.MONDAY, "midweek", version);

                    LOG.debug(i++ + " MidweekPrice: " + " " + price.getCode() + " " + productid + " "
                            + salesoffice + " " + adjust.getExtra() + " " + currency + " midweek");
                }
                if (price.getWeekendrentalprice().signum() != 0) {
                    adjust = setAdjustment(sqlSession, productid, 1, 1, currency.name(), action.getDate(),
                            action.getTodate(), price, Adjustment.SATURDAY, "weekend", version);
                    adjust = setAdjustment(sqlSession, productid, 2, 2, currency.name(), action.getDate(),
                            action.getTodate(), price, (byte) 0x60, "weekend", version);
                    adjust = setAdjustment(sqlSession, productid, 3, 3, currency.name(), action.getDate(),
                            action.getTodate(), price, (byte) 0x70, "weekend", version);

                    LOG.debug(i++ + " WeekendPrice: " + " " + price.getCode() + " " + productid + " "
                            + salesoffice + " " + adjust.getExtra() + " " + currency + " weekend");
                }
                //               LOG.debug(i++ + "DailyPrice: " + " " + price.getCode() + " " + product.getId() + " " + salesoffice + " " + action.getValue() + " " + currency + " " + duration);
            }
            Adjustment cancelAction = new Adjustment();
            cancelAction.setCurrency(currency.name());
            cancelAction.setPartyID(altparty);
            cancelAction.setVersion(version);

            sqlSession.getMapper(AdjustmentMapper.class).cancelversion(cancelAction);
            sqlSession.commit();
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
        delete(fn);
    }
    if (checkedVersion) {
        readPrices(version, salesoffice, currency, 7);
        readPrices(version, salesoffice, currency, 14);
        readPrices(version, salesoffice, currency, 21);
        readPrices(version, salesoffice, currency, 28);
    }
}

From source file:net.cbtltd.rest.interhome.A_Handler.java

License:Open Source License

/**
 * Read prices./*from  w  ww  .  j  a v a 2 s  . co m*/
 *
 * @param version the version
 * @param salesoffice the salesoffice
 * @param currency the currency
 * @param duration the duration
 */
private synchronized void readPrices(Date version, String salesoffice, Currency.Code currency, int duration) {
    String altparty = getAltpartyid();
    String message = "Interhome readPrices Weekly " + altparty;
    LOG.debug(message);
    String fn = null;
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.price");
        Unmarshaller um = jc.createUnmarshaller();

        fn = "price_" + salesoffice + "_" + currency.name().toLowerCase()
                + (duration < 14 ? "" : "_" + String.valueOf(duration)) + ".xml";
        Prices prices = (Prices) um.unmarshal(ftp(fn));

        if (prices != null && prices.getPrice() != null) {
            int count = prices.getPrice().size();
            LOG.debug("Total prices for " + duration + " days: " + count);
        } else {
            LOG.debug("Error, no price file for " + duration + " days");
            return;
        }

        int i = 0;
        for (Price weekprice : prices.getPrice()) {
            String altid = weekprice.getCode();
            //            if (!altid.equals("CH3920.126.1") || !"CH3920.126.1".equalsIgnoreCase(altid)) continue;
            String productid = getProductId(altid);

            if (productid == null) {
                Product product = sqlSession.getMapper(ProductMapper.class)
                        .altread(new NameId(altparty, altid));
                if (product == null) {
                    LOG.error(Error.product_id.getMessage() + " " + weekprice.getCode());
                    continue;
                }
                PRODUCTS.put(altid, product.getId());
                productid = getProductId(altid);
            }

            //            if (!productid.equals("27077") || !String.valueOf(27077).equalsIgnoreCase(productid)) continue;

            Date fromdate = weekprice.getStartdate().toGregorianCalendar().getTime();
            Date todate = weekprice.getEnddate().toGregorianCalendar().getTime();

            if (weekprice.getServices() != null && weekprice.getServices().getService() != null) {
                net.cbtltd.shared.Price mandatory = new net.cbtltd.shared.Price();
                mandatory.setEntitytype(NameId.Type.Mandatory.name());
                mandatory.setEntityid(productid);
                mandatory.setCurrency(currency.name());
                mandatory.setPartyid(altparty);
                mandatory.setVersion(version);

                for (Service service : weekprice.getServices().getService()) {
                    mandatory.setType("Fees");
                    mandatory.setDate(fromdate);
                    mandatory.setTodate(todate);
                    mandatory.setQuantity(0.0);
                    mandatory.setUnit(Unit.EA);
                    mandatory.setAvailable(1);
                    mandatory.setMinStay(1);
                    net.cbtltd.shared.Price existprice = sqlSession.getMapper(PriceMapper.class)
                            .exists(mandatory);
                    if (existprice == null) {
                        sqlSession.getMapper(PriceMapper.class).create(mandatory);
                    } else {
                        mandatory = existprice;
                    }

                    mandatory.setState(net.cbtltd.shared.Price.CREATED);
                    mandatory.setName(getServicename(service.getCode()));
                    mandatory.setMinimum(0.0);
                    mandatory.setValue(
                            service.getServiceprice() == null ? 0.0 : service.getServiceprice().doubleValue());
                    mandatory.setRule("Manual");
                    sqlSession.getMapper(PriceMapper.class).update(mandatory);
                }
                sqlSession.getMapper(PriceMapper.class).cancelversion(mandatory);
            }

            //            Adjustment adjustment = setAdjustment(sqlSession, productid, 7, 7, currency.name(), fromdate, todate, weekprice, "1111111", "week", version);

            Adjustment action = new Adjustment();
            action.setCurrency(currency.name());
            action.setState(Adjustment.Created);
            action.setPartyID(altparty);
            action.setProductID(productid);
            action.setFromDate(fromdate);
            action.setToDate(todate);
            action.setMaxStay(999);
            action.setMinStay(5);

            Adjustment example = sqlSession.getMapper(AdjustmentMapper.class).readbyexample(action);
            if (example == null)
                continue;

            Double rentalPrice;
            if (weekprice.getSpecialoffer() != null
                    && weekprice.getSpecialoffer().getSpecialofferprice() != null) {
                rentalPrice = weekprice.getSpecialoffer().getSpecialofferprice().doubleValue();
            } else {
                rentalPrice = weekprice.getRentalprice().doubleValue();
            }

            Double dailyprice = DAILYPRICES.get(example.getID());
            Double fixprice = example.getFixPrice();
            Double extra = ((rentalPrice - fixprice) / duration) - dailyprice;// ( ( weekprice - fixprice ) / 7 ) - rentalprice[per/day]

            action.setMinStay(duration);
            action.setMaxStay(duration);
            action.setState(null);

            net.cbtltd.shared.Adjustment exists = sqlSession.getMapper(AdjustmentMapper.class).exists(action);
            if (exists == null) {
                sqlSession.getMapper(AdjustmentMapper.class).create(action);
            } else {
                action = exists;
            }

            action.setExtra(PaymentHelper.getAmountWithTwoDecimals(extra));
            action.setServicedays(Adjustment.WEEK);
            action.setState(Adjustment.Created);
            action.setFixPrice(fixprice);
            action.setVersion(version);

            sqlSession.getMapper(AdjustmentMapper.class).update(action);
            sqlSession.getMapper(AdjustmentMapper.class).cancelversion(action);

            LOG.debug(i++ + " WeekPrice: " + " " + weekprice.getCode() + " " + productid + " " + salesoffice
                    + " " + action.getExtra() + " " + currency + " " + duration);
        }
        sqlSession.commit();
    } catch (NullPointerException ex) {
        ex.printStackTrace();
        LOG.error("NPE" + ex.getStackTrace());
        sqlSession.rollback();
    } catch (RuntimeException e) {
        e.printStackTrace();
        LOG.error("RuntimeExc " + e.getStackTrace());
        sqlSession.rollback();
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getClass().getName() + ": " + x.getMessage());
    } finally {
        sqlSession.close();
        delete(fn);
    }
}

From source file:net.cbtltd.rest.interhome.A_Handler.java

License:Open Source License

/**
 * read Descriptions// w  w  w.ja  v a 2 s.co m
 */
public synchronized void readDescriptions() {
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        Language.Code language = Language.Code.en;
        readDescriptions(sqlSession, "outsidedescription_" + language.name() + ".xml", language,
                "House/Residence", true);
        readDescriptions(sqlSession, "insidedescription_" + language.name() + ".xml", language, "Interior",
                false);

        language = Language.Code.de;
        readDescriptions(sqlSession, "outsidedescription_" + language.name() + ".xml", language,
                "Haus/Residenz", true);
        readDescriptions(sqlSession, "insidedescription_" + language.name() + ".xml", language, "Innenbereich",
                false);

        language = Language.Code.fr;
        readDescriptions(sqlSession, "outsidedescription_" + language.name() + ".xml", language,
                "La maison/la rsidence de vacances", true);
        readDescriptions(sqlSession, "insidedescription_" + language.name() + ".xml", language,
                "L'intrieur du logement", false);

        language = Language.Code.es;
        readDescriptions(sqlSession, "outsidedescription_" + language.name() + ".xml", language,
                "Haus/Residenz", true);
        readDescriptions(sqlSession, "insidedescription_" + language.name() + ".xml", language, "Innenbereich",
                false);
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
    }
}

From source file:net.cbtltd.rest.interhome.A_Handler.java

License:Open Source License

/**
 * Test accommodation products./*from   ww w  .j ava2s  .  c  om*/
 *
 * @param sqlSession the current SQL session.
 */
public synchronized void readProducts1() {
    Date timestamp = new Date();
    String message = "Interhome testProducts " + getAltpartyid();
    LOG.debug(message);
    String fn = null;
    final SqlSession sqlSession = RazorServer.openSession();
    try {

        JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.accommodation");
        Unmarshaller um = jc.createUnmarshaller();
        fn = "accommodation.xml";
        Accommodations accommodations = (Accommodations) um.unmarshal(ftp(fn));
        LOG.debug("accommodation size " + accommodations.getAccommodation().size());
        int i = 0;
        Date version = new Date();
        ArrayList<String> attributes = new ArrayList<String>();
        for (Accommodation accommodation : accommodations.getAccommodation()) {
            try {
                attributes.clear();
                Product product = PartnerService.getProduct(sqlSession, getAltpartyid(),
                        accommodation.getCode());
                if (product == null) {
                    continue;
                }
                addType(attributes, accommodation.getType());
                if (accommodation.getAttributes() != null
                        && accommodation.getAttributes().getAttribute() != null) {
                    for (String attribute : accommodation.getAttributes().getAttribute()) {
                        addAttribute(attributes, attribute);
                    }
                }
                if (accommodation.getDetails() != null) {
                    addDetail(attributes, accommodation.getDetails());
                }
                addQuality(attributes, String.valueOf(accommodation.getQuality()));
                if (accommodation.getThemes() != null && accommodation.getThemes().getTheme() != null) {
                    for (String theme : accommodation.getThemes().getTheme()) {
                        addTheme(attributes, theme);
                    }
                }
                RelationService.replace(sqlSession, Relation.PRODUCT_ATTRIBUTE, product.getId(), attributes);
                sqlSession.commit();
                LOG.debug(i++ + " " + accommodation.getCode() + " " + product.getId());
                wait(getProductwait());
            } catch (Throwable x) {
                LOG.error(accommodation + " error " + x.getMessage());
            }
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error("Product Error " + x.getMessage());
    } finally {
        sqlSession.close();
        delete(fn);
    }
    MonitorService.monitor(message, timestamp);
}

From source file:net.cbtltd.rest.interhome.A_Handler.java

License:Open Source License

/**
 * Read accommodation products./*from  ww w  . j  a  va2  s  . c  o m*/
 */
public synchronized void readProducts() {
    Date version = new Date();
    String message = "Interhome readProducts " + getAltpartyid();
    LOG.debug(message);
    String codeinterhome = null;
    String fn = null;
    final SqlSession sqlSession = RazorServer.openSession();
    try {

        RelationService.load(sqlSession, Downloaded.PRODUCT_DOWNLOAD_DATE, getAltpartyid(), version.toString());

        JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.accommodation");
        Unmarshaller um = jc.createUnmarshaller();
        fn = "accommodation.xml";
        Accommodations accommodations = (Accommodations) um.unmarshal(ftp(fn));
        int i = 0;
        StringBuilder sb = new StringBuilder();
        //         boolean check = true;
        for (Accommodation accommodation : accommodations.getAccommodation()) {
            try {
                //               if (accommodation.getCode().equalsIgnoreCase("DK1026.631.1")) {check = false;}
                //               if (accommodation.getCountry().equalsIgnoreCase("FR")) {check = false;}
                //               if (check) continue;
                //               Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), accommodation.getCode());
                Product product = getProduct(sqlSession, getAltpartyid(), accommodation.getCode());
                //               if (product == null) {continue;}
                ArrayList<String> attributes = new ArrayList<String>();

                product.setBathroom(
                        accommodation.getBathrooms() == null ? 2 : accommodation.getBathrooms().intValue());
                product.setRoom(
                        accommodation.getBedrooms() == null ? 2 : accommodation.getBedrooms().intValue());
                net.cbtltd.shared.Country country = sqlSession.getMapper(CountryMapper.class)
                        .read(accommodation.getCountry());

                Geodata geodata = accommodation.getGeodata();
                product.setLatitude(geodata == null ? null : geodata.getLat().doubleValue());
                product.setLongitude(geodata == null ? null : geodata.getLng().doubleValue());
                product.setAltitude(0.0);

                product.setPerson(accommodation.getPax() == null ? 2 : accommodation.getPax().intValue());
                product.setRoom(
                        accommodation.getBedrooms() == null ? 1 : accommodation.getBedrooms().intValue());
                product.setToilet(
                        accommodation.getToilets() == null ? 0 : accommodation.getToilets().intValue());
                product.setChild(0);
                product.setSecuritydeposit(Product.DEFAULT_SECUIRTY_DEPOSIT);
                product.setCommission(20.0);
                product.setCleaningfee(Product.DEFAULT_CLEANING_FEE);
                product.setCurrency(country.getCurrency());
                //               product.setDiscount(20.0);
                product.setInfant(0);
                String floor = accommodation.getFloor();
                Short space = accommodation.getSqm();
                if (NumberUtils.isNumber(floor)) {
                    product.setFloor(Integer.valueOf(floor));
                } else {
                    LOG.error("Invalid floor or space value for product id: " + product.getId() + ", altid: "
                            + accommodation.getCode());
                }
                product.setSpace((space == null ? "0" : space) + " sq.m");

                product.setQuantity(1);
                product.setRank(getRank());
                product.setRating(5);
                //               product.setState(Product.CREATED);
                product.setType(Product.Type.Accommodation.name());
                product.setUnit(Unit.DAY);
                product.setWebaddress(accommodation.getUrl());
                product.setVersion(version);

                // Search location by specific Interhome Code.
                codeinterhome = accommodation.getCountry() + "." + accommodation.getPlace();
                Location location = new Location();
                try {
                    location.setCodeinterhome(codeinterhome);
                    location = sqlSession.getMapper(LocationMapper.class).interhomeSearch(location);
                    //location = getLocation(sqlSession, codeinterhome);
                } catch (Throwable x) {
                    LOG.error("Location error for Accommodation: " + accommodation.getCode() + ", country: "
                            + accommodation.getCountry() + ", region: " + accommodation.getRegion() + ", code: "
                            + accommodation.getPlace() + ". Error: " + x.getMessage());
                }
                if (location == null) {
                    sb.append("\n")
                            .append("Accommodation: " + accommodation.getCode() + " country: "
                                    + accommodation.getCountry() + " region: " + accommodation.getRegion()
                                    + " code: " + accommodation.getPlace());
                    product.setState(Product.SUSPENDED);
                } else {
                    product.setLocationid(location.getId());
                }

                String name = accommodation.getName();
                product.setName(name == null || name.trim().isEmpty()
                        ? getPropType(accommodation.getType()) + " "
                                + (location == null ? "" : location.getName())
                        : getPropType(accommodation.getType()) + " " + name.trim());

                sqlSession.getMapper(ProductMapper.class).update(product);

                if (accommodation.getBrand() != null) {
                    product.setValue(Product.Value.Brand.name(), accommodation.getBrand());
                }
                if (accommodation.getRegion() != null) {
                    product.setValue(Product.Value.Region.name(), accommodation.getRegion());
                }
                if (accommodation.getMaxrentalprice() != null) {
                    product.setDoubleValue(Product.Value.Maxrentalprice.name(),
                            accommodation.getMaxrentalprice().doubleValue());
                }
                if (accommodation.getMinrentalprice() != null) {
                    product.setDoubleValue(Product.Value.Minrentalprice.name(),
                            accommodation.getMinrentalprice().doubleValue());
                }
                if (accommodation.getSqm() != null) {
                    product.setIntegerValue(Product.Value.SquareMetre.name(),
                            accommodation.getSqm().intValue());
                }
                if (accommodation.getFloor() != null) {
                    product.setValue(Product.Value.Floor.name(), accommodation.getFloor());
                }

                addType(attributes, accommodation.getType());

                if (accommodation.getAttributes() != null
                        && accommodation.getAttributes().getAttribute() != null) {
                    for (String attribute : accommodation.getAttributes().getAttribute()) {
                        addAttribute(attributes, attribute);
                    }
                }

                if (accommodation.getDetails() != null) {
                    addDetail(attributes, accommodation.getDetails());
                }

                addQuality(attributes, String.valueOf(accommodation.getQuality()));

                if (accommodation.getThemes() != null && accommodation.getThemes().getTheme() != null) {
                    for (String theme : accommodation.getThemes().getTheme()) {
                        addTheme(attributes, theme);
                    }
                }

                RelationService.replace(sqlSession, Relation.PRODUCT_VALUE, product.getId(),
                        product.getValues());
                RelationService.create(sqlSession, Relation.PRODUCT_ATTRIBUTE, product.getId(), attributes);
                RelationService.removeDeprecatedData(sqlSession, Relation.PRODUCT_ATTRIBUTE, product.getId(),
                        attributes);

                /*               StringBuilder description = new StringBuilder();
                               Distances distances = accommodation.getDistances();
                               if (distances != null && distances.getDistance() != null) {
                                  description.append("Distances to:");
                                  for (Distance distance : distances.getDistance()) {
                                     description.append(" ")
                                     .append(getDistance(distance.getType()))
                                     .append(" ")
                                     .append(distance.getValue())
                                     .append("m ");
                                  }
                                  description.append("\n");
                               }
                        
                               Text action = new Text(product.getPublicId(), Language.Code.en.name());
                               Text text = sqlSession.getMapper(TextMapper.class).readbyexample(action);
                               if (text == null) {text = new Text(product.getPublicId(), product.getPublicLabel(), Text.Type.HTML, new Date(), "", Language.Code.en.name());}
                               text.setState(Text.State.Created.name());
                               text.setNotes(description.toString());
                               product.setPublicText(text);
                               TextService.update(sqlSession, product.getTexts());*/

                if (HasUrls.LIVE && accommodation.getPictures() != null
                        && accommodation.getPictures().getPicture() != null) {
                    ArrayList<NameId> images = new ArrayList<NameId>();
                    List<Picture> pictures = accommodation.getPictures().getPicture();

                    int k = 0;
                    for (Picture picture : pictures) {
                        if (picture.getType().equalsIgnoreCase("M")) {
                            String imageid = getImage(picture.getType()) + " " + getImage(picture.getSeason());
                            images.add(new NameId(imageid,
                                    picture.getUrl().replace("partner-medium", "partner-xlarge")));
                            pictures.remove(k);
                            break;
                        }
                        k++;
                    }
                    k = 0;
                    while (k < pictures.size()) {
                        Picture picture = pictures.get(k);
                        if (picture.getType().equalsIgnoreCase("I")) {
                            String imageid = getImage(picture.getType()) + " " + getImage(picture.getSeason());
                            images.add(new NameId(imageid,
                                    picture.getUrl().replace("partner-medium", "partner-xlarge")));
                            pictures.remove(k);
                        } else
                            k++;
                    }
                    for (Picture picture : pictures) {
                        try {
                            String imageid = getImage(picture.getType()) + " " + getImage(picture.getSeason());
                            images.add(new NameId(imageid,
                                    picture.getUrl().replace("partner-medium", "partner-xlarge")));
                        } catch (Throwable x) {
                            LOG.error("\nURL error " + picture.getUrl());
                        }
                    }
                    UploadFileService.uploadImages(sqlSession, NameId.Type.Product, product.getId(),
                            Language.EN, images);
                }
                sqlSession.commit();
                LOG.debug(i++ + " " + accommodation.getCode() + " = " + product.getId());
                //               wait(getProductwait());
            } catch (Throwable x) {
                LOG.error(accommodation + " error " + x.getMessage());
            }
            // TODO: CJM if (i > 10) break;
        }
        Product action = new Product();
        action.setAltpartyid(getAltpartyid());
        action.setState(Product.CREATED);
        action.setVersion(version);

        sqlSession.getMapper(ProductMapper.class).cancelversion(action);
        sqlSession.commit();

        LOG.debug("Missing Places" + sb.toString());

        /*         Language.Code language = Language.Code.en;
                 readDescriptions(sqlSession, "outsidedescription_" + language.name() + ".xml", language, "House/Residence", false);
                 readDescriptions(sqlSession, "insidedescription_" + language.name() + ".xml", language, "Interior", false);
                
                 language = Language.Code.de; 
                 readDescriptions(sqlSession, "outsidedescription_" + language.name() + ".xml", language, "Haus/Residenz", true);
                 readDescriptions(sqlSession, "insidedescription_" + language.name() + ".xml", language, "Innenbereich", false);
                
                 language = Language.Code.fr; 
                 readDescriptions(sqlSession, "outsidedescription_" + language.name() + ".xml", language, "La maison/la rsidence de vacances", true);
                 readDescriptions(sqlSession, "insidedescription_" + language.name() + ".xml", language, "L'intrieur du logement", false);
                
                 language = Language.Code.es; 
                 readDescriptions(sqlSession, "outsidedescription_" + language.name() + ".xml", language, "Haus/Residenz", true);
                 readDescriptions(sqlSession, "insidedescription_" + language.name() + ".xml", language, "Innenbereich", false);
                 */
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
        delete(fn);
    }
    //MonitorService.monitor(message, timestamp);
}