List of usage examples for javax.transaction UserTransaction rollback
void rollback() throws IllegalStateException, SecurityException, SystemException;
From source file:org.alfresco.web.ui.common.component.data.UIRichList.java
/** * Sort the dataset using the specified sort parameters * /*w w w . j a va 2s . 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 w w.j a v a 2 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) *//*from ww w. j a va 2s.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); } }
From source file:org.alfresco.web.ui.wcm.component.UIDeploymentReports.java
/** * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext) *//*from w w w . j a v a 2s. c o m*/ @SuppressWarnings("unchecked") public void encodeBegin(FacesContext context) throws IOException { if (isRendered() == false) { return; } ResponseWriter out = context.getResponseWriter(); UserTransaction tx = null; try { tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); tx.begin(); String storeName = getValue(); if (storeName == null) { throw new IllegalArgumentException("The store must be specified."); } boolean showPrevious = getShowPrevious(); if (showPrevious) { renderPreviousReports(context, out, storeName); } else { renderAttempt(context, out, storeName); } tx.commit(); } catch (Throwable err) { try { if (tx != null) { tx.rollback(); } } catch (Exception tex) { } throw new RuntimeException(err); } }
From source file:org.alfresco.web.ui.wcm.component.UIDeployWebsite.java
@Override public void encodeBegin(FacesContext context) throws IOException { if (isRendered() == false) { return;/*from ww w.j ava2s .co m*/ } ResponseWriter out = context.getResponseWriter(); UserTransaction tx = null; try { tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); tx.begin(); NodeRef webProject = this.getWebsite(); if (webProject == null) { throw new IllegalArgumentException("The web project must be specified."); } NodeService nodeService = Repository.getServiceRegistry(context).getNodeService(); out.write("<script type='text/javascript' src='"); out.write(context.getExternalContext().getRequestContextPath()); out.write("/scripts/select-all.js'></script>\n"); // add some before the panels out.write("\n<div style='padding-top:4px;'></div>\n"); if (this.getMonitor()) { // get the ids of the deployment monitor objects List<String> deployMonitorIds = this.getMonitorIds(); if (logger.isDebugEnabled()) { logger.debug("Monitoring deployment of: " + deployMonitorIds); } // TODO: Add support for 'sniffing' the session for deployment monitors // this could be useful when the monitor ids are not known // render the supporting script required for monitoring renderScript(context, out, deployMonitorIds); // render each server being deployed with an animated icon, the subsequent // AJAX callback will update the progress. for (String id : deployMonitorIds) { // try and find the monitor object in the session, if it's not there // it has probably completed and been removed DeploymentMonitor monitor = (DeploymentMonitor) context.getExternalContext().getSessionMap() .get(id); if (monitor != null) { if (logger.isDebugEnabled()) logger.debug("Found deployment monitor: " + monitor); renderMonitoredServer(context, out, nodeService, monitor.getTargetServer(), id); } } } else { if (WCMAppModel.CONSTRAINT_TESTSERVER.equals(getDeployMode())) { // determine the state, the sandbox may already have a test server // allocated, in which case we need to allow the user to preview or // re-deploy. If this is the first deployment or the test server has // been removed then show a list of available test servers to choose // from. List<NodeRef> allocatedServers = DeploymentUtil.findAllocatedTestServers(getStore()); if (!allocatedServers.isEmpty()) { // there is at least one allocated server for (NodeRef allocatedServer : allocatedServers) { renderAllocatedTestServer(context, out, nodeService, allocatedServer); } } else { // a test server(s) needs to be selected - display the list of test servers List<NodeRef> refs = Repository.getServiceRegistry(context).getDeploymentService() .findTestDeploymentServers(webProject, true); // Resolve the unsorted list of NodeRef to a sorted list of DeploymentServerConfig. List<DeploymentServerConfig> servers = toSortedDeploymentServerConfig(nodeService, refs); if (servers.size() > 0) { ParentChildCheckboxHelper helper = new ParentChildCheckboxHelper( this.getClientId(context)); boolean selected = false; for (DeploymentServerConfig server : servers) { // Get the display group String displayGroup = (String) server.getProperties() .get(DeploymentServerConfig.PROP_GROUP); helper.setCurrentDisplayGroup(displayGroup); if (helper.newGroup) { out.write("<p class='mainSubTitle'>"); out.write("<input type='checkbox' id='"); out.write(helper.groupParentId); out.write("' value='"); out.write(Utils.encode(displayGroup)); out.write("'"); out.write(" "); out.write("onClick=\"select_all(\'"); out.write(helper.groupChildName); out.write("\', this.checked);\" "); out.write(" /> "); out.write(Utils.encode(displayGroup)); out.write("</p>"); } if (helper.groupParentId.length() > 0) { // render the test server with a child checkbox renderCheckableServer(context, out, nodeService, server.getServerRef(), selected, helper.groupChildName, helper.groupParentId); } else { // render the test server without a parent checkbox renderCheckableServer(context, out, nodeService, server.getServerRef(), selected, this.getClientId(context)); } } } else { // show the none available message out.write("<div class='deployServersInfo'><img src='"); out.write(context.getExternalContext().getRequestContextPath()); out.write("/images/icons/info_icon.gif' /> "); out.write(Application.getMessage(context, "deploy_test_server_not_available")); out.write("</div>\n"); out.write("<script type='text/javascript'>\n"); out.write("disableOKButton = function() { "); out.write("document.getElementById('dialog:finish-button').disabled = true; }\n"); out.write("window.onload = disableOKButton;\n"); out.write("</script>\n"); } } } else { // Display live servers not test servers // TODO: get a list of the servers that have been successfully deployed to List<NodeRef> refs = Repository.getServiceRegistry(context).getDeploymentService() .findLiveDeploymentServers(webProject); // Resolve the unsorted list of NodeRef to a sorted list of DeploymentServerConfig. List<DeploymentServerConfig> servers = toSortedDeploymentServerConfig(nodeService, refs); ParentChildCheckboxHelper helper = new ParentChildCheckboxHelper(this.getClientId(context)); // Now display the servers for (DeploymentServerConfig server : servers) { // TODO: determine if the server has already been successfully deployed to boolean selected = true; // Get the display group String displayGroup = (String) server.getProperties() .get(DeploymentServerConfig.PROP_GROUP); helper.setCurrentDisplayGroup(displayGroup); if (helper.newGroup) { out.write("<p class='mainSubTitle'>"); out.write("<input type='checkbox' id='"); out.write(helper.groupParentId); out.write("' value='"); out.write(Utils.encode(displayGroup)); out.write("'"); out.write(" checked='checked' "); out.write("onClick=\"select_all(\'"); out.write(helper.groupChildName); out.write("\', this.checked);\" "); out.write(" /> "); out.write(Utils.encode(displayGroup)); out.write("</p>"); } if (helper.groupParentId.length() > 0) { // render the live server with a child checkbox renderCheckableServer(context, out, nodeService, server.getServerRef(), selected, helper.groupChildName, helper.groupParentId); } else { // render the live server without a parent checkbox renderCheckableServer(context, out, nodeService, server.getServerRef(), selected, this.getClientId(context)); } } } } tx.commit(); } catch (Throwable err) { try { if (tx != null) { tx.rollback(); } } catch (Exception tex) { } throw new RuntimeException(err); } }
From source file:org.alfresco.web.ui.wcm.component.UIPendingSubmissions.java
/** * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext) *//*from www . j a v a 2s .co m*/ @SuppressWarnings("unchecked") public void encodeBegin(FacesContext context) throws IOException { if (isRendered() == false) { return; } ResponseWriter out = context.getResponseWriter(); ResourceBundle bundle = Application.getBundle(context); UserTransaction tx = null; try { tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); tx.begin(); String sandbox = getValue(); if (sandbox == null) { throw new IllegalArgumentException("Sandbox must be specified."); } // get the preview url for the sandbox String sandboxPreviewUrl = AVMUtil.getPreviewURI(sandbox); // get the noderef representing the web project PropertyValue val = Repository.getServiceRegistry(context).getAVMService().getStoreProperty(sandbox, SandboxConstants.PROP_WEB_PROJECT_NODE_REF); NodeRef webProject = (NodeRef) val.getValue(DataTypeDefinition.NODE_REF); // get the list of pending tasks for this project WorkflowTaskQuery query = new WorkflowTaskQuery(); query.setTaskName(QName.createQName(NamespaceService.WCMWF_MODEL_1_0_URI, "submitpendingTask")); query.setTaskState(WorkflowTaskState.IN_PROGRESS); Map<QName, Object> processProps = new HashMap<QName, Object>(); processProps.put(WCMWorkflowModel.ASSOC_WEBPROJECT, webProject); query.setProcessCustomProps(processProps); query.setOrderBy(new WorkflowTaskQuery.OrderBy[] { WorkflowTaskQuery.OrderBy.TaskDue_Desc, WorkflowTaskQuery.OrderBy.TaskActor_Asc }); List<WorkflowTask> pendingTasks = Repository.getServiceRegistry(context).getWorkflowService() .queryTasks(query); if (pendingTasks.size() == 0) { out.write(bundle.getString(MSG_NO_PENDING)); } else { // output the javascript to handle the visual diff out.write("<script type='text/javascript'>"); out.write("\nfunction diff(pendingStoreUrl, stagingStoreUrl) {"); out.write("\nwindow.open(pendingStoreUrl, 'pendingPreview', "); out.write("'left=40,top=150,width=450,height=300,scrollbars=yes,resizable=yes');"); out.write("\nwindow.open(stagingStoreUrl, 'stagingPreview', "); out.write("'left=520,top=150,width=450,height=300,scrollbars=yes,resizable=yes');"); out.write("\n}\n</script>"); // output header row out.write("<table class='pendingSubmissionsList' cellspacing=2 cellpadding=1 border=0 width=100%>"); out.write("<tr align=left><th>"); out.write(bundle.getString(MSG_DESCRIPTION)); out.write("</th><th>"); out.write(bundle.getString(MSG_LABEL)); out.write("</th><th>"); out.write(bundle.getString(MSG_SUBMITTED)); out.write("</th><th>"); out.write(bundle.getString(MSG_USERNAME)); out.write("</th><th>"); out.write(bundle.getString(MSG_LAUNCH_DATE)); out.write("</th><th>"); out.write(bundle.getString(MSG_ACTIONS)); out.write("</th></tr>"); // output the pending submissions and their actions Map requestMap = context.getExternalContext().getRequestMap(); for (WorkflowTask task : pendingTasks) { String desc = (String) task.properties.get(WorkflowModel.PROP_DESCRIPTION); String label = (String) task.properties.get(WCMWorkflowModel.PROP_LABEL); String submitted = Utils.getDateTimeFormat(context).format(task.path.instance.startDate); String username = (String) Repository.getServiceRegistry(context).getNodeService() .getProperty(task.path.instance.initiator, ContentModel.PROP_USERNAME); Date launchDate = (Date) task.properties.get(WCMWorkflowModel.PROP_LAUNCH_DATE); String launch = Utils.getDateTimeFormat(context).format(launchDate); out.write("<tr><td>"); // show task link UIActionLink showTask = findAction(ACT_SHOW_TASK, sandbox); if (showTask == null) { Map<String, String> params = new HashMap<String, String>(1); params.put("id", "#{" + REQUEST_TASKID + "}"); params.put("type", "#{" + REQUEST_TASKTYPE + "}"); showTask = createAction(context, sandbox, ACT_SHOW_TASK, "#{" + REQUEST_LABEL + "}", null, "#{WorkflowBean.setupTaskDialog}", "dialog:manageTask", null, params); } requestMap.put(REQUEST_LABEL, desc); requestMap.put(REQUEST_TASKID, task.id); requestMap.put(REQUEST_TASKTYPE, task.definition.metadata.getName().toString()); Utils.encodeRecursive(context, showTask); requestMap.remove(REQUEST_LABEL); requestMap.remove(REQUEST_TASKID); requestMap.remove(REQUEST_TASKTYPE); out.write("</td><td>"); out.write(Utils.encode(label)); out.write("</td><td>"); out.write(submitted); out.write("</td><td>"); out.write(Utils.encode(username)); out.write("</td><td>"); out.write(launch); out.write("</td><td><nobr>"); // details action UIActionLink details = findAction(ACT_DETAILS, sandbox); if (details == null) { Map<String, String> params = new HashMap<String, String>(1); params.put("id", "#{" + REQUEST_TASKID + "}"); params.put("type", "#{" + REQUEST_TASKTYPE + "}"); details = createAction(context, sandbox, ACT_DETAILS, null, "/images/icons/Details.gif", "#{WorkflowBean.setupTaskDialog}", "dialog:manageTask", null, params); } requestMap.put(REQUEST_TASKID, task.id); requestMap.put(REQUEST_TASKTYPE, task.definition.metadata.getName().toString()); Utils.encodeRecursive(context, details); out.write(" "); requestMap.remove(REQUEST_TASKID); requestMap.remove(REQUEST_TASKTYPE); // preview action NodeRef pkg = task.path.instance.workflowPackage; Pair<Integer, String> pkgPath = AVMNodeConverter.ToAVMVersionPath(pkg); String workflowStore = AVMUtil.getStoreName(pkgPath.getSecond()); String workflowPreviewUrl = AVMUtil.getPreviewURI(workflowStore); UIActionLink preview = findAction(ACT_PREVIEW, sandbox); if (preview == null) { preview = createAction(context, sandbox, ACT_PREVIEW, null, "/images/icons/preview_website.gif", null, null, "#{" + REQUEST_PREVIEW_REF + "}", null); } requestMap.put(REQUEST_PREVIEW_REF, workflowPreviewUrl); Utils.encodeRecursive(context, preview); requestMap.remove(REQUEST_PREVIEW_REF); out.write(" "); // visual diff action out.write("<a href='#' onclick='diff(\""); out.write(workflowPreviewUrl); out.write("\",\""); out.write(sandboxPreviewUrl); out.write("\"); return false;'>"); out.write("<img border='0' align='absmiddle' title='"); out.write(Application.getMessage(context, ACT_DIFF)); out.write("' alt='"); out.write(Application.getMessage(context, ACT_DIFF)); out.write("' src='"); out.write(context.getExternalContext().getRequestContextPath()); out.write("/images/icons/diff.gif'/></a> "); // promote action UIActionLink promote = findAction(ACT_PROMOTE, sandbox); if (promote == null) { Map<String, String> params = new HashMap<String, String>(1); params.put("taskId", "#{" + REQUEST_TASKID + "}"); promote = createAction(context, sandbox, ACT_PROMOTE, null, "/images/icons/promote_submission.gif", "#{AVMBrowseBean.promotePendingSubmission}", null, null, params); } requestMap.put(REQUEST_TASKID, task.id); Utils.encodeRecursive(context, promote); requestMap.remove(REQUEST_TASKID); out.write(" "); // abort action UIActionLink abort = findAction(ACT_ABORT, sandbox); if (abort == null) { Map<String, String> params = new HashMap<String, String>(1); params.put("workflowInstanceId", "#{" + REQUEST_WORKFLOWID + "}"); abort = createAction(context, sandbox, ACT_ABORT, null, "/images/icons/abort_submission.gif", "#{AVMBrowseBean.cancelPendingSubmission}", null, null, params); } requestMap.put(REQUEST_WORKFLOWID, task.path.instance.id); Utils.encodeRecursive(context, abort); requestMap.remove(REQUEST_WORKFLOWID); out.write(" "); out.write("</nobr></td></tr>"); } out.write("</table>"); } tx.commit(); } catch (Throwable err) { try { if (tx != null) { tx.rollback(); } } catch (Exception tex) { } throw new RuntimeException(err); } }
From source file:org.alfresco.web.ui.wcm.component.UISandboxSnapshots.java
/** * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext) *///w w w . jav a2 s.c om @SuppressWarnings("unchecked") public void encodeBegin(FacesContext context) throws IOException { if (isRendered() == false) { return; } ResponseWriter out = context.getResponseWriter(); ResourceBundle bundle = Application.getBundle(context); DateFormat df = Utils.getDateTimeFormat(context); AVMService avmService = getAVMService(context); SandboxService sbService = getSandboxService(context); UserTransaction tx = null; try { tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true); tx.begin(); String sandbox = getValue(); if (sandbox == null) { throw new IllegalArgumentException("Sandbox must be specified."); } // TODO: apply tag style - removed hardcoded out.write("<table class='snapshotItemsList' cellspacing=2 cellpadding=1 border=0 width=100%>"); // header row out.write("<tr align=left><th>"); out.write(bundle.getString(MSG_LABEL)); out.write("</th><th>"); out.write(bundle.getString(MSG_DESCRIPTION)); out.write("</th><th>"); out.write(bundle.getString(MSG_DATE)); out.write("</th><th>"); out.write(bundle.getString(MSG_USERNAME)); out.write("</th><th>"); out.write(bundle.getString(MSG_VERSION)); out.write("</th><th>"); out.write(bundle.getString(MSG_STATUS)); out.write("</th><th>"); out.write(bundle.getString(MSG_ACTIONS)); out.write("</th></tr>"); // get the list of snapshots we can potentially display List<SandboxVersion> versions; String dateFilter = getDateFilter(); if (dateFilter == null || dateFilter.equals(FILTER_DATE_ALL)) { versions = sbService.listSnapshots(sandbox, false); } else { Date toDate = new Date(); Date fromDate; if (FILTER_DATE_TODAY.equals(dateFilter)) { final Calendar c = Calendar.getInstance(); c.setTime(toDate); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); fromDate = c.getTime(); } else if (FILTER_DATE_WEEK.equals(dateFilter)) { fromDate = new Date(toDate.getTime() - (1000L * 60L * 60L * 24L * 7L)); } else if (FILTER_DATE_MONTH.equals(dateFilter)) { fromDate = new Date(toDate.getTime() - (1000L * 60L * 60L * 24L * 30L)); } else { throw new IllegalArgumentException("Unknown date filter mode: " + dateFilter); } versions = sbService.listSnapshots(sandbox, fromDate, toDate, false); } // determine whether the deploy action should be shown boolean showDeployAction = false; NodeRef webProjectRef = Repository.getServiceRegistry(context).getWebProjectService() .getWebProjectNodeFromStore(WCMUtil.getWebProjectStoreId(sandbox)); List<NodeRef> deployToServers = Repository.getServiceRegistry(context).getDeploymentService() .findLiveDeploymentServers(webProjectRef); if (deployToServers != null && deployToServers.size() > 0) { showDeployAction = true; } // determine the deployment status for the website NodeService nodeService = Repository.getServiceRegistry(context).getNodeService(); determineDeploymentStatus(context, webProjectRef, sandbox, nodeService, avmService); Map requestMap = context.getExternalContext().getRequestMap(); for (SandboxVersion item : versions) { // only display snapshots with a valid label/tag - others are system generated snapshots if (!item.isSystemGenerated()) { int version = item.getVersion(); out.write("<tr><td>"); out.write(Utils.encode(item.getLabel())); out.write("</td><td>"); out.write(item.getDescription() != null ? Utils.encode(item.getDescription()) : ""); out.write("</td><td>"); out.write(df.format(item.getCreatedDate())); out.write("</td><td>"); out.write(Utils.encode(item.getCreator())); out.write("</td><td>"); out.write(Integer.toString(version)); out.write("</td><td>"); if (version == this.deployAttemptVersion && this.deployStatus != null) { out.write(this.deployStatus); } else { out.write(" "); } out.write("</td><td><nobr>"); // create actions for the item // revert action UIActionLink action = findAction(ACT_SNAPSHOT_REVERT, sandbox); if (action == null) { Map<String, String> params = new HashMap<String, String>(2, 1.0f); params.put("sandbox", sandbox); params.put("version", "#{" + REQUEST_SNAPVERSION + "}"); action = createAction(context, sandbox, ACT_SNAPSHOT_REVERT, "/images/icons/revert.gif", "#{DialogManager.setupParameters}", "dialog:revertSnapshot", null, params); } requestMap.put(REQUEST_SNAPVERSION, Integer.toString(item.getVersion())); Utils.encodeRecursive(context, action); // deploy action (if there are deployto servers specified) if (showDeployAction) { out.write(" "); action = findAction(ACT_SNAPSHOT_DEPLOY, sandbox); if (action == null) { Map<String, String> params = new HashMap<String, String>(2, 1.0f); params.put("version", "#{" + REQUEST_SNAPVERSION + "}"); params.put("store", sandbox); action = createAction(context, sandbox, ACT_SNAPSHOT_DEPLOY, "/images/icons/deploy.gif", "#{DialogManager.setupParameters}", "dialog:deployWebsite", null, params); } Utils.encodeRecursive(context, action); } // TODO: restore once preview of a store by version is implemented in vserver // out.write(" "); /* * Utils.encodeRecursive(context, aquireAction( context, sandbox, ACT_SNAPSHOT_PREVIEW, null, null, null)); out.write(" "); */ boolean isLatestVersion = WCMCompareUtils.isLatestVersion(versions, item); // ///////////////////////////////////////////////////////////////////////// if (!isLatestVersion) { out.write(" "); // Compare To Current Snapshot action = findAction(ACT_SNAPSHOT_COMPARE_TO_CURRENT, sandbox); if (action == null) { Map<String, String> params = new HashMap<String, String>(4, 1.0f); params.put("sandbox", sandbox); params.put("store", sandbox); params.put("version", "#{" + REQUEST_SNAPVERSION + "}"); action = createAction(context, sandbox, ACT_SNAPSHOT_COMPARE_TO_CURRENT, "/images/icons/comparetocurrent.png", "#{DialogManager.setupParameters}", "dialog:compareToCurrentSnapshot", null, params); } Utils.encodeRecursive(context, action); } boolean isFirstVersion = WCMCompareUtils.isFirstVersion(versions, item); if (!isFirstVersion) { out.write(" "); // Compare To previous Snapshot action = findAction(ACT_SNAPSHOT_COMPARE_TO_PREVIOUS, sandbox); if (action == null) { Map<String, String> params = new HashMap<String, String>(2, 1.0f); params.put("sandbox", sandbox); params.put("version", "#{" + REQUEST_SNAPVERSION + "}"); action = createAction(context, sandbox, ACT_SNAPSHOT_COMPARE_TO_PREVIOUS, "/images/icons/comparetoprevious.png", "#{DialogManager.setupParameters}", "dialog:compareToPreviousSnapshot", null, params); } Utils.encodeRecursive(context, action); } out.write(" "); // Compare To Any Snapshot action = findAction(ACT_SNAPSHOT_COMPARE_TO_ANY, sandbox); if (action == null) { Map<String, String> params = new HashMap<String, String>(2, 1.0f); params.put("sandbox", sandbox); params.put("version", "#{" + REQUEST_SNAPVERSION + "}"); action = createAction(context, sandbox, ACT_SNAPSHOT_COMPARE_TO_ANY, "/images/icons/comparetoany.png", "#{DialogManager.setupParameters}", "dialog:compareToAnySnapshot", null, params); } Utils.encodeRecursive(context, action); requestMap.remove(REQUEST_SNAPVERSION); out.write("</nobr></td></tr>"); } } // end table out.write("</table>"); tx.commit(); } catch (Throwable err) { try { if (tx != null) { tx.rollback(); } } catch (Exception tex) { } throw new RuntimeException(err); } }
From source file:org.alfresco.web.ui.wcm.component.UIUserSandboxes.java
/** * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext) *//*from w ww. j a v a 2s . c om*/ @SuppressWarnings("unchecked") public void encodeBegin(FacesContext context) throws IOException { if (isRendered() == false) { return; } ResponseWriter out = context.getResponseWriter(); this.rowToUserLookup.clear(); this.userToRowLookup.clear(); this.userNodes.clear(); this.forms = null; ResourceBundle bundle = Application.getBundle(context); SandboxService sbService = getSandboxService(context); WebProjectService wpService = getWebProjectService(context); NodeService nodeService = getNodeService(context); PermissionService permissionService = getPermissionService(context); AVMBrowseBean avmBrowseBean = (AVMBrowseBean) FacesHelper.getManagedBean(context, AVMBrowseBean.BEAN_NAME); boolean showAllSandboxes = avmBrowseBean.getShowAllSandboxes(); UserTransaction tx = null; try { tx = Repository.getUserTransaction(context, true); tx.begin(); NodeRef websiteRef = getValue(); if (websiteRef == null) { throw new IllegalArgumentException("Website NodeRef must be specified."); } String storeRoot = (String) nodeService.getProperty(websiteRef, WCMAppModel.PROP_AVMSTORE); // find out the current user role in the web project User currentUser = Application.getCurrentUser(context); String currentUserName = currentUser.getUserName(); String currentUserRole = wpService.getWebUserRole(websiteRef, currentUserName); // sort the user list alphabetically and insert the current user at the top of the list List<UserRoleWrapper> userRoleWrappers; if (showAllSandboxes) { Map<String, String> userRoles = null; if (currentUserRole.equals(WCMUtil.ROLE_CONTENT_MANAGER) || currentUserRole.equals(WCMUtil.ROLE_CONTENT_PUBLISHER)) { Map<String, String> allUserRoles = wpService.listWebUsers(websiteRef); WebProjectInfo wpInfo = wpService.getWebProject(websiteRef); List<SandboxInfo> sbInfos = sbService.listSandboxes(wpInfo.getStoreId()); userRoles = new HashMap<String, String>(sbInfos.size()); // Note: currently displays author sandboxes only for (SandboxInfo sbInfo : sbInfos) { if (sbInfo.getSandboxType().equals(SandboxConstants.PROP_SANDBOX_AUTHOR_MAIN)) { userRoles.put(sbInfo.getName(), allUserRoles.get(sbInfo.getName())); } } } else { userRoles = new HashMap<String, String>(1); userRoles.put(currentUserName, currentUserRole); } userRoleWrappers = buildSortedUserRoles(nodeService, currentUserName, userRoles); } else { userRoleWrappers = buildCurrentUserRole(wpService, websiteRef, currentUserName); } // determine whether the deploy action should be shown boolean deployServersConfigured = false; List<NodeRef> deployToServers = Repository.getServiceRegistry(context).getDeploymentService() .findTestDeploymentServers(websiteRef, false); if (deployToServers != null && deployToServers.size() > 0) { deployServersConfigured = true; } // output a javascript function we need for multi-select functionality out.write(SCRIPT_MULTISELECT); // walk the list of users who have a sandbox in the website int index = 0; for (UserRoleWrapper wrapper : userRoleWrappers) { String username = wrapper.UserName; String userrole = wrapper.UserRole; // create the lookup value of sandbox index to username this.userToRowLookup.put(index, username); this.rowToUserLookup.put(username, index); // build the name of the main store for this user (user sandbox id) String mainStore = AVMUtil.buildUserMainStoreName(storeRoot, username); // check it exists before we render the view if (sbService.getSandbox(mainStore) != null) { // check the permissions on this store for the current user if (logger.isDebugEnabled()) logger.debug("Checking user role to view store: " + mainStore); if ((showAllSandboxes && (currentUserName.equals(username) || WCMUtil.ROLE_CONTENT_MANAGER.equals(currentUserRole) || WCMUtil.ROLE_CONTENT_PUBLISHER.equals(currentUserRole))) || showAllSandboxes == false) { if (logger.isDebugEnabled()) logger.debug("Building sandbox view for user store: " + mainStore); // determine if the sandbox has an allocated test server for deployment List<NodeRef> testServers = DeploymentUtil.findAllocatedTestServers(mainStore); boolean hasAllocatedTestServer = (!testServers.isEmpty()); // determine if there are any previous deployment attempts List<NodeRef> deployAttempts = DeploymentUtil.findDeploymentAttempts(mainStore); boolean hasPreviousDeployments = (deployAttempts.size() > 0); // for each user sandbox, generate an outer panel table PanelGenerator.generatePanelStart(out, context.getExternalContext().getRequestContextPath(), "innerwhite", "white"); // components for the current username, preview, browse and modified items inner list out.write("<table cellspacing=2 cellpadding=2 border=0 width=100%><tr><td>"); // show the icon for the sandbox as a clickable browse link image // this is currently identical to the sandbox_browse action as below UIActionLink browseAction = aquireAction(context, mainStore, username, ACT_SANDBOX_ICON, WebResources.IMAGE_USERSANDBOX_32, "#{AVMBrowseBean.setupSandboxAction}", "browseSandbox"); browseAction .setTooltip(Application.getMessage(context, ACT_SANDBOX_BROWSE) + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"); browseAction.setShowLink(false); Utils.encodeRecursive(context, browseAction); out.write("</td><td width=100%>"); if (wrapper.IsCurrentUser == false) { out.write("<b>"); out.write(bundle.getString(MSG_USERNAME)); out.write(":</b> "); out.write(Utils.encode(username)); } else { out.write("<b>"); out.write(bundle.getString(MSG_MY_SANDBOX)); out.write("</b>"); } out.write(" ("); out.write(bundle.getString(userrole)); out.write(")</td><td><table cellpadding='4' cellspacing='0'><tr><td><nobr>"); // Direct actions for a sandbox... // Browse Sandbox UIActionLink action = aquireAction(context, mainStore, username, ACT_SANDBOX_BROWSE, "/images/icons/space_small.gif", "#{AVMBrowseBean.setupSandboxAction}", "browseSandbox"); action.setTooltip(Application.getMessage(context, ACT_SANDBOX_BROWSE) + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"); Utils.encodeRecursive(context, action); out.write("</nobr></td><td><nobr>"); // Preview Website String websiteUrl = AVMUtil.getPreviewURI(mainStore, JNDIConstants.DIR_DEFAULT_WWW_APPBASE + '/' + getWebapp()); Map requestMap = context.getExternalContext().getRequestMap(); requestMap.put(REQUEST_PREVIEW_REF, websiteUrl); action = aquireAction(context, mainStore, username, ACT_SANDBOX_PREVIEW, "/images/icons/preview_website.gif", null, null, "#{" + REQUEST_PREVIEW_REF + "}", null); action.setTooltip(Application.getMessage(context, ACT_SANDBOX_PREVIEW) + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"); Utils.encodeRecursive(context, action); requestMap.remove(REQUEST_PREVIEW_REF); out.write("</nobr></td><td><nobr>"); // Submit All Items action = aquireAction(context, mainStore, username, ACT_SANDBOX_SUBMITALL, "/images/icons/submit_all.gif", "#{AVMBrowseBean.setupAllItemsAction}", "dialog:submitSandboxItems"); action.setTooltip(Application.getMessage(context, ACT_SANDBOX_SUBMITALL) + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"); Utils.encodeRecursive(context, action); out.write("</nobr></td><td><nobr>"); // Revert All Items action = aquireAction(context, mainStore, username, ACT_SANDBOX_REVERTALL, "/images/icons/revert_all.gif", "#{AVMBrowseBean.setupAllItemsAction}", "dialog:revertAllItems"); action.setTooltip(Application.getMessage(context, ACT_SANDBOX_REVERTALL) + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"); Utils.encodeRecursive(context, action); out.write("</nobr></td><td><nobr>"); // More Actions menu UIMenu menu = findMenu(mainStore); if (menu == null) { // create the menu, then the actions menu = createMenu(context, mainStore); menu.setTooltip(Application.getMessage(context, "more_actions") + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"); // add the menu to this component this.getChildren().add(menu); } // clear current menu actions then add relevant ones menu.getChildren().clear(); // Deploy action if (deployServersConfigured) { Map<String, String> dialogParams = new HashMap<String, String>(6); dialogParams.put("store", mainStore); dialogParams.put("username", username); requestMap.put(REQUEST_UPDATE_TEST_SERVER, Boolean.toString(hasAllocatedTestServer)); dialogParams.put("updateTestServer", "#{" + REQUEST_UPDATE_TEST_SERVER + "}"); UIActionLink deploy = createAction(context, mainStore, username, ACT_SANDBOX_DEPLOY, "/images/icons/deploy.gif", "#{DialogManager.setupParameters}", "dialog:deployWebsite", null, dialogParams, false); deploy.setTooltip(Application.getMessage(context, ACT_SANDBOX_DEPLOY) + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"); menu.getChildren().add(deploy); } // View deployment report action if (hasPreviousDeployments) { UIActionLink reports = createAction(context, mainStore, username, ACT_SANDBOX_DEPLOY_REPORT, "/images/icons/deployment_report.gif", "#{DialogManager.setupParameters}", "dialog:viewDeploymentReport", null, null, false); reports.setTooltip(Application.getMessage(context, ACT_SANDBOX_DEPLOY_REPORT) + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"); menu.getChildren().add(reports); } // Release Test Server action if (hasAllocatedTestServer) { UIActionLink releaseServer = createAction(context, mainStore, username, ACT_SANDBOX_RELEASE_SERVER, "/images/icons/release_server.gif", "#{DialogManager.setupParameters}", "dialog:releaseTestServer", null, null, false); releaseServer.setTooltip(Application.getMessage(context, ACT_SANDBOX_RELEASE_SERVER) + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"); menu.getChildren().add(releaseServer); } // Refresh Sandbox action UIActionLink refresh = createAction(context, mainStore, username, ACT_SANDBOX_REFRESH, "/images/icons/reset.gif", "#{AVMBrowseBean.refreshSandbox}", null, null, null, false); refresh.setTooltip(Application.getMessage(context, ACT_SANDBOX_REFRESH) + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"); menu.getChildren().add(refresh); // Delete Sandbox action if (WCMUtil.ROLE_CONTENT_MANAGER.equals(currentUserRole)) { UIActionLink delete = createAction(context, mainStore, username, ACT_REMOVE_SANDBOX, "/images/icons/delete_sandbox.gif", "#{AVMBrowseBean.setupSandboxAction}", "dialog:deleteSandbox", null, null, false); delete.setTooltip(Application.getMessage(context, ACT_REMOVE_SANDBOX) + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"); menu.getChildren().add(delete); } // render the menu Utils.encodeRecursive(context, menu); out.write("</nobr></td></tr></table></td></tr>"); // modified items panel out.write("<tr><td></td><td colspan=2>"); String panelImage = WebResources.IMAGE_COLLAPSED; if (this.expandedPanels.contains(username + PANEL_MODIFIED)) { panelImage = WebResources.IMAGE_EXPANDED; } String title = Application.getMessage(context, MSG_MODIFIED_ITEMS) + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"; String submitScript = Utils.generateFormSubmit(context, this, getClientId(context) + PANEL_MODIFIED, username + PANEL_MODIFIED); out.write("<a href=\"#\" tabIndex=\"0\" onclick=\"" + submitScript + "\">"); out.write(Utils.buildImageTag(context, panelImage, 11, 11, title)); out.write("</a>"); out.write(" <b title=\"" + title + "\">"); out.write(bundle.getString(MSG_MODIFIED_ITEMS)); out.write("</b>"); if (this.expandedPanels.contains(username + PANEL_MODIFIED)) { out.write("<div style='padding:2px'></div>"); // list the modified docs for this sandbox user renderUserFiles(context, out, username, storeRoot, index); } out.write("</td></tr>"); // content forms panel if (permissionService.hasPermission( AVMNodeConverter.ToNodeRef(-1, AVMUtil.buildSandboxRootPath(mainStore)), PermissionService.ADD_CHILDREN) == AccessStatus.ALLOWED) { out.write("<tr style='padding-top:4px'><td></td><td colspan=2>"); panelImage = WebResources.IMAGE_COLLAPSED; if (this.expandedPanels.contains(username + PANEL_FORMS)) { panelImage = WebResources.IMAGE_EXPANDED; } title = Application.getMessage(context, MSG_CONTENT_FORMS) + " (" + username + " " + Application.getMessage(context, "sandbox_title_extension") + ")"; submitScript = Utils.generateFormSubmit(context, this, getClientId(context) + PANEL_FORMS, username + PANEL_FORMS); out.write("<a href=\"#\" tabIndex=\"0\" onclick=\"" + submitScript + "\">"); out.write(Utils.buildImageTag(context, panelImage, 11, 11, title)); out.write("</a>"); out.write(" <b title=\"" + title + "\">"); out.write(bundle.getString(MSG_CONTENT_FORMS)); out.write("</b>"); if (this.expandedPanels.contains(username + PANEL_FORMS)) { out.write("<div style='padding:2px'></div>"); // list the content forms for this sandbox user renderContentForms(context, out, websiteRef, username, storeRoot); } out.write("</td></tr>"); } out.write("</table>"); // end the outer panel for this sandbox PanelGenerator.generatePanelEnd(out, context.getExternalContext().getRequestContextPath(), "innerwhite"); // spacer row if (index++ < userRoleWrappers.size() - 1) { out.write("<div style='padding:4px'></div>"); } } } } tx.commit(); } catch (Throwable err) { try { if (tx != null) { tx.rollback(); } } catch (Exception tex) { } throw new RuntimeException(err); } }
From source file:org.apache.axis2.transport.jms.JMSMessageSender.java
/** * Perform actual send of JMS message to the Destination selected * * @param message the JMS message//w ww . ja v a 2 s . c o m * @param msgCtx the Axis2 MessageContext */ public void send(Message message, MessageContext msgCtx) { Boolean jtaCommit = getBooleanProperty(msgCtx, BaseConstants.JTA_COMMIT_AFTER_SEND); Boolean rollbackOnly = getBooleanProperty(msgCtx, BaseConstants.SET_ROLLBACK_ONLY); Boolean persistent = getBooleanProperty(msgCtx, JMSConstants.JMS_DELIVERY_MODE); Integer priority = getIntegerProperty(msgCtx, JMSConstants.JMS_PRIORITY); Integer timeToLive = getIntegerProperty(msgCtx, JMSConstants.JMS_TIME_TO_LIVE); // Do not commit, if message is marked for rollback if (rollbackOnly != null && rollbackOnly) { jtaCommit = Boolean.FALSE; } if (persistent != null) { try { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } catch (JMSException e) { handleException("Error setting JMS Producer for PERSISTENT delivery", e); } } if (priority != null) { try { producer.setPriority(priority); } catch (JMSException e) { handleException("Error setting JMS Producer priority to : " + priority, e); } } if (timeToLive != null) { try { producer.setTimeToLive(timeToLive); } catch (JMSException e) { handleException("Error setting JMS Producer TTL to : " + timeToLive, e); } } boolean sendingSuccessful = false; // perform actual message sending try { if (jmsSpec11 || isQueue == null) { producer.send(message); } else { if (isQueue) { ((QueueSender) producer).send(message); } else { ((TopicPublisher) producer).publish(message); } } // set the actual MessageID to the message context for use by any others down the line String msgId = null; try { msgId = message.getJMSMessageID(); if (msgId != null) { msgCtx.setProperty(JMSConstants.JMS_MESSAGE_ID, msgId); } } catch (JMSException ignore) { } sendingSuccessful = true; if (log.isDebugEnabled()) { log.debug("Sent Message Context ID : " + msgCtx.getMessageID() + " with JMS Message ID : " + msgId + " to destination : " + producer.getDestination()); } } catch (JMSException e) { log.error("Error sending message with MessageContext ID : " + msgCtx.getMessageID() + " to destination : " + destination, e); } finally { if (jtaCommit != null) { UserTransaction ut = (UserTransaction) msgCtx.getProperty(BaseConstants.USER_TRANSACTION); if (ut != null) { try { if (sendingSuccessful && jtaCommit) { ut.commit(); } else { ut.rollback(); } msgCtx.removeProperty(BaseConstants.USER_TRANSACTION); if (log.isDebugEnabled()) { log.debug((sendingSuccessful ? "Committed" : "Rolled back") + " JTA Transaction"); } } catch (Exception e) { handleException("Error committing/rolling back JTA transaction after " + "sending of message with MessageContext ID : " + msgCtx.getMessageID() + " to destination : " + destination, e); } } } else { try { if (session.getTransacted()) { if (sendingSuccessful && (rollbackOnly == null || !rollbackOnly)) { session.commit(); } else { session.rollback(); } } if (log.isDebugEnabled()) { log.debug((sendingSuccessful ? "Committed" : "Rolled back") + " local (JMS Session) Transaction"); } } catch (JMSException e) { handleException("Error committing/rolling back local (i.e. session) " + "transaction after sending of message with MessageContext ID : " + msgCtx.getMessageID() + " to destination : " + destination, e); } } } }
From source file:org.apache.ofbiz.entity.transaction.TransactionUtil.java
/** Rolls back transaction in the current thread IF transactions are available */ public static void rollback(Throwable causeThrowable) throws GenericTransactionException { UserTransaction ut = TransactionFactoryLoader.getInstance().getUserTransaction(); if (ut != null) { try {/*from ww w.j ava 2s . c o m*/ int status = ut.getStatus(); Debug.logVerbose("Current status : " + getTransactionStateString(status), module); if (status != STATUS_NO_TRANSACTION) { //if (Debug.infoOn()) Thread.dumpStack(); if (causeThrowable == null && Debug.infoOn()) { Exception newE = new Exception("Stack Trace"); Debug.logError(newE, "[TransactionUtil.rollback]", module); } // clear out the stamps to keep it clean clearTransactionStamps(); // clear out the stack too clearTransactionBeginStack(); clearSetRollbackOnlyCause(); ut.rollback(); Debug.logInfo("Transaction rolled back", module); } else { Debug.logWarning("Transaction not rolled back, status is STATUS_NO_TRANSACTION", module); } } catch (IllegalStateException e) { Throwable t = e.getCause() == null ? e : e.getCause(); throw new GenericTransactionException( "Could not rollback transaction, IllegalStateException exception: " + t.toString(), t); } catch (SystemException e) { Throwable t = e.getCause() == null ? e : e.getCause(); throw new GenericTransactionException( "System error, could not rollback transaction: " + t.toString(), t); } } else { Debug.logInfo("No UserTransaction, transaction not rolled back", module); } }