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.users.DeleteUserDialog.java

public String search() {

    if (this.searchCriteria == null || this.searchCriteria.length() == 0) {
        this.users = Collections.<Node>emptyList();
    } else {//from ww  w . ja  v  a2  s.  c o 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 ww w.j  ava 2 s  .c om
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 2  s.  co 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//from  w w  w.j  av a  2s.c o 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  .java 2  s.  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 }));
        }
    }
}

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

/**
 * Action handler bound to the user shortcuts Shelf component called when a node is removed
 *//*from   w w  w.  j a  v a  2  s  . co  m*/
public void removeShortcut(ActionEvent event) {
    UIShortcutsShelfItem.ShortcutEvent shortcutEvent = (UIShortcutsShelfItem.ShortcutEvent) event;

    // remove from persistent store
    UserTransaction tx = null;
    try {
        FacesContext context = FacesContext.getCurrentInstance();
        tx = Repository.getUserTransaction(context);
        tx.begin();

        List<String> shortcuts = getShortcutList(context);
        if (shortcuts.size() > shortcutEvent.Index) {
            // remove the shortcut from the saved list and persist back
            shortcuts.remove(shortcutEvent.Index);
            PreferencesService.getPreferences(context).setValue(PREF_SHORTCUTS, (Serializable) shortcuts);

            // commit the transaction
            tx.commit();

            // remove shortcut Node from the in-memory list
            Node node = getShortcuts().remove(shortcutEvent.Index);

            if (logger.isDebugEnabled())
                logger.debug("Removed node: " + node.getName() + " from 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) {
        }
    }
}

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

/**
 * Action handler bound to the user shortcuts Shelf component called when a node is clicked
 *//*from w  w  w  .j  av  a  2 s .  c om*/
public void click(ActionEvent event) {
    // work out which node was clicked from the event data
    UIShortcutsShelfItem.ShortcutEvent shortcutEvent = (UIShortcutsShelfItem.ShortcutEvent) event;
    Node selectedNode = getShortcuts().get(shortcutEvent.Index);

    try {
        if (getPermissionService().hasPermission(selectedNode.getNodeRef(),
                PermissionService.READ) == AccessStatus.ALLOWED) {
            if (getNodeService().exists(selectedNode.getNodeRef()) == false) {
                throw new InvalidNodeRefException(selectedNode.getNodeRef());
            }

            DictionaryService dd = Repository.getServiceRegistry(FacesContext.getCurrentInstance())
                    .getDictionaryService();
            if (dd.isSubClass(selectedNode.getType(), ContentModel.TYPE_FOLDER)) {
                // then navigate to the appropriate node in UI
                // use browse bean functionality for this as it will update the breadcrumb for us
                this.browseBean.updateUILocation(selectedNode.getNodeRef());
            } else if (dd.isSubClass(selectedNode.getType(), ContentModel.TYPE_CONTENT)) {
                // view details for document
                this.browseBean.setupContentAction(selectedNode.getId(), true);
                FacesContext fc = FacesContext.getCurrentInstance();
                fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:showDocDetails");
            }
        } else {
            Utils.addErrorMessage(
                    Application.getMessage(FacesContext.getCurrentInstance(), "error_shortcut_permissions"));
        }
    } catch (InvalidNodeRefException refErr) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF),
                new Object[] { selectedNode.getId() }));

        // remove item from the shortcut list
        UserTransaction tx = null;
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            tx = Repository.getUserTransaction(context);
            tx.begin();

            List<String> shortcuts = getShortcutList(context);
            if (shortcuts.size() > shortcutEvent.Index) {
                // remove the shortcut from the saved list and persist back
                shortcuts.remove(shortcutEvent.Index);
                PreferencesService.getPreferences(context).setValue(PREF_SHORTCUTS, (Serializable) shortcuts);

                // commit the transaction
                tx.commit();

                // remove shortcut Node from the in-memory list
                Node node = getShortcuts().remove(shortcutEvent.Index);

                if (logger.isDebugEnabled())
                    logger.debug("Removed deleted node: " + node.getName() + " from the user shortcuts list.");
            }
        } catch (Throwable err) {
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }
        }
    }
}

From source file:org.alfresco.web.bean.wcm.AVMBrowseBean.java

/**
 * Build the lists of files and folders within the current browsing path in a website space
 *///from w  w  w . j a  v  a 2 s.  co  m
private void buildDirectoryNodes() {
    UserTransaction tx = null;
    try {
        FacesContext context = FacesContext.getCurrentInstance();
        tx = Repository.getUserTransaction(context, true);
        tx.begin();

        Map<String, AVMNodeDescriptor> nodes = getAvmService().getDirectoryListing(-1, getCurrentPath());
        this.files = new ArrayList<Map>(nodes.size());
        this.folders = new ArrayList<Map>(nodes.size());
        for (String name : nodes.keySet()) {
            AVMNodeDescriptor avmRef = nodes.get(name);

            // build and add the client representation of the AVM node
            addAVMNodeResult(avmRef);
        }

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

From source file:org.alfresco.web.bean.wcm.AVMBrowseBean.java

/**
 * Build the lists of files and folders from the current search context in a website space
 *//* w ww .j  a  va 2s .co m*/
private void buildSearchNodes() {
    String query = this.searchContext.buildQuery(getMinimumSearchLength());
    if (query == null) {
        this.folders = Collections.<Map>emptyList();
        this.files = Collections.<Map>emptyList();
        return;
    }

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

        // build up the search parameters
        SearchParameters sp = new SearchParameters();
        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp.setQuery(query);
        // add the Staging Store for this website - it is the only searchable store for now
        sp.addStore(new StoreRef(StoreRef.PROTOCOL_AVM, getStagingStore()));

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

        results = getSearchService().query(sp);

        if (logger.isDebugEnabled()) {
            logger.debug("Search results returned: " + results.length());
        }

        // filter hidden folders above the web app
        boolean isStagingStore = getIsStagingStore();
        int sandboxPathLength = AVMUtil.getSandboxPath(getCurrentPath()).length();

        this.files = new ArrayList<Map>(results.length());
        this.folders = new ArrayList<Map>(results.length());
        for (ResultSetRow row : results) {
            NodeRef nodeRef = row.getNodeRef();

            // Modify the path to point to the current user sandbox - this change is performed so
            // that any action permission evaluators will correctly resolve for the current user.
            // Therefore deleted node will be filtered out by the lookup() call, but some text based
            // results may be incorrect - however a note is provided in the search UI to indicate this.
            String path = AVMNodeConverter.ToAVMVersionPath(nodeRef).getSecond();
            if (isStagingStore == false) {
                path = getSandbox() + ':' + AVMUtil.getStoreRelativePath(path);
            }
            if (path.length() > sandboxPathLength) {
                AVMNodeDescriptor avmRef = getAvmService().lookup(-1, path);
                if (avmRef != null) {
                    AVMNode node = addAVMNodeResult(avmRef);

                    // add extra properties for search results lists
                    node.addPropertyResolver("displayPath", AVMNode.RESOLVER_DISPLAY_PATH);
                    node.addPropertyResolver("parentPath", AVMNode.RESOLVER_PARENT_PATH);
                }
            }
        }

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

From source file:org.alfresco.web.bean.wcm.AVMBrowseBean.java

/**
 * Undo changes to a single node/*www  .  j  a va2s  . co m*/
 */
public void revertNode(ActionEvent event) {
    String avmPath = getPathFromEventArgs(event);
    String sbStoreId = WCMUtil.getSandboxStoreId(avmPath);
    List<String> namesForDisplayMsg = new LinkedList<String>();
    UserTransaction tx = null;
    final FacesContext context = FacesContext.getCurrentInstance();
    try {
        tx = Repository.getUserTransaction(context, false);
        tx.begin();

        AVMNodeDescriptor node = getAvmService().lookup(-1, avmPath, true);
        if (node != null) {
            FormInstanceData fid = null;
            if (getAvmService().hasAspect(-1, avmPath, WCMAppModel.ASPECT_RENDITION)) {
                fid = this.getFormsService().getRendition(-1, avmPath).getPrimaryFormInstanceData();
            } else if (getAvmService().hasAspect(-1, avmPath, WCMAppModel.ASPECT_FORM_INSTANCE_DATA)) {
                fid = this.getFormsService().getFormInstanceData(-1, avmPath);
            }
            List<String> paths = new ArrayList<String>();
            if (fid != null) {
                paths.add(WCMUtil.getStoreRelativePath(fid.getPath()));
                namesForDisplayMsg.add(fid.getName());
                for (Rendition r : fid.getRenditions()) {
                    paths.add(WCMUtil.getStoreRelativePath(r.getPath()));
                    namesForDisplayMsg.add(r.getName());
                }
            } else {
                paths.add(WCMUtil.getStoreRelativePath(avmPath));
                namesForDisplayMsg.add(node.getName());
            }

            getSandboxService().revertList(sbStoreId, paths);
        }

        // commit the transaction
        tx.commit();

        // if we get here, all was well - output friendly status message to the user
        this.displayStatusMessage(context,
                MessageFormat.format(Application.getMessage(context, MSG_REVERT_SUCCESS),
                        StringUtils.join(namesForDisplayMsg.toArray(), ", "), namesForDisplayMsg.size()));
    } catch (Throwable err) {
        err.printStackTrace(System.err);
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC),
                err.getMessage()), err);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }
}