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

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

Introduction

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

Prototype

void commit();

Source Link

Document

Flushes batch statements and commits database connection.

Usage

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from  w ww. j a v  a 2s.  c o m
public Map<String, String> createReservationAndPayment(SqlSession sqlSession, Reservation reservation,
        CreditCard creditCard) {
    Date timestamp = new Date();
    String message = "Lodgix createReservationAndPayment (PartyId: " + this.getAltpartyid() + "), resrvationId:"
            + reservation.getId();
    LOG.debug(message);

    Map<String, String> result = new HashMap<String, String>();
    try {
        if (reservation.notActive()) {
            throw new ServiceException(Error.reservation_state,
                    reservation.getId() + " state " + reservation.getState());
        }
        Product product = sqlSession.getMapper(ProductMapper.class).read(reservation.getProductid());
        if (product == null) {
            throw new ServiceException(Error.product_id, reservation.getProductid());
        }
        if (reservation.noAgentid()) {
            throw new ServiceException(Error.reservation_agentid);
        }
        Party agent = sqlSession.getMapper(PartyMapper.class).read(reservation.getAgentid());
        if (agent == null) {
            throw new ServiceException(Error.party_id, reservation.getAgentid());
        }
        if (reservation.noCustomerid()) {
            reservation.setCustomerid(Party.NO_ACTOR);
        }
        Party customer = sqlSession.getMapper(PartyMapper.class).read(reservation.getCustomerid());
        if (customer == null) {
            throw new ServiceException(Error.reservation_customerid, reservation.getCustomerid());
        }

        //not neccessary any more to check price. This is done in AbstractReservation
        //         double oldQuote = reservation.getQuote();
        List<Element> orderItemList = this.getOrderItemsAndComputePrice(sqlSession, reservation,
                product.getAltid(), reservation.getCurrency(), timestamp);

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

        String userFirstLastName = "";
        if (!customer.noFirstName()) {
            userFirstLastName += customer.getFirstName();
        }
        if (!customer.noFamilyName()) {
            if (!this.checkIfValueNullOrEmpty(userFirstLastName)) {
                userFirstLastName += " ";
            }
            userFirstLastName += customer.getFamilyName();
        }

        StringBuilder requestQuote = new StringBuilder();
        requestQuote.append("<?xml version='1.0' encoding='UTF-8'?>");
        requestQuote.append("<bookingRequest>");
        requestQuote.append("  <bookingRequestDetails>");
        requestQuote.append("    <advertiserAssignedId>" + product.getCode() + "</advertiserAssignedId>");
        requestQuote.append("    <listingExternalId>" + product.getAltid() + "</listingExternalId>");
        requestQuote.append("    <propertyUrl>" + product.getWebaddress() + "</propertyUrl>");
        requestQuote.append("    <listingChannel>" + CHANNEL_LIST_VALUE + "</listingChannel>");
        if (!checkIfValueNullOrEmpty(reservation.getNotes())) {
            requestQuote.append("<message>" + reservation.getNotes() + "</message>");
        }
        requestQuote.append("    <inquirer>");
        requestQuote.append("        <name>" + userFirstLastName + "</name>");

        if (!customer.noEmailaddress()) {
            requestQuote.append("    <emailAddress>" + customer.getEmailaddress() + "</emailAddress>");
        }
        if (!checkIfValueNullOrEmpty(customer.getDayphone())) {
            requestQuote.append("    <phoneNumber>" + customer.getDayphone() + "</phoneNumber>");
        }
        requestQuote.append("        <address rel='BILLING'>");
        requestQuote.append("          <addressLine1>" + customer.getLocalAddress() + "</addressLine1>");
        requestQuote.append("          <addressLine3>" + customer.getCity() + "</addressLine3>");

        //TODO check state for Canada
        if (!checkIfValueNullOrEmpty(customer.getRegion())) {
            requestQuote.append("      <addressLine4>" + customer.getRegion() + "</addressLine4>");
        }

        if (!customer.noCountry()) {
            requestQuote.append("        <country>" + customer.getCountry() + "</country>");
        }
        if (!checkIfValueNullOrEmpty(customer.getPostalcode())) {
            requestQuote.append("        <postalCode>" + customer.getPostalcode() + "</postalCode>");
        }

        requestQuote.append("        </address>");
        requestQuote.append("    </inquirer>");
        requestQuote.append("    <commission/>");
        requestQuote.append("    <reservation>");
        requestQuote.append("      <numberOfAdults>" + reservation.getAdult() + "</numberOfAdults>");
        requestQuote.append("      <numberOfChildren>" + reservation.getChild() + "</numberOfChildren>");
        requestQuote.append("      <numberOfPets>" + NUMBER_OF_PETS_DEFAULT + "</numberOfPets>");
        requestQuote.append("      <reservationDates>");
        requestQuote.append(
                "        <beginDate>" + apiRequestDF.format(reservation.getFromdate()) + "</beginDate>");
        requestQuote.append("        <endDate>" + apiRequestDF.format(reservation.getTodate()) + "</endDate>");
        requestQuote.append("      </reservationDates>");
        requestQuote.append("    </reservation>");
        if (orderItemList != null && orderItemList.size() > 0) {
            requestQuote.append("<orderItemList>");
            for (Element orderItemElement : orderItemList) {
                requestQuote.append("<orderItem>");
                requestQuote.append("  <feeType>" + orderItemElement.getChildText("feeType") + "</feeType>");
                requestQuote.append("  <name>" + orderItemElement.getChildText("name") + "</name>");
                requestQuote.append("  <preTaxAmount currency='"
                        + orderItemElement.getChild("preTaxAmount").getAttributeValue("currency") + "'>"
                        + orderItemElement.getChildText("preTaxAmount") + "</preTaxAmount>");
                requestQuote.append("  <totalAmount currency='"
                        + orderItemElement.getChild("totalAmount").getAttributeValue("currency") + "'>"
                        + orderItemElement.getChildText("totalAmount") + "</totalAmount>");
                requestQuote.append("</orderItem>");
            }
            requestQuote.append("</orderItemList>");
        }

        requestQuote.append("    <paymentCard>");
        requestQuote.append("      <paymentFormType>CARD</paymentFormType>");
        requestQuote.append("      <billingAddress rel='BILLING'>");
        requestQuote.append("        <addressLine1>" + customer.getLocalAddress() + "</addressLine1>");
        requestQuote.append("        <addressLine3>" + customer.getCity() + "</addressLine3>");

        //TODO check state for Canada
        if (!checkIfValueNullOrEmpty(customer.getRegion())) {
            requestQuote.append("      <addressLine4>" + customer.getRegion() + "</addressLine4>");
        }
        if (!customer.noCountry()) {
            requestQuote.append("      <country>" + customer.getCountry() + "</country>");
        }
        if (!checkIfValueNullOrEmpty(customer.getPostalcode())) {
            requestQuote.append("      <postalCode>" + customer.getPostalcode() + "</postalCode>");
        }

        //card month need to be in MM format
        String cardMonth = creditCard.getMonth();
        if (cardMonth.length() == 1) {
            cardMonth = "0" + cardMonth;
        }
        requestQuote.append("      </billingAddress>");
        requestQuote.append("      <cvv>" + creditCard.getSecurityCode() + "</cvv>");
        requestQuote.append("      <expiration>" + cardMonth + "/" + creditCard.getYear() + "</expiration>");
        requestQuote.append("      <number>" + creditCard.getNumber() + "</number>");
        requestQuote.append("      <numberToken>" + HOMEAWAY_TOKEN_CARD_NUMBER + "</numberToken>");
        requestQuote.append("      <nameOnCard>" + userFirstLastName + "</nameOnCard>");
        requestQuote.append("      <paymentCardDescriptor>");
        requestQuote.append("        <paymentFormType>CARD</paymentFormType>");
        requestQuote.append(
                "        <cardCode>" + this.getCreditCardLodgixTypeId(creditCard.getType()) + "</cardCode>");
        //requestQuote.append("        <cardType>CREDIT</cardType>");
        requestQuote.append("      </paymentCardDescriptor>");
        requestQuote.append("    </paymentCard>");
        requestQuote.append("    <travelerSource>" + CHANNEL_LIST_VALUE + "</travelerSource>");
        requestQuote.append("  </bookingRequestDetails>");
        requestQuote.append("</bookingRequest>");

        String request = requestQuote.toString();
        LOG.debug("Book Request: " + request);
        String responseQuote = getApiConnection(request, LODGIX_API_BOOK_URL);

        SAXBuilder builder = new SAXBuilder();
        Document document = (Document) builder.build(new StringReader(responseQuote));
        Element rootNode = document.getRootElement();

        if (rootNode.getChild("bookingResponseDetails") != null) {
            Element reservationLodgix = rootNode.getChild("bookingResponseDetails");
            reservation.setAltid(reservationLodgix.getChildText("externalId"));
            //            reservation.setConfirmationId(reservationLodgix.getChildText("operationKey"));
            reservation.setAltpartyid(getAltpartyid());
            reservation.setMessage(null);
            result.put(GatewayHandler.STATE, GatewayHandler.ACCEPTED);
            LOG.debug("Lodgix reservation success. Reservation AltID: "
                    + reservationLodgix.getChildText("externalId"));
        } else {
            result.put(GatewayHandler.STATE, GatewayHandler.FAILED);
            String errorDescription = "";
            if (rootNode.getChild("errorList") != null
                    && rootNode.getChild("errorList").getChildren("error") != null) {
                List<Element> errorList = rootNode.getChild("errorList").getChildren("error");
                for (Element errorElement : errorList) {
                    errorDescription += errorElement.getChildText("message") + "; ";
                }
            }
            LOG.debug("Lodgix reservation not success. Error: " + errorDescription);
            result.put(GatewayHandler.ERROR_MSG, errorDescription);
            return result;
        }

    } catch (ServiceException e) {
        reservation.setMessage(e.getMessage());
        reservation.setState(Reservation.State.Cancelled.name());
        sqlSession.getMapper(ReservationMapper.class).update(reservation);
        sqlSession.commit();
        throw new ServiceException(e.getError(), e.getMessage());
    } catch (Throwable x) {
        reservation.setMessage(x.getMessage());
        reservation.setState(Reservation.State.Cancelled.name());
        LOG.error(x.getMessage());
    }
    sqlSession.getMapper(ReservationMapper.class).update(reservation);
    sqlSession.commit();
    MonitorService.monitor(message, timestamp);

    return result;
}

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  v a2  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);/*www .  j a  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 a2 s  .c o  m

    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   w  ww.j  av a 2  s. c  o  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.mybookingpal.A_Handler.java

License:Open Source License

public void writeAvailableSchedule(String partyid) {
    LOG.debug("writeAvailableSchedule");
    String filename = "availabilityschedule";
    String ROOT_ELEMENT = "products";
    BufferedWriter bw = createXMLFile(filename);
    writeOpeningXML(ROOT_ELEMENT, bw);/*w  w  w .j a  v  a2  s  .c o  m*/
    final SqlSession sqlSession = RazorServer.openSession();
    final String POS = Model.encrypt(partyid);

    ChannelPartner channelpartnerid = sqlSession.getMapper(ChannelPartnerMapper.class)
            .readByPartyId(Integer.parseInt(partyid));
    if (channelpartnerid == null && channelpartnerid.getId() == null) {
        throw new ServiceException(Error.party_value, "product [" + partyid + "]");
    }

    ReservationFeedGenerator reservationfeedgenerator = null;
    reservationfeedgenerator = reservationfeedgenerator.getInstance();

    ArrayList<String> productidlist = PropertyList.getActivePropertyListByChannelPartner(sqlSession,
            channelpartnerid.getId().toString());

    XStream xstream = XstreamAnnotations.getAnnotationsForAvailableSchedule();

    try {
        for (int i = 0; i < productidlist.size(); i++) {
            bw.write((xstream
                    .toXML(reservationfeedgenerator.generateAvailabilitySchedule(productidlist.get(i), POS))));
            bw.newLine();

            if (i % A_Handler.COMMIT_SESSION == 0) {
                sqlSession.commit();
            }

        }
    } catch (IOException e) {
        LOG.error(e.getMessage());
        ;
    } finally {
        writeClosingXML(ROOT_ELEMENT, bw);
        sqlSession.commit(false);
        sqlSession.close();
    }

}

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

License:Open Source License

public void writeDetailInformation(final String partyid) throws InterruptedException {

    final SqlSession sqlSession = RazorServer.openSession();
    long lStartTime = System.currentTimeMillis();
    int pagenumber = 0;
    final String POS = Model.encrypt(partyid);

    ChannelPartner channelpartnerid = sqlSession.getMapper(ChannelPartnerMapper.class)
            .readByPartyId(Integer.parseInt(partyid));
    if (channelpartnerid == null && channelpartnerid.getId() == null) {
        throw new ServiceException(Error.party_value, "product [" + partyid + "]");
    }// w  w  w . j a  va2s.com

    String ROOT_ELEMENT = "properties";
    String filename = "detailinformation_";
    BufferedWriter bw = createXMLFile(filename + pagenumber);
    writeOpeningXML(ROOT_ELEMENT, bw);
    productFeedGenerator = productFeedGenerator.getInstance();

    ArrayList<String> productidlist = PropertyList.getActivePropertyListByChannelPartner(sqlSession,
            channelpartnerid.getId().toString());
    //   ArrayList<String> productidlist = getActivePropertyList();

    XStream xstream = XstreamAnnotations.getAnnotationsForDetailInformation();

    try {
        for (int i = 0; i < productidlist.size(); i++) {
            System.out.println(productidlist.get(i));
            bw.write(xstream.toXML(
                    productFeedGenerator.generateDetailInformation(productidlist.get(i), POS, sqlSession)));

            if (i % NUMBER_PRODUCT_PER_PAGE == 0 & i != 0) {
                pagenumber++;
                bw = openNewXMLFile(ROOT_ELEMENT, filename + pagenumber, bw);

            }

            if (i % 15 == 0) {
                sqlSession.commit();
            }
            if (i > 800)
                break;
        }

    } catch (IOException e) {
        LOG.error(e.getMessage());
    } finally {
        writeClosingXML(ROOT_ELEMENT, bw);
        sqlSession.close();
    }

    System.out.println("Elapsed seconds: " + (System.currentTimeMillis() - lStartTime) / 1000.0);
}

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

License:Open Source License

/**
 * Transfer accommodation alerts./*from www.j  ava  2s . com*/
 * 
 * @param sqlSession the current SQL session.
 */
@Override
public synchronized void readAlerts() {
    Date version = new Date();

    LOG.debug("readAlerts NextpaxAPIKEY: " + getApikey() + "STARTED");
    int i = 0;
    String message = "readAlerts " + getAltpartyid();
    LOG.debug(message);
    String fn = null;
    String language;
    String text;
    String startdate;
    String enddate;
    float deposit = 0;
    final SqlSession sqlSession = RazorServer.openSession();
    String partyId = getAltpartyid();

    SAXBuilder parser = new SAXBuilder();
    Document document;
    net.cbtltd.shared.Alert action = new net.cbtltd.shared.Alert();
    try {

        fn = "paxgenerator_house_notices_" + getApikey() + ".xml";
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(ftp(fn)));
            String line;
            while ((line = br.readLine()) != null) {
                while (line.contains("&")) {
                    line = line.replace("&", "");
                }
                sb.append(line);
            }
            br.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        document = parser.build(new ByteArrayInputStream(sb.toString().getBytes()));
        Element rootNode = document.getRootElement();
        List<Element> notices = rootNode.getChildren("Notices");

        for (Element note : notices) {
            String altid = note.getChildText("HouseID");
            Product product = sqlSession.getMapper(ProductMapper.class)
                    .altread(new NameId(getAltpartyid(), altid));
            if (product == null) {
                LOG.error(Error.product_id.getMessage());
                continue;
            }

            HashMap<String, String> texts = new HashMap<String, String>();
            List<Element> descriptions = note.getChildren("Notice");
            for (Element description : descriptions) {
                language = description.getChildText("Language");
                text = description.getChildText("Text");

                String trimText = text.trim();
                int depositIndex = trimText.indexOf("deposit:");

                if (depositIndex >= 0) {
                    deposit = Float.parseFloat(
                            trimText.substring(depositIndex + 9, trimText.indexOf(" ", depositIndex + 9))
                                    .replace(",", "."));
                    LOG.debug("House deposit: " + deposit);
                }

                startdate = description.getChildText("From");
                enddate = description.getChildText("Until");

                action.setEntitytype(NameId.Type.Product.name());
                action.setEntityid(product.getId());
                action.setFromdate(DF.parse(startdate));
                action.setTodate(DF.parse(enddate));
                action.setLanguage(language);
                action.setName(text);

                net.cbtltd.shared.Alert duplicate = sqlSession.getMapper(AlertMapper.class).duplicate(action);
                if (duplicate == null) {
                    sqlSession.getMapper(AlertMapper.class).create(action);
                } else {
                    sqlSession.getMapper(AlertMapper.class).update(action);
                }

                product.setSecuritydeposit((double) deposit);
                sqlSession.getMapper(ProductMapper.class).update(product);
                sqlSession.commit();
                LOG.debug(i++ + " " + action.toString());
            }
            sqlSession.commit();
        }
    } catch (JDOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        sqlSession.close();
        delete(fn);
    }
    LOG.debug("readAlerts NextpaxAPIKEY: " + getApikey() + " DONE");
    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 w w.ja va 2 s.  com*/

    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  w w  . j  a  va2 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);
}