Search in sources :

Example 1 with AssociationDefinition

use of org.alfresco.service.cmr.dictionary.AssociationDefinition in project acs-community-packaging by Alfresco.

the class BaseAssociationEditor method getAvailableOptions.

/**
 * Retrieves the available options for the current association
 *
 * @param context Faces Context
 * @param contains The contains part of the query
 */
protected void getAvailableOptions(FacesContext context, String contains) {
    AssociationDefinition assocDef = getAssociationDefinition(context);
    if (assocDef != null) {
        // find and show all the available options for the current association
        String type = assocDef.getTargetClass().getName().toString();
        if (type.equals(ContentModel.TYPE_AUTHORITY_CONTAINER.toString())) {
            UserTransaction tx = null;
            try {
                tx = Repository.getUserTransaction(context, true);
                tx.begin();
                String safeContains = null;
                if (contains != null && contains.length() > 0) {
                    safeContains = Utils.remove(contains.trim(), "\"");
                    safeContains = safeContains.toLowerCase();
                }
                // get all available groups
                AuthorityService authorityService = Repository.getServiceRegistry(context).getAuthorityService();
                Set<String> groups = authorityService.getAllAuthoritiesInZone(AuthorityService.ZONE_APP_DEFAULT, AuthorityType.GROUP);
                this.availableOptions = new ArrayList<NodeRef>(groups.size());
                // get the NodeRef for each matching group
                AuthorityDAO authorityDAO = (AuthorityDAO) FacesContextUtils.getRequiredWebApplicationContext(context).getBean("authorityDAO");
                if (authorityDAO != null) {
                    List<String> matchingGroups = new ArrayList<String>();
                    String groupDisplayName;
                    for (String group : groups) {
                        // get display name, if not present strip prefix from group id
                        groupDisplayName = authorityService.getAuthorityDisplayName(group);
                        if (groupDisplayName == null || groupDisplayName.length() == 0) {
                            groupDisplayName = group.substring(PermissionService.GROUP_PREFIX.length());
                        }
                        // otherwise just add the group name to the sorted set
                        if (safeContains != null) {
                            if (groupDisplayName.toLowerCase().indexOf(safeContains) != -1) {
                                matchingGroups.add(group);
                            }
                        } else {
                            matchingGroups.add(group);
                        }
                    }
                    // sort the group names
                    Collections.sort(matchingGroups, new SimpleStringComparator());
                    // go through the sorted set and get the NodeRef for each group
                    for (String groupName : matchingGroups) {
                        NodeRef groupRef = authorityDAO.getAuthorityNodeRefOrNull(groupName);
                        if (groupRef != null) {
                            this.availableOptions.add(groupRef);
                        }
                    }
                }
                // commit the transaction
                tx.commit();
            } catch (Throwable err) {
                Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC), err.getMessage()), err);
                this.availableOptions = Collections.<NodeRef>emptyList();
                try {
                    if (tx != null) {
                        tx.rollback();
                    }
                } catch (Exception tex) {
                }
            }
        } else if (type.equals(ContentModel.TYPE_PERSON.toString())) {
            List<Pair<QName, String>> filter = (contains != null && contains.trim().length() > 0) ? Utils.generatePersonFilter(contains.trim()) : null;
            // Always sort by last name, then first name
            List<Pair<QName, Boolean>> sort = new ArrayList<Pair<QName, Boolean>>();
            sort.add(new Pair<QName, Boolean>(ContentModel.PROP_LASTNAME, true));
            sort.add(new Pair<QName, Boolean>(ContentModel.PROP_FIRSTNAME, true));
            // Log the filtering
            if (logger.isDebugEnabled())
                logger.debug("Query filter: " + filter);
            // How many to limit too?
            int maxResults = Application.getClientConfig(context).getSelectorsSearchMaxResults();
            if (maxResults <= 0) {
                maxResults = Utils.getPersonMaxResults();
            }
            List<PersonInfo> persons = Repository.getServiceRegistry(context).getPersonService().getPeople(filter, true, sort, new PagingRequest(maxResults, null)).getPage();
            // Save the results
            List<NodeRef> nodes = new ArrayList<NodeRef>(persons.size());
            for (PersonInfo person : persons) {
                nodes.add(person.getNodeRef());
            }
            this.availableOptions = nodes;
        } else {
            // for all other types/aspects perform a lucene search
            StringBuilder query = new StringBuilder("+TYPE:\"");
            if (assocDef.getTargetClass().isAspect()) {
                query = new StringBuilder("+ASPECT:\"");
            } else {
                query = new StringBuilder("+TYPE:\"");
            }
            query.append(type);
            query.append("\"");
            if (contains != null && contains.trim().length() != 0) {
                String safeContains = null;
                if (contains != null && contains.length() > 0) {
                    safeContains = Utils.remove(contains.trim(), "\"");
                    safeContains = safeContains.toLowerCase();
                }
                query.append(" AND +@");
                String nameAttr = Repository.escapeQName(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "name"));
                query.append(nameAttr);
                query.append(":\"*" + safeContains + "*\"");
            }
            int maxResults = Application.getClientConfig(context).getSelectorsSearchMaxResults();
            if (logger.isDebugEnabled()) {
                logger.debug("Query: " + query.toString());
                logger.debug("Max results size: " + maxResults);
            }
            SearchParameters searchParams = new SearchParameters();
            searchParams.addStore(Repository.getStoreRef());
            searchParams.setLanguage(SearchService.LANGUAGE_LUCENE);
            searchParams.setQuery(query.toString());
            if (maxResults > 0) {
                searchParams.setLimit(maxResults);
                searchParams.setLimitBy(LimitBy.FINAL_SIZE);
            }
            ResultSet results = null;
            try {
                results = Repository.getServiceRegistry(context).getSearchService().query(searchParams);
                this.availableOptions = results.getNodeRefs();
            } catch (SearcherException se) {
                logger.info("Search failed for: " + query, se);
                Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_QUERY));
            } finally {
                if (results != null) {
                    results.close();
                }
            }
        }
        if (logger.isDebugEnabled())
            logger.debug("Found " + this.availableOptions.size() + " available options");
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) PersonInfo(org.alfresco.service.cmr.security.PersonService.PersonInfo) QName(org.alfresco.service.namespace.QName) AuthorityService(org.alfresco.service.cmr.security.AuthorityService) ArrayList(java.util.ArrayList) AuthorityDAO(org.alfresco.repo.security.authority.AuthorityDAO) SearcherException(org.alfresco.repo.search.SearcherException) AbortProcessingException(javax.faces.event.AbortProcessingException) IOException(java.io.IOException) PagingRequest(org.alfresco.query.PagingRequest) NodeRef(org.alfresco.service.cmr.repository.NodeRef) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition) SearcherException(org.alfresco.repo.search.SearcherException) ResultSet(org.alfresco.service.cmr.search.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) Pair(org.alfresco.util.Pair)

Example 2 with AssociationDefinition

use of org.alfresco.service.cmr.dictionary.AssociationDefinition in project acs-community-packaging by Alfresco.

the class BaseAssociationEditor method encodeBegin.

/**
 * @see javax.faces.component.UIComponent#encodeBegin(javax.faces.context.FacesContext)
 */
public void encodeBegin(FacesContext context) throws IOException {
    if (isRendered() == false) {
        return;
    }
    // reset the highlighted row flag
    this.highlightedRow = false;
    ResponseWriter out = context.getResponseWriter();
    // get the child associations currently on the node and any that have been added
    NodeService nodeService = Repository.getServiceRegistry(context).getNodeService();
    // show the editable association component
    AssociationDefinition assocDef = getAssociationDefinition(context);
    if (assocDef == null) {
        logger.warn("Failed to find association definition for association '" + associationName + "'");
        // add an error message as the property is not defined in the data dictionary
        String msg = MessageFormat.format(Application.getMessage(context, MSG_ERROR_ASSOC), new Object[] { this.associationName });
        Utils.addErrorMessage(msg);
    } else {
        String targetType = assocDef.getTargetClass().getName().toString();
        boolean allowMany = assocDef.isTargetMany();
        populateAssocationMaps((Node) getValue(), nodeService);
        if (isDisabled()) {
            // show the current list of associations in a read-only form
            renderReadOnlyAssociations(context, out, nodeService);
        } else {
            // start outer table
            out.write("<table border='0' cellspacing='4' cellpadding='0' class='multiValueSelector'>");
            if (allowMany) {
                out.write("<tr><td colspan='2'>1.&nbsp;");
                out.write(getSelectItemsMsg());
                out.write("</td></tr>");
                // show the search field
                renderSearchField(context, out);
                // show available options for this association
                renderAvailableOptions(context, out, nodeService, targetType, allowMany);
                // add the Add to List button
                out.write("<tr><td colspan='2'>2.&nbsp;<input type='submit' value='");
                out.write(Application.getMessage(context, MSG_ADD_TO_LIST_BUTTON));
                out.write("' onclick=\"");
                out.write(generateFormSubmit(context, Integer.toString(ACTION_ADD)));
                out.write("\"/>");
                // add some padding
                out.write("<tr><td height='6'></td></tr>");
                out.write("<tr><td colspan='2'>");
                out.write(getSelectedItemsMsg());
                out.write("</td></tr>");
                // show all the current associations
                out.write("<tr><td colspan='2'><table cellspacing='0' cellpadding='2' border='0' class='selectedItems'>");
                out.write("<tr><td colspan='2' class='selectedItemsHeader'>");
                out.write(Application.getMessage(context, "name"));
                out.write("</td></tr>");
                renderExistingAssociations(context, out, nodeService, allowMany);
                out.write("</table></td></tr>");
            } else {
                if (this.showAvailable) {
                    out.write("<tr><td colspan='2'>1.&nbsp;");
                    out.write(getSelectItemMsg());
                    out.write("</td></tr>");
                    // show the search field
                    renderSearchField(context, out);
                    // show available options for this association
                    renderAvailableOptions(context, out, nodeService, targetType, allowMany);
                    // add the ok and cancel buttons
                    out.write("<tr><td colspan='2' align='right'><input type='submit' value='");
                    out.write(Application.getMessage(context, MSG_OK));
                    out.write("' onclick=\"");
                    out.write(generateFormSubmit(context, Integer.toString(ACTION_SET)));
                    out.write("\"/>&nbsp;&nbsp;<input type='submit' value='");
                    out.write(Application.getMessage(context, MSG_CANCEL));
                    out.write("' onclick=\"");
                    out.write(generateFormSubmit(context, Integer.toString(ACTION_CANCEL)));
                    out.write("\"/></td></tr>");
                } else {
                    // show the select button if required
                    if ((allowMany == false && this.originalAssocs.size() == 0 && this.added.size() == 0) || (allowMany == false && this.originalAssocs.size() == 1 && this.removed.size() == 1 && this.added.size() == 0)) {
                        out.write("<tr><td><input type='submit' value='");
                        out.write(Application.getMessage(context, MSG_SELECT_BUTTON));
                        out.write("' onclick=\"");
                        out.write(generateFormSubmit(context, Integer.toString(ACTION_SELECT)));
                        out.write("\"/></td></tr>");
                    } else {
                        // show the current association
                        renderExistingAssociations(context, out, nodeService, allowMany);
                    }
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("number original = " + this.originalAssocs.size());
                logger.debug("number added = " + this.added.size());
                logger.debug("number removed = " + this.removed.size());
            }
            // close table
            out.write("</table>");
            // output a hidden field containing the current value
            out.write("<input type='hidden' id='");
            out.write(this.getClientId(context));
            out.write("_current_value");
            out.write("' name='");
            out.write(this.getClientId(context));
            out.write("_current_value");
            out.write("' value='");
            // if the current state will leave the node without any associations
            // do not set a value for the hidden field
            int numberAssocs = (this.originalAssocs.size() + this.added.size()) - this.removed.size();
            if (numberAssocs > 0) {
                out.write(Integer.toString(numberAssocs));
            }
            out.write("' />");
        }
    }
}
Also used : AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition) ResponseWriter(javax.faces.context.ResponseWriter) NodeService(org.alfresco.service.cmr.repository.NodeService)

Example 3 with AssociationDefinition

use of org.alfresco.service.cmr.dictionary.AssociationDefinition in project acs-community-packaging by Alfresco.

the class UIChildAssociation method generateItem.

protected void generateItem(FacesContext context, UIPropertySheet propSheet) throws IOException {
    String associationName = (String) getName();
    // get details of the association
    DataDictionary dd = (DataDictionary) FacesContextUtils.getRequiredWebApplicationContext(context).getBean(Application.BEAN_DATA_DICTIONARY);
    AssociationDefinition assocDef = dd.getAssociationDefinition(propSheet.getNode(), associationName);
    if (assocDef == null) {
        logger.warn("Failed to find child association definition for association '" + associationName + "'");
    } else {
        // that the association is a parent child one
        if (assocDef.isChild() == false) {
            logger.warn("The association named '" + associationName + "' is not a child association");
        } else {
            String displayLabel = (String) getDisplayLabel();
            if (displayLabel == null) {
                // try and get the repository assigned label
                displayLabel = assocDef.getTitle(dd.getDictionaryService());
                // if the label is still null default to the local name of the property
                if (displayLabel == null) {
                    displayLabel = assocDef.getName().getLocalName();
                }
            }
            // generate the label and type specific control
            generateLabel(context, propSheet, displayLabel);
            generateControl(context, propSheet, assocDef);
        }
    }
}
Also used : AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition) DataDictionary(org.alfresco.web.bean.repository.DataDictionary)

Example 4 with AssociationDefinition

use of org.alfresco.service.cmr.dictionary.AssociationDefinition in project acs-community-packaging by Alfresco.

the class TransientNode method initNode.

/**
 * Initialises the node.
 *
 * @param data The properties and associations to initialise the node with
 */
protected void initNode(Map<QName, Serializable> data) {
    if (logger.isDebugEnabled())
        logger.debug("Initialising transient node with data: " + data);
    DictionaryService ddService = this.getServiceRegistry().getDictionaryService();
    // marshall the given properties and associations into the internal maps
    this.associations = new QNameNodeMap(this, this);
    this.childAssociations = new QNameNodeMap(this, this);
    if (data != null) {
        // go through all data items and allocate to the correct internal list
        for (QName item : data.keySet()) {
            PropertyDefinition propDef = ddService.getProperty(item);
            if (propDef != null) {
                this.properties.put(item, data.get(item));
            } else {
                // see if the item is either type of association
                AssociationDefinition assocDef = ddService.getAssociation(item);
                if (assocDef != null) {
                    if (assocDef.isChild()) {
                        Object obj = data.get(item);
                        if (obj instanceof NodeRef) {
                            NodeRef child = (NodeRef) obj;
                            // create a child association reference, add it to a list and add the list
                            // to the list of child associations for this node
                            List<ChildAssociationRef> assocs = new ArrayList<ChildAssociationRef>(1);
                            ChildAssociationRef childRef = new ChildAssociationRef(assocDef.getName(), this.nodeRef, null, child);
                            assocs.add(childRef);
                            this.childAssociations.put(item, assocs);
                        } else if (obj instanceof List) {
                            List targets = (List) obj;
                            List<ChildAssociationRef> assocs = new ArrayList<ChildAssociationRef>(targets.size());
                            for (Object target : targets) {
                                if (target instanceof NodeRef) {
                                    NodeRef currentChild = (NodeRef) target;
                                    ChildAssociationRef childRef = new ChildAssociationRef(assocDef.getName(), this.nodeRef, null, currentChild);
                                    assocs.add(childRef);
                                }
                            }
                            if (assocs.size() > 0) {
                                this.childAssociations.put(item, assocs);
                            }
                        }
                    } else {
                        Object obj = data.get(item);
                        if (obj instanceof NodeRef) {
                            NodeRef target = (NodeRef) obj;
                            // create a association reference, add it to a list and add the list
                            // to the list of associations for this node
                            List<AssociationRef> assocs = new ArrayList<AssociationRef>(1);
                            AssociationRef assocRef = new AssociationRef(null, this.nodeRef, assocDef.getName(), target);
                            assocs.add(assocRef);
                            this.associations.put(item, assocs);
                        } else if (obj instanceof List) {
                            List targets = (List) obj;
                            List<AssociationRef> assocs = new ArrayList<AssociationRef>(targets.size());
                            for (Object target : targets) {
                                if (target instanceof NodeRef) {
                                    NodeRef currentTarget = (NodeRef) target;
                                    AssociationRef assocRef = new AssociationRef(null, this.nodeRef, assocDef.getName(), currentTarget);
                                    assocs.add(assocRef);
                                }
                            }
                            if (assocs.size() > 0) {
                                this.associations.put(item, assocs);
                            }
                        }
                    }
                }
            }
        }
    }
    // show that the maps have been initialised
    this.propsRetrieved = true;
    this.assocsRetrieved = true;
    this.childAssocsRetrieved = true;
    // setup the list of aspects the node would have
    TypeDefinition typeDef = ddService.getType(this.type);
    if (typeDef == null) {
        throw new AlfrescoRuntimeException("Failed to find type definition: " + this.type);
    }
    // get flat list of all aspects for the type
    List<QName> defaultAspects = new ArrayList<QName>(16);
    getMandatoryAspects(typeDef, defaultAspects);
    this.aspects = new HashSet<QName>(defaultAspects);
    // setup remaining variables
    this.path = null;
    this.locked = Boolean.FALSE;
    this.workingCopyOwner = Boolean.FALSE;
}
Also used : QName(org.alfresco.service.namespace.QName) ArrayList(java.util.ArrayList) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) PropertyDefinition(org.alfresco.service.cmr.dictionary.PropertyDefinition) AssociationRef(org.alfresco.service.cmr.repository.AssociationRef) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) TypeDefinition(org.alfresco.service.cmr.dictionary.TypeDefinition) NodeRef(org.alfresco.service.cmr.repository.NodeRef) DictionaryService(org.alfresco.service.cmr.dictionary.DictionaryService) AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List)

Example 5 with AssociationDefinition

use of org.alfresco.service.cmr.dictionary.AssociationDefinition in project acs-community-packaging by Alfresco.

the class BaseComponentGenerator method generateAndAdd.

@SuppressWarnings("unchecked")
public UIComponent generateAndAdd(FacesContext context, UIPropertySheet propertySheet, PropertySheetItem item) {
    UIComponent component = null;
    if (item instanceof UIProperty) {
        // get the property definition
        PropertyDefinition propertyDef = getPropertyDefinition(context, propertySheet.getNode(), item.getName());
        // create the component and add it to the property sheet
        component = createComponent(context, propertySheet, item);
        // setup the component for multi value editing if necessary
        component = setupMultiValuePropertyIfNecessary(context, propertySheet, item, propertyDef, component);
        // setup common aspects of the property i.e. value binding
        setupProperty(context, propertySheet, item, propertyDef, component);
        // add the component now, it needs to be added before the validations
        // are setup as we need access to the component id, which in turn needs
        // to have a parent to get the correct id
        item.getChildren().add(component);
        // setup the component for mandatory validation if necessary
        setupMandatoryPropertyIfNecessary(context, propertySheet, item, propertyDef, component);
        // setup any constraints the property has
        setupConstraints(context, propertySheet, item, propertyDef, component);
        // setup any converter the property needs
        setupConverter(context, propertySheet, item, propertyDef, component);
    } else if (item instanceof UISeparator) {
        // just create the component and add it
        component = createComponent(context, propertySheet, item);
        item.getChildren().add(component);
    } else {
        // get the association definition
        AssociationDefinition assocationDef = this.getAssociationDefinition(context, propertySheet.getNode(), item.getName());
        // create the component and add it to the property sheet
        component = createComponent(context, propertySheet, item);
        // setup common aspects of the association i.e. value binding
        setupAssociation(context, propertySheet, item, assocationDef, component);
        // add the component now, it needs to be added before the validations
        // are setup as we need access to the component id, which needs have a
        // parent to get the correct id
        item.getChildren().add(component);
        // setup the component for mandatory validation if necessary
        setupMandatoryAssociationIfNecessary(context, propertySheet, item, assocationDef, component);
        // setup any converter the association needs
        setupConverter(context, propertySheet, item, assocationDef, component);
    }
    return component;
}
Also used : AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition) UIProperty(org.alfresco.web.ui.repo.component.property.UIProperty) UIComponent(javax.faces.component.UIComponent) UISeparator(org.alfresco.web.ui.repo.component.property.UISeparator) PropertyDefinition(org.alfresco.service.cmr.dictionary.PropertyDefinition)

Aggregations

AssociationDefinition (org.alfresco.service.cmr.dictionary.AssociationDefinition)27 QName (org.alfresco.service.namespace.QName)19 PropertyDefinition (org.alfresco.service.cmr.dictionary.PropertyDefinition)11 HashMap (java.util.HashMap)8 ArrayList (java.util.ArrayList)7 ChildAssociationDefinition (org.alfresco.service.cmr.dictionary.ChildAssociationDefinition)7 Collection (java.util.Collection)5 ClassDefinition (org.alfresco.service.cmr.dictionary.ClassDefinition)5 NodeRef (org.alfresco.service.cmr.repository.NodeRef)5 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)4 TypeDefinition (org.alfresco.service.cmr.dictionary.TypeDefinition)4 List (java.util.List)3 WebScriptException (org.springframework.extensions.webscripts.WebScriptException)3 IOException (java.io.IOException)2 Serializable (java.io.Serializable)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 Entry (java.util.Map.Entry)2 AspectDefinition (org.alfresco.service.cmr.dictionary.AspectDefinition)2 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)2