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

License:Open Source License

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

License:Open Source License

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

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

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

License:Open Source License

/**
 * {@inheritDoc}// w ww .ja v  a  2 s .co  m
 */
@Override
public Map<String, String> createReservationAndPayment(SqlSession sqlSession, Reservation reservation,
        CreditCard creditCard) {

    Date timestamp = new Date();
    String message = "createReservation " + reservation.getId();
    LOG.debug(message);

    Map<String, String> result = new HashMap<String, String>();

    try {
        if (reservation.notActive()) {
            throw new ServiceException(Error.reservation_state,
                    reservation.getName() + " " + reservation.getState());
        }
        if (reservation.noProductid()) {
            throw new ServiceException(Error.product_id, " reservation " + reservation.getName());
        }
        if (reservation.noAgentid() && reservation.noCustomerid()) {
            throw new ServiceException(Error.party_id, reservation.getId());
        }

        Party customer = sqlSession.getMapper(PartyMapper.class).read(reservation.getCustomerid());
        if (customer == null) {
            customer = sqlSession.getMapper(PartyMapper.class).read(reservation.getAgentid());
        }
        if (customer == null) {
            throw new ServiceException(Error.party_id, reservation.getId());
        }

        String productaltid = PartnerService.getProductaltid(sqlSession, reservation);

        double oldQuote = reservation.getQuote();

        computePrice(sqlSession, reservation, productaltid);

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

        // Create request XML string
        XMLOutputter outputter = new XMLOutputter();
        Element root = new Element("SummitCove_Reservations");
        //         root.setAttribute("Version", String.valueOf(3));
        Element element = new Element("Reservation");
        root.addContent(element);

        Element propertyID = new Element("PropertyID");
        element.addContent(propertyID);
        propertyID.setText(productaltid);

        Element arrivalDate = new Element("ArrivalDate");
        element.addContent(arrivalDate);
        arrivalDate.setText(format(reservation.getFromdate()));

        Element departureDate = new Element("DepartureDate");
        element.addContent(departureDate);
        departureDate.setText(format(reservation.getTodate()));

        Element firstName = new Element("FirstName");
        element.addContent(firstName);
        firstName.setText(customer.noFirstName() ? Model.UNKNOWN : customer.getFirstName());

        Element lastName = new Element("LastName");
        element.addContent(lastName);
        lastName.setText(customer.noFamilyName() ? Model.UNKNOWN : customer.getFamilyName());

        Element address = new Element("Address");
        element.addContent(address);
        //         address.setText(customer.noAddress(0) ? Model.UNKNOWN : customer.getAddress(0));
        String customerLocalAddress = StringUtils.isEmpty(customer.getLocalAddress()) ? Model.UNKNOWN
                : customer.getLocalAddress();
        address.setText(customerLocalAddress);

        Element city = new Element("City");
        element.addContent(city);
        //         city.setText(customer.noAddress(1) ? Model.UNKNOWN : customer.getAddress(1));
        String customerCity = StringUtils.isEmpty(customer.getCity()) ? Model.UNKNOWN : customer.getCity();
        city.setText(customerCity);

        Element state = new Element("State");
        element.addContent(state);
        //         state.setText(customer.noAddress(2) ? Model.UNKNOWN : customer.getAddress(2));
        String customerState = StringUtils.isEmpty(customer.getRegion()) ? Model.UNKNOWN : customer.getState();
        state.setText(customerState);

        Element zip = new Element("Zip");
        element.addContent(zip);
        //         zip.setText(customer.getPostalcode() == null || customer.getPostalcode().trim().isEmpty() ? Model.UNKNOWN : customer.getPostalcode());
        String customerZip = StringUtils.isEmpty(customer.getPostalcode()) ? Model.UNKNOWN
                : customer.getPostalcode();
        zip.setText(customerZip);

        Element country = new Element("Country");
        element.addContent(country);
        country.setText(customer.noCountry() ? Country.US : customer.getCountry());

        Element dayPhone = new Element("DayPhone");
        element.addContent(dayPhone);
        dayPhone.setText(customer.getDayphone());

        Element eveningPhone = new Element("EveningPhone");
        element.addContent(eveningPhone);
        eveningPhone.setText(customer.getNightphone() == null || customer.getNightphone().trim().isEmpty()
                ? customer.getDayphone()
                : customer.getNightphone());

        Element email = new Element("Email");
        element.addContent(email);
        email.setText(customer.getEmailaddress());

        Element adults = new Element("Adults");
        element.addContent(adults);
        adults.setText(String.valueOf(reservation.getAdult()));

        Element children = new Element("Children");
        element.addContent(children);
        children.setText(String.valueOf(reservation.getChild()));

        Element insuranceOptIn = new Element("InsuranceOptIn");
        element.addContent(insuranceOptIn);
        insuranceOptIn.setText("1");

        // Submit request
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        outputter.output(element, os);
        String rq = os.toString();
        LOG.debug(message + " rq=" + rq);

        InputStream is = PartnerService.getInputStreamNoSSL(RESERVATION_URL, getApikey(), rq);
        SAXBuilder parser = new SAXBuilder();
        Document document = parser.build(is);
        Element rootNode = document.getRootElement();
        String res = rootNode.getValue();
        String[] args = res.split("\\.");
        reservation.setAltid(args[1]);
        reservation.setAltpartyid(getAltpartyid());

        result.put(GatewayHandler.STATE, GatewayHandler.ACCEPTED);

        LOG.error("createReservation " + reservation.getId() + " " + reservation.getAltid());
    } 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) {
        if (x.getMessage() != null && x.getMessage().contains("409")) {
            reservation.setMessage(Error.reservation_api + "Collides with another reservation");
        } else {
            reservation.setMessage(x.getMessage());
        }
        reservation.setState(Reservation.State.Cancelled.name());
        LOG.error(reservation.getMessage());
    }
    sqlSession.getMapper(ReservationMapper.class).update(reservation);
    sqlSession.commit();

    return result;

}

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

License:Open Source License

@Override
public void readPrices() {
    Date version = new Date();
    String message = "readPrices NextpaxAPIKEY: " + this.getApikey() + "STARTED";
    LOG.debug(message);// w ww .  j ava  2  s . c om

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

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

            if (product == null) {
                continue;
            }

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

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

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

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

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

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

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

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

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

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

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

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

License:Open Source License

public void readFeesOld() {

    Date version = new Date();
    String message = "readPrices NextpaxAPIKEY: " + this.getApikey() + "STARTED";
    LOG.debug(message);/* w  w  w.  ja  v  a  2s  .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");
        for (Element house : houses) {
            String altid = house.getChildText("HouseID");
            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altid);

            if (product == null) {
                continue;
            }

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

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

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

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

}

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

License:Open Source License

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

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

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

            if (product == null) {
                continue;
            }

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

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

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

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

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

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

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

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

License:Open Source License

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

    String partyId = getAltpartyid();
    String fileName = "staytoday.xml";
    Map<String, Location> locations = new HashMap<String, Location>();
    try {/* www.  j a  v a2 s  . c om*/
        // House attributes.
        RelationService.load(sqlSession, Downloaded.PRODUCT_DOWNLOAD_DATE, partyId, new Date().toString());
        SAXBuilder parser = new SAXBuilder();

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

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

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

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

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

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

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

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

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

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

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

            // build the list

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

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

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

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

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

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

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

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

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

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

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

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

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

            product.setPhysicaladdress(address);

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

            sqlSession.getMapper(ProductMapper.class).update(product);
            productsProceeded.add(altid);

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

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

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

License:Open Source License

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

    final SqlSession sqlSession = RazorServer.openSession();
    String fileName = "paxgenerator_house_properties_" + getApikey() + ".xml";
    int updatedHouses = 0;
    try {/* w ww. j av  a 2 s. c  om*/
        long startParsing = System.currentTimeMillis();
        LOG.debug("Time taken to parse " + fileName + " : " + (System.currentTimeMillis() - startParsing)
                + " milli seconds.");

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

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

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

            Integer toilet = 0;
            LOG.debug("Setting properties for: " + product.getId());
            List<Element> properties = house.getChildren("Property");
            for (Element property : properties) {
                String attrKey = property.getChildText("PropertyCode");
                // Use `case` when we will move to JAVA 7 or higher
                if (attrKey.equals("B01")) {
                    try {
                        product.setBathroom(Integer.parseInt(property.getChildText("Value"))); // Number of bedrooms.
                    } catch (NumberFormatException e) {
                        // do nothing...move onto next property
                    }
                } else if (attrKey.equals("T07")) {
                    try {
                        toilet = Integer.parseInt(property.getChildText("Value"));
                    } catch (NumberFormatException e) {
                        // do nothing...move onto next property
                    }
                } // do not have mapping do nothing. *Maybe create attributes or add into description?
                else if (attrKey.equals("D02")) {
                    // number of double beds
                } else if (attrKey.equals("S02")) {
                    // number of single beds
                } else if (attrKey.equals("S03")) {
                    // number of sofas
                } else {
                    // look up ATTRIBUTE Map
                    String attrList = ATTRIBUTES.get(attrKey);
                    if (!StringUtils.isEmpty(attrList)) {
                        RelationService.delete(sqlSession, Relation.PRODUCT_OTA_ATTRIBUTE, product.getId(),
                                attrList);
                        // if we are running delta import....this will make sure create will not fail.
                        RelationService.create(sqlSession, Relation.PRODUCT_OTA_ATTRIBUTE, product.getId(),
                                attrList);
                    }
                }
            }

            product.setToilet(toilet);
            if ((product.getRoom() == null || product.getRoom() < 1) || (product.getBathroom() == null)) {
                product.setState(Product.SUSPENDED);
            } else {
                product.setState(Product.CREATED);
            }
            product.setAssignedtomanager(true);

            sqlSession.getMapper(ProductMapper.class).update(product);
            sqlSession.commit();
            updatedHouses++;
        }

    } catch (Throwable e) {
        sqlSession.rollback();
        LOG.error(e.getMessage());
    } finally {
        sqlSession.close();
        delete(fileName);
    }
    LOG.debug("Time taken to complete house properties for " + getApikey() + " with number of houses "
            + updatedHouses + " : " + ((System.currentTimeMillis() - startTime)) / 1000 + " seconds.");
}

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

License:Open Source License

@Override
public void readDescriptions() {
    long startTime = System.currentTimeMillis();
    String altid;/*from w  ww . j  a v a 2 s. c  om*/
    Product product;

    String fileName = "paxgenerator_house_descriptions_" + getApikey() + ".xml";
    int propertymanagerid = getPropertyManagerID(getApikey());

    final SqlSession sqlSession = RazorServer.openSession();
    try {
        long startParsing = System.currentTimeMillis();

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

        Element rootNode = document.getRootElement();
        List<Element> houses = rootNode.getChildren("offer", ns);
        int i = 0;
        StringBuilder sb;
        boolean needBreak = false;
        for (Element house : houses) {
            //try {
            i++;
            if (i < 1907) {
                continue;
            }
            //               if (i % 30 == 0) {
            //                  Thread.sleep(36000);
            //               }
            //               if (i > 735) {
            //                  break;
            //               }

            System.out.println("!!!Product DESC i = " + i);
            System.out.println("!!!Product DESC i = " + i);
            System.out.println("!!!Product DESC i = " + i);
            altid = house.getAttributeValue("internal-id");
            product = PartnerService.getProduct(sqlSession, getAltpartyid(), altid, false);
            if (product == null) {
                continue;
            }

            HashMap<String, String> texts = new HashMap<String, String>(); // Maps language to its text
            Element description = house.getChild("description", ns);
            if (description == null) {
                continue;
            }
            String language = "RU";
            String text = description.getText();

            texts.put(language, text.length() <= IsPartner.TEXT_NOTES_LENGTH ? text
                    : text.substring(0, IsPartner.TEXT_NOTES_LENGTH));

            //if (!texts.containsKey(Language.EN) && RazorConfig.doTranslation()) {// must have an English description!
            if (!texts.containsKey(Language.EN)) {// must have an English description!
                String englishTranslation;
                for (String lang : texts.keySet()) {
                    // sleep for a while to meet google's rate limit
                    Thread.sleep(1200);
                    //System.out.println("TRY TO TRANSLATE: " + texts.get(lang) + ", " + lang + ", " + Language.EN);
                    englishTranslation = TextService.translate(texts.get(lang), lang, Language.EN);
                    if (StringUtils.isNotEmpty(englishTranslation)) {
                        texts.put(Language.EN, englishTranslation);
                        LOG.debug("English_Translation : " + texts.get(Language.EN));
                        break;
                    } else {
                        System.out.println("!!!TTRANSLATION FAILED!!!");
                    }
                    if (englishTranslation == null) {
                        needBreak = true;
                        break;
                    }
                }
            }

            if (needBreak) {
                break;
            }

            for (String lang : texts.keySet()) {
                System.out.println("!!!updating: " + lang);
                LOG.debug("language " + lang + " notes " + texts.get(lang));
                product.setPublicText(new Text(product.getPublicId(), product.getPublicLabel(), Text.Type.Text,
                        new Date(), texts.get(lang), lang));
                TextService.update(sqlSession, product.getTexts());
            }

            if (i > 0 && i % IsPartner.PRICE_BATCH_SIZE == 0) {
                LOG.debug("Smart flush for description: " + i);
                sqlSession.commit();
            }
            //} catch(Exception e) {
            //   e.printStackTrace();
            //}
        }
        sqlSession.commit();
    } catch (Throwable e) {
        e.printStackTrace();
        LOG.error(e.getMessage());
        sqlSession.rollback();
    } finally {
        sqlSession.close();
        delete(fileName);
    }
    LOG.debug("Time taken to complete product descriptions for " + getApikey() + " : "
            + ((System.currentTimeMillis() - startTime)) / 1000 + " seconds.");
}

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

License:Open Source License

@Override
public void readImages() {
    System.out.println("Yandex. Start reading images");
    final SqlSession sqlSession = RazorServer.openSession();
    String message = "Read Images";
    LOG.debug(message);/*from w ww.  jav  a 2s .  c o m*/
    Date version = new Date();
    try {

        Element rootNode = document.getRootElement();
        List<Element> houses = rootNode.getChildren("offer", ns);
        System.out.println("Number of properties " + houses.size());
        int j = 0;
        for (Element house : houses) {
            j++;
            System.out.println("Product images: " + j);
            String altid = house.getAttributeValue("internal-id");
            Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altid);
            if (product == null) {
                continue;
            }
            //ArrayList<NameId> images = new ArrayList<NameId>();
            List<Element> images = house.getChildren("image", ns);
            System.out.println("Number of images " + images.size());
            int i = 1;
            for (Element imageElement : images) {
                String name = product.getName();
                String url = imageElement.getText();
                System.out.println("Image name: " + name + ", url: " + url);

                net.cbtltd.shared.Image image = new net.cbtltd.shared.Image();
                image.setName(name);
                image.setUrl(url);
                image.setLanguage(Language.RU);
                image.setType(Image.Type.Linked);
                image.setStandard(true);
                image.setProductId(Integer.parseInt(product.getId()));
                image.setNotes(name);
                image.setSort(i++);
                image.setState("Created");

                List<String> idList = sqlSession.getMapper(ImageMapper.class).imageidsbyurl(image);
                if (idList != null && idList.size() > 0) {
                    image.setId(idList.get(0));
                    sqlSession.getMapper(ImageMapper.class).update(image);
                } else {
                    sqlSession.getMapper(ImageMapper.class).create(image);
                }

                //images.add(new NameId(name, url));
            }
            //LOG.debug("Total images uploading for the property " + product.getId() + ": " + images.size());
            //UploadFileService.uploadImages(sqlSession, NameId.Type.Product, product.getId(), Language.EN, images);

            sqlSession.commit();
            MonitorService.monitor(message, version);
        }
    } catch (Throwable e) {
        sqlSession.rollback();
        e.printStackTrace();
        LOG.error(e.getMessage());
    } finally {
        sqlSession.close();
    }
    long endTime = System.currentTimeMillis();
    LOG.debug("Total time taken for readImage execution " + getApikey() + " : " + (endTime - startTime) / 1000
            + " seconds.");
}