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.UserGroupEngineBean.java

/**
 * {@inheritDoc}/*from w  w  w. j  a v  a2  s.c o  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void rebuildMandatorGroups() throws FxApplicationException {
    Connection con = null;
    PreparedStatement ps = null;
    Statement stmt = null;
    String sql = "";
    try {
        con = Database.getDbConnection();
        stmt = con.createStatement();
        List<Mandator> missing = new ArrayList<Mandator>(5);
        for (Mandator m : CacheAdmin.getEnvironment().getMandators(true, true)) {
            try {
                UserGroup g = loadMandatorGroup(m.getId());
                sql = "DELETE FROM " + TBL_ASSIGN_GROUPS + " WHERE USERGROUP=" + g.getId();
                stmt.executeUpdate(sql);
                sql = "INSERT INTO " + TBL_ASSIGN_GROUPS + " (ACCOUNT,USERGROUP) (SELECT a.id, " + g.getId()
                        + " FROM " + TBL_ACCOUNTS + " a WHERE a.MANDATOR=" + m.getId() + " AND a.ID!="
                        + Account.NULL_ACCOUNT + ")";
                stmt.executeUpdate(sql);
            } catch (FxNotFoundException e) {
                missing.add(m);
            }
        }
        final long NOW = System.currentTimeMillis();
        for (Mandator m : missing) {
            sql = "INSERT INTO " + TBL_USERGROUPS + " "
                    + "(ID,MANDATOR,AUTOMANDATOR,ISSYSTEM,NAME,COLOR,CREATED_BY,CREATED_AT,MODIFIED_BY,MODIFIED_AT) VALUES ("
                    + "?,?,?,?,?,?,?,?,?,?)";
            if (ps == null)
                ps = con.prepareStatement(sql);
            long gid = seq.getId(FxSystemSequencer.GROUP);
            ps.setLong(1, gid);
            ps.setLong(2, m.getId());
            ps.setLong(3, m.getId());
            ps.setBoolean(4, true); //ISSYSTEM
            ps.setString(5, "Everyone (" + m.getName() + ")");
            ps.setString(6, "#00AA00");
            ps.setLong(7, 0);
            ps.setLong(8, NOW);
            ps.setLong(9, 0);
            ps.setLong(10, NOW);
            ps.executeUpdate();
            sql = "INSERT INTO " + TBL_ASSIGN_GROUPS + " (ACCOUNT,USERGROUP) (SELECT a.ID, " + gid + " FROM "
                    + TBL_ACCOUNTS + " a WHERE a.MANDATOR=" + m.getId() + " AND a.ID!=" + Account.NULL_ACCOUNT
                    + ")";
            stmt.executeUpdate(sql);
        }

        StructureLoader.updateUserGroups(FxContext.get().getDivisionId(), loadAll(-1));
    } catch (SQLException exc) {
        FxLoadException le = new FxLoadException(exc, "ex.usergroup.sqlError", exc.getMessage(), sql);
        LOG.error(le);
        throw le;
    } finally {
        if (ps != null)
            try {
                ps.close();
            } catch (SQLException e) {
                //ignore
            }
        Database.closeObjects(UserGroupEngineBean.class, con, stmt);
    }
}

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

/**
 * {@inheritDoc}/*from w  ww  . j ava 2s. c om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void assign(long aclId, long groupId, ACLPermission... permissions) throws FxApplicationException {
    boolean mayRead = false;
    boolean mayEdit = false;
    boolean mayRelate = false;
    boolean mayDelete = false;
    boolean mayExport = false;
    boolean mayCreate = false;
    for (ACLPermission perm : permissions) {
        switch (perm) {
        case CREATE:
            mayCreate = true;
            break;
        case DELETE:
            mayDelete = true;
            break;
        case EDIT:
            mayEdit = true;
            break;
        case EXPORT:
            mayExport = true;
            break;
        case RELATE:
            mayRelate = true;
            break;
        case READ:
            mayRead = true;
            break;
        }
    }
    assign(aclId, groupId, mayRead, mayEdit, mayRelate, mayDelete, mayExport, mayCreate);
}

From source file:com.flexive.ejb.beans.configuration.GenericConfigurationImpl.java

/**
 * {@inheritDoc}//from   ww  w .  jav  a2  s  .co m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public <T extends Serializable> void remove(Parameter<T> parameter) throws FxApplicationException {
    remove(parameter, parameter.getKey());
}

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

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public String snapshotWorkspace(String wskey) throws CoreServiceException, KeyNotFoundException,
        AccessDeniedException, WorkspaceReadOnlyException, WorkspaceUnchangedException {
    LOGGER.log(Level.FINE, "snapshoting workspace [" + wskey + "]");
    try {//from  w  w  w  .  ja  va2 s  .  co  m
        String caller = membership.getProfileKeyForConnectedIdentifier();
        List<String> subjects = membership.getConnectedIdentifierSubjects();

        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");
        }
        if (applyReadOnly(caller, subjects, workspace)) {
            throw new WorkspaceReadOnlyException(
                    "unable to snapshot workspace with key [" + wskey + "] because it is read only");
        }

        String name = String.valueOf(workspace.getClock());

        if (!workspace.hasChanged()) {
            throw new WorkspaceUnchangedException(
                    "unable to snapshot because workspace has no pending modifications since last snapshot");
        }

        try {
            JsonObjectBuilder builder = Json.createObjectBuilder();
            builder.add("wskey", wskey);
            builder.add("snapshotName", name);
            builder.add("wsalias", workspace.getAlias());

            JsonObject jsonObject = builder.build();
            String hash = binarystore.put(new ByteArrayInputStream(jsonObject.toString().getBytes()));

            List<String> mds = findMetadataObjectsForTargetAndName(workspace.getHead(),
                    MetadataFormat.WORKSPACE);

            if (mds.isEmpty()) {
                LOGGER.log(Level.INFO, "creating workspace metadata for root collection");
                createMetadataObject(wskey, "/", MetadataFormat.WORKSPACE, hash, null, false);
            } else {
                LOGGER.log(Level.INFO, "updating workspace metadata for root collection");
                updateMetadataObject(wskey, "/", MetadataFormat.WORKSPACE, hash, null, false);
            }
        } catch (BinaryStoreServiceException | DataCollisionException | CoreServiceException
                | KeyNotFoundException | InvalidPathException | AccessDeniedException | MetadataFormatException
                | PathNotFoundException | KeyAlreadyExistsException e) {
            throw new CoreServiceException(
                    "cannot create workspace metadata for collection root : " + e.getMessage());
        }

        workspace.setKey(wskey);
        workspace.incrementClock();

        OrtolangObjectIdentifier hidentifier = registry.lookup(workspace.getHead());
        checkObjectType(hidentifier, Collection.OBJECT_TYPE);
        Collection collection = em.find(Collection.class, hidentifier.getId());
        if (collection == null) {
            throw new CoreServiceException(
                    "unable to load head collection with id [" + hidentifier.getId() + "] from storage");
        }
        collection.setKey(workspace.getHead());

        Collection clone = cloneCollection(workspace.getHead(), collection, workspace.getClock());

        workspace.addSnapshot(new SnapshotElement(name, collection.getKey()));
        workspace.setHead(clone.getKey());
        workspace.setChanged(false);
        em.merge(workspace);

        registry.update(wskey);

        ArgumentsBuilder argsBuilder = new ArgumentsBuilder(2).addArgument("ws-alias", workspace.getAlias())
                .addArgument("snapshot-name", name);
        notification.throwEvent(wskey, caller, Workspace.OBJECT_TYPE,
                OrtolangEvent.buildEventType(CoreService.SERVICE_NAME, Workspace.OBJECT_TYPE, "snapshot"),
                argsBuilder.build());
        return name;
    } catch (KeyLockedException | NotificationServiceException | RegistryServiceException
            | MembershipServiceException | AuthorisationServiceException | CloneException e) {
        ctx.setRollbackOnly();
        LOGGER.log(Level.SEVERE, "unexpected error occurred while snapshoting workspace", e);
        throw new CoreServiceException("unable to snapshot workspace with key [" + wskey + "]", e);
    }
}

From source file:com.flexive.ejb.beans.configuration.GenericConfigurationImpl.java

/**
 * {@inheritDoc}/*from   ww w.  j av  a2s .  c om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public <T extends Serializable> void removeAll(Parameter<T> parameter) throws FxApplicationException {
    remove(parameter, null);
}

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

/**
 * {@inheritDoc}/*from   ww w .  j ava  2  s .  co  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public FxContent prepareSave(FxContent content) throws FxApplicationException {
    Connection con = null;
    try {
        con = Database.getDbConnection();
        return prepareSave(con, StorageManager.getContentStorage(content.getPk().getStorageMode()), content);
    } catch (FxNotFoundException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } catch (FxInvalidParameterException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } finally {
        Database.closeObjects(ContentEngineBean.class, con, null);
    }
}

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

/**
 * {@inheritDoc}//from www.  j  av a 2s. co m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void addItemData(long briefcaseId, List<BriefcaseItemData> itemDatas) throws FxApplicationException {
    if (itemDatas == null || itemDatas.size() == 0)
        return;
    Briefcase br = load(briefcaseId); // check read permissions
    Connection con = null;
    PreparedStatement stmt = null;
    long lastId = -1;
    int pos = -1;
    try {
        con = Database.getDbConnection();

        for (BriefcaseItemData itemData : itemDatas) {
            if (lastId != itemData.getId()) {
                lastId = itemData.getId();
                if (stmt != null) {
                    stmt.executeBatch();
                    stmt.close();
                }
                //existance check and evaluate position
                stmt = con.prepareStatement(
                        "SELECT COUNT(*) FROM " + TBL_BRIEFCASE_DATA + " WHERE briefcase_id=? AND id=?");
                stmt.setLong(1, briefcaseId);
                stmt.setLong(2, itemData.getId());
                ResultSet rs = stmt.executeQuery();
                if (rs == null || !rs.next() || rs.getLong(1) != 1)
                    throw new FxNotFoundException(LOG, "ex.briefcase.notFound.item", itemData.getId(),
                            br.getName());
                stmt.close();
                stmt = con.prepareStatement(
                        "SELECT MAX(pos) FROM " + TBL_BRIEFCASE_DATA_ITEM + " WHERE briefcase_id=? AND id=?");
                stmt.setLong(1, briefcaseId);
                stmt.setLong(2, itemData.getId());
                rs = stmt.executeQuery();
                pos = rs.next() ? rs.getInt(1) : 0;
                stmt.close();
                stmt = con.prepareStatement("INSERT INTO " + TBL_BRIEFCASE_DATA_ITEM
                        + "(briefcase_id, id, pos, intflag1, intflag2, intflag3, longflag1, longflag2, metadata) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                stmt.setLong(1, briefcaseId);
                stmt.setLong(2, itemData.getId());
            }
            if (stmt == null) {
                LOG.fatal("PreparedStatement was null trying to add briefcase item data!");
                continue;
            }
            stmt.setLong(3, ++pos);
            if (itemData.isIntFlagSet(1))
                stmt.setInt(4, itemData.getIntFlag1());
            else
                stmt.setNull(4, Types.INTEGER);
            if (itemData.isIntFlagSet(2))
                stmt.setInt(5, itemData.getIntFlag2());
            else
                stmt.setNull(5, Types.INTEGER);
            if (itemData.isIntFlagSet(3))
                stmt.setInt(6, itemData.getIntFlag3());
            else
                stmt.setNull(6, Types.INTEGER);
            if (itemData.isLongFlagSet(1))
                stmt.setLong(7, itemData.getLongFlag1());
            else
                stmt.setNull(7, Types.BIGINT);
            if (itemData.isLongFlagSet(2))
                stmt.setLong(8, itemData.getLongFlag2());
            else
                stmt.setNull(8, Types.BIGINT);
            stmt.setString(9, itemData.getMetaData());
            stmt.addBatch();
        }
        if (stmt != null)
            stmt.executeBatch();
    } catch (Exception e) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, e, "ex.briefcase.addItemData", br.getName(), lastId, e.getMessage());
    } finally {
        Database.closeObjects(BriefcaseEngineBean.class, con, stmt);
    }
}

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

/**
 * {@inheritDoc}//ww w .  j  av  a  2s  . com
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void unassign(long aclId, long groupId) throws FxApplicationException {
    Connection con = null;
    Statement stmt = null;
    String curSql;
    UserTicket ticket = FxContext.getUserTicket();
    checkPermissions(ticket, groupId, aclId, true);

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

        // Delete any old assignments
        curSql = "DELETE FROM " + TBL_ACLS_ASSIGNMENT + " WHERE USERGROUP=" + groupId + " AND ACL=" + aclId;
        stmt = con.createStatement();
        if (stmt.executeUpdate(curSql) == 0)
            throw new FxNotFoundException("ex.aclAssignment.notFound", aclId, groupId);

        // Update active UserTickets
        UserTicketStore.flagDirtyHavingGroupId(groupId);
    } catch (FxNotFoundException e) {
        throw e;
    } catch (Exception exc) {
        EJBUtils.rollback(ctx);
        throw new FxRemoveException(LOG, exc, "ex.aclAssignment.unassigneFailed", aclId, groupId);
    } finally {
        Database.closeObjects(ACLEngineBean.class, con, stmt);
    }

}

From source file:com.flexive.ejb.beans.configuration.DivisionConfigurationEngineBean.java

/**
 * {@inheritDoc}//from ww w .  j av a2  s  .c o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void setResourceValue(String key, FxString value) throws FxApplicationException {
    if (StringUtils.isBlank(key))
        return;
    key = key.trim();
    if (key.length() > 250)
        throw new FxApplicationException("ex.configuration.resource.key.tooLong", key);
    if (!StringUtils.isAsciiPrintable(key))
        throw new FxApplicationException("ex.configuration.resource.key.nonAscii", key);
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();
        ps = con.prepareStatement("DELETE FROM " + TBL_RESOURCES + " WHERE RKEY=?");
        ps.setString(1, key);
        ps.executeUpdate();
        if (value != null && !value.isEmpty()) {
            ps.close();
            ps = con.prepareStatement("INSERT INTO " + TBL_RESOURCES + " (RKEY,LANG,RVAL)VALUES(?,?,?)");
            ps.setString(1, key);
            for (long lang : value.getTranslatedLanguages()) {
                ps.setLong(2, lang);
                ps.setString(3, value.getTranslation(lang));
                ps.addBatch();
            }
            ps.executeBatch();
        }
    } catch (SQLException e) {
        throw new FxApplicationException(e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(DivisionConfigurationEngine.class, con, ps);
    }
}

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

/**
 * {@inheritDoc}/*w  ww  . ja v a  2 s. c  o  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public int removeMandatorPhrases(long mandator) throws FxNoAccessException, FxEntryInUseException {
    return removeMandatorPhrases(FxPhraseCategorySelection.SELECTION_ANY, mandator);
}