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.nextpax.A_Handler.java

License:Open Source License

private void readHousePropertyCodes() {
    long startTime = System.currentTimeMillis();

    SAXBuilder parser = new SAXBuilder();
    Document document = null;/*from  w ww  .  j  a va2 s . c o m*/
    final SqlSession sqlSession = RazorServer.openSession();
    String fileName = "paxgenerator_house_properties_" + getApikey() + ".xml";
    int updatedHouses = 0;
    try {
        long startParsing = System.currentTimeMillis();
        document = parser.build(ftp(fileName));
        // document = parser.build(new File(System
        // .getProperty("user.home")
        // + File.separator
        // + "PMS"
        // + File.separator
        // + "nextpax"
        // + File.separator
        // + getApikey()
        // + File.separator + fileName));
        LOG.debug("Time taken to parse " + fileName + " : " + (System.currentTimeMillis() - startParsing)
                + " milli seconds.");

        Element rootNode = document.getRootElement();
        List<Element> houses = rootNode.getChildren("Properties");

        for (Element house : houses) {
            String altid = house.getChildText("HouseID");
            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altid, false);
            if (product == null) {
                continue;
            }

            Integer toilet = 0;
            LOG.debug("Setting properties for: " + product.getId());
            List<Element> properties = house.getChildren("Property");
            for (Element property : properties) {
                String attrKey = property.getChildText("PropertyCode");
                // Use `case` when we will move to JAVA 7 or higher
                if (attrKey.equals("B02")) {
                    int numbedroom = 0;
                    try {
                        numbedroom = Integer.parseInt(property.getChildText("Value")); // Number of bedrooms.
                    } catch (NumberFormatException e) {
                        // do nothing...move onto next property
                    }
                    product.setRoom(numbedroom); // need to decide
                    // attribute for bedroom
                    if (numbedroom > 8) {
                        RelationService.create(sqlSession, Relation.PRODUCT_ATTRIBUTE, product.getId(),
                                ATTRIBUTES.get(attrKey) + 9);
                    } else if (numbedroom > 0) {
                        RelationService.create(sqlSession, Relation.PRODUCT_ATTRIBUTE, product.getId(),
                                ATTRIBUTES.get(attrKey) + numbedroom);
                    }
                } else if (attrKey.equals("B01")) {
                    try {
                        product.setBathroom(Integer.parseInt(property.getChildText("Value"))); // Number of bedrooms.
                    } catch (NumberFormatException e) {
                        // do nothing...move onto next property
                    }
                } else if (attrKey.equals("T07")) {
                    try {
                        toilet = Integer.parseInt(property.getChildText("Value"));
                    } catch (NumberFormatException e) {
                        // do nothing...move onto next property
                    }
                } // do not have mapping do nothing. *Maybe create attributes or add into description?
                else if (attrKey.equals("D02")) {
                    // number of double beds
                } else if (attrKey.equals("S02")) {
                    // number of single beds
                } else if (attrKey.equals("S03")) {
                    // number of sofas
                } else {
                    // look up ATTRIBUTE Map
                    String attrList = ATTRIBUTES.get(attrKey);
                    if (!StringUtils.isEmpty(attrList)) {
                        RelationService.delete(sqlSession, Relation.PRODUCT_OTA_ATTRIBUTE, product.getId(),
                                attrList);
                        // if we are running delta import....this will make sure create will not fail.
                        RelationService.create(sqlSession, Relation.PRODUCT_OTA_ATTRIBUTE, product.getId(),
                                attrList);
                    }
                }
            }

            product.setToilet(toilet);
            if ((product.getRoom() == null || product.getRoom() < 1) || (product.getBathroom() == null)) {
                product.setState(Product.SUSPENDED);
            } else {
                product.setState(Product.CREATED);
            }
            product.setAssignedtomanager(true);
            sqlSession.getMapper(ProductMapper.class).update(product);
            sqlSession.commit();
            updatedHouses++;
        }

    } catch (Throwable e) {
        sqlSession.rollback();
        LOG.error(e.getMessage());
    } finally {
        sqlSession.close();
        delete(fileName);
    }
    LOG.debug("Time taken to complete house properties for " + getApikey() + " with number of houses "
            + updatedHouses + " : " + ((System.currentTimeMillis() - startTime)) / 1000 + " seconds.");
}

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

License:Open Source License

@Override
public void readDescriptions() {
    long startTime = System.currentTimeMillis();
    String altid;//from   w  w  w.ja v a 2s.  c om
    SAXBuilder parser = new SAXBuilder();
    Product product;
    Document document = null;

    String fileName = "paxgenerator_house_descriptions_" + getApikey() + ".xml";
    int propertymanagerid = getPropertyManagerID(getApikey());

    final SqlSession sqlSession = RazorServer.openSession();
    try {
        long startParsing = System.currentTimeMillis();

        LOG.debug("Time taken to parse " + fileName + " : " + (System.currentTimeMillis() - startParsing)
                + " milli seconds.");
        document = parser.build(ftp(fileName));
        // document = parser.build(new File(System
        // .getProperty("user.home")
        // + File.separator
        // + "PMS"
        // + File.separator
        // + "nextpax"
        // + File.separator
        // + getApikey()
        // + File.separator + fileName));
        Element rootNode = document.getRootElement();
        List<Element> houses = rootNode.getChildren("Descriptions");
        int i = 0;
        StringBuilder sb;
        for (Element house : houses) {
            altid = house.getChildText("HouseID");
            product = PartnerService.getProduct(sqlSession, getAltpartyid(), altid, false);
            if (product == null) {
                continue;
            }

            HashMap<String, String> texts = new HashMap<String, String>(); // Maps language to its text
            List<Element> descriptions = house.getChildren("Description");
            for (Element description : descriptions) {
                String language = description.getChildText("Language").toUpperCase();
                String text = description.getChildText("Text");
                String type = description.getChildText("Type");
                if (type.equalsIgnoreCase("p")) {
                    continue; // price table.
                }
                sb = new StringBuilder();
                if (texts.get(language) == null) {
                    sb.append(getDescriptionType(language, type)).append(":").append(text).append("\n");
                } else {
                    sb.append(texts.get(language)).append(getDescriptionType(language, type)).append(":")
                            .append(text).append("\n");
                }
                texts.put(language, sb.toString().length() <= IsPartner.TEXT_NOTES_LENGTH ? sb.toString()
                        : sb.toString().substring(0, IsPartner.TEXT_NOTES_LENGTH));
            }

            if (!texts.containsKey(Language.EN) && RazorConfig.doTranslation()) {// must have an English description!
                String englishTranslation;
                for (String language : texts.keySet()) {
                    // sleep for a while to meet google's rate limit
                    Thread.sleep(500);
                    englishTranslation = TextService.translate(texts.get(language), language, Language.EN);
                    if (StringUtils.isNotEmpty(englishTranslation)) {
                        texts.put(Language.EN, englishTranslation);
                        LOG.debug("English_Translation : " + texts.get(Language.EN));
                        break;
                    }
                }
            }
            // if(emailPayment(propertymanagerid)){
            // for(String language : texts.keySet()){
            // texts.put(language, NameId.trim(texts.get(language),20000 - EMAILCREDITCARD.length()) + EMAILCREDITCARD);
            // }
            // }
            for (String language : texts.keySet()) {
                LOG.debug("language " + language + " notes " + texts.get(language));
                product.setPublicText(new Text(product.getPublicId(), product.getPublicLabel(), Text.Type.HTML,
                        new Date(), texts.get(language), language));
                TextService.update(sqlSession, product.getTexts());
            }

            i++;
            if (i > 0 && i % IsPartner.PRICE_BATCH_SIZE == 0) {
                LOG.debug("Smart flush for description: " + i);
                sqlSession.commit();
            }
        }
        sqlSession.commit();
    } catch (Throwable e) {
        LOG.error(e.getMessage());
        sqlSession.rollback();
    } finally {
        sqlSession.close();
        delete(fileName);
    }
    LOG.debug("Time taken to complete product descriptions for " + getApikey() + " : "
            + ((System.currentTimeMillis() - startTime)) / 1000 + " seconds.");
}

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

License:Open Source License

public void incremenalImages() {
    final SqlSession sqlSession = RazorServer.openSession();
    long startTime = System.currentTimeMillis();
    Document document;//w w w  .jav  a2s .  c  o m
    String message = "Create Images started NextpaxAPIKey: " + getApikey();
    LOG.debug(message);
    Date version = new Date();

    String fileName = "paxgenerator_house_pictures_" + getApikey() + ".xml";
    try {
        // House attributes.
        // RelationService.load(sqlSession, Downloaded.PRODUCT_DOWNLOAD_DATE, getAltpartyid(), new Date().toString());
        SAXBuilder parser = new SAXBuilder();

        long startParsing = System.currentTimeMillis();
        document = parser.build(ftp(fileName));
        // document = parser.build(new File(System
        // .getProperty("user.home")
        // + File.separator
        // + "PMS"
        // + File.separator
        // + "nextpax"
        // + File.separator
        // + getApikey()
        // + File.separator + fileName));
        LOG.debug("Time taken to parse " + fileName + " : " + (System.currentTimeMillis() - startParsing)
                + " milli seconds.");

        Element rootNode = document.getRootElement();
        String partner = rootNode.getChildText("Partner");
        List<Element> houses = rootNode.getChildren("Pictures");
        for (Element house : houses) {
            String altid = house.getChildText("HouseID");
            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altid);
            if (product == null) {
                continue;
            }
            String lastimage = sqlSession.getMapper(TextMapper.class)
                    .lastimage(NameId.Type.Product.name() + product.getId() + "-%");
            // if the images exist move to the next property images
            if (lastimage != null) {
                continue;
            }

            ArrayList<NameId> images = new ArrayList<NameId>();
            List<Element> pictures = house.getChildren("Picture");
            for (Element picture : pictures) {
                String name = picture.getChildText("Name");
                // String size = picture.getChildText("Size");
                String type = picture.getChildText("Type");
                String title = getImageTitle(type);

                images.add(new NameId(title,
                        IMAGE_URL + getBrandAbbreviation(partner) + "/" + altid + "/" + name));
            }
            LOG.debug("Total images uploading for the property " + product.getId() + ": " + images.size());

            UploadFileService.uploadImages(sqlSession, NameId.Type.Product, product.getId(), Language.EN,
                    images);
            sqlSession.commit();

            MonitorService.monitor(message, version);
        }
    } catch (Throwable e) {
        sqlSession.rollback();
        LOG.error(e.getMessage());
    } finally {
        sqlSession.close();
        delete(fileName);
    }
    long endTime = System.currentTimeMillis();
    LOG.debug("Total time taken for createImage execution " + getApikey() + " : " + (endTime - startTime) / 1000
            + " seconds.");
}

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

License:Open Source License

@Override
public void readImages() {
    final SqlSession sqlSession = RazorServer.openSession();
    // first download all the images
    /*      CompositeConfiguration config = new CompositeConfiguration();
          config.addConfiguration(new SystemConfiguration());
          try {//from  ww w .ja  v a 2 s . c om
             config.addConfiguration(new PropertiesConfiguration("storage.properties"));
          } catch (ConfigurationException e) {
             LOG.error(e.getMessage());
          }
            
          String rootFolder = config.getString("bp.root.folder");
          Element rootNode = downloadImages(rootFolder);
          String partner = rootNode.getChildText("Partner");
          List<Element> houses = rootNode.getChildren("Pictures");
          long startTime = System.currentTimeMillis();
    */
    String message = "Read Images started NextpaxAPIKey: " + getApikey();
    LOG.debug(message);
    Date version = new Date();
    String fileName = "paxgenerator_house_pictures_" + getApikey() + ".xml";
    try {
        /*         SAXBuilder parser = new SAXBuilder();
                 Document document = parser.build(ftp(fileName));
                 Element rootNode = document.getRootElement();
                 String partner = rootNode.getChildText("Partner");
                 List<Element> houses = rootNode.getChildren("Pictures");*/

        JAXBContext jc = JAXBContext.newInstance(net.cbtltd.rest.nextpax.ProductPictures.class);
        Unmarshaller um = jc.createUnmarshaller();
        ProductPictures productPictures = (ProductPictures) um.unmarshal(ftp(fileName));
        String partner = productPictures.getPartner();
        List<Pictures> houses = productPictures.getPictures();//this should give us list of house objects

        // RelationService.load(sqlSession, Downloaded.PRODUCT_DOWNLOAD_DATE, getAltpartyid(), new Date().toString());

        for (Pictures pictures : houses) {
            String altid = pictures.getHouseID();
            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altid);
            if (product == null) {
                continue;
            }
            ArrayList<NameId> images = new ArrayList<NameId>();
            // List<Element> pictures = house.getChildren("Picture");
            for (Picture picture : pictures.getPicture()) {
                String size = picture.getSize(); // need to check size, to prevent loading small images.
                                                 // n - normal, s - small.
                if (size.equalsIgnoreCase("s")) {
                    continue; // we don't need small images
                }
                String name = picture.getName();
                String type = picture.getType();
                String title = getImageTitle(type);

                images.add(new NameId(title,
                        IMAGE_URL + getBrandAbbreviation(partner) + "/" + altid + "/" + name));
            }
            LOG.debug("Total images uploading for the property " + product.getId() + ": " + images.size());
            UploadFileService.uploadImages(sqlSession, NameId.Type.Product, product.getId(), Language.EN,
                    images);

            sqlSession.commit();
            MonitorService.monitor(message, version);
        }
    } catch (Throwable e) {
        sqlSession.rollback();
        e.printStackTrace();
        LOG.error(e.getMessage());
    } finally {
        sqlSession.close();
        delete(fileName);
    }
    long endTime = System.currentTimeMillis();
    LOG.debug("Total time taken for readImage execution " + getApikey() + " : " + (endTime - startTime) / 1000
            + " seconds.");
}

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

License:Open Source License

@Override
public synchronized void readSchedule() {
    LOG.debug("NextPax readSchedule() key: " + this.getApikey() + "_started");
    Scanner sc = null;/*from   www  . j  a v  a2  s .c  o  m*/
    Date version = new Date();
    String line = "";
    String message = "readSchedule";
    String altid;
    String periodid;
    String startdate;
    String enddate;
    Double length;
    String lastminute;
    String rentprice;
    String bookingcosts;
    String discount;
    String othercosts;
    String totalprice;
    String discountcode;
    String recordhash;
    String[] houseinformation;

    Product product = null;

    String partyId = getAltpartyid();

    boolean firsttime = true;
    long startTime = System.currentTimeMillis();

    LOG.debug(message);
    final SqlSession sqlSession = RazorServer.openSession();
    String filename = "paxgenerator_available_bookingnet_" + getApikey() + ".csv";
    try {
        // RelationService.load(sqlSession, Downloaded.PRODUCT_DOWNLOAD_DATE, getAltpartyid(), new Date().toString());

        long startTimeForCSVRead = System.currentTimeMillis();
        sc = new Scanner(ftp(filename));
        // sc = new Scanner(new BufferedReader(new InputStreamReader(
        // new FileInputStream(System.getProperty("user.home")
        // + File.separator
        // + "PMS"
        // + File.separator
        // + "nextpax"
        // + File.separator
        // + getApikey()
        // + File.separator
        // + filename)
        // )));
        long endTimeForCSVRead = System.currentTimeMillis();
        LOG.debug("Time taken to read csv: " + (endTimeForCSVRead - startTimeForCSVRead));

        SortedSet<DateTime> availableDates = new TreeSet<DateTime>();
        List<Price> prices = new ArrayList<Price>();
        long startTimeForProductProcessing = 0;
        int i = 0;

        // remove header information.
        line = sc.nextLine();
        String currenthouse = "";
        while (sc.hasNext()) {
            line = sc.nextLine();
            if (line.isEmpty()) {
                continue;
            }
            houseinformation = line.split("\\|");

            if (firsttime) {
                currenthouse = houseinformation[0];
                product = sqlSession.getMapper(ProductMapper.class).altread(new NameId(partyId, currenthouse));
                if (product == null) {
                    continue;
                }
                firsttime = false;
                // product = PartnerService.getProduct(sqlSession, partyId, currenthouse); // check for null
                startTimeForProductProcessing = System.currentTimeMillis();
            }

            altid = houseinformation[0];
            periodid = houseinformation[1];
            startdate = houseinformation[2];
            enddate = houseinformation[3];
            length = Double.valueOf(houseinformation[4]);
            lastminute = houseinformation[5];
            rentprice = houseinformation[6];
            bookingcosts = houseinformation[7];
            discount = houseinformation[8];
            othercosts = houseinformation[9];
            totalprice = houseinformation[10];
            discountcode = houseinformation[11];
            recordhash = houseinformation[12];

            // price table
            Price price = new Price();
            price.setAltid(periodid);
            price.setPartyid(getAltpartyid());
            price.setEntitytype(NameId.Type.Product.name());
            price.setEntityid(product.getId());
            price.setCurrency(Currency.Code.EUR.name());
            price.setQuantity(length);
            price.setUnit(Unit.DAY);
            price.setName(Price.RACK_RATE);
            price.setType(NameId.Type.Reservation.name());
            price.setDate(DF.parse(startdate));
            price.setTodate(DF.parse(enddate));

            net.cbtltd.shared.Price exists = sqlSession.getMapper(PriceMapper.class).existsAltID(price);

            price.setFactor(1.0);
            price.setOrganizationid(getAltpartyid());
            price.setRule(getDayOfWeek(DF.parse(startdate)));
            price.setAvailable(1);
            price.setState(Price.CREATED);
            double unitprice = Double.valueOf(totalprice) / length; // what is this ?
            price.setValue(NameId.round(Double.valueOf(totalprice) / length));
            price.setMinimum(Double.valueOf(totalprice));
            price.setMinStay(length.intValue());
            price.setVersion(version);

            price.setEntityid(product.getId());
            if (exists != null) {
                //add price into array and update it after
                // sqlSession.getMapper(PriceMapper.class).create(price);

                // check if there is reservation for this price.
                // if reservation is created and we still get the price,
                // we need to cancel the reservation
                Reservation action = new Reservation();
                action.setProductid(product.getId());
                action.setFromdate(price.getDate());
                action.setTodate(price.getTodate());
                action = sqlSession.getMapper(ReservationMapper.class).collides(action);
                if (action != null && StringUtils.isNotBlank(action.getAltid())) {
                    // cancel this reservation
                    PartnerService.cancelReservation(sqlSession, action);
                }
                price.setId(exists.getId());
                // sqlSession.getMapper(PriceMapper.class).update(price);
            }
            prices.add(price);

            // when we come across a new house will create reservations for
            // the blocked dates for the previous house.
            // create a map of available dates
            // iterate through prices and check off the dates from the
            // collection of month dates and use the rest of the dates
            // to create the reservation
            if (currenthouse.compareTo(altid) != 0 || !sc.hasNext()) {
                if (!sc.hasNext()) {
                    addToAvailableDates(availableDates, startdate, enddate);
                }

                createSchedule(availableDates, product, version, sqlSession);
                // insert list of prices
                sqlSession.getMapper(PriceMapper.class).insertList(prices);
                // clear list
                prices.clear();
                sqlSession.commit();

                LOG.debug("Time taken for Product Process " + currenthouse + " : "
                        + (System.currentTimeMillis() - startTimeForProductProcessing));

                // now cancel price for existing property that we did not process in this run.
                sqlSession.getMapper(PriceMapper.class).cancelversion(price);

                // reset fields
                // create a new set for the next home
                currenthouse = altid;
                availableDates = new TreeSet<DateTime>();
                // product = PartnerService.getProduct(sqlSession, partyId, currenthouse);
                product = sqlSession.getMapper(ProductMapper.class).altread(new NameId(partyId, currenthouse));
                startTimeForProductProcessing = System.currentTimeMillis();
            }

            if (sc.hasNext()) {
                addToAvailableDates(availableDates, startdate, enddate);
            }

            /*            i++;
                        if (i > 0 && i % IsPartner.PRICE_BATCH_SIZE == 0) {
                           LOG.debug("Smart flush for price: " + i);
                           sqlSession.commit();
                        }*/
        }
        sqlSession.commit();

        // Cancel old reservations.
        resetStartTime();
        cancelOldReservations(sqlSession, version);
        LOG.debug("Canceled old reservations: " + (System.currentTimeMillis() - getStartTime()));
        // sqlSession.commit(); // why duplicate?

    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        if (sc != null) {
            try {
                sc.close();
                delete(filename);
                sqlSession.close();
            } catch (Exception e) {
                LOG.error(e.getMessage());
            }
        }
    }
    long endTime = System.currentTimeMillis();
    LOG.debug("NextPax readSchedule() for key: " + this.getApikey() + " done." + " Time: "
            + (endTime - startTime));
    MonitorService.monitor(message, version);
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from w  w w. j  a  v  a2  s . c  o  m
public void readPrices() {
    Date version = new Date();
    String message = "readPrices RMS (Resort Management System)";
    LOG.debug(message);
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        //         RelationService.load(sqlSession, Downloaded.PRODUCT_DOWNLOAD_DATE, getAltpartyid(), new Date().toString());

        SAXBuilder parser = new SAXBuilder();
        Document documentUnitList = parser.build(PartnerService.getInputStream(UNIT_LIST_URL, RMS_SERVER_AUTH));
        Element rootNodeUnitList = documentUnitList.getRootElement();

        List<Element> units = rootNodeUnitList.getChildren("unit");
        for (Element unit : units) {
            String altId = unit.getChildText("unitId");
            LOG.debug("ReadPrice unitID=" + altId);

            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altId, false);
            if (product == null) {
                LOG.error(Error.product_altid.getMessage() + " " + altId);
                //               System.out.println("NOT EXIST property ID: " + altId);
                continue;
            }

            Document documentUnitRates = parser
                    .build(PartnerService.getInputStream(this.getUnitDetailsLink(altId), RMS_SERVER_AUTH));
            Element rootNodeUnitRates = documentUnitRates.getRootElement();
            List<Element> unitRatesList = rootNodeUnitRates.getChild("unit").getChild("rates")
                    .getChildren("rate");
            for (Element unitRate : unitRatesList) {
                Price price = new Price();
                price.setEntityid(product.getId());
                price.setEntitytype(NameId.Type.Product.name());
                price.setPartyid(getAltpartyid());
                price.setName(Price.RACK_RATE);
                price.setType(NameId.Type.Reservation.name());
                String startDateString = unitRate.getChildText("startDate");
                Date fromdate = dateFormaterFromResponse.parse(startDateString);
                price.setDate(fromdate);
                String endDateString = unitRate.getChildText("endDate");
                Date todate = dateFormaterFromResponse.parse(endDateString);
                price.setTodate(todate);
                price.setQuantity(1.0);
                price.setCurrency(product.getCurrency());
                price.setUnit(Unit.DAY);

                Price exists = sqlSession.getMapper(PriceMapper.class).exists(price);
                if (exists == null) {
                    sqlSession.getMapper(PriceMapper.class).create(price);
                } else {
                    price = exists;
                }

                price.setState(Price.CREATED);
                //FIXME check how to set few days in week
                price.setRule(Price.Rule.AnyCheckIn.name());

                //TODO they have weekly rate. What we should do??
                Integer minStay = 0;
                Double rateValue = null;
                try {
                    minStay = Integer.parseInt(unitRate.getChildText("minimumNightStay"));
                } catch (Exception parseExc) {
                }
                try {
                    rateValue = Double.valueOf(unitRate.getChildText("dailyRate"));
                } catch (Exception parseExc) {
                }

                Double minimumValue = minStay * rateValue;

                price.setValue(rateValue);
                price.setCost(rateValue);
                price.setMinStay(minStay);
                price.setMinimum(minimumValue);
                price.setAvailable(1);
                price.setVersion(version);
                sqlSession.getMapper(PriceMapper.class).update(price);
                sqlSession.getMapper(PriceMapper.class).cancelversion(price);

                sqlSession.commit();
            }

        }
    } catch (Throwable x) {
        x.printStackTrace();
        sqlSession.rollback();
        LOG.error(x.getStackTrace());
    } finally {
        sqlSession.close();
    }
    MonitorService.monitor(message, version);

}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from www  .j  av  a 2 s . c  om*/
public void readProducts() {
    String message = "readProducts RMS (Resort Management System) ";
    LOG.debug(message);
    Date version = new Date();

    StringBuilder sbNotKnowLocation = new StringBuilder();
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        RelationService.load(sqlSession, Downloaded.PRODUCT_DOWNLOAD_DATE, getAltpartyid(),
                new Date().toString());

        SAXBuilder parser = new SAXBuilder();
        Document documentUnitList = parser.build(PartnerService.getInputStream(UNIT_LIST_URL, RMS_SERVER_AUTH));
        Element rootNodeUnitList = documentUnitList.getRootElement();

        List<Element> units = rootNodeUnitList.getChildren("unit");
        for (Element unit : units) {
            //now we need to load unit (property) details for every unit
            String altId = unit.getChildText("unitId");
            LOG.debug("Read unitID=" + altId);

            Document documentUnitDetails = parser
                    .build(PartnerService.getInputStream(this.getUnitDetailsLink(altId), RMS_SERVER_AUTH));
            Element rootNodeUnitDetails = documentUnitDetails.getRootElement();
            Element unitDetails = rootNodeUnitDetails.getChild("unit");

            //this we read one more time, just to be sure. But that should be same.
            altId = unitDetails.getChildText("unitId");

            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altId);
            if (product == null) {
                continue;
            }

            Integer roomNumber = 0;
            Integer bathroomNumber = 0;
            Integer personNumber = 0;
            Double latitude = null;
            Double longitude = null;
            Double cleaningFee = 0.0;
            try {
                roomNumber = Integer.parseInt(unitDetails.getChildText("numberOfBedrooms"));
            } catch (Exception parseExc) {
            }
            try {
                bathroomNumber = Integer.parseInt(unitDetails.getChildText("numberOfBathrooms"));
            } catch (Exception parseExc) {
            }
            try {
                personNumber = Integer.parseInt(unitDetails.getChildText("maximumNumberOfPeople"));
            } catch (Exception parseExc) {
            }
            try {
                latitude = Double.valueOf(unitDetails.getChildText("latitude"));
            } catch (Exception parseExc) {
            }
            try {
                longitude = Double.valueOf(unitDetails.getChildText("longitude"));
            } catch (Exception parseExc) {
            }
            try {
                cleaningFee = Double.valueOf(unitDetails.getChildText("cleaningCharge"));
            } catch (Exception parseExc) {
            }

            Element unitAddress = unitDetails.getChild("address");
            StringBuilder physicalAddress = new StringBuilder();
            if (!checkIfValueNullOrEmpty(unitAddress.getChildText("line1"))) {
                physicalAddress.append(unitAddress.getChildText("line1")).append("\n");
            }
            if (!checkIfValueNullOrEmpty(unitAddress.getChildText("line2"))) {
                physicalAddress.append(unitAddress.getChildText("line2")).append("\n");
            }
            if (!checkIfValueNullOrEmpty(unitAddress.getChildText("state"))) {
                physicalAddress.append(unitAddress.getChildText("state")).append("\n");
            }
            if (!checkIfValueNullOrEmpty(unitAddress.getChildText("zipCode"))) {
                physicalAddress.append(unitAddress.getChildText("zipCode")).append("\n");
            }
            if (!checkIfValueNullOrEmpty(unitAddress.getChildText("region"))) {
                physicalAddress.append(unitAddress.getChildText("region")).append("\n");
            }
            if (!checkIfValueNullOrEmpty(unitAddress.getChildText("subRegion"))) {
                physicalAddress.append(unitAddress.getChildText("subRegion")).append("\n");
            }
            if (!checkIfValueNullOrEmpty(unitAddress.getChildText("country"))) {
                physicalAddress.append(unitAddress.getChildText("country")).append("\n");
            }

            product.setCurrency(unitDetails.getChild("details").getChildText("currency"));
            product.setName(unitDetails.getChildText("type") + ", " + unitDetails.getChildText("level") + ", "
                    + unitDetails.getChildText("localAddress"));
            product.setUnit(Unit.DAY);
            product.setRoom(roomNumber);
            product.setBathroom(bathroomNumber);
            product.setQuantity(1);
            product.setPerson(personNumber);
            product.setRank(getRank());
            product.setLatitude(latitude);
            product.setLongitude(longitude);
            product.setPhysicaladdress(physicalAddress.toString());
            product.setCleaningfee(cleaningFee);

            product.setWebaddress(getWebaddress());
            product.setCommission(getCommission());
            product.setDiscount(getDiscount());
            product.setRating(5);
            product.setAltitude(0.0);
            product.setChild(0);
            product.setInfant(0);
            product.setToilet(0);

            product.setVersion(version);

            String countryISO = unitAddress.getChildText("country");
            String state = unitAddress.getChildText("state");
            String city = unitAddress.getChildText("city");
            String latitudeStr = unitDetails.getChildText("latitude");
            String longitudeStr = unitDetails.getChildText("longitude");

            Location location = null;
            if (!(checkIfValueNullOrEmpty(latitudeStr) || checkIfValueNullOrEmpty(longitudeStr))) {
                location = PartnerService.getLocation(sqlSession, city, state, countryISO,
                        checkIfValueNullOrEmpty(latitudeStr) ? null : Double.valueOf(latitudeStr),
                        checkIfValueNullOrEmpty(longitudeStr) ? null : Double.valueOf(longitudeStr));
            } else {
                location = PartnerService.getLocation(sqlSession, city, state, countryISO);
            }

            if (location != null && location.getId() != null) {
                product.setLocationid(location.getId());
            } else {
                sbNotKnowLocation.append("\n").append("RMS (Resort Management System) property: " + altId
                        + " country: " + countryISO + " city: " + city);
                product.setState(Product.SUSPENDED);
            }

            //description build
            //TODO check maybe with real data to add fields locationDescription and sectionDescription
            StringBuilder description = new StringBuilder();
            description.append(unitDetails.getChildText("level")).append("\n\n");
            description.append(unitDetails.getChildText("description")).append("\n\n");

            ArrayList<String> attributes = new ArrayList<String>();
            System.out.println("Type: " + unitDetails.getChildText("type"));
            addType(attributes, unitDetails.getChildText("type"));

            List<Element> attributesList = unitDetails.getChild("miscellaneousFields").getChildren();
            for (Element attribute : attributesList) {
                String exist = attribute.getAttribute("field").getValue();
                addPropertyAttribute(attributes, attribute.getValue(), exist);
            }

            //in search fields there is also some attributes. Generally this attributes
            //are present in regular attributes (miscellaneousFields) but some are not
            List<Element> searchAattributesList = unitDetails.getChild("searchFields").getChildren();
            for (Element attribute : searchAattributesList) {
                String exist = attribute.getAttribute("description").getValue();
                if (attribute.getValue().equalsIgnoreCase("Internet") && isAttributeExist(exist)) {
                    attributes.add("RMA54"); //Internet access
                } else if (attribute.getValue().equalsIgnoreCase("Smoking")) {
                    if (isAttributeExist(exist)) {
                        attributes.add("RMA101");//smoking YES
                    } else {
                        attributes.add("RMA74");//smoking NO
                    }
                } else if (attribute.getValue().equalsIgnoreCase("Pets Allowed")) {
                    if (isAttributeExist(exist)) {
                        attributes.add("PET10"); //PET10 = Domestic pets
                        description.append("Pets are allowed.").append("\n\n");
                    } else {
                        description.append("Pets are not allowed.").append("\n\n");
                    }
                }
            }

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

            product.setPublicText(new Text(product.getPublicId(), product.getName(), Text.Type.HTML, new Date(),
                    description.toString(), Language.EN));
            TextService.update(sqlSession, product.getTexts());

            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);

            sqlSession.commit();

        }

        //canceling not updated products
        Product action = new Product();
        action.setAltpartyid(getAltpartyid());
        action.setState(Product.CREATED);
        action.setVersion(version);

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

    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
        x.printStackTrace();
    } finally {
        sqlSession.close();
    }
    LOG.debug("Missing Places" + sbNotKnowLocation.toString());
    MonitorService.monitor(message, version);

}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from w ww .  jav a  2 s.c om
public void readImages() {
    Date timestamp = new Date();
    String message = "readImages RMS (Resort Management System)";
    LOG.debug(message);

    final SqlSession sqlSession = RazorServer.openSession();
    try {
        RelationService.load(sqlSession, Downloaded.PRODUCT_DOWNLOAD_DATE, getAltpartyid(),
                new Date().toString());

        SAXBuilder parser = new SAXBuilder();
        Document documentUnitList = parser.build(PartnerService.getInputStream(UNIT_LIST_URL, RMS_SERVER_AUTH));
        Element rootNodeUnitList = documentUnitList.getRootElement();

        List<Element> units = rootNodeUnitList.getChildren("unit");
        for (Element unit : units) {
            String altId = unit.getChildText("unitId");
            Document documentUnitDetails = parser
                    .build(PartnerService.getInputStream(this.getUnitDetailsLink(altId), RMS_SERVER_AUTH));
            Element rootNodeUnitDetails = documentUnitDetails.getRootElement();
            Element unitDetails = rootNodeUnitDetails.getChild("unit");

            try {
                Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altId, false);
                if (product == null) {
                    continue;
                }
                List<Element> imageList = unitDetails.getChild("photos").getChildren("photo");
                if (HasUrls.LIVE && imageList != null && imageList.size() > 0) {
                    ArrayList<NameId> images = new ArrayList<NameId>();
                    for (Element imgElement : imageList) {
                        images.add(new NameId("", imgElement.getChildText("url")));
                    }
                    UploadFileService.uploadImages(sqlSession, NameId.Type.Product, product.getId(),
                            Language.EN, images);
                }
                sqlSession.commit();
            } catch (Throwable x) {
                LOG.error(x.getMessage());
                x.printStackTrace();
            }
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
    }
    MonitorService.monitor(message, timestamp);

}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from   www . j a  v  a  2  s .c  o m
public void readSchedule() {
    Date version = new Date();
    String message = "readSchedule RMS (Resort Management System)";

    Date startDate = Time.getDateStart();
    Date endDate = Time.addDuration(startDate, SCHEDULES_FOR_NUMBER_DAYS_IN_FUTURE, Time.DAY);

    LOG.debug(message);
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        String depStart = this.formatDateToCronRequest(startDate);
        String depEnd = this.formatDateToCronRequest(endDate);

        String reservationGetUrl = RMS_API_URL + "reservation/list?departureStart=" + depStart
                + "&departureEnd=" + depEnd;

        SAXBuilder parser = new SAXBuilder();
        Document document = parser.build(PartnerService.getInputStream(reservationGetUrl, RMS_SERVER_AUTH));
        Element rootNode = document.getRootElement();
        List<Element> reservationList = rootNode.getChildren("reservation");
        for (Element reservationElement : reservationList) {
            String altId = reservationElement.getChildText("unitId");
            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altId, false);
            if (product == null) {
                continue;
            }

            try {
                String arrivalDateString = reservationElement.getChildText("arrival");
                Date fromDate = dateFormaterFromResponse.parse(arrivalDateString);
                String departureDateString = reservationElement.getChildText("departure");
                Date toDate = dateFormaterFromResponse.parse(departureDateString);
                PartnerService.createSchedule(sqlSession, product, fromDate, toDate, version);
                PartnerService.cancelSchedule(sqlSession, product, version);

            } catch (Throwable x) {
                LOG.error(x.getMessage());
                x.printStackTrace();
            }
        }

        sqlSession.commit();

    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
    }
    MonitorService.monitor(message, version);
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from w w  w  .j a v a  2s .com
public void readPrices() {
    Date version = new Date();
    Date toDateForExtraPrices = Time.addDuration(version, FEES_PRICES_FOR_NUMBER_DAYS_IN_FUTURE, Time.DAY);
    Date minimumToDateForExtraPricesUpdate = Time.addDuration(version, FEES_PRICES_UPDATE_DAYS, Time.DAY);
    String message = "readPrices Streamline (Altpartyid:" + this.getAltpartyid() + ")";
    LOG.debug(message + version.toString());

    final SqlSession sqlSession = RazorServer.openSession();
    try {
        long functionStart = System.currentTimeMillis();
        String responseReservationsAndPrices = getXmlFeedConnection(sqlSession, this.getAltpartyid());
        SAXBuilder builder = new SAXBuilder();
        Document document = (Document) builder.build(new StringReader(responseReservationsAndPrices));
        Element rootNode = document.getRootElement();
        List<Element> properties = rootNode.getChildren("property");
        long gettingApiDataEnd = System.currentTimeMillis();
        LOG.debug("Reading API data takes: " + (gettingApiDataEnd - functionStart) + "ms");
        for (Element property : properties) {
            long onePropertyStart = System.currentTimeMillis();
            String altId = property.getChildText("propertyId");
            try {
                Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altId, false);
                if (product == null) {
                    //                  LOG.error("ERROR product not exsit:" + altId);
                    continue;
                }

                String productId = product.getId();

                //Rates
                ArrayList<Price> pricesFromApi = new ArrayList<Price>();
                ArrayList<Yield> discountYieldFromApi = new ArrayList<Yield>();
                //               ArrayList<Adjustment> adjustmentsFromApi = new ArrayList<Adjustment>();
                List<Element> ratePeriodsList = property.getChild("ratePeriods").getChildren("ratePeriod");
                for (Element ratePeriodEl : ratePeriodsList) {
                    String fromDateStr = ratePeriodEl.getChild("dateRange").getChildText("beginDate");
                    String toDateStr = ratePeriodEl.getChild("dateRange").getChildText("endDate");
                    Date fromDate = responseDF.parse(fromDateStr);
                    Date toDate = responseDF.parse(toDateStr);

                    int minimumStay = Integer.parseInt(ratePeriodEl.getChildText("minimumStay"));
                    List<Element> ratesList = ratePeriodEl.getChild("rates").getChildren("rate");
                    String dailyCurrency = product.getCurrency();
                    String weekendCurrency = product.getCurrency();
                    String weeklyCurrency = product.getCurrency();
                    String monthlyCurrency = product.getCurrency();
                    Double dailyRateValue = null;
                    Double weekendRateValue = null;
                    Double weeklyRateValue = null;
                    Double monthlyRateValue = null;
                    for (Element rateEl : ratesList) {
                        String rateAmountStr = rateEl.getChildText("amount");
                        String currency = rateEl.getChild("amount").getAttributeValue("currency");
                        Double rateValue = null;
                        try {
                            rateValue = Double.valueOf(rateAmountStr);
                        } catch (Exception parseExc) {
                        }

                        if (rateEl.getAttributeValue("rateType").equals("NIGHTLY_WEEKDAY")) {
                            dailyCurrency = currency;
                            dailyRateValue = rateValue;
                            Double minumumValue = rateValue * minimumStay;
                            this.addPrice(pricesFromApi, product, dailyCurrency, Unit.DAY, fromDate, toDate,
                                    rateValue, minumumValue, minimumStay);
                        } else if (rateEl.getAttributeValue("rateType").equals("NIGHTLY_WEEKEND")) {
                            weekendRateValue = rateValue;
                            weekendCurrency = currency;
                        } else if (rateEl.getAttributeValue("rateType").equals("WEEKLY")) {
                            weeklyRateValue = rateValue;
                            weeklyCurrency = currency;
                        } else if (rateEl.getAttributeValue("rateType").equals("MONTHLY")) {
                            monthlyRateValue = rateValue;
                            monthlyCurrency = currency;
                        }
                    }

                    if (weekendRateValue != null && dailyRateValue != null
                            && (weekendRateValue - dailyRateValue != 0.0)) {
                        if (!weekendCurrency.equalsIgnoreCase(dailyCurrency)) {
                            Double currencyRate = WebService.getRate(sqlSession, weekendCurrency, dailyCurrency,
                                    new Date());
                            weekendRateValue = PaymentHelper
                                    .getAmountWithTwoDecimals(weekendRateValue * currencyRate);
                        }
                        Yield weekendRateYield = YieldService.createWeekendRate(productId, dailyRateValue,
                                weekendRateValue, fromDate, toDate);
                        if (weekendRateYield != null) {
                            weekendRateYield.setParam(Yield.DAYS_OF_WEEKEND_FRI_SAT);
                            discountYieldFromApi.add(weekendRateYield);
                        }

                        //                     Double extraAdjustmentPrice = weekendRateValue - dailyRateValue;
                        //                     Adjustment adjustmentPrice = new Adjustment();
                        //                     adjustmentPrice.setCurrency(dailyCurrency);
                        //                     adjustmentPrice.setPartyID(getAltpartyid());
                        //                     adjustmentPrice.setProductID(product.getId());
                        //                     adjustmentPrice.setFromDate(fromDate);
                        //                     adjustmentPrice.setToDate(toDate);
                        //                     adjustmentPrice.setMaxStay(999);
                        //                     adjustmentPrice.setMinStay(minimumStay);
                        //                     adjustmentPrice.setExtra(extraAdjustmentPrice);
                        //                     adjustmentPrice.setServicedays(Adjustment.WEEKEND);
                        //                     
                        //                     adjustmentsFromApi.add(adjustmentPrice);
                    }

                    if (weeklyRateValue != null && dailyRateValue != null) {
                        if (!weeklyCurrency.equalsIgnoreCase(dailyCurrency)) {
                            Double currencyRate = WebService.getRate(sqlSession, weeklyCurrency, dailyCurrency,
                                    new Date());
                            weeklyRateValue = PaymentHelper
                                    .getAmountWithTwoDecimals(weeklyRateValue * currencyRate);
                        }
                        Yield weeklyDiscount = YieldService.createLengthOfStayDiscount(productId,
                                dailyRateValue, weeklyRateValue, 7, fromDate, toDate);
                        if (weeklyDiscount != null) {
                            discountYieldFromApi.add(weeklyDiscount);
                        }
                    }

                    if (monthlyRateValue != null && dailyRateValue != null) {
                        if (!monthlyCurrency.equalsIgnoreCase(dailyCurrency)) {
                            Double currencyRate = WebService.getRate(sqlSession, monthlyCurrency, dailyCurrency,
                                    new Date());
                            monthlyRateValue = PaymentHelper
                                    .getAmountWithTwoDecimals(monthlyRateValue * currencyRate);
                        }
                        //TODO set number of days in month
                        //This is now set on 30, but in case of Streamline
                        //min days for month price can be 27,28 
                        Yield monthlyDiscount = YieldService.createLengthOfStayDiscount(productId,
                                dailyRateValue, monthlyRateValue, 30, fromDate, toDate);
                        if (monthlyDiscount != null) {
                            discountYieldFromApi.add(monthlyDiscount);
                        }
                    }

                }

                //               long handlingPropertyRatesDataEnd = System.currentTimeMillis();
                //               LOG.debug("Handling property rates data takes: "+ (handlingPropertyRatesDataEnd-onePropertyStart) + "ms");

                PartnerService.updateProductPrices(sqlSession, product, NameId.Type.Product.name(),
                        pricesFromApi, version, false, null);
                //               long updateProductPricesEnd = System.currentTimeMillis();
                //               LOG.debug("PartnerService.updateProductPrices takes: "+ (updateProductPricesEnd-handlingPropertyRatesDataEnd) + "ms");

                //               PartnerService.updateProductAdjustments(sqlSession, product, adjustmentsFromApi, version);
                PartnerService.updateProductRateYields(sqlSession, product, discountYieldFromApi, version);
                //               long updateProductRateYieldsEnd = System.currentTimeMillis();
                //               LOG.debug("PartnerService.updateProductRateYields takes: "+ (updateProductRateYieldsEnd-updateProductPricesEnd) + "ms");

                ArrayList<Fee> feeFromApi = new ArrayList<Fee>();
                ArrayList<Tax> taxListFromApi = new ArrayList<Tax>();
                ArrayList<Tax> taxSpecialListForSomeFee = new ArrayList<Tax>();

                //it is important to first process fees and than taxes
                //because in there 'fees' we will have some tax which are only for some fees..
                //Fees
                List<Element> feesList = property.getChild("fees").getChildren("fee");
                for (Element feeElement : feesList) {
                    this.processFeeFromApi(feeFromApi, taxListFromApi, taxSpecialListForSomeFee, feeElement,
                            product, toDateForExtraPrices);
                }

                //taxes
                List<Element> taxesElementList = property.getChild("taxes").getChildren("tax");
                for (Element taxElement : taxesElementList) {
                    this.processFeeFromApi(feeFromApi, taxListFromApi, taxSpecialListForSomeFee, taxElement,
                            product, toDateForExtraPrices);
                }

                //               long handlingPropertyFeesAndTaxesDataEnd = System.currentTimeMillis();
                //               LOG.debug("Handling property fees and taxes data takes: "+ (handlingPropertyFeesAndTaxesDataEnd-updateProductRateYieldsEnd) + "ms");

                PartnerService.updateProductTaxes(sqlSession, product, taxListFromApi, version);

                //               long updateProductTaxesEnd = System.currentTimeMillis();
                //               LOG.debug("PartnerService.updateProductTaxes takes: "+ (updateProductTaxesEnd-handlingPropertyFeesAndTaxesDataEnd) + "ms");

                FeeService.updateProductFees(sqlSession, product, feeFromApi, version, true,
                        minimumToDateForExtraPricesUpdate);

                //               long updateProductFeesEnd = System.currentTimeMillis();
                //               LOG.debug("FeeService.updateProductFees takes: "+ (updateProductFeesEnd-updateProductTaxesEnd) + "ms");

                sqlSession.commit();

                LOG.debug("TOTAL one property (altID=" + altId + ") takes: "
                        + (System.currentTimeMillis() - onePropertyStart) + "ms");
            } catch (Throwable x) {
                LOG.error(Error.product_data.name() + altId);
                x.printStackTrace();
            }
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
    }
    MonitorService.monitor(message, version);

}