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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//ww w.j a  v a 2  s  . com
public Map<String, String> createReservationAndPayment(SqlSession sqlSession, Reservation reservation,
        CreditCard creditCard) {
    Date timestamp = new Date();
    String message = "RMS (Resort Management System) createReservationAndPayment, 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());
        }

        //this is not needed any more
        //         double oldQuote = reservation.getQuote();

        //first we need to run get unit price request one more time, 
        //because all prices need to be included in booking request
        Element rootNodeUnitPrice = this.createAndExecuteGetPriceRequest(sqlSession, reservation,
                product.getAltid());
        //we do this just to fill one more time reservation, to do price comparation.
        this.fillResultsAfterGetPrice(sqlSession, reservation, reservation.getCurrency(), rootNodeUnitPrice,
                product);
        //         if(oldQuote != reservation.getQuote()) {
        //            throw new ServiceException(Error.price_not_match, "old: " + oldQuote + ", new: " + reservation.getQuote());
        //         }

        Element unitElement = rootNodeUnitPrice.getChild("units").getChild("unit");

        String altId = product.getAltid();
        String arrivalDate = this.formatDateToReservationRequest(reservation.getFromdate());
        String departureDate = this.formatDateToReservationRequest(reservation.getTodate());

        //customer data
        String firstName = (!customer.noFirstName()) ? customer.getFirstName() : "";
        String lastName = (!customer.noFamilyName()) ? customer.getFamilyName() : "";
        String addressLine1 = (!this.checkIfValueNullOrEmpty(customer.getLocalAddress()))
                ? customer.getLocalAddress()
                : "";
        String city = (!this.checkIfValueNullOrEmpty(customer.getCity())) ? customer.getCity() : "City"; //city is mandatory 
        String state = (customer.getRegion() != null) ? customer.getRegion() : "";
        String zipCode = (customer.getPostalcode() != null) ? customer.getPostalcode() : "";
        //TODO check this maybe this is only address, not country
        String foreignAddress = (!customer.noCountry()) ? customer.getCountry() : "";
        String cellPhone = (customer.getMobilephone() != null) ? customer.getMobilephone() : "";
        String homePhone = (customer.getNightphone() != null) ? customer.getNightphone() : "";
        String officePhone = (customer.getDayphone() != null) ? customer.getDayphone() : "";
        String faxPhone = (customer.getFaxphone() != null) ? customer.getFaxphone() : "";
        String email = (!customer.noEmailaddress()) ? customer.getEmailaddress() : "";

        //API require at least one phone. So if phones not exist we add phone from agent
        if (this.checkIfValueNullOrEmpty(cellPhone) && this.checkIfValueNullOrEmpty(homePhone)) {
            cellPhone = (agent.getMobilephone() != null) ? agent.getMobilephone() : "";
            homePhone = (agent.getNightphone() != null) ? agent.getNightphone() : "";
        }

        String notePrefix = "Customer comment:";
        String note = (reservation.getNotes() != null) ? reservation.getNotes() : "";

        String resStatusCode = rootNodeUnitPrice.getChildText("reservationStatus");
        String guestRent = unitElement.getChildText("rateTotal");
        String taxTotal = unitElement.getChildText("taxTotal");
        String tax1 = unitElement.getChildText("tax1");
        String tax2 = unitElement.getChildText("tax2");
        String tax3 = unitElement.getChildText("tax3");
        String securityDeposit = unitElement.getChildText("securityDeposit");
        String grandTotal = unitElement.getChildText("grandTotal");
        String depositDue = unitElement.getChildText("depositDue");

        String resOperator = "bookingnet";

        String depositType = "CREDITCARD";
        String ccExpiration = creditCard.getMonth() + "-" + creditCard.getYear();
        String ccName = firstName + " " + lastName;
        String ccNumber = creditCard.getNumber();
        String ccSecurityCode = creditCard.getSecurityCode();

        //now create booking request
        String bookGetUrl = RMS_API_URL + "unit/book?" + "reservation.statusCode=" + resStatusCode
                + "&reservation.arrival=" + arrivalDate + "&reservation.departure=" + departureDate
                + "&reservation.unitId=" + altId + "&reservation.numberOfAdults=" + reservation.getAdult()
                + "&reservation.numberOfChildren=" + reservation.getChild() + "&reservation.firstName="
                + encodeParam(firstName) + "&reservation.lastName=" + encodeParam(lastName)
                + "&reservation.addressLine1=" + encodeParam(addressLine1) + "&reservation.city="
                + encodeParam(city) + "&reservation.state=" + encodeParam(state) + "&reservation.zipCode="
                + encodeParam(zipCode) + "&reservation.foreignAddress=" + encodeParam(foreignAddress)
                + "&reservation.cellPhone=" + encodeParam(cellPhone) + "&reservation.homePhone="
                + encodeParam(homePhone) + "&reservation.officePhone=" + encodeParam(officePhone)
                + "&reservation.faxPhone=" + encodeParam(faxPhone) + "&reservation.email=" + encodeParam(email)
                + "&reservation.notePrefix=" + encodeParam(notePrefix) + "&reservation.note="
                + encodeParam(note) + "&reservation.guestRent=" + guestRent + "&reservation.taxTotal="
                + taxTotal + "&reservation.tax1=" + tax1 + "&reservation.tax2=" + tax2 + "&reservation.tax3="
                + tax3 + "&reservation.securityDeposit=" + securityDeposit + "&reservation.grandTotal="
                + grandTotal + "&reservation.depositDue=" + depositDue + "&reservation.depositType="
                + depositType + "&reservation.operator=" + encodeParam(resOperator) + "&creditCard.expiration="
                + encodeParam(ccExpiration) + "&creditCard.name=" + encodeParam(ccName) + "&creditCard.number="
                + ccNumber + "&creditCard.securityCode=" + ccSecurityCode + "";

        /*
         String bookGetUrl = RMS_API_URL + "unit/book?" +
              "reservation.statusCode="+resStatusCode+
              "&reservation.arrival="+arrivalDate+
              "&reservation.departure="+departureDate+
              "&reservation.unitId="+altId+
              "&reservation.numberOfAdults="+reservation.getAdult()+
              "&reservation.numberOfChildren="+reservation.getChild()+
              "&reservation.firstName="+firstName+
              "&reservation.lastName="+lastName+
              "&reservation.addressLine1="+addressLine1+
              "&reservation.city="+city+
              "&reservation.state="+state+
              "&reservation.zipCode="+zipCode+
              "&reservation.foreignAddress="+foreignAddress+
              "&reservation.cellPhone="+cellPhone+
              "&reservation.homePhone="+homePhone+
              "&reservation.officePhone="+officePhone+
              "&faxPhone="+faxPhone+
              "&reservation.email="+email+
              "&reservation.notePrefix="+notePrefix+
              "&reservation.note="+note+
              "&reservation.guestRent="+guestRent+
              "&reservation.taxTotal="+taxTotal+
              "&reservation.tax1="+tax1+
              "&reservation.tax2="+tax2+
              "&reservation.tax3="+tax3+
              "&reservation.securityDeposit="+securityDeposit+
              "&reservation.grandTotal="+grandTotal+
              "&reservation.depositDue="+depositDue+
              "&reservation.depositType="+depositType+
              "&reservation.operator="+resOperator+
              "&creditCard.expiration="+ccExpiration+
              "&creditCard.name="+ccName+
              "&creditCard.number="+ccNumber+
              "&creditCard.securityCode="+ccSecurityCode+
              "";
         */

        //additional fees
        if (unitElement.getChild("charges") != null
                && unitElement.getChild("charges").getChildren("charge") != null) {
            List<Element> chargesList = unitElement.getChild("charges").getChildren("charge");
            for (Element chargeElement : chargesList) {
                String chargeId = chargeElement.getChildText("id");
                String chargeAmount = chargeElement.getChildText("amount");
                String chargeOption = chargeElement.getChildText("option");
                String chargeEnabled = chargeElement.getChildText("enabled");
                //if charge enabled and not required, than we set that option to false
                if (chargeEnabled.equalsIgnoreCase("true") && !chargeOption.equalsIgnoreCase("R")) {
                    chargeEnabled = "false";
                }

                /*
                //FIXME remove this later
                //this is some small error in API
                //in case of cleaning charge, charge is 120.0, and later charge is 120.07?!
                if(chargeId.equalsIgnoreCase("2")){
                   chargeAmount = "120.07";
                }
                */

                bookGetUrl += "&charge.id=" + chargeId + "&charge.amount=" + chargeAmount + "&charge.enabled="
                        + chargeEnabled;

            }
        }

        LOG.debug("Book request:" + bookGetUrl);
        SAXBuilder parser = new SAXBuilder();
        Document document = parser.build(PartnerService.getInputStream(bookGetUrl, RMS_SERVER_AUTH));
        Element rootNodeBook = document.getRootElement();

        if (rootNodeBook.getChildText("booked") != null
                && rootNodeBook.getChildText("booked").equalsIgnoreCase("true")) {
            reservation.setAltid(rootNodeBook.getChildText("reservationId"));
            reservation.setAltpartyid(getAltpartyid());
            reservation.setMessage(null);
            result.put(GatewayHandler.STATE, GatewayHandler.ACCEPTED);
        } else {
            result.put(GatewayHandler.STATE, GatewayHandler.FAILED);
            String errorDescription = "";
            if (rootNodeBook.getChildText("message") != null) {
                errorDescription = rootNodeBook.getChildText("message");
            }
            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());
        x.printStackTrace();
    }
    sqlSession.getMapper(ReservationMapper.class).update(reservation);
    sqlSession.commit();
    MonitorService.monitor(message, timestamp);

    return result;
}

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

License:Open Source License

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

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

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

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

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

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

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

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

                Double minimumValue = minStay * rateValue;

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

                sqlSession.commit();
            }

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

}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from   w  ww  .  j  a va2  s  . co  m
public void readProducts() {
    String message = "readProducts RMS (Resort Management System) ";
    LOG.debug(message);
    Date version = new Date();

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

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

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

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

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

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

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

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

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

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

            product.setVersion(version);

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

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

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

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

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

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

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

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

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

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

            sqlSession.commit();

        }

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

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

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

}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*w  w w.  ja  v a 2  s. c  o m*/
public void readImages() {
    Date timestamp = new Date();
    String message = "readImages RMS (Resort Management System)";
    LOG.debug(message);

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

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

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

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

}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from w  w w.ja  v  a 2 s . c  om*/
public void readSchedule() {
    Date version = new Date();
    String message = "readSchedule RMS (Resort Management System)";

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

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

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

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

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

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

        sqlSession.commit();

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

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

License:Open Source License

@Override
public Map<String, String> createReservationAndPayment(SqlSession sqlSession, Reservation reservation,
        CreditCard creditCard) {//from   ww w  .  j  a va 2  s  . c o  m
    Date timestamp = new Date();
    String message = "createReservationAndPayment Streamline (Altpartyid:" + 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());
        }

        //this is not necessary any more because this is done in AbstractReservation already 
        //         double oldQuote = reservation.getQuote();
        //         this.computePrice(sqlSession, reservation, product.getAltid(), reservation.getCurrency(),timestamp);
        //         
        //         if(oldQuote != reservation.getQuote()) {
        //            throw new ServiceException(Error.price_not_match, "old: " + oldQuote + ", new: " + reservation.getQuote());
        //         }

        String otherReqParamsAttributes = "<pricing_model>" + PRICING_MODEL + "</pricing_model>" + "<unit_id>"
                + product.getAltid() + "</unit_id>" + "<startdate>" + DF.format(reservation.getFromdate())
                + "</startdate>" + "<enddate>" + DF.format(reservation.getTodate()) + "</enddate>"
                + "<occupants>" + reservation.getAdult() + "</occupants>" + "<occupants_small>"
                + reservation.getChild() + "</occupants_small>+" + DO_NOT_USE_DISCOUNT_CODE;

        //now we need to find all optional tax and fees which are included by default to turn off them.
        Price actionPrice = new Price();
        actionPrice.setType(Tax.Type.SalesTaxExcluded.name());
        actionPrice.setEntityid(product.getId());
        actionPrice.setDate(new Date(0));
        ArrayList<Tax> productTaxesFromDB = sqlSession.getMapper(TaxMapper.class).taxdetail(actionPrice);
        for (Tax currProductTax : productTaxesFromDB) {
            if (currProductTax.getState().equalsIgnoreCase(Tax.MandatoryType.OptionalTax.name())
                    && currProductTax.getOptionValue() != null
                    && currProductTax.getOptionValue().equalsIgnoreCase(OPTIONAL_DEFAULT_ENABLED_FEE_TAX)) {
                otherReqParamsAttributes += "<optional_fee_" + currProductTax.getAltId() + ">no</optional_fee_"
                        + currProductTax.getAltId() + ">";
            }
        }

        Fee actionFee = new Fee();
        actionFee.setProductId(product.getId());
        actionFee.setPartyId(product.getAltpartyid());
        actionFee.setState(Fee.CREATED);
        ArrayList<Fee> productFeesFromDB = sqlSession.getMapper(FeeMapper.class)
                .readbyproductandstate(actionFee);
        for (Fee currProductFee : productFeesFromDB) {
            if (currProductFee.isTypeOptional() && currProductFee.getOptionValue() != null
                    && currProductFee.getOptionValue().equalsIgnoreCase(OPTIONAL_DEFAULT_ENABLED_FEE_TAX)) {
                otherReqParamsAttributes += "<optional_fee_" + currProductFee.getAltId() + ">no</optional_fee_"
                        + currProductFee.getAltId() + ">";
            }
        }

        //now we adding customer data which exist
        if (!customer.noFirstName()) {
            otherReqParamsAttributes += "<first_name>" + customer.getFirstName() + "</first_name>";
        }
        if (!customer.noFamilyName()) {
            otherReqParamsAttributes += "<last_name>" + customer.getFamilyName() + "</last_name>";
        }
        if (StringUtils.isNotEmpty(customer.getLocalAddress())) {
            otherReqParamsAttributes += "<address>" + customer.getLocalAddress() + "</address>";
        }
        if (StringUtils.isNotEmpty(customer.getCity())) {
            otherReqParamsAttributes += "<city>" + customer.getCity() + "</city>";
        }
        if (StringUtils.isNotEmpty(customer.getPostalcode())) {
            otherReqParamsAttributes += "<zip>" + customer.getPostalcode() + "</zip>";
        }
        if (!customer.noEmailaddress()) {
            otherReqParamsAttributes += "<email>" + customer.getEmailaddress() + "</email>";
        }
        if (!customer.noCountry()) {
            otherReqParamsAttributes += "<country_name>" + customer.getCountry() + "</country_name>";
        }
        if (StringUtils.isNotEmpty(customer.getRegion())) {
            otherReqParamsAttributes += "<state_name>" + customer.getRegion() + "</state_name>";
        }
        if (StringUtils.isNotEmpty(customer.getDayphone())) {
            otherReqParamsAttributes += "<work_phone>" + customer.getDayphone() + "</work_phone>";
        }
        if (StringUtils.isNotEmpty(customer.getNightphone())) {
            otherReqParamsAttributes += "<phone>" + customer.getNightphone() + "</phone>";
        }
        if (StringUtils.isNotEmpty(customer.getMobilephone())) {
            otherReqParamsAttributes += "<mobile_phone>" + customer.getMobilephone() + "</mobile_phone>";
        }
        if (StringUtils.isNotEmpty(customer.getFaxphone())) {
            otherReqParamsAttributes += "<fax>" + customer.getFaxphone() + "</fax>";
        }

        //adding credit card data
        otherReqParamsAttributes += "<credit_card_type_id>"
                + this.getCreditCardStreamlineTypeId(creditCard.getType()) + "</credit_card_type_id>"
                + "<credit_card_number>" + creditCard.getNumber() + "</credit_card_number>"
                + "<credit_card_expiration_month>" + creditCard.getMonth() + "</credit_card_expiration_month>"
                + "<credit_card_expiration_year>" + creditCard.getYear() + "</credit_card_expiration_year>"
                + "<credit_card_cid>" + creditCard.getSecurityCode() + "</credit_card_cid>";

        String channelPartnerName = DEFAULT_CHANNEL_PARTNER_NAME;
        ChannelPartner channelPartner = sqlSession.getMapper(ChannelPartnerMapper.class)
                .readByPartyId(Integer.valueOf(reservation.getAgentid()));
        if (channelPartner != null && channelPartner.getChannelName() != null) {
            channelPartnerName = channelPartner.getChannelName();
            LOG.debug("Streamline - channel partner name found: " + channelPartnerName);
        }

        //additional field for new API created for us
        otherReqParamsAttributes += "<price_total>" + reservation.getQuote() + "</price_total>"
                + "<hear_about_new>" + channelPartnerName + "</hear_about_new>";

        String responseMakeReservation = createXMLRequestToStreamline(sqlSession, "MakeReservationbookingnet",
                otherReqParamsAttributes);

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

        if (rootNode.getChild("data") != null && rootNode.getChild("data").getChild("reservation") != null) {
            Element reservationStreamline = rootNode.getChild("data").getChild("reservation");
            LOG.debug("Streamline reservation success, altId: "
                    + reservationStreamline.getChildText("confirmation_id"));
            reservation.setAltid(reservationStreamline.getChildText("confirmation_id"));
            reservation.setAltpartyid(getAltpartyid());
            reservation.setMessage(null);
            result.put(GatewayHandler.STATE, GatewayHandler.ACCEPTED);
        } else {
            result.put(GatewayHandler.STATE, GatewayHandler.FAILED);
            String errorDescription = "";
            if (rootNode.getChild("status") != null
                    && rootNode.getChild("status").getChild("description") != null) {
                errorDescription = rootNode.getChild("status").getChildText("description");
            }
            LOG.debug("Streamline reservation not success - error: " + errorDescription);
            result.put(GatewayHandler.ERROR_MSG, errorDescription);
            return result;
        }

    } catch (Throwable e) {
        e.printStackTrace();
        reservation.setMessage(e.getMessage());
        reservation.setState(Reservation.State.Cancelled.name());
        sqlSession.getMapper(ReservationMapper.class).update(reservation);
        sqlSession.commit();
        LOG.error(e.getMessage());
        throw new ServiceException(Error.reservation_api, e.getMessage());
    }

    sqlSession.getMapper(ReservationMapper.class).update(reservation);
    sqlSession.commit();
    MonitorService.monitor(message, timestamp);

    return result;
}

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

License:Open Source License

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

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

                String productId = product.getId();

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

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

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

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

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

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

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

                }

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

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

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

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

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

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

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

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

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

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

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

                sqlSession.commit();

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

}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from ww w. j a  va2  s  .  c  o  m*/
public void readProducts() {

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

    Date version = new Date();
    String responseAllProperties;

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

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

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

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

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

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

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

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

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

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

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

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

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

                product.setCurrency(CURRENCY_IN_STREAMLINE);

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

                product.setPhysicaladdress(physicalAddress.toString());

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

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

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

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

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

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

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

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

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

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

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

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

        //print not find attributes

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

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

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

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

}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override// ww w  .  j  av a2  s. c o m
public void readImages() {
    Date timestamp = new Date();
    String message = "readImages Streamline (Altpartyid:" + this.getAltpartyid() + ")";
    LOG.debug(message);

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

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

                sqlSession.commit();
            } catch (Throwable x) {
                LOG.error(Error.product_data.name() + altId);
                x.printStackTrace();
            }
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
    }
    MonitorService.monitor(message, timestamp);

}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from   w w  w .ja v  a2s .c  o  m*/
public void readSchedule() {
    Date version = new Date();
    String message = "readSchedule Streamline (Altpartyid:" + this.getAltpartyid() + ")";
    LOG.debug(message);

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

        SAXBuilder builder = new SAXBuilder();
        Document document = (Document) builder.build(new StringReader(responseReservationsAndPrices));
        Element rootNode = document.getRootElement();
        List<Element> properties = rootNode.getChildren("property");
        long parsingApiDataEnd = System.currentTimeMillis();
        LOG.debug("Parsing API data takes: " + (parsingApiDataEnd - gettingApiDataEnd) + "ms");

        for (Element property : properties) {
            long onePropertyStart = System.currentTimeMillis();
            String altId = property.getChildText("propertyId");
            try {
                Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altId, false);
                if (product == null) {
                    //                  LOG.error(Error.product_id.getMessage() + " " + altId);
                    continue;
                }

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

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

                    reservationsFromApi.add(reservation);
                }

                PartnerService.updateProductSchedules(sqlSession, product, reservationsFromApi, version);
                sqlSession.commit();

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