Example usage for javax.transaction UserTransaction commit

List of usage examples for javax.transaction UserTransaction commit

Introduction

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

Prototype

void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException,
        IllegalStateException, SystemException;

Source Link

Document

Complete the transaction associated with the current thread.

Usage

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

/**
 * Return the JSON objects representing a list of categories.
 * //  w w  w.j av a  2s.  c om
 * 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.
 * //  www.  j  a  va2  s  .  co  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) {
        }
    }
}

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

@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void getFolderNodes() throws Exception {
    FacesContext fc = FacesContext.getCurrentInstance();

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

        List<ChildAssociationRef> childRefs;
        NodeRef companyHomeRef = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId(fc));

        NodeRef parentRef = null;
        Map params = fc.getExternalContext().getRequestParameterMap();
        String strChildRef = Utils.encode((String) params.get(PARAM_CHILD));
        if (strChildRef != null && strChildRef.length() != 0) {
            // TODO: check permission on the parent
            NodeRef childRef = new NodeRef(strChildRef);
            parentRef = this.getNodeService().getPrimaryParent(childRef).getParentRef();
        } else {
            // TODO: check permission on the parent
            String strParentRef = Utils.encode((String) params.get(PARAM_PARENT));
            if (strParentRef == null || strParentRef.length() == 0) {
                parentRef = companyHomeRef;
                strParentRef = parentRef.toString();
            } else {
                parentRef = new NodeRef(strParentRef);
            }
        }

        List<FileInfo> folders = this.getFileFolderService().listFolders(parentRef);

        JSONWriter out = new JSONWriter(fc.getResponseWriter());
        out.startObject();
        out.startValue(ID_PARENT);
        out.startObject();
        out.writeValue(ID_ID, parentRef.toString());
        out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), parentRef));
        if (parentRef.equals(companyHomeRef)) {
            out.writeValue(ID_ISROOT, true);
        }
        out.endObject();
        out.endValue();
        out.startValue(ID_CHILDREN);
        out.startArray();

        // filter out those children that are not spaces
        for (FileInfo folder : folders) {
            out.startObject();
            out.writeValue(ID_ID, folder.getNodeRef().toString());
            out.writeValue(ID_NAME, (String) folder.getProperties().get(ContentModel.PROP_NAME));
            String icon = (String) folder.getProperties().get(ApplicationModel.PROP_ICON);
            out.writeValue(ID_ICON, FOLDER_IMAGE_PREFIX
                    + (icon != null ? icon + "-16.gif" : BrowseBean.SPACE_SMALL_DEFAULT + ".gif"));
            out.endObject();
        }

        out.endArray();
        out.endValue();
        out.endObject();

        tx.commit();
    } catch (Throwable err) {
        Utils.addErrorMessage("PickerBean exception in getFolderNodes()", 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 and cm:content nodes.
 * /*from  w  w  w  .  j av  a 2  s  .  com*/
 * IN: "parent" - noderef (can be null) of the parent to retrieve the child 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.
 * IN: "mimetypes" (optional) - if set, a comma separated list of mimetypes to restrict the file list.
 * 
 * It is assumed that only files should be selectable, all cm:folder nodes will be marked with the
 * 'selectable:false' property. Therefore the parent (which is a folder) is not selectable.
 * 
 * The 16x16 pixel node icon path is output as the 'icon' property for each child, in addition each
 * cm:content node has an property of 'url' for content download. 
 */
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void getFileFolderNodes() throws Exception {
    FacesContext fc = FacesContext.getCurrentInstance();

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

        DictionaryService dd = Repository.getServiceRegistry(fc).getDictionaryService();
        ContentService cs = Repository.getServiceRegistry(fc).getContentService();

        List<ChildAssociationRef> childRefs;
        NodeRef companyHomeRef = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId(fc));

        NodeRef parentRef = null;
        Map params = fc.getExternalContext().getRequestParameterMap();
        String strChildRef = Utils.encode((String) params.get(PARAM_CHILD));
        if (strChildRef != null && strChildRef.length() != 0) {
            // TODO: check permission on the parent
            NodeRef childRef = new NodeRef(strChildRef);
            parentRef = this.getNodeService().getPrimaryParent(childRef).getParentRef();
        } else {
            // TODO: check permission on the parent
            String strParentRef = Utils.encode((String) params.get(PARAM_PARENT));
            if (strParentRef == null || strParentRef.length() == 0) {
                parentRef = companyHomeRef;
                strParentRef = parentRef.toString();
            } else {
                parentRef = new NodeRef(strParentRef);
            }
        }

        // look for mimetype restriction parameter
        Set<String> mimetypes = null;
        String mimetypeParam = (String) params.get(PARAM_MIMETYPES);
        if (mimetypeParam != null && mimetypeParam.length() != 0) {
            // convert to a set of mimetypes to test each file against
            mimetypes = new HashSet<String>();
            for (StringTokenizer t = new StringTokenizer(mimetypeParam, ","); t.hasMoreTokens(); /**/) {
                mimetypes.add(t.nextToken());
            }
        }

        List<FileInfo> items = this.getFileFolderService().list(parentRef);

        JSONWriter out = new JSONWriter(fc.getResponseWriter());
        out.startObject();
        out.startValue(ID_PARENT);
        out.startObject();
        out.writeValue(ID_ID, parentRef.toString());
        out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), parentRef));
        if (parentRef.equals(companyHomeRef)) {
            out.writeValue(ID_ISROOT, true);
        }
        out.writeValue(ID_SELECTABLE, false);
        out.endObject();
        out.endValue();
        out.startValue(ID_CHILDREN);
        out.startArray();

        for (FileInfo item : items) {
            if (dd.isSubClass(this.getInternalNodeService().getType(item.getNodeRef()),
                    ContentModel.TYPE_FOLDER)) {
                // found a folder
                out.startObject();
                out.writeValue(ID_ID, item.getNodeRef().toString());
                String name = (String) item.getProperties().get(ContentModel.PROP_NAME);
                out.writeValue(ID_NAME, name);
                String icon = (String) item.getProperties().get(ApplicationModel.PROP_ICON);
                out.writeValue(ID_ICON, FOLDER_IMAGE_PREFIX
                        + (icon != null ? icon + "-16.gif" : BrowseBean.SPACE_SMALL_DEFAULT + ".gif"));
                out.writeValue(ID_SELECTABLE, false);
                out.endObject();
            } else {
                // must be a file
                boolean validFile = true;
                if (mimetypes != null) {
                    validFile = false;
                    ContentReader reader = cs.getReader(item.getNodeRef(), ContentModel.PROP_CONTENT);
                    if (reader != null) {
                        String mimetype = reader.getMimetype();
                        validFile = (mimetype != null && mimetypes.contains(mimetype));
                    }
                }
                if (validFile) {
                    out.startObject();
                    out.writeValue(ID_ID, item.getNodeRef().toString());
                    String name = (String) item.getProperties().get(ContentModel.PROP_NAME);
                    out.writeValue(ID_NAME, name);
                    String icon = FileTypeImageUtils.getFileTypeImage(fc, name, FileTypeImageSize.Small);
                    out.writeValue(ID_ICON, icon);
                    out.writeValue(ID_URL, DownloadContentServlet.generateBrowserURL(item.getNodeRef(), name));
                    out.endObject();
                }
            }
        }

        out.endArray();
        out.endValue();
        out.endObject();

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

From source file:org.alfresco.web.bean.BrowseBean.java

/**
 * Page accessed bean method to get the parent container nodes currently being browsed
 *
 * @return List of parent container Node objects for the current browse location
 *///from ww w.ja  va  2s .  com
public List<Node> getParentNodes(NodeRef currNodeRef) {
    // As per AWC-1507 there are two scenarios for navigating to the space details. First
    // scenario is to show space details of the current space. Second scenario is to show 
    // space details of a child space of the current space. For now, added an extra query
    // so that existing context remains unaffected for second scenario, although it does 
    // mean that in first scenario there will be an extra query even though parentContainerNodes
    // and containerNodes will contain the same list.

    if (this.parentContainerNodes == null) {
        long startTime = 0;
        if (logger.isDebugEnabled())
            startTime = System.currentTimeMillis();

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

            NodeRef parentRef = getNodeService().getPrimaryParent(currNodeRef).getParentRef();

            List<FileInfo> children = this.getFileFolderService().list(parentRef);
            this.parentContainerNodes = new ArrayList<Node>(children.size());
            for (FileInfo fileInfo : children) {
                // create our Node representation from the NodeRef
                NodeRef nodeRef = fileInfo.getNodeRef();

                // find it's type so we can see if it's a node we are interested in
                QName type = this.getNodeService().getType(nodeRef);

                // make sure the type is defined in the data dictionary
                TypeDefinition typeDef = this.getDictionaryService().getType(type);

                if (typeDef != null) {
                    MapNode node = null;

                    // look for Space folder node
                    if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) == true
                            && this.getDictionaryService().isSubClass(type,
                                    ContentModel.TYPE_SYSTEM_FOLDER) == false) {
                        // create our Node representation
                        node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
                        node.addPropertyResolver("icon", this.resolverSpaceIcon);
                        node.addPropertyResolver("smallIcon", this.resolverSmallIcon);

                        this.parentContainerNodes.add(node);
                    } else if (ApplicationModel.TYPE_FOLDERLINK.equals(type)) {
                        // create our Folder Link Node representation
                        node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
                        node.addPropertyResolver("icon", this.resolverSpaceIcon);
                        node.addPropertyResolver("smallIcon", this.resolverSmallIcon);

                        this.parentContainerNodes.add(node);
                    }
                } else {
                    if (logger.isWarnEnabled())
                        logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type);
                }
            }

            // commit the transaction
            tx.commit();
        } catch (InvalidNodeRefException refErr) {
            Utils.addErrorMessage(MessageFormat.format(
                    Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF),
                    new Object[] { refErr.getNodeRef() }), refErr);
            this.parentContainerNodes = Collections.<Node>emptyList();
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }
        } catch (Throwable err) {
            Utils.addErrorMessage(MessageFormat.format(
                    Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC),
                    err.getMessage()), err);
            this.parentContainerNodes = Collections.<Node>emptyList();
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }
        }

        if (logger.isDebugEnabled()) {
            long endTime = System.currentTimeMillis();
            logger.debug("Time to query and build map parent nodes: " + (endTime - startTime) + "ms");
        }
    }

    List<Node> result = this.parentContainerNodes;

    // we clear the member variable during invalidateComponents()

    return result;
}

From source file:org.alfresco.web.bean.BrowseBean.java

/**
 * Query a list of nodes for the specified parent node Id
 *
 * @param parentNodeId     Id of the parent node or null for the root node
 *///from  ww  w.j a v a  2 s .co m
private void queryBrowseNodes(String parentNodeId) {
    long startTime = 0;
    if (logger.isDebugEnabled())
        startTime = System.currentTimeMillis();

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

        NodeRef parentRef;
        if (parentNodeId == null) {
            // no specific parent node specified - use the root node
            parentRef = this.getNodeService().getRootNode(Repository.getStoreRef());
        } else {
            // build a NodeRef for the specified Id and our store
            parentRef = new NodeRef(Repository.getStoreRef(), parentNodeId);
        }

        List<FileInfo> children = null;
        FileFilterMode.setClient(Client.webclient);
        try {
            children = this.getFileFolderService().list(parentRef);
        } finally {
            FileFilterMode.clearClient();
        }

        this.containerNodes = new ArrayList<Node>(children.size());
        this.contentNodes = new ArrayList<Node>(children.size());

        // in case of dynamic config, only lookup once
        Set<NodeEventListener> nodeEventListeners = getNodeEventListeners();

        for (FileInfo fileInfo : children) {
            // create our Node representation from the NodeRef
            NodeRef nodeRef = fileInfo.getNodeRef();

            // find it's type so we can see if it's a node we are interested in
            QName type = this.getNodeService().getType(nodeRef);

            // make sure the type is defined in the data dictionary
            TypeDefinition typeDef = this.getDictionaryService().getType(type);

            if (typeDef != null) {
                MapNode node = null;

                // look for File content node
                if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT)) {
                    // create our Node representation
                    node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
                    setupCommonBindingProperties(node);

                    this.contentNodes.add(node);
                }
                // look for Space folder node
                else if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) == true && this
                        .getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) {
                    // create our Node representation
                    node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
                    node.addPropertyResolver("icon", this.resolverSpaceIcon);
                    node.addPropertyResolver("smallIcon", this.resolverSmallIcon);

                    this.containerNodes.add(node);
                }
                // look for File Link object node
                else if (ApplicationModel.TYPE_FILELINK.equals(type)) {
                    // create our File Link Node representation
                    node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
                    // only display the user has the permissions to navigate to the target of the link
                    NodeRef destRef = (NodeRef) node.getProperties().get(ContentModel.PROP_LINK_DESTINATION);
                    if (destRef != null && new Node(destRef).hasPermission(PermissionService.READ) == true) {
                        node.addPropertyResolver("url", this.resolverLinkUrl);
                        node.addPropertyResolver("downloadUrl", this.resolverLinkDownload);
                        node.addPropertyResolver("webdavUrl", this.resolverLinkWebdavUrl);
                        node.addPropertyResolver("cifsPath", this.resolverLinkCifsPath);
                        node.addPropertyResolver("fileType16", this.resolverFileType16);
                        node.addPropertyResolver("fileType32", this.resolverFileType32);
                        node.addPropertyResolver("lang", this.resolverLang);

                        this.contentNodes.add(node);
                    }
                } else if (ApplicationModel.TYPE_FOLDERLINK.equals(type)) {
                    // create our Folder Link Node representation
                    node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
                    // only display the user has the permissions to navigate to the target of the link
                    NodeRef destRef = (NodeRef) node.getProperties().get(ContentModel.PROP_LINK_DESTINATION);
                    if (destRef != null && new Node(destRef).hasPermission(PermissionService.READ) == true) {
                        node.addPropertyResolver("icon", this.resolverSpaceIcon);
                        node.addPropertyResolver("smallIcon", this.resolverSmallIcon);

                        this.containerNodes.add(node);
                    }
                }

                // inform any listeners that a Node wrapper has been created
                if (node != null) {
                    for (NodeEventListener listener : nodeEventListeners) {
                        listener.created(node, type);
                    }
                }
            } else {
                if (logger.isWarnEnabled())
                    logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type);
            }
        }

        // commit the transaction
        tx.commit();
    } catch (InvalidNodeRefException refErr) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF),
                new Object[] { refErr.getNodeRef() }), refErr);
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC),
                err.getMessage()), err);
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }

    if (logger.isDebugEnabled()) {
        long endTime = System.currentTimeMillis();
        logger.debug("Time to query and build map nodes: " + (endTime - startTime) + "ms");
    }
}

From source file:org.alfresco.web.bean.BrowseBean.java

/**
 * Search for a list of nodes using the specific search context
 *
 * @param searchContext    To use to perform the search
 *//*from www. j  a  v a 2s . c  o  m*/
private void searchBrowseNodes(SearchContext searchContext) {
    long startTime = 0;
    if (logger.isDebugEnabled())
        startTime = System.currentTimeMillis();

    // get the searcher object to build the query
    String query = searchContext.buildQuery(getMinimumSearchLength());
    if (query == null) {
        // failed to build a valid query, the user probably did not enter the
        // minimum text required to construct a valid search
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), MSG_SEARCH_MINIMUM),
                new Object[] { getMinimumSearchLength() }));
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        return;
    }

    // perform the search against the repo
    UserTransaction tx = null;
    ResultSet results = null;
    try {
        tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true);
        tx.begin();

        // build up the search parameters
        SearchParameters sp = new SearchParameters();
        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp.setQuery(query);
        sp.addStore(Repository.getStoreRef());

        // limit search results size as configured
        int searchLimit = Application.getClientConfig(FacesContext.getCurrentInstance()).getSearchMaxResults();
        if (searchLimit > 0) {
            sp.setLimitBy(LimitBy.FINAL_SIZE);
            sp.setLimit(searchLimit);
        }

        sp.setBulkFetchEnabled(
                Application.getClientConfig(FacesContext.getCurrentInstance()).isBulkFetchEnabled());

        results = this.getSearchService().query(sp);
        if (logger.isDebugEnabled())
            logger.debug("Search results returned: " + results.length());

        // create a list of items from the results
        this.containerNodes = new ArrayList<Node>(results.length());
        this.contentNodes = new ArrayList<Node>(results.length());
        if (results.length() != 0) {
            // in case of dynamic config, only lookup once
            Set<NodeEventListener> nodeEventListeners = getNodeEventListeners();

            for (ResultSetRow row : results) {
                NodeRef nodeRef = row.getNodeRef();

                if (this.getNodeService().exists(nodeRef)) {
                    // find it's type so we can see if it's a node we are interested in
                    QName type = this.getNodeService().getType(nodeRef);

                    // make sure the type is defined in the data dictionary
                    TypeDefinition typeDef = this.getDictionaryService().getType(type);

                    if (typeDef != null) {
                        MapNode node = null;

                        // look for Space or File nodes
                        if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER)
                                && this.getDictionaryService().isSubClass(type,
                                        ContentModel.TYPE_SYSTEM_FOLDER) == false) {
                            // create our Node representation
                            node = new MapNode(nodeRef, this.getNodeService(), false);

                            node.addPropertyResolver("path", this.resolverPath);
                            node.addPropertyResolver("displayPath", this.resolverDisplayPath);
                            node.addPropertyResolver("icon", this.resolverSpaceIcon);
                            node.addPropertyResolver("smallIcon", this.resolverSmallIcon);

                            this.containerNodes.add(node);
                        } else if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT)) {
                            // create our Node representation
                            node = new MapNode(nodeRef, this.getNodeService(), false);

                            setupCommonBindingProperties(node);

                            node.addPropertyResolver("path", this.resolverPath);
                            node.addPropertyResolver("displayPath", this.resolverDisplayPath);

                            this.contentNodes.add(node);
                        }
                        // look for File Link object node
                        else if (ApplicationModel.TYPE_FILELINK.equals(type)) {
                            // create our File Link Node representation
                            node = new MapNode(nodeRef, this.getNodeService(), false);
                            // only display the user has the permissions to navigate to the target of the link
                            NodeRef destRef = (NodeRef) node.getProperties()
                                    .get(ContentModel.PROP_LINK_DESTINATION);
                            if (new Node(destRef).hasPermission(PermissionService.READ) == true) {
                                node.addPropertyResolver("url", this.resolverLinkUrl);
                                node.addPropertyResolver("downloadUrl", this.resolverLinkDownload);
                                node.addPropertyResolver("webdavUrl", this.resolverLinkWebdavUrl);
                                node.addPropertyResolver("cifsPath", this.resolverLinkCifsPath);
                                node.addPropertyResolver("fileType16", this.resolverFileType16);
                                node.addPropertyResolver("fileType32", this.resolverFileType32);
                                node.addPropertyResolver("lang", this.resolverLang);
                                node.addPropertyResolver("path", this.resolverPath);
                                node.addPropertyResolver("displayPath", this.resolverDisplayPath);

                                this.contentNodes.add(node);
                            }
                        } else if (ApplicationModel.TYPE_FOLDERLINK.equals(type)) {
                            // create our Folder Link Node representation
                            node = new MapNode(nodeRef, this.getNodeService(), false);
                            // only display the user has the permissions to navigate to the target of the link
                            NodeRef destRef = (NodeRef) node.getProperties()
                                    .get(ContentModel.PROP_LINK_DESTINATION);
                            if (new Node(destRef).hasPermission(PermissionService.READ) == true) {
                                node.addPropertyResolver("icon", this.resolverSpaceIcon);
                                node.addPropertyResolver("smallIcon", this.resolverSmallIcon);
                                node.addPropertyResolver("path", this.resolverPath);
                                node.addPropertyResolver("displayPath", this.resolverDisplayPath);

                                this.containerNodes.add(node);
                            }
                        }

                        // inform any listeners that a Node wrapper has been created
                        if (node != null) {
                            for (NodeEventListener listener : nodeEventListeners) {
                                listener.created(node, type);
                            }
                        }
                    } else {
                        if (logger.isWarnEnabled())
                            logger.warn(
                                    "Found invalid object in database: id = " + nodeRef + ", type = " + type);
                    }
                } else {
                    if (logger.isWarnEnabled())
                        logger.warn("Missing object returned from search indexes: id = " + nodeRef
                                + " search query: " + query);
                }
            }
        }

        // commit the transaction
        tx.commit();
    } catch (InvalidNodeRefException refErr) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF),
                new Object[] { refErr.getNodeRef() }), refErr);
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (SearcherException serr) {
        logger.info("Search failed for: " + query, serr);
        Utils.addErrorMessage(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_QUERY));
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_SEARCH),
                new Object[] { err.getMessage() }), err);
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } finally {
        if (results != null) {
            results.close();
        }
    }

    if (logger.isDebugEnabled()) {
        long endTime = System.currentTimeMillis();
        logger.debug("Time to query and build map nodes: " + (endTime - startTime) + "ms");
    }
}

From source file:org.alfresco.web.bean.categories.CategoriesDialog.java

/**
 * @return The list of categories Nodes to display. Returns the list root categories or the 
 *         list of sub-categories for the current category if set.
 *//*ww w .  j a  v a 2  s. c  o  m*/
public List<Node> getCategories() {
    List<Node> categories;

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

        Collection<ChildAssociationRef> refs;
        if (getCategoryRef() == null) {
            // root categories
            refs = getCategoryService().getCategories(Repository.getStoreRef(),
                    ContentModel.ASPECT_GEN_CLASSIFIABLE, Depth.IMMEDIATE);
        } else {
            // sub-categories of an existing category
            refs = getCategoryService().getChildren(getCategoryRef(), Mode.SUB_CATEGORIES, Depth.IMMEDIATE);
        }
        categories = new ArrayList<Node>(refs.size());
        for (ChildAssociationRef child : refs) {
            Node categoryNode = new Node(child.getChildRef());
            // force early props init within transaction
            categoryNode.getProperties();
            categories.add(categoryNode);
        }

        // commit the transaction
        tx.commit();
    } catch (InvalidNodeRefException refErr) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF),
                new Object[] { refErr.getNodeRef() }));
        categories = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC),
                err.getMessage()), err);
        categories = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }

    return categories;
}

From source file:org.alfresco.web.bean.coci.EditOfflineDialog.java

/**
 * Checkout document to the same space as original one and then add the
 * OFFLINE_EDITING property./*from  w  ww  . j  av  a 2 s  .com*/
 */
private void checkoutFile(Node node) {
    UserTransaction tx = null;
    FacesContext context = FacesContext.getCurrentInstance();

    if (node != null) {
        try {
            tx = Repository.getUserTransaction(context, false);
            tx.begin();

            if (logger.isDebugEnabled())
                logger.debug("Trying to checkout content node Id: " + node.getId());
            NodeRef workingCopyRef = null;

            // checkout the content to the current space
            workingCopyRef = property.getVersionOperationsService().checkout(node.getNodeRef());
            getNodeService().setProperty(workingCopyRef, ContentModel.PROP_WORKING_COPY_MODE, OFFLINE_EDITING);

            // set the working copy Node instance
            Node workingCopy = new Node(workingCopyRef);
            property.setWorkingDocument(workingCopy);

            // create content URL to the content download servlet with ID and
            // expected filename
            String url = DownloadContentServlet.generateDownloadURL(workingCopyRef, workingCopy.getName());

            workingCopy.getProperties().put("url", url);
            workingCopy.getProperties().put("fileType32",
                    FileTypeImageUtils.getFileTypeImage(workingCopy.getName(), false));

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

            Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_CHECKOUT)
                    + err.getMessage(), err);
        }
    } else {
        logger.warn("WARNING: checkoutFile called without a current Document!");
    }
}

From source file:org.alfresco.web.bean.forums.ForumsBean.java

private void getNodes() {
    long startTime = 0;
    if (logger.isDebugEnabled())
        startTime = System.currentTimeMillis();

    UserTransaction tx = null;
    try {/*from  w w  w.j  a va2 s .  c o  m*/
        FacesContext context = FacesContext.getCurrentInstance();
        tx = Repository.getUserTransaction(context, true);
        tx.begin();

        // get the current space from NavigationBean
        String parentNodeId = this.navigator.getCurrentNodeId();

        NodeRef parentRef;
        if (parentNodeId == null) {
            // no specific parent node specified - use the root node
            parentRef = this.getNodeService().getRootNode(Repository.getStoreRef());
        } else {
            // build a NodeRef for the specified Id and our store
            parentRef = new NodeRef(Repository.getStoreRef(), parentNodeId);
        }

        List<ChildAssociationRef> childRefs = this.getNodeService().getChildAssocs(parentRef,
                ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
        this.forums = new ArrayList<Node>(childRefs.size());
        this.topics = new ArrayList<Node>(childRefs.size());
        this.posts = new ArrayList<Node>(childRefs.size());

        for (ChildAssociationRef ref : childRefs) {
            // create our Node representation from the NodeRef
            NodeRef nodeRef = ref.getChildRef();

            if (this.getNodeService().exists(nodeRef)) {
                // find it's type so we can see if it's a node we are interested in
                QName type = this.getNodeService().getType(nodeRef);

                // make sure the type is defined in the data dictionary
                TypeDefinition typeDef = this.getDictionaryService().getType(type);

                if (typeDef != null) {
                    // extract forums, forum, topic and post types

                    if (this.getDictionaryService().isSubClass(type,
                            ContentModel.TYPE_SYSTEM_FOLDER) == false) {
                        if (this.getDictionaryService().isSubClass(type, ForumModel.TYPE_FORUMS)
                                || this.getDictionaryService().isSubClass(type, ForumModel.TYPE_FORUM)) {
                            // create our Node representation
                            MapNode node = new MapNode(nodeRef, this.getNodeService(), true);
                            node.addPropertyResolver("icon", this.browseBean.resolverSpaceIcon);
                            node.addPropertyResolver("smallIcon", this.browseBean.resolverSmallIcon);

                            this.forums.add(node);
                        }
                        if (this.getDictionaryService().isSubClass(type, ForumModel.TYPE_TOPIC)) {
                            // create our Node representation
                            MapNode node = new MapNode(nodeRef, this.getNodeService(), true);
                            node.addPropertyResolver("icon", this.browseBean.resolverSpaceIcon);
                            node.addPropertyResolver("smallIcon", this.browseBean.resolverSmallIcon);
                            node.addPropertyResolver("replies", this.resolverReplies);

                            this.topics.add(node);
                        } else if (this.getDictionaryService().isSubClass(type, ForumModel.TYPE_POST)) {
                            // create our Node representation
                            MapNode node = new MapNode(nodeRef, this.getNodeService(), true);

                            this.browseBean.setupCommonBindingProperties(node);
                            node.addPropertyResolver("smallIcon", this.browseBean.resolverSmallIcon);
                            node.addPropertyResolver("message", this.resolverContent);
                            node.addPropertyResolver("replyTo", this.resolverReplyTo);

                            this.posts.add(node);
                        }
                    }
                } else {
                    if (logger.isWarnEnabled())
                        logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type);
                }
            }
        }

        // commit the transaction
        tx.commit();
    } catch (InvalidNodeRefException refErr) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF),
                new Object[] { refErr.getNodeRef() }));
        this.forums = Collections.<Node>emptyList();
        this.topics = Collections.<Node>emptyList();
        this.posts = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(
                Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC),
                err.getMessage()), err);
        this.forums = Collections.<Node>emptyList();
        this.topics = Collections.<Node>emptyList();
        this.posts = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }

    if (logger.isDebugEnabled()) {
        long endTime = System.currentTimeMillis();
        logger.debug("Time to query and build forums nodes: " + (endTime - startTime) + "ms");
    }
}