Example usage for javax.transaction UserTransaction commit

List of usage examples for javax.transaction UserTransaction commit

Introduction

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

Prototype

void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException,
        IllegalStateException, SystemException;

Source Link

Document

Complete the transaction associated with the current thread.

Usage

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.
 *//*w ww .  j a va 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 www.j av  a2  s .c  o  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
 * /*from  w w w .j a v  a  2s. co m*/
 * @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   w ww .j av a2 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();/*from   w  ww  .  jav a2  s. co  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;
}

From source file:org.alfresco.web.bean.users.DeleteUserDialog.java

public String search() {

    if (this.searchCriteria == null || this.searchCriteria.length() == 0) {
        this.users = Collections.<Node>emptyList();
    } else {// www.j  a  va2  s. co m
        FacesContext context = FacesContext.getCurrentInstance();
        UserTransaction tx = null;

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

            // define the query to find people by their first or last name
            String search = ISO9075.encode(this.searchCriteria);
            List<Pair<QName, String>> filter = Utils.generatePersonFilter(search);

            if (logger.isDebugEnabled()) {
                logger.debug("Query filter: " + filter);
            }

            List<PersonInfo> persons = getPersonService().getPeople(filter, true, Utils.generatePersonSort(),
                    new PagingRequest(Utils.getPersonMaxResults(), null)).getPage();

            if (logger.isDebugEnabled()) {
                logger.debug("Found " + persons.size() + " users");
            }

            this.users = new ArrayList<Node>(persons.size());

            for (PersonInfo person : persons) {
                // create our Node representation
                MapNode node = new MapNode(person.getNodeRef());

                // 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();
                props.put("fullName",
                        ((String) props.get("firstName")) + ' ' + ((String) props.get("lastName")));
                NodeRef homeFolderNodeRef = (NodeRef) props.get("homeFolder");
                if (homeFolderNodeRef != null) {
                    props.put("homeSpace", homeFolderNodeRef);
                }

                this.users.add(node);
            }

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

    // return null to stay on the same page
    return null;
}

From source file:org.alfresco.web.bean.users.UsersDialog.java

/**
 * Action handler called for the OK button press
 *//*from   w  w w.  j a  v a  2  s.  c o m*/
public String changeUserDetails() {
    String outcome = DIALOG_CLOSE;

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

        Map<QName, Serializable> props = properties.getNodeService()
                .getProperties(properties.getPerson().getNodeRef());
        props.put(ContentModel.PROP_FIRSTNAME,
                (String) properties.getPerson().getProperties().get(ContentModel.PROP_FIRSTNAME));
        props.put(ContentModel.PROP_LASTNAME,
                (String) properties.getPerson().getProperties().get(ContentModel.PROP_LASTNAME));
        props.put(ContentModel.PROP_EMAIL,
                (String) properties.getPerson().getProperties().get(ContentModel.PROP_EMAIL));

        // persist changes
        properties.getNodeService().setProperties(properties.getPerson().getNodeRef(), props);

        tx.commit();

        // if the above call was successful, then reset Person Node in the session
        Application.getCurrentUser(context).reset();
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC),
                err.getMessage()), err);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }

    return outcome;
}

From source file:org.alfresco.web.bean.users.UsersDialog.java

/**
 * Event handler called when the user wishes to search for a user
 * //from   w w  w  .  ja va 2s.  c  o  m
 * @return The outcome
 */
public String search() {
    properties.getUsersRichList().setValue(null);

    if (properties.getSearchCriteria() == null || properties.getSearchCriteria().trim().length() == 0) {
        this.users = Collections.<Node>emptyList();
    } else {
        FacesContext context = FacesContext.getCurrentInstance();
        UserTransaction tx = null;

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

            // define the query to find people by their first or last name
            String search = properties.getSearchCriteria();
            if (logger.isDebugEnabled()) {
                logger.debug("Query filter: " + search);
            }

            List<PersonInfo> persons = properties
                    .getPersonService().getPeople(Utils.generatePersonFilter(search), true,
                            Utils.generatePersonSort(), new PagingRequest(Utils.getPersonMaxResults(), null))
                    .getPage();

            if (logger.isDebugEnabled()) {
                logger.debug("Found " + persons.size() + " users");
            }

            this.users = new ArrayList<Node>(persons.size());

            for (PersonInfo person : persons) {
                // create our Node representation
                MapNode node = new MapNode(person.getNodeRef());

                // 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);
                }

                node.addPropertyResolver("sizeLatest", this.resolverUserSizeLatest);
                node.addPropertyResolver("quota", this.resolverUserQuota);
                node.addPropertyResolver("isMutable", this.resolverUserMutable);

                this.users.add(node);
            }

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

    // return null to stay on the same page
    return null;
}

From source file:org.alfresco.web.bean.users.UserShortcutsBean.java

/**
 * @return the List of shortcut Nodes/* w ww  .j av  a2  s  .  co m*/
 */
public List<Node> getShortcuts() {
    if (this.shortcuts == null) {
        List<String> shortcuts = null;
        NodeRef prefRef = null;
        UserTransaction tx = null;
        boolean rollback = false;
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            tx = Repository.getUserTransaction(context);
            tx.begin();

            // get the shortcuts from the preferences for this user
            shortcuts = getShortcutList(context);
            if (shortcuts.size() != 0) {
                // each shortcut node ID is persisted as a list item in a well known property
                this.shortcuts = new ArrayList<Node>(shortcuts.size());
                for (int i = 0; i < shortcuts.size(); i++) {
                    NodeRef ref = new NodeRef(Repository.getStoreRef(), shortcuts.get(i));
                    try {
                        if (this.getNodeService().exists(ref) == true) {
                            Node node = new Node(ref);

                            // quick init properties while in the usertransaction
                            node.getProperties();

                            // save ref to the Node for rendering
                            this.shortcuts.add(node);
                        } else {
                            // ignore this shortcut node - no longer exists in the system!
                            // we write the node list back again afterwards to correct this
                            if (logger.isDebugEnabled())
                                logger.debug("Found invalid shortcut node Id: " + ref.getId());
                        }
                    } catch (AccessDeniedException accessErr) {
                        // ignore this shortcut node - no longer exists in the system!
                        // we write the node list back again afterwards to correct this
                        if (logger.isDebugEnabled())
                            logger.debug("Found invalid shortcut node Id: " + ref.getId());
                        rollback = true;
                    }
                }
            } else {
                this.shortcuts = new ArrayList<Node>(5);
            }

            if (rollback == false) {
                tx.commit();
            } else {
                tx.rollback();
            }
        } 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) {
            }
        }

        // if the count of accessable shortcuts is different to our original list then
        // write the valid shortcut IDs back to correct invalid node refs
        if (shortcuts != null && shortcuts.size() != this.shortcuts.size()) {
            try {
                shortcuts = new ArrayList<String>(this.shortcuts.size());
                for (int i = 0; i < this.shortcuts.size(); i++) {
                    shortcuts.add(this.shortcuts.get(i).getId());
                }
                PreferencesService.getPreferences().setValue(PREF_SHORTCUTS, (Serializable) shortcuts);
            } catch (Exception err) {
                Utils.addErrorMessage(MessageFormat.format(
                        Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC),
                        err.getMessage()), err);
            }
        }
    }

    return this.shortcuts;
}

From source file:org.alfresco.web.bean.users.UserShortcutsBean.java

/**
 * Action handler called when a new shortcut is to be added to the list
 *///from   w w  w.j  a v  a 2s .  co m
public void createShortcut(ActionEvent event) {
    // TODO: add this action to the Details screen for Space and Document
    UIActionLink link = (UIActionLink) event.getComponent();
    Map<String, String> params = link.getParameterMap();
    String id = params.get("id");
    if (id != null && id.length() != 0) {
        try {
            NodeRef ref = new NodeRef(Repository.getStoreRef(), id);
            Node node = new Node(ref);

            boolean foundShortcut = false;
            for (int i = 0; i < getShortcuts().size(); i++) {
                if (node.getId().equals(getShortcuts().get(i).getId())) {
                    // found same node already in the list - so we don't need to add it again
                    foundShortcut = true;
                    break;
                }
            }

            if (foundShortcut == false) {
                // add to persistent store
                UserTransaction tx = null;
                try {
                    FacesContext context = FacesContext.getCurrentInstance();
                    tx = Repository.getUserTransaction(context);
                    tx.begin();

                    List<String> shortcuts = getShortcutList(context);
                    shortcuts.add(node.getNodeRef().getId());
                    PreferencesService.getPreferences(context).setValue(PREF_SHORTCUTS,
                            (Serializable) shortcuts);

                    // commit the transaction
                    tx.commit();

                    // add our new shortcut Node to the in-memory list
                    getShortcuts().add(node);

                    if (logger.isDebugEnabled())
                        logger.debug("Added node: " + node.getName() + " to the user shortcuts list.");
                } 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) {
                    }
                }
            }
        } catch (InvalidNodeRefException refErr) {
            Utils.addErrorMessage(MessageFormat.format(
                    Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF),
                    new Object[] { id }));
        }
    }
}