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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from  w w w  . ja  v a2 s  . c  o  m
public void readProducts() {

    String message = "readProducts Streamline (Altpartyid:" + this.getAltpartyid() + ")";
    LOG.debug(message);

    Date version = new Date();
    String responseAllProperties;

    StringBuilder sbNotKnowLocation = new StringBuilder();
    final SqlSession sqlSession = RazorServer.openSession();
    try {

        responseAllProperties = createXMLRequestToStreamline(sqlSession, "GetPropertyList", "");
        SAXBuilder builder = new SAXBuilder();
        Document document = (Document) builder.build(new StringReader(responseAllProperties));
        Element rootNode = document.getRootElement();
        List<Element> properties = rootNode.getChild("data").getChildren("property");
        for (Element property : properties) {
            try {
                String altId = property.getChildText("id");
                //            LOG.debug("Current AltId="+altId);
                String countryISO = property.getChildText("country_name");

                //data for finding location
                String state = property.getChildText("state_name");
                String city = property.getChildText("city");
                String latitudeLocationStr = property.getChildText("location_latitude");
                String longitudeLocationStr = property.getChildText("location_longitude");

                //Streamline provide us 2 set of coordinates. One for location (city) and one for property. 
                //This coordinates will be used for finding locations, so first we use location coordinates,
                //and if not exist we use property coordinates
                if (StringUtils.isEmpty(latitudeLocationStr) && StringUtils.isEmpty(longitudeLocationStr)) {
                    latitudeLocationStr = property.getChildText("latitude");
                    longitudeLocationStr = property.getChildText("longitude");
                }

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

                if (LOG.isDebugEnabled())
                    LOG.debug("Processing property : " + product.getName());

                Integer roomNumber = 0;
                Integer bathroomNumber = 0;
                Integer maxPersonTotalNumber = 0;
                Integer childNumber = 0;
                Integer adultsNumber = 0;
                Double latitude = null;
                Double longitude = null;
                try {
                    roomNumber = Integer.parseInt(property.getChildText("bedrooms_number"));
                } catch (Exception parseExc) {
                    LOG.error("Parse exception: " + parseExc.getMessage());
                }
                try {
                    bathroomNumber = Integer.parseInt(property.getChildText("bathrooms_number"));
                } catch (Exception parseExc) {
                    LOG.error("Parse exception: " + parseExc.getMessage());
                }
                try {
                    maxPersonTotalNumber = Integer.parseInt(property.getChildText("max_occupants"));
                } catch (Exception parseExc) {
                    LOG.error("Parse exception: " + parseExc.getMessage());
                }
                try {
                    adultsNumber = Integer.parseInt(property.getChildText("max_adults"));
                } catch (Exception parseExc) {
                    LOG.error("Parse exception: " + parseExc.getMessage());
                }
                childNumber = maxPersonTotalNumber - adultsNumber;
                if (childNumber < 0) {
                    childNumber = 0;
                }
                try {
                    latitude = Double.valueOf(property.getChildText("latitude"));
                } catch (Exception parseExc) {
                }
                try {
                    longitude = Double.valueOf(property.getChildText("longitude"));
                } catch (Exception parseExc) {
                }

                StringBuilder physicalAddress = new StringBuilder();
                StringBuilder physicalAddressForLocation = new StringBuilder();
                if (StringUtils.isNotEmpty(property.getChildText("address"))) {
                    physicalAddress.append(property.getChildText("address")).append("\n");
                    physicalAddressForLocation.append(property.getChildText("address")).append(", ");
                }
                if (StringUtils.isNotEmpty(property.getChildText("city"))) {
                    physicalAddress.append(property.getChildText("city")).append("\n");
                    physicalAddressForLocation.append(property.getChildText("city")).append(", ");
                }
                if (StringUtils.isNotEmpty(property.getChildText("state_description"))) {
                    physicalAddress.append(property.getChildText("state_description")).append("\n");
                    physicalAddressForLocation.append(property.getChildText("state_description")).append(", ");
                }
                if (StringUtils.isNotEmpty(property.getChildText("country_name"))) {
                    physicalAddress.append(property.getChildText("country_name")).append("\n");
                    physicalAddressForLocation.append(property.getChildText("country_name"));
                }

                //finding long and lat using physical address and Google Location service 
                //if they do not exist in API response (if exist we do not need to find) 
                //and if we have reason to find - if address is changed or lat or long do not exist in product  
                if ((latitude == null || longitude == null)
                        && (!physicalAddress.toString().equalsIgnoreCase(product.getPhysicaladdress())
                                || product.getLatitude() == null || product.getLongitude() == null)
                        && StringUtils.isNotEmpty(physicalAddress.toString())) {
                    Location propertyLocation = GoogleLocationProcessor
                            .getGoogleLocation(physicalAddressForLocation.toString());
                    if (propertyLocation != null) {
                        if (latitude == null) {
                            latitude = propertyLocation.getLatitude();
                        }
                        if (longitude == null) {
                            longitude = propertyLocation.getLongitude();
                        }
                    }
                }

                String propertyName = property.getChildText("name");
                //               if(property.getChildText("seo_title")!=null && !property.getChildText("seo_title").equalsIgnoreCase("")){
                //                  propertyName = property.getChildText("seo_title");
                //               } else{
                if (property.getChildText("home_type") != null
                        && !property.getChildText("home_type").equalsIgnoreCase("")) {
                    propertyName += ", " + property.getChildText("home_type");
                }

                if (city != null && !city.equalsIgnoreCase("")) {
                    propertyName += " at " + city;
                }

                if (property.getChildText("view_name") != null
                        && !property.getChildText("view_name").equalsIgnoreCase("")) {
                    propertyName += ", with " + property.getChildText("view_name");
                }
                //               }

                if (propertyName.length() > 99) {
                    propertyName = propertyName.substring(0, 99);
                }

                product.setCurrency(CURRENCY_IN_STREAMLINE);

                //            product.setName(property.getChildText("name") +", "+ property.getChildText("seo_title") );
                product.setName(propertyName);
                product.setUnit(Unit.DAY);
                product.setRoom(roomNumber);
                product.setBathroom(bathroomNumber);
                product.setQuantity(1);
                product.setPerson(adultsNumber);
                product.setChild(0);
                //               product.setChild(childNumber);
                product.setRank(0.0);

                product.setPhysicaladdress(physicalAddress.toString());

                if (product.getLocationid() == null) {
                    Location location = null;
                    if (locationMap.get(city + state + countryISO) != null) {
                        location = locationMap.get(city + state + countryISO);
                    } else if (StringUtils.isNotEmpty(latitudeLocationStr)
                            && StringUtils.isNotEmpty(longitudeLocationStr)) {
                        location = PartnerService.getLocation(sqlSession, city, state, countryISO,
                                Double.valueOf(latitudeLocationStr), Double.valueOf(longitudeLocationStr));
                        locationMap.put(city + state + countryISO, location);
                    } else {
                        location = PartnerService.getLocation(sqlSession, city, state, countryISO);
                        locationMap.put(city + state + countryISO, location);
                    }

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

                product.setLatitude(latitude);
                product.setLongitude(longitude);
                product.setWebaddress(getWebaddress());
                product.setCommission(getCommission());
                product.setDiscount(getDiscount());
                product.setRating(5);
                product.setAltitude(0.0);
                product.setVersion(version);

                /*
                 //not used
                `Options` 
                `Tax` 
                `Code` 
                `Unspsc` 
                `Servicedays` 
                `Toilet` 
                `Infant` 
                `Baby` 
                `Linenchange` 
                `Refresh` 
                `OwnerDiscount` 
                `DynamicPricingEnabled` 
                `AssignedtoManager` 
                `CleaningFee` 
                `SecurityDeposit` 
                 */

                //description build
                StringBuilder description = new StringBuilder();
                description.append(property.getChildText("seo_description")).append("\n");
                description.append(property.getChildText("short_description")).append("\n");
                description.append(property.getChildText("description")).append("\n");

                ArrayList<String> attributes = new ArrayList<String>();
                addType(attributes, property.getChildText("lodging_type_id"));

                //attributes
                String otherReqParamsAttributes = "<unit_id>" + altId + "</unit_id>";
                String responseAttr = createXMLRequestToStreamline(sqlSession, "GetPropertyAmenities",
                        otherReqParamsAttributes);
                builder = new SAXBuilder();
                Document documentAttr = (Document) builder.build(new StringReader(responseAttr));
                Element rootNodeAttributes = documentAttr.getRootElement();
                List<Element> propertyAttributes = rootNodeAttributes.getChild("data").getChildren("amenity");
                for (Element amenity : propertyAttributes) {
                    addPropertyAttribute(attributes, amenity.getChildText("amenity_name"));
                }

                //removing duplicate values from attributes
                HashSet<String> attributeHashSet = new HashSet<String>();
                attributeHashSet.addAll(attributes);
                attributes.clear();
                attributes.addAll(attributeHashSet);

                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();
            } catch (Throwable x) {
                sqlSession.rollback();
                LOG.error(x.getMessage());
                x.printStackTrace();
            }
        }

        //print not find attributes

        HashSet<String> hs = new HashSet<String>();
        hs.addAll(PROPERTY_ATTRIBUTES_NOT_FOUND);
        PROPERTY_ATTRIBUTES_NOT_FOUND.clear();
        PROPERTY_ATTRIBUTES_NOT_FOUND.addAll(hs);
        //         LOG.debug("Streamline attributes not find (Altpartyid:"+this.getAltpartyid()+"): ");
        //         for(String tempAttr : PROPERTY_ATTRIBUTES_NOT_FOUND){
        //            System.out.println(":::"+tempAttr +":::");
        //         }

        //canceling product which are not updated 
        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();
    }
    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 av a  2  s.  co  m
public void readImages() {
    Date timestamp = new Date();
    String message = "readImages Streamline (Altpartyid:" + this.getAltpartyid() + ")";
    LOG.debug(message);

    final SqlSession sqlSession = RazorServer.openSession();
    try {
        String responseAllProperties = createXMLRequestToStreamline(sqlSession, "GetPropertyList", "");
        SAXBuilder builder = new SAXBuilder();
        Document document = (Document) builder.build(new StringReader(responseAllProperties));
        Element rootNode = document.getRootElement();
        List<Element> properties = rootNode.getChild("data").getChildren("property");
        for (Element property : properties) {
            String altId = property.getChildText("id");
            try {
                Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altId, false);
                if (product == null) {
                    continue;
                }

                String otherReqParamsImages = "<unit_id>" + altId + "</unit_id>";
                String responseImages = createXMLRequestToStreamline(sqlSession, "GetPropertyGalleryImages",
                        otherReqParamsImages);
                builder = new SAXBuilder();
                Document documentImg = (Document) builder.build(new StringReader(responseImages));
                Element rootNodeImages = documentImg.getRootElement();
                List<Element> propertyImages = rootNodeImages.getChild("data").getChildren("image");
                if (propertyImages != null && propertyImages.size() > 0) {
                    ArrayList<NameId> images = new ArrayList<NameId>();
                    for (Element image : propertyImages) {
                        images.add(new NameId(image.getChildText("id"), image.getChildText("image_path")));
                    }
                    UploadFileService.uploadImages(sqlSession, NameId.Type.Product, product.getId(),
                            Language.EN, images);
                }

                sqlSession.commit();
            } 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, timestamp);

}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from   ww w .j  a va  2  s  .  c  om
public void readSchedule() {
    Date version = new Date();
    String message = "readSchedule Streamline (Altpartyid:" + this.getAltpartyid() + ")";
    LOG.debug(message);

    final SqlSession sqlSession = RazorServer.openSession();
    try {
        long functionStart = System.currentTimeMillis();
        String responseReservationsAndPrices = getXmlFeedConnection(sqlSession, this.getAltpartyid());
        long gettingApiDataEnd = System.currentTimeMillis();
        LOG.debug("Reading API data takes: " + (gettingApiDataEnd - functionStart) + "ms");

        SAXBuilder builder = new SAXBuilder();
        Document document = (Document) builder.build(new StringReader(responseReservationsAndPrices));
        Element rootNode = document.getRootElement();
        List<Element> properties = rootNode.getChildren("property");
        long parsingApiDataEnd = System.currentTimeMillis();
        LOG.debug("Parsing API data takes: " + (parsingApiDataEnd - gettingApiDataEnd) + "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_id.getMessage() + " " + altId);
                    continue;
                }

                List<Element> reservationsListFeed = property.getChild("reservations")
                        .getChildren("reservation");
                ArrayList<Reservation> reservationsFromApi = new ArrayList<Reservation>();
                for (Element reservationEl : reservationsListFeed) {
                    String fromDateStr = reservationEl.getChild("reservationDates").getChildText("beginDate");
                    String toDateStr = reservationEl.getChild("reservationDates").getChildText("endDate");
                    Date fromDate = responseDF.parse(fromDateStr);
                    Date toDate = responseDF.parse(toDateStr);

                    Reservation reservation = new Reservation();
                    reservation.setProductid(product.getId());
                    reservation.setFromdate(fromDate);
                    reservation.setTodate(toDate);

                    reservationsFromApi.add(reservation);
                }

                PartnerService.updateProductSchedules(sqlSession, product, reservationsFromApi, version);
                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);
}

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

License:Open Source License

/**
 * Transfer accommodation products./*from   w w  w.  j  a v a2 s  .c  o  m*/
 *
 * @param sqlSession the current SQL session.
 */
public synchronized void readProducts() {
    Date version = new Date();
    String message = "readProducts ";
    String altpartyid = getAltpartyid();
    LOG.debug(message);
    final SqlSession sqlSession = RazorServer.openSession();
    try {

        RelationService.load(sqlSession, Downloaded.PRODUCT_DOWNLOAD_DATE, altpartyid, new Date().toString());
        SAXBuilder parser = new SAXBuilder();
        Document document = parser.build(PartnerService.getInputStreamNoSSL(PROPERTIES_URL, getApikey(), null));
        //         Document document = parser.build(PROPERTIES_URL);

        Element rootNode = document.getRootElement();
        List<Element> properties = rootNode.getChildren("Property");
        int i = 0;
        for (Element property : properties) {
            String altid = property.getChildText("PropertyID");
            Product product = PartnerService.getProduct(sqlSession, altpartyid, altid);
            if (product == null) {
                continue;
            }
            ArrayList<String> attributes = new ArrayList<String>();
            ArrayList<NameId> images = new ArrayList<NameId>();
            StringBuilder description = new StringBuilder();
            boolean isActive = property.getChildText("PropertyActive").equals("1") ? true : false;
            product.setState((isActive ? Product.CREATED : Product.SUSPENDED));

            String ProductID = product.getId();
            String propertyAddress = property.getChildText("PropertyAddress");
            String propertyCity = property.getChildText("PropertyCity");
            String propertyState = property.getChildText("PropertyState");
            if (propertyState.equals("COLO")) {
                propertyState = "CO";
            }
            String propertyZip = property.getChildText("PropertyZip");
            String latitude = property.getChildText("Latitude");
            String longitude = property.getChildText("Longitude");

            Location location = PartnerService.getLocation(sqlSession, propertyCity, propertyState, Country.US);
            product.setLocationid(location.getId());
            product.setLatitude(latitude == null ? location.getLatitude() : Double.valueOf(latitude));
            product.setLongitude(longitude == null ? location.getLongitude() : Double.valueOf(longitude));
            product.setAltitude(0.0);

            StringBuilder address = new StringBuilder();
            if (propertyAddress != null && !propertyAddress.isEmpty()) {
                address.append(propertyAddress).append("\n");
            }
            if (propertyCity != null && !propertyCity.isEmpty()) {
                address.append(propertyCity).append("\n");
            }
            if (propertyState != null && !propertyState.isEmpty()) {
                address.append(propertyState).append("\n");
            }
            if (propertyZip != null && !propertyZip.isEmpty()) {
                address.append(propertyZip).append("\n");
            }
            address.append(Country.US);
            product.setPhysicaladdress(address.toString());

            product.setOwnerid(altpartyid);
            product.setSupplierid(altpartyid);

            String sleepingCapacity = property.getChildText("SleepingCapacity");
            product.setPerson(sleepingCapacity == null || sleepingCapacity.isEmpty() ? 1
                    : Integer.valueOf(sleepingCapacity));
            product.setChild(0);
            product.setInfant(0);
            product.setQuantity(1);

            product.setRating(5);
            product.setCommission(getCommission());
            //            product.setCleaningfee(Double.parseDouble(property.getChildText("CleaningFee")));
            //            product.setSecuritydeposit(Double.parseDouble(property.getChildText("DamageFee")));
            product.setDiscount(getDiscount());
            product.setRank(getRank());

            String bedrooms = property.getChildText("Bedrooms");
            product.setRoom(bedrooms == null || bedrooms.isEmpty() ? 1 : Integer.valueOf(bedrooms));

            String bathrooms = property.getChildText("Bathrooms");
            String[] bathtoilet = bathrooms == null ? null : bathrooms.split("\\.");
            product.setBathroom(
                    bathtoilet == null || bathtoilet[0].isEmpty() ? 0 : Integer.valueOf(bathtoilet[0]));
            product.setToilet(bathtoilet == null || bathtoilet.length < 2 ? product.getBathroom()
                    : product.getBathroom() + 1);

            product.setType(Product.Type.Accommodation.name());
            product.setCurrency(getCurrency());
            product.setUnit(Unit.DAY);
            product.setWebaddress(getWebaddress());
            product.setVersion(version);

            String propertyUnit = property.getChildText("PropertyUnit");
            String propertyName = property.getChildText("PropertyName");
            String name = propertyName + " " + propertyUnit;
            product.setName(name);
            //product.setName(PartnerService.getProductname(name, location.getName(), ProductID));

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

            product.setValue(Product.Value.InsuranceRate.name(),
                    property.getChildText(Product.Value.InsuranceRate.name()));
            product.setValue(Product.Value.SquareFeet.name(),
                    property.getChildText(Product.Value.SquareFeet.name()));
            product.setValue(Product.Value.SlopeProximity.name(),
                    property.getChildText(Product.Value.SlopeProximity.name()));
            product.setValue(Product.Value.SingleBeds.name(),
                    property.getChildText(Product.Value.SingleBeds.name()));
            product.setValue(Product.Value.QueenBeds.name(),
                    property.getChildText(Product.Value.QueenBeds.name()));
            product.setValue(Product.Value.KingBeds.name(),
                    property.getChildText(Product.Value.KingBeds.name()));

            String oneLiner = property.getChildText("OneLiner");
            if (oneLiner != null && !oneLiner.isEmpty()) {
                description.append(oneLiner);
            }
            String propertyDescriptionOverview = property.getChildText("PropertyDescriptionOverview");
            if (propertyDescriptionOverview != null && !propertyDescriptionOverview.isEmpty()) {
                description.append("\n").append(propertyDescriptionOverview);
            }

            Price action = new Price();
            action.setEntitytype(NameId.Type.Mandatory.name());
            action.setType(Tax.Type.SalesTaxExcluded.name());
            action.setEntityid(ProductID);
            action.setOrderby(Price.ID);
            ArrayList<Tax> list = sqlSession.getMapper(TaxMapper.class).taxbyrelation(action);
            if (list.size() == 0) {
                addTax(sqlSession, null, "Tax Rate", Double.valueOf(property.getChildText("TaxRate")),
                        ProductID);
                addTax(sqlSession, null, "Resort Tax Rate",
                        Double.valueOf(property.getChildText("ResortTaxRate")), ProductID);
            } else if (list.size() == 2) {
                for (Tax tax : list) {
                    if (tax.getName().equals("Tax Rate")
                            && !tax.getAmount().equals(Double.valueOf(property.getChildText("TaxRate")))) {
                        addTax(sqlSession, tax.getId(), "Tax Rate",
                                Double.valueOf(property.getChildText("TaxRate")), ProductID);
                        continue;
                    }
                    if (tax.getName().equals("Resort Tax Rate") && !tax.getAmount()
                            .equals(Double.valueOf(property.getChildText("ResortTaxRate")))) {
                        addTax(sqlSession, tax.getId(), "Resort Tax Rate",
                                Double.valueOf(property.getChildText("ResortTaxRate")), ProductID);
                    }
                }
            } else {
                LOG.error("You have too many relations for product: " + ProductID + ", check your database.");
            }

            //            tax = new Tax();
            //            tax.setAccountid(Account.VAT_OUTPUT);
            //            tax.setPartyid(getAltpartyid());
            //            tax.setName("Resort Tax Rate");
            //            tax.setType(Tax.Type.SalesTaxExcluded.name());
            //            tax.setDate(new Date(0));
            //            exists = sqlSession.getMapper(TaxMapper.class).exists(tax);
            //            if (exists == null) {sqlSession.getMapper(TaxMapper.class).create(tax);}
            //            else {tax = exists;}
            //            tax.setState(Tax.CREATED);
            //            tax.setDate(new Date(0));
            //            tax.setAmount(Double.valueOf(property.getChildText("ResortTaxRate")));
            //            tax.setThreshold(0);
            //            tax.setVersion(version);
            //            sqlSession.getMapper(TaxMapper.class).update(tax);
            //            RelationService.replace(sqlSession, Relation.PRODUCT_TAX, ProductID, tax.getId());
            //            sqlSession.getMapper(TaxMapper.class).cancelversion(tax);

            String title;
            String descr;
            for (int j = 1; j <= 10; j++) {
                title = property.getChildText("RoomTitle" + j);
                descr = property.getChildText("RoomDescription" + j);
                addText(description, title);
                addText(description, descr);
            }

            addText(description, property.getChildText("PropertyFeaturesOverview"));

            for (int j = 1; j <= 10; j++) {
                title = property.getChildText("FeatureTitle" + j);
                descr = property.getChildText("FeatureDescription" + j);
                addText(description, title);
                addText(description, descr);
            }

            for (int j = 1; j <= 20; j++) {
                String url = property.getChildText("PictureURL" + j);
                if (url == null || url.isEmpty()) {
                    continue;
                }
                url = PICTURES_URL + url.replace(".", "_full.");
                String text = property.getChildText("PictureCaption" + j);
                addImage(images, url, text);
            }

            addPrice(sqlSession, version, ProductID, altpartyid, property.getChildText("Season_Regular_Start"),
                    property.getChildText("Season_Regular_End"),
                    property.getChildText("Season_Regular_NightlyRate"),
                    property.getChildText("Season_Regular_NightMin"), "Regular Season");

            addPrice(sqlSession, version, ProductID, altpartyid,
                    property.getChildText("Season_MLK-Weekend_Start"),
                    property.getChildText("Season_MLK-Weekend_End"),
                    property.getChildText("Season_MLK-Weekend_NightlyRate"),
                    property.getChildText("Season_MLK-Weekend_NightMin"), "MLK Weekend");

            addPrice(sqlSession, version, ProductID, altpartyid,
                    property.getChildText("Season_Pre-Powder_Start"),
                    property.getChildText("Season_Pre-Powder_End"),
                    property.getChildText("Season_Pre-Powder_NightlyRate"),
                    property.getChildText("Season_Pre-Powder_NightMin"), "Pre-Powder Season");

            addPrice(sqlSession, version, ProductID, altpartyid,
                    property.getChildText("Season_Presidents-Day_Start"),
                    property.getChildText("Season_Presidents-Day_End"),
                    property.getChildText("Season_Presidents-Day_NightlyRate"),
                    property.getChildText("Season_Presidents-Day_NightMin"), "President's Day");

            addPrice(sqlSession, version, ProductID, altpartyid, property.getChildText("Season_Powder_Start"),
                    property.getChildText("Season_Powder_End"),
                    property.getChildText("Season_Powder_NightlyRate"),
                    property.getChildText("Season_Powder_NightMin"), "Powder Season");

            addPrice(sqlSession, version, ProductID, altpartyid,
                    property.getChildText("Season_Spring-Break_Start"),
                    property.getChildText("Season_Spring-Break_End"),
                    property.getChildText("Season_Spring-Break_NightlyRate"),
                    property.getChildText("Season_Spring-Break_NightMin"), "Spring Break");

            addPrice(sqlSession, version, ProductID, altpartyid,
                    property.getChildText("Season_Spring-Prime_Start"),
                    property.getChildText("Season_Spring-Prime_End"),
                    property.getChildText("Season_Spring-Prime_NightlyRate"),
                    property.getChildText("Season_Spring-Prime_NightMin"), "Spring Prime Season");

            addPrice(sqlSession, version, ProductID, altpartyid,
                    property.getChildText("Season_Late-Spring_Start"),
                    property.getChildText("Season_Late-Spring_End"),
                    property.getChildText("Season_Late-Spring_NightlyRate"),
                    property.getChildText("Season_Late-Spring_NightMin"), "Late Spring Season");

            addPrice(sqlSession, version, ProductID, altpartyid, property.getChildText("Season_Summer_Start"),
                    property.getChildText("Season_Summer_End"),
                    property.getChildText("Season_Summer_NightlyRate"),
                    property.getChildText("Season_Summer_NightMin"), "Summer Season");

            addPrice(sqlSession, version, ProductID, altpartyid, property.getChildText("Season_Fall_Start"),
                    property.getChildText("Season_Fall_End"), property.getChildText("Season_Fall_NightlyRate"),
                    property.getChildText("Season_Fall_NightMin"), "Fall Season");

            addPrice(sqlSession, version, ProductID, altpartyid,
                    property.getChildText("Season_Thanksgiving_Start"),
                    property.getChildText("Season_Thanksgiving_End"),
                    property.getChildText("Season_Thanksgiving_NightlyRate"),
                    property.getChildText("Season_Thanksgiving_NightMin"), "Thanksgiving");

            addPrice(sqlSession, version, ProductID, altpartyid, property.getChildText("Season_Early_Start"),
                    property.getChildText("Season_Early_End"),
                    property.getChildText("Season_Early_NightlyRate"),
                    property.getChildText("Season_Early_NightMin"), "Early Season");

            addPrice(sqlSession, version, ProductID, altpartyid, property.getChildText("Season_Holiday_Start"),
                    property.getChildText("Season_Holiday_End"),
                    property.getChildText("Season_Holiday_NightlyRate"),
                    property.getChildText("Season_Holiday_NightMin"), "Holiday Season");

            addFee(sqlSession, version, ProductID, property.getChildText("CleaningFee"), "Cleaning Fee");
            addFee(sqlSession, version, ProductID, property.getChildText("DamageFee"), "Damage Fee");

            Price price = new Price();
            price.setEntitytype(NameId.Type.Product.name());
            price.setEntityid(ProductID);
            price.setPartyid(altpartyid);
            price.setCurrency(Currency.Code.USD.name());
            price.setVersion(version);
            sqlSession.getMapper(PriceMapper.class).cancelversion(price);
            price.setEntitytype(NameId.Type.Mandatory.name());
            sqlSession.getMapper(PriceMapper.class).cancelversion(price);

            product.setPublicText(new Text(product.getPublicId(), product.getPublicLabel(), Text.Type.HTML,
                    new Date(), description.toString(), Language.EN));
            TextService.update(sqlSession, product.getTexts());
            RelationService.replace(sqlSession, Relation.PRODUCT_VALUE, ProductID, product.getValues());
            RelationService.create(sqlSession, Relation.PRODUCT_ATTRIBUTE, ProductID, attributes);
            UploadFileService.uploadImages(sqlSession, NameId.Type.Product, ProductID, Language.EN, images);

            sqlSession.commit();
            LOG.debug(i++ + " " + altid + " " + ProductID + " " + product.getName());
            wait(getProductwait());
            //TODO: TEST break;
        }
        Product action = new Product();
        action.setAltpartyid(altpartyid);
        action.setState(Product.CREATED);

        sqlSession.getMapper(ProductMapper.class).cancelversion(action);
        sqlSession.commit();
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
    }
    //MonitorService.monitor(message, version);
}

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

License:Open Source License

/**
 * Transfer reservation schedule.//from ww  w  . j  a  va 2s  .  co  m
 *
 * @param sqlSession the current SQL session.
 */
public synchronized void readSchedule() {
    Date timestamp = new Date();
    String message = "readSchedule ";
    LOG.debug(message);
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        SAXBuilder parser = new SAXBuilder();
        Document document = parser
                .build(PartnerService.getInputStreamNoSSL(RESERVATION_URL, getApikey(), null));

        Element rootNode = document.getRootElement();
        List<Element> bookings = rootNode.getChildren("Reservation");
        for (Element booking : bookings) {
            String altid = booking.getChildText("PropertyID");
            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altid);
            if (product == null) {
                continue;
            }
            //String altid = booking.getChildText("ReservationID");
            PartnerService.createSchedule(sqlSession, product, parse(booking.getChildText("ArrivalDate")),
                    parse(booking.getChildText("DepartureDate")), timestamp);
            PartnerService.cancelSchedule(sqlSession, product, timestamp);
            sqlSession.commit();
            wait(getSchedulewait());
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
    }
    MonitorService.monitor(message, timestamp);
}

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

License:Open Source License

@Override
public void readPrices() {
    Date version = new Date();
    String message = "readPrices NextpaxAPIKEY: " + this.getApikey() + "STARTED";
    LOG.debug(message);/*from  w  w w  . j a v a  2 s .co m*/

    final SqlSession sqlSession = RazorServer.openSession();
    try {
        // rates

        Element rootNode = document.getRootElement();
        List<Element> houses = rootNode.getChildren("offer", ns);
        int ij = 0;
        for (Element house : houses) {
            ij++;
            if (ij > 2260) {
                break;
            }
            if (ij < 2100) {
                continue;
            }
            System.out.println("Product prices: " + ij);
            System.out.println("product #" + ij);
            String altid = house.getAttributeValue("internal-id");
            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altid);

            if (product == null) {
                continue;
            }

            Element costs = house.getChild("rateperiods", ns);
            if (costs == null) {
                continue;
            }
            List<Element> costList = costs.getChildren("rateperiod", ns);
            for (Element cost : costList) {
                try {
                    LOG.debug("cost " + cost);

                    String from = cost.getChildText("startdate", ns);
                    String until = cost.getChildText("enddate", ns);
                    String costcurrency = cost.getChildText("currency", ns);

                    Double dailyrate = 0d;
                    String dailyrateS = cost.getChildText("dailyrate", ns);
                    if (dailyrateS != null && !dailyrateS.isEmpty())
                        dailyrate = Double.valueOf(dailyrateS);

                    Double weekendrate = 0d;
                    String weekendrateS = cost.getChildText("weekendrate", ns);
                    if (weekendrateS != null && !weekendrateS.isEmpty())
                        weekendrate = Double.valueOf(weekendrateS);

                    Double weekrate = 0d;
                    String weekrateS = cost.getChildText("weekrate", ns);
                    if (weekrateS != null && !weekrateS.isEmpty())
                        weekrate = Double.valueOf(weekrateS);

                    Double monthrate = 0d;
                    String monthrateS = cost.getChildText("monthrate", ns);
                    if (monthrateS != null && !monthrateS.isEmpty())
                        monthrate = Double.valueOf(monthrateS);

                    String costcode = "";
                    Double costamount = 0.0;
                    for (int i = 0; i < 4; i++) {
                        switch (i) {
                        case 0:
                            costamount = dailyrate;
                            costcode = "Price per day";
                            break;
                        case 1:
                            costamount = weekendrate;
                            costcode = "Price per weekend";
                            break;
                        case 2:
                            costamount = weekrate;
                            costcode = "Price per week";
                            break;
                        case 3:
                            costamount = monthrate;
                            costcode = "Price per month";
                            break;
                        default:
                            break;
                        }

                        System.out.println("costamount = " + costamount);
                        if (costamount != 0.0) {

                            Price price = new Price();
                            price.setPartyid(getAltpartyid());
                            price.setEntitytype(NameId.Type.Product.name());
                            price.setEntityid(product.getId());// productID
                            price.setCurrency(costcurrency);
                            price.setQuantity(0.0);
                            price.setName(costcode);
                            price.setType(NameId.Type.Reservation.name());
                            price.setDate(DF.parse(from));
                            price.setTodate(DF.parse(until));
                            price.setAvailable(1);

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

                            // price.setAltid(costcode);
                            price.setAltpartyid(getAltpartyid());
                            price.setFactor(1.0);
                            price.setOrganizationid(getAltpartyid());
                            price.setRule(Price.Rule.FixedRate.name());
                            price.setState(Price.CREATED);
                            price.setValue(Double.valueOf(costamount));
                            price.setMinimum(0.0);
                            price.setVersion(version);
                            sqlSession.getMapper(PriceMapper.class).update(price);
                            // sqlSession.getMapper(PriceMapper.class).cancelversion(price);
                            // If it just has not been updated we are deleting it.
                            // Will decide how we want to handle updates
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            sqlSession.commit();
            LOG.debug("readPrices NextpaxAPIKEY: " + this.getApikey() + "DONE");
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
        x.printStackTrace();
    } finally {
        sqlSession.close();
    }
    MonitorService.monitor(message, version);
}

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

License:Open Source License

public void readFeesOld() {

    Date version = new Date();
    String message = "readPrices NextpaxAPIKEY: " + this.getApikey() + "STARTED";
    LOG.debug(message);/*from w w  w. ja v a 2  s. c  o  m*/

    String fn = "c:\\parsing\\p.xml";

    final SqlSession sqlSession = RazorServer.openSession();
    try {

        SAXBuilder parser = new SAXBuilder();

        //   Document document = parser.build(ftp(fn));
        Document document = parser.build(new FileInputStream(fn));

        Element rootNode = document.getRootElement();
        List<Element> houses = rootNode.getChildren("AdditionalCosts");
        for (Element house : houses) {
            String altid = house.getChildText("HouseID");
            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altid);

            if (product == null) {
                continue;
            }

            List<Element> costs = house.getChildren("AdditionalCost");
            for (Element cost : costs) {
                LOG.debug("cost " + cost);
                String costcode = cost.getChildText("CostCode");
                String costtype = cost.getChildText("CostType");
                String costamount = cost.getChildText("CostAmount");
                String costamounttype = cost.getChildText("CostAmountType");
                String costcurrency = cost.getChildText("CostCurrency");
                String number = cost.getChildText("Number");
                String from = cost.getChildText("From");
                String until = cost.getChildText("Until");

                Fee feeObject = new Fee();
                feeObject.setProductId(product.getId());
                feeObject.setPartyId(product.getAltpartyid());
                //feeObject.setState(Fee.CREATED);

                feeObject.setName(""/*getCostCode(costcode)*/);
                feeObject.setEntityType(21);
                sqlSession.getMapper(FeeMapper.class).create(feeObject);

            }
            sqlSession.commit();
            LOG.debug("readPrices NextpaxAPIKEY: " + this.getApikey() + "DONE");
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
        // x.printStackTrace();
    } finally {
        sqlSession.close();
        delete(fn);
    }
    MonitorService.monitor(message, version);

}

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

License:Open Source License

public void readFees() {
    Date version = new Date();
    String message = "readFees Yandex";
    LOG.debug(message);//from w w w .  j a v a 2s  .c o  m

    final SqlSession sqlSession = RazorServer.openSession();
    try {
        // fees

        Element rootNode = document.getRootElement();
        List<Element> houses = rootNode.getChildren("offer", ns);
        int ij = 0;
        for (Element house : houses) {
            ij++;
            System.out.println("Product fees: " + ij);
            //            if (ij>10) {
            //               break;
            //            }
            String altid = house.getAttributeValue("internal-id");
            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altid);

            if (product == null) {
                continue;
            }

            Element fees = house.getChild("fees", ns);
            if (fees == null) {
                continue;
            }
            List<Element> feeList = fees.getChildren("fee", ns);
            for (Element fee : feeList) {
                try {
                    LOG.debug("fee " + fee);

                    String feecode = fee.getAttributeValue("type");
                    String feecurrency = fee.getChildText("currency", ns);

                    Double feecost = 0d;
                    String feecostS = fee.getChildText("cost", ns);
                    if (feecostS != null && !feecostS.isEmpty())
                        feecost = Double.valueOf(feecostS);

                    Fee feeObject = new Fee();
                    feeObject.setProductId(product.getId());
                    feeObject.setPartyId(product.getAltpartyid());
                    feeObject.setState(Fee.CREATED);
                    feeObject.setUnit(1);
                    feeObject.setValueType(1);

                    feeObject.setName(feecode);
                    feeObject.setEntityType(21);
                    feeObject.setCurrency(feecurrency);
                    feeObject.setValue(feecost);

                    Fee exists = sqlSession.getMapper(FeeMapper.class).exists(feeObject);
                    if (exists == null) {
                        sqlSession.getMapper(FeeMapper.class).create(feeObject);
                    }

                    /*Price price = new Price();
                    price.setPartyid(getAltpartyid());
                    price.setEntitytype(NameId.Type.Product.name());
                    price.setEntityid(product.getId());// productID
                    price.setCurrency(feecurrency);
                    price.setQuantity(0.0);
                    price.setName(feecode);
                    price.setType(NameId.Type.Tax.name());
                    price.setAvailable(1);
                            
                    Date date = new Date();
                    price.setDate(date);
                    price.setTodate(date);
                            
                    LOG.debug("price " + price);
                    Price exists = sqlSession.getMapper(PriceMapper.class).exists(price);
                    if (exists == null) {
                       sqlSession.getMapper(PriceMapper.class).create(price);
                    } else {
                       price = exists;
                    }
                            
                    price.setAltpartyid(getAltpartyid());
                    price.setFactor(1.0);
                    price.setOrganizationid(getAltpartyid());
                    price.setRule(Price.Rule.FixedRate.name());
                    price.setState(Price.CREATED);
                    price.setValue(Double.valueOf(feecost));
                    price.setMinimum(0.0);
                    price.setVersion(version);
                    sqlSession.getMapper(PriceMapper.class).update(price);*/
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            sqlSession.commit();
            LOG.debug("readFees Yandex DONE");
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
        x.printStackTrace();
    } finally {
        sqlSession.close();
    }
    MonitorService.monitor(message, version);
}

From source file:net.cbtltd.rest.yandex.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 ww  w  .j a  v a  2  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();
        Element rootNode = document.getRootElement();
        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) {
            i++;
            if (i < 433) {
                continue;
            }
            System.out.println("Products number: " + i);
            //try {
            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", ns); // sometimes empty
            name = "";

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

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

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

            Element rateperiods = house.getChild("rateperiods", ns);
            String currency = null;
            if (rateperiods != null) {
                List<Element> rateperiodList = rateperiods.getChildren("rateperiod", ns);
                if (rateperiodList.size() > 0) {
                    currency = rateperiodList.get(0).getChildText("currency", ns);
                }
            }

            Element details = house.getChild("details", ns);

            String maxpersons = details.getChildText("maximumOccupancy", ns);

            String region = house.getChildText("Region", ns); // 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", ns);
            String minchildren = house.getChildText("MinChildren", ns); // MinChildren

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

            // 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";
            }

            //=== suitability ===//
            Element suitability = house.getChild("suitability", ns);

            String FAM = suitability.getChildText("is_family", ns);
            if (StringUtils.isNotBlank(FAM) && FAM.equals("true")) {
                attributes.add(net.cbtltd.shared.Attribute.FAM);
            }
            String SMO = suitability.getChildText("is_nosmoking", ns);
            if (StringUtils.isNotBlank(SMO) && SMO.equals("false")) {
                attributes.add(net.cbtltd.shared.Attribute.SMO);
            }
            String PHY = suitability.getChildText("is_invalid", ns);
            if (StringUtils.isNotBlank(PHY) && PHY.equals("true")) {
                attributes.add(net.cbtltd.shared.Attribute.PHY);
            }
            //=== suitability ===//

            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 + " " + altid; // 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 = "House in " + locationName + " " + altid;
                    }
                }
            } // 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);

            //=== additional properties ===//
            int rooms = 0;
            try {
                rooms = Integer.parseInt(house.getChildText("rooms", ns)); // Number of rooms.
            } catch (NumberFormatException e) {
            }
            product.setRoom(rooms);

            try {
                product.setBathroom(Integer.parseInt(details.getChildText("bathrooms", ns))); // Number of bedrooms.
            } catch (NumberFormatException e) {
            }

            try {
                product.setPerson(Integer.parseInt(maxpersons));
            } catch (NumberFormatException e) {
            }

            product.setPhysicaladdress(address);

            product.setState(Product.CREATED);
            //=== additional properties ===//

            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 e) {
            //   continue;
            //}
        }
    } 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.yandex.A_Handler.java

License:Open Source License

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

    final SqlSession sqlSession = RazorServer.openSession();
    String fileName = "paxgenerator_house_properties_" + getApikey() + ".xml";
    int updatedHouses = 0;
    try {/* ww  w  . ja v  a2s . c  o m*/
        long startParsing = System.currentTimeMillis();
        LOG.debug("Time taken to parse " + fileName + " : " + (System.currentTimeMillis() - startParsing)
                + " milli seconds.");

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

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

            int rooms = 0;
            try {
                rooms = Integer.parseInt(house.getChildText("Value")); // Number of bedrooms.
            } catch (NumberFormatException e) {
            }
            product.setRoom(rooms);
            if (rooms > 8) {
                RelationService.create(sqlSession, Relation.PRODUCT_ATTRIBUTE, product.getId(),
                        ATTRIBUTES.get("B02") + 9);
            } else if (rooms > 0) {
                RelationService.create(sqlSession, Relation.PRODUCT_ATTRIBUTE, product.getId(),
                        ATTRIBUTES.get("B02") + rooms);
            }

            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("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.");
}