Example usage for org.springframework.transaction.annotation Propagation REQUIRES_NEW

List of usage examples for org.springframework.transaction.annotation Propagation REQUIRES_NEW

Introduction

In this page you can find the example usage for org.springframework.transaction.annotation Propagation REQUIRES_NEW.

Prototype

Propagation REQUIRES_NEW

To view the source code for org.springframework.transaction.annotation Propagation REQUIRES_NEW.

Click Source Link

Document

Create a new transaction, and suspend the current transaction if one exists.

Usage

From source file:es.emergya.bbdd.dao.FlotaHome.java

@SuppressWarnings("unchecked")
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = Throwable.class)
private void removeRoles(Flota f) {
    try {//from  w  w w  .j a  v  a 2  s.c o m
        if (f != null && f.getId() != null) {
            Session currentSession = getSession();
            currentSession.clear();

            f = this.get(f.getId());

            final Set<Rol> roles = Collections.unmodifiableSet(f.getRoles());
            if (f != null && roles != null)
                for (Rol r : roles) {
                    r = (Rol) currentSession.get(Rol.class, r.getId());
                    if (r != null && r.getFlotas() != null) {
                        final Set<Flota> flotas = Collections.unmodifiableSet(r.getFlotas());
                        List<Flota> aBorrar = new LinkedList<Flota>();
                        for (Flota fl : flotas)
                            if (fl.getId().equals(f.getId()))
                                aBorrar.add(fl);
                        for (Flota fl : aBorrar)
                            r.getFlotas().remove(fl);
                        currentSession.saveOrUpdate(r);
                    }
                }
        }
    } catch (Throwable t) {
        log.error(t, t);
    }
}

From source file:es.emergya.bbdd.dao.IncidenciaHome.java

@SuppressWarnings("unchecked")
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true, rollbackFor = Throwable.class)
public List<Incidencia> getAll() {
    List<Incidencia> res = new LinkedList<Incidencia>();
    try {/* w  w  w.jav a 2s . c  o  m*/
        Session currentSession = getSession();
        currentSession.clear();
        Criteria criteria = currentSession.createCriteria(Incidencia.class)
                .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        res = (List<Incidencia>) criteria.list();
        for (Incidencia i : res) {
            if (i.getCreador() != null)
                i.getCreador().getId();
            if (i.getEstado() != null)
                i.getEstado().getId();
            if (i.getCategoria() != null)
                i.getCategoria().getId();
        }
    } catch (Throwable t) {
        log.error(t, t);
    }
    return res;
}

From source file:es.tid.fiware.rss.expenditureLimit.dao.impl.tests.DbeExpendControlDaoTest.java

@Test
public void testNewExpendLimitDataForaUser() {

    BmService bmService = new BmService();
    bmService.setNuServiceId(1);//from  ww w  .  j a  v a 2 s . c  om
    BmCurrency bmCurrency = new BmCurrency();
    bmCurrency.setNuCurrencyId(1);
    BmObCountry bmObCountry = new BmObCountry();
    bmObCountry.setId(new BmObCountryId(1, 1));
    List<DbeExpendControl> l = expLimitDao.getExpendDataForUserAppProvCurrencyObCountry("userId01", bmService,
            "app123456", bmCurrency, bmObCountry);

    Assert.assertTrue("Elements founds", l != null && l.size() == 3);
    Iterator<DbeExpendControl> it = l.iterator();
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(Propagation.REQUIRES_NEW.value());
    TransactionStatus status = transactionManager.getTransaction(def);
    while (it.hasNext()) {
        DbeExpendControl el = it.next();
        DbeExpendControl neoEc = new DbeExpendControl();
        neoEc.setId(new DbeExpendLimitPK());
        neoEc.getId().setNuCountryId(el.getId().getNuCountryId());
        neoEc.getId().setNuCurrencyId(el.getId().getNuCountryId());
        neoEc.getId().setNuObId(el.getId().getNuCountryId());
        neoEc.getId().setNuServiceId(el.getId().getNuCountryId());
        neoEc.getId().setTxAppProviderId("123456");
        neoEc.getId().setTxElType(el.getId().getTxElType());
        neoEc.getId().setTxEndUserId("userId101");
        neoEc.setDtNextPeriodStart(el.getDtNextPeriodStart());
        neoEc.setTxNotifications(el.getTxNotifications());
        neoEc.setFtExpensedAmount(el.getFtExpensedAmount());
        expLimitDao.saveDbeExpendControl(neoEc);
    }
    transactionManager.commit(status);
    l = expLimitDao.getExpendDataForUserAppProvCurrencyObCountry("userId101", bmService, "123456", bmCurrency,
            bmObCountry);

    Assert.assertTrue("Elements founds", l != null && l.size() == 3);
    it = l.iterator();
    while (it.hasNext()) {
        DbeExpendControl el = it.next();
        if (!el.getId().getTxAppProviderId().equalsIgnoreCase("123456")) {
            Assert.fail("Application provider invalid: " + el.getId().getTxAppProviderId());
        }
        if (!el.getId().getTxEndUserId().equalsIgnoreCase("userId101")) {
            Assert.fail("User invalid: " + el.getId().getTxEndUserId());
        }
    }
}

From source file:org.jresponder.engine.SendingEngineImpl.java

/**
 * Used internally to process one record inside a transaction.
 * @return true if the loop calling this method should continue,
 * or false if we're done for now./*from w w  w .  j  a  v a  2s . c om*/
 */
// must have it's own transaction
@Transactional(propagation = Propagation.REQUIRES_NEW)
public boolean engineLoopProcessOne() {

    // 1. select next batch size (maybe just 1 for now) where next
    //    consideration date is older than now

    Subscription mySubscription = mainDao.getNextSendableSubscription(SubscriptionStatus.ACTIVE);

    // if no result, then bail out, nothing to do
    if (mySubscription == null) {
        logger().debug("No more results, exiting loop");
        return false;
    }

    // the subscription we are now processing
    logger().debug("Got subscription with id: {}", mySubscription.getId());

    // look up the subscriber too
    Subscriber mySubscriber = mySubscription.getSubscriber();

    if (mySubscriber == null) {
        throw new RuntimeException("Data error, subscription with id " + mySubscription.getId()
                + " has null subscriber, should not be possible");
    }

    // Make sure we don't send to people who are asked off

    // if status is not okay...
    if (mySubscriber.getSubscriberStatus() != SubscriberStatus.OK) {
        // end this subscription
        endSubscription(mySubscription);
        // log for posterity
        logger().info(
                "Was going to send to subscriber (email={}) but status is not OK, it's '{}', not sending and ending subscription.",
                mySubscriber.getEmail(), mySubscriber.getSubscriberStatus());
        // bail out
        return true;
    }

    // 2. for this Subscription, find last message processed in
    //    the list for that group

    // first make sure we have a corresponding message group
    MessageGroup myMessageGroup = messageGroupSource
            .getMessageGroupByName(mySubscription.getMessageGroupName());

    // if no such message group, then we just get rid of the
    // subscription (lose the date so it doesn't get pulled back up);
    // also catch the case where no subscriber record, should never
    // happen, but adding scenario for robustness)
    if (myMessageGroup == null || mySubscriber == null) {

        logger().warn("Either message group or subscriber was null, "
                + "bailing out (messageGroup: {}, subscriber: {})", myMessageGroup, mySubscriber);

        /* ====================================================== */
        /* clear next send date of subscription                   */
        /* ====================================================== */
        endSubscription(mySubscription);
        return true;
    }

    // get the name of the last message
    String myLastMessageName = mySubscription.getLastMessageName();
    logger().debug("myLastMessageName: {}", myLastMessageName);

    // if last message exists
    int mySendMessageRefIndex = myMessageGroup.indexOfName(myLastMessageName);
    if (mySendMessageRefIndex >= 0) {
        // increment to next one to get the message we should send
        mySendMessageRefIndex++;
    }
    // if last message name was null, then start at zero
    if (myLastMessageName == null) {
        mySendMessageRefIndex = 0;
    }

    logger().debug("myLastMessageRefIndex: {}", mySendMessageRefIndex);

    // 3. get the next message

    List<MessageRef> myMessageRefList = myMessageGroup.getMessageRefList();

    // the MessageRef that we are to send
    MessageRef mySendMessageRef = null;
    if (mySendMessageRefIndex >= 0) {
        // make sure we haven't gone beyond the end of the messages
        if (myMessageRefList.size() > mySendMessageRefIndex) {
            mySendMessageRef = myMessageRefList.get(mySendMessageRefIndex);
        }
    }
    logger().debug("about to send mySendMessageRef: {}", mySendMessageRef);

    // no message to send (either couldn't find last message or
    // there is no next message); also check for the case where
    // the last send date is not set (should never happen, but just
    // to keep it from breaking the system we treat it like end
    // of list)
    if (mySendMessageRef == null || mySubscription.getLastSendDate() == null) {
        logger().debug("no more messages to send for this subscription");
        /* ====================================================== */
        /* clear next send date of subscription                   */
        /* ====================================================== */
        endSubscription(mySubscription);
        return true;
    }

    if (mySubscription.getLastSendDate() == null) {
        logger().warn("last_send_date was null on subscription, should never happen");
    }

    // 3a.read the time on it and recalculate, confirm that
    //    time is now past

    Long myWait = mySendMessageRef.getWaitAfterLastMessage();
    if (myWait == null) {
        /* ====================================================== */
        /* clear next send date of subscription                   */
        /* ====================================================== */
        logger().warn("'wait after last message' value was not set for this message, ending the subscription");
        endSubscription(mySubscription);
        return true;
    }

    // 3b.if not past then set next consideration date to recalced date
    //    and kick back

    // see if it's time to send yet
    long myLastSendDate = mySubscription.getLastSendDate().getTime();
    if (myLastSendDate + myWait > new Date().getTime()) {
        logger().debug("it is not yet time to send this message, putting it back for later");
        // not time to send (possibly message changed since
        // this subscription record was last edited - also first
        // subscription looks like this);
        // reset the nextSendDate and move on
        mySubscription.setNextSendDate(new Date(myLastSendDate + myWait));
        mainDao.persist(mySubscription);
        return true;
    }

    // 4. render and send message

    boolean mySendWorked = sendMessage(mySendMessageRef, myMessageGroup, mySubscriber, mySubscription,
            LogEntryType.MESSAGE_SENT);

    // if the sending was skipped...
    if (!mySendWorked) {

        // write a log entry for the skipping
        mainDao.logEntry(LogEntryType.MESSAGE_SKIPPED, mySubscriber, myMessageGroup.getName(),
                propUtil.mkprops("message_name", mySendMessageRef.getName()));

    }

    // 5. get next message in the list and recalculate date based on that,
    //    update last message name and save

    // update the last sent info
    mySubscription.setLastMessageName(mySendMessageRef.getName());
    mySubscription.setLastSendDate(new Date());

    // index of next message
    int myNextMessageRefIndex = mySendMessageRefIndex + 1;

    // 5a.if no more messages, then next consideration date is set to null

    if (myNextMessageRefIndex >= myMessageRefList.size()) {
        mySubscription.setNextSendDate(null);
    }

    // if we have a next message, then calc when it fires
    else {

        MessageRef myNextMessageRef = myMessageRefList.get(myNextMessageRefIndex);
        Long myNextWait = myNextMessageRef.getWaitAfterLastMessage();
        mySubscription.setNextSendDate(new Date(mySubscription.getLastSendDate().getTime() + myNextWait));

    }

    // save the changes to the subscription
    mainDao.persist(mySubscription);

    if (mySubscription.getNextSendDate() == null) {

        // write a log entry for the completion of the subscription
        mainDao.logEntry(LogEntryType.SUBSCRIPTION_DONE, mySubscriber, myMessageGroup.getName(),
                propUtil.mkprops("message_name", mySendMessageRef.getName()));
    }

    // as far as we know, there should be more to process...
    return true;

}

From source file:de.hska.ld.oidc.listeners.LDToSSSEventListener.java

@Transactional(propagation = Propagation.REQUIRES_NEW)
private void createDefaultDiscussion(DocumentCreationEvent event, Document newDocument,
        SSSCreateDiscRequestDto sssCreateDiscRequestDto) {
    try {/* w  ww . ja va 2 s .  co m*/
        String episodeId = null;
        try {
            Document document = documentService.findById(newDocument.getId());
            if (document != null) {
                DocumentSSSInfo documentSSSInfo = documentSSSInfoService.getDocumentSSSInfo(document);
                if (documentSSSInfo != null) {
                    episodeId = documentSSSInfo.getEpisodeId();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        SSSCreateDiscResponseDto result = sssClient.createDiscussion(String.valueOf(newDocument.getId()),
                sssCreateDiscRequestDto, event.getAccessToken(), episodeId);
        String disc = result.getDisc();
        System.out.println(disc);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:architecture.ee.web.community.announce.impl.DefaultAnnounceManager.java

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void deleteAnnounce(long announceId) {
    try {/*from   w w  w  . java2s  . c o  m*/
        Announce announce = getAnnounce(announceId);
        announceDao.delete(announce);
        // fire event;
        announceCache.remove(announce.getAnnounceId());
    } catch (AnnounceNotFoundException e) {
        log.error(e);
    }
}

From source file:es.emergya.bbdd.dao.PatrullaHome.java

@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = Throwable.class)
public void removeRecursos(Patrulla p) {
    if (p == null || p.getId() == null)
        return;/*from  w w w. j av  a  2  s. com*/

    try {
        Session currentSession = getSession();
        currentSession.clear();

        p = this.get(p.getId());
        if (p != null && p.getRecursos() != null) {
            for (Recurso r : p.getRecursos()) {
                try {
                    r.setPatrullas(null);
                    currentSession.saveOrUpdate(r);
                } catch (Throwable t) {
                    log.error("No pude eliminar el recurso de la patrulla", t);
                }
            }
        }
    } catch (Throwable t) {
        log.error(t, t);
    }
}

From source file:org.fcrepo.fixity.db.HibernateDatabaseService.java

@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void addStat(DailyStatistics stat) {
    final Session sess = sessionFactory.openSession();
    try {/*from  w w  w  .j  a  v  a2  s .  c  om*/
        sess.save(stat);
        sess.flush();
    } finally {
        sess.close();
    }
}

From source file:es.emergya.bbdd.dao.RolHome.java

@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = Throwable.class)
public void removeFlotas(Rol rol) {
    if (rol == null || rol.getId() == null)
        return;//from  w w  w .j ava2  s.  c om

    Session currentSession = getSession();
    currentSession.clear();
    Rol entity = this.get(rol.getId());

    if (entity == null)
        return;

    if (entity.getFlotas() != null)
        for (Flota f : entity.getFlotas()) {
            if (!rol.getFlotas().contains(f)) {
                log.debug("Borrando la flota " + f + " del rol " + entity);
                f.getRoles().remove(entity);
                currentSession.saveOrUpdate(f);
            } else
                log.debug("La flota " + f + " permanece en el rol " + entity);
        }
    entity.setFlotas(new HashSet<Flota>());
    currentSession.saveOrUpdate(entity);
}

From source file:es.emergya.bbdd.dao.CapaInformacionHome.java

@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true, rollbackFor = Throwable.class)
public boolean alreadyExists(String nombre) {
    Integer res = new Integer(-1);
    try {/*from w  w w .j a  va  2 s  .  co  m*/
        Session currentSession = getSession();
        currentSession.clear();
        Criteria criteria = currentSession.createCriteria(CapaInformacion.class)
                .setProjection(Projections.rowCount()).add(Restrictions.ilike("nombre", nombre));
        Integer count = (Integer) criteria.uniqueResult();
        res = count.intValue();
    } catch (Throwable t) {
        log.error(t, t);
    }
    return res != 0;
}