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:org.nightlabs.jfire.accounting.AccountingManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@RolesAllowed("_Guest_")
@SuppressWarnings("unchecked")
@Override//  ww  w  .j a  v a2 s. c  om
public Collection<Currency> getCurrencies(final String[] fetchGroups, final int maxFetchDepth) {
    final PersistenceManager pm = createPersistenceManager();
    try {
        pm.getFetchPlan().setMaxFetchDepth(maxFetchDepth);
        if (fetchGroups != null)
            pm.getFetchPlan().setGroups(fetchGroups);

        final Query q = pm.newQuery(Currency.class);
        return pm.detachCopyAll((Collection<Currency>) q.execute());
    } finally {
        pm.close();
    }
}

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

/**
 * {@inheritDoc}/* w ww. ja v a  2s .  co  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void setGroups(long accountId, List<UserGroup> groups) throws FxApplicationException {
    if (groups != null && groups.size() > 0) {
        long groupIds[] = new long[groups.size()];
        int pos = 0;
        for (UserGroup group : groups) {
            groupIds[pos++] = group.getId();
        }
        setGroups(accountId, groupIds);
    } else {
        setGroups(accountId);
    }
}

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

/**
 * {@inheritDoc}/* w  w w .j a  v a 2 s. com*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void updateItemData(long briefcaseId, BriefcaseItemData updateData) throws FxApplicationException {
    if (updateData == null)
        return;
    Briefcase br = load(briefcaseId); // check read permissions
    Connection con = null;
    PreparedStatement stmt = null;
    try {
        con = Database.getDbConnection();
        // check if the item actually exists
        stmt = con.prepareStatement(
                "SELECT COUNT(*) FROM " + TBL_BRIEFCASE_DATA_ITEM + " WHERE briefcase_id=? AND id=? AND pos=?");
        stmt.setLong(1, briefcaseId);
        stmt.setLong(2, updateData.getId());
        stmt.setInt(3, updateData.getPos());
        ResultSet rs = stmt.executeQuery();
        if (rs == null || !rs.next() || rs.getLong(1) != 1)
            throw new FxNotFoundException(LOG, "ex.briefcase.notFound.item", updateData.getId(), br.getName());
        stmt.close();
        stmt = con.prepareStatement("UPDATE " + TBL_BRIEFCASE_DATA_ITEM
        //               1           2           3            4            5           6                    7        8         9
                + " SET intflag1=?, intflag2=?, intflag3=?, longflag1=?, longflag2=?, metadata=? WHERE briefcase_id=? AND id=? AND pos=?");
        stmt.setLong(7, briefcaseId);
        stmt.setLong(8, updateData.getId());
        stmt.setLong(9, updateData.getPos());
        if (updateData.isIntFlagSet(1))
            stmt.setInt(1, updateData.getIntFlag1());
        else
            stmt.setNull(1, Types.INTEGER);
        if (updateData.isIntFlagSet(2))
            stmt.setInt(2, updateData.getIntFlag2());
        else
            stmt.setNull(2, Types.INTEGER);
        if (updateData.isIntFlagSet(3))
            stmt.setInt(3, updateData.getIntFlag3());
        else
            stmt.setNull(3, Types.INTEGER);
        if (updateData.isLongFlagSet(1))
            stmt.setLong(4, updateData.getLongFlag1());
        else
            stmt.setNull(4, Types.BIGINT);
        if (updateData.isLongFlagSet(2))
            stmt.setLong(5, updateData.getLongFlag2());
        else
            stmt.setNull(5, Types.BIGINT);
        stmt.setString(6, updateData.getMetaData());
        stmt.executeUpdate();
    } catch (Exception e) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, e, "ex.briefcase.updateItemData", br.getName(), updateData.getId(),
                e.getMessage());
    } finally {
        Database.closeObjects(BriefcaseEngineBean.class, con, stmt);
    }
}

From source file:fr.ortolang.diffusion.core.CoreServiceBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Workspace archiveWorkspace(String wskey, Boolean archive)
        throws CoreServiceException, KeyNotFoundException, AccessDeniedException, WorkspaceReadOnlyException {
    LOGGER.log(Level.FINE, "archiving workspace [" + wskey + "]");
    try {//from   w  w  w . j a  v a2 s  .com
        String caller = membership.getProfileKeyForConnectedIdentifier();
        List<String> subjects = membership.getConnectedIdentifierSubjects();

        if (!MembershipService.SUPERUSER_IDENTIFIER.equals(caller)) {
            throw new CoreServiceException(
                    "only " + MembershipService.SUPERUSER_IDENTIFIER + " can archive workspace");
        }

        OrtolangObjectIdentifier identifier = registry.lookup(wskey);
        checkObjectType(identifier, Workspace.OBJECT_TYPE);
        authorisation.checkPermission(wskey, subjects, "update");

        Workspace workspace = em.find(Workspace.class, identifier.getId());
        if (workspace == null) {
            throw new CoreServiceException(
                    "unable to load workspace with id [" + identifier.getId() + "] from storage");
        }
        workspace.setArchive(archive);
        workspace.setKey(wskey);
        em.merge(workspace);

        registry.update(wskey);
        indexing.index(wskey);

        ArgumentsBuilder argsBuilder = new ArgumentsBuilder(2).addArgument("ws-alias", workspace.getAlias())
                .addArgument("archive", archive.toString());
        notification.throwEvent(wskey, caller, Workspace.OBJECT_TYPE,
                OrtolangEvent.buildEventType(CoreService.SERVICE_NAME, Workspace.OBJECT_TYPE, "archive"),
                argsBuilder.build());

        return workspace;
    } catch (KeyLockedException | NotificationServiceException | RegistryServiceException
            | MembershipServiceException | AuthorisationServiceException | IndexingServiceException e) {
        ctx.setRollbackOnly();
        LOGGER.log(Level.SEVERE, "unexpected error occurred while archiving workspace", e);
        throw new CoreServiceException("unable to archive workspace with key [" + wskey + "]", e);
    }
}

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

/**
 * {@inheritDoc}//from   w  w w  .j a  va  2 s .c o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void setGroups(long accountId, long... groups) throws FxApplicationException {
    // Handle null params
    if (groups == null)
        groups = new long[0];

    final UserTicket ticket = FxContext.getUserTicket();

    // Permission checks
    try {
        if (!checkPermissions(accountId)[MAY_SET_GROUPS])
            throw new FxNoAccessException("ex.account.groups.noAssignPermission", accountId);
    } catch (FxLoadException le) {
        throw new FxUpdateException(le.getMessage());
    }

    Account account = load(accountId);

    // Remove duplicated entries and add group everyone
    groups = FxArrayUtils.removeDuplicates(groups);

    // Ensure group EVERYONE and mandator group is part of the list, since every user is assigned to it
    groups = FxArrayUtils.addElement(groups, UserGroup.GROUP_EVERYONE);
    groups = FxArrayUtils.addElement(groups, group.loadMandatorGroup(account.getMandatorId()).getId());

    // Check the groups
    List<UserGroup> currentlyAssigned;
    try {
        currentlyAssigned = getGroups(accountId);
    } catch (FxLoadException exc) {
        throw new FxUpdateException(exc);
    }

    StringBuilder sbHistory = new StringBuilder(1000);
    sbHistory.append("<original>\n");
    for (UserGroup org : currentlyAssigned)
        sbHistory.append("  <group id=\"").append(org.getId()).append("\" mandator=\"")
                .append(org.getMandatorId()).append("\">").append(org.getName()).append("</group>\n");
    sbHistory.append("</original>\n").append("<new>\n");

    for (long grp : groups) {
        UserGroup g = CacheAdmin.getEnvironment().getUserGroup(grp);
        sbHistory.append("  <group id=\"").append(g.getId()).append("\" mandator=\"").append(g.getMandatorId())
                .append("\">").append(g.getName()).append("</group>\n");
        // Do not check the special gropups
        if (grp == UserGroup.GROUP_EVERYONE)
            continue;
        if (grp == UserGroup.GROUP_OWNER)
            continue;
        if (grp == UserGroup.GROUP_UNDEFINED)
            continue;
        if (FxSharedUtils.indexOfSelectableObject(currentlyAssigned, grp) != -1)
            continue;
        // Perform the check for all regular groups, loading an inaccessible
        // group will throw an exception which is what we want here

        if (g.isSystem())
            continue;
        //make sure the calling user is assigned all roles of the group as well
        for (Role check : group.getRoles(grp))
            if (!ticket.isInRole(check))
                throw new FxNoAccessException("ex.account.roles.assign.noMember.group", check.name(),
                        g.getName());
        if (!ticket.isGlobalSupervisor()) {
            if (g.getMandatorId() != account.getMandatorId())
                throw new FxNoAccessException("ex.account.group.assign.wrongMandator", g.getName(), accountId);
        }
    }
    sbHistory.append("</new>\n");

    // Write group assignments to the database
    Connection con = null;
    PreparedStatement ps = null;

    try {
        // Obtain a database connection
        con = Database.getDbConnection();

        // Delete the old assignments of the user
        ps = con.prepareStatement("DELETE FROM " + TBL_ASSIGN_GROUPS + " WHERE ACCOUNT=?");
        ps.setLong(1, accountId);
        ps.executeUpdate();
        if (groups.length > 0) {
            ps.close();
            ps = con.prepareStatement("INSERT INTO " + TBL_ASSIGN_GROUPS + " (ACCOUNT,USERGROUP) VALUES (?,?)");
        }

        // Store the new assignments of the user
        for (long group : groups) {
            // Skipp 'null' group
            if (group == UserGroup.GROUP_UNDEFINED)
                continue;
            ps.setLong(1, accountId);
            ps.setLong(2, group);
            ps.executeUpdate();
        }
        LifeCycleInfoImpl.updateLifeCycleInfo(TBL_ACCOUNTS, "ID", accountId);
        // Ensure any active ticket of the updated user are refreshed
        UserTicketStore.flagDirtyHavingUserId(accountId);
        EJBLookup.getHistoryTrackerEngine().trackData(sbHistory.toString(), "history.account.setGroups",
                account.getLoginName());
    } catch (SQLException exc) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, exc, "ex.account.roles.updateFailed.sql", accountId, exc.getMessage());
    } finally {
        Database.closeObjects(AccountEngineBean.class, con, ps);
    }

}

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

/**
 * {@inheritDoc}// w ww . j  a  va 2  s . com
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void removeAssignmentScriptMappingForEvent(long scriptId, long assignmentId, 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_ASSIGN + " WHERE SCRIPT=? AND ASSIGNMENT=? AND STYPE=?";
        ps = con.prepareStatement(sql);
        ps.setLong(1, scriptId);
        ps.setLong(2, assignmentId);
        ps.setLong(3, event.getId());
        ps.executeUpdate();
        success = true;
    } catch (SQLException exc) {
        throw new FxRemoveException(LOG, exc, "ex.scripting.mapping.assign.remove.failed", scriptId,
                assignmentId, exc.getMessage());
    } finally {
        Database.closeObjects(ScriptingEngineBean.class, con, ps);
        if (!success)
            EJBUtils.rollback(ctx);
        else
            StructureLoader.reloadScripting(FxContext.get().getDivisionId());
    }
}

From source file:org.ejbca.core.ejb.ca.store.CertificateStoreSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override/*  w  w  w . ja va  2  s. c  o m*/
public CertReqHistory getCertReqHistory(Admin admin, BigInteger certificateSN, String issuerDN) {
    CertReqHistory retval = null;
    Collection<CertReqHistoryData> result = CertReqHistoryData.findByIssuerDNSerialNumber(entityManager,
            issuerDN, certificateSN.toString());
    if (result.iterator().hasNext()) {
        retval = result.iterator().next().getCertReqHistory();
    }
    return retval;
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@RolesAllowed({ "org.nightlabs.jfire.store.editUnconfirmedProductType",
        "org.nightlabs.jfire.store.editConfirmedProductType" })
@Override//from w  ww .  ja  v a 2 s. c om
public ProductTypeStatusHistoryItem setProductTypeStatus_confirmed(ProductTypeID productTypeID, boolean get,
        String[] fetchGroups, int maxFetchDepth) throws CannotConfirmProductTypeException {
    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_confirmed(User.getUser(pm, getPrincipal()), productType);

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

From source file:org.ejbca.core.ejb.ca.store.CertificateStoreSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override//  w ww.  j  ava  2s.c  om
public List<CertReqHistory> getCertReqHistory(Admin admin, String username) {
    ArrayList<CertReqHistory> retval = new ArrayList<CertReqHistory>();
    Collection<CertReqHistoryData> result = CertReqHistoryData.findByUsername(entityManager, username);
    Iterator<CertReqHistoryData> iter = result.iterator();
    while (iter.hasNext()) {
        retval.add(iter.next().getCertReqHistory());
    }
    return retval;
}

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

/**
 * {@inheritDoc}/*  ww w.  j  a  v  a 2 s.  co  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void populate(FxTreeMode mode) throws FxApplicationException {
    final int maxNodeChildren = 3; // "default" of 3 data population nodes
    populate(mode, maxNodeChildren);
}