Java Code Examples for org.alfresco.service.cmr.repository.NodeRef#toString()

The following examples show how to use org.alfresco.service.cmr.repository.NodeRef#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractBulkFilesystemImporter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected final void validateNodeRefIsWritableSpace(NodeRef target)
{
    if (target == null)
    {
        throw new IllegalArgumentException("target must not be null.");
    }
    
    if (!fileFolderService.exists(target))
    {
        throw new IllegalArgumentException("Target '" + target.toString() + "' doesn't exist.");
    }
    
    if (AccessStatus.DENIED.equals(permissionService.hasPermission(target, PermissionService.ADD_CHILDREN)))
    {
        throw new IllegalArgumentException("Target '" + target.toString() + "' is not writeable.");
    }
    
    if (!fileFolderService.getFileInfo(target).isFolder())
    {
        throw new IllegalArgumentException("Target '" + target.toString() + "' is not a space.");
    }
}
 
Example 2
Source File: RatingDelete.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache)
{
    Map<String, Object> model = new HashMap<String, Object>();

    NodeRef nodeRef = parseRequestForNodeRef(req);
    String ratingSchemeName = parseRequestForScheme(req);
    
    Rating deletedRating = ratingService.removeRatingByCurrentUser(nodeRef, ratingSchemeName);
    if (deletedRating == null)
    {
        // There was no rating in the specified scheme to delete.
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Unable to delete non-existent rating: "
                + ratingSchemeName + " from " + nodeRef.toString());
    }
    
    model.put(NODE_REF, nodeRef.toString());
    model.put(AVERAGE_RATING, ratingService.getAverageRating(nodeRef, ratingSchemeName));
    model.put(RATINGS_TOTAL, ratingService.getTotalRating(nodeRef, ratingSchemeName));
    model.put(RATINGS_COUNT, ratingService.getRatingsCount(nodeRef, ratingSchemeName));
  
    return model;
}
 
Example 3
Source File: ViewXMLExporter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void startNode(NodeRef nodeRef)
{
    try
    {
        AttributesImpl attrs = new AttributesImpl(); 

        Path path = nodeService.getPath(nodeRef);
        if (path.size() > 1)
        {
            // a child name does not exist for root
            Path.ChildAssocElement pathElement = (Path.ChildAssocElement)path.last();
            QName childQName = pathElement.getRef().getQName();
            attrs.addAttribute(NamespaceService.REPOSITORY_VIEW_1_0_URI, CHILDNAME_LOCALNAME, CHILDNAME_QNAME.toPrefixString(), null, toPrefixString(childQName));
        }
        
        QName type = nodeService.getType(nodeRef);
        contentHandler.startElement(type.getNamespaceURI(), type.getLocalName(), toPrefixString(type), attrs);
    }
    catch (SAXException e)
    {
        throw new ExporterException("Failed to process start node event - node ref " + nodeRef.toString(), e);
    }
}
 
Example 4
Source File: ViewXMLExporter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void startACL(NodeRef nodeRef)
{
    try
    {
        AttributesImpl attrs = new AttributesImpl(); 
        boolean inherit = permissionService.getInheritParentPermissions(nodeRef);
        if (!inherit)
        {
            attrs.addAttribute(NamespaceService.REPOSITORY_VIEW_1_0_URI, INHERITPERMISSIONS_LOCALNAME, INHERITPERMISSIONS_QNAME.toPrefixString(), null, "false");
        }
        contentHandler.startElement(ACL_QNAME.getNamespaceURI(), ACL_QNAME.getLocalName(), toPrefixString(ACL_QNAME), attrs);
    }
    catch (SAXException e)
    {
        throw new ExporterException("Failed to process start ACL event - node ref " + nodeRef.toString());
    }
}
 
Example 5
Source File: AbstractRatingWebScript.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected NodeRef parseRequestForNodeRef(WebScriptRequest req)
{
    // get the parameters that represent the NodeRef, we know they are present
    // otherwise this webscript would not have matched
    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    String storeType = templateVars.get("store_type");
    String storeId = templateVars.get("store_id");
    String nodeId = templateVars.get("id");

    // create the NodeRef and ensure it is valid
    StoreRef storeRef = new StoreRef(storeType, storeId);
    NodeRef nodeRef = new NodeRef(storeRef, nodeId);

    if (!this.nodeService.exists(nodeRef))
    {
        throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find node: " + nodeRef.toString());
    }

    return nodeRef;
}
 
Example 6
Source File: ScriptNodeVariableType.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void setValue(Object value, ValueFields valueFields)
{
    String textValue = null;
    if (value != null) 
    {
        if (!(value instanceof ActivitiScriptNode)) 
        {
            throw new ActivitiException("Passed value is not an instance of ActivitiScriptNode, cannot set variable value.");
        }
        NodeRef reference = (((ActivitiScriptNode)value).getNodeRef());
        if (reference != null)
        {
            // Use the string representation of the NodeRef
            textValue = reference.toString();             
        }
    }
    valueFields.setTextValue(textValue);
}
 
Example 7
Source File: ViewXMLExporter.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void endNode(NodeRef nodeRef)
{
    try
    {
        QName type = nodeService.getType(nodeRef);
        contentHandler.endElement(type.getNamespaceURI(), type.getLocalName(), toPrefixString(type));
    }
    catch (SAXException e)
    {
        throw new ExporterException("Failed to process end node event - node ref " + nodeRef.toString(), e);
    }
}
 
Example 8
Source File: RhinoScriptProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.repository.ScriptProcessor#execute(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName, java.util.Map)
 */
public Object execute(NodeRef nodeRef, QName contentProp, Map<String, Object> model)
{
    try
    {
        if (this.services.getNodeService().exists(nodeRef) == false)
        {
            throw new AlfrescoRuntimeException("Script Node does not exist: " + nodeRef);
        }
        
        if (contentProp == null)
        {
            contentProp = ContentModel.PROP_CONTENT;
        }
        ContentReader cr = this.services.getContentService().getReader(nodeRef, contentProp);
        if (cr == null || cr.exists() == false)
        {
            throw new AlfrescoRuntimeException("Script Node content not found: " + nodeRef);
        }
        
        // compile the script based on the node content
        Script script;
        Context cx = Context.enter();
        try
        {
            script = cx.compileString(resolveScriptImports(cr.getContentString()), nodeRef.toString(), 1, null);
        }
        finally
        {
            Context.exit();
        }
        
        return executeScriptImpl(script, model, false, nodeRef.toString());
    }
    catch (Throwable err)
    {
        throw new ScriptException("Failed to execute script '" + nodeRef.toString() + "': " + err.getMessage(), err);
    }
}
 
Example 9
Source File: ViewXMLExporter.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void endAspect(NodeRef nodeRef, QName aspect)
{
    try
    {
        contentHandler.endElement(aspect.getNamespaceURI(), aspect.getLocalName(), toPrefixString(aspect));
    }
    catch (SAXException e)
    {
        throw new ExporterException("Failed to process end aspect event - node ref " + nodeRef.toString() + "; aspect " + toPrefixString(aspect), e);
    }
}
 
Example 10
Source File: CascadingIT.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * After updating the test data hierarchy (folders and file), the test checks that the cascade tracker properly
 * reflects the changes in the index.
 */
@Test 
public void solrTracking_folderUpdate_shouldReIndexFolderAndChildren() throws Exception
{
    // Update the folder
    Transaction txn = getTransaction(0, 1);

    folderMetaData.getProperties().put(ContentModel.PROP_CASCADE_TX, new StringPropertyValue(Long.toString(txn.getId())));
    folderMetaData.getProperties().put(ContentModel.PROP_NAME, new StringPropertyValue("folder2"));
    folderNode.setTxnId(txn.getId());
    folderMetaData.setTxnId(txn.getId());

    // Change the ancestor on the file just to see if it's been updated
    NodeRef nodeRef = new NodeRef(new StoreRef("workspace", "SpacesStore"), createGUID());
    childFolderMetaData.setAncestors(ancestors(nodeRef));
    fileMetaData.setAncestors(ancestors(nodeRef));

    upsertData(txn, singletonList(folderNode), singletonList(folderMetaData));

    // Check that the ancestor has been changed and indexed
    TermQuery query = new TermQuery(new Term(QueryConstants.FIELD_ANCESTOR, nodeRef.toString()));
    waitForDocCount(query, 2, MAX_WAIT_TIME);

    // Child folder and grandchild document must be updated
    // This is the same query as before but instead of using a Lucene query, it uses the /afts endpoint (request handler)
    ModifiableSolrParams params =
            new ModifiableSolrParams()
                    .add(CommonParams.Q, QueryConstants.FIELD_ANCESTOR + ":\"" + nodeRef.toString() + "\"")
                    .add(CommonParams.QT, "/afts")
                    .add(CommonParams.START, "0")
                    .add(CommonParams.ROWS, "6")
                    .add(CommonParams.SORT, "id asc")
                    .add(CommonParams.FQ, "{!afts}AUTHORITY_FILTER_FROM_JSON");

    SolrServletRequest req =
            areq(params,
        "{\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [ \"mike\"], \"tenants\": [ \"\" ]}");

    assertQ(req, "*[count(//doc)=2]", "//result/doc[1]/long[@name='DBID'][.='" + childFolderNode.getId() + "']", "//result/doc[2]/long[@name='DBID'][.='" + fileNode.getId() + "']");
}
 
Example 11
Source File: TransformerDebug.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String getFileNameOrNodeRef(NodeRef sourceNodeRef, boolean firstLevel, long sourceSize, boolean getName)
{
    String result = getName ? null : "";
    if (sourceNodeRef != null)
    {
        try
        {
            result = getName
                    ? (String)nodeService.getProperty(sourceNodeRef, ContentModel.PROP_NAME)
                    : sourceNodeRef.toString()+" ";
        }
        catch (RuntimeException e)
        {
            // ignore (normally InvalidNodeRefException) but we should ignore other RuntimeExceptions too
        }
    }
    if (result == null)
    {
        if (!firstLevel)
        {
            result = getName ? "<<TemporaryFile>>" : "";
        }
        else if (sourceSize < 0)
        {
            // fileName = "<<AnyFile>>"; commented out as it does not add to debug readability
        }
    }
    return result;
}
 
Example 12
Source File: MultilingualContentServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Does the work of making the translation a simple node again.  No parent-child relationships
 * are modified and the pivot-container logic is not done here.
 * 
 * @param translationNodeRef                a translation
 */
private void unmakeTranslationSimple(NodeRef translationNodeRef)
{      
    try
    {
        this.policyBehaviourFilter.disableBehaviour(ContentModel.TYPE_MULTILINGUAL_CONTAINER);
        if (nodeService.hasAspect(translationNodeRef, ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION))
        {
            nodeService.removeAspect(translationNodeRef, ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION);
            nodeService.addAspect(translationNodeRef, ContentModel.ASPECT_TEMPORARY, null);
        }
        else
        {
            if (nodeService.hasAspect(translationNodeRef, ContentModel.ASPECT_MULTILINGUAL_DOCUMENT))
            {
                nodeService.removeAspect(translationNodeRef, ContentModel.ASPECT_MULTILINGUAL_DOCUMENT);
            }
        }
        List<ChildAssociationRef> assocRefs = nodeService.getParentAssocs(
                translationNodeRef,
                ContentModel.ASSOC_MULTILINGUAL_CHILD, 
                RegexQNamePattern.MATCH_ALL);
        if (assocRefs.size() != 1)
        {
            throw new AlfrescoRuntimeException(
                    "Unable to remove ASSOC_MULTILINGUAL_CHILD on : " + translationNodeRef.toString());
        }
    }
    finally
    {
        this.policyBehaviourFilter.enableBehaviour(ContentModel.TYPE_MULTILINGUAL_CONTAINER);
    }
}
 
Example 13
Source File: DocumentLinkServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public List<Long> getNodeLinksIds(NodeRef nodeRef)
{
    /* Validate input */
    PropertyCheck.mandatory(this, "nodeRef", nodeRef);

    /* Get all links of the given nodeRef */
    PagingRequest pagingRequest = new PagingRequest(0, 100000);
    List<Long> nodeLinks = new ArrayList<Long>();

    Pair<Long, QName> nameQName = qnameDAO.getQName(ContentModel.PROP_LINK_DESTINATION);
    if (nameQName != null)
    {
        // Execute the canned query if there are links in the database
        GetDoclinkNodesCannedQueryParams parameterBean = new GetDoclinkNodesCannedQueryParams(nodeRef.toString(), 
                                                                                              nameQName.getFirst(), 
                                                                                              pagingRequest.getMaxItems());
        CannedQueryParameters params = new CannedQueryParameters(parameterBean, 
                                                                 null, 
                                                                 null, 
                                                                 pagingRequest.getRequestTotalCountMax(), 
                                                                 pagingRequest.getQueryExecutionId());
        CannedQuery<Long> query = new GetDoclinkNodesCannedQuery(cannedQueryDAO, 
                                                                 params);
        CannedQueryResults<Long> results = query.execute();

        for (Long nodeId : results.getPage())
        {
            nodeLinks.add(nodeId);
        }
    }

    return nodeLinks;
}
 
Example 14
Source File: CMISNodeInfoImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected void analyseNodeRef(boolean checkExists)
{
    objectId = null;
    currentNodeId = nodeRef.toString();
    currentObjectId = null;
    versionLabel = null;
    hasPWC = false;

    // check for existence
    if (checkExists && (!connector.getNodeService().exists(nodeRef)))
    {
        objecVariant = CMISObjectVariant.NOT_EXISTING;
        return;
    }
    
    if (connector.filter(nodeRef))
    {
        objecVariant = CMISObjectVariant.NOT_EXISTING;
        return;
    }
    
    if (isFolder())
    {
        objecVariant = CMISObjectVariant.FOLDER;
        objectId = connector.constructObjectId(nodeRef, null);
        currentObjectId = objectId;
        return;
    }
    else if (isItem())
    {
        objecVariant = CMISObjectVariant.ITEM;
        objectId = connector.constructObjectId(nodeRef, null);
        currentObjectId = objectId;
        return;
    }
    else if (getType() == null)
    {
        objecVariant = CMISObjectVariant.NOT_A_CMIS_OBJECT;
        return;
    }
    
    // check PWC
    if (isNodeWorkingCopy())
    {
        NodeRef checkedOut = connector.getCheckOutCheckInService().getCheckedOut(nodeRef);
        if (checkedOut == null)
        {
            // catch a rare audit case
            checkedOut = nodeRef;
        }

        objecVariant = CMISObjectVariant.PWC;

        objectId = connector.constructObjectId(checkedOut, CMISConnector.PWC_VERSION_LABEL);

        versionLabel = CMISConnector.PWC_VERSION_LABEL;
        currentObjectId = connector.createObjectId(checkedOut);
        currentNodeId = checkedOut.toString();
        hasPWC = true;
        return;
    }

    // check version
    if (isNodeAVersion(nodeRef))
    {
        analyseVersionNode();
    }
    else
    {
        analyseCurrentVersion();
    }
}
 
Example 15
Source File: EmailHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Gets the email template path or the given fallback template path.
 *
 * @param clientName           optional client app name (used only for logging)
 * @param emailTemplatePath    the email template xpath or class path
 * @param fallbackTemplatePath the fallback template
 * @return <ul>
 * <li>If {@code emailTemplatePath} is empty the fallback template is returned.</li>
 * <li>if the given {@code emailTemplatePath} is an xpath (i.e. starts with app:company_home),
 * then an xpath search will be performed to find the {@code NodeRef}. If no nodeRef
 * is found, the fallback template is returned. </li>
 * <li>If {@code emailTemplatePath} is a nodeRef and the node does not exist, the fallback
 * template is returned, otherwise a string representation of the NodeRef is returned.</li>
 * <li>if {@code emailTemplatePath} is a class path which results in a template being found,
 * then the {@code emailTemplatePath} is returned; otherwise, the fallback template is returned.</li>
 * </ul>
 */
public String getEmailTemplate(String clientName, String emailTemplatePath, String fallbackTemplatePath)
{
    if (StringUtils.isEmpty(emailTemplatePath))
    {
        if (LOGGER.isDebugEnabled())
        {
            LOGGER.debug("No email template path is set for client [" + clientName + "]. The fallback template will be used: "
                        + fallbackTemplatePath);
        }
        return fallbackTemplatePath;
    }

    // Make sure that the path doesn't start with '/'
    if (emailTemplatePath.startsWith("/"))
    {
        emailTemplatePath = emailTemplatePath.substring(1);
    }

    if (emailTemplatePath.startsWith(companyHomeChildName))
    {
        NodeRef nodeRef = getLocalizedEmailTemplateNodeRef(emailTemplatePath);
        if (nodeRef == null)
        {
            LOGGER.warn("Couldn't find email template with the XPath [" + emailTemplatePath + "] for client [" + clientName
                        + "]. The fallback template will be used: " + fallbackTemplatePath);

            return fallbackTemplatePath;
        }
        return nodeRef.toString();
    }
    else if (NodeRef.isNodeRef(emailTemplatePath))
    {
        // Just check whether the nodeRef exists or not
        NodeRef ref = new NodeRef(emailTemplatePath);
        if (!nodeService.exists(ref))
        {
            LOGGER.warn("Couldn't find email template with the NodeRef [" + ref + "] for client [" + clientName
                        + "]. The fallback template will be used: " + fallbackTemplatePath);

            return fallbackTemplatePath;
        }

        // No need to return the nodeRef, as this will be handled later by the 'ClassPathRepoTemplateLoader' class
        return emailTemplatePath;
    }
    else
    {
        try
        {
            // We just use the template loader to check whether the given
            // template path is valid and the file is found
            Object template = templateLoader.findTemplateSource(emailTemplatePath);
            if (template != null)
            {
                if (LOGGER.isDebugEnabled())
                {
                    LOGGER.debug("Using email template with class path [" + emailTemplatePath + "] for client: " + clientName);
                }
                return emailTemplatePath;
            }
            else
            {
                LOGGER.warn("Couldn't find email template with class path [" + emailTemplatePath + "] for client [" + clientName
                            + "]. The fallback template will be used: " + fallbackTemplatePath);
            }
        }
        catch (IOException ex)
        {
            LOGGER.error("Error occurred while finding the email template with the class path [" + emailTemplatePath + "] for client ["
                        + clientName + "]. The fallback template will be used: " + fallbackTemplatePath, ex);

        }
        return fallbackTemplatePath;
    }
}
 
Example 16
Source File: StoreRedirectorProxyFactoryTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void throwException(NodeRef ref1)
{
    throw new IllegalArgumentException(ref1.toString());
}
 
Example 17
Source File: ImapServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public String getDefaultEmailBodyTemplate(EmailBodyFormat type)
{
    if (defaultBodyTemplates == null)
    {
        defaultBodyTemplates = new HashMap<EmailBodyFormat, String>(4);
        
        for (EmailBodyFormat onetype : EmailBodyFormat.values())
        {
            String result = onetype.getClasspathTemplatePath();
            try
            {
                // This query uses cm:name to find the template node(s).
                // For the case where the templates are renamed, it would be better to use a QName path-based query.
                

                final StringBuilder templateName = new StringBuilder(DICTIONARY_TEMPLATE_PREFIX).append("_").append(onetype.getTypeSubtype()).append("_").append(onetype.getWebApp()).append(".ftl");

                final String repositoryTemplatePath = getRepositoryTemplatePath();
                int indexOfStoreDelim = repositoryTemplatePath.indexOf(StoreRef.URI_FILLER);
                if (indexOfStoreDelim == -1)
                {
                    throw new IllegalArgumentException("Bad path format, " + StoreRef.URI_FILLER + " not found");
                }
                indexOfStoreDelim += StoreRef.URI_FILLER.length();
                int indexOfPathDelim = repositoryTemplatePath.indexOf("/", indexOfStoreDelim);
                if (indexOfPathDelim == -1)
                {
                    throw new IllegalArgumentException("Bad path format, '/' not found");
                }
                final String storePath = repositoryTemplatePath.substring(0, indexOfPathDelim);
                final String rootPathInStore = repositoryTemplatePath.substring(indexOfPathDelim);
                final String query = rootPathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + templateName;
                if (logger.isDebugEnabled())
                {
                    logger.debug("[getDefaultEmailBodyTemplate] Query: " + query);
                }
                StoreRef storeRef = new StoreRef(storePath);
                
                NodeRef rootNode = nodeService.getRootNode(storeRef);
                
                List<NodeRef> templates = searchService.selectNodes(rootNode, query, null, namespaceService, true);
                if (templates == null || templates.size() == 0)
                {
                    if(logger.isDebugEnabled())
                    {
                        logger.debug("template not found:" + templateName);
                    }
                    throw new AlfrescoRuntimeException(String.format("[getDefaultEmailBodyTemplate] IMAP message template '%1$s' does not exist in the path '%2$s'.", templateName, repositoryTemplatePath));
                }
                final NodeRef defaultLocaleTemplate = templates.get(0);
  
                NodeRef localisedSibling = serviceRegistry.getFileFolderService().getLocalizedSibling(defaultLocaleTemplate);
                result = localisedSibling.toString();
            }
            // We are catching all exceptions. E.g. search service can possibly throw an exceptions on malformed queries.
            catch (Exception e)
            {
                logger.error("ImapServiceImpl [getDefaultEmailBodyTemplate]", e);
            }
            defaultBodyTemplates.put(onetype, result);
        }
    }
    return defaultBodyTemplates.get(type);
}
 
Example 18
Source File: VirtualPreferenceServiceExtensionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testSetFavoritesPreferencesForFolders() throws Exception
{
    NodeRef physicalFolder = createFolder(testRootFolder.getNodeRef(),
                                          "FOLDER").getChildRef();
    NodeRef virtualFolder = createVirtualizedFolder(testRootFolder.getNodeRef(),
                                                    VIRTUAL_FOLDER_2_NAME,
                                                    TEST_TEMPLATE_6_JSON_SYS_PATH);
    NodeRef node1 = nodeService.getChildByName(virtualFolder,
                                               ContentModel.ASSOC_CONTAINS,
                                               "Node1");
    assertNotNull(node1);

    prepareMocks("FOLDER", physicalFolder);
    try
    {
    NodeRef physicalFolderInVirtualContext = nodeService.getChildByName(node1,
                                                                        ContentModel.ASSOC_CONTAINS,
                                                                        "FOLDER");
    assertNotNull(physicalFolderInVirtualContext);

    // set preference to one folder from one virtual folder and check if
    // the actual nodeRef is present in
    // org.alfresco.share.folders.favourites preference
    Map<String, Serializable> preferences = new TreeMap<String, Serializable>();
    String key = EXT_FOLDERS_FAVOURITES + physicalFolderInVirtualContext.toString() + CREATED_AT;
    preferences.put(key,
                    "CREATED");
    preferences.put(FOLDERS_FAVOURITES_KEY,
                    physicalFolderInVirtualContext.toString());
    preferenceService.setPreferences("admin",
                                     preferences);

    String preference = (String) preferenceService.getPreference("admin",
                                                                 FOLDERS_FAVOURITES_KEY);
    assertFalse(preference.contains(physicalFolderInVirtualContext.toString()));
    assertTrue(preference.contains(physicalFolder.toString()));
    assertNull((String) preferenceService.getPreference("admin",
                                                        EXT_FOLDERS_FAVOURITES
                                                                    + physicalFolderInVirtualContext.toString()
                                                                    + CREATED_AT));
    assertNotNull((String) preferenceService.getPreference("admin",
                                                           EXT_FOLDERS_FAVOURITES + physicalFolder.toString()
                                                                       + CREATED_AT));

    // remove favorite for a folder from one virtual folder and check that
    // the physical folder is not favorite anymore
    // and that the ext keys are removed
    preferences = new TreeMap<String, Serializable>();
    key = EXT_FOLDERS_FAVOURITES + physicalFolderInVirtualContext.toString() + CREATED_AT;
    preferences.put(key,
                    null);
    preferences.put(FOLDERS_FAVOURITES_KEY,
                    physicalFolder.toString());
    preferenceService.setPreferences("admin",
                                     preferences);

    preference = (String) preferenceService.getPreference("admin",
                                                          FOLDERS_FAVOURITES_KEY);
    assertTrue(preference.isEmpty());

    assertNull((String) preferenceService.getPreference("admin",
                                                        EXT_FOLDERS_FAVOURITES
                                                                    + physicalFolderInVirtualContext.toString()
                                                                    + CREATED_AT));
    assertNull((String) preferenceService.getPreference("admin",
                                                        EXT_FOLDERS_FAVOURITES + physicalFolder.toString()
                                                                    + CREATED_AT));
    }
    finally
    {
        resetMocks();
    }
}
 
Example 19
Source File: VirtualPreferenceServiceExtensionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testSetFavoritesPreferencesForDocuments() throws Exception
{
    NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef,
                                               ContentModel.ASSOC_CONTAINS,
                                               "Node2");
    HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
    properties.put(ContentModel.PROP_NAME,
                   "testfile.txt");
    QName assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI,
                                         QName.createValidLocalName("testfile.txt"));

    nodeService.createNode(node2,
                           ContentModel.ASSOC_CONTAINS,
                           assocQName,
                           ContentModel.TYPE_CONTENT,
                           properties);
    NodeRef node2_1 = nodeService.getChildByName(node2,
                                                 ContentModel.ASSOC_CONTAINS,
                                                 "Node2_1");
    nodeService.createNode(node2_1,
                           ContentModel.ASSOC_CONTAINS,
                           assocQName,
                           ContentModel.TYPE_CONTENT,
                           properties);

    NodeRef testfile1 = nodeService.getChildByName(node2_1,
                                                   ContentModel.ASSOC_CONTAINS,
                                                   "testfile-1.txt");
    NodeRef physicalTestfile1 = nodeService.getChildByName(virtualFolder1NodeRef,
                                                           ContentModel.ASSOC_CONTAINS,
                                                           "testfile-1.txt");

    // set preference to one document from one virtual folder and check if
    // the actual nodeRef is present in
    // org.alfresco.share.documents.favourites preference
    Map<String, Serializable> preferences = new TreeMap<String, Serializable>();
    String key = EXT_DOCUMENTS_FAVOURITES + testfile1.toString() + CREATED_AT;
    preferences.put(key,
                    "CREATED");
    preferences.put(DOCUMENTS_FAVOURITES_KEY,
                    testfile1.toString());
    preferenceService.setPreferences("admin",
                                     preferences);

    String preference = (String) preferenceService.getPreference("admin",
                                                                 DOCUMENTS_FAVOURITES_KEY);
    assertFalse(preference.contains(testfile1.toString()));
    assertTrue(preference.contains(physicalTestfile1.toString()));
    assertNull((String) preferenceService.getPreference("admin",
                                                        EXT_DOCUMENTS_FAVOURITES + testfile1.toString()
                                                                    + CREATED_AT));
    assertNotNull((String) preferenceService.getPreference("admin",
                                                           EXT_DOCUMENTS_FAVOURITES + physicalTestfile1.toString()
                                                                       + CREATED_AT));

    // remove favorite for a document from one virtual folder and check that
    // the physical document is not favorite anymore
    // and that the ext keys are removed
    preferences = new TreeMap<String, Serializable>();
    key = EXT_DOCUMENTS_FAVOURITES + testfile1.toString() + CREATED_AT;
    preferences.put(key,
                    null);
    preferences.put(DOCUMENTS_FAVOURITES_KEY,
                    physicalTestfile1.toString());
    preferenceService.setPreferences("admin",
                                     preferences);

    preference = (String) preferenceService.getPreference("admin",
                                                          DOCUMENTS_FAVOURITES_KEY);
    assertTrue(preference.isEmpty());

    assertNull((String) preferenceService.getPreference("admin",
                                                        EXT_DOCUMENTS_FAVOURITES + testfile1.toString()
                                                                    + CREATED_AT));
    assertNull((String) preferenceService.getPreference("admin",
                                                        EXT_DOCUMENTS_FAVOURITES + physicalTestfile1.toString()
                                                                    + CREATED_AT));
}
 
Example 20
Source File: FormServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testContentForms() throws Exception
{
    // create FormData object 
    String name = "created-" + this.documentName;
    String title = "This is the title property";
    String mimetype = "text/html";
    String content = "This is the content.";
    FormData data = createContentFormData(name, title, mimetype, content);
    
    // supply the destination
    data.addFieldData(AbstractFormProcessor.DESTINATION, this.folder.toString());
    
    // persist the data
    NodeRef newNode = (NodeRef)this.formService.saveForm(new Item(TYPE_FORM_ITEM_KIND, "cm:content"), data);
    
    // check the node was created correctly
    checkContentDetails(newNode, name, title, mimetype, content);
    
    // get the form for the new content and check the form data
    List<String> fields = new ArrayList<String>(2);
    fields.add("cm:name");
    fields.add("cm:content");
    Form form = this.formService.getForm(new Item(NODE_FORM_ITEM_KIND, newNode.toString()), fields);
    assertNotNull(form);
    assertEquals(name, form.getFormData().getFieldData("prop_cm_name").getValue().toString());
    String contentUrl = form.getFormData().getFieldData("prop_cm_content").getValue().toString();
    assertTrue("Expected content url to contain mimetype", (contentUrl.indexOf("mimetype=") != -1));
    assertTrue("Expected content url to contain encoding", (contentUrl.indexOf("encoding=") != -1));
    assertTrue("Expected content url to contain size", (contentUrl.indexOf("size=") != -1));
    
    // create another node without supplying the mimetype and check the details
    String name2 = "created2-" + this.documentName;
    data = createContentFormData(name2, title, null, content);
    data.addFieldData(AbstractFormProcessor.DESTINATION, this.folder.toString());
    NodeRef newNode2 = (NodeRef)this.formService.saveForm(new Item(TYPE_FORM_ITEM_KIND, "cm:content"), data);
    checkContentDetails(newNode2, name2, title, "text/plain", content);
    
    // update the content and the mimetype
    Item item = new Item(NODE_FORM_ITEM_KIND, newNode.toString());
    String updatedContent = "This is the updated content";
    String updatedMimetype = "text/plain";
    data = createContentFormData(name, title, updatedMimetype, updatedContent);
    this.formService.saveForm(item, data);
    
    // check the node was updated correctly
    checkContentDetails(newNode, name, title, updatedMimetype, updatedContent);
    
    // update the content and mimetype again but ensure the content is updated last
    // to check the mimetype change is not lost
    updatedContent = "<element>The content is now XML</content>";
    updatedMimetype = "text/xml";
    data = createContentFormData(name, title, updatedMimetype, updatedContent);
    // remove and add content to ensure it's last
    data.removeFieldData("prop_cm_content");
    data.addFieldData("prop_cm_content", updatedContent);
    this.formService.saveForm(item, data);
    
    // check the details
    checkContentDetails(newNode, name, title, updatedMimetype, updatedContent);
    
    // update just the content
    updatedContent = "<element attribute=\"true\">The content is still XML</content>";
    data = createContentFormData(null, null, null, updatedContent);
    this.formService.saveForm(item, data);
    checkContentDetails(newNode, name, title, updatedMimetype, updatedContent);
}