Example usage for javax.transaction UserTransaction begin

List of usage examples for javax.transaction UserTransaction begin

Introduction

In this page you can find the example usage for javax.transaction UserTransaction begin.

Prototype

void begin() throws NotSupportedException, SystemException;

Source Link

Document

Create a new transaction and associate it with the current thread.

Usage

From source file:org.alfresco.web.bean.BrowseBean.java

/**
 * Query a list of nodes for the specified parent node Id
 *
 * @param parentNodeId     Id of the parent node or null for the root node
 *///w w w  .  j  a va 2  s . co  m
private void queryBrowseNodes(String parentNodeId) {
    long startTime = 0;
    if (logger.isDebugEnabled())
        startTime = System.currentTimeMillis();

    UserTransaction tx = null;
    try {
        FacesContext context = FacesContext.getCurrentInstance();
        tx = Repository.getUserTransaction(context, true);
        tx.begin();

        NodeRef parentRef;
        if (parentNodeId == null) {
            // no specific parent node specified - use the root node
            parentRef = this.getNodeService().getRootNode(Repository.getStoreRef());
        } else {
            // build a NodeRef for the specified Id and our store
            parentRef = new NodeRef(Repository.getStoreRef(), parentNodeId);
        }

        List<FileInfo> children = null;
        FileFilterMode.setClient(Client.webclient);
        try {
            children = this.getFileFolderService().list(parentRef);
        } finally {
            FileFilterMode.clearClient();
        }

        this.containerNodes = new ArrayList<Node>(children.size());
        this.contentNodes = new ArrayList<Node>(children.size());

        // in case of dynamic config, only lookup once
        Set<NodeEventListener> nodeEventListeners = getNodeEventListeners();

        for (FileInfo fileInfo : children) {
            // create our Node representation from the NodeRef
            NodeRef nodeRef = fileInfo.getNodeRef();

            // find it's type so we can see if it's a node we are interested in
            QName type = this.getNodeService().getType(nodeRef);

            // make sure the type is defined in the data dictionary
            TypeDefinition typeDef = this.getDictionaryService().getType(type);

            if (typeDef != null) {
                MapNode node = null;

                // look for File content node
                if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT)) {
                    // create our Node representation
                    node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
                    setupCommonBindingProperties(node);

                    this.contentNodes.add(node);
                }
                // look for Space folder node
                else if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) == true && this
                        .getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) {
                    // create our Node representation
                    node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
                    node.addPropertyResolver("icon", this.resolverSpaceIcon);
                    node.addPropertyResolver("smallIcon", this.resolverSmallIcon);

                    this.containerNodes.add(node);
                }
                // look for File Link object node
                else if (ApplicationModel.TYPE_FILELINK.equals(type)) {
                    // create our File Link Node representation
                    node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
                    // only display the user has the permissions to navigate to the target of the link
                    NodeRef destRef = (NodeRef) node.getProperties().get(ContentModel.PROP_LINK_DESTINATION);
                    if (destRef != null && new Node(destRef).hasPermission(PermissionService.READ) == true) {
                        node.addPropertyResolver("url", this.resolverLinkUrl);
                        node.addPropertyResolver("downloadUrl", this.resolverLinkDownload);
                        node.addPropertyResolver("webdavUrl", this.resolverLinkWebdavUrl);
                        node.addPropertyResolver("cifsPath", this.resolverLinkCifsPath);
                        node.addPropertyResolver("fileType16", this.resolverFileType16);
                        node.addPropertyResolver("fileType32", this.resolverFileType32);
                        node.addPropertyResolver("lang", this.resolverLang);

                        this.contentNodes.add(node);
                    }
                } else if (ApplicationModel.TYPE_FOLDERLINK.equals(type)) {
                    // create our Folder Link Node representation
                    node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
                    // only display the user has the permissions to navigate to the target of the link
                    NodeRef destRef = (NodeRef) node.getProperties().get(ContentModel.PROP_LINK_DESTINATION);
                    if (destRef != null && new Node(destRef).hasPermission(PermissionService.READ) == true) {
                        node.addPropertyResolver("icon", this.resolverSpaceIcon);
                        node.addPropertyResolver("smallIcon", this.resolverSmallIcon);

                        this.containerNodes.add(node);
                    }
                }

                // inform any listeners that a Node wrapper has been created
                if (node != null) {
                    for (NodeEventListener listener : nodeEventListeners) {
                        listener.created(node, type);
                    }
                }
            } else {
                if (logger.isWarnEnabled())
                    logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type);
            }
        }

        // commit the transaction
        tx.commit();
    } catch (InvalidNodeRefException refErr) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF),
                new Object[] { refErr.getNodeRef() }), refErr);
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC),
                err.getMessage()), err);
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }

    if (logger.isDebugEnabled()) {
        long endTime = System.currentTimeMillis();
        logger.debug("Time to query and build map nodes: " + (endTime - startTime) + "ms");
    }
}

From source file:org.alfresco.web.bean.BrowseBean.java

/**
 * Search for a list of nodes using the specific search context
 *
 * @param searchContext    To use to perform the search
 *///from w  ww . java  2  s.co  m
private void searchBrowseNodes(SearchContext searchContext) {
    long startTime = 0;
    if (logger.isDebugEnabled())
        startTime = System.currentTimeMillis();

    // get the searcher object to build the query
    String query = searchContext.buildQuery(getMinimumSearchLength());
    if (query == null) {
        // failed to build a valid query, the user probably did not enter the
        // minimum text required to construct a valid search
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), MSG_SEARCH_MINIMUM),
                new Object[] { getMinimumSearchLength() }));
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        return;
    }

    // perform the search against the repo
    UserTransaction tx = null;
    ResultSet results = null;
    try {
        tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true);
        tx.begin();

        // build up the search parameters
        SearchParameters sp = new SearchParameters();
        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp.setQuery(query);
        sp.addStore(Repository.getStoreRef());

        // limit search results size as configured
        int searchLimit = Application.getClientConfig(FacesContext.getCurrentInstance()).getSearchMaxResults();
        if (searchLimit > 0) {
            sp.setLimitBy(LimitBy.FINAL_SIZE);
            sp.setLimit(searchLimit);
        }

        sp.setBulkFetchEnabled(
                Application.getClientConfig(FacesContext.getCurrentInstance()).isBulkFetchEnabled());

        results = this.getSearchService().query(sp);
        if (logger.isDebugEnabled())
            logger.debug("Search results returned: " + results.length());

        // create a list of items from the results
        this.containerNodes = new ArrayList<Node>(results.length());
        this.contentNodes = new ArrayList<Node>(results.length());
        if (results.length() != 0) {
            // in case of dynamic config, only lookup once
            Set<NodeEventListener> nodeEventListeners = getNodeEventListeners();

            for (ResultSetRow row : results) {
                NodeRef nodeRef = row.getNodeRef();

                if (this.getNodeService().exists(nodeRef)) {
                    // find it's type so we can see if it's a node we are interested in
                    QName type = this.getNodeService().getType(nodeRef);

                    // make sure the type is defined in the data dictionary
                    TypeDefinition typeDef = this.getDictionaryService().getType(type);

                    if (typeDef != null) {
                        MapNode node = null;

                        // look for Space or File nodes
                        if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER)
                                && this.getDictionaryService().isSubClass(type,
                                        ContentModel.TYPE_SYSTEM_FOLDER) == false) {
                            // create our Node representation
                            node = new MapNode(nodeRef, this.getNodeService(), false);

                            node.addPropertyResolver("path", this.resolverPath);
                            node.addPropertyResolver("displayPath", this.resolverDisplayPath);
                            node.addPropertyResolver("icon", this.resolverSpaceIcon);
                            node.addPropertyResolver("smallIcon", this.resolverSmallIcon);

                            this.containerNodes.add(node);
                        } else if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT)) {
                            // create our Node representation
                            node = new MapNode(nodeRef, this.getNodeService(), false);

                            setupCommonBindingProperties(node);

                            node.addPropertyResolver("path", this.resolverPath);
                            node.addPropertyResolver("displayPath", this.resolverDisplayPath);

                            this.contentNodes.add(node);
                        }
                        // look for File Link object node
                        else if (ApplicationModel.TYPE_FILELINK.equals(type)) {
                            // create our File Link Node representation
                            node = new MapNode(nodeRef, this.getNodeService(), false);
                            // only display the user has the permissions to navigate to the target of the link
                            NodeRef destRef = (NodeRef) node.getProperties()
                                    .get(ContentModel.PROP_LINK_DESTINATION);
                            if (new Node(destRef).hasPermission(PermissionService.READ) == true) {
                                node.addPropertyResolver("url", this.resolverLinkUrl);
                                node.addPropertyResolver("downloadUrl", this.resolverLinkDownload);
                                node.addPropertyResolver("webdavUrl", this.resolverLinkWebdavUrl);
                                node.addPropertyResolver("cifsPath", this.resolverLinkCifsPath);
                                node.addPropertyResolver("fileType16", this.resolverFileType16);
                                node.addPropertyResolver("fileType32", this.resolverFileType32);
                                node.addPropertyResolver("lang", this.resolverLang);
                                node.addPropertyResolver("path", this.resolverPath);
                                node.addPropertyResolver("displayPath", this.resolverDisplayPath);

                                this.contentNodes.add(node);
                            }
                        } else if (ApplicationModel.TYPE_FOLDERLINK.equals(type)) {
                            // create our Folder Link Node representation
                            node = new MapNode(nodeRef, this.getNodeService(), false);
                            // only display the user has the permissions to navigate to the target of the link
                            NodeRef destRef = (NodeRef) node.getProperties()
                                    .get(ContentModel.PROP_LINK_DESTINATION);
                            if (new Node(destRef).hasPermission(PermissionService.READ) == true) {
                                node.addPropertyResolver("icon", this.resolverSpaceIcon);
                                node.addPropertyResolver("smallIcon", this.resolverSmallIcon);
                                node.addPropertyResolver("path", this.resolverPath);
                                node.addPropertyResolver("displayPath", this.resolverDisplayPath);

                                this.containerNodes.add(node);
                            }
                        }

                        // inform any listeners that a Node wrapper has been created
                        if (node != null) {
                            for (NodeEventListener listener : nodeEventListeners) {
                                listener.created(node, type);
                            }
                        }
                    } else {
                        if (logger.isWarnEnabled())
                            logger.warn(
                                    "Found invalid object in database: id = " + nodeRef + ", type = " + type);
                    }
                } else {
                    if (logger.isWarnEnabled())
                        logger.warn("Missing object returned from search indexes: id = " + nodeRef
                                + " search query: " + query);
                }
            }
        }

        // commit the transaction
        tx.commit();
    } catch (InvalidNodeRefException refErr) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF),
                new Object[] { refErr.getNodeRef() }), refErr);
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (SearcherException serr) {
        logger.info("Search failed for: " + query, serr);
        Utils.addErrorMessage(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_QUERY));
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_SEARCH),
                new Object[] { err.getMessage() }), err);
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } finally {
        if (results != null) {
            results.close();
        }
    }

    if (logger.isDebugEnabled()) {
        long endTime = System.currentTimeMillis();
        logger.debug("Time to query and build map nodes: " + (endTime - startTime) + "ms");
    }
}

From source file:org.alfresco.web.bean.categories.CategoriesDialog.java

/**
 * @return The list of categories Nodes to display. Returns the list root categories or the 
 *         list of sub-categories for the current category if set.
 *//* ww  w.  j  a  v  a2 s . c  o m*/
public List<Node> getCategories() {
    List<Node> categories;

    UserTransaction tx = null;
    try {
        FacesContext context = FacesContext.getCurrentInstance();
        tx = Repository.getUserTransaction(context, true);
        tx.begin();

        Collection<ChildAssociationRef> refs;
        if (getCategoryRef() == null) {
            // root categories
            refs = getCategoryService().getCategories(Repository.getStoreRef(),
                    ContentModel.ASPECT_GEN_CLASSIFIABLE, Depth.IMMEDIATE);
        } else {
            // sub-categories of an existing category
            refs = getCategoryService().getChildren(getCategoryRef(), Mode.SUB_CATEGORIES, Depth.IMMEDIATE);
        }
        categories = new ArrayList<Node>(refs.size());
        for (ChildAssociationRef child : refs) {
            Node categoryNode = new Node(child.getChildRef());
            // force early props init within transaction
            categoryNode.getProperties();
            categories.add(categoryNode);
        }

        // commit the transaction
        tx.commit();
    } catch (InvalidNodeRefException refErr) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF),
                new Object[] { refErr.getNodeRef() }));
        categories = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC),
                err.getMessage()), err);
        categories = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }

    return categories;
}

From source file:org.alfresco.web.bean.coci.EditOfflineDialog.java

/**
 * Checkout document to the same space as original one and then add the
 * OFFLINE_EDITING property.// ww  w  . ja  v  a 2s  .  com
 */
private void checkoutFile(Node node) {
    UserTransaction tx = null;
    FacesContext context = FacesContext.getCurrentInstance();

    if (node != null) {
        try {
            tx = Repository.getUserTransaction(context, false);
            tx.begin();

            if (logger.isDebugEnabled())
                logger.debug("Trying to checkout content node Id: " + node.getId());
            NodeRef workingCopyRef = null;

            // checkout the content to the current space
            workingCopyRef = property.getVersionOperationsService().checkout(node.getNodeRef());
            getNodeService().setProperty(workingCopyRef, ContentModel.PROP_WORKING_COPY_MODE, OFFLINE_EDITING);

            // set the working copy Node instance
            Node workingCopy = new Node(workingCopyRef);
            property.setWorkingDocument(workingCopy);

            // create content URL to the content download servlet with ID and
            // expected filename
            String url = DownloadContentServlet.generateDownloadURL(workingCopyRef, workingCopy.getName());

            workingCopy.getProperties().put("url", url);
            workingCopy.getProperties().put("fileType32",
                    FileTypeImageUtils.getFileTypeImage(workingCopy.getName(), false));

            // commit the transaction
            tx.commit();
        } catch (Throwable err) {
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }

            Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_CHECKOUT)
                    + err.getMessage(), err);
        }
    } else {
        logger.warn("WARNING: checkoutFile called without a current Document!");
    }
}

From source file:org.alfresco.web.bean.forums.ForumsBean.java

private void getNodes() {
    long startTime = 0;
    if (logger.isDebugEnabled())
        startTime = System.currentTimeMillis();

    UserTransaction tx = null;
    try {//from  www .ja  va  2s  .  c o m
        FacesContext context = FacesContext.getCurrentInstance();
        tx = Repository.getUserTransaction(context, true);
        tx.begin();

        // get the current space from NavigationBean
        String parentNodeId = this.navigator.getCurrentNodeId();

        NodeRef parentRef;
        if (parentNodeId == null) {
            // no specific parent node specified - use the root node
            parentRef = this.getNodeService().getRootNode(Repository.getStoreRef());
        } else {
            // build a NodeRef for the specified Id and our store
            parentRef = new NodeRef(Repository.getStoreRef(), parentNodeId);
        }

        List<ChildAssociationRef> childRefs = this.getNodeService().getChildAssocs(parentRef,
                ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
        this.forums = new ArrayList<Node>(childRefs.size());
        this.topics = new ArrayList<Node>(childRefs.size());
        this.posts = new ArrayList<Node>(childRefs.size());

        for (ChildAssociationRef ref : childRefs) {
            // create our Node representation from the NodeRef
            NodeRef nodeRef = ref.getChildRef();

            if (this.getNodeService().exists(nodeRef)) {
                // find it's type so we can see if it's a node we are interested in
                QName type = this.getNodeService().getType(nodeRef);

                // make sure the type is defined in the data dictionary
                TypeDefinition typeDef = this.getDictionaryService().getType(type);

                if (typeDef != null) {
                    // extract forums, forum, topic and post types

                    if (this.getDictionaryService().isSubClass(type,
                            ContentModel.TYPE_SYSTEM_FOLDER) == false) {
                        if (this.getDictionaryService().isSubClass(type, ForumModel.TYPE_FORUMS)
                                || this.getDictionaryService().isSubClass(type, ForumModel.TYPE_FORUM)) {
                            // create our Node representation
                            MapNode node = new MapNode(nodeRef, this.getNodeService(), true);
                            node.addPropertyResolver("icon", this.browseBean.resolverSpaceIcon);
                            node.addPropertyResolver("smallIcon", this.browseBean.resolverSmallIcon);

                            this.forums.add(node);
                        }
                        if (this.getDictionaryService().isSubClass(type, ForumModel.TYPE_TOPIC)) {
                            // create our Node representation
                            MapNode node = new MapNode(nodeRef, this.getNodeService(), true);
                            node.addPropertyResolver("icon", this.browseBean.resolverSpaceIcon);
                            node.addPropertyResolver("smallIcon", this.browseBean.resolverSmallIcon);
                            node.addPropertyResolver("replies", this.resolverReplies);

                            this.topics.add(node);
                        } else if (this.getDictionaryService().isSubClass(type, ForumModel.TYPE_POST)) {
                            // create our Node representation
                            MapNode node = new MapNode(nodeRef, this.getNodeService(), true);

                            this.browseBean.setupCommonBindingProperties(node);
                            node.addPropertyResolver("smallIcon", this.browseBean.resolverSmallIcon);
                            node.addPropertyResolver("message", this.resolverContent);
                            node.addPropertyResolver("replyTo", this.resolverReplyTo);

                            this.posts.add(node);
                        }
                    }
                } else {
                    if (logger.isWarnEnabled())
                        logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type);
                }
            }
        }

        // commit the transaction
        tx.commit();
    } catch (InvalidNodeRefException refErr) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF),
                new Object[] { refErr.getNodeRef() }));
        this.forums = Collections.<Node>emptyList();
        this.topics = Collections.<Node>emptyList();
        this.posts = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC),
                err.getMessage()), err);
        this.forums = Collections.<Node>emptyList();
        this.topics = Collections.<Node>emptyList();
        this.posts = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }

    if (logger.isDebugEnabled()) {
        long endTime = System.currentTimeMillis();
        logger.debug("Time to query and build forums nodes: " + (endTime - startTime) + "ms");
    }
}

From source file:org.alfresco.web.bean.groups.GroupsDialog.java

/**
 * @return The list of user objects to display. Returns the list of user for the current group.
 *///from   w  w  w.j a  v  a  2  s  .co  m
public List<Map<String, Object>> getUsers() {
    List<Map<String, Object>> users;

    UserTransaction tx = null;
    try {
        FacesContext context = FacesContext.getCurrentInstance();
        tx = Repository.getUserTransaction(context, true);
        tx.begin();

        Set<String> authorities;
        if (this.group == null) {
            authorities = Collections.<String>emptySet();
        } else {
            // users of an existing group
            boolean immediate = (this.filterMode.equals(FILTER_CHILDREN));
            authorities = this.getAuthorityService().getContainedAuthorities(AuthorityType.USER, this.group,
                    immediate);
        }
        users = new ArrayList<Map<String, Object>>(authorities.size());
        for (String authority : authorities) {
            final Map<String, Object> authMap = new HashMap<String, Object>(8);

            final String userName = this.getAuthorityService().getShortName(authority);
            authMap.put("userName", userName);
            authMap.put("id", Utils.encode(authority));
            authMap.put("name", new AuthorityNamePropertyResolver(userName));
            authMap.put("firstName", new AuthorityPropertyResolver(userName, ContentModel.PROP_FIRSTNAME));
            authMap.put("lastName", new AuthorityPropertyResolver(userName, ContentModel.PROP_LASTNAME));

            users.add(authMap);
        }

        // commit the transaction
        tx.commit();
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC),
                err.getMessage()), err);
        users = Collections.<Map<String, Object>>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }

    return users;
}

From source file:org.alfresco.web.bean.groups.GroupsDialog.java

/**
* Remove specified user from the current group
*//*from  w  w  w. ja  v a2 s. co m*/
public void removeUser(ActionEvent event) {
    UIActionLink link = (UIActionLink) event.getComponent();
    Map<String, String> params = link.getParameterMap();
    String authority = params.get("id");
    if (authority != null && authority.length() != 0) {
        UserTransaction tx = null;
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            tx = Repository.getUserTransaction(context);
            tx.begin();

            this.getAuthorityService().removeAuthority(this.group, authority);

            // commit the transaction
            tx.commit();

            // refresh UI after change
            contextUpdated();
        } catch (Throwable err) {
            Utils.addErrorMessage(MessageFormat.format(
                    Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC),
                    err.getMessage()), err);
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }
        }
    }
}

From source file:org.alfresco.web.bean.repository.Repository.java

/**
 * Query a list of Person type nodes from the repo
 * It is currently assumed that all Person nodes exist below the Repository root node
 * /*  w ww.  j a  v a  2 s. c  om*/
 * @param context Faces Context
 * @param nodeService The node service
 * @param personService PersonService
 * @return List of Person node objects
 */
public static List<Node> getUsers(FacesContext context, NodeService nodeService, PersonService personService) {
    List<Node> personNodes = null;

    UserTransaction tx = null;
    try {
        tx = Repository.getUserTransaction(context, true);
        tx.begin();

        NodeRef peopleRef = personService.getPeopleContainer();

        // TODO: better to perform an XPath search or a get for a specific child type here?
        List<ChildAssociationRef> childRefs = nodeService.getChildAssocs(peopleRef);
        personNodes = new ArrayList<Node>(childRefs.size());
        for (ChildAssociationRef ref : childRefs) {
            // create our Node representation from the NodeRef
            NodeRef nodeRef = ref.getChildRef();

            if (nodeService.getType(nodeRef).equals(ContentModel.TYPE_PERSON)) {
                // create our Node representation
                MapNode node = new MapNode(nodeRef);

                // set data binding properties
                // this will also force initialisation of the props now during the UserTransaction
                // it is much better for performance to do this now rather than during page bind
                Map<String, Object> props = node.getProperties();
                String firstName = (String) props.get("firstName");
                String lastName = (String) props.get("lastName");
                props.put("fullName",
                        (firstName != null ? firstName : "") + ' ' + (lastName != null ? lastName : ""));
                NodeRef homeFolderNodeRef = (NodeRef) props.get("homeFolder");
                if (homeFolderNodeRef != null) {
                    props.put("homeSpace", homeFolderNodeRef);
                }

                personNodes.add(node);
            }
        }

        // commit the transaction
        tx.commit();
    } catch (InvalidNodeRefException refErr) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_NODEREF),
                new Object[] { "root" }));
        personNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC),
                err.getMessage()), err);
        personNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }

    return personNodes;
}

From source file:org.alfresco.web.bean.rules.RulesDialog.java

/**
 * Reapply the currently defines rules to the
 * @param event ActionEvent/*from ww  w .  j a v  a  2  s .c om*/
 */
public void reapplyRules(ActionEvent event) {
    boolean toChildren = false;
    UIActionLink link = (UIActionLink) event.getComponent();
    Map<String, String> params = link.getParameterMap();
    String toChildrenStr = params.get("toChildren");
    if (toChildrenStr != null) {
        toChildren = new Boolean(toChildrenStr).booleanValue();
    }

    FacesContext fc = FacesContext.getCurrentInstance();
    UserTransaction tx = null;

    try {
        tx = Repository.getUserTransaction(fc);
        tx.begin();

        // Set the include inherited parameter to match the current filter value
        boolean executeInherited = true;
        if (this.filterModeMode.equals(LOCAL)) {
            executeInherited = false;
        }

        // Reapply the rules
        reapplyRules(this.getSpace().getNodeRef(), executeInherited, toChildren);

        // TODO how do I get the message here ...
        String msg = Application.getMessage(fc, MSG_REAPPLY_RULES_SUCCESS);
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
        String formId = Utils.getParentForm(fc, event.getComponent()).getClientId(fc);
        fc.addMessage(formId + ":rulesList", facesMsg);

        // commit the transaction
        tx.commit();
    } catch (Throwable e) {
        // rollback the transaction
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
        }
        Utils.addErrorMessage(
                MessageFormat.format(Application.getMessage(fc, Repository.ERROR_GENERIC), e.getMessage()), e);
    }
}

From source file:org.alfresco.web.bean.spaces.DeleteSpaceDialog.java

@Override
protected String finishImpl(FacesContext context, String outcome) throws Exception {
    final boolean isAdmin = this.navigator.getCurrentUser().isAdmin();
    // get the space to delete
    Node node = this.browseBean.getActionSpace();
    if (node != null) {
        // force cache of name property so we can use it after the delete
        node.getName();//  ww  w.j a v a 2  s . c o  m

        if (logger.isDebugEnabled())
            logger.debug("Trying to delete space: " + node.getId() + " using delete mode: " + this.deleteMode);

        try {
            if (isAdmin && !this.executeRules) {
                Repository.getServiceRegistry(context).getRuleService().disableRules();
            }
            if (DELETE_ALL.equals(this.deleteMode)) {
                NodeRef nodeRef = node.getNodeRef();
                // Check the node still exists
                if (this.getNodeService().exists(nodeRef)) {
                    if (isAdmin && !this.archiveNodes) {
                        this.getNodeService().addAspect(node.getNodeRef(), ContentModel.ASPECT_TEMPORARY, null);
                    }

                    // ensure the node still exists before deleting
                    if (this.getNodeService().exists(node.getNodeRef())) {
                        this.getNodeService().deleteNode(node.getNodeRef());
                    }
                }
            } else {
                List<ChildAssociationRef> childRefs = this.getNodeService().getChildAssocs(node.getNodeRef(),
                        ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
                List<NodeRef> deleteRefs = new ArrayList<NodeRef>(childRefs.size());
                for (ChildAssociationRef ref : childRefs) {
                    NodeRef nodeRef = ref.getChildRef();

                    if (this.getNodeService().exists(nodeRef)) {
                        if (DELETE_CONTENTS.equals(this.deleteMode)) {
                            deleteRefs.add(nodeRef);
                        } else {
                            // find it's type so we can see if it's a node we are interested in
                            QName type = this.getNodeService().getType(nodeRef);

                            // make sure the type is defined in the data dictionary
                            TypeDefinition typeDef = this.getDictionaryService().getType(type);

                            if (typeDef != null) {
                                if (DELETE_FOLDERS.equals(this.deleteMode)) {
                                    // look for folder type
                                    if (this.getDictionaryService().isSubClass(type,
                                            ContentModel.TYPE_FOLDER) == true
                                            && this.getDictionaryService().isSubClass(type,
                                                    ContentModel.TYPE_SYSTEM_FOLDER) == false) {
                                        deleteRefs.add(nodeRef);
                                    }
                                } else if (DELETE_FILES.equals(this.deleteMode)) {
                                    // look for content file type
                                    if (this.getDictionaryService().isSubClass(type,
                                            ContentModel.TYPE_CONTENT)) {
                                        deleteRefs.add(nodeRef);
                                    }
                                }
                            }
                        }
                    }
                }

                // delete the list of refs
                TransactionService txService = Repository.getServiceRegistry(context).getTransactionService();
                for (NodeRef nodeRef : deleteRefs) {
                    UserTransaction tx = null;

                    try {
                        tx = txService.getNonPropagatingUserTransaction();
                        tx.begin();

                        if (isAdmin && !this.archiveNodes) {
                            this.getNodeService().addAspect(nodeRef, ContentModel.ASPECT_TEMPORARY, null);
                        }

                        // ensure the node still exists before deleting
                        if (this.getNodeService().exists(node.getNodeRef())) {
                            this.getNodeService().deleteNode(nodeRef);
                        }

                        tx.commit();
                    } catch (Throwable err) {
                        try {
                            if (tx != null) {
                                tx.rollback();
                            }
                        } catch (Exception ex) {
                        }
                    }
                }
            }
        } finally {
            if (isAdmin && !this.executeRules) {
                Repository.getServiceRegistry(context).getRuleService().enableRules();
            }
        }
    } else {
        logger.warn("WARNING: delete called without a current Space!");
    }

    return outcome;
}