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.AbstractProduct.java

/**
 * Gets the property detail./*w  w  w . ja  va 2s.c om*/
 *
 * @param productid the productid
 * @param pos the pos
 * @param language the language
 * @param test the test
 * @param xsl the xsl
 * @return the detail
 */
protected PropertyResponse getPropertyDetail(String productid, String pos, String language, String date,
        String toDate, String currency, Boolean test, String version, String xsl) {

    Date timestamp = new Date();
    String message = "/product/" + productid + "/propertydetail?pos=" + pos + "&language=" + language + "&xsl="
            + xsl + "&test=" + test;
    LOG.debug(message);
    // Integer countImages = 20;
    SqlSession sqlSession = RazorServer.openSession();
    PropertyResponse response = new PropertyResponse();
    Property result = null;
    try {
        // TODO: if unlimited images worked wel - remove limit from query
        result = getPropertyDetail(sqlSession, productid, pos, language, date, toDate, currency, null, test,
                version);
        response.setProperty(result);
        result.setXsl(xsl);
        sqlSession.commit();
    } catch (JAXBException e) {
        LOG.error(e.getMessage() + "\n");
    } catch (Throwable x) {
        sqlSession.rollback();
        if (x != null && x.getMessage() != null && !x.getMessage().startsWith(Error.data_unchanged.name())) {
            LOG.error(message + "\n" + x.getMessage());
        }
        result = new Property();
        result.setMessage(message + " " + x.getMessage());
        response.setErrorMessage(message + " " + x.getMessage());
        result.setXsl(xsl);
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return response;
}

From source file:net.cbtltd.rest.AbstractProduct.java

/**
 * Gets the attributes.//from  ww w  .  ja v  a  2 s. co  m
 *
 * @param productid the productid
 * @param pos the pos
 * @param test the test
 * @param xsl the xsl
 * @return the attributes 
 */
protected Attributes getAttributes(String productid, String pos, Boolean test, String version, String xsl) {

    Date timestamp = new Date();
    String message = "/product/" + productid + "/attribute" + "?pos=" + pos + "&xsl=" + xsl + "&test=" + test;
    LOG.debug(message);
    SqlSession sqlSession = RazorServer.openSession();
    Attributes result = null;
    try {
        getProperty(sqlSession, pos, productid, test, version); //gets property. 
        HashMap<String, ArrayList<String>> attributeMap = RelationService.readMap(sqlSession,
                Relation.PRODUCT_ATTRIBUTE, productid, Attribute.ACCOMMODATION_SEARCH);
        if (attributeMap == null || attributeMap.isEmpty()) {
            throw new ServiceException(Error.product_attribute, productid);
        }
        Collection<Attribute> attributes = new ArrayList<Attribute>();
        for (String key : attributeMap.keySet()) {
            ArrayList<String> values = new ArrayList<String>();
            for (String value : attributeMap.get(key)) {
                values.add(getValueName(sqlSession, value));
            }
            if (attributeMap.get(key).size() > 0) {
                attributes.add(new Attribute(getValueName(sqlSession, key), values));
            }
        }
        result = new Attributes(NameId.Type.Product.name(), productid, null, attributes, xsl);
        sqlSession.commit();
    } catch (Throwable x) {
        sqlSession.rollback();
        if (x != null && x.getMessage() != null && !x.getMessage().startsWith(Error.data_unchanged.name())) {
            LOG.error(message + "\n" + x.getMessage());
        }
        result = new Attributes(NameId.Type.Product.name(), productid, message + " " + x.getMessage(), null,
                xsl);
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractProduct.java

/**
 * Gets the images by id./*w ww  . j a va 2s . c  om*/
 *
 * @param productid the productid
 * @param pos the pos
 * @param test the test
 * @param xsl the xsl
 * @return the images by id
 */
protected Items getImagesById(String productid, String pos, Boolean test, String version, String xsl) {
    List<NameId> listNameId;
    Date timestamp = new Date();
    String message = "/product/" + productid + "/image?pos=" + pos + "&xsl=" + xsl + "&test=" + test;
    LOG.debug(message);
    SqlSession sqlSession = RazorServer.openSession();
    Items result = null;
    try {
        Property product = getProperty(sqlSession, pos, productid, test, version);
        if (product.hasSupplierid(PartyIds.PARTY_INTERHOME_ID)) {
            result = new Items(NameId.Type.Product.name(), productid, "Image", null, sqlSession
                    .getMapper(TextMapper.class).imagesbyurl(new NameId(NameId.Type.Product.name(), productid)),
                    xsl);
        } else {

            //            listNameId=sqlSession.getMapper(TextMapper.class).imagesbynameid(new NameId(NameId.Type.Product.name(), productid));
            //            if(listNameId!=null){
            //               LOG.info("listNameId from Text Mapper is "+listNameId.size());   
            //            }
            //            
            //            if(listNameId==null || (listNameId!=null && listNameId.size()==0)){
            //               listNameId=sqlSession.getMapper(ImageMapper.class).imagesbynameid(new NameId(NameId.Type.Product.name(), productid));
            //            }

            listNameId = ImageService.getProductRegularImageURLsAndDescription(sqlSession, productid);

            if (listNameId != null) {
                LOG.info("listNameId from Image Mapper is " + listNameId.size());
            }
            result = new Items(NameId.Type.Product.name(), productid, "Image", null, listNameId, xsl);
        }
        sqlSession.commit();
    } catch (Throwable x) {
        sqlSession.rollback();
        if (x != null && x.getMessage() != null && !x.getMessage().startsWith(Error.data_unchanged.name())) {
            LOG.error(message + "\n" + x.getMessage());
        }
        result = new Items(NameId.Type.Product.name(), productid, "Image", message + " " + x.getMessage(), null,
                xsl);
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractProduct.java

/**
 * Gets the price list./*  w  w w  . j a v a 2 s  .  c  o m*/
 *
 * @param productid the productid
 * @param pos the pos
 * @param test the test
 * @param xsl the xsl
 * @return the price list
 */
protected PriceList getPriceList(String productid, String pos, Boolean test, String version, String xsl) {

    final SqlSession sqlSession = RazorServer.openSession();
    PriceList propertypricelist = null;
    try {
        propertypricelist = getPriceList(productid, pos, test, version, xsl, sqlSession, false);
    } finally {
        sqlSession.commit();
        sqlSession.close();
    }

    return propertypricelist;
}

From source file:net.cbtltd.rest.AbstractProduct.java

/**
 * Creates, updates or deletes a product.
 *
 * @param action the product parameter.//from  www  .  jav a  2s . c om
 * @param pos the point of sale code.
 * @param xsl the style sheet.
 * @return the product.
 */
protected static synchronized Property setProperty(Property action, String pos, String xsl) {
    Date timestamp = new Date();
    String message = "\nPOST product?pos=" + pos + "&xsl=" + xsl + " params " + action.getId() + " "
            + action.toString();
    LOG.debug(message);
    SqlSession sqlSession = RazorServer.openSession();
    Property result = new Property();

    try {
        Party party = Constants.getParty(sqlSession, pos);
        String partyid = party.getId(); //Constants.decryptPos(pos); //TODO: only for managers

        Product product = null;
        if (action.hasAltpartyid()) {
            product = sqlSession.getMapper(ProductMapper.class).altread(action);
        } else if (action.hasId()) {
            product = sqlSession.getMapper(ProductMapper.class).read(action.getId());
        }

        if (product == null) { //new product
            product = new Product();
            product.setActorid(partyid);
            product.setAltid(action.getAltid());
            product.setAltpartyid(action.getAltpartyid());
            product.setType(Product.Type.Accommodation.name());
            product.setSupplierid(action.hasSupplierid() ? action.getSupplierid() : partyid);
            product.setUnit(Unit.DAY);
            sqlSession.getMapper(ProductMapper.class).create(product);
            RelationService.replace(sqlSession, Relation.ORGANIZATION_PRODUCT, product.getSupplierid(),
                    product.getId());
        }

        product.setAltitude(action.getAltitude());
        product.setBathroom(action.getBathroom());
        product.setChild(action.getChild());
        product.setCode(action.getCode());
        product.setCommission(action.getCommissionValue());
        product.setCurrency(action.hasCurrency() ? action.getCurrency() : Currency.Code.USD.name());
        product.setDiscount(action.getDiscount());
        product.setInfant(action.getInfant());
        product.setLanguage(action.hasLanguage() ? action.getLanguage() : Language.Code.en.name());

        //         Location location = null;
        //         if (action.hasLocationid()) {location = sqlSession.getMapper(LocationMapper.class).read(action.getLocationid());}
        //         else {location = PartnerService.getLocation(sqlSession, action.getCity(), action.getRegion(), action.getCountry(), action.getLatitude(), action.getLongitude(), action.getAltitude());}
        //         if (location == null) {throw new ServiceException(Error.location_id, product.getLocationid());}
        //
        //         product.setLocationid(location.getId());
        //         product.setLatitude(action.getLatitude());
        //         product.setLongitude(action.getLongitude());
        //         if (product.noLatLng()) {
        //            product.setLatitude(location == null ? null : location.getLatitude());
        //            product.setLongitude(location == null ? null : location.getLongitude());
        //         }      
        //         product.setName(action.hasName() ? action.getName() : location == null ? product.getId() : location.getName() + " " + product.getId());

        product.setLocationid(action.getLocationid());
        product.setLatitude(action.getLatitude());
        product.setLongitude(action.getLongitude());
        product.setName(action.getName());
        product.setOwnerid(action.hasOwnerid() ? action.getOwnerid() : partyid);
        product.setPerson(action.getPerson());
        product.setPhysicaladdress(action.getPhysicaladdress());
        product.setQuantity(action.getQuantity());
        product.setRank(0.0);
        product.setRating(action.getRating());
        product.setRoom(action.getRoom());
        product.setState(action.hasState() ? action.getState() : Product.CREATED);
        product.setToilet(action.getToilet());
        product.setWebaddress(action.getWebaddress());

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

        if (action.getAttributes() != null) {
            ArrayList<String> kvs = new ArrayList<String>();
            Collection<Attribute> attributes = action.getAttributes().attribute;
            for (Attribute attribute : attributes) {
                Collection<String> values = attribute.values.value;
                if (values != null) {
                    for (String value : values) {
                        kvs.add(value);
                    }
                }
            }
            RelationService.create(sqlSession, Relation.PRODUCT_ATTRIBUTE, product.getId(), kvs);
        }

        if (action.getImages() != null && HasUrls.LIVE) {
            ArrayList<NameId> images = new ArrayList<NameId>();
            Collection<String> urls = action.getImages().getImage();
            if (urls != null) {
                for (String url : urls) {
                    images.add(new NameId("", url));
                }
                UploadFileService.uploadImages(sqlSession, NameId.Type.Product, product.getId(), Language.EN,
                        images);
            }

        }

        if (action.getKeyvalues() != null) {
            ArrayList<String> kvs = new ArrayList<String>();
            Collection<KeyValue> keyvalues = action.getKeyvalues();
            for (KeyValue keyvalue : keyvalues) {
                kvs.add(keyvalue.getKey() + Model.DELIMITER + keyvalue.getValue());
            }
            RelationService.replace(sqlSession, Relation.PRODUCT_VALUE, action.getId(), kvs);
        }

        LOG.debug("\nPricetable " + action.getPricetable());
        if (action.getPricetable() != null) {
            Collection<Price> prices = action.getPricetable().price;
            LOG.debug("\nPrices " + prices);
            for (Price price : prices) {
                if (price.noValue() || price.getValue() <= 0.0) {
                    throw new ServiceException(Error.price_data, "Invalid Value");
                }
                //               if (price.noDuration(0.0, Time.DAY)) {throw new ServiceException(Error.price_data, "Invalid Duration");}
                price.setEntitytype(NameId.Type.Product.name());
                price.setEntityid(product.getId());
                price.setPartyid(product.getSupplierid());
                price.setName(price.noName() ? Price.RACK_RATE : price.getName());
                price.setType(NameId.Type.Reservation.name());
                LOG.debug("\nParameter " + price);

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

                price.setUnit(price.getUnit() == null ? Unit.DAY : price.getUnit());
                price.setState(Price.CREATED);
                price.setAvailable(price.getAvailable() == null ? 1 : price.getAvailable());
                price.setQuantity(price.noQuantity() ? 0.0 : price.getQuantity());
                price.setMinimum(price.getMinimum() == null ? 0.0 : price.getMinimum());
                sqlSession.getMapper(PriceMapper.class).update(price);
                LOG.debug("\nPrice " + price);
            }
        }

        if (action.getReviews() != null) {
            Collection<Review> reviews = action.getReviews().review;
            for (Review review : reviews) {
                Event<Rate> event = new Event<Rate>();
                event.setActivity(NameId.Type.Reservation.name());
                event.setActorid(partyid);
                event.setDate(review.getDate());
                event.setName(SessionService.pop(sqlSession, action.getOrganizationid(), Serial.RATE));
                event.setNotes(review.getNotes());
                event.setOrganizationid(product.getOrganizationid());
                event.setProcess(Event.Type.Rate.name());
                event.setState(review.getState() == null ? Event.CREATED : review.getState());
                event.setType(Event.NOMINAL);
                if (event.hasId()) {
                    sqlSession.getMapper(EventMapper.class).update(event);
                } else {
                    event.setName(SessionService.pop(sqlSession, event.getOrganizationid(), Serial.RATE));
                    sqlSession.getMapper(EventMapper.class).create(event);
                }

                if (review.getRatings() != null) {
                    Collection<Rating> ratings = review.getRatings();
                    for (Rating rating : ratings) {
                        Rate rate = new Rate();
                        rate.setCustomerid(partyid);
                        rate.setEventid(event.getId());
                        rate.setName(rating.getName());
                        rate.setQuantity(rating.getCount());
                        rate.setProductid(product.getId());
                        rate.setType(Rate.RATING);
                        sqlSession.getMapper(RateMapper.class).create(rate);
                    }
                }
            }
        }

        if (action.hasDescription()) {
            product.setPublicText(new Text(product.getPublicId(), product.getPublicLabel(), Text.Type.HTML,
                    new Date(), action.getDescription(), product.getLanguage()));
        }
        if (action.hasContents()) {
            product.setContentsText(new Text(product.getContentsId(), product.getContentsLabel(),
                    Text.Type.HTML, new Date(), action.getDescription(), product.getLanguage()));
        }
        if (action.hasOptions()) {
            product.setOptionsText(new Text(product.getOptionsId(), product.getOptionsLabel(), Text.Type.HTML,
                    new Date(), action.getOptions(), product.getLanguage()));
        }
        if (action.hasCheckin()) {
            product.setCheckinText(new Text(product.getCheckinId(), product.getCheckinLabel(), Text.Type.HTML,
                    new Date(), action.getCheckin(), product.getLanguage()));
        }
        if (action.hasConditions()) {
            product.setConditionsText(new Text(product.getConditionsId(), product.getConditionsLabel(),
                    Text.Type.HTML, new Date(), action.getConditions(), product.getLanguage()));
        }
        TextService.update(sqlSession, product.getTexts());

        //         RelationService.replace(sqlSession, Relation.PRODUCT_VALUE, action.getId(), action.getValues());
        RelationService.create(sqlSession, Relation.PRODUCT_ATTRIBUTE, action.getId(),
                action.getAttributemap());
        RelationService.unload(sqlSession, Downloaded.PRODUCT_DOWNLOAD, action.getId(), null);

        sqlSession.commit();
        result.setId(product.getId());
    } catch (Throwable x) {
        sqlSession.rollback();
        result.setMessage(message + " " + x.getMessage());
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractReservation.java

/**
 * Creates, updates or cancels a reservation.
 *
 * @param action the reservation parameter.
 * @param pos the POS code.//from   w ww .ja  va  2 s  . com
 * @param xsl the style sheet.
 * @return the provisional reservation.
 */
protected static synchronized Reservation setReservation(Reservation action, String pos, String xsl) {
    Date timestamp = new Date();
    String message = "POST reservation?pos=" + pos + "&xsl=" + xsl + "\nparams " + action.paramString();
    LOG.debug(message);
    SqlSession sqlSession = RazorServer.openSession();
    Reservation result = null;
    try {

        String partyid = Constants.decryptPos(pos);

        Product product = getProduct(sqlSession, pos, action.getProductid(), License.DEFAULT_WAIT);
        if (product == null) {
            throw new ServiceException(Error.product_id, action.getProductid());
        }

        if (action.notValidState()) {
            throw new ServiceException(Error.reservation_state, action.getId() + " " + action.getState());
        }

        if (action.noId()) { //new reservation
            result = action;
            result.setName(SessionService.pop(sqlSession, product.getSupplierid(), Serial.RESERVATION));
            //set booking id in the name field

            result.setAltpartyid(product.getAltpartyid());
            result.setAltid(action.getAltid());
            //            result.setName("Booking Id "+action.getAltid());
            result.setOrganizationid(product.getSupplierid());
            result.setActorid(Party.NO_ACTOR);

            //TODO:COnfirm with Chirayu
            if (action.getAgentid() != null) {
                result.setAgentid(action.getAgentid());
            } else {
                result.setAgentid(partyid);
            }

            result.setDate(new Date());
            result.setDuedate(result.getDate());
            result.setDonedate(null);
            result.setUnit(product.getUnit());
            result.setCurrency(product.getCurrency());
            result.setState(action.getState());
            sqlSession.getMapper(ReservationMapper.class).create(result);
            if (State.Cancelled.name().equalsIgnoreCase(action.getState())) {
                // incase a reservation is created and cancelled
                // immediately.
                // TODO:validate with chirayu.

                MonitorService.update(sqlSession, Data.Origin.XML_JSON, NameId.Type.Reservation, result);
                sqlSession.commit();
                return result;
            }
        } else {

            result = sqlSession.getMapper(ReservationMapper.class).read(action.getId());

        }

        if (result == null) {
            throw new ServiceException(Error.reservation_id, action.getId());
        }

        if (action.getEmailaddress() != null) {
            Party customer = getParty(sqlSession, action.getEmailaddress(), action.getFamilyname(),
                    action.getFirstname());
            RelationService.replace(sqlSession, Relation.ORG_PARTY_ + Party.Type.Customer.name(), partyid,
                    customer.getId());
            RelationService.replace(sqlSession, Relation.ORG_PARTY_ + Party.Type.Customer.name(),
                    product.getSupplierid(), customer.getId());
            result.setCustomerid(customer.getId());
            result.setEmailaddress(action.getEmailaddress());
        }

        if (action.getFromdate() != null || action.getTodate() != null) {
            if (action.noDuration(0.9, Time.DAY)) {
                throw new ServiceException(Error.date_invalid, action.getProductFromToDate());
            }
            result.setFromdate(action.getFromdate());
            result.setTodate(action.getTodate());
        }

        if (action.getArrivaltime() != null) {
            result.setArrivaltime(action.getArrivaltime());
        } else {
            result.setArrivaltime(Reservation.ARRIVALTIME);
        }

        if (action.getDeparturetime() != null) {
            result.setDeparturetime(action.getDeparturetime());
        } else {
            result.setDeparturetime(Reservation.DEPARTURETIME);
        }

        Double quote = action.getQuote();
        Double taxrate = action.getTaxrate();
        String currency = action.getCurrency();

        //if (quote != null) {result.setQuote(quote);}
        if (taxrate != null) {
            result.setTaxrate(taxrate);
        }
        if (currency != null) {
            result.setCurrency(currency);
        }

        if (action.hasNotes()) {
            result.setNotes(action.getNotes());
        }

        result.setState(action.getState());

        ReservationService.computePrice(sqlSession, result, null);
        if (quote != 0) {
            Double oldquote = action.getQuote();
            action.setQuote(quote);
            if (action.getQuotedetail() != null) {
                for (net.cbtltd.shared.Price pricedetail : action.getQuotedetail()) {
                    if (pricedetail.hasType(net.cbtltd.shared.Price.TAX_EXCLUDED)
                            || pricedetail.hasType(net.cbtltd.shared.Price.TAX_INCLUDED)
                            || pricedetail.hasType(net.cbtltd.shared.Price.TAX_ON_TAX)) {
                        pricedetail.setValue(pricedetail.getValue() * quote / oldquote);
                    }
                }
            }
        }

        //TODO: save tax allocations
        if (result.notCurrency(product.getCurrency())) {
            result.setQuote(WebService.getRate(sqlSession, result.getCurrency(), product.getCurrency())
                    * result.getQuote());
        }
        result.setCost(result.getQuote() * ReservationService.getDiscountfactor(sqlSession, result));
        result.setDeposit(ReservationService.getDeposit(sqlSession, result)); //.getOrganizationid(), action.getFromdate()));
        if (result.getDeposit() != null && result.getDeposit().isNaN()) {
            result.setDeposit(0.0);
        }

        sqlSession.getMapper(ReservationMapper.class).update(result);

        if (action.getKeyvalues() != null) {
            ArrayList<String> kvs = new ArrayList<String>();
            Collection<KeyValue> keyvalues = action.getKeyvalues();
            for (KeyValue keyvalue : keyvalues) {
                kvs.add(keyvalue.getKey() + Model.DELIMITER + keyvalue.getValue());
            }
            RelationService.replace(sqlSession, Relation.RESERVATION_VALUE, action.getId(), kvs);
        }

        result.setAlert(getAlert(sqlSession, result));
        String textid = NameId.Type.Party.name() + product.getSupplierid() + Text.Code.Contract.name();
        String terms = TextService.notes(sqlSession, textid, Language.EN);
        result.setTerms(terms);

        result.setCollisions(ReservationService.getCollisions(sqlSession, result));
        if (result.hasCollisions()) {
            throw new ServiceException(Error.product_not_available, result.getProductFromToDate());
        }

        //System.out.println("\nALTID " + product.hasAltpartyid() + " " + product.getAltpartyid());

        if (product.hasAltpartyid()) {
            try {
                PartnerService.createReservation(sqlSession, result);
            } catch (ServiceException e) {
                //   LOG.error(e.getMessage(),e);
                LOG.error(e.getMessage());
            }
        }

        MonitorService.update(sqlSession, Data.Origin.XML_JSON, NameId.Type.Reservation, result);
        sqlSession.commit();

        if (result.isActive() && product.noAltpartyid()) {
            EmailService.provisionalReservation(sqlSession, result);
        }

    } catch (Throwable x) {
        x.printStackTrace();
        sqlSession.rollback();
        result = new Reservation();
        result.setMessage(message + "\nsetReservation failed " + x.getMessage());
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);

    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractReservation.java

protected static synchronized ReservationResponse createInquiredReservation(String pos, String productId,
        String fromDate, String toDate, String notes, Integer adult, Integer child, // reservation fields
        String emailAddress, String familyName, String firstName, String phoneNumber) { // customer fields
    SqlSession sqlSession = RazorServer.openSession();
    ReservationResponse response = new ReservationResponse();
    Party channelPartnerParty = null;/*from  ww  w  .  j av a 2s.  c  om*/
    Party propertyManager = null;
    Product product = null;
    Reservation reservation = null;
    PropertyManagerInfo propertyManagerInfo = null;
    PaymentTransaction paymentTransaction = null;
    boolean successful = false;
    try {
        channelPartnerParty = JSONService.getParty(sqlSession, pos);
        if (channelPartnerParty == null) {
            throw new ServiceException(Error.reservation_agentid);
        }
        product = sqlSession.getMapper(ProductMapper.class).read(productId);
        propertyManager = sqlSession.getMapper(PartyMapper.class).read(product.getSupplierid());
        propertyManagerInfo = sqlSession.getMapper(PropertyManagerInfoMapper.class)
                .readbypmid(Integer.valueOf(product.getSupplierid()));
        Party customer = processCustomer(sqlSession, emailAddress, familyName, firstName, product, phoneNumber,
                channelPartnerParty, product.getSupplierid(), channelPartnerParty, null, null, null, null, null,
                null);
        reservation = PaymentHelper.prepareReservation(channelPartnerParty, customer, product,
                propertyManagerInfo, fromDate, toDate, notes, productId, adult, child);
        reservation.setState(Reservation.State.Cancelled.name());
        sqlSession.getMapper(ReservationMapper.class).create(reservation);
        if (product.getInquireState().equals(Product.SEND_EMAIL)) {
            EmailService.inquiredReservationForManager(sqlSession, reservation);
            EmailService.inquiredReservationForRenter(sqlSession, reservation);
            successful = true;
        } else if (product.getInquireState().equals(Product.USE_API)) {
            PartnerService.inquireReservation(sqlSession, reservation);
            successful = true;
        } else {
            throw new ServiceException(Error.inquiry_state);
        }

        Map<String, String> result = new HashMap<String, String>();
        result.put(GatewayHandler.STATE, GatewayHandler.INQUIRED);
        Integer agentId = channelPartnerParty == null ? null : Integer.valueOf(channelPartnerParty.getId());
        paymentTransaction = PaymentHelper.prepareInquiryTransaction(reservation, product, agentId);
        reservation.setState(Reservation.State.Inquiry.name());
        sqlSession.getMapper(ReservationMapper.class).update(reservation);
        sqlSession.commit();
        response.setPropertyAddress(ReservationService.getPropertyLocation(sqlSession, product));
        response.setPropertyName(product.getName());
        response.setPropertyManagerEmail(propertyManager.getEmailaddress());
        response.setReservationInfo(new ReservationInfo(reservation));
    } catch (RuntimeException x) {
        x.printStackTrace();
        response.setErrorMessage(x.getMessage());
        LOG.error(x.getMessage());
    } catch (Exception x) {
        if (!successful) {
            Integer id = channelPartnerParty == null ? null : Integer.valueOf(channelPartnerParty.getId());
            Map<String, String> result = new HashMap<String, String>();
            result.put(GatewayHandler.STATE, GatewayHandler.FAILED);
            paymentTransaction = PaymentHelper.prepareInquiryTransaction(reservation, product, id);
        }
    } finally {
        if (paymentTransaction != null) {
            sqlSession.getMapper(PaymentTransactionMapper.class).create(paymentTransaction);
            sqlSession.commit();
        }
        sqlSession.close();
    }
    return response;
}

From source file:net.cbtltd.rest.AbstractReservation.java

protected static synchronized ReservationResponse createReservationPayment(String pos, String productId,
        String fromDate, String toDate, String emailAddress, String familyName, String firstName, String notes,
        String cardNumber, String cardExpiryMonth, String cardExpiryYear, String amount, String currency,
        String phoneNumber, Integer cardType, Integer cvc, Integer adult, Integer child, String address,
        String country, String state, String city, String zip, Integer birthDay, Integer birthMonth,
        Integer birthYear, String altId) {
    resetValue(address);/* w ww. j  ava  2  s  . c  o  m*/
    resetValue(country);
    resetValue(city);
    resetValue(state);
    SqlSession sqlSession = RazorServer.openSession();
    ReservationResponse response = new ReservationResponse();
    PaymentTransaction paymentTransaction = null;
    PendingTransaction pendingTransaction = null;
    Reservation reservation = new Reservation();
    boolean reservationFinished = false;
    GatewayHandler handler = null;
    try {
        if (StringUtils.isEmpty(pos) || StringUtils.isEmpty(productId) || StringUtils.isEmpty(fromDate)
                || StringUtils.isEmpty(toDate) || StringUtils.isEmpty(emailAddress)
                || StringUtils.isEmpty(familyName) | StringUtils.isEmpty(firstName)
                || StringUtils.isEmpty(phoneNumber) || cardType == null || child == null
                || StringUtils.isEmpty(currency) || birthDay == null || birthMonth == null || birthYear == null
                || amount == null || zip == null) {
            throw new ServiceException(Error.parameter_absent);
        }

        if (adult == null || adult < 1) {
            throw new ServiceException(Error.missing_adult_parameter);
        }
        if (StringUtils.isEmpty(cardNumber) || StringUtils.isEmpty(cardExpiryMonth)
                || StringUtils.isEmpty(cardExpiryYear) || cvc == null) {
            //            throw new ServiceException(Error.credit_card_error);
        }
        //yyyy-mm-dd
        if (fromDate.compareToIgnoreCase(toDate) > 0) {
            throw new ServiceException(Error.date_range);
        }

        Date birthDate = null;
        if (birthYear != null && birthMonth != null && birthDay != null) {
            birthDate = stringToDate(birthYear, birthMonth - 1, birthDay);
        }

        boolean encodable = false;
        if (state != null) {
            encodable = CommonUtils
                    .iso88591Encodable(new String[] { firstName, familyName, address, country, city, state });
        } else {
            encodable = CommonUtils
                    .iso88591Encodable(new String[] { firstName, familyName, address, country, city });
        }

        if (!encodable) {
            throw new ServiceException(Error.parameter_invalid);
        }

        //   String[] ignoreIds = {"179805", "90640", "179769","179791","179792","179793","179795","179801","179802", "179896", "179797",
        //      "179799", "179800", "179803", "179804"};  

        // Credit card initialization
        CreditCard creditCard = new CreditCard();
        creditCard.setFirstName(firstName);
        creditCard.setLastName(familyName);
        creditCard.setMonth(cardExpiryMonth);
        cardNumber = cardNumber.trim();
        creditCard.setNumber(cardNumber);
        creditCard.setType(CreditCardType.get(cardType));
        creditCard.setYear(cardExpiryYear);
        creditCard.setSecurityCode(cvc.toString());

        // Initialization of necessary instances
        Product product = sqlSession.getMapper(ProductMapper.class).read(productId);
        if (!product.getState().equals(Product.CREATED)) {
            throw new ServiceException(Error.product_inactive);
        }
        int supplierId = Integer.valueOf(product.getSupplierid());
        PropertyManagerInfo propertyManagerInfo = sqlSession.getMapper(PropertyManagerInfoMapper.class)
                .readbypmid(supplierId);
        if (propertyManagerInfo == null) {
            throw new ServiceException(Error.database_cannot_find_property_manager, String.valueOf(supplierId));
        }

        response.setPropertyName(product.getName());
        response.setPropertyAddress(ReservationService.getPropertyLocation(sqlSession, product));

        // Initialization end
        Party channelPartnerParty = JSONService.getParty(sqlSession, pos);
        //      Party channelPartnerParty = JSONService.getPartyWithPMCheck(sqlSession, pos, product.getSupplierid()); // this method checks agent's status and throws an exception in case of agent is inactive
        if (channelPartnerParty == null) {
            throw new ServiceException(Error.reservation_agentid);
        }
        //         Party customer = JSONService.getCustomer(sqlSession, emailAddress, familyName, firstName, product.getSupplierid(), phoneNumber, channelPartnerParty);
        Party customer = processCustomer(sqlSession, emailAddress, familyName, firstName, product, phoneNumber,
                channelPartnerParty, product.getSupplierid(), channelPartnerParty, address, country, city, zip,
                state, birthDate);
        Party propertyManager = sqlSession.getMapper(PartyMapper.class)
                .read(propertyManagerInfo.getPropertyManagerId().toString());
        response.setPropertyManagerName(propertyManager.getName());
        response.setPropertyManagerEmail(propertyManager.getEmailaddress());
        response.setPropertyManagerPhone(propertyManager.getDayphone());

        // Reservation processing
        reservation = PaymentHelper.prepareReservation(channelPartnerParty, customer, product,
                propertyManagerInfo, fromDate, toDate, notes, productId, adult, child);

        // END INITIALIZATION BLOCK

        Double amountToCheck = PaymentHelper.roundAmountTwoDecimals(amount);
        Double amountDifference = PaymentHelper.amountDifference(sqlSession, reservation, amountToCheck,
                currency);
        if (amountDifference > 1 && (BPThreadLocal.get() == null || !BPThreadLocal.get())) {
            throw new ServiceException(Error.price_not_match,
                    "passed: " + amountToCheck + currency + ", difference: " + amountDifference);
        }

        if (propertyManagerInfo.getFundsHolder() == ManagerToGateway.bookingnet_HOLDER) {
            //            amount = PaymentHelper.convertToDefaultMbpCurrency(sqlSession, reservation, propertyManagerInfo, PaymentHelper.roundAmountTwoDecimals(amount), currency).toString();
            currency = PaymentHelper.DEFAULT_bookingnet_CURRENCY;
        } else {
            //            amount = PaymentService.convertCurrency(sqlSession, currency, reservation.getCurrency(), PaymentHelper.roundAmountTwoDecimals(amount)).toString();
            currency = product.getCurrency();
        }
        if (reservation.getAltpartyid() == null
                || !Arrays.asList(livePricingIds).contains(reservation.getAltpartyid())) {
            ReservationService.computePrice(sqlSession, reservation, currency);
            Double deposit = ReservationService.getDeposit(reservation, propertyManagerInfo);
            reservation.setDeposit(deposit);
            reservation.setCost(
                    reservation.getQuote() * ReservationService.getDiscountfactor(sqlSession, reservation));
        } else {
            LOG.error("PartnerService.readPrice started");
            PartnerService.readPrice(sqlSession, reservation, product.getAltid(), currency);

            if ((reservation.getPrice() == null || reservation.getPrice() <= 0)
                    || (reservation.getQuote() == null || reservation.getQuote() <= 0)) {
                throw new ServiceException(Error.price_missing, "Price was resturned null or 0");
            }

            ReservationService.computeLivePrice(sqlSession, reservation, null, currency);

            LOG.error("PartnerService.readPrice finished");

        }

        if (reservation.getPrice() == 0.0) {
            throw new ServiceException(Error.price_data);
        }

        // END PRICE BLOCK

        boolean available = sqlSession.getMapper(ReservationMapper.class).available(reservation);
        if (!available) {
            throw new ServiceException(Error.product_not_available);
        }
        reservation.setState(Reservation.State.Provisional.name());

        reservation
                .setName(SessionService.pop(sqlSession, reservation.getOrganizationid(), Serial.RESERVATION));

        reservation.setCollisions(ReservationService.getCollisions(sqlSession, reservation));
        if (reservation.hasCollisions()) {
            throw new ServiceException(Error.product_not_available, reservation.getProductFromToDate());
        }

        if (StringUtils.isNotEmpty(altId)) {
            reservation.setAltid(altId);
        }
        sqlSession.getMapper(ReservationMapper.class).create(reservation);

        ReservationService.createEvent(sqlSession, paymentTransaction, reservation, creditCard);

        // END AVAILABILITY BLOCK

        ManagerToGateway managerToGateway = null;
        PaymentGatewayProvider paymentGatewayProvider = null;
        Map<String, String> resultMap = null;
        int paymentGatewayId = -1;
        // Processing charge type
        String chargeType = PaymentHelper.getChargeType(propertyManagerInfo, reservation);
        Double firstPayment = PaymentHelper.getFirstPayment(reservation, propertyManagerInfo);
        Double secondPayment = PaymentHelper.getSecondPayment(reservation, propertyManagerInfo);

        response.setDownPayment(firstPayment);

        Double amountToCharge = PaymentHelper.isFullPaymentMethod(chargeType) ? firstPayment + secondPayment
                : firstPayment;
        if (PaymentHelper.isApiPaymentMethod(chargeType)) {
            if (StringUtils.isEmpty(reservation.getState())) {
                reservation.setState(Reservation.State.Confirmed.name());
            }
            resultMap = PartnerService.createReservationAndPayment(sqlSession, reservation, creditCard);
            if (resultMap != null && PaymentHelper.isDepositPaymentMethod(chargeType)
                    && resultMap.get(GatewayHandler.STATE).equals(GatewayHandler.ACCEPTED)) {
                pendingTransaction = PaymentHelper.preparePendingTransaction(sqlSession, pos, familyName,
                        firstName, cardNumber, phoneNumber, reservation, product,
                        propertyManagerInfo.getPropertyManagerId(), propertyManagerInfo, secondPayment, null,
                        resultMap, null);
                sqlSession.getMapper(PendingTransactionMapper.class).create(pendingTransaction);
                sqlSession.commit();
            }
        } else if (chargeType.equalsIgnoreCase(PaymentHelper.FULL_PAYMENT_METHOD)
                || chargeType.equalsIgnoreCase(PaymentHelper.DEPOSIT_PAYMENT_METHOD)) {
            /* 
             * The following line is bad because this is the final payment. Once it was charged, we have no information about renter's CC
             * and in case of cancellation (deposit and full payment) or second payment (deposit payment) we have no CC information about renter.
             * Thus, there is always needed to create the payment profile in payment gateway and store returned information to database.
             * 
             * resultMap = handler.createPaymentByCreditCard(product.getCurrency(), firstPayment);
             */

            // Payment gateway initialization
            managerToGateway = sqlSession.getMapper(ManagerToGatewayMapper.class).readBySupplierId(supplierId);
            paymentGatewayId = managerToGateway.getPaymentGatewayId();
            paymentGatewayProvider = PaymentGatewayHolder.getPaymentGateway(paymentGatewayId);
            handler = PaymentHelper.initializeHandler(propertyManagerInfo, managerToGateway, creditCard);

            if (!paymentGatewayProvider.getName().equals(PaymentGatewayHolder.DIBS)) {
                resultMap = PaymentHelper.processPayment(sqlSession, paymentGatewayProvider, amountToCharge,
                        reservation, handler, currency, creditCard, paymentGatewayId);
            }

            // Pending transaction processing
            if (resultMap != null && chargeType.equalsIgnoreCase(PaymentHelper.DEPOSIT_PAYMENT_METHOD)
                    && resultMap.get(GatewayHandler.STATE).equals(GatewayHandler.ACCEPTED)) {
                pendingTransaction = PaymentHelper.preparePendingTransaction(sqlSession, pos, familyName,
                        firstName, cardNumber, phoneNumber, reservation, product, supplierId,
                        propertyManagerInfo, secondPayment, paymentGatewayProvider, resultMap,
                        paymentGatewayId);

                sqlSession.getMapper(PendingTransactionMapper.class).create(pendingTransaction);
            }
        } else if (chargeType.equalsIgnoreCase(PaymentHelper.MAIL_PAYMENT_METHOD)) {
            setReservationState(reservation, chargeType);
            response.setReservationInfo(new ReservationInfo(reservation));
            sqlSession.getMapper(ReservationMapper.class).update(reservation);
            sqlSession.commit();
        } else {
            throw new ServiceException(Error.payment_method_unsupported);
        }

        if (propertyManagerInfo.getPropertyManagerId() != Integer.valueOf(RazorConfig.getNextpaxNovasolId())) {
            paymentTransaction = PaymentHelper.preparePaymentTransaction(sqlSession, reservation,
                    propertyManagerInfo, firstPayment, managerToGateway, cardNumber,
                    Integer.valueOf(channelPartnerParty.getId()), product, resultMap, false);
        }

        if (chargeType.equalsIgnoreCase(PaymentHelper.MAIL_PAYMENT_METHOD)) {
            sendEmails(sqlSession, paymentTransaction, chargeType);
            return response;
        }

        // END PAYMENT BLOCK

        if (resultMap != null && resultMap.get(GatewayHandler.STATE).equals(GatewayHandler.ACCEPTED)
                || (paymentGatewayProvider != null
                        && paymentGatewayProvider.getName().equals(PaymentGatewayHolder.DIBS))) {
            if (product.hasAltpartyid() && !PaymentHelper.isApiPaymentMethod(chargeType)) {
                if (reservation.getState() == null) {
                    reservation.setState(Reservation.State.Confirmed.name());
                }
                try {
                    PartnerService.createReservation(sqlSession, reservation);
                } catch (ServiceException e) {
                    LOG.error(e.getMessage());
                }
            }

            MonitorService.update(sqlSession, Data.Origin.JQUERY, NameId.Type.Reservation, reservation);

            if (paymentGatewayProvider != null
                    && paymentGatewayProvider.getName().equals(PaymentGatewayHolder.DIBS)) {
                if (paymentGatewayId != -1 && paymentGatewayProvider != null
                        && (!reservation.getState().equals(Reservation.State.Cancelled.name()))) {
                    resultMap = PaymentHelper.processPayment(sqlSession, paymentGatewayProvider, amountToCharge,
                            reservation, handler, currency, creditCard, paymentGatewayId);
                    paymentTransaction = PaymentHelper.preparePaymentTransaction(sqlSession, reservation,
                            propertyManagerInfo, firstPayment, managerToGateway, cardNumber,
                            Integer.valueOf(channelPartnerParty.getId()), product, resultMap, false);
                    if (resultMap == null
                            || !resultMap.get(GatewayHandler.STATE).equals(GatewayHandler.ACCEPTED)) {
                        LOG.error("An error occurred while processing your payment");
                        PartnerService.cancelReservation(sqlSession, reservation);
                        reservation.setState(Reservation.State.Cancelled.name());
                        if (resultMap != null) {
                            response.setErrorMessage(resultMap.get(GatewayHandler.ERROR_MSG));
                        } else {
                            response.setErrorMessage("Something went wrong with payment processing");
                        }
                    } else {
                        PartnerService.confirmReservation(sqlSession, reservation);
                    }
                }
            }

            // END PARTNER RESERVATION BLOCK

            // refund transaction made in case of PMS rejected the reservation
            if (paymentTransaction != null && reservation.getState() != null
                    && reservation.getState().equals(Reservation.State.Cancelled.name())) {
                List<PaymentTransaction> paymentTransactions = new ArrayList<PaymentTransaction>();
                paymentTransactions.add(paymentTransaction);
                refundAmount(sqlSession, supplierId, paymentTransactions, firstPayment);
                cancelPendingTransactions(sqlSession, reservation);
                reservationFinished = true;
                throw new ServiceException(Error.pms_reservation_reject);
            } else if (paymentTransaction == null && paymentGatewayProvider != null
                    && paymentGatewayProvider.getName().equals(PaymentGatewayHolder.DIBS)) {
                cancelPendingTransactions(sqlSession, reservation);
                reservationFinished = true;
                throw new ServiceException(Error.pms_reservation_reject);
            } else {
                setReservationState(reservation, chargeType);
                reservationFinished = true;
            }

            ReservationService.createEvent(sqlSession, paymentTransaction, reservation, creditCard);
            sqlSession.getMapper(ReservationMapper.class).update(reservation);
            // Pending transaction end
            sendEmails(sqlSession, paymentTransaction, chargeType);

            // END VERIFICATION BLOCK
        } else {
            reservation.setState(Reservation.State.Cancelled.name());
            sqlSession.getMapper(ReservationMapper.class).update(reservation);
            if (resultMap != null && resultMap.get(GatewayHandler.ERROR_MSG) != null) {
                LOG.error("An error occurred while processing your payment");
                response.setErrorMessage(resultMap.get(GatewayHandler.ERROR_MSG));
            } else {
                LOG.error("An error occurred while processing your payment");
                response.setErrorMessage("Something went wrong with payment processing");
            }
        }
        sqlSession.commit();
    } catch (ServiceException ex) {
        response.setErrorMessage(ex.getDetailedMessage());
        sqlSession.getMapper(ReservationMapper.class).update(reservation);
        LOG.error(ex.getDetailedMessage());

        if (reservationFinished) {
            sqlSession.commit();
        } else {
            sqlSession.rollback();
        }
    } catch (Throwable x) {
        x.printStackTrace();
        response.setErrorMessage(x.getMessage());
        sqlSession.getMapper(ReservationMapper.class).update(reservation);
        LOG.error(x.getMessage());

        if (reservationFinished) {
            sqlSession.commit();
        } else {
            sqlSession.rollback();
        }
    } finally {
        sqlSession.close();
    }

    try {
        sqlSession = RazorServer.openSession();
        if (paymentTransaction != null) {
            sqlSession.getMapper(PaymentTransactionMapper.class).create(paymentTransaction);
            sqlSession.commit();
        }
    } catch (Throwable x) {
        response.setErrorMessage(x.getMessage());
        LOG.error(x.getMessage());
        sqlSession.rollback();
    } finally {
        sqlSession.close();
    }

    try {
        sqlSession = RazorServer.openSession();
        roundReservationDoubleValues(reservation);
        sendAdminEmail(sqlSession, paymentTransaction);
    } catch (Exception x) {
        if (!response.isError()) {
            response.setErrorMessage("Unable to round the values for reservation. :" + x.getMessage());
        }
        LOG.error("Unable to round the values for reservation.");
        sqlSession.rollback();
    } finally {
        sqlSession.close();
    }

    response.setReservationInfo(new ReservationInfo(reservation));
    return response;
}

From source file:net.cbtltd.rest.AbstractReservation.java

private static Party processCustomer(SqlSession sqlSession, String emailAddress, String familyName,
        String firstName, Product product, String phoneNumber, Party channelPartnerParty, String organizationId,
        Party agent, String address, String country, String city, String zip, String state, Date birthDate) {
    Party customer = sqlSession.getMapper(PartyMapper.class).readbyemailaddress(emailAddress);
    if (customer == null) {
        customer = JSONService.getDetailedCustomer(sqlSession, emailAddress, familyName, firstName,
                product.getSupplierid(), phoneNumber, channelPartnerParty, address, country, city, zip, state,
                birthDate);/* w  ww .j a  v a  2 s.com*/
    } else {
        customer.setDayphone(phoneNumber);
        customer.setEmailaddress(emailAddress);
        customer.setName(familyName, firstName);
        customer.setState(Party.CREATED);
        customer.setBirthdate(birthDate);
        customer.setCreatorid(agent == null ? organizationId : agent.getId());
        customer.setCountry(country);
        customer.setCity(city);
        customer.setRegion(state == null || state.equals("0") ? "" : state);
        customer.setCurrency(agent == null ? Currency.Code.USD.name() : agent.getCurrency());
        customer.setLanguage(agent == null ? Language.EN : agent.getLanguage());
        customer.setLocalAddress(address);
        customer.setPostalcode(zip);
        customer.setUsertype(Constants.RENTER_USER_TYPE);
        sqlSession.getMapper(PartyMapper.class).update(customer);
    }
    sqlSession.commit();
    return customer;
}

From source file:net.cbtltd.rest.AbstractReservation.java

protected static synchronized CancelReservationResponse cancelBooking(String reservationPos) throws Exception {
    SqlSession sqlSession = RazorServer.openSession();
    CancelReservationResponse cancelReservationResponse = new CancelReservationResponse();
    try {/*  ww  w  .  ja v  a2  s  . c o m*/
        if (reservationPos == null) {
            throw new ServiceException(Error.parameter_absent, "reservationId");
        }

        String reservationId = Model.decrypt(reservationPos);
        Reservation reservation = sqlSession.getMapper(ReservationMapper.class).read(reservationId);
        if (reservation == null) {
            throw new ServiceException(Error.database_cannot_find, "reservation");
        }
        if (reservation.getState().equals(Reservation.State.Cancelled.name())) {
            throw new ServiceException(Error.reservation_cancelled);
        }

        int propertyManagerId = Integer.valueOf(reservation.getOrganizationid());
        PropertyManagerInfo propertyManagerInfo = sqlSession.getMapper(PropertyManagerInfoMapper.class)
                .readbypmid(propertyManagerId);
        if (propertyManagerInfo == null) {
            throw new ServiceException(Error.database_cannot_find, "property manager info");
        }

        double cancellationAmount = ReservationService.calculateCancellationAmount(sqlSession, reservation,
                propertyManagerInfo);
        boolean refund = cancellationAmount < 0;

        ManagerToGateway managerToGateway = sqlSession.getMapper(ManagerToGatewayMapper.class)
                .readBySupplierId(propertyManagerId);
        Map<String, String> transactionResult = null;

        // initialize property manager and agent
        Party propertyManager = sqlSession.getMapper(PartyMapper.class)
                .read(propertyManagerInfo.getPropertyManagerId().toString());
        Party renter = sqlSession.getMapper(PartyMapper.class).read(reservation.getCustomerid());
        Product product = sqlSession.getMapper(ProductMapper.class).read(reservation.getProductid());
        String propertyAddress = ReservationService.getPropertyLocation(sqlSession, product);

        double absAmount = Math.abs(cancellationAmount);
        reservation.setState(Reservation.State.Cancelled.name());
        if (propertyManagerInfo.getFundsHolder() == ManagerToGateway.bookingnet_HOLDER) {
            cancelPendingTransaction(sqlSession, reservation);
            if (managerToGateway == null) {
                if (refund) {
                    EmailService.cancelWithoutGatewayToPMRefund(propertyManager, renter, reservation, absAmount,
                            propertyAddress);
                } else {
                    EmailService.cancelWithoutGatewayToPMCharge(propertyManager, renter, reservation, absAmount,
                            propertyAddress);
                }
                insertCancellationPaymentTransaction(sqlSession, cancellationAmount, managerToGateway,
                        reservation, propertyManagerInfo, null, null, null, null, null, "");
                SharedService.onReservationStateChange(sqlSession, reservation, product);
            } else {
                List<PaymentTransaction> paymentTransactions = sqlSession
                        .getMapper(PaymentTransactionMapper.class)
                        .readByReservationId(Integer.valueOf(reservationId));
                CreditCard creditCard = new CreditCard();
                creditCard.setNumber(String.valueOf(paymentTransactions.get(0).getPartialIin()));
                GatewayHandler gatewayHandler = PaymentHelper.initializeHandler(propertyManagerInfo,
                        managerToGateway, creditCard);
                if (absAmount >= 1) {
                    if (refund) {
                        transactionResult = gatewayHandler.createRefund(paymentTransactions, absAmount);
                        EmailService.cancelWithGatewayToPMRefund(propertyManager, renter, reservation,
                                absAmount, propertyAddress);
                        EmailService.cancelWithGatewayToRenterRefund(propertyManager, renter, reservation,
                                absAmount, propertyAddress);
                    } else {
                        transactionResult = gatewayHandler.createPaymentByProfile(sqlSession,
                                reservation.getCurrency(), absAmount, Integer.valueOf(reservationId));
                        EmailService.cancelWithGatewayToPMCharge(propertyManager, renter, reservation,
                                absAmount, propertyAddress);
                        EmailService.cancelWithGatewayToRenterCharge(propertyManager, renter, reservation,
                                absAmount, propertyAddress);
                    }
                    if (transactionResult != null) {
                        insertCancellationPaymentTransaction(sqlSession, cancellationAmount, managerToGateway,
                                reservation, propertyManagerInfo,
                                transactionResult.get(GatewayHandler.TRANSACTION_ID),
                                transactionResult.get(GatewayHandler.ERROR_MSG),
                                Integer.valueOf(creditCard.getNumber()), null,
                                transactionResult.get(GatewayHandler.STATE),
                                paymentTransactions.get(0).getCurrency());
                    }
                }
                // set cancelled flag to true
                for (PaymentTransaction paymentTransaction : paymentTransactions) {
                    if (paymentTransaction.getStatus().equals(GatewayHandler.ACCEPTED)) {
                        updateTransactionToCancelled(sqlSession, paymentTransaction);
                    }
                }
                if (paymentTransactions.get(0) != null) {
                    ReservationService.createEvent(sqlSession, paymentTransactions.get(0), reservation,
                            creditCard);
                }
            }
        } else {
            EmailService.cancelPMWithoutFundsHolder(sqlSession, propertyManager, renter, reservation,
                    propertyAddress);
            EmailService.cancelRenterWithoutFundsHolder(propertyManager, renter, reservation, propertyAddress);
            SharedService.onReservationStateChange(sqlSession, reservation, product);
        }

        if (transactionResult != null && transactionResult.get(GatewayHandler.ERROR_MSG) != null) {
            cancelReservationResponse.setErrorMessage(transactionResult.get(GatewayHandler.ERROR_MSG));
        }
        sqlSession.getMapper(ReservationMapper.class).update(reservation);
        sqlSession.commit();
        if (product.hasAltpartyid()) {
            PartnerService.cancelReservation(sqlSession, reservation);
        }
    } catch (Exception e) {
        cancelReservationResponse.setErrorMessage(e.getMessage());
        LOG.error(e.getMessage());
        sqlSession.rollback();
    } finally {
        sqlSession.close();
    }
    return cancelReservationResponse;
}