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

License:Open Source License

@Override
public synchronized void readSchedule() {
    LOG.debug("Yandex readSchedule() key: " + this.getApikey() + "_started");
    Scanner sc = null;/*w  ww .j a  va2 s . co 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

/**
 * Service to calculate license fees and commission at the end of each month.
 *
 * @param date of license run.//w ww  .ja va  2s.  co  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.MonitorService.java

/** Persist the monitor instances - executed periodically by the RazorServer scheduler. */
public static void monitor() {
    LOG.debug("Save CALLS " + CALLS);
    SqlSession sqlSession = RazorServer.openSession();
    try {/*ww w.ja va2  s .c o  m*/
        Monitor monitor = new Monitor();
        monitor.setDate(new Date());
        for (String name : CALLS.keySet()) {
            Counter counter = CALLS.get(name);
            if (counter.count == 0) {
                continue;
            }
            monitor.setName(name);
            monitor.setCount(counter.count);
            counter.count = 0;
            monitor.setDuration(counter.duration);
            counter.duration = 0.0;
            sqlSession.getMapper(MonitorMapper.class).create(monitor);
            sqlSession.commit();
        }
    } catch (Throwable x) {
        LOG.error(x.getMessage() + "CALLS error " + CALLS);
    } finally {
        sqlSession.close();
    }
}

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

/**
 * Executes the OrganizationCreate action to create a property manager (Party of type organization) instance.
 *
 * @param sqlSession the current SQL session.
 * @param action the action to be executed.
 * @return the organization/* ww w.j  av a  2  s .co m*/
 */
public final Organization execute(SqlSession sqlSession, OrganizationCreate action) {
    LOG.debug("OrganizationCreate in " + action);
    try {

        Party exists = sqlSession.getMapper(PartyMapper.class).readbyemailaddress(action.getEmailaddress());
        if (exists == null) {
            sqlSession.getMapper(PartyMapper.class).create(action);
        }

        action.setEmployerid(action.getId());
        action.setCurrency(Currency.Code.USD.name());
        action.setLanguage(Language.EN);
        sqlSession.getMapper(PartyMapper.class).insertlogo(action.getId());
        sqlSession.getMapper(PartyMapper.class).insertaccounts(action.getId());

        RelationService.create(sqlSession, Relation.PARTY_ROLE, action.getId(),
                String.valueOf(AccessControl.ADMINISTRATOR));
        RelationService.replace(sqlSession, Relation.PARTY_VALUE, action.getId(), action.getValues());
        RelationService.create(sqlSession, Relation.ORGANIZATION_CURRENCY, action.getId(),
                Currency.Code.USD.name());
        RelationService.create(sqlSession, Relation.ORGANIZATION_LANGUAGE, action.getId(), Language.EN);

        RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Actor.name(), action.getId(),
                action.getId());
        RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Employer.name(), action.getId(),
                action.getId());
        RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Organization.name(), action.getId(),
                action.getId());
        RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Owner.name(), action.getId(),
                action.getId());
        RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Supplier.name(), action.getId(),
                action.getId());
        RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Supplier.name(), action.getId(),
                Party.CBT_LTD_PARTY); //Licensor
        RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Actor.name(), action.getId(),
                Party.NO_ACTOR);
        ArrayList<String> organizationids = RelationService.read(sqlSession,
                Relation.ORG_PARTY_ + Party.Type.Organization.name(), null, null);
        RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Organization.name(), action.getId(),
                organizationids);
        //allow partner APIS to be scheduled into  a single Parnter API. 
        RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Organization.name(),
                organizationids, action.getId());

        sqlSession.getMapper(PartyMapper.class).update(action);
        sqlSession.commit();

        final NameIdAction param = new NameIdAction();
        param.setOrganizationid(action.getId());
        action.setCurrencies(
                RelationService.read(sqlSession, Relation.ORGANIZATION_CURRENCY, action.getId(), null));
        action.setLanguages(
                RelationService.read(sqlSession, Relation.ORGANIZATION_LANGUAGE, action.getId(), null));
        action.setCurrency(Currency.Code.USD.name());
        action.setLanguage(Language.EN);
        MonitorService.update(sqlSession, Data.Origin.CONSOLE, NameId.Type.Party, action);
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    }
    LOG.debug("OrganizationCreate out " + action);
    return action;
}

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

/**
 * Updates the progress of users towards certain goals.
 * Executed periodically by the RazorServer scheduler. 
 *///from   w  w w .  ja  v  a  2 s. c  om
public static final void progress() {
    LOG.debug("PartyService progress");
    SqlSession sqlSession = RazorServer.openSession();
    try {
        sqlSession.getMapper(PartyMapper.class).progressdelete();
        sqlSession.getMapper(PartyMapper.class).progressactivitymax();
        sqlSession.getMapper(PartyMapper.class).progressage();
        sqlSession.getMapper(PartyMapper.class).progressagemax();
        sqlSession.getMapper(PartyMapper.class).progressconfirm();
        sqlSession.getMapper(PartyMapper.class).progresscreator();
        sqlSession.getMapper(PartyMapper.class).progresscreatormax();
        //         sqlSession.getMapper(PartyMapper.class).progressvalue();
        //         sqlSession.getMapper(PartyMapper.class).progressvaluemax();
        sqlSession.commit();
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
    }
}

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

/**
 * Executes the specified action on the action.service() service.
 *
 * @param action the action to be executed.
 * @return the response.//from   www.ja  v  a2 s  .  com
 * @throws SerializationException the serialization exception
 */
public HasResponse execute(HasService action) throws SerializationException {

    HasResponse response = null;
    LOG.debug("\n\nRazorServer execute " + action.getClass().getName() + "\naction " + action);
    String classname = action.service().classname();

    try {
        Class<?> c = Class.forName(classname); // say AccountService
        Method[] allMethods = c.getDeclaredMethods(); // can be static
        for (Method m : allMethods) {
            String mname = m.getName();
            if (mname.equals("execute")) {
                Type[] pType = m.getGenericParameterTypes();
                if (pType[1].toString().equals("class " + action.getClass().getName())) {
                    SqlSession sqlSession = openSession();
                    try {
                        m.setAccessible(true);
                        Object t = getService(action.service());
                        response = (HasResponse) m.invoke(t, sqlSession, action);
                        sqlSession.commit();
                    } catch (IllegalAccessException x) {
                        LOG.error("IllegalAccessException " + action.getClass().getName() + "\n"
                                + x.getMessage());
                    } catch (InvocationTargetException x) {
                        LOG.error("InvocationTargetException exception " + action.getClass().getName() + "\n"
                                + x.getMessage());
                    } catch (Throwable x) {
                        sqlSession.rollback();
                        MonitorService.log(x);
                    } finally {
                        sqlSession.close();
                    }
                }
            }
        }
    } catch (ClassNotFoundException x) {
        MonitorService.log(x);
        LOG.error("ClassNotFoundException " + action.getClass().getName() + "\n" + x.getMessage());
    }
    return response;
}

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

License:Open Source License

/**
 * Refreshes the special offers, which is invoked periodically by the RazorServer scheduler.
 * Deletes the existing special list, creates new special list, calculates new special prices.
 *//*from w  ww .j  a  v  a2  s  . c  o  m*/
public static final void specialrefresh() {
    Date timestamp = new Date();
    SqlSession sqlSession = RazorServer.openSession();
    try {
        sqlSession.getMapper(SpecialMapper.class).deleteall();
        ArrayList<Yield> maximumgapfillers = sqlSession.getMapper(YieldMapper.class).maximumgapfillers();
        for (Yield yield : maximumgapfillers) {
            sqlSession.getMapper(SpecialMapper.class).refresh(yield);
        }
        ArrayList<Special> specials = sqlSession.getMapper(SpecialMapper.class).readall();
        if (specials == null || specials.isEmpty()) {
            return;
        }
        Reservation reservation = new Reservation();
        for (Special special : specials) {

            reservation.setOrganizationid(special.getSupplierid());
            reservation.setActorid(Party.NO_ACTOR);
            reservation.setFromdate(special.getStartdate());
            reservation.setTodate(special.getEnddate());
            reservation.setUnit(Unit.DAY);
            reservation.setCurrency(special.getCurrency());
            reservation.setProductid(special.getProductid());

            computePrice(sqlSession, reservation, null);
            Double price = reservation.getPrice();
            Double quote = reservation.getQuote();
            Double extra = reservation.getExtra();
            if (price == null || quote == null || price <= 0.01 || quote <= 0.01 || price <= quote
                    || special.getStartdate().after(special.getEnddate())) {
                sqlSession.getMapper(SpecialMapper.class).delete(special.getId());
            } else {
                special.setPrice(price);
                special.setQuote(quote);
                sqlSession.getMapper(SpecialMapper.class).update(special);
                createQuotedetail(sqlSession, reservation);
            }
        }
        sqlSession.commit();
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getMessage());
    } finally {
        sqlSession.close();
    }
    MonitorService.monitor("specialrefresh", timestamp);
}

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

License:Open Source License

/**
 * Handles upload file requests is in a page submitted by a HTTP POST method.
 * Form field values are extracted into a parameter list to set an associated Text instance.
 * 'File' type merely saves file and creates associated db record having code = file name.
 * Files may be rendered by reference in a browser if the browser is capable of the file type.
 * 'Image' type creates and saves thumbnail and full size jpg images and creates associated
 * text record having code = full size file name. The images may be viewed by reference in a browser.
 * 'Blob' type saves file and creates associated text instance having code = full size file name
 * and a byte array data value equal to the binary contents of the file.
 *
 * @param request the HTTP upload request.
 * @param response the HTTP response.//from ww  w .j ava2s .c om
 * @throws ServletException signals that an HTTP exception has occurred.
 * @throws IOException signals that an I/O exception has occurred.
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletRequestContext ctx = new ServletRequestContext(request);

    if (ServletFileUpload.isMultipartContent(ctx) == false) {
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "The servlet can only handle multipart requests."));
        return;
    }

    LOG.debug("UploadFileService doPost request " + request);

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    LOG.debug("\n doPost upload " + upload);

    SqlSession sqlSession = RazorServer.openSession();
    try {
        HashMap<String, String> params = new HashMap<String, String>();
        for (FileItem item : (List<FileItem>) upload.parseRequest(request)) {
            if (item.isFormField()) { // add for field value to parameter list
                String param = item.getFieldName();
                String value = item.getString();
                params.put(param, value);
            } else if (item.getSize() > 0) { // process uploaded file
                //               String fn = RazorServer.ROOT_DIRECTORY + item.getFieldName();    // input file path
                String fn = RazorConfig.getImageURL() + item.getFieldName(); // input file path
                LOG.debug("doPost fn " + fn);
                byte[] data = item.get();
                String mimeType = item.getContentType();

                String productId = item.getFieldName();
                Pattern p = Pattern.compile("\\d+");
                Matcher m = p.matcher(productId);
                while (m.find()) {
                    productId = m.group();
                    LOG.debug("Image uploaded for Product ID: " + productId);
                    break;
                }

                // TO DO - convert content type to mime..also check if uploaded type is image

                // getMagicMatch accepts Files or byte[],
                // which is nice if you want to test streams
                MagicMatch match = null;
                try {
                    match = parser.getMagicMatch(data, false);
                    LOG.debug("Mime type of image: " + match.getMimeType());
                } catch (MagicParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MagicMatchNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MagicException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (match != null) {
                    mimeType = match.getMimeType();
                }

                // image processor logic needs to know about the format of the image
                String contentType = RazorConfig.getMimeExtension(mimeType);

                if (StringUtils.isNotEmpty(contentType)) {
                    ImageService.uploadImages(sqlSession, productId, item.getFieldName(),
                            params.get(Text.FILE_NOTES), data, contentType);
                    LOG.debug("doPost commit params " + params);
                    sqlSession.commit();
                } else {
                    // unknown content/mime type...do not upload the file
                    sendResponse(response, new FormResponse(HttpServletResponse.SC_BAD_REQUEST,
                            "File type - " + contentType + " is not supported"));
                }
                //               File file = new File(fn);                            // output file name
                //               File tempf = File.createTempFile(Text.TEMP_FILE, "");
                //               item.write(tempf);
                //               file.delete();
                //               tempf.renameTo(file);
                //               int fullsizepixels = Integer.valueOf(params.get(Text.FULLSIZE_PIXELS));
                //               if (fullsizepixels <= 0) {fullsizepixels = Text.FULLSIZE_PIXELS_VALUE;}
                //               int thumbnailpixels = Integer.valueOf(params.get(Text.THUMBNAIL_PIXELS));
                //               if (thumbnailpixels <= 0) {thumbnailpixels = Text.THUMBNAIL_PIXELS_VALUE;}
                //
                //               setText(sqlSession, file, fn, params.get(Text.FILE_NAME), params.get(Text.FILE_TYPE), params.get(Text.FILE_NOTES), Language.EN, fullsizepixels, thumbnailpixels);
            }
        }
        sendResponse(response, new FormResponse(HttpServletResponse.SC_ACCEPTED, "OK"));
    } catch (Throwable x) {
        sqlSession.rollback();
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage()));
        LOG.error("doPost error " + x.getMessage());
    } finally {
        sqlSession.close();
    }
}

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

/**
 * Gets the exchange rate for the specified currency rate instance.
 * /*w w w  .j a v a 2  s  .co m*/
 * @param sqlSession the current SQL session.
 * @param action the specified currency rate instance.
 * @return the exchange rate.
 */
public static synchronized final Double getRate(SqlSession sqlSession, Currencyrate action) {
    LOG.debug("Currencyrate in " + action);
    if (action.hasId(action.getToid())) {
        return 1.0;
    }
    String key = action.key();
    if (!exchangerates.containsKey(key)) {
        Currencyrate currencyrate = sqlSession.getMapper(CurrencyrateMapper.class).readbyexample(action);
        if (currencyrate == null) {
            try {
                if (action.getId() == null || action.getToid() == null) {
                    return null;
                }
                Double rate = getWebRate(action.getId(), action.getToid());
                action.setRate(rate == null ? 0.0 : rate);
                sqlSession.getMapper(CurrencyrateMapper.class).create(action);
                sqlSession.commit();
                currencyrate = action;
            } catch (Exception x) {
                sqlSession.rollback();
                MonitorService.log(x);
            }
        }
        exchangerates.put(key, currencyrate.getRate());
        LOG.debug("New Rate " + key + " = " + exchangerates.get(key));
    }
    LOG.debug("Currencyrate out " + exchangerates.get(key));
    return exchangerates.get(key);
}

From source file:net.k3rnel.arena.server.database.DatabaseManager.java

License:Open Source License

/**
 * Creates the database.//from   w  w  w .j a va 2 s .c o  m
 * @return
 */
public void onCreate() {
    SqlSession session = DataConnection.openSession();
    try {
        System.out.println("Warning... Schema " + GameServer.getDatabaseName() + " must already be created!");
        DatabaseMapper dMapper = session.getMapper(DatabaseMapper.class);
        dMapper.create_table_users();
        dMapper.create_table_misc();
        new MiscManager(session).insert(new Misc("version", DATABASE_VERSION));
        session.commit();
    } catch (SQLException e) {
        System.out.println("Failed to create the database");
    } finally {
        session.close();
    }

}