Example usage for javax.persistence LockModeType PESSIMISTIC_WRITE

List of usage examples for javax.persistence LockModeType PESSIMISTIC_WRITE

Introduction

In this page you can find the example usage for javax.persistence LockModeType PESSIMISTIC_WRITE.

Prototype

LockModeType PESSIMISTIC_WRITE

To view the source code for javax.persistence LockModeType PESSIMISTIC_WRITE.

Click Source Link

Document

Pessimistic write lock.

Usage

From source file:com.pinterest.rocksplicator.controller.mysql.MySQLTaskQueue.java

private TaskEntity enqueueTaskImpl(final TaskBase taskBase, final Cluster cluster, final int runDelaySeconds,
        final TaskState state, final String claimedWorker) {
    TagEntity tagEntity = getEntityManager().find(TagEntity.class, new TagId(cluster),
            LockModeType.PESSIMISTIC_WRITE);
    if (tagEntity == null) {
        LOG.error("Cluster {} is not created", cluster);
        getEntityManager().getTransaction().rollback();
        return null;
    }/*from  ww  w.  j  ava 2s.  com*/
    TaskEntity entity = new TaskEntity().setName(taskBase.name).setPriority(taskBase.priority)
            .setBody(taskBase.body).setCluster(tagEntity).setLastAliveAt(new Date())
            .setClaimedWorker(claimedWorker).setState(state.intValue())
            .setRunAfter(DateUtils.addSeconds(new Date(), runDelaySeconds));
    getEntityManager().persist(entity);
    getEntityManager().flush();
    return entity;
}

From source file:com.music.dao.Dao.java

public void lock(Object entity) {
    if (entity != null) {
        getEntityManager().lock(entity, LockModeType.PESSIMISTIC_WRITE);
    }
}

From source file:org.cleverbus.core.common.dao.MessageDaoJpaImpl.java

@Override
public Boolean updateMessageForLock(final Message msg) {
    Assert.notNull(msg, "the msg must not be null");

    // acquire pessimistic lock firstly
    String jSql = "SELECT m " + "FROM " + Message.class.getName() + " m " + "WHERE m.msgId = :msgId"
            + "     AND (m.state = '" + MsgStateEnum.PARTLY_FAILED + "' " + "     OR m.state = '"
            + MsgStateEnum.POSTPONED + "')";

    TypedQuery<Message> q = em.createQuery(jSql, Message.class);
    q.setParameter("msgId", msg.getMsgId());
    // note: https://blogs.oracle.com/carolmcdonald/entry/jpa_2_0_concurrency_and
    q.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    Message dbMsg = q.getSingleResult();

    if (dbMsg != null) {
        // change message's state to PROCESSING
        msg.setState(MsgStateEnum.PROCESSING);
        Date currDate = new Date();
        msg.setStartProcessTimestamp(currDate);
        msg.setLastUpdateTimestamp(currDate);

        update(msg);/*from  w  w w. j a va2s .  c  o  m*/
    }

    return true;
}

From source file:net.groupbuy.service.impl.ProductServiceImpl.java

/**
 * /*from  ww w  .j a v  a  2s .  c om*/
 */
@SuppressWarnings("unchecked")
private void updateHits() {
    Ehcache cache = cacheManager.getEhcache(Product.HITS_CACHE_NAME);
    List<Long> ids = cache.getKeys();
    for (Long id : ids) {
        Product product = productDao.find(id);
        if (product != null) {
            productDao.lock(product, LockModeType.PESSIMISTIC_WRITE);
            Element element = cache.get(id);
            long hits = (Long) element.getObjectValue();
            long increment = hits - product.getHits();
            Calendar nowCalendar = Calendar.getInstance();
            Calendar weekHitsCalendar = DateUtils.toCalendar(product.getWeekHitsDate());
            Calendar monthHitsCalendar = DateUtils.toCalendar(product.getMonthHitsDate());
            if (nowCalendar.get(Calendar.YEAR) != weekHitsCalendar.get(Calendar.YEAR)
                    || nowCalendar.get(Calendar.WEEK_OF_YEAR) > weekHitsCalendar.get(Calendar.WEEK_OF_YEAR)) {
                product.setWeekHits(increment);
            } else {
                product.setWeekHits(product.getWeekHits() + increment);
            }
            if (nowCalendar.get(Calendar.YEAR) != monthHitsCalendar.get(Calendar.YEAR)
                    || nowCalendar.get(Calendar.MONTH) > monthHitsCalendar.get(Calendar.MONTH)) {
                product.setMonthHits(increment);
            } else {
                product.setMonthHits(product.getMonthHits() + increment);
            }
            product.setHits(hits);
            product.setWeekHitsDate(new Date());
            product.setMonthHitsDate(new Date());
            productDao.merge(product);
        }
    }
}

From source file:entity.service.EntryFacadeREST.java

public Response modifyRacetime(Integer raceid, ResultData resultData) {
    EntryPK key = new EntryPK(raceid, resultData.getRacenum());
    Entry entry = em.find(Entry.class, key, LockModeType.PESSIMISTIC_WRITE);
    if (entry.getStatus().equals("FINISHED") && entry.getRacetime() != null) {
        entry.appendRacetimeMod(resultData.getRacetimemoddesc());
        entry.setRacetime(resultData.getRacetime());
        em.merge(entry);//  w ww  .j  a v a  2  s  .com
    } else {
        JsonObject jsonMsg = JsonBuilder.getJsonMsg("Az eredmny nem a megfelel llapotban van!",
                JsonBuilder.MsgType.WARNING, null);
        return Response.status(500).entity(jsonMsg).build();
    }
    String msg = "Eredmny mdostva: " + entry.getContestant().getName() + " ("
            + entry.getKey().getRacenum() + ") - " + Utils.simpleTimeFormat.format(entry.getRacetime());
    JsonObject jsonMsg = JsonBuilder.getJsonMsg(msg, JsonBuilder.MsgType.INFO, null);
    return Response.ok(jsonMsg).build();
}

From source file:com.pinterest.rocksplicator.controller.mysql.MySQLTaskQueue.java

@Override
public Task dequeueTask(final String worker) {
    beginTransaction();/*w w w . j  ava2  s.  c  om*/
    Query query = getEntityManager().createNamedQuery("task.peekDequeue").setMaxResults(1);
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    List<TaskEntity> resultList = query.getResultList();
    if (resultList.isEmpty()) {
        LOG.info("No pending task to be dequeud");
        getEntityManager().getTransaction().rollback();
        return null;
    }
    TaskEntity claimedTask = resultList.get(0);
    claimedTask.setState(TaskState.RUNNING.intValue());
    claimedTask.setLastAliveAt(new Date());
    claimedTask.setClaimedWorker(worker);

    getEntityManager().persist(claimedTask);
    claimedTask.getCluster().setLocks(1);
    getEntityManager().persist(claimedTask.getCluster());
    getEntityManager().getTransaction().commit();
    return convertTaskEntityToTask(claimedTask);
}

From source file:com.pinterest.rocksplicator.controller.mysql.MySQLTaskQueue.java

private Cluster ackTask(final long id, final String output, TaskState ackState, boolean unlockCluster) {
    Query query = getEntityManager().createNamedQuery("task.findRunning").setParameter("id", id);
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    List<TaskEntity> resultList = query.getResultList();
    if (resultList.isEmpty()) {
        LOG.info("No matching task to ack: {}", id);
        getEntityManager().getTransaction().rollback();
        return null;
    }//  w w w .j  a v a 2 s  .c  om
    TaskEntity taskEntity = resultList.get(0);

    taskEntity.setState(ackState.intValue());
    taskEntity.setOutput(output);
    getEntityManager().persist(taskEntity);
    TagEntity cluster = taskEntity.getCluster();
    if (unlockCluster) {
        getEntityManager().lock(cluster, LockModeType.PESSIMISTIC_WRITE);
        cluster.setLocks(0);
        getEntityManager().persist(cluster);
    }
    return new Cluster(cluster.getNamespace(), cluster.getName());
}

From source file:net.groupbuy.service.impl.OrderServiceImpl.java

@Transactional(readOnly = true)
public Order build(Cart cart, Receiver receiver, PaymentMethod paymentMethod, ShippingMethod shippingMethod,
        CouponCode couponCode, boolean isInvoice, String invoiceTitle, boolean useBalance, String memo) {
    Assert.notNull(cart);//from   w ww.j a v  a2s  .c om
    Assert.notNull(cart.getMember());
    Assert.notEmpty(cart.getCartItems());

    Order order = new Order();
    order.setShippingStatus(ShippingStatus.unshipped);
    order.setFee(new BigDecimal(0));
    order.setPromotionDiscount(cart.getDiscount());
    order.setCouponDiscount(new BigDecimal(0));
    order.setOffsetAmount(new BigDecimal(0));
    order.setPoint(cart.getEffectivePoint());
    order.setMemo(memo);
    order.setMember(cart.getMember());

    if (receiver != null) {
        order.setConsignee(receiver.getConsignee());
        order.setAreaName(receiver.getAreaName());
        order.setAddress(receiver.getAddress());
        order.setZipCode(receiver.getZipCode());
        order.setPhone(receiver.getPhone());
        order.setArea(receiver.getArea());
    }

    if (!cart.getPromotions().isEmpty()) {
        StringBuffer promotionName = new StringBuffer();
        for (Promotion promotion : cart.getPromotions()) {
            if (promotion != null && promotion.getName() != null) {
                promotionName.append(" " + promotion.getName());
            }
        }
        if (promotionName.length() > 0) {
            promotionName.deleteCharAt(0);
        }
        order.setPromotion(promotionName.toString());
    }

    order.setPaymentMethod(paymentMethod);

    if (shippingMethod != null && paymentMethod != null
            && paymentMethod.getShippingMethods().contains(shippingMethod)) {
        BigDecimal freight = shippingMethod.calculateFreight(cart.getWeight());
        for (Promotion promotion : cart.getPromotions()) {
            if (promotion.getIsFreeShipping()) {
                freight = new BigDecimal(0);
                break;
            }
        }
        order.setFreight(freight);
        order.setShippingMethod(shippingMethod);
    } else {
        order.setFreight(new BigDecimal(0));
    }

    if (couponCode != null && cart.isCouponAllowed()) {
        couponCodeDao.lock(couponCode, LockModeType.PESSIMISTIC_WRITE);
        if (!couponCode.getIsUsed() && couponCode.getCoupon() != null && cart.isValid(couponCode.getCoupon())) {
            BigDecimal couponDiscount = cart.getEffectivePrice().subtract(
                    couponCode.getCoupon().calculatePrice(cart.getQuantity(), cart.getEffectivePrice()));
            couponDiscount = couponDiscount.compareTo(new BigDecimal(0)) > 0 ? couponDiscount
                    : new BigDecimal(0);
            order.setCouponDiscount(couponDiscount);
            order.setCouponCode(couponCode);
        }
    }

    List<OrderItem> orderItems = order.getOrderItems();
    for (CartItem cartItem : cart.getCartItems()) {
        if (cartItem != null && cartItem.getProduct() != null) {
            Product product = cartItem.getProduct();
            OrderItem orderItem = new OrderItem();
            orderItem.setSn(product.getSn());
            orderItem.setName(product.getName());
            orderItem.setFullName(product.getFullName());
            orderItem.setPrice(cartItem.getPrice());
            orderItem.setWeight(product.getWeight());
            orderItem.setThumbnail(product.getThumbnail());
            orderItem.setIsGift(false);
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setShippedQuantity(0);
            orderItem.setReturnQuantity(0);
            orderItem.setProduct(product);
            orderItem.setOrder(order);
            orderItems.add(orderItem);
        }
    }

    for (GiftItem giftItem : cart.getGiftItems()) {
        if (giftItem != null && giftItem.getGift() != null) {
            Product gift = giftItem.getGift();
            OrderItem orderItem = new OrderItem();
            orderItem.setSn(gift.getSn());
            orderItem.setName(gift.getName());
            orderItem.setFullName(gift.getFullName());
            orderItem.setPrice(new BigDecimal(0));
            orderItem.setWeight(gift.getWeight());
            orderItem.setThumbnail(gift.getThumbnail());
            orderItem.setIsGift(true);
            orderItem.setQuantity(giftItem.getQuantity());
            orderItem.setShippedQuantity(0);
            orderItem.setReturnQuantity(0);
            orderItem.setProduct(gift);
            orderItem.setOrder(order);
            orderItems.add(orderItem);
        }
    }

    Setting setting = SettingUtils.get();
    if (setting.getIsInvoiceEnabled() && isInvoice && StringUtils.isNotEmpty(invoiceTitle)) {
        order.setIsInvoice(true);
        order.setInvoiceTitle(invoiceTitle);
        order.setTax(order.calculateTax());
    } else {
        order.setIsInvoice(false);
        order.setTax(new BigDecimal(0));
    }

    if (useBalance) {
        Member member = cart.getMember();
        if (member.getBalance().compareTo(order.getAmount()) >= 0) {
            order.setAmountPaid(order.getAmount());
        } else {
            order.setAmountPaid(member.getBalance());
        }
    } else {
        order.setAmountPaid(new BigDecimal(0));
    }

    if (order.getAmountPayable().compareTo(new BigDecimal(0)) == 0) {
        order.setOrderStatus(OrderStatus.confirmed);
        order.setPaymentStatus(PaymentStatus.paid);
    } else if (order.getAmountPayable().compareTo(new BigDecimal(0)) > 0
            && order.getAmountPaid().compareTo(new BigDecimal(0)) > 0) {
        order.setOrderStatus(OrderStatus.confirmed);
        order.setPaymentStatus(PaymentStatus.partialPayment);
    } else {
        order.setOrderStatus(OrderStatus.unconfirmed);
        order.setPaymentStatus(PaymentStatus.unpaid);
    }

    if (paymentMethod != null && paymentMethod.getTimeout() != null
            && order.getPaymentStatus() == PaymentStatus.unpaid) {
        order.setExpire(DateUtils.addMinutes(new Date(), paymentMethod.getTimeout()));
    }

    return order;
}

From source file:gov.guilin.service.impl.OrderServiceImpl.java

@Transactional(readOnly = true)
public Order build(Cart cart, Receiver receiver, PaymentMethod paymentMethod, ShippingMethod shippingMethod,
        CouponCode couponCode, boolean isInvoice, String invoiceTitle, boolean useBalance, String memo) {
    Assert.notNull(cart);//from   www .j a  v a  2s  .c om
    Assert.notNull(cart.getMember());
    Assert.notEmpty(cart.getCartItems());

    Order order = new Order();
    order.setShippingStatus(ShippingStatus.unshipped);
    order.setFee(new BigDecimal(0));
    order.setPromotionDiscount(cart.getDiscount());
    order.setCouponDiscount(new BigDecimal(0));
    order.setOffsetAmount(new BigDecimal(0));
    order.setPoint(cart.getEffectivePoint());
    order.setMemo(memo);
    order.setMember(cart.getMember());
    Supplier supplier = cart.getCartItems().iterator().next().getProduct().getSupplier();
    Assert.notNull(supplier);
    order.setSupplier(supplier);

    if (receiver != null) {
        order.setConsignee(receiver.getConsignee());
        order.setAreaName(receiver.getAreaName());
        order.setAddress(receiver.getAddress());
        order.setZipCode(receiver.getZipCode());
        order.setPhone(receiver.getPhone());
        order.setArea(receiver.getArea());
    }

    if (!cart.getPromotions().isEmpty()) {
        StringBuffer promotionName = new StringBuffer();
        for (Promotion promotion : cart.getPromotions()) {
            if (promotion != null && promotion.getName() != null) {
                promotionName.append(" " + promotion.getName());
            }
        }
        if (promotionName.length() > 0) {
            promotionName.deleteCharAt(0);
        }
        order.setPromotion(promotionName.toString());
    }

    order.setPaymentMethod(paymentMethod);

    if (shippingMethod != null && paymentMethod != null
            && paymentMethod.getShippingMethods().contains(shippingMethod)) {
        BigDecimal freight = shippingMethod.calculateFreight(cart.getWeight());
        for (Promotion promotion : cart.getPromotions()) {
            if (promotion.getIsFreeShipping()) {
                freight = new BigDecimal(0);
                break;
            }
        }
        order.setFreight(freight);
        order.setShippingMethod(shippingMethod);
    } else {
        order.setFreight(new BigDecimal(0));
    }

    if (couponCode != null && cart.isCouponAllowed()) {
        couponCodeDao.lock(couponCode, LockModeType.PESSIMISTIC_WRITE);
        if (!couponCode.getIsUsed() && couponCode.getCoupon() != null && cart.isValid(couponCode.getCoupon())) {
            BigDecimal couponDiscount = cart.getEffectivePrice().subtract(
                    couponCode.getCoupon().calculatePrice(cart.getQuantity(), cart.getEffectivePrice()));
            couponDiscount = couponDiscount.compareTo(new BigDecimal(0)) > 0 ? couponDiscount
                    : new BigDecimal(0);
            order.setCouponDiscount(couponDiscount);
            order.setCouponCode(couponCode);
        }
    }

    List<OrderItem> orderItems = order.getOrderItems();
    for (CartItem cartItem : cart.getCartItems()) {
        if (cartItem != null && cartItem.getProduct() != null) {
            Product product = cartItem.getProduct();
            OrderItem orderItem = new OrderItem();
            orderItem.setSn(product.getSn());
            orderItem.setName(product.getName());
            orderItem.setFullName(product.getFullName());
            orderItem.setPrice(cartItem.getPrice());
            orderItem.setWeight(product.getWeight());
            orderItem.setThumbnail(product.getThumbnail());
            orderItem.setIsGift(false);
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setShippedQuantity(0);
            orderItem.setReturnQuantity(0);
            orderItem.setProduct(product);
            orderItem.setOrder(order);
            orderItems.add(orderItem);
        }
    }

    for (GiftItem giftItem : cart.getGiftItems()) {
        if (giftItem != null && giftItem.getGift() != null) {
            Product gift = giftItem.getGift();
            OrderItem orderItem = new OrderItem();
            orderItem.setSn(gift.getSn());
            orderItem.setName(gift.getName());
            orderItem.setFullName(gift.getFullName());
            orderItem.setPrice(new BigDecimal(0));
            orderItem.setWeight(gift.getWeight());
            orderItem.setThumbnail(gift.getThumbnail());
            orderItem.setIsGift(true);
            orderItem.setQuantity(giftItem.getQuantity());
            orderItem.setShippedQuantity(0);
            orderItem.setReturnQuantity(0);
            orderItem.setProduct(gift);
            orderItem.setOrder(order);
            orderItems.add(orderItem);
        }
    }

    Setting setting = SettingUtils.get();
    if (setting.getIsInvoiceEnabled() && isInvoice && StringUtils.isNotEmpty(invoiceTitle)) {
        order.setIsInvoice(true);
        order.setInvoiceTitle(invoiceTitle);
        order.setTax(order.calculateTax());
    } else {
        order.setIsInvoice(false);
        order.setTax(new BigDecimal(0));
    }

    if (useBalance) {
        Member member = cart.getMember();
        if (member.getBalance().compareTo(order.getAmount()) >= 0) {
            order.setAmountPaid(order.getAmount());
        } else {
            order.setAmountPaid(member.getBalance());
        }
    } else {
        order.setAmountPaid(new BigDecimal(0));
    }

    if (order.getAmountPayable().compareTo(new BigDecimal(0)) == 0) {
        order.setOrderStatus(OrderStatus.confirmed);
        order.setPaymentStatus(PaymentStatus.paid);
    } else if (order.getAmountPayable().compareTo(new BigDecimal(0)) > 0
            && order.getAmountPaid().compareTo(new BigDecimal(0)) > 0) {
        order.setOrderStatus(OrderStatus.confirmed);
        order.setPaymentStatus(PaymentStatus.partialPayment);
    } else {
        order.setOrderStatus(OrderStatus.unconfirmed);
        order.setPaymentStatus(PaymentStatus.unpaid);
    }

    if (paymentMethod != null && paymentMethod.getTimeout() != null
            && order.getPaymentStatus() == PaymentStatus.unpaid) {
        order.setExpire(DateUtils.addMinutes(new Date(), paymentMethod.getTimeout()));
    }

    return order;
}

From source file:com.enioka.jqm.tools.JobManagerHandler.java

/**
 * Update the {@link com.enioka.jqm.jpamodel.History} with the given progress data.
 * //  www  .  ja  v a2s. c o  m
 * @param msg
 * @throws JqmKillException
 */
private void sendProgress(Integer msg) {
    EntityManager em = Helpers.getNewEm();
    try {
        em.getTransaction().begin();
        this.ji = em.find(JobInstance.class, this.ji.getId(), LockModeType.PESSIMISTIC_WRITE);
        ji.setProgress(msg);
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}