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.server.ReservationService.java

License:Open Source License

/**
 * Executes the BrochurePrice action to refresh its price.
 * This occurs when the currency or duration of the prospective stay is changed.
 *
 * @param sqlSession the current SQL session.
 * @param action the action to be executed.
 * @return the response./*from  www  .  j  av  a2  s .  c  o m*/
 */
public final PriceResponse execute(SqlSession sqlSession, BrochurePrice action) {
    Date timestamp = new Date();
    PriceResponse response = new PriceResponse();
    try {
        resetPrice(sqlSession, action, action.getPriceunit());
        resetCurrency(sqlSession, action, action.getTocurrency());
        response.setValue(action.getPrice());
        response.setQuote(action.getQuote());
        response.setQuotedetail(action.getQuotedetail());
        response.setCost((action.getQuote() - action.getExtra()) * getDiscountfactor(sqlSession, action));
        response.setCurrency(action.getCurrency());
        //         response.setCollisions(sqlSession.getMapper(ReservationMapper.class).collisions(action));
        //         response.addCollisions(sqlSession.getMapper(ReservationMapper.class).parentcollisions(action));
        //         response.addCollisions(sqlSession.getMapper(ReservationMapper.class).childcollisions(action));
        response.setCollisions(getCollisions(sqlSession, action));
        response.setAlerts(getAlerts(sqlSession, action));
    } catch (Throwable x) {
        sqlSession.rollback();
        MonitorService.log(x);
    }
    MonitorService.monitor("BrochurePrice", timestamp);
    return response;
}

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

License:Open Source License

/**
 * Executes the ReservationTable action to read a list of Reservation instances.
 *
 * @param sqlSession the current SQL session.
 * @param action action the action to be executed.
 * @return the response.//  w ww . ja  v  a  2s . com
 */
public final Table<Reservation> execute(SqlSession sqlSession, ReservationTable action) {
    Date timestamp = new Date();
    Table<Reservation> table = new Table<Reservation>();
    try {
        table.setDatasize(sqlSession.getMapper(ReservationMapper.class).count(action));
        table.setValue(sqlSession.getMapper(ReservationMapper.class).list(action)); //CJM ACTION!
    } catch (Throwable x) {
        sqlSession.rollback();
        MonitorService.log(x);
    }
    MonitorService.monitor("ReservationTable", timestamp);
    return table;
}

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

License:Open Source License

public final List<ReservationEntities> fetchReservation(SqlSession sqlSession, String lastFetch) {
    Date timestamp = new Date();
    List<ReservationEntities> listReservationEntities = new ArrayList<ReservationEntities>();
    try {/*from   w ww.  j ava2 s.c om*/
        List<Reservation> listReservation = sqlSession.getMapper(ReservationMapper.class)
                .readBasedOnTime(lastFetch);

        for (Reservation reservation : listReservation) {
            //get ReservationExt
            ReservationExt ext = new ReservationExt();
            ext.setReservationId(reservation.getAltid());
            List<ReservationExt> listReservationExt = sqlSession.getMapper(ReservationExtMapper.class)
                    .readReservationExt(ext);
            if (listReservationExt != null) {
                reservation.setListReservationExt(listReservationExt);
            }

            //get Product mapped to reservation.
            Product product = sqlSession.getMapper(ProductMapper.class).read(reservation.getProductid());

            reservation.setProduct(product);
            Party customer = sqlSession.getMapper(PartyMapper.class).read(reservation.getCustomerid());
            reservation.setCustomer(customer);

            ReservationEntities action = new ReservationEntities();
            action.setReservation(reservation);

            if (action.getReservation() == null) {
                throw new ServiceException(Error.reservation_id, action.getReservation().getId());
            }
            action.getReservation().setDiscountfactor(getDiscountfactor(sqlSession, action.getReservation()));
            if (action.getReservation().hasProductid()) {
                action.setProduct(
                        sqlSession.getMapper(ProductMapper.class).read(action.getReservation().getProductid()));
            }
            if (action.getProduct() != null && action.getProduct().getOwnerid() != null) {
                action.setOwner(sqlSession.getMapper(PartyMapper.class).read(action.getProduct().getOwnerid()));
            }
            if (action.getProduct() != null && action.getProduct().getSupplierid() != null) {
                action.setManager(
                        sqlSession.getMapper(PartyMapper.class).read(action.getProduct().getSupplierid()));
            }
            if (action.getReservation().hasAgentid()) {
                action.setAgent(
                        sqlSession.getMapper(PartyMapper.class).read(action.getReservation().getAgentid()));
            }
            if (action.getReservation().hasCustomerid()) {
                action.setCustomer(
                        sqlSession.getMapper(PartyMapper.class).read(action.getReservation().getCustomerid()));
            }
            if (action.getReservation().hasServiceid()) {
                action.setService(
                        sqlSession.getMapper(PartyMapper.class).read(action.getReservation().getServiceid()));
            }
            listReservationEntities.add(action);
        }
    } catch (Throwable x) {
        sqlSession.rollback();
        MonitorService.log(x);
    }
    MonitorService.monitor("ReservationEntities", timestamp);
    return listReservationEntities;
}

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 www  .  j av a2s.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.
 * /*from w  w  w.ja  v  a2 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.landora.animeinfo.anidb.AnimeCategoryParser.java

License:Open Source License

public void parseAnimeCategory(InputStream is) {
    SqlSession session = null;

    try {//w  ww.ja  v  a 2  s.  c  o  m
        session = AnimeDataManager.getInstance().openSession();
        AnimeMapper mapper = session.getMapper(AnimeMapper.class);

        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(is);

        reader.nextTag();
        reader.require(XMLStreamReader.START_ELEMENT, null, "categorylist");

        Map<Integer, AnimeCategory> categories = new HashMap<Integer, AnimeCategory>();
        Map<Integer, Integer> parentCategories = new HashMap<Integer, Integer>();

        int t1;
        while ((t1 = reader.nextTag()) != XMLStreamReader.END_ELEMENT) {
            reader.require(XMLStreamReader.START_ELEMENT, null, "category");

            int categoryId = Integer.parseInt(reader.getAttributeValue(null, "id"));
            int parentCategoryId = Integer.parseInt(reader.getAttributeValue(null, "parentid"));

            AnimeCategory category = new AnimeCategory();
            category.setId(categoryId);
            category.setHentai(Boolean.parseBoolean(reader.getAttributeValue(null, "ishentai")));

            int t2;
            while ((t2 = reader.nextTag()) != XMLStreamReader.END_ELEMENT) {
                if (reader.getLocalName().equals("name")) {
                    category.setName(XMLUtilities.nextString(reader).trim());
                } else if (reader.getLocalName().equals("description")) {
                    category.setDescription(XMLUtilities.nextString(reader).trim());
                }
            }

            if (categoryId > 0) {
                if (mapper.updateCategory(category) == 0) {
                    mapper.insertCategory(category);
                }

                categories.put(categoryId, category);

                if (parentCategoryId > 0) {
                    parentCategories.put(categoryId, parentCategoryId);
                }
            }
        }
        reader.close();

        for (Map.Entry<Integer, Integer> entry : parentCategories.entrySet()) {
            AnimeCategory c1 = categories.get(entry.getKey());
            c1.setParentCategory(categories.get(entry.getValue()));
            mapper.updateCategory(c1);
        }

        session.commit();
    } catch (Exception e) {
        session.rollback();
        log.error("Error saving anime categories.", e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:net.landora.animeinfo.anidb.AnimeTitleParser.java

License:Open Source License

public void parseAnimeTitle(InputStream is) {
    SqlSession session = null;

    try {/*from w  ww.  ja va  2 s .c o  m*/
        session = AnimeDataManager.getInstance().openSession();
        AnimeNameLookupMapper mapper = session.getMapper(AnimeNameLookupMapper.class);

        mapper.deleteAnimeNames();

        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(is);

        reader.nextTag();
        reader.require(XMLStreamReader.START_ELEMENT, null, "animetitles");

        int t1;
        while ((t1 = reader.nextTag()) != XMLStreamReader.END_ELEMENT) {
            reader.require(XMLStreamReader.START_ELEMENT, null, "anime");

            int animeId = Integer.parseInt(reader.getAttributeValue(null, "aid"));

            AnimeNameLookupSummary anime = new AnimeNameLookupSummary();
            anime.setAnimeId(animeId);

            List<AnimeNameLookup> newNames = new ArrayList<AnimeNameLookup>();

            int t2;
            while ((t2 = reader.nextTag()) != XMLStreamReader.END_ELEMENT) {
                reader.require(XMLStreamReader.START_ELEMENT, null, "title");

                AnimeNameLookup name = new AnimeNameLookup();
                for (int i = 0; i < reader.getAttributeCount(); i++) {
                    String aname = reader.getAttributeLocalName(i);
                    if (aname.equals("type")) {
                        name.setType(reader.getAttributeValue(i));
                    } else if (aname.equals("lang")) {
                        name.setLanguage(reader.getAttributeValue(i));
                    }

                }

                name.setName(XMLUtilities.nextString(reader));
                name.setAnime(anime);
                newNames.add(name);
            }

            for (AnimeNameLookup name : newNames) {
                if (name.getType().equalsIgnoreCase("main")) {
                    anime.setNameMain(name.getName());
                } else if (name.getType().equalsIgnoreCase("official")
                        && name.getLanguage().equalsIgnoreCase("en")) {
                    anime.setNameEnglish(name.getName());
                }
            }

            mapper.insertAnime(anime);
            for (AnimeNameLookup name : newNames) {
                mapper.insertAnimeName(name);
            }

        }
        reader.close();

        mapper.updateExistingAnimeMainName();
        mapper.deleteCoreAnimeNames();
        mapper.insertExistingAnimeMainName();

        session.commit();
    } catch (Exception e) {
        session.rollback();
        log.error("Error saving anime titles.", e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:net.landora.animeinfo.data.AnimeDBA.java

License:Open Source License

public static void saveAnimeWithNames(Anime anime) {
    SqlSession session = null;

    try {/*from   www. ja  va 2s .  co  m*/
        session = AnimeDataManager.getInstance().openSession();
        AnimeMapper mapper = session.getMapper(AnimeMapper.class);

        int rows = mapper.updateAnime(anime);
        if (rows == 0) {
            mapper.insertAnime(anime);
        } else {
            mapper.deleteAnimeNames(anime);
            mapper.deleteAnimeCategoryWeight(anime);
            mapper.deleteAnimeRelations(anime);
        }

        for (AnimeName name : anime.getNames()) {
            mapper.insertAnimeName(name);
        }
        for (AnimeCategoryWeight category : anime.getCategories()) {
            mapper.insertAnimeCategoryWeight(category);
        }
        for (AnimeRelation relation : anime.getRelations()) {
            mapper.insertAnimeRelation(relation);
        }

        session.commit();

        animeCache.put(anime.getAnimeId(), anime);
    } catch (Exception e) {
        session.rollback();
        log.error("Error saving anime.", e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:net.landora.animeinfo.data.AnimeDBA.java

License:Open Source License

public static Anime getAnime(int animeId) {
    Anime result = animeCache.get(animeId);
    if (result != null) {
        return result;
    }// w w w.  j a va2  s  . c o m

    SqlSession session = null;

    try {
        session = AnimeDataManager.getInstance().openSession();
        AnimeMapper mapper = session.getMapper(AnimeMapper.class);

        result = mapper.selectAnime(animeId);
        if (result != null) {
            animeCache.put(result.getAnimeId(), result);
        }

        return result;
    } catch (Exception e) {
        session.rollback();
        log.error("Error getting anime.", e);
        return null;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:net.landora.animeinfo.data.AnimeDBA.java

License:Open Source License

public static AnimeCategory getAnimeCategory(int categoryId) {
    SqlSession session = null;

    try {/*  w  w  w  . j  ava  2s.  co m*/
        session = AnimeDataManager.getInstance().openSession();
        AnimeMapper mapper = session.getMapper(AnimeMapper.class);

        return mapper.selectCategory(categoryId);
    } catch (Exception e) {
        session.rollback();
        log.error("Error getting anime.", e);
        return null;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}