Example usage for org.springframework.transaction.support TransactionCallbackWithoutResult TransactionCallbackWithoutResult

List of usage examples for org.springframework.transaction.support TransactionCallbackWithoutResult TransactionCallbackWithoutResult

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionCallbackWithoutResult TransactionCallbackWithoutResult.

Prototype

TransactionCallbackWithoutResult

Source Link

Usage

From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java

/**
 * Test dirty properties in UOW. See bug #1018.
 *//*  w ww. j  a  v  a2  s.  c o m*/
@Test
public void testDirtyPropertiesInUOW() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();

    EnhancedDetachedCriteria companyCriteria = EnhancedDetachedCriteria.forClass(Company.class);
    final Company comp = hbc.findFirstByCriteria(companyCriteria, EMergeMode.MERGE_KEEP, Company.class);
    assertTrue("Dirty properties are not initialized", hbc.getDirtyProperties(comp) != null);
    assertTrue("Dirty properties are not empty", hbc.getDirtyProperties(comp).isEmpty());
    comp.setName("Updated");
    assertTrue("Company name is not dirty", hbc.getDirtyProperties(comp).containsKey(Nameable.NAME));

    hbc.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            EnhancedDetachedCriteria departmentCriteria = EnhancedDetachedCriteria.forClass(Department.class);
            Department dep = hbc.findFirstByCriteria(departmentCriteria, EMergeMode.MERGE_KEEP,
                    Department.class);
            assertFalse("Company property is already initialized",
                    Hibernate.isInitialized(dep.straightGetProperty(Department.COMPANY)));
            // Should be initialized now
            Company uowComp = dep.getCompany();
            assertTrue("Dirty properties are not initialized", hbc.getDirtyProperties(uowComp) != null);
            assertTrue("Dirty properties are not empty", hbc.getDirtyProperties(uowComp).isEmpty());
            assertFalse("Company is not fresh from DB", comp.getName().equals(uowComp.getName()));
            uowComp.setNameRaw("UpdatedUow");
            assertTrue("Company name is not dirty",
                    hbc.getDirtyProperties(uowComp).containsKey(Nameable.NAME_RAW));
        }
    });
    assertEquals("Company name has not been correctly committed", "UpdatedUow", comp.getNameRaw());
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java

@Override
public void insert(final Ligplaats ligplaats) throws DAOException {
    try {//from ww  w .  j a  va  2s .com
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                jdbcTemplate.update(new PreparedStatementCreator() {
                    @Override
                    public PreparedStatement createPreparedStatement(Connection connection)
                            throws SQLException {
                        PreparedStatement ps = connection
                                .prepareStatement("insert into bag_ligplaats (" + "bag_ligplaats_id,"
                                        + "aanduiding_record_inactief," + "aanduiding_record_correctie,"
                                        + "officieel," + "ligplaats_status," + "ligplaats_geometrie,"
                                        + "begindatum_tijdvak_geldigheid," + "einddatum_tijdvak_geldigheid,"
                                        + "in_onderzoek," + "bron_documentdatum," + "bron_documentnummer,"
                                        + "bag_nummeraanduiding_id" + ") values (?,?,?,?,?,?,?,?,?,?,?,?)");
                        ps.setLong(1, ligplaats.getIdentificatie());
                        ps.setInt(2, ligplaats.getAanduidingRecordInactief().ordinal());
                        ps.setLong(3, ligplaats.getAanduidingRecordCorrectie());
                        ps.setInt(4, ligplaats.getOfficieel().ordinal());
                        ps.setInt(5, ligplaats.getLigplaatsStatus().ordinal());
                        ps.setString(6, ligplaats.getLigplaatsGeometrie());
                        ps.setTimestamp(7, new Timestamp(ligplaats.getBegindatumTijdvakGeldigheid().getTime()));
                        if (ligplaats.getEinddatumTijdvakGeldigheid() == null)
                            ps.setNull(8, Types.TIMESTAMP);
                        else
                            ps.setTimestamp(8,
                                    new Timestamp(ligplaats.getEinddatumTijdvakGeldigheid().getTime()));
                        ps.setInt(9, ligplaats.getInOnderzoek().ordinal());
                        ps.setDate(10, new Date(ligplaats.getDocumentdatum().getTime()));
                        ps.setString(11, ligplaats.getDocumentnummer());
                        ps.setLong(12, ligplaats.getHoofdAdres());
                        return ps;
                    }
                });
                insertNevenadressen(TypeAdresseerbaarObject.LIGPLAATS, ligplaats);
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException("Error inserting ligplaats: " + ligplaats.getIdentificatie(), e);
    }
}

From source file:org.opennms.ng.services.collectd.Collectd.java

/**
 * {@inheritDoc}/*from   w  w w.ja  v a 2s  . c om*/
 * <p/>
 * This method is invoked by the JMS topic session when a new event is
 * available for processing. Currently only text based messages are
 * processed by this callback. Each message is examined for its Universal
 * Event Identifier and the appropriate action is taking based on each
 * UEI.
 */
@Override
public void onEvent(final Event event) {

    Logging.withPrefix(getName(), new Runnable() {

        @Override
        public void run() {
            m_transTemplate.execute(new TransactionCallbackWithoutResult() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    onEventInTransaction(event);
                }
            });
        }
    });
}

From source file:org.jspresso.hrsample.backend.JspressoModelTest.java

/**
 * Test Collection null elements. See bug #643
 *//*  ww w  .j  a  va  2  s  .  com*/
@Test(expected = MandatoryPropertyException.class)
public void testNullElementAllowed() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();
    EnhancedDetachedCriteria crit = EnhancedDetachedCriteria.forClass(Employee.class);
    Employee e = hbc.findFirstByCriteria(crit, EMergeMode.MERGE_CLEAN_EAGER, Employee.class);
    e.addToEvents(null);
    hbc.registerForUpdate(e);
    hbc.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            hbc.performPendingOperations();
        }
    });
}

From source file:org.jspresso.hrsample.backend.JspressoModelTest.java

/**
 * Persistent collection substitution on save. See bug #1114
 *//*  w w w .j av  a2s.  c o m*/
@Test
public void testPersistentCollectionSubstitution() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();
    Company comp = hbc.getEntityFactory().createEntityInstance(Company.class);
    comp.setName("testC");

    Department dept = hbc.getEntityFactory().createEntityInstance(Department.class);
    dept.setName("testD");
    dept.setOuId("TE-001");

    comp.addToDepartments(dept);

    hbc.registerForUpdate(comp);
    hbc.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            hbc.performPendingOperations();
        }
    });

    assertTrue("Persistent entity collection is not instance of PersistentCollection",
            comp.straightGetProperty(Company.DEPARTMENTS) instanceof PersistentCollection);
    assertTrue("Entity is transient after save", comp.isPersistent());
}

From source file:net.solarnetwork.node.settings.ca.CASettingsService.java

private void importSettingsCSV(Reader in, final ImportCallback callback) throws IOException {
    final ICsvBeanReader reader = new CsvBeanReader(in, CsvPreference.STANDARD_PREFERENCE);
    final CellProcessor[] processors = new CellProcessor[] { null, new ConvertNullTo(""), null,
            new CellProcessor() {

                @Override//w  w  w.j  ava2 s .c o m
                public Object execute(Object arg, CsvContext ctx) {
                    Set<net.solarnetwork.node.Setting.SettingFlag> set = null;
                    if (arg != null) {
                        int mask = Integer.parseInt(arg.toString());
                        set = net.solarnetwork.node.Setting.SettingFlag.setForMask(mask);
                    }
                    return set;
                }
            }, new org.supercsv.cellprocessor.ParseDate(SETTING_MODIFIED_DATE_FORMAT) };
    reader.getHeader(true);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            Setting s;
            try {
                while ((s = reader.read(Setting.class, CSV_HEADERS, processors)) != null) {
                    if (!callback.shouldImportSetting(s)) {
                        continue;
                    }
                    if (s.getValue() == null) {
                        settingDao.deleteSetting(s.getKey(), s.getType());
                    } else {
                        settingDao.storeSetting(s);
                    }
                }
            } catch (IOException e) {
                log.error("Unable to import settings: {}", e.getMessage());
                status.setRollbackOnly();
            } finally {
                try {
                    reader.close();
                } catch (IOException e) {
                    // ingore
                }
            }
        }
    });
}

From source file:com.thoughtworks.go.server.dao.PipelineSqlMapDaoIntegrationTest.java

private void saveRev(final Material material, final Modification modification) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override/* w  w  w .j a  v  a 2 s.c o m*/
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            materialRepository.saveMaterialRevision(new MaterialRevision(material, modification));
        }
    });
}

From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java

@Override
public void insertMessage(final EbMSMessage message, final EbMSMessageStatus status) throws DAOException {
    try {/*  ww w. ja  v  a 2s  .co m*/
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                try {
                    Date timestamp = new Date();
                    KeyHolder keyHolder = new GeneratedKeyHolder();
                    jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp,
                            message.getMessageHeader().getCPAId(),
                            message.getMessageHeader().getConversationId(),
                            message.getMessageOrder() == null ? null
                                    : message.getMessageOrder().getSequenceNumber().getValue().longValue(),
                            message.getMessageHeader().getMessageData().getMessageId(),
                            message.getMessageHeader().getMessageData().getRefToMessageId(),
                            message.getMessageHeader().getFrom().getRole(),
                            message.getMessageHeader().getTo().getRole(),
                            message.getMessageHeader().getService().getType(),
                            message.getMessageHeader().getService().getValue(),
                            message.getMessageHeader().getAction(), message.getOriginal(),
                            XMLMessageBuilder.getInstance(SignatureType.class)
                                    .handle(new ObjectFactory().createSignature(message.getSignature())),
                            XMLMessageBuilder.getInstance(MessageHeader.class)
                                    .handle(message.getMessageHeader()),
                            XMLMessageBuilder.getInstance(SyncReply.class).handle(message.getSyncReply()),
                            XMLMessageBuilder.getInstance(MessageOrder.class).handle(message.getMessageOrder()),
                            XMLMessageBuilder.getInstance(AckRequested.class).handle(message.getAckRequested()),
                            XMLMessageBuilder.getInstance(Manifest.class).handle(message.getManifest()),
                            status), keyHolder);

                    for (DataSource attachment : message.getAttachments()) {
                        simpleJdbcTemplate.update("insert into ebms_attachment (" + "ebms_message_id," + "name,"
                                + "content_type," + "content" + ") values (?,?,?,?)",
                                keyHolder.getKey().longValue(),
                                attachment.getName() == null ? Constants.DEFAULT_FILENAME
                                        : attachment.getName(),
                                attachment.getContentType().split(";")[0].trim(),
                                IOUtils.toByteArray(attachment.getInputStream()));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

        });
    } catch (RuntimeException e) {
        throw new DAOException(e);
    }
}

From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java

/**
 * Test uninitialized reference properties merge on commit. See bug #1023.
 *///from  ww w .  j  a  v a 2 s .  co  m
@Test
public void testUnititializedPropertiesMerge() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();

    EnhancedDetachedCriteria departmentCriteria = EnhancedDetachedCriteria.forClass(Department.class);
    List<Department> departments = hbc.findByCriteria(departmentCriteria, EMergeMode.MERGE_KEEP,
            Department.class);
    final Department department = departments.get(0);
    final Company existingCompany = (Company) department.straightGetProperty(Department.COMPANY);
    assertFalse("Company property is already initialized", Hibernate.isInitialized(existingCompany));

    Serializable newCompanyId = hbc.getTransactionTemplate().execute(new TransactionCallback<Serializable>() {

        @Override
        public Serializable doInTransaction(TransactionStatus status) {
            Department departmentClone = hbc.cloneInUnitOfWork(department);
            Company newCompany = hbc.getEntityFactory().createEntityInstance(Company.class);
            newCompany.setName("NewCompany");
            departmentClone.setCompany(newCompany);
            return newCompany.getId();
        }
    });
    assertEquals("New company reference is not correctly merged", newCompanyId,
            department.getCompany().getId());
    assertEquals("New company name is not correctly merged", "NewCompany", department.getCompany().getName());

    hbc.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            List<IEntity> clonedEntities = hbc
                    .cloneInUnitOfWork(Arrays.asList((IEntity) existingCompany, department));
            Company existingCompanyClone = (Company) clonedEntities.get(0);
            assertFalse("Company clone is already initialized", Hibernate.isInitialized(existingCompanyClone));
            Department departmentClone = (Department) clonedEntities.get(1);
            departmentClone.setCompany(existingCompanyClone);
        }
    });
    assertEquals("New company reference is not correctly merged", existingCompany.getId(),
            department.getCompany().getId());

    final Department otherDepartment = departments.get(1);
    Department deptFromUow = hbc.getTransactionTemplate().execute(new TransactionCallback<Department>() {

        @Override
        public Department doInTransaction(TransactionStatus status) {
            Department d = hbc.findById(otherDepartment.getId(), null, Department.class);
            return d;
        }
    });
    assertFalse("Department Company property from UOW is initialized",
            Hibernate.isInitialized(deptFromUow.straightGetProperty(Department.COMPANY)));
    hbc.merge(deptFromUow, EMergeMode.MERGE_EAGER);
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java

@Override
public void insert(final Standplaats standplaats) throws DAOException {
    try {/*from  w w  w  . j  a  v a  2  s.c  o  m*/
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                jdbcTemplate.update(new PreparedStatementCreator() {
                    @Override
                    public PreparedStatement createPreparedStatement(Connection connection)
                            throws SQLException {
                        PreparedStatement ps = connection
                                .prepareStatement("insert into bag_standplaats (" + "bag_standplaats_id,"
                                        + "aanduiding_record_inactief," + "aanduiding_record_correctie,"
                                        + "officieel," + "standplaats_status," + "standplaats_geometrie,"
                                        + "begindatum_tijdvak_geldigheid," + "einddatum_tijdvak_geldigheid,"
                                        + "in_onderzoek," + "bron_documentdatum," + "bron_documentnummer,"
                                        + "bag_nummeraanduiding_id" + ") values (?,?,?,?,?,?,?,?,?,?,?,?)");
                        ps.setLong(1, standplaats.getIdentificatie());
                        ps.setInt(2, standplaats.getAanduidingRecordInactief().ordinal());
                        ps.setLong(3, standplaats.getAanduidingRecordCorrectie());
                        ps.setInt(4, standplaats.getOfficieel().ordinal());
                        ps.setInt(5, standplaats.getStandplaatsStatus().ordinal());
                        ps.setString(6, standplaats.getStandplaatsGeometrie());
                        ps.setTimestamp(7,
                                new Timestamp(standplaats.getBegindatumTijdvakGeldigheid().getTime()));
                        if (standplaats.getEinddatumTijdvakGeldigheid() == null)
                            ps.setNull(8, Types.TIMESTAMP);
                        else
                            ps.setTimestamp(8,
                                    new Timestamp(standplaats.getEinddatumTijdvakGeldigheid().getTime()));
                        ps.setInt(9, standplaats.getInOnderzoek().ordinal());
                        ps.setDate(10, new Date(standplaats.getDocumentdatum().getTime()));
                        ps.setString(11, standplaats.getDocumentnummer());
                        ps.setLong(12, standplaats.getHoofdAdres());
                        return ps;
                    }
                });
                insertNevenadressen(TypeAdresseerbaarObject.STANDPLAATS, standplaats);
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException("Error inserting standplaats: " + standplaats.getIdentificatie(), e);
    }
}