List of usage examples for javax.transaction UserTransaction begin
void begin() throws NotSupportedException, SystemException;
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. * //from w w w . ja va 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.ja v a 2 s . com*/ * @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 *///from w ww. j a va 2 s .c o 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 {/*from w w w . ja va2s. c o m*/ 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 ww . j a v a 2 s. 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 2s .co m*/ 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. * //from w w w . j av a 2 s . 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(); // 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; }
From source file:org.alfresco.web.bean.wizard.NewUserWizard.java
/** * @see org.alfresco.web.bean.wizard.AbstractWizardBean#finish() *///from w w w . ja v a2 s. c om public String finish() { String outcome = FINISH_OUTCOME; // TODO: implement create new Person object from specified details UserTransaction tx = null; try { FacesContext context = FacesContext.getCurrentInstance(); tx = Repository.getUserTransaction(context); tx.begin(); if (this.editMode) { // update the existing node in the repository NodeRef nodeRef = getPerson().getNodeRef(); Map<QName, Serializable> props = this.getNodeService().getProperties(nodeRef); props.put(ContentModel.PROP_USERNAME, this.userName); props.put(ContentModel.PROP_FIRSTNAME, this.firstName); props.put(ContentModel.PROP_LASTNAME, this.lastName); // calculate whether we need to move the old home space or create new NodeRef newHomeFolderRef; NodeRef oldHomeFolderRef = (NodeRef) this.getNodeService().getProperty(nodeRef, ContentModel.PROP_HOMEFOLDER); boolean moveHomeSpace = false; boolean renameHomeSpace = false; if (oldHomeFolderRef != null && this.getNodeService().exists(oldHomeFolderRef) == true) { // the original home folder ref exists so may need moving if it has been changed ChildAssociationRef childAssocRef = this.getNodeService().getPrimaryParent(oldHomeFolderRef); NodeRef currentHomeSpaceLocation = childAssocRef.getParentRef(); if (this.homeSpaceName.length() != 0) { if (currentHomeSpaceLocation.equals(this.homeSpaceLocation) == false && oldHomeFolderRef.equals(this.homeSpaceLocation) == false && currentHomeSpaceLocation.equals(getCompanyHomeSpace()) == false && currentHomeSpaceLocation.equals(getDefaultHomeSpace()) == false) { moveHomeSpace = true; } String oldHomeSpaceName = Repository.getNameForNode(getNodeService(), oldHomeFolderRef); if (oldHomeSpaceName.equals(this.homeSpaceName) == false && oldHomeFolderRef.equals(this.homeSpaceLocation) == false && oldHomeFolderRef.equals(this.defaultHomeSpaceRef) == false) { renameHomeSpace = true; } } } if (logger.isDebugEnabled()) logger.debug("Moving space: " + moveHomeSpace + " and renaming space: " + renameHomeSpace); if (moveHomeSpace == false && renameHomeSpace == false) { if (this.homeSpaceLocation != null && this.homeSpaceName.length() != 0) { newHomeFolderRef = createHomeSpace(this.homeSpaceLocation.getId(), this.homeSpaceName, false); } else if (this.homeSpaceLocation != null) { // location selected but no home space name entered, // so the home ref should be set to the newly selected space newHomeFolderRef = this.homeSpaceLocation; // set the permissions for this space so the user can access it } else { // nothing selected - use Company Home by default newHomeFolderRef = getCompanyHomeSpace(); } } else { // either move, rename or both required if (moveHomeSpace == true) { this.getNodeService().moveNode(oldHomeFolderRef, this.homeSpaceLocation, ContentModel.ASSOC_CONTAINS, this.getNodeService().getPrimaryParent(oldHomeFolderRef).getQName()); } newHomeFolderRef = oldHomeFolderRef; // ref ID doesn't change if (renameHomeSpace == true) { // change HomeSpace node name this.getNodeService().setProperty(newHomeFolderRef, ContentModel.PROP_NAME, this.homeSpaceName); } } props.put(ContentModel.PROP_HOMEFOLDER, newHomeFolderRef); props.put(ContentModel.PROP_EMAIL, this.email); props.put(ContentModel.PROP_ORGID, this.companyId); this.getNodeService().setProperties(nodeRef, props); // TODO: RESET HomeSpace Ref found in top-level navigation bar! // NOTE: not need cos only admin can do this? } else { if (tenantService.isEnabled()) { String currentDomain = tenantService.getCurrentUserDomain(); if (!currentDomain.equals(TenantService.DEFAULT_DOMAIN)) { if (!tenantService.isTenantUser(this.userName)) { // force domain onto the end of the username this.userName = tenantService.getDomainUser(this.userName, currentDomain); logger.warn("Added domain to username: " + this.userName); } else { try { tenantService.checkDomainUser(this.userName); } catch (RuntimeException re) { throw new AuthenticationException( "User must belong to same domain as admin: " + currentDomain); } } } } if (this.password.equals(this.confirm)) { // create properties for Person type from submitted Form data Map<QName, Serializable> props = new HashMap<QName, Serializable>(7, 1.0f); props.put(ContentModel.PROP_USERNAME, this.userName); props.put(ContentModel.PROP_FIRSTNAME, this.firstName); props.put(ContentModel.PROP_LASTNAME, this.lastName); NodeRef homeSpaceNodeRef; if (this.homeSpaceLocation != null && this.homeSpaceName.length() != 0) { // create new homeSpaceNodeRef = createHomeSpace(this.homeSpaceLocation.getId(), this.homeSpaceName, true); } else if (this.homeSpaceLocation != null) { // set to existing homeSpaceNodeRef = homeSpaceLocation; setupHomeSpacePermissions(homeSpaceNodeRef); } else { // default to Company Home homeSpaceNodeRef = getCompanyHomeSpace(); } props.put(ContentModel.PROP_HOMEFOLDER, homeSpaceNodeRef); props.put(ContentModel.PROP_EMAIL, this.email); props.put(ContentModel.PROP_ORGID, this.companyId); // create the node to represent the Person NodeRef newPerson = this.getPersonService().createPerson(props); // ensure the user can access their own Person object this.getPermissionService().setPermission(newPerson, this.userName, getPermissionService().getAllPermission(), true); if (logger.isDebugEnabled()) logger.debug("Created Person node for username: " + this.userName); // create the ACEGI Authentication instance for the new user this.getAuthenticationService().createAuthentication(this.userName, this.password.toCharArray()); if (logger.isDebugEnabled()) logger.debug("Created User Authentication instance for username: " + this.userName); } else { outcome = null; Utils.addErrorMessage(Application.getMessage(context, UsersDialog.ERROR_PASSWORD_MATCH)); } } // commit the transaction tx.commit(); // reset the richlist component so it rebinds to the users list invalidateUserList(); } catch (Throwable e) { // rollback the transaction try { if (tx != null) { tx.rollback(); } } catch (Exception tex) { } Utils.addErrorMessage(MessageFormat .format(Application.getMessage(FacesContext.getCurrentInstance(), ERROR), e.getMessage()), e); outcome = null; } return outcome; }
From source file:org.alfresco.web.bean.workflow.ManageTaskDialog.java
@SuppressWarnings("deprecation") public String takeOwnership() { String outcome = getDefaultFinishOutcome(); if (LOGGER.isDebugEnabled()) LOGGER.debug("Taking ownership of task: " + this.getWorkflowTask().id); FacesContext context = FacesContext.getCurrentInstance(); // before taking ownership check the task still exists and is not // completed// ww w. ja va 2 s.co m WorkflowTask checkTask = this.getWorkflowService().getTaskById(this.getWorkflowTask().id); if (checkTask == null || checkTask.state == WorkflowTaskState.COMPLETED) { Utils.addErrorMessage(Application.getMessage(context, "invalid_task")); return outcome; } UserTransaction tx = null; try { tx = Repository.getUserTransaction(context); tx.begin(); // prepare the edited parameters for saving User user = Application.getCurrentUser(context); String userName = user.getUserName(); Map<QName, Serializable> params = new HashMap<QName, Serializable>(); params.put(ContentModel.PROP_OWNER, userName); // update the task with the updated parameters and resources updateResources(); this.getWorkflowService().updateTask(this.getWorkflowTask().id, params, null, null); // 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); outcome = this.getErrorOutcome(e); } return outcome; }
From source file:org.alfresco.web.bean.workflow.ManageTaskDialog.java
@SuppressWarnings("deprecation") public String returnOwnership() { String outcome = getDefaultFinishOutcome(); if (LOGGER.isDebugEnabled()) LOGGER.debug("Returning ownership of task to pool: " + this.getWorkflowTask().id); FacesContext context = FacesContext.getCurrentInstance(); // before returning ownership check the task still exists and is not // completed//w w w . j ava2 s .c o m WorkflowTask checkTask = this.getWorkflowService().getTaskById(this.getWorkflowTask().id); if (checkTask == null || checkTask.state == WorkflowTaskState.COMPLETED) { Utils.addErrorMessage(Application.getMessage(context, "invalid_task")); return outcome; } UserTransaction tx = null; try { tx = Repository.getUserTransaction(context); tx.begin(); // prepare the edited parameters for saving Map<QName, Serializable> params = new HashMap<QName, Serializable>(); params.put(ContentModel.PROP_OWNER, null); // update the task with the updated parameters and resources updateResources(); this.getWorkflowService().updateTask(this.getWorkflowTask().id, params, null, null); // 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); outcome = this.getErrorOutcome(e); } return outcome; }