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

/**
 * {@inheritDoc}//from   w  w  w.  java 2  s  .  com
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public FxPK createNewVersion(FxContent content) throws FxApplicationException {
    content.checkForceSystemPropertyPermissions();
    Connection con = null;
    PreparedStatement ps = null;
    if (content.getPk().isNew())
        return save(content);
    try {
        //security check start
        FxEnvironment env = CacheAdmin.getEnvironment();
        FxType type = env.getType(content.getTypeId());
        Step step = env.getStep(content.getStepId());
        UserTicket ticket = FxContext.getUserTicket();
        FxPermissionUtils.checkMandatorExistance(content.getMandatorId());
        FxPermissionUtils.checkTypeAvailable(type.getId(), false);

        con = Database.getDbConnection();
        //check edit permission on current version
        final ContentStorage storage = StorageManager.getContentStorage(content.getPk().getStorageMode());

        FxPermissionUtils.checkPermission(ticket, ticket.getUserId(), ACLPermission.CREATE, type,
                step.getAclId(), content.getAclIds(), true);
        FxContent prepared = prepareSave(con, storage, content);
        //security check end

        FxScriptBinding binding = null;
        long[] typeScripts;
        //scripting before start
        //type scripting
        typeScripts = type.getScriptMapping(
                content.getPk().isNew() ? FxScriptEvent.BeforeContentCreate : FxScriptEvent.BeforeContentSave);
        if (typeScripts != null)
            for (long script : typeScripts) {
                if (binding == null)
                    binding = new FxScriptBinding();
                binding.setVariable("content", content);
                Object result = scripting.runScript(script, binding).getResult();
                if (result != null && result instanceof FxContent) {
                    content = (FxContent) result;
                }
            }
        //assignment scripting
        if (type.hasScriptedAssignments()) {
            binding = null;
            for (FxAssignment as : type.getScriptedAssignments(FxScriptEvent.BeforeAssignmentDataSave)) {
                if (binding == null)
                    binding = new FxScriptBinding();
                binding.setVariable("assignment", as);
                for (long script : as.getScriptMapping(FxScriptEvent.BeforeAssignmentDataSave)) {
                    binding.setVariable("content", content);
                    Object result = scripting.runScript(script, binding).getResult();
                    if (result != null && result instanceof FxContent) {
                        content = (FxContent) result;
                    }
                }
            }
        }
        //scripting before end

        FxPK pk = storage.contentCreateVersion(con, CacheAdmin.getEnvironment(), null, prepared);

        //scripting after start
        //assignment scripting
        if (type.hasScriptedAssignments()) {
            binding = new FxScriptBinding();
            binding.setVariable("pk", pk);
            for (FxAssignment as : type.getScriptedAssignments(FxScriptEvent.AfterAssignmentDataSave)) {
                binding.setVariable("assignment", as);
                for (long script : as.getScriptMapping(FxScriptEvent.AfterAssignmentDataSave)) {
                    scripting.runScript(script, binding);
                }
            }
        }
        //type scripting
        typeScripts = env.getType(content.getTypeId()).getScriptMapping(FxScriptEvent.AfterContentSave);
        if (typeScripts != null)
            for (long script : typeScripts) {
                if (binding == null)
                    binding = new FxScriptBinding();
                binding.setVariable("pk", pk);
                scripting.runScript(script, binding);
            }
        //scripting after end

        return pk;
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } catch (FxNotFoundException e) {
        EJBUtils.rollback(ctx);
        throw e;
    } catch (FxApplicationException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } catch (Exception e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(LOG, e);
    } catch (Throwable t) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(LOG, t);
    } finally {
        Database.closeObjects(ContentEngineBean.class, con, ps);
        if (!ctx.getRollbackOnly())
            CacheAdmin.expireCachedContent(content.getId());
    }
}

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

/**
 * {@inheritDoc}/*from   ww w  .ja  va2s.  c  o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public FxScriptInfo createScriptFromDropLibrary(String dropName, String libraryname, FxScriptInfo scriptInfo)
        throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptManagement);
    String code = FxSharedUtils.loadFromInputStream(
            FxSharedUtils.getResourceStream(dropName + "Resources/scripts/library/" + libraryname), -1);
    if (code == null || code.length() == 0) { // this might be a jar file
        if (LOG.isDebugEnabled()) {
            LOG.debug(
                    "Failed to locate script in regular application library, checking for drop application in classpath JARs");
        }
        try {
            final FxDropApplication dropApplication = FxSharedUtils.getDropApplication(dropName);
            final Map<String, String> libraries = dropApplication.loadTextResources("scripts/library/");
            for (Map.Entry<String, String> libEntry : libraries.entrySet()) {
                if (libEntry.getKey().endsWith('/' + libraryname)
                        || libEntry.getKey().endsWith(File.separator + libraryname)) {
                    code = libEntry.getValue();
                    break;
                }
            }
        } catch (Exception e) {
            LOG.error("Failed to load library scripts for " + dropName + " from JAR file: " + e.getMessage(),
                    e);
        }
    }

    if (code == null || code.length() == 0) {
        throw new FxNotFoundException("ex.scripting.load.library.failed", libraryname);
    }
    return createScript(new FxScriptInfoEdit(-1, scriptInfo.getEvent(), scriptInfo.getName(),
            scriptInfo.getDescription(), code, scriptInfo.isActive(), scriptInfo.isCached()));
}

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

/**
 * {@inheritDoc}/*from w ww.j  a  va2s  .  co m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void move(FxTreeMode mode, long nodeId, long destinationId, int newPosition)
        throws FxApplicationException {
    Connection con = null;
    try {
        con = Database.getDbConnection();
        StorageManager.getTreeStorage().move(con, seq, mode, nodeId, destinationId, newPosition);
        StorageManager.getTreeStorage().checkTreeIfEnabled(con, mode);
        FxContext.get().setTreeWasModified();
    } catch (FxApplicationException ae) {
        EJBUtils.rollback(ctx);
        throw ae;
    } catch (Throwable t) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, t, "ex.tree.move.failed", nodeId, destinationId, newPosition);
    } finally {
        Database.closeObjects(TreeEngineBean.class, con, null);
    }
}

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

/**
 * {@inheritDoc}/*from w ww  . j av a  2s. c om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void setRootPassword(String value) throws FxApplicationException {
    put(SystemParameters.GLOBAL_ROOT_PASSWORD, getHashedPassword(value));
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override//from  ww  w.  j  a  v  a2  s  . c o  m
public void setRevokeStatus(Admin admin, String issuerdn, BigInteger serno, Date revokedate,
        Collection<Integer> publishers, int reason, String userDataDN) {
    if (log.isTraceEnabled()) {
        log.trace(">setRevokeStatus(),  issuerdn=" + issuerdn + ", serno=" + serno.toString(16) + ", reason="
                + reason);
    }
    try {
        Certificate certificate = findCertificateByIssuerAndSerno(admin, issuerdn, serno);
        setRevokeStatus(admin, certificate, revokedate, publishers, reason, userDataDN);
    } catch (FinderException e) {
        String msg = intres.getLocalizedMessage("store.errorfindcertserno", serno.toString(16));
        logSession.log(admin, issuerdn.hashCode(), LogConstants.MODULE_CA, new java.util.Date(), null, null,
                LogConstants.EVENT_ERROR_REVOKEDCERT, msg);
        throw new EJBException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<setRevokeStatus(),  issuerdn=" + issuerdn + ", serno=" + serno.toString(16) + ", reason="
                + reason);
    }
}

From source file:gov.nih.nci.caarray.application.project.ProjectManagementServiceBean.java

/**
 * {@inheritDoc}/*from w w  w.j av a 2s.c o  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Source copySource(Project project, long sourceId)
        throws ProposalWorkflowException, InconsistentProjectStateException {
    checkIfProjectSaveAllowed(project);
    final Source source = this.searchDao.retrieve(Source.class, sourceId);
    final Source copy = new Source();
    copyInto(Source.class, copy, source);
    project.getExperiment().getSources().add(copy);
    copy.setExperiment(project.getExperiment());
    this.projectDao.save(project);
    return copy;
}

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

/**
 * {@inheritDoc}/*from  w  w w  .  j a  va  2  s  . co m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public boolean removePhrase(int category, String phraseKey, long mandator)
        throws FxNoAccessException, FxEntryInUseException {
    Connection con = null;
    PreparedStatement ps = null;
    final UserTicket userTicket = FxContext.getUserTicket();
    checkMandatorAccess(mandator, userTicket);
    checkPhraseKey(phraseKey);
    try {
        // Obtain a database connection
        con = Database.getDbConnection();
        ps = con.prepareStatement("SELECT ID FROM " + TBL_PHRASE + " WHERE PKEY=? AND MANDATOR=? AND CAT=?");
        ps.setString(1, phraseKey);
        ps.setLong(2, mandator);
        ps.setInt(3, category);
        ResultSet rs = ps.executeQuery();
        if (rs != null && rs.next()) {
            long id = rs.getLong(1);
            rs.close();
            ps.close();
            ps = con.prepareStatement(
                    "SELECT ID FROM " + TBL_PHRASE_TREE + " WHERE PHRASEID=? AND PMANDATOR=? AND CAT=?");
            ps.setLong(1, id);
            ps.setLong(2, mandator);
            ps.setInt(3, category);
            ResultSet rsCheck = ps.executeQuery();
            if (rsCheck != null && rsCheck.next())
                throw new FxEntryInUseException("ex.phrase.inUse.tree", phraseKey);
            if (rsCheck != null)
                rsCheck.close();
            ps.close();
            ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE_VALUES + " WHERE ID=? AND MANDATOR=?");
            ps.setLong(1, id);
            ps.setLong(2, mandator);
            ps.execute();
            ps.close();
            ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE_MAP + " WHERE PHRASEID=? AND PMANDATOR=?");
            ps.setLong(1, id);
            ps.setLong(2, mandator);
            ps.execute();
            ps.close();
            ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE + " WHERE ID=? AND MANDATOR=? AND CAT=?");
            ps.setLong(1, id);
            ps.setLong(2, mandator);
            ps.setInt(3, category);
            ps.execute();
            return true;
        }
        return false;
    } catch (SQLException exc) {
        EJBUtils.rollback(ctx);
        throw new FxDbException(LOG, exc, "ex.db.sqlError", exc.getMessage()).asRuntimeException();
    } finally {
        Database.closeObjects(PhraseEngineBean.class, con, ps);
    }
}

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

/**
 * {@inheritDoc}/* ww  w  .ja  v  a  2  s . c om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void clearDivisionCache() {
    FxCacheMBean cache = CacheAdmin.getInstance();
    try {
        // clear local caches
        synchronized (divisions) {
            divisions.clear();
        }
        synchronized (domainCache) {
            domainCache.clear();
        }
        // clear shared cache
        cache.globalRemove(getBeanPath(CACHE_DIVISIONS));
    } catch (FxCacheException e) {
        LOG.error("Failed to clear cache: " + e.getMessage(), e);
    }
}

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

/**
 * {@inheritDoc}//from  w  ww. j  a v  a 2  s  . c o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void assign(long aclId, long groupId, boolean mayRead, boolean mayEdit, boolean mayRelate,
        boolean mayRemove, boolean mayExport, boolean mayCreate) throws FxApplicationException {
    UserTicket ticket = FxContext.getUserTicket();
    // Delete rather than create?
    if (!mayRead && !mayRelate && !mayExport && !mayEdit && !mayRemove && !mayCreate) {
        try {
            unassign(aclId, groupId);
        } catch (FxNotFoundException e) {
            // ignore missing assignments
        } catch (FxRemoveException exc) {
            throw new FxCreateException(exc.getMessage(), exc);
        }
        return;
    }

    // Permission & exists check
    checkPermissions(ticket, groupId, aclId, true);

    Connection con = null;
    PreparedStatement stmt = null;
    String curSql;
    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.prepareStatement(curSql);
        int ucount = stmt.executeUpdate();
        stmt.close();
        if (LOG.isDebugEnabled())
            LOG.debug("Deleted assignments group[" + groupId + "]-acl[" + aclId + "]:" + ucount);

        curSql = "INSERT INTO " + TBL_ACLS_ASSIGNMENT +
        //1         2   3     4     5       6       7       8     9          10         11          12
                "(USERGROUP,ACL,PREAD,PEDIT,PREMOVE,PCREATE,PEXPORT,PREL,CREATED_AT,CREATED_BY,MODIFIED_AT,MODIFIED_BY)"
                + " VALUES " + "(?,?,?,?,?,?,?,?,?,?,?,?)";

        final long NOW = System.currentTimeMillis();
        stmt = con.prepareStatement(curSql);
        stmt.setLong(1, groupId);
        stmt.setLong(2, aclId);
        stmt.setBoolean(3, mayRead);
        stmt.setBoolean(4, mayEdit);
        stmt.setBoolean(5, mayRemove);
        stmt.setBoolean(6, mayCreate);
        stmt.setBoolean(7, mayExport);
        stmt.setBoolean(8, mayRelate);
        stmt.setLong(9, NOW);
        stmt.setLong(10, ticket.getUserId());
        stmt.setLong(11, NOW);
        stmt.setLong(12, ticket.getUserId());

        stmt.executeUpdate();

        // Update active UserTickets
        UserTicketStore.flagDirtyHavingGroupId(groupId);

        final ACL acl = CacheAdmin.getEnvironment().getACL(aclId);
        final ACLAssignment as = new ACLAssignment(aclId, groupId, mayRead, mayEdit, mayRelate, mayRemove,
                mayExport, mayCreate, acl.getCategory(), acl.getLifeCycleInfo());
        EJBLookup.getHistoryTrackerEngine().trackData(ConversionEngine.getXStream().toXML(as),
                "history.acl.assign", acl.getName());
    } catch (Exception exc) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(LOG, exc, "ex.aclAssignment.createFailed");
    } finally {
        Database.closeObjects(ACLEngineBean.class, con, stmt);
    }

}

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

/**
 * {@inheritDoc}/*from  www .  ja v  a2  s .com*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public <T extends Serializable> Map<String, T> getAll(Parameter<T> parameter) throws FxApplicationException {
    Connection conn = null;
    PreparedStatement stmt = null;
    ParameterData<T> data = parameter.getData();
    HashMap<String, T> parameters = new HashMap<String, T>();
    try {
        conn = getConnection();
        stmt = getSelectStatement(conn, data.getPath().getValue());
        ResultSet rs = stmt.executeQuery();
        while (rs != null && rs.next()) {
            // retrieve parameters and put them in hashmap
            parameters.put(rs.getString(1), parameter.getValue(rs.getString(2)));
        }
        return parameters;
    } catch (SQLException se) {
        throw new FxLoadException(LOG, se, "ex.db.sqlError", se.getMessage());
    } finally {
        Database.closeObjects(GenericConfigurationImpl.class, conn, stmt);
    }
}