Example usage for javax.ejb TransactionAttributeType REQUIRED

List of usage examples for javax.ejb TransactionAttributeType REQUIRED

Introduction

In this page you can find the example usage for javax.ejb TransactionAttributeType REQUIRED.

Prototype

TransactionAttributeType REQUIRED

To view the source code for javax.ejb TransactionAttributeType REQUIRED.

Click Source Link

Document

If a client invokes the enterprise bean's method while the client is associated with a transaction context, the container invokes the enterprise bean's method in the client's transaction context.

Usage

From source file:com.flexive.ejb.beans.ScriptingEngineBean.java

/**
 * {@inheritDoc}//from   w  w  w.j a va 2s . c om
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void removeTypeScriptMappingForEvent(long scriptId, long typeId, FxScriptEvent event)
        throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptManagement);
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    boolean success = false;
    try {
        // Obtain a database connection
        con = Database.getDbConnection();
        //                                                               1                2
        sql = "DELETE FROM " + TBL_SCRIPT_MAPPING_TYPES + " WHERE SCRIPT=? AND TYPEDEF=? AND STYPE=?";
        ps = con.prepareStatement(sql);
        ps.setLong(1, scriptId);
        ps.setLong(2, typeId);
        ps.setLong(3, event.getId());
        ps.executeUpdate();
        success = true;
    } catch (SQLException exc) {
        throw new FxRemoveException(LOG, exc, "ex.scripting.mapping.type.remove.failed", scriptId, typeId,
                exc.getMessage());
    } finally {
        Database.closeObjects(ScriptingEngineBean.class, con, ps);
        if (!success)
            EJBUtils.rollback(ctx);
        else
            StructureLoader.reloadScripting(FxContext.get().getDivisionId());
    }
}

From source file:org.nightlabs.jfire.accounting.AccountingManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@RolesAllowed("org.nightlabs.jfire.accounting.editAccount")
@Override/*from w w  w. j a  v a2s.  c om*/
public Account storeAccount(final Account account, final boolean get, final String[] fetchGroups,
        final int maxFetchDepth) {
    final PersistenceManager pm = createPersistenceManager();
    try {
        if (!account.getOrganisationID().equals(getOrganisationID()))
            throw new IllegalArgumentException(
                    "Given Account was created for a different organisation, can not store to this datastore!");

        final Account result = NLJDOHelper.storeJDO(pm, account, get, fetchGroups, maxFetchDepth);
        return result;
    } finally {
        pm.close();
    }
}

From source file:com.flexive.ejb.beans.ContentEngineBean.java

/**
 * {@inheritDoc}/*w  w  w  .  j  a  v a  2  s .com*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public FxContentSecurityInfo getContentSecurityInfo(FxPK pk) throws FxApplicationException {
    FxSharedUtils.checkParameterNull(pk, "pk");
    Connection con = null;
    try {
        ContentStorage storage = StorageManager.getContentStorage(pk.getStorageMode());
        con = Database.getDbConnection();
        return storage.getContentSecurityInfo(con, pk, null);
    } catch (FxNotFoundException e) {
        throw new FxLoadException(e);
    } catch (SQLException e) {
        throw new FxLoadException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(ContentEngineBean.class, con, null);
    }
}

From source file:org.rhq.enterprise.server.content.ContentSourceManagerBean.java

@RequiredPermission(Permission.MANAGE_REPOSITORIES)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@TransactionTimeout(90 * 60)/*from  w  ww . j  a  v  a2 s  .c  o  m*/
public PackageBits downloadPackageBits(Subject subject, PackageVersionContentSource pvcs) {
    PackageVersionContentSourcePK pk = pvcs.getPackageVersionContentSourcePK();
    int contentSourceId = pk.getContentSource().getId();
    int packageVersionId = pk.getPackageVersion().getId();
    String packageVersionLocation = pvcs.getLocation();

    switch (pk.getContentSource().getDownloadMode()) {
    case NEVER: {
        return null; // no-op, our content source was told to never download package bits
    }

    case DATABASE: {
        log.debug("Downloading package bits to DB for package located at [" + packageVersionLocation
                + "] on content source [" + contentSourceId + "]");
        break;
    }

    case FILESYSTEM: {
        log.debug("Downloading package bits to filesystem for package located at [" + packageVersionLocation
                + "] on content source [" + contentSourceId + "]");
        break;
    }

    default: {
        throw new IllegalStateException(" Unknown download mode - this is a bug, please report it: " + pvcs);
    }
    }

    InputStream bitsStream = null;
    PackageBits packageBits = null;

    try {
        ContentServerPluginContainer pc = ContentManagerHelper.getPluginContainer();
        bitsStream = pc.getAdapterManager().loadPackageBits(contentSourceId, packageVersionLocation);

        Connection conn = null;
        PreparedStatement ps = null;
        PreparedStatement ps2 = null;
        try {
            packageBits = createPackageBits(pk.getContentSource().getDownloadMode() == DownloadMode.DATABASE);

            PackageVersion pv = entityManager.find(PackageVersion.class, packageVersionId);
            pv.setPackageBits(packageBits); // associate the entities
            entityManager.flush(); // may not be necessary

            if (pk.getContentSource().getDownloadMode() == DownloadMode.DATABASE) {
                conn = dataSource.getConnection();
                // The blob has been initialized to EMPTY_BLOB already by createPackageBits...
                // we need to lock the row which will be updated so we are using FOR UPDATE
                ps = conn.prepareStatement(
                        "SELECT BITS FROM " + PackageBits.TABLE_NAME + " WHERE ID = ? FOR UPDATE");
                ps.setInt(1, packageBits.getId());
                ResultSet rs = ps.executeQuery();
                try {
                    while (rs.next()) {
                        //We can not create a blob directly because BlobImpl from Hibernate is not acceptable
                        //for oracle and Connection.createBlob is not working on postgres.
                        //This blob will be not empty because we saved there a bytes from String("a").
                        Blob blb = rs.getBlob(1);

                        StreamUtil.copy(bitsStream, blb.setBinaryStream(1), true);
                        ps2 = conn.prepareStatement(
                                "UPDATE " + PackageBits.TABLE_NAME + " SET bits = ? where id = ?");
                        ps2.setBlob(1, blb);
                        ps2.setInt(2, packageBits.getId());
                        if (ps2.execute()) {
                            throw new Exception("Did not download the package bits to the DB for ");
                        }
                        ps2.close();
                    }
                } finally {
                    rs.close();
                }
                ps.close();
                conn.close();

            } else {
                // store content to local file system
                File outputFile = getPackageBitsLocalFileAndCreateParentDir(pv.getId(), pv.getFileName());
                log.info("OutPutFile is located at: " + outputFile);
                boolean download = false;

                if (outputFile.exists()) {
                    // hmmm... it already exists, maybe we already have it?
                    // if the MD5's match, just ignore this download request and continue on
                    // If they are different we re-download
                    String expectedMD5 = (pv.getMD5() != null) ? pv.getMD5() : "<unspecified MD5>";
                    String actualMD5 = MessageDigestGenerator.getDigestString(outputFile);
                    if (!expectedMD5.trim().toLowerCase().equals(actualMD5.toLowerCase())) {
                        log.error("Already have package bits for [" + pv + "] located at [" + outputFile
                                + "] but the MD5 hashcodes do not match. Expected MD5=[" + expectedMD5
                                + "], Actual MD5=[" + actualMD5 + "] - redownloading package");
                        download = true;
                    } else {
                        log.info("Asked to download package bits but we already have it at [" + outputFile
                                + "] with matching MD5 of [" + actualMD5 + "]");
                        download = false;
                    }
                } else {
                    download = true;
                }
                if (download) {
                    StreamUtil.copy(bitsStream, new FileOutputStream(outputFile), true);
                    bitsStream = null;
                }

            }
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Exception e) {
                    log.warn("Failed to close prepared statement for package bits [" + packageVersionLocation
                            + "] on content source [" + contentSourceId + "]");
                }
            }

            if (ps2 != null) {
                try {
                    ps2.close();
                } catch (Exception e) {
                    log.warn("Failed to close prepared statement for package bits [" + packageVersionLocation
                            + "] on content source [" + contentSourceId + "]");
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    log.warn("Failed to close connection for package bits [" + packageVersionLocation
                            + "] on content source [" + contentSourceId + "]");
                }
            }
        }
    } catch (Throwable t) {
        // put the cause in here using ThrowableUtil because it'll dump SQL nextException messages too
        throw new RuntimeException("Did not download the package bits for [" + pvcs + "]. Cause: "
                + ThrowableUtil.getAllMessages(t), t);
    } finally {
        if (bitsStream != null) {
            try {
                bitsStream.close();
            } catch (Exception e) {
                log.warn("Failed to close stream to package bits located at [" + packageVersionLocation
                        + "] on content source [" + contentSourceId + "]");
            }
        }
    }

    return packageBits;
}

From source file:org.nightlabs.jfire.store.StoreManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@RolesAllowed("org.nightlabs.jfire.store.editConfirmedProductType")
@Override// w w w  . j  a va  2s .  c o  m
public ProductTypeStatusHistoryItem setProductTypeStatus_closed(ProductTypeID productTypeID, boolean get,
        String[] fetchGroups, int maxFetchDepth) {
    PersistenceManager pm = createPersistenceManager();
    try {
        if (get) {
            pm.getFetchPlan().setMaxFetchDepth(maxFetchDepth);
            if (fetchGroups != null)
                pm.getFetchPlan().setGroups(fetchGroups);
        }

        pm.getExtent(ProductType.class);
        Store store = Store.getStore(pm);
        ProductType productType = (ProductType) pm.getObjectById(productTypeID);
        ProductTypeStatusHistoryItem productTypeStatusHistoryItem = store
                .setProductTypeStatus_closed(User.getUser(pm, getPrincipal()), productType);

        if (productTypeStatusHistoryItem == null || !get)
            return null;
        else
            return pm.detachCopy(productTypeStatusHistoryItem);
    } finally {
        pm.close();
    }
}

From source file:com.flexive.ejb.beans.ContentEngineBean.java

/**
 * {@inheritDoc}/* w ww  . j a v  a2  s .  c om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public FxContentVersionInfo getContentVersionInfo(FxPK pk) throws FxApplicationException {
    FxSharedUtils.checkParameterNull(pk, "pk");
    Connection con = null;
    try {
        if (pk.isNew())
            return new FxContentVersionInfo(); //return an "empty" version info
        ContentStorage storage = StorageManager.getContentStorage(pk.getStorageMode());
        con = Database.getDbConnection();
        return storage.getContentVersionInfo(con, pk.getId());
    } catch (FxNotFoundException e) {
        throw new FxLoadException(e);
    } catch (SQLException e) {
        throw new FxLoadException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(ContentEngineBean.class, con, null);
    }
}

From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public boolean setRevokeStatus(AuthenticationToken admin, String issuerdn, BigInteger serno, int reason,
        String userDataDN) throws CertificateRevokeException, AuthorizationDeniedException {
    return setRevokeStatus(admin, issuerdn, serno, new Date(), reason, userDataDN);
}

From source file:org.nightlabs.jfire.accounting.AccountingManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@RolesAllowed("org.nightlabs.jfire.accounting.editAccount")
@Override// ww  w  . j av  a  2  s  .c  om
public void setAccountSummaryAccounts(final AnchorID anchorID, final Collection<AnchorID> _summaryAccountIDs) {
    final PersistenceManager pm = createPersistenceManager();
    try {
        final Set<AnchorID> summaryAccountIDs = new HashSet<AnchorID>(_summaryAccountIDs);

        final Account account = (Account) pm.getObjectById(anchorID);
        final Set<SummaryAccount> summaryAccountsToRemove = new HashSet<SummaryAccount>();
        for (final SummaryAccount sa : account.getSummaryAccounts()) {
            if (!summaryAccountIDs.remove(JDOHelper.getObjectId(sa)))
                summaryAccountsToRemove.add(sa);
        }

        for (final SummaryAccount summaryAccount : summaryAccountsToRemove)
            account.removeSummaryAccount(summaryAccount);

        for (final Iterator<AnchorID> iter = summaryAccountIDs.iterator(); iter.hasNext();) {
            final AnchorID summaryAccountID = iter.next();
            final SummaryAccount summaryAccount = (SummaryAccount) pm.getObjectById(summaryAccountID);
            account.addSummaryAccount(summaryAccount);
        }
    } finally {
        pm.close();
    }
}

From source file:com.flexive.ejb.beans.ScriptingEngineBean.java

/**
 * {@inheritDoc}//from   ww w  . j a v a  2s.com
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public FxScriptMappingEntry updateAssignmentScriptMappingForEvent(long scriptId, long assignmentId,
        FxScriptEvent event, boolean active, boolean derivedUsage) throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptManagement);
    FxScriptMappingEntry sm;
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    boolean success = false;
    //check script existance
    CacheAdmin.getEnvironment().getScript(scriptId);
    checkAssignmentScriptConsistency(scriptId, assignmentId, event, active, derivedUsage);
    try {
        long[] derived;
        if (!derivedUsage)
            derived = new long[0];
        else {
            List<FxAssignment> ass = CacheAdmin.getEnvironment().getDerivedAssignments(assignmentId);
            derived = new long[ass.size()];
            for (int i = 0; i < ass.size(); i++)
                derived[i] = ass.get(i).getId();
        }
        sm = new FxScriptMappingEntry(event, scriptId, active, derivedUsage, assignmentId, derived);
        // Obtain a database connection
        con = Database.getDbConnection();
        //                                                                1        2                  3            4
        sql = "UPDATE " + TBL_SCRIPT_MAPPING_ASSIGN
                + " SET DERIVED_USAGE=?,ACTIVE=? WHERE ASSIGNMENT=? AND SCRIPT=? AND STYPE=?";
        ps = con.prepareStatement(sql);
        ps.setBoolean(1, sm.isDerivedUsage());
        ps.setBoolean(2, sm.isActive());
        ps.setLong(3, sm.getId());
        ps.setLong(4, sm.getScriptId());
        ps.setLong(5, sm.getScriptEvent().getId());
        ps.executeUpdate();
        success = true;
    } catch (SQLException exc) {
        if (StorageManager.isUniqueConstraintViolation(exc))
            throw new FxEntryExistsException("ex.scripting.mapping.assign.notUnique", scriptId, assignmentId);
        throw new FxUpdateException(LOG, exc, "ex.scripting.mapping.assign.update.failed", scriptId,
                assignmentId, exc.getMessage());
    } finally {
        Database.closeObjects(ScriptingEngineBean.class, con, ps);
        if (!success)
            EJBUtils.rollback(ctx);
        else
            StructureLoader.reloadScripting(FxContext.get().getDivisionId());
    }
    return sm;
}

From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public boolean setRevokeStatus(AuthenticationToken admin, String issuerdn, BigInteger serno, Date revokedDate,
        int reason, String userDataDN) throws CertificateRevokeException, AuthorizationDeniedException {
    // authorization is handled by setRevokeStatus(admin, certificate, reason, userDataDN);
    Certificate certificate = findCertificateByIssuerAndSerno(issuerdn, serno);
    if (certificate == null) {
        String msg = INTRES.getLocalizedMessage("store.errorfindcertserno", null, serno);
        log.info(msg);/*from  w w  w.  j  a v  a 2 s  . c  om*/
        throw new CertificateRevokeException(msg);
    }
    return setRevokeStatus(admin, certificate, revokedDate, reason, userDataDN);
}