Example usage for javax.transaction UserTransaction rollback

List of usage examples for javax.transaction UserTransaction rollback

Introduction

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

Prototype

void rollback() throws IllegalStateException, SecurityException, SystemException;

Source Link

Document

Roll back the transaction associated with the current thread.

Usage

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  www  . j a v  a 2  s  .  c om*/
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 w  w .  j  ava 2  s .  c o 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/* w  w w. ja  v  a  2s  .  com*/
 */
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) {
        }
    }
}

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

/**
 * Event handler that transitions a 'submitpending' task to effectively
 * bypass the lauch date and immediately submit the items.
 * /*w  w  w  . j ava  2  s . c  o m*/
 * @param event The event
 */
public void promotePendingSubmission(ActionEvent event) {
    UIActionLink link = (UIActionLink) event.getComponent();
    Map<String, String> params = link.getParameterMap();
    String taskId = params.get("taskId");

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

        // transition the task
        this.getWorkflowService().endTask(taskId, "launch");

        // commit the transaction
        tx.commit();
    } 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.wcm.AVMBrowseBean.java

/**
 * Event handler that cancels a pending submission.
 * //  w  w w  .  j a va  2 s  .  c om
 * @param event The event
 */
public void cancelPendingSubmission(ActionEvent event) {
    UIActionLink link = (UIActionLink) event.getComponent();
    Map<String, String> params = link.getParameterMap();
    String workflowId = params.get("workflowInstanceId");

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

        // cancel the workflow
        this.getWorkflowService().cancelWorkflow(workflowId);

        // commit the transaction
        tx.commit();
    } 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.wcm.AVMEditBean.java

/**
 * Action called upon completion of the Update File page
 *///w w  w  .  jav  a2 s .co  m
public String updateFileOK() {
    String outcome = null;

    UserTransaction tx = null;

    AVMNode node = getAvmNode();
    if (node != null && this.getFileName() != null) {
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            tx = Repository.getUserTransaction(context);
            tx.begin();

            // get an updating writer that we can use to modify the content on the current node
            final ContentWriter writer = this.getAvmService().getContentWriter(node.getPath(), true);

            // also update the mime type in case a different type of file is uploaded
            String mimeType = Repository.getMimeTypeForFileName(context, this.fileName);
            writer.setMimetype(mimeType);
            writer.putContent(this.file);

            // commit the transaction
            tx.commit();
            if (this.getAvmService().hasAspect(-1, node.getPath(), WCMAppModel.ASPECT_FORM_INSTANCE_DATA)) {
                this.regenerateRenditions();
            }
            // Possibly notify virt server
            AVMUtil.updateVServerWebapp(node.getPath(), false);

            // clear action context
            resetState();

            outcome = AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME;
        } catch (Throwable err) {
            // rollback the transaction
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }
            Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_UPDATE)
                    + err.getMessage(), err);
        }
    }

    return outcome;
}

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

@Override
public void init(Map<String, String> parameters) {
    super.init(parameters);

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

    try {/*w  w w . java 2s .  com*/
        tx = Repository.getUserTransaction(context, true);
        tx.begin();

        // try and retrieve the link validation report from the workflow
        // store, if present setup the validation state on AVMBrowseBean
        this.store = this.workflowPackage.getStoreRef().getIdentifier();

        // get the web project noderef for the workflow store
        String wpStoreId = WCMUtil.getWebProjectStoreId(this.store);
        this.webProjectRef = getWebProjectService()
                .getWebProjectNodeFromStore(WCMUtil.getWebProjectStoreId(this.store));

        if (this.webProjectRef == null) {
            String mesg = MessageFormat.format(Application.getMessage(context, MSG_WEB_PRJ_DOES_NOT_EXIST),
                    wpStoreId);
            throw new AlfrescoRuntimeException(mesg);
        }

        // commit the changes
        tx.commit();
    } catch (Throwable e) {
        // rollback the transaction
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
        }
        Utils.addErrorMessage(formatErrorMessage(e), e);
    }
}

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

/**
 * Query callback method executed by the Generic Picker component. This method is part of the contract to the Generic Picker, it is up to the backing bean to execute whatever
 * query is appropriate and return the results.
 * //from   w  w w  .j  ava  2s . co  m
 * @param filterIndex Index of the filter drop-down selection
 * @param contains Text from the contains textbox
 * @return An array of SelectItem objects containing the results to display in the picker.
 */
public SelectItem[] pickerCallback(int filterIndex, String contains) {
    FacesContext context = FacesContext.getCurrentInstance();

    SelectItem[] items;

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

        List<SelectItem> results = new ArrayList<SelectItem>();

        if (filterIndex == 0) {
            List<PersonInfo> persons = getPersonService().getPeople(Utils.generatePersonFilter(contains.trim()),
                    true, Utils.generatePersonSort(), new PagingRequest(Utils.getPersonMaxResults(), null))
                    .getPage();

            for (int index = 0; index < persons.size(); index++) {
                PersonInfo person = persons.get(index);
                String firstName = person.getFirstName();
                String lastName = person.getLastName();
                String username = person.getUserName();
                if (username != null) {
                    SelectItem item = new SortableSelectItem(username,
                            firstName + " " + lastName + " [" + username + "]", lastName);
                    results.add(item);
                }
            }
        } else {
            Set<String> groups;

            if (contains != null && contains.startsWith("*")) {
                // if the search term starts with a wildcard use Lucene based search to find groups (results will be inconsistent)
                String term = contains.trim() + "*";
                groups = getAuthorityService().findAuthorities(AuthorityType.GROUP, null, false, term,
                        AuthorityService.ZONE_APP_DEFAULT);
            } else {
                // all other searches use the canned query so search results are consistent
                PagingResults<String> pagedResults = getAuthorityService().getAuthorities(AuthorityType.GROUP,
                        AuthorityService.ZONE_APP_DEFAULT, contains, true, true, new PagingRequest(10000));
                groups = new LinkedHashSet<String>(pagedResults.getPage());
            }

            // add the EVERYONE group to the results
            groups.addAll(getAuthorityService().getAllAuthorities(AuthorityType.EVERYONE));

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

                results.add(new SortableSelectItem(group, groupDisplayName, groupDisplayName));
            }
        }

        items = new SelectItem[results.size()];
        results.toArray(items);
        Arrays.sort(items);

        // commit the transaction
        tx.commit();
    } 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) {
        }

        items = new SelectItem[0];
    }

    return items;
}

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

/**
 * Calculate the lists of Submittable Items, Warning items and the list of available workflows.
 *///from  w w w. j a va  2 s .  com
private void calcluateListItemsAndWorkflows() {
    UserTransaction tx = null;

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

        List<AVMNodeDescriptor> selected;
        if (this.loadSelectedNodesFromBrowseBean) {
            // if the dialog was started from a workflow the AVM browse bean should
            // have the list of nodes that need submitting
            selected = this.avmBrowseBean.getNodesForSubmit();
            this.avmBrowseBean.setNodesForSubmit(null);
        }
        // if the dialog was started from the UI determine what nodes the user selected to submit
        else if (this.avmBrowseBean.getAllItemsAction()) {
            String webapp = this.avmBrowseBean.getWebapp();
            String userStore = AVMUtil.buildStoreWebappPath(this.avmBrowseBean.getSandbox(), webapp);
            String stagingStore = AVMUtil.buildStoreWebappPath(this.avmBrowseBean.getStagingStore(), webapp);
            List<AVMDifference> diffs = this.getAvmSyncService().compare(-1, userStore, -1, stagingStore,
                    getNameMatcher());
            selected = new ArrayList<AVMNodeDescriptor>(diffs.size());
            for (AVMDifference diff : diffs) {
                selected.add(getAvmService().lookup(-1, diff.getSourcePath(), true));
            }
        } else if (this.avmBrowseBean.getAvmActionNode() == null) {
            // multiple items selected
            selected = this.avmBrowseBean.getSelectedSandboxItems();
        } else {
            // single item selected
            selected = new ArrayList<AVMNodeDescriptor>(1);
            selected.add(getAvmService().lookup(-1, this.avmBrowseBean.getAvmActionNode().getPath(), true));
        }

        if (selected == null) {
            this.submitItems = Collections.<ItemWrapper>emptyList();
            this.warningItems = Collections.<ItemWrapper>emptyList();
        } else {
            Set<String> submittedPaths = new HashSet<String>(selected.size());
            this.submitItems = new ArrayList<ItemWrapper>(selected.size());
            this.warningItems = new ArrayList<ItemWrapper>(selected.size() >> 1);

            for (AVMNodeDescriptor node : selected) {
                if (AVMWorkflowUtil.isInActiveWorkflow(AVMUtil.getStoreName(node.getPath()), node)) {
                    this.warningItems.add(new ItemWrapper(node));
                    continue;
                }
                NodeRef ref = AVMNodeConverter.ToNodeRef(-1, node.getPath());
                if (submittedPaths.contains(node.getPath())) {
                    continue;
                }

                boolean isForm = getNodeService().hasAspect(ref, WCMAppModel.ASPECT_FORM_INSTANCE_DATA);
                boolean isRendition = getNodeService().hasAspect(ref, WCMAppModel.ASPECT_RENDITION);

                if (((!isForm) && (!isRendition)) || (node.isDeleted() && (!isForm))) {
                    // found single item for submit
                    // note: could be a single deleted rendition - to enable deletion of old renditions (eg. if template no longer applicable)
                    this.submitItems.add(new ItemWrapper(node));
                    submittedPaths.add(node.getPath());
                } else {
                    // item is a form (note: could be deleted) or a rendition

                    FormInstanceData fid = null;
                    try {
                        if (isRendition) {
                            // found a generated rendition asset - locate the parent form instance data file
                            // and use this to find all generated assets that are appropriate
                            // NOTE: this path value is store relative
                            fid = getFormsService().getRendition(ref).getPrimaryFormInstanceData(true);
                        } else {
                            fid = getFormsService().getFormInstanceData(ref);
                        }
                    } catch (FormNotFoundException fnfe) {
                        logger.warn(fnfe);
                    }

                    if (fid != null) {
                        // add the form instance data file to the list for submission
                        if (!submittedPaths.contains(fid.getPath())) {
                            this.submitItems
                                    .add(new ItemWrapper(getAvmService().lookup(-1, fid.getPath(), true)));
                            submittedPaths.add(fid.getPath());
                        }

                        // locate renditions for this form instance data file and add to list for submission
                        for (final Rendition rendition : fid.getRenditions(true)) {
                            final String renditionPath = rendition.getPath();
                            if (!submittedPaths.contains(renditionPath)) {
                                this.submitItems
                                        .add(new ItemWrapper(getAvmService().lookup(-1, renditionPath, true)));
                                submittedPaths.add(renditionPath);
                            }
                        }

                        // lookup the workflow defaults for that form and store into the list of available workflows
                        Form f = null;
                        try {
                            f = fid.getForm();
                            WorkflowDefinition defaultWfDef = f.getDefaultWorkflow();
                            if (defaultWfDef != null) {
                                this.workflows.add(new FormWorkflowWrapper(defaultWfDef.getName(),
                                        fid.getForm().getDefaultWorkflowParameters()));
                            }
                        } catch (FormNotFoundException fnfe) {
                            logger.warn(fnfe);
                        }
                    }

                    // See WCM-1090 ACT-1551
                    // cannot depend on renditions of the form instance to contain the present
                    // node. Add it here if it hasn't been added by the above process.
                    if (!submittedPaths.contains(node.getPath())) {
                        this.submitItems.add(new ItemWrapper(node));
                        submittedPaths.add(node.getPath());
                    }
                }
            }
        }

        tx.commit();
    } catch (Throwable e) {
        // rollback the transaction on error
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
        }

        // rethrow the exception to highlight the problem
        throw (RuntimeException) e;
    }
}

From source file:org.alfresco.web.bean.wizard.BaseInviteUsersWizard.java

/**
 * Query callback method executed by the Generic Picker component.
 * This method is part of the contract to the Generic Picker, it is up to the backing bean
 * to execute whatever query is appropriate and return the results.
 * //  w  w  w.j  a  v  a 2 s .  c o  m
 * @param filterIndex        Index of the filter drop-down selection
 * @param contains           Text from the contains textbox
 * 
 * @return An array of SelectItem objects containing the results to display in the picker.
 */
public SelectItem[] pickerCallback(int filterIndex, String contains) {
    FacesContext context = FacesContext.getCurrentInstance();

    // quick exit if not enough characters entered for a search
    String search = contains.trim();
    int searchMin = Application.getClientConfig(context).getPickerSearchMinimum();
    if (search.length() < searchMin) {
        Utils.addErrorMessage(
                MessageFormat.format(Application.getMessage(context, MSG_SEARCH_MINIMUM), searchMin));
        return new SelectItem[0];
    }

    SelectItem[] items;
    this.maxUsersReturned = false;

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

        int maxResults = Application.getClientConfig(context).getInviteUsersMaxResults();
        if (maxResults <= 0) {
            maxResults = Utils.getPersonMaxResults();
        }

        List<SelectItem> results;

        if (filterIndex == 0) {
            // Use lucene search to retrieve user details
            List<Pair<QName, String>> filter = null;
            if (search == null || search.length() == 0) {
                // if there is no search term, search for all people
            } else {
                filter = Utils.generatePersonFilter(search);
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Maximum invite users results size: " + maxResults);
                logger.debug("Using query filter to find users: " + filter);
            }

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

            results = new ArrayList<SelectItem>(persons.size());
            for (int index = 0; index < persons.size(); index++) {
                PersonInfo person = persons.get(index);

                String firstName = person.getFirstName();
                String lastName = person.getLastName();
                String username = person.getUserName();
                if (username != null) {
                    String name = (firstName != null ? firstName : "") + ' '
                            + (lastName != null ? lastName : "");
                    SelectItem item = new SortableSelectItem(username, name + " [" + username + "]",
                            lastName != null ? lastName : username);
                    results.add(item);
                }
            }
        } else {
            results = addGroupItems(search, maxResults);
        }

        items = new SelectItem[results.size()];
        results.toArray(items);
        Arrays.sort(items);

        // set the maximum users returned flag if appropriate
        if (results.size() == maxResults) {
            this.maxUsersReturned = true;
        }

        // commit the transaction
        tx.commit();
    } catch (BooleanQuery.TooManyClauses clauses) {
        Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), "too_many_users"));

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

        items = new SelectItem[0];
    } 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) {
        }

        items = new SelectItem[0];
    }

    return items;
}