Example usage for javax.transaction UserTransaction rollback

List of usage examples for javax.transaction UserTransaction rollback

Introduction

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

Prototype

void rollback() throws IllegalStateException, SecurityException, SystemException;

Source Link

Document

Roll back the transaction associated with the current thread.

Usage

From source file:org.alfresco.web.app.servlet.BaseTemplateContentServlet.java

/**
 * Processes the template request using the current context i.e. no
 * authentication checks are made, it is presumed they have already
 * been done.//from w  w  w  .  ja  v  a2 s . co  m
 * 
 * @param req The HTTP request
 * @param res The HTTP response
 * @param redirectToLogin Flag to determine whether to redirect to the login
 *                        page if the user does not have the correct permissions
 */
protected void processTemplateRequest(HttpServletRequest req, HttpServletResponse res, boolean redirectToLogin)
        throws ServletException, IOException {
    Log logger = getLogger();
    String uri = req.getRequestURI();

    if (logger.isDebugEnabled()) {
        String queryString = req.getQueryString();
        logger.debug("Processing URL: " + uri
                + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
    }

    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();

    t.nextToken(); // skip servlet name

    NodeRef nodeRef = null;
    NodeRef templateRef = null;

    try {
        String contentPath = req.getParameter(ARG_CONTEXT_PATH);
        if (contentPath != null && contentPath.length() != 0) {
            // process the name based path to resolve the NodeRef
            PathRefInfo pathInfo = resolveNamePath(getServletContext(), contentPath);

            nodeRef = pathInfo.NodeRef;
        } else if (tokenCount > 3) {
            // get NodeRef to the content from the URL elements
            StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
            nodeRef = new NodeRef(storeRef, t.nextToken());
        }

        // get NodeRef to the template if supplied
        String templatePath = req.getParameter(ARG_TEMPLATE_PATH);
        if (templatePath != null && templatePath.length() != 0) {
            // process the name based path to resolve the NodeRef
            PathRefInfo pathInfo = resolveNamePath(getServletContext(), templatePath);

            templateRef = pathInfo.NodeRef;
        } else if (tokenCount >= 7) {
            StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
            templateRef = new NodeRef(storeRef, t.nextToken());
        }
    } catch (AccessDeniedException err) {
        if (redirectToLogin) {
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to login page...");

            redirectToLoginPage(req, res, getServletContext());
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Returning 403 Forbidden error...");

            res.sendError(HttpServletResponse.SC_FORBIDDEN);
        }

        return;
    }

    // if no context is specified, use the template itself
    // TODO: should this default to something else?
    if (nodeRef == null && templateRef != null) {
        nodeRef = templateRef;
    }

    if (nodeRef == null) {
        throw new TemplateException("Not enough elements supplied in URL or no 'path' argument specified.");
    }

    // get the services we need to retrieve the content
    ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
    NodeService nodeService = serviceRegistry.getNodeService();
    TemplateService templateService = serviceRegistry.getTemplateService();
    PermissionService permissionService = serviceRegistry.getPermissionService();

    // check that the user has at least READ access on any nodes - else redirect to the login page
    if (permissionService.hasPermission(nodeRef, PermissionService.READ) == AccessStatus.DENIED
            || (templateRef != null && permissionService.hasPermission(templateRef,
                    PermissionService.READ) == AccessStatus.DENIED)) {
        if (redirectToLogin) {
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to login page...");

            redirectToLoginPage(req, res, getServletContext());
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Returning 403 Forbidden error...");

            res.sendError(HttpServletResponse.SC_FORBIDDEN);
        }

        return;
    }

    String mimetype = MIMETYPE_HTML;
    if (req.getParameter(ARG_MIMETYPE) != null) {
        mimetype = req.getParameter(ARG_MIMETYPE);
    }
    res.setContentType(mimetype);

    try {
        UserTransaction txn = null;
        try {
            txn = serviceRegistry.getTransactionService().getUserTransaction(true);
            txn.begin();

            // if template not supplied, then use the default against the node
            if (templateRef == null) {
                if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_TEMPLATABLE)) {
                    templateRef = (NodeRef) nodeService.getProperty(nodeRef, ContentModel.PROP_TEMPLATE);
                }
                if (templateRef == null) {
                    throw new TemplateException(
                            "Template reference not set against node or not supplied in URL.");
                }
            }

            // create the model - put the supplied noderef in as space/document as appropriate
            Map<String, Object> model = getModel(serviceRegistry, req, templateRef, nodeRef);

            // process the template against the node content directly to the response output stream
            // assuming the repo is capable of streaming in chunks, this should allow large files
            // to be streamed directly to the browser response stream.
            try {
                templateService.processTemplate(templateRef.toString(), model, res.getWriter());

                // commit the transaction
                txn.commit();
            } catch (SocketException e) {
                if (e.getMessage().contains("ClientAbortException")) {
                    // the client cut the connection - our mission was accomplished apart from a little error message
                    logger.error("Client aborted stream read:\n   node: " + nodeRef + "\n   template: "
                            + templateRef);
                    try {
                        if (txn != null) {
                            txn.rollback();
                        }
                    } catch (Exception tex) {
                    }
                } else {
                    throw e;
                }
            } finally {
                res.getWriter().close();
            }
        } catch (Throwable txnErr) {
            try {
                if (txn != null) {
                    txn.rollback();
                }
            } catch (Exception tex) {
            }
            throw txnErr;
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Error during template servlet processing: " + err.getMessage(),
                err);
    }
}

From source file:org.alfresco.web.app.servlet.CommandServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from www  .j ava2 s.  c om
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String uri = req.getRequestURI();

    if (logger.isDebugEnabled())
        logger.debug(
                "Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""));

    AuthenticationStatus status = servletAuthenticate(req, res);
    if (status == AuthenticationStatus.Failure) {
        return;
    }

    setNoCacheHeaders(res);

    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();
    if (tokenCount < 3) {
        throw new IllegalArgumentException("Command Servlet URL did not contain all required args: " + uri);
    }

    t.nextToken(); // skip servlet name

    // get the command processor to execute the command e.g. "workflow"
    String procName = t.nextToken();

    // get the command to perform
    String command = t.nextToken();

    // get any remaining uri elements to pass to the processor
    String[] urlElements = new String[tokenCount - 3];
    for (int i = 0; i < tokenCount - 3; i++) {
        urlElements[i] = t.nextToken();
    }

    // retrieve the URL arguments to pass to the processor
    Map<String, String> args = new HashMap<String, String>(8, 1.0f);
    Enumeration names = req.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        args.put(name, req.getParameter(name));
    }

    try {
        // get configured command processor by name from Config Service
        CommandProcessor processor = createCommandProcessor(procName);

        // validate that the processor has everything it needs to run the command
        if (processor.validateArguments(getServletContext(), command, args, urlElements) == false) {
            redirectToLoginPage(req, res, getServletContext());
            return;
        }

        ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
        UserTransaction txn = null;
        try {
            txn = serviceRegistry.getTransactionService().getUserTransaction();
            txn.begin();

            // inform the processor to execute the specified command
            if (processor instanceof ExtCommandProcessor) {
                ((ExtCommandProcessor) processor).process(serviceRegistry, req, res, command);
            } else {
                processor.process(serviceRegistry, req, command);
            }

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

        String returnPage = req.getParameter(ARG_RETURNPAGE);
        if (returnPage != null && returnPage.length() != 0) {
            validateReturnPage(returnPage, req);
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to specified return page: " + returnPage);

            res.sendRedirect(returnPage);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("No return page specified, displaying status output.");

            if (res.getContentType() == null && !res.isCommitted()) {
                res.setContentType("text/html");

                // request that the processor output a useful status message
                PrintWriter out = res.getWriter();
                processor.outputStatus(out);
                out.close();
            }
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Error during command servlet processing: " + err.getMessage(), err);
    }
}

From source file:org.alfresco.web.bean.ajax.CategoryBrowserPluginBean.java

public List<TreeNode> getCategoryRootNodes() {
    if (this.categoryRootNodes == null) {
        this.categoryRootNodes = new ArrayList<TreeNode>();
        this.categoryNodes = new HashMap<String, TreeNode>();

        UserTransaction tx = null;
        try {//www  .  j  ava 2s .c  o m
            tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true);
            tx.begin();

            Collection<ChildAssociationRef> childRefs = this.getCategoryService()
                    .getRootCategories(Repository.getStoreRef(), ContentModel.ASPECT_GEN_CLASSIFIABLE);

            for (ChildAssociationRef ref : childRefs) {
                NodeRef child = ref.getChildRef();
                TreeNode node = createTreeNode(child);
                this.categoryRootNodes.add(node);
                this.categoryNodes.put(node.getNodeRef(), node);
            }

            tx.commit();
        } catch (Throwable err) {
            Utils.addErrorMessage("NavigatorPluginBean exception in getCompanyHomeRootNodes()", err);
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }
        }
    }

    return this.categoryRootNodes;
}

From source file:org.alfresco.web.bean.ajax.CategoryBrowserPluginBean.java

/**
 * Retrieves the child folders for the noderef given in the 'noderef' parameter and caches the nodes against the area
 * in the 'area' parameter./*from w  ww . j  av a 2 s .c  o m*/
 */
public void retrieveChildren() throws IOException {
    FacesContext context = FacesContext.getCurrentInstance();
    ResponseWriter out = context.getResponseWriter();

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

        Map params = context.getExternalContext().getRequestParameterMap();
        String nodeRefStr = (String) params.get("nodeRef");

        // work out which list to cache the nodes in
        Map<String, TreeNode> currentNodes = getNodesMap();

        if (nodeRefStr != null && currentNodes != null) {
            // get the given node's details
            NodeRef parentNodeRef = new NodeRef(nodeRefStr);
            TreeNode parentNode = currentNodes.get(parentNodeRef.toString());
            parentNode.setExpanded(true);

            if (logger.isDebugEnabled())
                logger.debug("retrieving children for noderef: " + parentNodeRef);

            // remove any existing children as the latest ones will be added
            // below
            parentNode.removeChildren();

            // get all the child folder objects for the parent
            List<ChildAssociationRef> childRefs = this.getNodeService().getChildAssocs(parentNodeRef,
                    ContentModel.ASSOC_SUBCATEGORIES, RegexQNamePattern.MATCH_ALL);
            List<TreeNode> sortedNodes = new ArrayList<TreeNode>();
            for (ChildAssociationRef ref : childRefs) {
                NodeRef nodeRef = ref.getChildRef();
                logger.debug("retrieving child : " + nodeRef);
                // build the XML representation of the child node
                TreeNode childNode = createTreeNode(nodeRef);
                parentNode.addChild(childNode);
                currentNodes.put(childNode.getNodeRef(), childNode);
                sortedNodes.add(childNode);
            }

            // order the tree nodes by the tree label
            if (sortedNodes.size() > 1) {
                QuickSort sorter = new QuickSort(sortedNodes, "name", true,
                        IDataContainer.SORT_CASEINSENSITIVE);
                sorter.sort();
            }

            // generate the XML representation
            StringBuilder xml = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><nodes>");
            for (TreeNode childNode : sortedNodes) {
                xml.append(childNode.toXML());
            }
            xml.append("</nodes>");

            // send the generated XML back to the tree
            out.write(xml.toString());

            if (logger.isDebugEnabled())
                logger.debug("returning XML: " + xml.toString());
        }

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

From source file:org.alfresco.web.bean.ajax.NavigatorPluginBean.java

/**
 * Retrieves the child folders for the noderef given in the 
 * 'noderef' parameter and caches the nodes against the area in
 * the 'area' parameter.//from  ww  w  .  j a v a2 s  . c  o m
 */
public void retrieveChildren() throws IOException {
    FacesContext context = FacesContext.getCurrentInstance();
    ResponseWriter out = context.getResponseWriter();

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

        Map params = context.getExternalContext().getRequestParameterMap();
        String nodeRefStr = (String) params.get("nodeRef");
        String area = (String) params.get("area");

        if (logger.isDebugEnabled())
            logger.debug("retrieveChildren: area = " + area + ", nodeRef = " + nodeRefStr);

        // work out which list to cache the nodes in
        Map<String, TreeNode> currentNodes = getNodesMapForArea(area);

        if (nodeRefStr != null && currentNodes != null) {
            // get the given node's details
            NodeRef parentNodeRef = new NodeRef(nodeRefStr);
            TreeNode parentNode = currentNodes.get(parentNodeRef.toString());
            parentNode.setExpanded(true);

            if (logger.isDebugEnabled())
                logger.debug("retrieving children for noderef: " + parentNodeRef);

            // remove any existing children as the latest ones will be added below
            parentNode.removeChildren();

            // get all the child folder objects for the parent
            List<ChildAssociationRef> childRefs = this.getNodeService().getChildAssocs(parentNodeRef,
                    ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
            List<TreeNode> sortedNodes = new ArrayList<TreeNode>();
            for (ChildAssociationRef ref : childRefs) {
                NodeRef nodeRef = ref.getChildRef();

                if (isAddableChild(nodeRef)) {
                    // build the XML representation of the child node
                    TreeNode childNode = createTreeNode(nodeRef);
                    parentNode.addChild(childNode);
                    currentNodes.put(childNode.getNodeRef(), childNode);
                    sortedNodes.add(childNode);
                }
            }

            // order the tree nodes by the tree label
            if (sortedNodes.size() > 1) {
                QuickSort sorter = new QuickSort(sortedNodes, "name", true,
                        IDataContainer.SORT_CASEINSENSITIVE);
                sorter.sort();
            }

            // generate the XML representation
            StringBuilder xml = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><nodes>");
            for (TreeNode childNode : sortedNodes) {
                xml.append(childNode.toXML());
            }
            xml.append("</nodes>");

            // send the generated XML back to the tree
            out.write(xml.toString());

            if (logger.isDebugEnabled())
                logger.debug("returning XML: " + xml.toString());
        }

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

From source file:org.alfresco.web.bean.ajax.NavigatorPluginBean.java

/**
 * Returns the root nodes for the company home panel.
 * <p>//  w  w  w  . j a  v  a 2 s  .c o m
 * As the user expands and collapses nodes in the client this
 * cache will be updated with the appropriate nodes and states.
 * </p>
 * 
 * @return List of root nodes for the company home panel
 */
public List<TreeNode> getCompanyHomeRootNodes() {
    if (this.companyHomeRootNodes == null) {
        this.companyHomeRootNodes = new ArrayList<TreeNode>();
        this.companyHomeNodes = new HashMap<String, TreeNode>();

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

            // query for the child nodes of company home
            NodeRef root = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId(fc));
            List<ChildAssociationRef> childRefs = this.getNodeService().getChildAssocs(root,
                    ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);

            for (ChildAssociationRef ref : childRefs) {
                NodeRef child = ref.getChildRef();

                if (isAddableChild(child)) {
                    TreeNode node = createTreeNode(child);
                    this.companyHomeRootNodes.add(node);
                    this.companyHomeNodes.put(node.getNodeRef(), node);
                }
            }

            tx.commit();
        } catch (Throwable err) {
            Utils.addErrorMessage("NavigatorPluginBean exception in getCompanyHomeRootNodes()", err);
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }
        }
    }

    return this.companyHomeRootNodes;
}

From source file:org.alfresco.web.bean.ajax.NavigatorPluginBean.java

/**
 * Returns the root nodes for the my home panel.
 * <p>/*from  www  .j  av a  2 s .com*/
 * As the user expands and collapses nodes in the client this
 * cache will be updated with the appropriate nodes and states.
 * </p>
 * 
 * @return List of root nodes for the my home panel
 */
public List<TreeNode> getMyHomeRootNodes() {
    if (this.myHomeRootNodes == null) {
        this.myHomeRootNodes = new ArrayList<TreeNode>();
        this.myHomeNodes = new HashMap<String, TreeNode>();

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

            // query for the child nodes of the user's home
            NodeRef root = new NodeRef(Repository.getStoreRef(),
                    Application.getCurrentUser(FacesContext.getCurrentInstance()).getHomeSpaceId());
            List<ChildAssociationRef> childRefs = this.getNodeService().getChildAssocs(root,
                    ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);

            for (ChildAssociationRef ref : childRefs) {
                NodeRef child = ref.getChildRef();

                if (isAddableChild(child)) {
                    TreeNode node = createTreeNode(child);
                    this.myHomeRootNodes.add(node);
                    this.myHomeNodes.put(node.getNodeRef(), node);
                }
            }

            tx.commit();
        } catch (Throwable err) {
            Utils.addErrorMessage("NavigatorPluginBean exception in getMyHomeRootNodes()", err);
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }
        }
    }

    return this.myHomeRootNodes;
}

From source file:org.alfresco.web.bean.ajax.NavigatorPluginBean.java

/**
 * Returns the root nodes for the guest home panel.
 * <p>/*  w w w  .  j  a  v  a  2s .c om*/
 * As the user expands and collapses nodes in the client this
 * cache will be updated with the appropriate nodes and states.
 * </p>
 * 
 * @return List of root nodes for the guest home panel
 */
public List<TreeNode> getGuestHomeRootNodes() {
    if (this.guestHomeRootNodes == null) {
        this.guestHomeRootNodes = new ArrayList<TreeNode>();
        this.guestHomeNodes = new HashMap<String, TreeNode>();

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

            // query for the child nodes of the guest home space
            NavigationBean navBean = getNavigationBean();
            if (navBean != null) {
                NodeRef root = navBean.getGuestHomeNode().getNodeRef();
                List<ChildAssociationRef> childRefs = this.getNodeService().getChildAssocs(root,
                        ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);

                for (ChildAssociationRef ref : childRefs) {
                    NodeRef child = ref.getChildRef();

                    if (isAddableChild(child)) {
                        TreeNode node = createTreeNode(child);
                        this.guestHomeRootNodes.add(node);
                        this.guestHomeNodes.put(node.getNodeRef(), node);
                    }
                }
            }

            tx.commit();
        } catch (Throwable err) {
            Utils.addErrorMessage("NavigatorPluginBean exception in getGuestHomeRootNodes()", err);
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }
        }
    }

    return this.guestHomeRootNodes;
}

From source file:org.alfresco.web.bean.ajax.PickerBean.java

/**
 * Return the JSON objects representing a list of categories.
 * /*from w  w  w  .  j a va  2s.c  o  m*/
 * IN: "parent" - null for root categories, else the parent noderef of the categories to retrieve.
 * 
 * The pseudo root node 'Categories' is not selectable.
 */
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void getCategoryNodes() throws Exception {
    FacesContext fc = FacesContext.getCurrentInstance();

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

        Collection<ChildAssociationRef> childRefs;
        NodeRef parentRef = null;
        Map params = fc.getExternalContext().getRequestParameterMap();
        String strParentRef = Utils.encode((String) params.get(PARAM_PARENT));
        if (strParentRef == null || strParentRef.length() == 0) {
            childRefs = this.getCategoryService().getRootCategories(Repository.getStoreRef(),
                    ContentModel.ASPECT_GEN_CLASSIFIABLE);
        } else {
            parentRef = new NodeRef(strParentRef);
            childRefs = this.getCategoryService().getChildren(parentRef, CategoryService.Mode.SUB_CATEGORIES,
                    CategoryService.Depth.IMMEDIATE);
        }

        JSONWriter out = new JSONWriter(fc.getResponseWriter());
        out.startObject();
        out.startValue(ID_PARENT);
        out.startObject();
        if (parentRef == null) {
            out.writeNullValue(ID_ID);
            out.writeValue(ID_NAME, Application.getMessage(fc, MSG_CATEGORIES));
            out.writeValue(ID_ISROOT, true);
            out.writeValue(ID_SELECTABLE, false);
        } else {
            out.writeValue(ID_ID, strParentRef);
            out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), parentRef));
        }
        out.endObject();
        out.endValue();
        out.startValue(ID_CHILDREN);
        out.startArray();
        for (ChildAssociationRef ref : childRefs) {
            NodeRef nodeRef = ref.getChildRef();
            out.startObject();
            out.writeValue(ID_ID, nodeRef.toString());
            out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), nodeRef));
            out.endObject();
        }
        out.endArray();
        out.endValue();
        out.endObject();

        tx.commit();
    } catch (Throwable err) {
        Utils.addErrorMessage("PickerBean exception in getCategoryRootNodes()", err);
        fc.getResponseWriter().write("ERROR: " + err.getMessage());
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }
}

From source file:org.alfresco.web.bean.ajax.PickerBean.java

/**
 * Return the JSON objects representing a list of cm:folder nodes.
 * /*from   w w w  .  j a va 2  s  .c  o m*/
 * IN: "parent" - noderef (can be null) of the parent to retrieve the child folder nodes for. Null is valid
 *        and specifies the Company Home root as the parent.
 * IN: "child" - non-null value of the child noderef to retrieve the siblings for - the parent value returned
 *        in the JSON response will be the parent of the specified child.
 * 
 * The 16x16 pixel folder icon path is output as the 'icon' property for each child folder. 
 */
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void getTagNodes() throws Exception {
    FacesContext fc = FacesContext.getCurrentInstance();

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

        Collection<ChildAssociationRef> childRefs;
        NodeRef parentRef = null;
        Map params = fc.getExternalContext().getRequestParameterMap();
        String strParentRef = Utils.encode((String) params.get(ID_PARENT));
        if (strParentRef == null || strParentRef.length() == 0) {
            childRefs = this.getCategoryService().getRootCategories(Repository.getStoreRef(),
                    ContentModel.ASPECT_TAGGABLE);
        } else {
            parentRef = new NodeRef(strParentRef);
            childRefs = this.getCategoryService().getChildren(parentRef, CategoryService.Mode.SUB_CATEGORIES,
                    CategoryService.Depth.IMMEDIATE);
        }

        JSONWriter out = new JSONWriter(fc.getResponseWriter());
        out.startObject();
        out.startValue(ID_PARENT);
        out.startObject();
        if (parentRef == null) {
            out.writeNullValue(ID_ID);
            out.writeValue(ID_NAME, Application.getMessage(fc, MSG_TAGS));
            out.writeValue(ID_ISROOT, true);
            out.writeValue(ID_SELECTABLE, false);
        } else {
            out.writeValue(ID_ID, strParentRef);
            out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), parentRef));
        }
        out.endObject();
        out.endValue();
        out.startValue(ID_CHILDREN);
        out.startArray();
        for (ChildAssociationRef ref : childRefs) {
            NodeRef nodeRef = ref.getChildRef();
            out.startObject();
            out.writeValue(ID_ID, nodeRef.toString());
            out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), nodeRef));
            out.endObject();
        }
        out.endArray();
        out.endValue();
        out.endObject();

        tx.commit();
    } catch (Throwable err) {
        Utils.addErrorMessage("PickerBean exception in getTagNodes()", err);
        fc.getResponseWriter().write("ERROR: " + err.getMessage());
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }
}