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

/**
 * {@inheritDoc}//  www  . ja va 2  s  .  c  o  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public List<Briefcase> loadAll(boolean includeShared) throws FxApplicationException {
    return getList(null, includeShared);
}

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

/**
 * {@inheritDoc}//from  w  w w.  ja v  a  2s .  co m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void deactivate(long mandatorId) throws FxApplicationException {
    final UserTicket ticket = FxContext.getUserTicket();
    final FxEnvironment environment;
    // Security
    FxPermissionUtils.checkRole(ticket, Role.GlobalSupervisor);
    environment = CacheAdmin.getEnvironment();
    //exist check
    Mandator mand = environment.getMandator(mandatorId);
    if (!mand.isActive())
        return; //silently ignore
    if (mand.getId() == ticket.getMandatorId())
        throw new FxInvalidParameterException("mandatorId", "ex.mandator.deactivate.own", mand.getName(),
                mand.getId());
    Connection con = null;
    PreparedStatement ps = null;
    String sql;

    try {

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

        //                                                1              2              3          4
        sql = "UPDATE " + TBL_MANDATORS + " SET IS_ACTIVE=?, MODIFIED_BY=?, MODIFIED_AT=? WHERE ID=?";
        final long NOW = System.currentTimeMillis();
        ps = con.prepareStatement(sql);

        ps.setBoolean(1, false);
        ps.setLong(2, ticket.getUserId());
        ps.setLong(3, NOW);
        ps.setLong(4, mandatorId);
        ps.executeUpdate();
        StructureLoader.updateMandator(FxContext.get().getDivisionId(),
                new Mandator(mand.getId(), mand.getName(), mand.getMetadataId(), false,
                        new LifeCycleInfoImpl(mand.getLifeCycleInfo().getCreatorId(),
                                mand.getLifeCycleInfo().getCreationTime(), ticket.getUserId(), NOW)));
    } catch (SQLException exc) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, exc, "ex.mandator.updateFailed", mand.getName(), exc.getMessage());
    } finally {
        Database.closeObjects(MandatorEngineBean.class, con, ps);
    }
}

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

/**
 * {@inheritDoc}//from w ww.j  av  a  2s. co m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Briefcase load(long id) throws FxApplicationException {
    List<Briefcase> l = getList(id, true);
    if (l != null && l.size() > 0) {
        return l.get(0);
    } else {
        throw new FxNotFoundException(LOG, "ex.briefcase.notFound.id", id);
    }
}

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

License:asdf

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public boolean updateCertificateOnly(AuthenticationToken authenticationToken, Certificate certificate) {
    final String fingerprint = CertTools.getFingerprintAsString(certificate);
    final CertificateData certificateData = CertificateData.findByFingerprint(entityManager, fingerprint);
    if (certificateData == null || certificateData.getCertificate(entityManager) != null) {
        return false;
    }//from w  w w . j  a  v  a 2 s.com
    final boolean useBase64CertTable = CesecoreConfiguration.useBase64CertTable();
    if (useBase64CertTable) {
        // use special table for encoded data if told so.
        entityManager.persist(new Base64CertData(certificate));
    } else {
        try {
            certificateData.setBase64Cert(new String(Base64.encode(certificate.getEncoded())));
        } catch (CertificateEncodingException e) {
            log.error("Failed to encode certificate for fingerprint " + fingerprint, e);
            return false;
        }
    }
    final String username = certificateData.getUsername();
    final String serialNo = CertTools.getSerialNumberAsString(certificate);
    final String msg = INTRES.getLocalizedMessage("store.storecert", username, fingerprint,
            certificateData.getSubjectDN(), certificateData.getIssuerDN(), serialNo);
    Map<String, Object> details = new LinkedHashMap<String, Object>();
    details.put("msg", msg);
    final String caId = String.valueOf(CertTools.getIssuerDN(certificate).hashCode());
    logSession.log(EventTypes.CERT_STORED, EventStatus.SUCCESS, ModuleTypes.CERTIFICATE, ServiceTypes.CORE,
            authenticationToken.toString(), caId, serialNo, username, details);
    return true;
}

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

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Workspace createWorkspace(String wskey, String name, String type) throws CoreServiceException,
        KeyAlreadyExistsException, AccessDeniedException, AliasAlreadyExistsException {
    WorkspaceAlias alias = new WorkspaceAlias();
    em.persist(alias);//from  ww w.j  a  va  2 s .c  o m
    return createWorkspace(wskey, alias.getValue(), name, type);
}

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

/**
 * {@inheritDoc}//www. j  a  v  a2  s. co  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void clear(FxTreeMode mode) throws FxApplicationException {
    Connection con = null;
    try {
        con = Database.getDbConnection();
        UserTicket ticket = FxContext.getUserTicket();
        if (FxContext.get().getRunAsSystem() || ticket.isGlobalSupervisor())
            StorageManager.getTreeStorage().clearTree(con, contentEngine, mode);
        else
            throw new FxApplicationException("ex.tree.clear.notAllowed", mode.name());
        FxContext.get().setTreeWasModified();
    } catch (FxApplicationException ae) {
        EJBUtils.rollback(ctx);
        throw ae;
    } catch (Throwable t) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(LOG, t, "FxTree.err.clear.failed", mode);
    } finally {
        Database.closeObjects(TreeEngineBean.class, con, null);
    }
}

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

/**
 * {@inheritDoc}//w  w w  . j a  v a2s.c  o  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void clear(long id) throws FxApplicationException {
    Connection con = null;
    PreparedStatement stmt = null;
    final Briefcase br = load(id);
    checkEditBriefcase(br);
    try {
        con = Database.getDbConnection();
        stmt = con.prepareStatement("DELETE FROM " + TBL_BRIEFCASE_DATA_ITEM + " WHERE briefcase_id=?");
        stmt.setLong(1, id);
        stmt.executeUpdate();
        stmt.close();
        stmt = con.prepareStatement("DELETE FROM " + TBL_BRIEFCASE_DATA + " WHERE briefcase_id=?");
        stmt.setLong(1, id);
        stmt.executeUpdate();
    } catch (Exception e) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, e, "ex.briefcase.clear", br.getName(), e);
    } finally {
        closeObjects(BriefcaseEngineBean.class, con, stmt);
    }
}

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

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Workspace createWorkspace(String wskey, String alias, String name, String type)
        throws CoreServiceException, KeyAlreadyExistsException, AccessDeniedException,
        AliasAlreadyExistsException {/*  w w  w  .  j av a  2  s .co m*/
    LOGGER.log(Level.FINE, "creating workspace [" + wskey + "]");
    try {
        String caller = membership.getProfileKeyForConnectedIdentifier();
        List<String> subjects = membership.getConnectedIdentifierSubjects();
        authorisation.checkAuthentified(subjects);

        String members = UUID.randomUUID().toString();
        membership.createGroup(members, name + "'s Members",
                "Members of a workspace have all permissions on workspace content");
        membership.addMemberInGroup(members, caller);
        Map<String, List<String>> membersrules = authorisation.getPolicyRules(members);
        membersrules.put(MembershipService.MODERATORS_GROUP_KEY, Arrays.asList("read", "update"));
        membersrules.put(MembershipService.PUBLISHERS_GROUP_KEY, Arrays.asList("read"));
        membersrules.put(MembershipService.REVIEWERS_GROUP_KEY, Arrays.asList("read"));
        authorisation.setPolicyRules(members, membersrules);

        String head = UUID.randomUUID().toString();
        Collection collection = new Collection();
        collection.setId(UUID.randomUUID().toString());
        collection.setName("root");
        collection.setRoot(true);
        collection.setClock(1);
        em.persist(collection);

        Properties properties = new Properties();
        properties.put(WORKSPACE_REGISTRY_PROPERTY_KEY, wskey);
        registry.register(head, collection.getObjectIdentifier(), caller, properties);
        indexing.index(head);

        Map<String, List<String>> rules = new HashMap<String, List<String>>();
        rules.put(members, Arrays.asList("read", "create", "update", "delete", "download"));
        rules.put(MembershipService.MODERATORS_GROUP_KEY, Arrays.asList("read", "update", "download"));
        rules.put(MembershipService.PUBLISHERS_GROUP_KEY, Arrays.asList("read", "download"));
        rules.put(MembershipService.REVIEWERS_GROUP_KEY, Arrays.asList("read", "download"));
        authorisation.createPolicy(head, members);
        authorisation.setPolicyRules(head, rules);

        if (Arrays.asList(RESERVED_ALIASES).contains(alias)) {
            throw new CoreServiceException(alias + " is reserved and cannot be used as an alias");
        }

        List<Workspace> results = em.createNamedQuery("findWorkspaceByAlias", Workspace.class)
                .setParameter("alias", alias).getResultList();
        if (!results.isEmpty()) {
            ctx.setRollbackOnly();
            throw new AliasAlreadyExistsException(
                    "a workspace with alias [" + alias + "] already exists in storage");
        }
        PathBuilder palias;
        try {
            palias = PathBuilder.fromPath(alias);
            if (palias.isRoot() || palias.depth() > 1) {
                throw new InvalidPathException("incorrect depth for an alias path");
            }
        } catch (InvalidPathException e) {
            LOGGER.log(Level.SEVERE, "invalid alias for workspace", e);
            throw new CoreServiceException("alias is invalid", e);
        }
        String id = UUID.randomUUID().toString();
        Workspace workspace = new Workspace();
        workspace.setId(id);
        workspace.setKey(wskey);
        workspace.setAlias(palias.part());
        workspace.setName(name);
        workspace.setType(type);
        workspace.setHead(head);
        workspace.setChanged(true);
        workspace.setMembers(members);
        em.persist(workspace);

        registry.register(wskey, workspace.getObjectIdentifier(), caller);

        Map<String, List<String>> wsrules = new HashMap<String, List<String>>();
        wsrules.put(members, Collections.singletonList("read"));
        wsrules.put(MembershipService.UNAUTHENTIFIED_IDENTIFIER, Collections.singletonList("read"));
        wsrules.put(MembershipService.MODERATORS_GROUP_KEY,
                Arrays.asList("read", "create", "update", "delete"));
        wsrules.put(MembershipService.PUBLISHERS_GROUP_KEY, Arrays.asList("read"));
        wsrules.put(MembershipService.REVIEWERS_GROUP_KEY, Arrays.asList("read"));
        authorisation.createPolicy(wskey, caller);
        authorisation.setPolicyRules(wskey, wsrules);

        indexing.index(wskey);

        ArgumentsBuilder argsBuilder = new ArgumentsBuilder(1).addArgument("ws-alias", alias);
        notification.throwEvent(wskey, caller, Workspace.OBJECT_TYPE,
                OrtolangEvent.buildEventType(CoreService.SERVICE_NAME, Workspace.OBJECT_TYPE, "create"),
                argsBuilder.build());
        argsBuilder.addArgument("key", head).addArgument("path", "/");
        notification.throwEvent(wskey, caller, Workspace.OBJECT_TYPE,
                OrtolangEvent.buildEventType(CoreService.SERVICE_NAME, Collection.OBJECT_TYPE, "create"),
                argsBuilder.build());

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

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

/**
 * {@inheritDoc}//from w  w  w  .  j ava2s .  com
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public FxPK save(FxContent content) throws FxApplicationException {
    content.checkForceSystemPropertyPermissions();
    Connection con = null;
    PreparedStatement ps = null;
    FxPK pk = null;
    FxScriptEvent beforeAssignmentScript, afterAssignmentScript;
    try {
        FxEnvironment env = CacheAdmin.getEnvironment();
        FxPermissionUtils.checkMandatorExistance(content.getMandatorId());
        FxPermissionUtils.checkTypeAvailable(content.getTypeId(), false);
        ContentStorage storage = StorageManager.getContentStorage(content.getPk().getStorageMode());
        con = Database.getDbConnection();

        //security check start
        FxType type = env.getType(content.getTypeId());
        Step step = env.getStep(content.getStepId());
        UserTicket ticket = FxContext.getUserTicket();
        if (content.getPk().isNew()) {
            FxPermissionUtils.checkPermission(ticket, ticket.getUserId(), ACLPermission.CREATE, type,
                    step.getAclId(), content.getAclIds(), true);
            beforeAssignmentScript = FxScriptEvent.BeforeAssignmentDataCreate;
            afterAssignmentScript = FxScriptEvent.AfterAssignmentDataCreate;
        } else {
            FxPermissionUtils.checkPermission(ticket, ACLPermission.EDIT,
                    getContentSecurityInfo(content.getPk()), true);
            beforeAssignmentScript = FxScriptEvent.BeforeAssignmentDataSave;
            afterAssignmentScript = FxScriptEvent.AfterAssignmentDataSave;
        }
        if (type.isUsePropertyPermissions() && !ticket.isGlobalSupervisor() && content.getPk().isNew())
            FxPermissionUtils.checkPropertyPermissions(content, ACLPermission.CREATE);
        //security check end

        content = prepareSave(con, storage, content);

        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(beforeAssignmentScript)) {
                if (binding == null)
                    binding = new FxScriptBinding();
                binding.setVariable("assignment", as);
                for (long script : as.getScriptMapping(beforeAssignmentScript)) {
                    binding.setVariable("content", content);
                    Object result = scripting.runScript(script, binding).getResult();
                    if (result != null && result instanceof FxContent) {
                        content = (FxContent) result;
                    }
                }
            }
        }
        //scripting before end
        if (content.getPk().isNew() || content.isForcePkOnCreate()) {
            final Long contentId = content.getValue(FxLargeNumber.class, "/ID").getBestTranslation();
            pk = storage.contentCreate(con, env, null,
                    content.isForcePkOnCreate() && contentId != -1 ? contentId
                            : seq.getId(FxSystemSequencer.CONTENT),
                    content);
            if (LOG.isDebugEnabled())
                LOG.debug("creating new content for type "
                        + CacheAdmin.getEnvironment().getType(content.getTypeId()).getName());
        } else {
            boolean newVersion = false;
            if (type.isAutoVersion() && !FxContext.preventAutoVersioning()) {
                content.getRootGroup().removeEmptyEntries();
                content.compact();
                FxCachedContent cachedContent = CacheAdmin.getCachedContent(content.getPk());
                FxContent orgContent;
                if (cachedContent != null)
                    orgContent = cachedContent.getContent();
                else
                    orgContent = storage.contentLoad(con, content.getPk(), CacheAdmin.getEnvironment(), null);
                FxDelta delta = FxDelta.processDelta(orgContent, content);
                newVersion = delta.isDataChanged();
            }
            if (newVersion)
                pk = storage.contentCreateVersion(con, CacheAdmin.getEnvironment(), null, content);
            else
                pk = storage.contentSave(con, env, null, content,
                        EJBLookup.getConfigurationEngine().get(SystemParameters.TREE_FQN_PROPERTY));
        }
        //scripting after start
        //assignment scripting
        if (type.hasScriptedAssignments()) {
            binding = new FxScriptBinding();
            binding.setVariable("pk", pk);
            for (FxAssignment as : type.getScriptedAssignments(afterAssignmentScript)) {
                binding.setVariable("assignment", as);
                for (long script : as.getScriptMapping(afterAssignmentScript)) {
                    scripting.runScript(script, binding);
                }
            }
        }
        //type scripting
        typeScripts = env.getType(content.getTypeId()).getScriptMapping(
                content.getPk().isNew() ? FxScriptEvent.AfterContentCreate : 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 (FxNotFoundException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        //            if (Database.isUniqueConstraintViolation(e))
        //                throw new FxEntryExistsException("ex.structure.property.exists", property.getName(), (parentXPath.length() == 0 ? "/" : parentXPath));
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } catch (FxInvalidParameterException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } catch (FxCreateException e) {
        EJBUtils.rollback(ctx);
        throw e;
    } catch (FxNoAccessException e) {
        EJBUtils.rollback(ctx);
        throw e;
    } catch (Throwable t) {
        EJBUtils.rollback(ctx);
        if (t instanceof FxApplicationException)
            throw new FxCreateException(t); //no logging
        else
            throw new FxCreateException(LOG, t);
    } finally {
        Database.closeObjects(ContentEngineBean.class, con, ps);
        if (ctx.getRollbackOnly()) {
            FxBinaryUtils.removeTXFiles();
        } else
            FxBinaryUtils.resetTXFiles();
        if (!ctx.getRollbackOnly() && pk != null)
            CacheAdmin.expireCachedContent(pk.getId());
    }
}

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

/**
 * {@inheritDoc}//from  www  . j  a v a 2  s  .c  o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void updateScriptInfo(FxScriptInfoEdit script) throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptManagement);
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    boolean success = false;
    try {
        String code = "";
        if (script.getCode() != null)
            code = script.getCode();
        // Obtain a database connection
        con = Database.getDbConnection();
        //                                          1       2       3       4    5         6              7
        sql = "UPDATE " + TBL_SCRIPTS + " SET SNAME=?,SDESC=?,SDATA=?,STYPE=?,ACTIVE=?,IS_CACHED=? WHERE ID=?";
        ps = con.prepareStatement(sql);
        ps.setString(1, script.getName());
        ps.setString(2, script.getDescription());
        StorageManager.setBigString(ps, 3, code);
        ps.setLong(4, script.getEvent().getId());
        ps.setBoolean(5, script.isActive());
        ps.setBoolean(6, script.isCached());
        ps.setLong(7, script.getId());
        ps.executeUpdate();
        // remove script from cache if necessary
        if (FxSharedUtils.isGroovyScript(script.getName()) && !script.isCached())
            LocalScriptingCache.groovyScriptCache.remove(script.getId());
        success = true;
    } catch (SQLException exc) {
        throw new FxUpdateException(LOG, exc, "ex.scripting.update.failed", script.getName(), exc.getMessage());
    } finally {
        Database.closeObjects(ScriptingEngineBean.class, con, ps);
        if (!success)
            EJBUtils.rollback(ctx);
        else
            StructureLoader.reloadScripting(FxContext.get().getDivisionId());
    }
}