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.cesecore.keys.token.CryptoTokenManagementSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override//from  ww w  .jav  a 2  s.c  o  m
public void removeKeyPairPlaceholder(final AuthenticationToken authenticationToken, final int cryptoTokenId,
        final String alias) throws AuthorizationDeniedException, InvalidKeyException {
    assertAuthorization(authenticationToken, cryptoTokenId,
            CryptoTokenRules.REMOVE_KEYS.resource() + "/" + cryptoTokenId);
    final CryptoToken cryptoToken = getCryptoTokenAndAssertExistence(cryptoTokenId);

    boolean removed = false;
    final Properties props = new Properties();
    props.putAll(cryptoToken.getProperties());
    final String placeholdersString = props.getProperty(CryptoToken.KEYPLACEHOLDERS_PROPERTY, "");
    final List<String> entries = new ArrayList<String>(
            Arrays.asList(placeholdersString.split("[" + CryptoToken.KEYPLACEHOLDERS_OUTER_SEPARATOR + "]")));
    final Iterator<String> iter = entries.iterator();
    while (iter.hasNext()) {
        final String entry = iter.next();
        if (entry.startsWith(alias + CryptoToken.KEYPLACEHOLDERS_INNER_SEPARATOR)) {
            iter.remove();
            removed = true;
        }
    }

    if (removed) {
        final String newValue = StringUtils.join(entries, CryptoToken.KEYPLACEHOLDERS_OUTER_SEPARATOR);
        props.setProperty(CryptoToken.KEYPLACEHOLDERS_PROPERTY, newValue);
        cryptoToken.setProperties(props);
    }

    // Check if alias is in use
    if (!removed) {
        throw new InvalidKeyException("Alias " + alias + " is not in use");
    }

    try {
        cryptoTokenSession.mergeCryptoToken(cryptoToken);
    } catch (CryptoTokenNameInUseException e) {
        throw new IllegalStateException(e); // We have not changed the name of the CrytpoToken here, so this should never happen
    }

    final Map<String, Object> details = new LinkedHashMap<String, Object>();
    details.put("msg", "Deleted key pair placeholder from CryptoToken " + cryptoTokenId);
    details.put("keyAlias", alias);
    securityEventsLoggerSession.log(EventTypes.CRYPTOTOKEN_DELETE_ENTRY, EventStatus.SUCCESS,
            ModuleTypes.CRYPTOTOKEN, ServiceTypes.CORE, authenticationToken.toString(),
            String.valueOf(cryptoTokenId), null, null, details);
}

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

/**
 * {@inheritDoc}/*ww  w  .  j av a  2s  .co  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void populate(FxTreeMode mode, int maxNodeChildren) throws FxApplicationException {

    Connection con = null;
    try {
        con = Database.getDbConnection();
        StorageManager.getTreeStorage().populate(con, seq, contentEngine, mode, maxNodeChildren);
        FxContext.get().setTreeWasModified();
    } catch (FxApplicationException ae) {
        EJBUtils.rollback(ctx);
        throw ae;
    } catch (Throwable t) {
        EJBUtils.rollback(ctx);
        throw new FxLoadException(LOG, t, "ex.tree.populate", mode, t.getMessage());
    } finally {
        Database.closeObjects(TreeEngineBean.class, con, null);
    }
}

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

/**
 * {@inheritDoc}/*from  w w w .j a v  a 2 s . c  o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void removeTypeScriptMapping(long scriptId, long typeId) 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=?";
        ps = con.prepareStatement(sql);
        ps.setLong(1, scriptId);
        ps.setLong(2, typeId);
        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.ejbca.core.ejb.ca.store.CertificateStoreSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override/*w  w w.j a  v  a 2s  . c  o m*/
public boolean setStatus(String fingerprint, int status) {
    return CertificateData.updateStatus(entityManager, fingerprint, status);
}

From source file:com.flexive.ejb.beans.structure.AssignmentEngineBean.java

/**
 * {@inheritDoc}/*from  ww  w  .  jav  a2  s .co  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long createGroup(FxGroupEdit group, String parentXPath) throws FxApplicationException {
    return createGroup(FxType.ROOT_ID, group, parentXPath);
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@RolesAllowed({ "org.nightlabs.jfire.store.editUnconfirmedProductType",
        "org.nightlabs.jfire.store.editConfirmedProductType" })
@Override/*  w  w  w.  ja  v a2 s  .  c  o m*/
public ProductTypeStatusHistoryItem setProductTypeStatus_saleable(ProductTypeID productTypeID, boolean saleable,
        boolean get, String[] fetchGroups, int maxFetchDepth) throws CannotMakeProductTypeSaleableException {
    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_saleable(User.getUser(pm, getPrincipal()), productType, saleable);

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

From source file:com.flexive.ejb.beans.structure.AssignmentEngineBean.java

/**
 * {@inheritDoc}/*from  w  w w .j  av  a2  s  . c o  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long createGroup(long typeId, FxGroupEdit group, String parentXPath) throws FxApplicationException {
    return createGroup(typeId, group, parentXPath, group.getName());
}

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

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void deleteWorkspace(String wskey)
        throws CoreServiceException, KeyNotFoundException, AccessDeniedException, WorkspaceReadOnlyException {
    deleteWorkspace(wskey, false);/*from  ww w . j  av  a2s .  co m*/
}

From source file:com.flexive.ejb.beans.structure.AssignmentEngineBean.java

/**
 * {@inheritDoc}/*from w w  w .j av  a 2s  . c o  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long createGroup(long typeId, FxGroupEdit group, String parentXPath, String assignmentAlias)
        throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.StructureManagement);
    Connection con = null;
    PreparedStatement ps = null;
    StringBuilder sql = new StringBuilder(2000);
    long newGroupId;
    long newAssignmentId;
    try {
        parentXPath = parentXPath.toUpperCase();
        assignmentAlias = assignmentAlias.toUpperCase();
        FxType type = CacheAdmin.getEnvironment().getType(typeId);
        FxAssignment tmp = type.getAssignment(parentXPath);
        if (tmp != null && tmp instanceof FxPropertyAssignment)
            throw new FxInvalidParameterException("ex.structure.assignment.noGroup", parentXPath);
        //parentXPath is valid, create the group, then assign it to root
        newGroupId = seq.getId(FxSystemSequencer.TYPEGROUP);
        con = Database.getDbConnection();
        ContentStorage storage = StorageManager.getContentStorage(type.getStorageMode());
        // do not allow to add mandatory groups (i.e. min multiplicity > 0) to types for which content exists
        if (storage.getTypeInstanceCount(con, typeId) > 0 && group.getMultiplicity().getMin() > 0) {
            throw new FxCreateException("ex.structure.group.creation.exisitingContentMultiplicityError",
                    group.getName(), group.getMultiplicity().getMin());
        }

        //create group
        sql.append("INSERT INTO ").append(TBL_STRUCT_GROUPS)
                .append("(ID,NAME,DEFMINMULT,DEFMAXMULT,MAYOVERRIDEMULT)VALUES(?,?,?,?,?)");
        ps = con.prepareStatement(sql.toString());
        ps.setLong(1, newGroupId);
        ps.setString(2, group.getName());
        ps.setInt(3, group.getMultiplicity().getMin());
        ps.setInt(4, group.getMultiplicity().getMax());
        ps.setBoolean(5, group.mayOverrideBaseMultiplicity());
        ps.executeUpdate();
        ps.close();
        sql.setLength(0);
        Database.storeFxString(new FxString[] { group.getLabel(), group.getHint() }, con, TBL_STRUCT_GROUPS,
                new String[] { "DESCRIPTION", "HINT" }, "ID", newGroupId);
        //calc new position
        sql.append("SELECT COALESCE(MAX(POS)+1,0) FROM ").append(TBL_STRUCT_ASSIGNMENTS)
                .append(" WHERE PARENTGROUP=? AND TYPEDEF=?");
        ps = con.prepareStatement(sql.toString());
        ps.setLong(1, (tmp == null ? FxAssignment.NO_PARENT : tmp.getId()));
        ps.setLong(2, typeId);
        ResultSet rs = ps.executeQuery();
        long pos = 0;
        if (rs != null && rs.next())
            pos = rs.getLong(1);
        ps.close();
        storeOptions(con, TBL_STRUCT_GROUP_OPTIONS, "ID", newGroupId, null, group.getOptions());
        sql.setLength(0);
        //create root assignment
        sql.append("INSERT INTO ").append(TBL_STRUCT_ASSIGNMENTS).
        //               1  2     3       4       5       6       7       8   9     10     11   12          13     14
                append("(ID,ATYPE,ENABLED,TYPEDEF,MINMULT,MAXMULT,DEFMULT,POS,XPATH,XALIAS,BASE,PARENTGROUP,AGROUP,GROUPMODE)"
                        + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        ps = con.prepareStatement(sql.toString());
        newAssignmentId = seq.getId(FxSystemSequencer.ASSIGNMENT);
        ps.setLong(1, newAssignmentId);
        ps.setInt(2, FxAssignment.TYPE_GROUP);
        ps.setBoolean(3, true);
        ps.setLong(4, typeId);
        ps.setInt(5, group.getMultiplicity().getMin());
        ps.setInt(6, group.getMultiplicity().getMax());
        if (group.getMultiplicity().isValid(group.getAssignmentDefaultMultiplicity())) {
            ps.setInt(7, group.getAssignmentDefaultMultiplicity());
        } else {
            //default is min(min,1).
            ps.setInt(7, group.getMultiplicity().getMin() > 1 ? group.getMultiplicity().getMin() : 1);
        }
        ps.setLong(8, pos);
        if (parentXPath == null || "/".equals(parentXPath))
            parentXPath = "";
        ps.setString(9, type.getName() + XPathElement.stripType(parentXPath) + "/" + assignmentAlias);
        ps.setString(10, assignmentAlias);
        ps.setNull(11, java.sql.Types.NUMERIC);
        ps.setLong(12, (tmp == null ? FxAssignment.NO_PARENT : tmp.getId()));
        ps.setLong(13, newGroupId);
        ps.setInt(14, group.getAssignmentGroupMode().getId());
        ps.executeUpdate();
        Database.storeFxString(new FxString[] { group.getLabel(), group.getHint() }, con,
                TBL_STRUCT_ASSIGNMENTS, new String[] { "DESCRIPTION", "HINT" }, "ID", newAssignmentId);
        StructureLoader.reloadAssignments(FxContext.get().getDivisionId());
        htracker.track(type, "history.assignment.createGroup", group.getName(), type.getId(), type.getName());
        if (type.getId() != FxType.ROOT_ID)
            createInheritedAssignments(CacheAdmin.getEnvironment().getAssignment(newAssignmentId), con, sql,
                    type.getDerivedTypes());
    } catch (FxNotFoundException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } catch (FxLoadException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } catch (SQLException e) {
        final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(e);
        EJBUtils.rollback(ctx);
        if (uniqueConstraintViolation)
            throw new FxEntryExistsException("ex.structure.group.exists", group.getName(),
                    (parentXPath.length() == 0 ? "/" : parentXPath));
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(AssignmentEngineBean.class, con, ps);
    }
    return newAssignmentId;
}

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

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void deleteWorkspace(String wskey, boolean force)
        throws CoreServiceException, KeyNotFoundException, AccessDeniedException, WorkspaceReadOnlyException {
    LOGGER.log(Level.FINE, "deleting workspace [" + wskey + "]");
    try {/*from  w  w w .j  a  va2 s  .  c  o m*/
        String caller = membership.getProfileKeyForConnectedIdentifier();
        List<String> subjects = membership.getConnectedIdentifierSubjects();

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

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

        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 (!force) {
            if (applyReadOnly(caller, subjects, workspace)) {
                throw new WorkspaceReadOnlyException(
                        "unable to delete workspace with key [" + wskey + "] because it is read only");
            }
            if (workspace.getType().equals(WorkspaceType.SYSTEM.name())) {
                throw new CoreServiceException("unable to delete with key [" + wskey
                        + "] because it is of type: " + WorkspaceType.SYSTEM.name());
            }
            String current = workspace.getHead();
            while (current != null) {
                String parent = registry.getParent(current);
                if (parent != null && registry.getPublicationStatus(parent)
                        .equals(OrtolangObjectState.Status.PUBLISHED.value())) {
                    throw new CoreServiceException("unable to delete workspace with key [" + wskey
                            + "] because it has a published version");
                }
                current = parent;
            }
        }
        workspace.setAlias(null);
        em.merge(workspace);

        membership.deleteGroup(workspace.getMembers());
        registry.delete(wskey);
        indexing.remove(wskey);

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