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

License:Open Source License

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

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

License:Open Source License

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

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

License:Open Source License

@Override
public void readPrices() {
    Date version = new Date();
    String message = "readPrices Lodgix (PartyId: " + this.getAltpartyid() + ")";
    LOG.debug(message);/*from w  w w.j a  va  2  s  .c o  m*/

    //TODO temp finding last cronjob run
    //temp will be 10 days.
    Calendar cal = Calendar.getInstance();
    cal.setTime(version);
    cal.add(Calendar.DATE, -500);
    Date lastCronJobRun = cal.getTime();

    final SqlSession sqlSession = RazorServer.openSession();
    try {
        Party party = sqlSession.getMapper(PartyMapper.class).read(this.getAltpartyid());
        String advertiserIdForThisPM = party.getAltid();
        ListingContentIndex content = CommonUtils.unmarshall(new URL(RATES_URL), ListingContentIndex.class);

        for (AdvertiserListingIndex.Advertiser advertiser : content.getAdvertisers().getAdvertiser()) {
            String advertiserIdCurrent = advertiser.getAssignedId();
            if (!advertiserIdForThisPM.equalsIgnoreCase(advertiserIdCurrent)) {
                continue;
            }
            for (ListingContentIndexEntry contentIndex : advertiser.getListingContentIndexEntry()) {
                //checking last update
                Date apiPropertyLastUpdate = getDateTime(contentIndex.getLastUpdatedDate());
                if (apiPropertyLastUpdate.before(lastCronJobRun)) {
                    continue;
                }

                if (!checkIfValueNullOrEmpty(contentIndex.getUnitRatesUrl())) {
                    RatePeriods ratePeriodsList = CommonUtils
                            .unmarshall(new URL(contentIndex.getUnitRatesUrl()), RatePeriods.class);
                    String altId = contentIndex.getListingExternalId();
                    //                  LOG.debug("Current property altId: " + altId);
                    Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altId, false);
                    if (product == null) {
                        continue;
                    }

                    ArrayList<Price> pricesFromApi = new ArrayList<Price>();
                    ArrayList<Yield> discountYieldFromApi = new ArrayList<Yield>();

                    for (RatePeriod ratePeriodCurrent : ratePeriodsList.getRatePeriod()) {
                        Date fromDate = getDateTime(ratePeriodCurrent.getDateRange().getBeginDate());
                        Date toDate = getDateTime(ratePeriodCurrent.getDateRange().getEndDate());
                        Integer minimumStay = ratePeriodCurrent.getMinimumStay();
                        if (minimumStay == null) {
                            //if minimum stay missing than = 1
                            minimumStay = 1;
                        }

                        List<Rate> ratesList = ratePeriodCurrent.getRates().getRate();
                        String currencyDaily = product.getCurrency();
                        String currencyWeekend = product.getCurrency();
                        String currencyWeekly = product.getCurrency();
                        String currencyMonthly = product.getCurrency();
                        Double dailyRateValue = null;
                        Double weekendRateValue = null;
                        Double weeklyRateValue = null;
                        Double monthlyRateValue = null;

                        //TODO This need to be tested on UAT
                        for (Rate rateCurrent : ratesList) {
                            // in response some prices have value=0 so that rates we will not use
                            // we using nightly rate, weekend rate (adjusted price) 
                            // and also remember weekly rate (if nightly do not exist - this is noticed for some properties)
                            if (rateCurrent.getAmount().getValue() != null
                                    && rateCurrent.getAmount().getValue().doubleValue() > 0) {
                                if (rateCurrent.getRateType().equals(RateType.NIGHTLY_WEEKDAY)) {
                                    dailyRateValue = rateCurrent.getAmount().getValue().doubleValue();
                                    currencyDaily = rateCurrent.getAmount().getCurrency();
                                } else if (rateCurrent.getRateType().equals(RateType.NIGHTLY_WEEKEND)) {
                                    weekendRateValue = rateCurrent.getAmount().getValue().doubleValue();
                                    currencyWeekend = rateCurrent.getAmount().getCurrency();
                                } else if (rateCurrent.getRateType().equals(RateType.WEEKLY)) {
                                    weeklyRateValue = rateCurrent.getAmount().getValue().doubleValue();
                                    currencyWeekly = rateCurrent.getAmount().getCurrency();
                                } else if (rateCurrent.getRateType().equals(RateType.MONTHLY)) {
                                    monthlyRateValue = rateCurrent.getAmount().getValue().doubleValue();
                                    currencyMonthly = rateCurrent.getAmount().getCurrency();
                                } else {
                                    System.out.println("######################################### Rate type: "
                                            + rateCurrent.getRateType().toString());
                                }
                            }
                        }

                        if (dailyRateValue != null && minimumStay != null) {
                            Price price = new Price();
                            price.setEntityid(product.getId());
                            price.setEntitytype(NameId.Type.Product.name());
                            price.setPartyid(getAltpartyid());
                            price.setName(Price.RACK_RATE);
                            price.setType(NameId.Type.Reservation.name());
                            price.setQuantity(1.0);
                            price.setCurrency(currencyDaily);
                            price.setUnit(Unit.DAY);
                            price.setDate(fromDate);
                            price.setTodate(toDate);

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

                            //                        price.setState(Price.CREATED);
                            // TODO check this with them, they have this but we do not get this information
                            price.setRule(Price.Rule.AnyCheckIn.name());
                            price.setValue(dailyRateValue);
                            price.setCost(dailyRateValue);
                            price.setMinStay(minimumStay);
                            price.setMinimum(dailyRateValue * minimumStay);
                            price.setAvailable(1);
                            //                        price.setVersion(version);
                            //                        sqlSession.getMapper(PriceMapper.class).update(price);
                            //                        sqlSession.getMapper(PriceMapper.class).cancelversion(price);

                            pricesFromApi.add(price);

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

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

                            if (monthlyRateValue != null && dailyRateValue != null) {
                                if (!currencyMonthly.equalsIgnoreCase(currencyDaily)) {
                                    Double currencyRate = WebService.getRate(sqlSession, currencyMonthly,
                                            currencyDaily, new Date());
                                    monthlyRateValue = PaymentHelper
                                            .getAmountWithTwoDecimals(monthlyRateValue * currencyRate);
                                }
                                Yield monthlyDiscount = YieldService.createLengthOfStayDiscount(product.getId(),
                                        dailyRateValue, monthlyRateValue, 30, fromDate, toDate);
                                if (monthlyDiscount != null) {
                                    discountYieldFromApi.add(monthlyDiscount);
                                }
                            }

                            //this is case when we have adjustment value also
                            //we adding this rate price only if regular weekly price exist
                            //                        if (rateAmountWeekendValue != null) {
                            //                           Double extraAdjustmentPrice = rateAmountWeekendValue - dailyRateValue;
                            //                           Adjustment adjustmentPrice = new Adjustment();
                            //                           adjustmentPrice.setCurrency(currencyWeekend);
                            //                           adjustmentPrice.setPartyID(getAltpartyid());
                            //                           adjustmentPrice.setProductID(product.getId());
                            //                           adjustmentPrice.setFromDate(fromDate);
                            //                           adjustmentPrice.setToDate(toDate);
                            //                           adjustmentPrice.setMaxStay(999);
                            //                           adjustmentPrice.setMinStay(minimumStay);
                            //                           adjustmentPrice.setExtra(extraAdjustmentPrice);
                            //                           adjustmentPrice.setServicedays(Adjustment.WEEKEND);
                            ////                           adjustmentPrice.setState(Adjustment.Created);
                            //                           
                            //                           Adjustment existsAdjustment = sqlSession.getMapper(AdjustmentMapper.class).exists(adjustmentPrice);
                            //                           if (existsAdjustment == null) {
                            //                              sqlSession.getMapper(AdjustmentMapper.class).create(adjustmentPrice);
                            //                           }
                            //                           else {
                            //                              adjustmentPrice = existsAdjustment;
                            //                           }
                            //                           
                            //                           adjustmentPrice.setState(Adjustment.Created);
                            //                           adjustmentPrice.setVersion(version);
                            //                           
                            //                           sqlSession.getMapper(AdjustmentMapper.class).update(adjustmentPrice);
                            //                           sqlSession.getMapper(AdjustmentMapper.class).cancelversion(adjustmentPrice);
                            //                        }
                        }
                    }

                    PartnerService.updateProductPrices(sqlSession, product, NameId.Type.Product.name(),
                            pricesFromApi, version, false, null);
                    PartnerService.updateProductRateYields(sqlSession, product, discountYieldFromApi, version);

                    sqlSession.commit();
                }
            }
        }

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

}

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

License:Open Source License

@Override
public void readProducts() {
    String message = "readProducts Lodgix (PartyId: " + this.getAltpartyid() + ")";
    LOG.debug(message);/*from ww  w .ja va2  s. c o m*/
    Date version = new Date();

    StringBuilder sbNotKnowLocation = new StringBuilder();
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        // FeedParser<AdvertiserListingIndex.Advertiser, Listing> parser = FeedParserFactory.getFactoryInstance().createContentIndexedFeedParser(ALL_PRODUCTS_URL);

        Party party = sqlSession.getMapper(PartyMapper.class).read(this.getAltpartyid());
        String advertiserIdForThisPM = party.getAltid();
        ListingContentIndex content = CommonUtils.unmarshall(new URL(PRODUCTS_URL), ListingContentIndex.class);
        for (AdvertiserListingIndex.Advertiser advertiser : content.getAdvertisers().getAdvertiser()) {
            String advertiserIdCurrent = advertiser.getAssignedId();
            if (!advertiserIdForThisPM.equalsIgnoreCase(advertiserIdCurrent)) {
                continue;
            }
            for (ListingContentIndexEntry contentIndex : advertiser.getListingContentIndexEntry()) {

                Listing propertyListing = CommonUtils.unmarshall(new URL(contentIndex.getListingUrl()),
                        Listing.class);

                String altId = propertyListing.getExternalId();
                LOG.debug("Current AltId=" + altId);

                Address propertyAddress = propertyListing.getLocation().getAddress();
                String countryISO = propertyAddress.getCountry().value();
                String state = propertyAddress.getStateOrProvince();
                String city = propertyAddress.getCity();
                Double latitude = propertyListing.getLocation().getGeoCode().getLatLng().getLatitude()
                        .doubleValue();
                Double longitude = propertyListing.getLocation().getGeoCode().getLatLng().getLongitude()
                        .doubleValue();

                Location location = null;
                if (latitude != null && longitude != null) {
                    location = PartnerService.getLocation(sqlSession, city, state, countryISO, latitude,
                            longitude);
                } else {
                    location = PartnerService.getLocation(sqlSession, city, state, countryISO);
                }

                if (location == null) {
                    sbNotKnowLocation.append("\n")
                            .append("Lodgix property: " + altId + " country: " + countryISO + " city: " + city);
                }
                Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altId, true);
                if (product == null) {
                    continue;
                }

                ArrayList<String> attributes = new ArrayList<String>();

                if (propertyListing.getUnits().getUnit().size() > 0) {
                    UnitWSD propertyUnit = propertyListing.getUnits().getUnit().get(0);

                    product.setPerson(propertyUnit.getMaxSleep());
                    product.setCurrency(propertyUnit.getUnitMonetaryInformation().getCurrency());

                    attributes.add(propertyUnit.getPropertyType().getCode());
                    //                  addType(attributes, propertyUnit.getPropertyType().name());

                    int numberOfBathrooms = 0;
                    if (propertyUnit.getBathrooms().getBathroom() != null) {
                        numberOfBathrooms = propertyUnit.getBathrooms().getBathroom().size();
                        for (Bathroom currentBathroom : propertyUnit.getBathrooms().getBathroom()) {
                            attributes.add(currentBathroom.getRoomSubType().getCode());
                        }
                    }
                    product.setBathroom(numberOfBathrooms);

                    int numberOfBedrooms = 0;
                    if (propertyUnit.getBedrooms().getBedroom() != null) {
                        numberOfBedrooms = propertyUnit.getBedrooms().getBedroom().size();
                        for (Bedroom currentBedroom : propertyUnit.getBedrooms().getBedroom()) {
                            attributes.add(currentBedroom.getRoomSubType().getCode());
                        }
                    }
                    product.setRoom(numberOfBedrooms);

                    //this are unit features
                    if (propertyUnit.getFeatureValues() != null
                            && propertyUnit.getFeatureValues().getFeatureValue() != null) {
                        for (UnitFeatureValue feature : propertyUnit.getFeatureValues().getFeatureValue()) {
                            attributes.add(feature.getUnitFeatureName().getCode());
                        }
                    }
                }

                String propertyName = "";
                for (net.cbtltd.rest.homeaway.feedparser.domain.Text propertyNameText : propertyListing
                        .getAdContent().getPropertyName().getTexts().getText()) {
                    if (propertyNameText.getLocale().equalsIgnoreCase(LOCALE_LANGUAGE)) {
                        propertyName = propertyNameText.getTextValue();
                        break;
                    }
                }

                if (propertyName.equalsIgnoreCase("")) {
                    System.out.println("WARNING: There is no property name on english.");
                    for (net.cbtltd.rest.homeaway.feedparser.domain.Text propertyHedlineText : propertyListing
                            .getAdContent().getHeadline().getTexts().getText()) {
                        if (propertyHedlineText.getLocale().equalsIgnoreCase(LOCALE_LANGUAGE)) {
                            propertyName = propertyHedlineText.getTextValue();
                            break;
                        }
                    }
                }
                product.setName(propertyName);

                product.setAltSupplierId(getAltpartyid());
                product.setSupplierid(getAltpartyid());

                product.setCommission(getCommission());
                product.setDiscount(getDiscount());
                product.setRank(0.0);
                product.setAltitude(0.0);
                product.setLatitude(latitude);
                product.setLongitude(longitude);

                product.setWebaddress(getWebaddress());
                product.setCommission(getCommission());
                product.setDiscount(getDiscount());
                product.setRating(5);

                product.setChild(0);
                product.setInfant(0);
                product.setToilet(0);
                product.setQuantity(1);
                product.setUnit(Unit.DAY);
                product.setSecuritydeposit(Product.DEFAULT_SECUIRTY_DEPOSIT);
                product.setCleaningfee(Product.DEFAULT_CLEANING_FEE);

                // this 2 fields we need for creating getting quotes
                //web address field is not used, so we can use this field too
                product.setCode(advertiserIdCurrent);
                product.setWebaddress(contentIndex.getListingUrl());

                product.setVersion(version);

                StringBuilder address = new StringBuilder();
                if (!checkIfValueNullOrEmpty(propertyAddress.getAddressLine1())) {
                    address.append(propertyAddress.getAddressLine1()).append("\n");
                }
                if (!checkIfValueNullOrEmpty(propertyAddress.getAddressLine2())) {
                    address.append(propertyAddress.getAddressLine2()).append("\n");
                }
                if (!checkIfValueNullOrEmpty(city)) {
                    address.append(city).append("\n");
                }
                if (!checkIfValueNullOrEmpty(state)) {
                    address.append(state).append("\n");
                }
                if (!checkIfValueNullOrEmpty(countryISO)) {
                    address.append(countryISO).append("\n");
                }

                product.setPhysicaladdress(address.toString());

                // TODO check this setting state
                if (location != null && propertyListing.isActive()) {
                    product.setLocationid(location.getId());
                    product.setState(Product.CREATED);
                } else {
                    product.setState(Product.SUSPENDED);
                }

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

                //this are property features
                if (propertyListing.getFeatureValues() != null
                        && propertyListing.getFeatureValues().getFeatureValue() != null) {
                    for (ListingFeatureValue feature : propertyListing.getFeatureValues().getFeatureValue()) {
                        attributes.add(feature.getListingFeatureName().getCode());
                    }
                }

                String descriptionProperty = "";
                for (net.cbtltd.rest.homeaway.feedparser.domain.Text descriptionText : propertyListing
                        .getAdContent().getDescription().getTexts().getText()) {
                    if (descriptionText.getLocale().equalsIgnoreCase(LOCALE_LANGUAGE)) {
                        descriptionProperty = descriptionText.getTextValue();
                        break;
                    }
                }
                StringBuilder description = new StringBuilder();
                description.append(descriptionProperty);
                product.setPublicText(new Text(product.getPublicId(), product.getName(), Text.Type.HTML,
                        new Date(), description.toString(), Language.EN));

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

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

                sqlSession.commit();
            }

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

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

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

}

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

License:Open Source License

@Override
public void readImages() {
    Date timestamp = new Date();
    String message = "readImages Lodgix (PartyId: " + this.getAltpartyid() + ")";
    LOG.debug(message);// ww  w .  j  av  a2s  .c  om

    final SqlSession sqlSession = RazorServer.openSession();
    try {
        Party party = sqlSession.getMapper(PartyMapper.class).read(this.getAltpartyid());
        String advertiserIdForThisPM = party.getAltid();

        ListingContentIndex content = CommonUtils.unmarshall(new URL(PRODUCTS_URL), ListingContentIndex.class);
        for (AdvertiserListingIndex.Advertiser advertiser : content.getAdvertisers().getAdvertiser()) {
            String advertiserIdCurrent = advertiser.getAssignedId();
            if (!advertiserIdForThisPM.equalsIgnoreCase(advertiserIdCurrent)) {
                continue;
            }
            for (ListingContentIndexEntry contentIndex : advertiser.getListingContentIndexEntry()) {
                if (!checkIfValueNullOrEmpty(contentIndex.getListingUrl())) {
                    Listing propertyListing = CommonUtils.unmarshall(new URL(contentIndex.getListingUrl()),
                            Listing.class);
                    String altId = propertyListing.getExternalId();

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

                    if (propertyListing.getImages() != null && propertyListing.getImages().getImage() != null) {
                        ArrayList<NameId> images = new ArrayList<NameId>();
                        List<Image> imagesList = propertyListing.getImages().getImage();
                        for (Image currentImage : imagesList) {
                            images.add(new NameId(currentImage.getExternalId(), currentImage.getUri()));
                        }
                        UploadFileService.uploadImages(sqlSession, NameId.Type.Product, product.getId(),
                                Language.EN, images);
                    }

                    sqlSession.commit();
                }
            }
        }

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

}

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

License:Open Source License

@Override
public void readSchedule() {
    Date version = new Date();
    String message = "readSchedule Lodgix (PartyId: " + this.getAltpartyid() + ")";
    LOG.debug(message);//from www  . j  ava2  s  .  co  m

    //TODO temp finding last cronjob run
    //temp will be 5 days.
    Calendar cal = Calendar.getInstance();
    cal.setTime(version);
    cal.add(Calendar.DATE, -555);
    Date lastCronJobRun = cal.getTime();

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

        Party party = sqlSession.getMapper(PartyMapper.class).read(this.getAltpartyid());
        String advertiserIdForThisPM = party.getAltid();

        ListingContentIndex content = CommonUtils.unmarshall(new URL(RESERVATIONS_URL),
                ListingContentIndex.class);

        for (AdvertiserListingIndex.Advertiser advertiser : content.getAdvertisers().getAdvertiser()) {
            String advertiserIdCurrent = advertiser.getAssignedId();
            if (!advertiserIdForThisPM.equalsIgnoreCase(advertiserIdCurrent)) {
                continue;
            }

            for (ListingContentIndexEntry contentIndex : advertiser.getListingContentIndexEntry()) {
                //checking last update
                Date apiPropertyLastUpdate = getDateTime(contentIndex.getLastUpdatedDate());
                if (apiPropertyLastUpdate.before(lastCronJobRun)) {
                    continue;
                }

                if (!checkIfValueNullOrEmpty(contentIndex.getUnitReservationsUrl())) {
                    ListingReservations reservationList = CommonUtils.unmarshall(
                            new URL(contentIndex.getUnitReservationsUrl()), ListingReservations.class);
                    String altId = reservationList.getListingExternalId();

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

                    ArrayList<Reservation> reservationsFromApi = new ArrayList<Reservation>();
                    for (net.cbtltd.rest.homeaway.feedparser.domain.Reservation reservationCurrent : reservationList
                            .getReservations().getReservation()) {
                        XMLGregorianCalendar beginDate = reservationCurrent.getReservationDates()
                                .getBeginDate();
                        XMLGregorianCalendar endDate = reservationCurrent.getReservationDates().getEndDate();

                        Date fromDate = getDateTime(beginDate);
                        Date toDate = getDateTime(endDate);

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

                        reservationsFromApi.add(reservation);

                        //                     PartnerService.createSchedule(sqlSession, product, fromDate, toDate, version);
                    }

                    //                  PartnerService.cancelSchedule(sqlSession, product, version);

                    PartnerService.updateProductSchedules(sqlSession, product, reservationsFromApi, version);
                    sqlSession.commit();
                }
            }
        }
    } catch (Throwable x) {
        x.printStackTrace();
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
    }
    MonitorService.monitor(message, version);
}

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

License:Open Source License

public void readFees() {

    Date version = new Date();
    String message = "readPrices NextpaxAPIKEY: " + this.getApikey() + "STARTED";
    LOG.debug(message);//from w ww.j  a  v a2s  . c  om

    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");
        int i = 0;
        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.nextpax.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);//  w  ww.jav  a 2 s. c o m

    String fn = "paxgenerator_house_additional_costs_" + getApikey() + ".xml";
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        // costs
        // additional_costs
        SAXBuilder parser = new SAXBuilder();
        Document document = parser.build(ftp(fn));
        Element rootNode = document.getRootElement();
        List<Element> houses = rootNode.getChildren("AdditionalCosts");
        int i = 0;
        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");

                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.setUnit(costamounttype);
                price.setName(getCostCode(costcode));
                price.setType(costtype.equalsIgnoreCase("MAN") ? NameId.Type.Mandatory.name()
                        : NameId.Type.Feature.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
            }
            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.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  w w.j  av  a 2s  . co 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;//from   w  w  w .  j  a  v  a 2 s .  c  o  m

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