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

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

Introduction

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

Prototype

void rollback();

Source Link

Document

Discards pending batch statements and rolls database connection back.

Usage

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

License:Open Source License

@Override
public void readDescriptions() {
    long startTime = System.currentTimeMillis();
    String altid;/*from  w  ww . j a  v a2 s.  c  o  m*/
    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  w  w. j  a  v a 2  s .c  om*/
    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.");
}

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

License:Open Source License

@Override
public synchronized void readSchedule() {
    LOG.debug("Yandex readSchedule() key: " + this.getApikey() + "_started");
    Scanner sc = null;//from  ww  w . j  ava2s .  c o  m
    Date version = new Date();
    String line = "";
    String message = "readSchedule";
    String altid;
    String periodid;
    String startdate;
    String enddate;
    Double length;
    String lastminute;
    String rentprice;
    String bookingcosts;
    String discount;
    String othercosts;
    String totalprice;
    String discountcode;
    String recordhash;
    String[] houseinformation;

    Product product = null;

    String partyId = getAltpartyid();

    boolean firsttime = true;
    long startTime = System.currentTimeMillis();

    LOG.debug(message);
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        SortedSet<DateTime> availableDates = new TreeSet<DateTime>();
        List<Price> prices = new ArrayList<Price>();
        long startTimeForProductProcessing = 0;
        int i = 0;

        Element rootNode = document.getRootElement();
        List<Element> houses = rootNode.getChildren("offer", ns);
        for (Element house : houses) {

            altid = house.getAttributeValue("internal-id");
            product = PartnerService.getProduct(sqlSession, partyId, altid);
            System.out.println("PRODUCT ID: " + product.getId());

            Element ratePeriods = house.getChild("rateperiods", ns);
            List<Element> ratePeriodList = ratePeriods.getChildren("rateperiod", ns);
            System.out.println("ratePeriodList size = " + ratePeriodList.size());
            for (Element ratePeriod : ratePeriodList) {
                startdate = ratePeriod.getChildText("startdate", ns);
                enddate = ratePeriod.getChildText("enddate", ns);
                System.out.println("startdate = " + startdate);
                System.out.println("enddate = " + enddate);

                addToAvailableDates(availableDates, startdate, enddate);
                createSchedule(availableDates, product, version, sqlSession);
            }
        }
        /*
        String currenthouse = "";
        while (sc.hasNext()) {
           line = sc.nextLine();
           if (line.isEmpty()) {
              continue;
           }
           houseinformation = line.split("\\|");
                
           if (firsttime) {
              currenthouse = houseinformation[0];
              product = sqlSession.getMapper(ProductMapper.class).altread(new NameId(partyId, currenthouse));
              if (product == null) {
          continue;
              }
              firsttime = false;
              // product = PartnerService.getProduct(sqlSession, partyId, currenthouse); // check for null
              startTimeForProductProcessing = System.currentTimeMillis();
           }
                
           altid = houseinformation[0];
           periodid = houseinformation[1];
           startdate = houseinformation[2];
           enddate = houseinformation[3];
           length = Double.valueOf(houseinformation[4]);
           lastminute = houseinformation[5];
           rentprice = houseinformation[6];
           bookingcosts = houseinformation[7];
           discount = houseinformation[8];
           othercosts = houseinformation[9];
           totalprice = houseinformation[10];
           discountcode = houseinformation[11];
           recordhash = houseinformation[12];
                
           // price table
           Price price = new Price();
           price.setAltid(periodid);
           price.setPartyid(getAltpartyid());
           price.setEntitytype(NameId.Type.Product.name());
           price.setEntityid(product.getId());
           price.setCurrency(Currency.Code.EUR.name());
           price.setQuantity(length);
           price.setUnit(Unit.DAY);
           price.setName(Price.RACK_RATE);
           price.setType(NameId.Type.Reservation.name());
           price.setDate(DF.parse(startdate));
           price.setTodate(DF.parse(enddate));
                
           net.cbtltd.shared.Price exists = sqlSession.getMapper(PriceMapper.class).existsAltID(price);
                
           price.setFactor(1.0);
           price.setOrganizationid(getAltpartyid());
           price.setRule(getDayOfWeek(DF.parse(startdate)));
           price.setAvailable(1);
           price.setState(Price.CREATED);
           double unitprice = Double.valueOf(totalprice) / length; // what is this ?
           price.setValue(NameId.round(Double.valueOf(totalprice) / length));
           price.setMinimum(Double.valueOf(totalprice));
           price.setMinStay(length.intValue());
           price.setVersion(version);
                
           price.setEntityid(product.getId());
           if (exists != null) {
              //add price into array and update it after
              // sqlSession.getMapper(PriceMapper.class).create(price);
                      
              // check if there is reservation for this price.
              // if reservation is created and we still get the price,
              // we need to cancel the reservation
              Reservation action = new Reservation();
              action.setProductid(product.getId());
              action.setFromdate(price.getDate());
              action.setTodate(price.getTodate());
              action = sqlSession.getMapper(ReservationMapper.class).collides(action);
              if (action != null && StringUtils.isNotBlank(action.getAltid())) {
          // cancel this reservation
          PartnerService.cancelReservation(sqlSession, action);
              }
              price.setId(exists.getId());
              // sqlSession.getMapper(PriceMapper.class).update(price);
           }
           prices.add(price);
                
           // when we come across a new house will create reservations for
           // the blocked dates for the previous house.
           // create a map of available dates
           // iterate through prices and check off the dates from the
           // collection of month dates and use the rest of the dates
           // to create the reservation
           if (currenthouse.compareTo(altid) != 0 || !sc.hasNext()) {
              if (!sc.hasNext()) {
          addToAvailableDates(availableDates, startdate, enddate);
              }
                
              createSchedule(availableDates, product, version, sqlSession);
              // insert list of prices
              sqlSession.getMapper(PriceMapper.class).insertList(prices);
              // clear list
              prices.clear();
              sqlSession.commit();
                      
              LOG.debug("Time taken for Product Process " + currenthouse + " : "
             + (System.currentTimeMillis() - startTimeForProductProcessing));
                
              // now cancel price for existing property that we did not process in this run.
              sqlSession.getMapper(PriceMapper.class).cancelversion(price);
                
              // reset fields
              // create a new set for the next home
              currenthouse = altid;
              availableDates = new TreeSet<DateTime>();
              // product = PartnerService.getProduct(sqlSession, partyId, currenthouse);
              product = sqlSession.getMapper(ProductMapper.class).altread(new NameId(partyId, currenthouse));
              startTimeForProductProcessing = System.currentTimeMillis();
           }
                
           if (sc.hasNext()) {
              addToAvailableDates(availableDates, startdate, enddate);
           }
                
        }*/
        sqlSession.commit();

        // Cancel old reservations.
        resetStartTime();
        cancelOldReservations(sqlSession, version);
        LOG.debug("Canceled old reservations: " + (System.currentTimeMillis() - getStartTime()));
        sqlSession.commit();

    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        if (sc != null) {
            try {
                sc.close();
                sqlSession.close();
            } catch (Exception e) {
                LOG.error(e.getMessage());
            }
        }
    }
    long endTime = System.currentTimeMillis();
    LOG.debug("NextPax readSchedule() for key: " + this.getApikey() + " done." + " Time: "
            + (endTime - startTime));
    MonitorService.monitor(message, version);
}

From source file:net.cbtltd.server.LicenseService.java

/**
 * Executes the LicenseCreate action./* w  w w.  j ava2s.c  o  m*/
 *
 * @param sqlSession the current SQL session
 * @param action the action to be executed.
 * @return the response.
 */
public final License execute(SqlSession sqlSession, LicenseCreate action) {
    LOG.debug("LicenseCreate in " + action);
    try {
        sqlSession.getMapper(LicenseMapper.class).create(action);
    } catch (Throwable x) {
        sqlSession.rollback();
        MonitorService.log(x);
    }
    return action;
}

From source file:net.cbtltd.server.LicenseService.java

/**
 * Executes the LicenseRead action./*from  ww  w.  jav a  2 s  .co m*/
 *
 * @param sqlSession the current SQL session
 * @param action the action to be executed.
 * @return the response.
 */
public final License execute(SqlSession sqlSession, LicenseRead action) {
    License license = null;
    try {
        license = sqlSession.getMapper(LicenseMapper.class).read(action.getId());
    } catch (Throwable x) {
        sqlSession.rollback();
        MonitorService.log(x);
    }
    return license;
}

From source file:net.cbtltd.server.LicenseService.java

/**
 * Executes the LicenseUpdate action.//from   w w  w .j a  va2 s  .  c o  m
 *
 * @param sqlSession the current SQL session
 * @param action the action to be executed.
 * @return the response.
 */
public final License execute(SqlSession sqlSession, LicenseUpdate action) {
    LOG.debug("LicenseUpdate " + action);
    try {
        sqlSession.getMapper(LicenseMapper.class).update(action);
        MonitorService.update(sqlSession, Data.Origin.CONSOLE, NameId.Type.License, action);
        LICENSED.clear();
    } catch (Throwable x) {
        sqlSession.rollback();
        MonitorService.log(x);
    }
    return action;
}

From source file:net.cbtltd.server.LicenseService.java

/**
 * Executes the LicenseDelete action.//from w ww. j  av a 2 s .  co m
 *
 * @param sqlSession the current SQL session
 * @param action the action to be executed.
 * @return the response.
 */
public final License execute(SqlSession sqlSession, LicenseDelete action) {
    try {
        sqlSession.getMapper(LicenseMapper.class).delete(action.getId());
    } catch (Throwable x) {
        sqlSession.rollback();
        MonitorService.log(x);
    }
    return null;
}

From source file:net.cbtltd.server.LicenseService.java

/**
 * Executes the LicenseTable action to read an license table for a property.
 *
 * @param sqlSession the current SQL session.
 * @param action the action to be executed.
 * @return the response.//www  . j av a 2  s .  co m
 */
public final Table<License> execute(SqlSession sqlSession, LicenseTable action) {
    LOG.debug("LicenseTable in " + action);
    Table<License> table = new Table<License>();
    try {
        table.setDatasize(sqlSession.getMapper(LicenseMapper.class).count(action));
        table.setValue(sqlSession.getMapper(LicenseMapper.class).list(action));
    } catch (Throwable x) {
        sqlSession.rollback();
        MonitorService.log(x);
    }
    LOG.debug("LicenseTable out " + table);
    return table;
}

From source file:net.cbtltd.server.LicenseService.java

/**
 * Service to calculate license fees and commission at the end of each month.
 *
 * @param date of license run./* www . ja  v  a2  s.c  o m*/
 */
public static void license(Date date) {
    LOG.debug("License run at " + date);
    SqlSession sqlSession = RazorServer.openSession();
    try {
        ArrayList<Balance> openingbalances = sqlSession.getMapper(JournalMapper.class)
                .licensebalances(Party.CBT_LTD_PARTY);

        {
            ArrayList<Journal> journals = sqlSession.getMapper(JournalMapper.class).license(date);
            Event<Journal> event = null;
            String thisOrganizationid = null;

            int i = 0;
            for (Journal journal : journals) {
                if (!journal.hasOrganizationid(thisOrganizationid)) {
                    i++;
                    endEvent(sqlSession, event, "License Total");
                    thisOrganizationid = journal.getOrganizationid();
                    event = createEvent(sqlSession, thisOrganizationid, date, "License");
                }
                event.addItem(journal);
            }
            endEvent(sqlSession, event, "License Total");
        }
        {
            ArrayList<Journal> journals = sqlSession.getMapper(JournalMapper.class).commission(date);
            Event<Journal> event = null;
            String thisOrganizationid = null;

            for (Journal journal : journals) {
                if (!journal.hasOrganizationid(thisOrganizationid)) {
                    endEvent(sqlSession, event, "Commission Total");
                    thisOrganizationid = journal.getOrganizationid();
                    event = createEvent(sqlSession, thisOrganizationid, date, "Commission");
                }
                journal.setDebitamount(journal.getDebitamount() * WebService.getRate(sqlSession,
                        journal.getCurrency(), Currency.Code.USD.name(), event.getDate()));
                journal.setCurrency(Currency.Code.USD.name());
                event.addItem(journal);
            }
            endEvent(sqlSession, event, "Commission Total");
        }

        LOG.debug("License openingbalances " + openingbalances);
        suspend(sqlSession, date, openingbalances);
        sqlSession.commit();
    } catch (Throwable x) {
        sqlSession.rollback();
        MonitorService.log(x);
    } finally {
        sqlSession.close();
    }
}

From source file:net.cbtltd.server.LicenseService.java

/** Service to calculate license fees and commission balances and email addresses. */
public static final void balance() {
    SqlSession sqlSession = RazorServer.openSession();
    try {/*  w  w w.j ava  2  s . c om*/
        //         Report report = new Report();
        //         report.setActorid(Party.ADMINISTRATOR);
        //         report.setCurrency(Currency.Code.USD.name());
        //         report.setDate(new Date());
        //         report.setDesign(Design.LICENSE_STATEMENT);
        //         report.setFormat(Report.PDF);
        //         report.setNotes("Automatically generated by License Service");
        //         report.setTodate(new Date());

        ArrayList<Balance> balances = sqlSession.getMapper(JournalMapper.class)
                .licensebalances(Party.CBT_LTD_PARTY);
        LOG.debug("balance " + balances);
        for (Balance balance : balances) {

            //            report.setOrganizationid(balance.getPartyid());
            //            report = ReportService.execute(sqlSession, report);

            Currencyrate currencyrate = new Currencyrate(balance.getCurrency(), Currency.Code.USD.name(),
                    new Date());
            currencyrate.setRate(WebService.getRate(sqlSession, currencyrate));
            EmailService.licensebalance(balance.getEmailaddress(), balance.getBalance(), currencyrate);
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        MonitorService.log(x);
    } finally {
        sqlSession.close();
    }
}