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.workflow.ManageTaskDialog.java

@SuppressWarnings("deprecation")
public String transition() {
    String outcome = getDefaultFinishOutcome();

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Transitioning task: " + this.getWorkflowTask().id);

    // before transitioning check the task still exists and is not completed
    FacesContext context = FacesContext.getCurrentInstance();
    WorkflowTask checkTask = this.getWorkflowService().getTaskById(this.getWorkflowTask().id);
    if (checkTask == null || checkTask.state == WorkflowTaskState.COMPLETED) {
        Utils.addErrorMessage(Application.getMessage(context, "invalid_task"));
        return outcome;
    }/*  w  w w  .j  av  a 2  s. c  om*/

    // to find out which transition button was pressed we need
    // to look for the button's id in the request parameters,
    // the first non-null result is the button that was pressed.
    Map<?, ?> reqParams = context.getExternalContext().getRequestParameterMap();

    String selectedTransition = null;
    for (WorkflowTransition trans : this.getWorkflowTransitions()) {
        Object result = reqParams.get(CLIENT_ID_PREFIX + FacesHelper.makeLegalId(trans.title));
        if (result != null) {
            // this was the button that was pressed
            selectedTransition = trans.id;
            break;
        }
    }

    UserTransaction tx = null;

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

        // prepare the edited parameters for saving
        Map<QName, Serializable> params = WorkflowUtil.prepareTaskParams(this.taskNode);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Transitioning task with parameters: " + params);

        // update the task with the updated parameters and resources
        updateResources();
        this.getWorkflowService().updateTask(this.getWorkflowTask().id, params, null, null);

        // signal the selected transition to the workflow task
        this.getWorkflowService().endTask(this.getWorkflowTask().id, selectedTransition);

        // commit the changes
        tx.commit();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Ended task with transition: " + selectedTransition);
    } catch (Throwable e) {
        // rollback the transaction
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
        }
        Utils.addErrorMessage(formatErrorMessage(e), e);
        outcome = this.getErrorOutcome(e);
    }

    return outcome;
}

From source file:org.alfresco.web.bean.workflow.ManageTaskDialog.java

/**
 * Returns a list of resources associated with this task i.e. the children
 * of the workflow package/*from  w  w  w  .  j  a v  a2  s .  c om*/
 * 
 * @return The list of nodes
 */
public List<Node> getResources() {
    this.resources = new ArrayList<Node>(4);

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

            List<NodeRef> contents = this.workflowService.getPackageContents(getWorkflowTask().id);

            for (NodeRef nodeRef : contents) {
                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
                    if (this.getDictionaryService().getType(type) != null) {
                        // look for content nodes or links to content
                        // NOTE: folders within workflow packages are
                        // ignored for now
                        if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT)
                                || ApplicationModel.TYPE_FILELINK.equals(type)) {
                            // if the node is not in the removed list
                            // then add create the
                            // client side representation and add to the
                            // list
                            if (this.packageItemsToRemove == null
                                    || this.packageItemsToRemove.contains(nodeRef.toString()) == false) {
                                createAndAddNode(nodeRef);
                            }
                        }
                    }
                }
            }

            // now iterate through the items to add list and add them to the
            // list of resources
            if (this.packageItemsToAdd != null) {
                for (String newItem : this.packageItemsToAdd) {
                    NodeRef nodeRef = new NodeRef(newItem);
                    if (this.getNodeService().exists(nodeRef)) {
                        // we know the type is correct as this was added as
                        // a result of a query
                        // for all content items so just add the item to the
                        // resources list
                        createAndAddNode(nodeRef);
                    } else {
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug("Ignoring " + nodeRef + " as it has been removed from the repository");
                    }
                }
            }

            // commit the transaction
            tx.commit();
        } catch (Throwable err) {
            Utils.addErrorMessage(MessageFormat.format(
                    Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC),
                    err.getMessage()), err);
            this.resources = Collections.<Node>emptyList();
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }
        }
    } else if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Failed to find workflow package for task: " + this.getWorkflowTask().id);
    }

    return this.resources;
}

From source file:org.alfresco.web.bean.workflow.StartWorkflowWizard.java

/**
 * Returns a list of resources associated with this task
 * i.e. the children of the workflow package
 * /*from  w  ww.  j  a va 2 s . c  om*/
 * @return The list of nodes
 */
public List<Node> getResources() {
    this.resources = new ArrayList<Node>(4);

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

        for (String newItem : this.packageItemsToAdd) {
            NodeRef nodeRef = new NodeRef(newItem);
            if (this.getNodeService().exists(nodeRef)) {
                // create our Node representation
                MapNode node = new MapNode(nodeRef, this.getNodeService(), true);
                this.browseBean.setupCommonBindingProperties(node);

                // add property resolvers to show path information
                node.addPropertyResolver("path", this.browseBean.resolverPath);
                node.addPropertyResolver("displayPath", this.browseBean.resolverDisplayPath);

                this.resources.add(node);
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("Ignoring " + nodeRef + " as it has been removed from the repository");
            }
        }

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

    return this.resources;
}

From source file:org.alfresco.web.bean.workflow.WorkflowBean.java

/**
 * Returns a list of nodes representing the "all" active tasks.
 * // w  ww  . j  a  v  a 2  s .c om
 * @return List of all active tasks
 */
public List<Node> getAllActiveTasks() {
    if (this.activeTasks == null) {
        // get the current username
        FacesContext context = FacesContext.getCurrentInstance();
        User user = Application.getCurrentUser(context);
        String userName = user.getUserName();

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

            // query for all active tasks
            WorkflowTaskQuery query = new WorkflowTaskQuery();
            List<WorkflowTask> tasks = this.getWorkflowService().queryTasks(query);

            // create a list of transient nodes to represent
            this.activeTasks = new ArrayList<Node>(tasks.size());
            for (WorkflowTask task : tasks) {
                Node node = createTask(task);
                this.activeTasks.add(node);

                if (logger.isDebugEnabled())
                    logger.debug("Added active task: " + node);
            }

            // commit the changes
            tx.commit();
        } catch (Throwable e) {
            // rollback the transaction
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception ex) {
            }
            Utils.addErrorMessage("Failed to get all active tasks: " + e.toString(), e);
        }
    }

    return this.activeTasks;
}

From source file:org.alfresco.web.bean.workflow.WorkflowBean.java

/**
 * Returns a list of nodes representing the "pooled" to do tasks the 
 * current user has.//from   w  w  w  .  j a va  2s . c o m
 * 
 * @return List of to do tasks
 */
public List<Node> getPooledTasks() {
    if (this.pooledTasks == null) {
        // get the current username
        FacesContext context = FacesContext.getCurrentInstance();
        User user = Application.getCurrentUser(context);
        String userName = user.getUserName();

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

            // get the current pooled tasks for the current user
            List<WorkflowTask> tasks = this.getWorkflowService().getPooledTasks(userName, true);

            // create a list of transient nodes to represent
            this.pooledTasks = new ArrayList<Node>(tasks.size());
            for (WorkflowTask task : tasks) {
                Node node = createTask(task);
                this.pooledTasks.add(node);

                if (logger.isDebugEnabled())
                    logger.debug("Added pooled task: " + node);
            }

            // commit the changes
            tx.commit();
        } catch (Throwable e) {
            // rollback the transaction
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception ex) {
            }
            Utils.addErrorMessage("Failed to get pooled tasks: " + e.toString(), e);
        }
    }

    return this.pooledTasks;
}

From source file:org.alfresco.web.bean.workflow.WorkflowBean.java

/**
 * Returns a list of nodes representing the to do tasks the 
 * current user has./*from  w w w .j  ava2  s  . c o m*/
 * 
 * @return List of to do tasks
 */
public List<Node> getTasksToDo() {
    if (this.tasks == null) {
        // get the current username
        FacesContext context = FacesContext.getCurrentInstance();
        User user = Application.getCurrentUser(context);
        String userName = user.getUserName();

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

            // get the current in progress tasks for the current user
            List<WorkflowTask> tasks = this.getWorkflowService().getAssignedTasks(userName,
                    WorkflowTaskState.IN_PROGRESS, true);

            // create a list of transient nodes to represent
            this.tasks = new ArrayList<Node>(tasks.size());
            for (WorkflowTask task : tasks) {
                Node node = createTask(task);
                this.tasks.add(node);

                if (logger.isDebugEnabled())
                    logger.debug("Added to do task: " + node);
            }

            // commit the changes
            tx.commit();
        } catch (Throwable e) {
            // rollback the transaction
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception ex) {
            }
            Utils.addErrorMessage("Failed to get to do tasks: " + e.toString(), e);
        }
    }

    return this.tasks;
}

From source file:org.alfresco.web.bean.workflow.WorkflowBean.java

/**
 * Returns a list of nodes representing the completed tasks the 
 * current user has.//from  w  ww.j a v a2s  .  com
 * 
 * @return List of completed tasks
 */
public List<Node> getTasksCompleted() {
    if (this.completedTasks == null) {
        // get the current username
        FacesContext context = FacesContext.getCurrentInstance();
        User user = Application.getCurrentUser(context);
        String userName = user.getUserName();

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

            // get the current in progress tasks for the current user
            ClientConfigElement clientConfig = (ClientConfigElement) Application.getConfigService(context)
                    .getGlobalConfig().getConfigElement(ClientConfigElement.CONFIG_ELEMENT_ID);
            WorkflowTaskQuery query = new WorkflowTaskQuery();
            query.setActive(null);
            query.setActorId(userName);
            query.setTaskState(WorkflowTaskState.COMPLETED);
            query.setLimit(clientConfig.getTasksCompletedMaxResults());
            List<WorkflowTask> tasks = this.getWorkflowService().queryTasks(query);

            // create a list of transient nodes to represent
            this.completedTasks = new ArrayList<Node>(tasks.size());
            for (WorkflowTask task : tasks) {
                Node node = createTask(task);
                this.completedTasks.add(node);

                if (logger.isDebugEnabled())
                    logger.debug("Added completed task: " + node);
            }

            // commit the changes
            tx.commit();
        } catch (Throwable e) {
            // rollback the transaction
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception ex) {
            }
            Utils.addErrorMessage("Failed to get completed tasks: " + e.toString(), e);
        }
    }

    return this.completedTasks;
}

From source file:org.alfresco.web.ui.common.component.data.UIRichList.java

/**
 * Sort the dataset using the specified sort parameters
 * /*from  w w w .  java2s .  c  o  m*/
 * @param column        Column to sort
 * @param descending    True for descending sort, false for ascending
 * @param mode          Sort mode to use (see IDataContainer constants)
 */
public void sort(String column, boolean descending, String mode) {
    this.sortColumn = column;
    this.sortDescending = descending;
    this.sortOrPageChanged = true;

    // delegate to the data model to sort its contents
    // place in a UserTransaction as we may need to perform a LOT of node calls to complete
    UserTransaction tx = null;
    try {
        if (getDataModel().size() > 16) {
            FacesContext context = FacesContext.getCurrentInstance();
            tx = Repository.getUserTransaction(context, true);
            tx.begin();
        }

        getDataModel().sort(column, descending, mode);

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

From source file:org.alfresco.web.ui.repo.component.property.BaseAssociationEditor.java

/**
 * Retrieves the available options for the current association
 * /*w  ww.  j a  v  a2  s  .c o m*/
 * @param context Faces Context
 * @param contains The contains part of the query
 */
protected void getAvailableOptions(FacesContext context, String contains) {
    AssociationDefinition assocDef = getAssociationDefinition(context);
    if (assocDef != null) {
        // find and show all the available options for the current association
        String type = assocDef.getTargetClass().getName().toString();

        if (type.equals(ContentModel.TYPE_AUTHORITY_CONTAINER.toString())) {
            UserTransaction tx = null;
            try {
                tx = Repository.getUserTransaction(context, true);
                tx.begin();

                String safeContains = null;
                if (contains != null && contains.length() > 0) {
                    safeContains = Utils.remove(contains.trim(), "\"");
                    safeContains = safeContains.toLowerCase();
                }

                // get all available groups
                AuthorityService authorityService = Repository.getServiceRegistry(context)
                        .getAuthorityService();
                Set<String> groups = authorityService.getAllAuthoritiesInZone(AuthorityService.ZONE_APP_DEFAULT,
                        AuthorityType.GROUP);
                this.availableOptions = new ArrayList<NodeRef>(groups.size());

                // get the NodeRef for each matching group
                AuthorityDAO authorityDAO = (AuthorityDAO) FacesContextUtils
                        .getRequiredWebApplicationContext(context).getBean("authorityDAO");
                if (authorityDAO != null) {
                    List<String> matchingGroups = new ArrayList<String>();

                    String groupDisplayName;
                    for (String group : groups) {
                        // get display name, if not present strip prefix from group id
                        groupDisplayName = authorityService.getAuthorityDisplayName(group);
                        if (groupDisplayName == null || groupDisplayName.length() == 0) {
                            groupDisplayName = group.substring(PermissionService.GROUP_PREFIX.length());
                        }

                        // if a search string is present make sure the group matches
                        // otherwise just add the group name to the sorted set
                        if (safeContains != null) {
                            if (groupDisplayName.toLowerCase().indexOf(safeContains) != -1) {
                                matchingGroups.add(group);
                            }
                        } else {
                            matchingGroups.add(group);
                        }
                    }

                    // sort the group names
                    Collections.sort(matchingGroups, new SimpleStringComparator());

                    // go through the sorted set and get the NodeRef for each group
                    for (String groupName : matchingGroups) {
                        NodeRef groupRef = authorityDAO.getAuthorityNodeRefOrNull(groupName);
                        if (groupRef != null) {
                            this.availableOptions.add(groupRef);
                        }
                    }
                }

                // commit the transaction
                tx.commit();
            } catch (Throwable err) {
                Utils.addErrorMessage(MessageFormat.format(
                        Application.getMessage(context, Repository.ERROR_GENERIC), err.getMessage()), err);
                this.availableOptions = Collections.<NodeRef>emptyList();
                try {
                    if (tx != null) {
                        tx.rollback();
                    }
                } catch (Exception tex) {
                }
            }
        } else if (type.equals(ContentModel.TYPE_PERSON.toString())) {
            List<Pair<QName, String>> filter = (contains != null && contains.trim().length() > 0)
                    ? Utils.generatePersonFilter(contains.trim())
                    : null;

            // Always sort by last name, then first name
            List<Pair<QName, Boolean>> sort = new ArrayList<Pair<QName, Boolean>>();
            sort.add(new Pair<QName, Boolean>(ContentModel.PROP_LASTNAME, true));
            sort.add(new Pair<QName, Boolean>(ContentModel.PROP_FIRSTNAME, true));

            // Log the filtering
            if (logger.isDebugEnabled())
                logger.debug("Query filter: " + filter);

            // How many to limit too?
            int maxResults = Application.getClientConfig(context).getSelectorsSearchMaxResults();
            if (maxResults <= 0) {
                maxResults = Utils.getPersonMaxResults();
            }

            List<PersonInfo> persons = Repository.getServiceRegistry(context).getPersonService()
                    .getPeople(filter, true, sort, new PagingRequest(maxResults, null)).getPage();

            // Save the results
            List<NodeRef> nodes = new ArrayList<NodeRef>(persons.size());
            for (PersonInfo person : persons) {
                nodes.add(person.getNodeRef());
            }
            this.availableOptions = nodes;
        } else {
            // for all other types/aspects perform a lucene search
            StringBuilder query = new StringBuilder("+TYPE:\"");
            if (assocDef.getTargetClass().isAspect()) {
                query = new StringBuilder("+ASPECT:\"");
            } else {
                query = new StringBuilder("+TYPE:\"");
            }

            query.append(type);
            query.append("\"");

            if (contains != null && contains.trim().length() != 0) {
                String safeContains = null;
                if (contains != null && contains.length() > 0) {
                    safeContains = Utils.remove(contains.trim(), "\"");
                    safeContains = safeContains.toLowerCase();
                }

                query.append(" AND +@");
                String nameAttr = Repository
                        .escapeQName(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "name"));
                query.append(nameAttr);
                query.append(":\"*" + safeContains + "*\"");
            }

            int maxResults = Application.getClientConfig(context).getSelectorsSearchMaxResults();

            if (logger.isDebugEnabled()) {
                logger.debug("Query: " + query.toString());
                logger.debug("Max results size: " + maxResults);
            }

            SearchParameters searchParams = new SearchParameters();
            searchParams.addStore(Repository.getStoreRef());
            searchParams.setLanguage(SearchService.LANGUAGE_LUCENE);
            searchParams.setQuery(query.toString());
            if (maxResults > 0) {
                searchParams.setLimit(maxResults);
                searchParams.setLimitBy(LimitBy.FINAL_SIZE);
            }

            ResultSet results = null;
            try {
                results = Repository.getServiceRegistry(context).getSearchService().query(searchParams);
                this.availableOptions = results.getNodeRefs();
            } catch (SearcherException se) {
                logger.info("Search failed for: " + query, se);
                Utils.addErrorMessage(
                        Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_QUERY));
            } finally {
                if (results != null) {
                    results.close();
                }
            }
        }

        if (logger.isDebugEnabled())
            logger.debug("Found " + this.availableOptions.size() + " available options");
    }
}

From source file:org.alfresco.web.ui.repo.component.UINavigator.java

/**
 * @see javax.faces.component.UIInput#broadcast(javax.faces.event.FacesEvent)
 *//*  w  w w  . j a  v  a2s . c  o  m*/
public void broadcast(FacesEvent event) throws AbortProcessingException {
    if (event instanceof NavigatorEvent) {
        FacesContext context = FacesContext.getCurrentInstance();
        NavigatorEvent navEvent = (NavigatorEvent) event;

        // node or panel selected?
        switch (navEvent.getMode()) {
        case PANEL_SELECTED: {
            String panelSelected = navEvent.getItem();

            // a panel was selected, setup the context to make the panel
            // the focus
            NavigationBean nb = (NavigationBean) FacesHelper.getManagedBean(context, NavigationBean.BEAN_NAME);
            if (nb != null) {
                try {
                    if (logger.isDebugEnabled())
                        logger.debug("Selecting panel: " + panelSelected);

                    nb.processToolbarLocation(panelSelected, true);
                } catch (InvalidNodeRefException refErr) {
                    Utils.addErrorMessage(MessageFormat.format(
                            Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NOHOME),
                            Application.getCurrentUser(context).getHomeSpaceId()), refErr);
                } catch (Exception err) {
                    Utils.addErrorMessage(MessageFormat.format(
                            Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC),
                            err.getMessage()), err);
                }
            }

            break;
        }
        case NODE_SELECTED: {
            // a node was clicked in the tree
            boolean nodeExists = true;
            NodeRef nodeClicked = new NodeRef(navEvent.getItem());

            // make sure the node exists still before navigating to it
            UserTransaction tx = null;
            try {
                tx = Repository.getUserTransaction(context, true);
                tx.begin();

                NodeService nodeSvc = Repository.getServiceRegistry(context).getNodeService();
                nodeExists = nodeSvc.exists(nodeClicked);

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

            if (nodeExists) {
                // setup the context to make the node the current node
                BrowseBean bb = (BrowseBean) FacesHelper.getManagedBean(context, BrowseBean.BEAN_NAME);
                if (bb != null) {
                    if (logger.isDebugEnabled())
                        logger.debug("Selected node: " + nodeClicked);

                    bb.clickSpace(nodeClicked);
                }
            } else {
                String msg = Application.getMessage(context, "navigator_node_deleted");
                Utils.addErrorMessage(msg);
            }

            break;
        }
        }
    } else {
        super.broadcast(event);
    }
}