Example usage for javax.transaction UserTransaction begin

List of usage examples for javax.transaction UserTransaction begin

Introduction

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

Prototype

void begin() throws NotSupportedException, SystemException;

Source Link

Document

Create a new transaction and associate it with the current thread.

Usage

From source file:org.alfresco.web.ui.wcm.component.UIDeploymentReports.java

/**
 * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext)
 *///from   w  w w .  j a v  a 2 s. 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;//w ww  .j a v a 2  s .c om
    }

    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' />&nbsp;");
                        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)
 *//* w  w w .j a v a2 s. com*/
@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("&nbsp;&nbsp;");
                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("&nbsp;&nbsp;");

                // 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>&nbsp;&nbsp;");

                // 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("&nbsp;&nbsp;");

                // 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("&nbsp;&nbsp;");

                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)
 *///from   w  w w .jav  a  2 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("&nbsp;");
                }
                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("&nbsp;&nbsp;");
                    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("&nbsp;&nbsp;");
                /*
                 * Utils.encodeRecursive(context, aquireAction( context, sandbox, ACT_SNAPSHOT_PREVIEW, null, null, null)); out.write("&nbsp;");
                 */

                boolean isLatestVersion = WCMCompareUtils.isLatestVersion(versions, item);
                // /////////////////////////////////////////////////////////////////////////
                if (!isLatestVersion) {

                    out.write("&nbsp;&nbsp;");

                    // 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("&nbsp;&nbsp;");

                    // 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("&nbsp;&nbsp;");
                // 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  www.  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();

    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>&nbsp;");
                        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("&nbsp;<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("&nbsp;<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.ofbiz.entity.transaction.TransactionUtil.java

protected static void internalBegin(UserTransaction ut, int timeout)
        throws SystemException, NotSupportedException {
    // set the timeout for THIS transaction
    if (timeout > 0) {
        ut.setTransactionTimeout(timeout);
        if (Debug.verboseOn()) {
            Debug.logVerbose("Set transaction timeout to : " + timeout + " seconds", module);
        }/*from   w  w w .  ja v a  2 s  .c  o  m*/
    }

    // begin the transaction
    ut.begin();
    if (Debug.verboseOn()) {
        Debug.logVerbose("Transaction begun", module);
    }

    // reset the timeout to the default
    if (timeout > 0) {
        ut.setTransactionTimeout(0);
    }
}

From source file:org.craftercms.cstudio.alfresco.dm.util.impl.DmImportServiceImpl.java

/**
 * submit imported items to go live/*  w  w w .j a  v  a  2s.  co m*/
 * 
 * @param site
 * @param publishChannelGroup
 * @param importedFullPaths
 */
protected void submitToGoLive(String site, String publishChannelGroup, List<String> importedFullPaths) {
    DmTransactionService transaction = getService(DmTransactionService.class);
    UserTransaction tnx = transaction.getNonPropagatingUserTransaction();
    try {
        tnx.begin();
        MultiChannelPublishingContext mcpContext = new MultiChannelPublishingContext(publishChannelGroup, "",
                "Import Service");
        DmPublishService publishService = getService(DmPublishService.class);
        publishService.publish(site, importedFullPaths, null, mcpContext);
        LOGGER.info("All files have been submitted to be publish");
        tnx.commit();
    } catch (Exception ex) {
        LOGGER.error("Unable to publish files due a error ", ex);
        try {
            tnx.rollback();
        } catch (IllegalStateException e) {
            LOGGER.error("Unable to rollback Transaction");
        } catch (SecurityException e) {
            LOGGER.error("Unable to rollback Transaction");
        } catch (SystemException e) {
            LOGGER.error("Unable to rollback Transaction");
        }
    }
}

From source file:org.droolsjbpm.services.test.ci.SessionMGMTandCIBaseTest.java

protected UserTransaction setupEnvironment(Environment environment) {
    UserTransaction ut = null;
    try {/*from w w w.j  a  va 2  s.  co m*/
        this.em.toString();
        environment.set(EnvironmentName.ENTITY_MANAGER_FACTORY, this.em.getEntityManagerFactory());
    } catch (ContextNotActiveException e) {
        try {
            ut = InitialContext.doLookup("java:comp/UserTransaction");
        } catch (Exception ex) {
            try {
                ut = InitialContext
                        .doLookup(System.getProperty("jbpm.ut.jndi.lookup", "java:jboss/UserTransaction"));

            } catch (Exception e1) {
                throw new RuntimeException("Cannot find UserTransaction", e1);
            }
        }
        try {
            ut.begin();
            environment.set(EnvironmentName.TRANSACTION, ut);
        } catch (Exception ex) {

        }
        environment.set(EnvironmentName.ENTITY_MANAGER_FACTORY, this.emf);
    }

    return ut;
}

From source file:org.etk.entity.engine.plugins.transaction.TransactionUtil.java

protected static synchronized void internalBegin(UserTransaction ut, int timeout)
        throws SystemException, NotSupportedException {
    // set the timeout for THIS transaction
    if (timeout > 0) {
        ut.setTransactionTimeout(timeout);
        if (logger.isDebugEnabled()) {
            logger.debug("[TransactionUtil.begin] set transaction timeout to : " + timeout + " seconds");
        }//from w w w. jav  a2 s  .c  o m
    }

    // begin the transaction
    ut.begin();
    if (logger.isDebugEnabled()) {
        logger.debug("[TransactionUtil.begin] transaction begun");
    }

    // reset the timeout to the default
    if (timeout > 0) {
        ut.setTransactionTimeout(0);
    }
}

From source file:org.firstopen.singularity.util.TransactionManager.java

/**
 * /*  w w w . ja  v a2s .c  o  m*/
 * 
 */
public void begin() {
    log.debug("begin");
    try {
        UserTransaction userTransaction = TransactionUtil.getUserTransaction();
        if (userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION) {
            userTransaction.begin();
            log.debug("JTA transaction started");
        }

    } catch (Exception e) {
        log.error("cannot begin transaction");

        throw new InfrastructureException(e);
    }

}