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

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

Introduction

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

Prototype

void commit();

Source Link

Document

Flushes batch statements and commits database connection.

Usage

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

License:Open Source License

/**
 * Read property locations./* w w  w .j a  v a2 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

/**
 * Checks and creates the location from its name, region and country it if it does not exist.
 *
 * @param sqlSession the current SQL session.
 * @param name the name of current location
 * @param region the name of current location region (currently only for US)
 * @param countrycode the current country
 * @param codeInterhome the unique Interhome code for current location
 * @return the location object/*from  w  w w .j a  v a  2s . c  o  m*/
 */
private final void setLocation(SqlSession sqlSession, String name, String region, String countrycode,
        String codeinterhome) {
    Location location = getLocation(sqlSession, codeinterhome);
    if (location == null) {
        location = PartnerService.getLocation(sqlSession, name, region, countrycode);
        location.setCodeinterhome(codeinterhome);
        sqlSession.getMapper(LocationMapper.class).update(location);
        sqlSession.commit();
        LOG.debug("Location changed: " + location);
    } else {
        LOG.debug("Location no changes: " + location);
    }
}

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 ava 2s  .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   ww  w . j  av a  2 s.c  om
 *
 * @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./*from   w  w  w.j ava 2s  .com*/
 *
 * @param sqlSession the current SQL session.
 * @param fn the description file name
 * @param language the ISO language code of the description
 * @param title the title of the description
 */
public void readDescriptions(SqlSession sqlSession, String fn, Language.Code language, String title,
        boolean first) {
    try {
        JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.description");
        Unmarshaller um = jc.createUnmarshaller();
        Descriptions descriptions = (Descriptions) um.unmarshal(ftp(fn));
        int i = 0;
        for (Description description : descriptions.getDescription()) {
            Product product = sqlSession.getMapper(ProductMapper.class)
                    .altread(new NameId(getAltpartyid(), description.getCode()));
            if (product == null) {
                LOG.error(Error.product_id.getMessage() + " " + description.getCode());
            } else {
                Text action = new Text(product.getPublicId(), language.name());
                Text text = sqlSession.getMapper(TextMapper.class).readbyexample(action);
                if (text == null) {
                    text = new Text(product.getPublicId(), "Description", Text.Type.HTML, new Date(), "",
                            language.name());
                }
                text.setState(Text.State.Created.name());

                if (first) {
                    text.setNotes(title + "\n" + description.getText());
                } else if (!text.getNotes().startsWith(title) && description.getText() != null
                        && !description.getText().isEmpty()) {
                    text.setNotes(title + "\n" + description.getText() + "\n\n" + text.getNotes());
                }

                product.setPublicText(text);
                TextService.update(sqlSession, product.getTexts());
                sqlSession.commit();
                LOG.debug(i++ + " " + language.name() + " " + description.getCode() + " = " + product.getId());
            }
            wait(getProductwait());
        }
    } catch (Throwable x) {
        x.getMessage();
    } finally {
        delete(fn);
    }
}

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

License:Open Source License

/**
 * Test accommodation products./*w  w  w  .ja  va  2 s .co  m*/
 *
 * @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./*www . j a  v  a  2s  . c om*/
 */
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);
}

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

License:Open Source License

/**
 * Transfer reservation schedule.//  w w  w.ja  v  a  2s .c o  m
 *
 * @param sqlSession the current SQL session.
 */
public synchronized void readSchedule() {
    Date timestamp = new Date();
    String message = "readSchedule ";
    LOG.debug(message);
    String fn = null;
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        RelationService.load(sqlSession, Downloaded.SCHEDULE_DOWNLOAD_DATE, getAltpartyid(),
                new Date().toString());
        JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.vacancy");
        Unmarshaller um = jc.createUnmarshaller();
        fn = "vacancy.xml";
        Vacancies vacancies = (Vacancies) um.unmarshal(ftp(fn));
        for (Vacancy vacancy : vacancies.getVacancy()) {
            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), vacancy.getCode());
            if (product == null) {
                continue;
            }
            String availabilities = vacancy.getAvailability();
            Date startdate = vacancy.getStartday().toGregorianCalendar().getTime();
            Date fromdate = null;
            Date todate = null;
            int index;
            for (index = 0; index < availabilities.length(); index++) {
                char availability = availabilities.charAt(index);
                if (fromdate == null && (availability == 'N' || availability == 'Q')) {
                    fromdate = Time.addDuration(startdate, index, Time.DAY);
                } else if (fromdate != null && availability == 'Y') {
                    todate = Time.addDuration(startdate, index, Time.DAY);
                    PartnerService.createSchedule(sqlSession, product, fromdate, todate, timestamp);
                    fromdate = null;
                    todate = null;
                }
            }
            if (todate == null && fromdate != null) {
                todate = Time.addDuration(startdate, index, Time.DAY);
                PartnerService.createSchedule(sqlSession, product, fromdate, todate, timestamp);
            }
            Reservation reservation = new Reservation();
            reservation.setProductid(product.getId());
            reservation.setVersion(timestamp);
            PartnerService.cancelSchedule(sqlSession, reservation);
            sqlSession.commit();
            wait(getSchedulewait());
        }
        readMinStay();
    } 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

/**
 * Transfer minstay values./*from www .ja  va  2  s  .c  o m*/
 *
 * @param sqlSession the current SQL session.
 */
public synchronized void readMinStay() {
    Date timestamp = new Date();
    String message = "readMinStay ";
    LOG.debug(message);
    String fn = null;
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.vacancy");
        Unmarshaller um = jc.createUnmarshaller();
        fn = "vacancy.xml";
        Vacancies vacancies = (Vacancies) um.unmarshal(ftp(fn));
        for (Vacancy vacancy : vacancies.getVacancy()) {
            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), vacancy.getCode());
            if (product == null) {
                continue;
            }
            String minstays = vacancy.getMinstay();
            char prevVal = minstays.charAt(0);
            Date startdate = vacancy.getStartday().toGregorianCalendar().getTime();
            Date fromdate = startdate;
            Date todate = null;
            int value = getMinStay(prevVal);
            int index;
            for (index = 1; index < minstays.length(); index++) {
                char currVal = minstays.charAt(index);
                if (currVal != prevVal) {
                    todate = Time.addDuration(startdate, index - 1, Time.DAY);
                    PartnerService.createMinStay(sqlSession, value, product, fromdate, todate, timestamp);
                    fromdate = Time.addDuration(startdate, index, Time.DAY);
                }
                prevVal = currVal;
                value = getMinStay(currVal);
            }
            todate = Time.addDuration(startdate, index, Time.DAY);
            PartnerService.createMinStay(sqlSession, value, product, fromdate, todate, timestamp);
            PartnerService.deleteMinStay(sqlSession, product, timestamp);
            sqlSession.commit();
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
        delete(fn);
    } finally {
        sqlSession.close();
        delete(fn);
    }
}

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

License:Open Source License

/**
 * {@inheritDoc}//  w ww .jav  a  2 s . c  o m
 */
@Override
public Map<String, String> createReservationAndPayment(SqlSession sqlSession, Reservation reservation,
        CreditCard creditCard) {

    Date timestamp = new Date();
    String message = "createReservation " + reservation.getId();
    LOG.debug(message);

    Map<String, String> result = new HashMap<String, String>();
    try {
        if (reservation.notActive()) {
            throw new ServiceException(Error.reservation_state,
                    reservation.getId() + " state " + reservation.getState());
        }

        Product product = sqlSession.getMapper(ProductMapper.class).read(reservation.getProductid());
        if (product == null) {
            throw new ServiceException(Error.product_id, reservation.getProductid());
        }
        if (reservation.noAgentid()) {
            throw new ServiceException(Error.reservation_agentid);
        }
        Party agent = sqlSession.getMapper(PartyMapper.class).read(reservation.getAgentid());
        if (agent == null) {
            throw new ServiceException(Error.party_id, reservation.getAgentid());
        }
        if (reservation.noCustomerid()) {
            reservation.setCustomerid(Party.NO_ACTOR);
        }
        Party customer = sqlSession.getMapper(PartyMapper.class).read(reservation.getCustomerid());
        if (customer == null) {
            throw new ServiceException(Error.reservation_customerid, reservation.getCustomerid());
        }

        double oldQuote = reservation.getQuote();
        computePrice(sqlSession, reservation, product.getAltid(), reservation.getCurrency());

        if (oldQuote != reservation.getQuote()) {
            throw new ServiceException(Error.price_not_match,
                    "old: " + oldQuote + ", new: " + reservation.getQuote());
        }

        ClientBookingInputValue rq = createClientBookingRequest(product, reservation, agent, customer,
                creditCard);

        LOG.debug("\nclientBooking rq=" + rq + "\n");
        ClientBookingReturnValue rs = getAuthenticatedPort(getRetailerCode(reservation.getCurrency()))
                .clientBooking(rq);
        LOG.debug("\nclientBooking rs=" + rs + "\n");

        if (rs.isOk()) {
            reservation.setAltid(rs.getBookingID());
            reservation.setAltpartyid(getAltpartyid());
            reservation.setMessage(null);
            result.put(GatewayHandler.STATE, GatewayHandler.ACCEPTED);
        } else {
            result.put(GatewayHandler.STATE, GatewayHandler.FAILED);
            result.put(GatewayHandler.ERROR_MSG, rs.getErrors().getError().get(0).getDescription());
            return result;
            //            throw new ServiceException(Error.reservation_api, rs.getErrors().getError().get(0).getDescription());
        }
    } catch (ServiceException e) {
        reservation.setMessage(e.getMessage());
        reservation.setState(Reservation.State.Cancelled.name());
        sqlSession.getMapper(ReservationMapper.class).update(reservation);
        sqlSession.commit();
        throw new ServiceException(e.getError(), e.getMessage());
    } catch (Throwable x) {
        reservation.setMessage(x.getMessage());
        reservation.setState(Reservation.State.Cancelled.name());
        LOG.error(x.getMessage());
    }
    sqlSession.getMapper(ReservationMapper.class).update(reservation);
    sqlSession.commit();
    MonitorService.monitor(message, timestamp);

    return result;
}