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:fr.ortolang.diffusion.core.CoreServiceBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Collection createCollection(String wskey, String path) throws CoreServiceException, KeyNotFoundException,
        InvalidPathException, AccessDeniedException, PathNotFoundException, PathAlreadyExistsException,
        WorkspaceReadOnlyException, KeyAlreadyExistsException {
    String key = UUID.randomUUID().toString();
    try {/*from ww  w  .ja  va 2 s  . c  o  m*/
        return createCollection(wskey, key, path);
    } catch (KeyAlreadyExistsException e) {
        ctx.setRollbackOnly();
        LOGGER.log(Level.WARNING, "the generated key already exists : " + key);
        throw e;
    }
}

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

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Collection createCollection(String wskey, String key, String path)
        throws CoreServiceException, KeyAlreadyExistsException, InvalidPathException, AccessDeniedException,
        PathNotFoundException, PathAlreadyExistsException, WorkspaceReadOnlyException {
    LOGGER.log(Level.FINE,//from   ww w  . ja  v a2s .c  o  m
            "creating collection with key [" + key + "] into workspace [" + wskey + "] at path [" + path + "]");
    try {
        PathBuilder npath = PathBuilder.fromPath(path);
        if (npath.isRoot()) {
            throw new InvalidPathException("forbidden to create the root collection");
        }
        PathBuilder ppath = npath.clone().parent();

        String caller = membership.getProfileKeyForConnectedIdentifier();
        List<String> subjects = membership.getConnectedIdentifierSubjects();
        authorisation.checkAuthentified(subjects);
        LOGGER.log(Level.FINEST, "user [" + caller + "] is authentified");

        OrtolangObjectIdentifier wsidentifier = registry.lookup(wskey);
        checkObjectType(wsidentifier, Workspace.OBJECT_TYPE);
        LOGGER.log(Level.FINEST, "workspace with key [" + wskey + "] exists");

        Workspace ws = em.find(Workspace.class, wsidentifier.getId());
        if (ws == null) {
            throw new CoreServiceException(
                    "unable to load workspace with id [" + wsidentifier.getId() + "] from storage");
        }
        if (applyReadOnly(caller, subjects, ws)) {
            throw new WorkspaceReadOnlyException("unable to create collection in workspace with key [" + wskey
                    + "] because it is read only");
        }
        ws.setKey(wskey);
        LOGGER.log(Level.FINEST, "workspace loaded");

        authorisation.checkPermission(ws.getHead(), subjects, "create");
        LOGGER.log(Level.FINEST,
                "user [" + caller + "] has 'create' permission on the head collection of this workspace");

        Collection parent = loadCollectionAtPath(ws.getHead(), ppath, ws.getClock());
        LOGGER.log(Level.FINEST, "parent collection loaded for path " + ppath.build());

        if (parent.containsElementName(npath.part())) {
            throw new PathAlreadyExistsException(npath.build());
        }

        String id = UUID.randomUUID().toString();
        Collection collection = new Collection();
        collection.setId(id);
        collection.setKey(key);
        collection.setName(npath.part());
        collection.setRoot(false);
        collection.setClock(ws.getClock());
        em.persist(collection);
        LOGGER.log(Level.FINEST, "collection [" + key + "] created");

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

        authorisation.clonePolicy(key, ws.getHead());
        LOGGER.log(Level.FINEST, "security policy cloned from head collection to key [" + key + "]");

        parent.addElement(new CollectionElement(Collection.OBJECT_TYPE, collection.getName(),
                System.currentTimeMillis(), 0, Collection.MIME_TYPE, key));
        em.merge(parent);
        registry.update(parent.getKey());
        LOGGER.log(Level.FINEST, "collection [" + key + "] added to parent [" + parent.getKey() + "]");

        ws.setChanged(true);
        em.merge(ws);
        registry.update(ws.getKey());
        LOGGER.log(Level.FINEST, "workspace set changed");

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

        return collection;
    } catch (KeyLockedException | KeyNotFoundException | RegistryServiceException | NotificationServiceException
            | IdentifierAlreadyRegisteredException | AuthorisationServiceException | MembershipServiceException
            | IndexingServiceException e) {
        LOGGER.log(Level.SEVERE, "unexpected error occurred during collection creation", e);
        ctx.setRollbackOnly();
        throw new CoreServiceException(
                "unable to create collection into workspace [" + wskey + "] at path [" + path + "]", e);
    }
}

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

/**
 * {@inheritDoc}/*  ww  w.  j  a  v a2 s. c  om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void fixContactData() throws FxApplicationException {
    List<Account> acct = loadAll(null, null, null, null, null, null, null, null, 0, Integer.MAX_VALUE);
    FxContext.get().runAsSystem();
    try {
        for (Account a : acct) {
            if (a.getContactData().getId() == -1) {
                FxContent contactData = co
                        .initialize(CacheAdmin.getEnvironment().getType(FxType.CONTACTDATA).getId());
                contactData.setAclId(ACL.ACL_CONTACTDATA);
                contactData.setValue("/SURNAME", new FxString(false, a.getName()));
                //contactData.setValue("/DISPLAYNAME", new FxString(true, a.getName()));
                contactData.setValue("/EMAIL", new FxString(false, a.getEmail()));
                FxPK contactDataPK = co.save(contactData);
                update(a.getId(), null, null, null, null, null, null, null, null, null, null, null, null,
                        contactDataPK.getId());
            }
        }
    } finally {
        FxContext.get().stopRunAsSystem();
    }
}

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

/**
 * {@inheritDoc}/*from   www  .j ava2 s  .c om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void assignPhrase(long assignmentOwner, long nodeId, long nodeMandator, long phraseId,
        long phraseMandator, long pos, boolean checkPositioning)
        throws FxNotFoundException, FxNoAccessException {
    assignPhrase(FxPhraseCategorySelection.CATEGORY_DEFAULT, assignmentOwner, nodeId, nodeMandator, phraseId,
            phraseMandator, pos, checkPositioning);
}

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

/**
 * {@inheritDoc}/*w  w w.  j av  a2s .  c  o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void assignPhrase(int category, long assignmentOwner, long nodeId, long nodeMandator, long phraseId,
        long phraseMandator, long pos, boolean checkPositioning)
        throws FxNotFoundException, FxNoAccessException {
    checkMandatorAccess(assignmentOwner, FxContext.getUserTicket());
    Connection con = null;
    PreparedStatement ps = null;
    try {
        // Obtain a database connection
        con = Database.getDbConnection();

        ps = con.prepareStatement("SELECT ID FROM " + TBL_PHRASE_TREE + " WHERE ID=? AND MANDATOR=? AND CAT=?");
        ps.setLong(1, nodeId);
        ps.setLong(2, nodeMandator);
        ps.setInt(3, category);
        ResultSet rs = ps.executeQuery();
        if (rs == null || !(rs.next()))
            throw new FxNotFoundException("ex.phrases.node.notFound.id", nodeId, nodeMandator);
        ps.close();
        ps = con.prepareStatement("SELECT POS FROM " + TBL_PHRASE_MAP
                + " WHERE MANDATOR=? AND NODEID=? AND NODEMANDATOR=? AND PHRASEID=? AND PMANDATOR=? AND CAT=? AND DIRECT=TRUE");
        ps.setLong(1, assignmentOwner);
        ps.setLong(2, nodeId);
        ps.setLong(3, nodeMandator);
        ps.setLong(4, phraseId);
        ps.setLong(5, phraseMandator);
        ps.setInt(6, category);
        rs = ps.executeQuery();
        if (rs != null && rs.next()) {
            long orgPos = rs.getLong(1);
            if (!rs.wasNull()) {
                if (orgPos == pos)
                    return;
                if (pos <= 1 && orgPos == 1)
                    return; //already at the top
                updatePhrasePosition(con, category, assignmentOwner, nodeId, nodeMandator, phraseId,
                        phraseMandator, pos, checkPositioning);
                return;
            }
        }
        //insert
        ps.close();
        //remove from phrase map in case it is already there as indirect
        ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE_MAP
                + " WHERE MANDATOR=? AND CAT=? AND NODEID=? AND NODEMANDATOR=? AND PHRASEID=? AND PMANDATOR=?");
        ps.setLong(1, assignmentOwner);
        ps.setInt(2, category);
        ps.setLong(3, nodeId);
        ps.setLong(4, nodeMandator);
        ps.setLong(5, phraseId);
        ps.setLong(6, phraseMandator);
        ps.executeUpdate();
        ps.close();
        ps = con.prepareStatement("INSERT INTO " + TBL_PHRASE_MAP
                + "(MANDATOR,CAT,NODEID,NODEMANDATOR,PHRASEID,PMANDATOR,POS,DIRECT)VALUES(?,?,?,?,?,?,?,?)");
        ps.setLong(1, assignmentOwner);
        ps.setInt(2, category);
        ps.setLong(3, nodeId);
        ps.setLong(4, nodeMandator);
        ps.setLong(5, phraseId);
        ps.setLong(6, phraseMandator);
        ps.setLong(7, pos);
        ps.setBoolean(8, true);
        ps.executeUpdate();
        if (checkPositioning)
            updatePhrasePosition(con, category, assignmentOwner, nodeId, nodeMandator, phraseId, phraseMandator,
                    pos, checkPositioning);
        rebuildPhraseChildMapping(con, assignmentOwner, category, phraseId, phraseMandator);
    } 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.AccountEngineBean.java

/**
 * {@inheritDoc}/*from  w w w. j  ava2  s .c  om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public String generateRestToken() throws FxApplicationException {
    final UserTicket ticket = FxContext.getUserTicket();

    if (ticket.isGuest()) {
        throw new FxUpdateException("ex.account.rest.generate.guest");
    }

    if (!ticket.isInRole(Role.RestApiAccess)) {
        throw new FxNoAccessException("ex.account.rest.generate.role", ticket.getLoginName(),
                Role.RestApiAccess.getName());
    }

    Connection con = null;
    PreparedStatement stmt = null;
    final DBStorage storage = StorageManager.getStorageImpl();
    try {
        con = Database.getDbConnection();
        stmt = con.prepareStatement(
                "UPDATE " + DatabaseConst.TBL_ACCOUNTS + " SET REST_TOKEN=?, REST_EXPIRES=? WHERE ID=?");

        final String token = RandomStringUtils.randomAlphanumeric(REST_TOKEN_LENGTH);
        stmt.setString(1, token);
        stmt.setLong(2, System.currentTimeMillis() + REST_TOKEN_EXPIRY);
        stmt.setLong(3, ticket.getUserId());

        stmt.executeUpdate();

        return token;
    } catch (SQLException e) {
        if (storage.isUniqueConstraintViolation(e)) {
            // try again
            Database.closeObjects(AccountEngineBean.class, con, stmt);
            generateRestToken();
        }
        throw new FxDbException(e);
    } finally {
        Database.closeObjects(AccountEngineBean.class, con, stmt);
    }
}

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

/**
 * {@inheritDoc}/*from  w w  w .j a  v  a 2s  .c  o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void loginByRestToken(String token) throws FxApplicationException {
    Connection con = null;
    PreparedStatement stmt = null;

    if (token == null || token.length() != REST_TOKEN_LENGTH) {
        throw new FxInvalidParameterException("token", "ex.account.rest.token.invalid", token);
    }

    try {
        con = Database.getDbConnection();
        stmt = con.prepareStatement(
                "SELECT LOGIN_NAME, REST_EXPIRES FROM " + DatabaseConst.TBL_ACCOUNTS + " WHERE REST_TOKEN=?");
        stmt.setString(1, token);

        final ResultSet rs = stmt.executeQuery();

        if (rs.next()) {
            final String loginName = rs.getString(1);
            final long expires = rs.getLong(2);
            if (expires < System.currentTimeMillis()) {
                throw new FxRestApiTokenExpiredException(token);
            }

            // request-only "login" (not tracked, just replace the user ticket)
            FxContext.startRunningAsSystem();
            try {
                FxContext.get().overrideTicket(UserTicketStore.getUserTicket(loginName));
            } finally {
                FxContext.stopRunningAsSystem();
            }
        } else {
            // token invalid (or overwritten by a new token)
            throw new FxRestApiTokenExpiredException(token);
        }
    } catch (SQLException e) {
        throw new FxDbException(e);
    } finally {
        Database.closeObjects(AccountEngineBean.class, con, stmt);
    }
}

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

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Collection readCollection(String key)
        throws CoreServiceException, KeyNotFoundException, AccessDeniedException {
    LOGGER.log(Level.FINE, "reading collection with key [" + key + "]");
    try {//  w  w w.  j  av a2 s .  co  m
        List<String> subjects = membership.getConnectedIdentifierSubjects();

        OrtolangObjectIdentifier cidentifier = registry.lookup(key);
        checkObjectType(cidentifier, Collection.OBJECT_TYPE);
        authorisation.checkPermission(key, subjects, "read");

        Collection collection = em.find(Collection.class, cidentifier.getId());
        if (collection == null) {
            throw new CoreServiceException(
                    "unable to load collection with id [" + cidentifier.getId() + "] from storage");
        }
        collection.setKey(key);

        return collection;
    } catch (MembershipServiceException | AuthorisationServiceException | RegistryServiceException e) {
        LOGGER.log(Level.SEVERE, "unexpected error while reading collection", e);
        throw new CoreServiceException("unable to read collection with key [" + key + "]", e);
    }
}

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

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public String resolvePathFromCollection(String key, String path) throws KeyNotFoundException,
        CoreServiceException, AccessDeniedException, InvalidPathException, PathNotFoundException {
    LOGGER.log(Level.FINE, "reading collection with key [" + key + "]");
    try {//from  www.  j  ava 2  s . co m
        List<String> subjects = membership.getConnectedIdentifierSubjects();

        OrtolangObjectIdentifier cidentifier = registry.lookup(key);
        checkObjectType(cidentifier, Collection.OBJECT_TYPE);

        Collection collection = em.find(Collection.class, cidentifier.getId());
        if (collection == null) {
            throw new CoreServiceException(
                    "unable to load collection with id [" + cidentifier.getId() + "] from storage");
        }
        collection.setKey(key);

        PathBuilder pathTarget = PathBuilder.fromPath(path);
        PathBuilder parentTarget = pathTarget.clone().parent();

        Collection parent = readCollectionAtPath(key, parentTarget);

        String partTarget = pathTarget.part();

        CollectionElement element = parent.findElementByName(partTarget);
        if (element == null) {
            throw new PathNotFoundException(path);
        }
        authorisation.checkPermission(element.getKey(), subjects, "read");

        return element.getKey();
    } catch (MembershipServiceException | AuthorisationServiceException | RegistryServiceException e) {
        LOGGER.log(Level.SEVERE, "unexpected error while reading collection", e);
        throw new CoreServiceException(
                "unable to resolve path " + path + " from collection with key [" + key + "]", e);
    }
}

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

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void moveElements(String wskey, List<String> sources, String destination)
        throws PathAlreadyExistsException, PathNotFoundException, RegistryServiceException,
        InvalidPathException, AccessDeniedException, WorkspaceReadOnlyException, CoreServiceException,
        KeyNotFoundException {// w  w w  . ja  va2s . co  m
    if (!sources.isEmpty()) {
        try {
            String ppath = PathBuilder.fromPath(sources.get(0)).parent().build();
            for (String source : sources) {
                String sppath = PathBuilder.fromPath(source).parent().build();
                if (!ppath.equals(sppath)) {
                    throw new InvalidPathException("unable to move elements from different collections");
                }
            }
            String parentKey = resolveWorkspacePath(wskey, "head", ppath);
            OrtolangObjectIdentifier identifier = registry.lookup(parentKey);
            checkObjectType(identifier, Collection.OBJECT_TYPE);
            Collection collection = readCollection(parentKey);

            for (String source : sources) {
                CollectionElement collectionElement = collection
                        .findElementByName(PathBuilder.fromPath(source).part());
                switch (collectionElement.getType()) {
                case DataObject.OBJECT_TYPE:
                    moveDataObject(wskey, source,
                            destination + PathBuilder.PATH_SEPARATOR + collectionElement.getName());
                    break;
                case Collection.OBJECT_TYPE:
                    moveCollection(wskey, source,
                            destination + PathBuilder.PATH_SEPARATOR + collectionElement.getName());
                    break;
                case Link.OBJECT_TYPE:
                    moveLink(wskey, source,
                            destination + PathBuilder.PATH_SEPARATOR + collectionElement.getName());
                }
            }
        } catch (AccessDeniedException | CoreServiceException | RegistryServiceException
                | WorkspaceReadOnlyException | InvalidPathException | PathNotFoundException
                | KeyNotFoundException e) {
            ctx.setRollbackOnly();
            LOGGER.log(Level.SEVERE, "unexpected error while moving workspace elements", e);
            throw e;
        } catch (PathAlreadyExistsException e) {
            ctx.setRollbackOnly();
            throw e;
        }
    }
}