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

License:Open Source License

private void createOrUpdateProducts(HashSet<String> productsProceeded) {
    long startTime = System.currentTimeMillis();
    final SqlSession sqlSession = RazorServer.openSession();

    String partyId = getAltpartyid();
    String fileName = "staytoday.xml";
    Map<String, Location> locations = new HashMap<String, Location>();
    try {/*from   w ww  .  j  av a2  s  .  c  o  m*/
        // House attributes.
        RelationService.load(sqlSession, Downloaded.PRODUCT_DOWNLOAD_DATE, partyId, new Date().toString());
        SAXBuilder parser = new SAXBuilder();

        long startParsing = System.currentTimeMillis();
        Document document = null;
        //document = parser.build(ftp(fileName));
        System.out.println("HERE IS FILE PARSING");

        String workingDirectory = System.getProperty("user.dir");
        document = parser.build(new File(workingDirectory + "\\doc\\staytoday.xml"));

        //LOG.debug("Time taken to parse " + fileName + " : " + (System.currentTimeMillis() - startParsing) + " milli seconds.");

        Element rootNode = document.getRootElement();
        Namespace ns = rootNode.getNamespace();
        List<Element> houses = rootNode.getChildren("offer", ns);
        System.out.println(rootNode.getNamespace());
        System.out.println(rootNode.getChild("generation-date", ns).getName());
        System.out.println("Number of properties " + houses.size());
        int i = 0;
        for (Element house : houses) {
            ArrayList<String> attributes = new ArrayList<String>();
            // ArrayList<NameId> images = new ArrayList<NameId>();
            // StringBuilder description = new StringBuilder();

            String altid = house.getAttributeValue("internal-id");
            String name = house.getChildText("Name"); // sometimes empty

            Element locationNode = house.getChild("location", ns);

            String longitudeValue = locationNode.getChildText("longitude");
            String latitudeValue = locationNode.getChildText("latitude");
            Double longitude = longitudeValue == null ? null : Double.valueOf(longitudeValue);
            Double latitude = latitudeValue == null ? null : Double.valueOf(latitudeValue);

            String country = locationNode.getChildText("country");
            String place = locationNode.getChildText("city");
            String address = locationNode.getChildText("address"); // never used yet

            Element fee = house.getChild("fees");

            String region = house.getChildText("Region"); // might be empty? TODO check what to do in such case
            if (StringUtils.isNotBlank(region) && region.length() > 2) {
                region = region.substring(2);
            }
            String zipCode = house.getChildText("ZipCode");
            String minchildren = house.getChildText("MinChildren"); // MinChildren
            String minpersons = house.getChildText("MinPersons"); // MaxPersons
            String maxpersons = house.getChildText("MaxPersons");
            String currency = house.getChildText("Currency");

            // attribute list
            String pool = house.getChildText("Pool");
            String tennis = house.getChildText("Tennis");
            String ski = house.getChildText("Ski");
            String type = house.getChildText("Type");
            String numberofstars = house.getChildText("NumberOfStars");
            String numberofpets = house.getChildText("NumberOfPets");

            // String water = house.getChildText("Water"); // mapping is not known, probable match LOC33
            // String arrivalday = house.getChildText("ArrivalDay"); // we may need this.
            // String brand = house.getChildText("Brand");

            // build the list

            if (StringUtils.isBlank(numberofstars)) {
                numberofstars = "0";
            }

            if (StringUtils.isNotBlank(pool) && pool.equals("Y")) {
                attributes.add(ATTRIBUTES.get("pool"));
            }
            if (StringUtils.isNotBlank(tennis) && tennis.equals("Y")) {
                attributes.add(ATTRIBUTES.get("tennis"));
            }
            if (StringUtils.isNotBlank(ski) && ski.equals("Y")) {
                attributes.add(ATTRIBUTES.get("ski"));
            }

            if (StringUtils.isNotBlank(numberofpets) && Integer.parseInt(numberofpets) > 0) {
                attributes.add(ATTRIBUTES.get("All pets"));
            }

            if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(HOUSE_TYPES.get(type))) {
                if (type.equals("APO")) {
                    String[] apartmentTypes = HOUSE_TYPES.get(type).split(",");
                    for (String ota : apartmentTypes) {
                        attributes.add(ota);
                    }
                } else {
                    attributes.add(HOUSE_TYPES.get(type));
                }
            } else {
                LOG.debug("Property type is not available for product <" + altid + ">: " + type);
            }

            // we can use these later on when we build POI database. Nextpax provides separate feed for holiday parks
            String holidaypark = house.getChildText("HolidayPark");
            String skiarea = house.getChildText("SkiArea");

            Product product = PartnerService.getProduct(sqlSession, partyId, altid);
            Location location;
            if (product != null && product.getLocationid() != null) {
                location = sqlSession.getMapper(LocationMapper.class).read(product.getLocationid());
            } else {
                location = locations.get(StringUtils.isNotBlank(place) ? place + country : zipCode + country);
            }
            // set location if null
            // look in the database first
            // then do a google geocode API lookup
            if (location == null
                    && (StringUtils.isBlank(place) || PATTERN_FOR_SPECIAL_CHARACTERS.matcher(place).find())) {
                location = PartnerService.getLocation(sqlSession, zipCode, country, latitude, longitude);
                locations.put(StringUtils.isNotBlank(place) ? place + country : zipCode + country, location);
            } else if (location == null) {
                place = ISO8859CharacterNormalizer.decode(place);
                location = PartnerService.getLocation(sqlSession, place, region, country, latitude, longitude,
                        zipCode);
                locations.put(place + country, location); // will create too big map. Maybe use only location ID instead of whole object
            }

            // set the name if it is blank
            if (StringUtils.isBlank(name) && location != null) {
                String locationName = location.getName() == null ? location.getGname() : location.getName();
                // sometimes GeoLocation returns null, in this case, use gname.
                locationName = locationName == null ? location.getAdminarea_lvl_1() : locationName;
                name = "House" + " in " + locationName; // Set the Name to be sure it will not be null after this point.
                if (attributes.size() > 0) {
                    ArrayList<NameId> pctList = sqlSession.getMapper(AttributeMapper.class)
                            .pctListValue(new net.cbtltd.shared.Attribute("PCT",
                                    attributes.get(0).substring("PCT".length())));
                    for (NameId attribute : pctList) { // what if list is empty?
                        name = attribute.getName() + " in " + locationName;
                    }
                }
            } // check if this might go for 'else'

            if (product == null) {
                LOG.debug("Incative property <" + altid + ">. Updating...");
                //according to the code, following line will give us exact property, but with inactive state.
                product = sqlSession.getMapper(ProductMapper.class).altread(new NameId(partyId, altid));
            }
            product = createOrUpdateProductModel(location, place, region, zipCode, country, maxpersons,
                    minchildren, numberofstars, currency, latitude, longitude, name, product);
            sqlSession.getMapper(ProductMapper.class).update(product);
            productsProceeded.add(altid);

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

            LOG.debug(i++ + " " + altid + " " + product.getId() + " " + product.getId() + " "
                    + product.getName());
            sqlSession.commit();
        }
    } catch (Exception x) {
        sqlSession.rollback();
        x.printStackTrace();
        LOG.error(x.getMessage());
    } finally {
        //         sqlSession.commit(); //TODO remove? not sure if we need this
        sqlSession.close();
        delete(fileName);
    }
    LOG.debug("Time taken to complete create products for " + getApikey() + " : "
            + ((System.currentTimeMillis() - startTime)) / 1000 + " seconds.");
}

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

License:Open Source License

private void setLocation() {
    final SqlSession sqlSession = RazorServer.openSession();
    String altid = "";
    Product product;//ww w . j  a va2s.c  om

    long startTime = System.currentTimeMillis();
    String fileName = "paxgenerator_houses_" + getApikey() + ".xml";
    Map<String, Location> locations = new HashMap<String, Location>();
    int i = 0;
    try {
        // RelationService.load(sqlSession, Downloaded.PRODUCT_DOWNLOAD_DATE, getAltpartyid(), new Date().toString());
        SAXBuilder parser = new SAXBuilder();
        long startParsing = System.currentTimeMillis();
        Document document = null;
        document = parser.build(new File(System.getProperty("user.home") + File.separator + "PMS"
                + File.separator + "nextpax" + File.separator + fileName));
        LOG.debug("Time taken to parse " + fileName + " : " + (System.currentTimeMillis() - startParsing)
                + " milli seconds.");

        Element rootNode = document.getRootElement();
        List<Element> houses = rootNode.getChildren("House");
        for (Element house : houses) {
            altid = house.getChildText("HouseID");
            ArrayList<String> attributes = new ArrayList<String>();
            ArrayList<NameId> images = new ArrayList<NameId>();
            StringBuilder description = new StringBuilder();

            String country = house.getChildText("Country");
            String region = house.getChildText("Region");
            if (StringUtils.isNotBlank(region) && region.length() > 2) {
                region = region.substring(2);
            }
            String place = house.getChildText("Place");
            String zipCode = house.getChildText("ZipCode");
            String name = house.getChildText("Name");
            String latitude = house.getChildText("Latitude");
            String longitude = house.getChildText("Longitude");
            // attribute list
            String type = house.getChildText("Type");
            // build the list
            if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(HOUSE_TYPES.get(type))) {
                if (type.equals("APO")) {
                    String[] apartmentTypes = HOUSE_TYPES.get(type).split(",");
                    for (String ota : apartmentTypes) {
                        attributes.add(ota);
                    }
                } else {
                    attributes.add(HOUSE_TYPES.get(type));
                }
            } else {
                LOG.debug("Property type is not available for product <" + altid + ">: " + type);
            }

            product = PartnerService.getProduct(sqlSession, getAltpartyid(), altid);
            if (product == null) {
                LOG.debug("Property does not exist <" + altid + ">");
            } else if (StringUtils.isBlank(product.getLocationid())) {
                Location location = null;
                LOG.debug("Processing location altid/place: " + altid + " " + place);
                location = locations.get(StringUtils.isNotBlank(place) ? place + country : zipCode + country);
                if (StringUtils.isBlank(place) || PATTERN_FOR_SPECIAL_CHARACTERS.matcher(place).find()) {
                    if (location == null) {
                        location = PartnerService.getLocation(sqlSession, zipCode, country,
                                latitude == null ? null : Double.valueOf(latitude),
                                longitude == null ? null : Double.valueOf(longitude));
                        locations.put(StringUtils.isNotBlank(place) ? place + country : zipCode + country,
                                location);
                    }
                } else {
                    if (location == null) {
                        try {
                            place = ISO8859CharacterNormalizer.decode(place);
                        } catch (Exception e) {
                            LOG.error("Character mapping does not have mapping for place/altid/country: "
                                    + place + ":" + altid + ":" + country);
                            continue;
                        }
                        location = PartnerService.getLocation(sqlSession, place, region, country,
                                latitude == null ? null : Double.valueOf(latitude),
                                longitude == null ? null : Double.valueOf(longitude), zipCode);
                        locations.put(place + country, location);
                    }
                }

                // set the name if it is blank
                if (StringUtils.isBlank(name)) {
                    if (attributes.size() > 0) {
                        ArrayList<NameId> pctList = sqlSession.getMapper(AttributeMapper.class)
                                .pctListValue(new net.cbtltd.shared.Attribute("PCT",
                                        attributes.get(0).substring("PCT".length())));
                        for (NameId attribute : pctList) {
                            name = attribute.getName() + " in "
                                    + (StringUtils.isNotBlank(location.getName()) ? location.getName() : place);
                        }
                    } else {
                        name = "House" + " in "
                                + (StringUtils.isNotBlank(location.getName()) ? location.getName() : place);
                    }
                } else {
                    name = ISO8859CharacterNormalizer.decode(name);
                }

                updateProductModelForLocation(location, name, product);
                sqlSession.getMapper(ProductMapper.class).update(product);
                LOG.debug("Location processed altID/Name/Location: " + altid + " " + product.getName() + " "
                        + (location == null ? null : location.getName()));
                i++;
            }
            sqlSession.commit();
        }
    } catch (GoogleLocationLimitException e) {
        sqlSession.commit();
        sqlSession.close();
        LOG.error(e.getMessage());
        LOG.debug("Processing location for house id: " + altid + " total locations processed: " + i);
    } catch (Throwable x) {
        sqlSession.rollback();
        x.printStackTrace();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
    }
    LOG.debug("Time taken to update houses(" + i + ")" + "locations(" + locations.size() + ") for "
            + getApikey() + " : " + ((System.currentTimeMillis() - startTime)) / 1000 + " seconds.");
}

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;//  ww  w.j av a 2  s.co 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  ww.  j  a v  a2  s.co  m
    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;/*from  w  w  w . j a v a  2 s. 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 {/*  w  ww  .j av  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

private void cancelOldReservations(SqlSession sqlSession, Date version) {
    // sqlSession = RazorServer.openSession();
    Reservation reservation = new Reservation();
    reservation.setVersion(version);/*from ww w. ja va2 s. c om*/
    reservation.setAltpartyid(getAltpartyid());
    sqlSession.getMapper(ReservationMapper.class).cancelversionbypartyid(reservation);

    sqlSession.commit();
}

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;//  w ww  .  j av a 2  s.  co 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.ReservationRest.java

@POST
@Consumes(MediaType.APPLICATION_XML)/*ww w. j av a2 s.c  o  m*/
@Path("/")
@Descriptions({
        @Description(value = "Create a reservation of a product between the specified dates", target = DocTarget.METHOD),
        @Description(value = "Uploaded Reservation", target = DocTarget.RETURN),
        @Description(value = "Request", target = DocTarget.REQUEST),
        @Description(value = "Response", target = DocTarget.RESPONSE),
        @Description(value = "Resource", target = DocTarget.RESOURCE) })
public static synchronized Reservation postReservation(Reservation rq,
        @Description("Mandatory POS Code") @DefaultValue(Constants.NO_POS) @QueryParam("pos") String pos,
        @Description("Optional XSLT") @DefaultValue(Constants.NO_XSL) @QueryParam("xsl") String xsl) {
    Reservation persistedReservation = setReservation(rq, pos, xsl);
    //persist the reservation extension here
    SqlSession sqlSession = RazorServer.openSession();
    String reservationId = persistedReservation.getAltid();
    //delete already existing record and persist the new ones
    ReservationExt query = new ReservationExt();
    query.setReservationId(reservationId);
    List<ReservationExt> listTempReservationExt = sqlSession.getMapper(ReservationExtMapper.class)
            .readReservationExt(query);
    if (listTempReservationExt != null) {
        LOG.info("No of records already exists in ext" + listTempReservationExt.size());
    }

    if (listTempReservationExt != null && listTempReservationExt.size() > 0
            && !State.Cancelled.name().equalsIgnoreCase(rq.getState())) {
        LOG.info("Deleting records with reservation id " + reservationId);
        sqlSession.getMapper(ReservationExtMapper.class).delete(reservationId);
    }
    List<ReservationExt> listPersistedReservationExt = new ArrayList<ReservationExt>();
    for (ReservationExt ext : rq.getListReservationExt()) {
        ext.setReservationId(reservationId);
        ext.setState("Created");
        if ("Guest".equalsIgnoreCase(ext.getType())) {
            persistedReservation.setGuestName(ext.getName());
        }
        sqlSession.getMapper(ReservationExtMapper.class).create(ext);
        listPersistedReservationExt.add(ext);
    }
    persistedReservation.setListReservationExt(listPersistedReservationExt);
    sqlSession.commit();
    sqlSession.close();
    return persistedReservation;
}

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

@GET
@Path("/createwithpayment")
@Descriptions({ @Description(value = "Create the reservation and payment", target = DocTarget.METHOD),
        @Description(value = "Provisional Reservation", target = DocTarget.RETURN),
        @Description(value = "Request", target = DocTarget.REQUEST),
        @Description(value = "Response", target = DocTarget.RESPONSE),
        @Description(value = "Resource", target = DocTarget.RESOURCE) })
public static synchronized ReservationResponse createReservationAndPayment(Reservation rq,
        @Description(value = "Point of sale code") @QueryParam("pos") String pos) {
    DateTime fromDateTime = new DateTime(rq.getFromdate());
    DateTime toDateTime = new DateTime(rq.getTodate());

    Integer cardType = 0;//w  w w  .j  a va  2s .  com
    /*
     * "0" - MASTER CARD
       "1" - VISA
       "2" - AMERICAN EXPRESS
       "3" - DINERS CLUB
       "4" - DISCOVER
       "5" - JBC
     */
    if ("Master Card".equalsIgnoreCase(rq.getCardType())) {
        cardType = 0;
    } else if ("Visa".equalsIgnoreCase(rq.getCardType())) {
        cardType = 1;
    } else if ("American Express".equalsIgnoreCase(rq.getCardType())) {
        cardType = 2;
    }
    Integer cardCode = 0;
    try {
        cardCode = Integer.parseInt(rq.getCardcode());
    } catch (NumberFormatException e) {
        cardCode = 123;
    }
    ReservationResponse reservationResponse = createReservationPayment(pos, rq.getProductid(),
            dateTimeFormatter.print(fromDateTime), dateTimeFormatter.print(toDateTime), rq.getEmailaddress(),
            rq.getFamilyname(), rq.getFirstname(), rq.getNotes(), rq.getCardnumber(), rq.getCardmonth(),
            rq.getCardyear(), rq.getCost() + "", rq.getCurrency(), rq.getPhoneNumber(), cardType, cardCode,
            rq.getAdult(), rq.getChild(), rq.getAddrress(), rq.getCountry(), "", rq.getCity(), rq.getZip(), 0,
            0, 0, rq.getAltid());
    LOG.info("reservationResponse " + reservationResponse.SUCCESS);

    //if(reservationResponse!=null && reservationResponse.SUCCESS){
    LOG.info("Start to persist reservation extension here size is " + rq.getListReservationExt().size());

    //persist the reservation extension here
    SqlSession sqlSession = RazorServer.openSession();
    Reservation reservation = null;

    if (reservationResponse.getReservationInfo() != null) {
        reservation = sqlSession.getMapper(ReservationMapper.class)
                .read(reservationResponse.getReservationInfo().getId());

        List<ReservationExt> listPersistedReservationExt = new ArrayList<ReservationExt>();
        for (ReservationExt ext : rq.getListReservationExt()) {
            ext.setReservationId(reservation.getAltid());
            ext.setState("Created");
            if ("Guest".equalsIgnoreCase(ext.getType())) {
                reservation.setGuestName(ext.getName());
            }
            sqlSession.getMapper(ReservationExtMapper.class).create(ext);
            listPersistedReservationExt.add(ext);
        }

        LOG.info("Persisted Addons size " + listPersistedReservationExt.size());
        reservation.setListReservationExt(listPersistedReservationExt);
    }

    sqlSession.commit();
    sqlSession.close();
    //   }
    return reservationResponse;
    /*return createReservationPayment("5e7e3a77b3714ea2", "121","2014-07-04 ","2014-07-04", "senthil.subash@nibodha.com", "Subash", "Senthil", "Sample Notes", "5346330641608164", "11","2018", 
    "100", "EUR", "9940483172", 0,123 , 2, 0, "Test Addr", "USA", "Cali", "Irvine", "", 11, 11,1980);*/
}