下面列出了org.json.simple.JSONAware#org.alfresco.service.cmr.repository.NodeRef 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testSetAndGet()
{
NodeRef ephemeralNodeRef = new NodeRef("workspace://SpacesStore/12345");
LockState ephemeralLock = LockState.createLock(
ephemeralNodeRef, LockType.NODE_LOCK, "owner", null, Lifetime.EPHEMERAL, null);
NodeRef persistentNodeRef = new NodeRef("workspace://SpacesStore/5838743");
LockState persistentLock = LockState.createLock(
persistentNodeRef, LockType.NODE_LOCK, "owner", null, Lifetime.PERSISTENT, null);
lockStore.set(ephemeralNodeRef, ephemeralLock);
lockStore.set(persistentNodeRef, persistentLock);
LockState newLockState = lockStore.get(ephemeralNodeRef);
assertEquals(ephemeralLock, newLockState);
newLockState = lockStore.get(persistentNodeRef);
assertEquals(persistentLock, newLockState);
}
/**
* * This method gets all nodes from the archive which were originally
* contained within the specified StoreRef.
*
* @param storeRef mandatory store ref
* @param paging mandatory paging
* @param filter optional filter
*/
protected PagingResults<NodeRef> getArchivedNodesFrom(StoreRef storeRef, ScriptPagingDetails paging, String filter)
{
NodeService nodeService = serviceRegistry.getNodeService();
NodeRef archiveStoreRootNodeRef = nodeService.getStoreArchiveNode(storeRef);
// Create canned query
ArchivedNodesCannedQueryBuilder queryBuilder = new ArchivedNodesCannedQueryBuilder.Builder(
archiveStoreRootNodeRef, paging).filter(filter)
.sortOrderAscending(false).build();
// Query the DB
PagingResults<NodeRef> result = nodeArchiveService.listArchivedNodes(queryBuilder);
return result;
}
@Test
public void testContains()
{
NodeRef nodeRef1 = new NodeRef("workspace://SpacesStore/12345");
LockState lock1 = LockState.createLock(nodeRef1, LockType.NODE_LOCK, "owner", null, Lifetime.EPHEMERAL, null);
NodeRef nodeRef2 = new NodeRef("workspace://SpacesStore/5838743");
LockState lock2 = LockState.createLock(nodeRef2, LockType.NODE_LOCK, "owner", null, Lifetime.PERSISTENT, null);
NodeRef nodeRef3 = new NodeRef("workspace://SpacesStore/65752323");
lockStore.set(nodeRef1, lock1);
lockStore.set(nodeRef2, lock2);
assertNotNull(lockStore.get(nodeRef1));
assertNotNull(lockStore.get(nodeRef2));
assertNull(lockStore.get(nodeRef3));
}
public NodeRef getPerson(final String user)
{
NodeRef person = null;
String domain = tenantService.getPrimaryDomain(user); // get primary tenant
if (domain != null)
{
person = TenantUtil.runAsTenant(new TenantRunAsWork<NodeRef>()
{
public NodeRef doWork() throws Exception
{
return personService.getPerson(user);
}
}, domain);
}
else
{
person = personService.getPerson(user);
}
return person;
}
private String getReportBaseName(NodeRef reportParentFolder)
{
String prefixName = null;
List<FileInfo> list = fileFolderService.list(reportParentFolder);
for (FileInfo file : list)
{
if (file.getNodeRef().toString().contains(transferId))
{
// found the existing "destination" remote file
Serializable name = nodeService.getProperty(file.getNodeRef(), ContentModel.PROP_NAME);
if (name instanceof String)
{
String fileName = (String) name;
if (fileName.lastIndexOf(".") > 0)
{
prefixName = fileName.substring(0, fileName.lastIndexOf("."));
}
}
break;
}
}
return prefixName;
}
@SuppressWarnings("unchecked")
private boolean alreadyCreated(NodeRef nodeRef)
{
Set<NodeRef> createdNodes = (Set<NodeRef>)AlfrescoTransactionSupport.getResource(KEY_CREATED_NODES);
if (createdNodes != null)
{
for (NodeRef createdNodeRef : createdNodes)
{
if (createdNodeRef.equals(nodeRef))
{
if (logger.isDebugEnabled()) logger.debug("alreadyCreated: nodeRef="+nodeRef);
return true;
}
}
}
return false;
}
@Override
public String getPathFromRepo(final ChildAssociationRef assocRef)
{
return doAsSystem(new RunAsWork<String>()
{
@Override
public String doWork() throws Exception
{
NodeRef ref = assocRef.getParentRef();
String name = ((String) nodeService.getProperty(ref, ContentModel.PROP_NAME)).toLowerCase();
ChildAssociationRef parent = nodeService.getPrimaryParent(ref);
QName qname = parent.getQName();
if (qname.equals(QName.createQName(NamespaceService.APP_MODEL_1_0_URI, "company_home")))
{
return "repository";
}
else
{
return getPathFromRepo(parent) + "/" + name;
}
}
});
}
/**
* REPO-828 (MNT-16401)
* @throws Exception
*/
public void testDeleteCommentPostActivity() throws Exception
{
permissionService.setPermission(sitePage, USER_TWO, PermissionService.ALL_PERMISSIONS, true);
postLookup.execute();
feedGenerator.execute();
int activityNumStart = activityService.getSiteFeedEntries(SITE_SHORT_NAME).size();
Response response = addComment(sitePage, USER_TWO, 200);
postLookup.execute();
feedGenerator.execute();
int activityNumNext = activityService.getSiteFeedEntries(SITE_SHORT_NAME).size();
assertEquals("The activity feeds were not generated after adding a comment", activityNumStart + 1, activityNumNext);
JSONObject jsonResponse = parseResponseJSON(response);
String nodeRefComment = getOrNull(jsonResponse, JSON_KEY_NODEREF);
NodeRef commentNodeRef = new NodeRef(nodeRefComment);
deleteComment(commentNodeRef, sitePage, USER_TWO, 200);
activityNumStart = activityNumNext;
postLookup.execute();
feedGenerator.execute();
activityNumNext = activityService.getSiteFeedEntries(SITE_SHORT_NAME).size();
assertEquals("The activity feeds were not generated after deleting a comment", activityNumStart + 1, activityNumNext);
}
/**
* Test versioning many nodes in one go
*/
@Test
public void testVersioningManyNodes()
{
NodeRef versionableNode = createNewVersionableNode();
// Snap shot data
String expectedVersionLabel = peekNextVersionLabel(versionableNode, versionProperties);
// Snap-shot the node created date-time
long beforeVersionTime = ((Date)nodeService.getProperty(versionableNode, ContentModel.PROP_CREATED)).getTime();
// Version the list of nodes created
Collection<Version> versions = this.versionService.createVersion(
this.versionableNodes.values(),
this.versionProperties);
// Check the returned versions are correct
CheckVersionCollection(expectedVersionLabel, beforeVersionTime, versions);
// TODO check the version histories
}
@Override
public synchronized Collection<NodeRef> getNextWork()
{
// Record the user folder node IDs
final List<NodeRef> folderNodes = new ArrayList<NodeRef>(SHARED_SURF_CONFIG_BATCH_MAX_QUERY_RANGE);
// Keep querying until we have enough results to give back
int minResults = SHARED_SURF_CONFIG_BATCH_MAX_QUERY_RANGE / 2;
while (currentId <= maxId && folderNodes.size() < minResults)
{
List<NodeRef> nodeIds = patchDAO.getChildrenOfTheSharedSurfConfigFolder(currentId, currentId + SHARED_SURF_CONFIG_BATCH_MAX_QUERY_RANGE);
folderNodes.addAll(nodeIds);
// Increment the minimum ID
currentId += SHARED_SURF_CONFIG_BATCH_MAX_QUERY_RANGE;
}
// Preload the nodes for quicker access
nodeDAO.cacheNodes(folderNodes);
// Done
return folderNodes;
}
public int loadFile(NodeRef container, File file) throws FileImporterException
{
try
{
Counter counter = new Counter();
create(counter, container, file, null, false, null);
return counter.getCount();
}
catch (Throwable e)
{
throw new FileImporterException("Failed to load file: \n" +
" container: " + container + "\n" +
" file: " + file,
e);
}
}
/**
* Round-trip of export then import will result in the imported content having the same categories
* assigned to it as for the exported content -- provided the source and destination stores are the same.
*/
@SuppressWarnings("unchecked")
@Category(RedundantTests.class)
@Test
public void testRoundTripKeepsCategoriesWhenWithinSameStore() throws Exception
{
// Use a store ref that has the bootstrapped categories
StoreRef storeRef = StoreRef.STORE_REF_WORKSPACE_SPACESSTORE;
NodeRef rootNode = nodeService.getRootNode(storeRef);
ChildAssociationRef contentChildAssocRef = createContentWithCategories(storeRef, rootNode);
// Export/import
File acpFile = exportContent(contentChildAssocRef.getParentRef());
FileInfo importFolderFileInfo = importContent(acpFile, rootNode);
// Check categories
NodeRef importedFileNode = fileFolderService.searchSimple(importFolderFileInfo.getNodeRef(), "test.txt");
assertNotNull("Couldn't find imported file: test.txt", importedFileNode);
assertTrue(nodeService.hasAspect(importedFileNode, ContentModel.ASPECT_GEN_CLASSIFIABLE));
List<NodeRef> importedFileCategories = (List<NodeRef>)
nodeService.getProperty(importedFileNode, ContentModel.PROP_CATEGORIES);
assertCategoriesEqual(importedFileCategories,
"Regions",
"Software Document Classification");
}
/**
* On add aspect policy behaviour
*
* @param nodeRef NodeRef
* @param aspectTypeQName QName
*/
public void onAddAspect(NodeRef nodeRef, QName aspectTypeQName)
{
this.ruleService.disableRules(nodeRef);
try
{
this.nodeService.createNode(
nodeRef,
ActionModel.ASSOC_ACTION_FOLDER,
ActionModel.ASSOC_ACTION_FOLDER,
ContentModel.TYPE_SYSTEM_FOLDER);
}
finally
{
this.ruleService.enableRules(nodeRef);
}
}
@SuppressWarnings("unused")
@Test
public void testCheckHidden() throws Exception
{
String nodeName = GUID.generate();
interceptor.setEnabled(false);
try
{
// Create some nodes that should be hidden but aren't
NodeRef node = fileFolderService.create(topNodeRef, nodeName, ContentModel.TYPE_FOLDER).getNodeRef();
NodeRef node11 = fileFolderService.create(node, nodeName + ".11", ContentModel.TYPE_FOLDER).getNodeRef();
NodeRef node12 = fileFolderService.create(node, ".12", ContentModel.TYPE_CONTENT).getNodeRef();
NodeRef node21 = fileFolderService.create(node11, nodeName + ".21", ContentModel.TYPE_FOLDER).getNodeRef();
NodeRef node22 = fileFolderService.create(node11, nodeName + ".22", ContentModel.TYPE_CONTENT).getNodeRef();
NodeRef node31 = fileFolderService.create(node21, ".31", ContentModel.TYPE_FOLDER).getNodeRef();
NodeRef node41 = fileFolderService.create(node31, nodeName + ".41", ContentModel.TYPE_CONTENT).getNodeRef();
txn.commit();
}
finally
{
interceptor.setEnabled(true);
}
}
public int getSequenceNumber(NodeRef nodeRef)
{
validateNode(nodeRef);
Serializable sequenceNumber = nodeService.getProperty(nodeRef, DownloadModel.PROP_SEQUENCE_NUMBER);
return ((Integer)sequenceNumber).intValue();
}
@Override
public void closeFile(SrvSession sess, TreeConnection tree,
NetworkFile param) throws IOException
{
if(logger.isDebugEnabled())
{
logger.debug("closeFile:" + param.getFullName());
}
ContentContext tctx = (ContentContext) tree.getContext();
NodeRef rootNode = tctx.getRootNode();
DriverState driverState = getDriverState(sess);
String[] paths = FileName.splitPath(param.getFullName());
String folder = paths[0];
String file = paths[1];
try
{
EvaluatorContext ctx = getEvaluatorContext(driverState, folder);
Operation o = new CloseFileOperation(file, param, rootNode, param.getFullName(), param.hasDeleteOnClose(), param.isForce());
Command c = ruleEvaluator.evaluate(ctx, o);
commandExecutor.execute(sess, tree, c);
releaseEvaluatorContextIfEmpty(driverState, ctx, folder);
}
catch(org.alfresco.repo.security.permissions.AccessDeniedException ade)
{
throw new AccessDeniedException("Unable to close file " + param.getFullName(), ade);
}
}
/**
* @see org.alfresco.repo.action.RuntimeActionService#directActionExecution(org.alfresco.service.cmr.action.Action,
* org.alfresco.service.cmr.repository.NodeRef)
*/
public void directActionExecution(Action action, NodeRef actionedUponNodeRef)
{
// Debug output
if (logger.isDebugEnabled())
{
logger.debug("The action is being executed as the user: "
+ this.authenticationContext.getCurrentUserName());
}
// Get the action executer and execute
ActionExecuter executer = (ActionExecuter) this.applicationContext.getBean(action.getActionDefinitionName());
executer.execute(action, actionedUponNodeRef);
}
/**
* Creates a new version node, setting the properties both calculated and specified.
*
* @param versionableNodeRef the reference to the node being versioned
* @param versionHistoryRef version history node reference
* @param standardVersionProperties version properties
* @param versionProperties version properties
* @param nodeDetails PolicyScope
* @return the version node reference
*/
private NodeRef createNewVersion(
NodeRef versionableNodeRef,
NodeRef versionHistoryRef,
Map<QName, Serializable> standardVersionProperties,
Map<String, Serializable> versionProperties,
PolicyScope nodeDetails)
{
// Create the new version
ChildAssociationRef childAssocRef = this.dbNodeService.createNode(
versionHistoryRef,
CHILD_QNAME_VERSIONS,
CHILD_QNAME_VERSIONS,
TYPE_QNAME_VERSION,
standardVersionProperties);
NodeRef versionNodeRef = childAssocRef.getChildRef();
// Store the meta data
storeVersionMetaData(versionNodeRef, versionProperties);
// Freeze the various parts of the node
freezeProperties(versionNodeRef, nodeDetails.getProperties());
freezeChildAssociations(versionNodeRef, nodeDetails.getChildAssociations());
freezeAssociations(versionNodeRef, nodeDetails.getAssociations());
freezeAspects(nodeDetails, versionNodeRef, nodeDetails.getAspects());
// Return the created node reference
return versionNodeRef;
}
protected AspectsIntegrityEvent(
NodeService nodeService,
DictionaryService dictionaryService,
NodeRef nodeRef)
{
super(nodeService, dictionaryService, nodeRef, null, null);
}
/**
* Overrides AbstractCommentsWebScript to add comment
*/
@Override
protected Map<String, Object> executeImpl(NodeRef nodeRef, WebScriptRequest req, Status status, Cache cache)
{
// get json object from request
JSONObject json = parseJSON(req);
/* MNT-10231, MNT-9771 fix */
this.behaviourFilter.disableBehaviour(nodeRef, ContentModel.ASPECT_AUDITABLE);
try
{
// add a comment
NodeRef commentNodeRef = addComment(nodeRef, json);
// generate response model for a comment node
Map<String, Object> model = generateModel(nodeRef, commentNodeRef);
// post an activity item
postActivity(json, req, nodeRef, COMMENT_CREATED_ACTIVITY);
return model;
}
finally
{
this.behaviourFilter.enableBehaviour(nodeRef, ContentModel.ASPECT_AUDITABLE);
}
}
public DBResultSet(SearchParameters searchParameters, List<Long> dbids, NodeDAO nodeDao, NodeService nodeService, TenantService tenantService, int maximumResultsFromUnlimitedQuery)
{
this.nodeDao = nodeDao;
this.dbids = dbids;
this.nodeService = nodeService;
this.tenantService = tenantService;
this.prefetch = new BitSet(dbids.size());
nodeRefs= new NodeRef[(dbids.size())];
final LimitBy limitBy;
int maxResults = -1;
if (searchParameters.getMaxItems() >= 0)
{
maxResults = searchParameters.getMaxItems();
limitBy = LimitBy.FINAL_SIZE;
}
else if(searchParameters.getLimitBy() == LimitBy.FINAL_SIZE && searchParameters.getLimit() >= 0)
{
maxResults = searchParameters.getLimit();
limitBy = LimitBy.FINAL_SIZE;
}
else
{
maxResults = searchParameters.getMaxPermissionChecks();
if (maxResults < 0)
{
maxResults = maximumResultsFromUnlimitedQuery;
}
limitBy = LimitBy.NUMBER_OF_PERMISSION_EVALUATIONS;
}
this.resultSetMetaData = new SimpleResultSetMetaData(
maxResults > 0 && dbids.size() < maxResults ? LimitBy.UNLIMITED : limitBy,
PermissionEvaluationMode.EAGER, searchParameters);
}
protected void deleteTestUsers() throws Exception
{
for (NodeRef testUser : testUsers)
{
try
{
nodeService.deleteNode(testUser);
}
catch (InvalidNodeRefException e)
{
//Just ignore it.
}
}
testUsers.clear();
}
private String toPath(NodeRef root, NodeRef leaf)
{
StringBuilder sb = new StringBuilder("");
List<String> path = getRelativePath(root, leaf);
if (path != null)
{
if (path.isEmpty())
{
sb.append('.');
}
else
{
for (String folder : path)
{
if (sb.length() > 0)
{
sb.append('/');
}
sb.append(folder);
}
}
}
else
{
sb.append("<notUnderSameRoot>");
}
return sb.toString();
}
/**
* Handles the work of converting aspects to JSON.
*
* @param nodeRef NodeRef
* @param useShortQNames boolean
* @return JSONArray
*/
@SuppressWarnings("unchecked")
protected JSONArray apsectsToJSON(NodeRef nodeRef, boolean useShortQNames)
{
JSONArray aspectsJSON = new JSONArray();
Set<QName> aspects = this.nodeService.getAspects(nodeRef);
for (QName aspect : aspects)
{
aspectsJSON.add(nameToString(aspect, useShortQNames));
}
return aspectsJSON;
}
protected void streamContentImpl(WebScriptRequest req, WebScriptResponse res,
ContentReader reader, NodeRef nodeRef, QName propertyQName,
boolean attach, Date modified, String eTag, String attachFileName)
throws IOException
{
delegate.setAttachment(req, res, attach, attachFileName);
// establish mimetype
String mimetype = reader.getMimetype();
String extensionPath = req.getExtensionPath();
if (mimetype == null || mimetype.length() == 0)
{
mimetype = MimetypeMap.MIMETYPE_BINARY;
int extIndex = extensionPath.lastIndexOf('.');
if (extIndex != -1)
{
String ext = extensionPath.substring(extIndex + 1);
mimetype = mimetypeService.getMimetype(ext);
}
}
// set mimetype for the content and the character encoding + length for the stream
res.setContentType(mimetype);
res.setContentEncoding(reader.getEncoding());
res.setHeader("Content-Length", Long.toString(reader.getSize()));
// set caching
Cache cache = new Cache();
cache.setNeverCache(false);
cache.setMustRevalidate(true);
cache.setMaxAge(0L);
cache.setLastModified(modified);
cache.setETag(eTag);
res.setCache(cache);
}
private boolean includeAspects(NodeRef nodeRef, Set<QName> inclusiveAspects, Set<QName> exclusiveAspects)
{
if (inclusiveAspects == null && exclusiveAspects == null)
{
return true;
}
Set<QName> nodeAspects = nodeService.getAspects(nodeRef);
if (inclusiveAspects != null)
{
Set<QName> includedIntersect = new HashSet<QName>(nodeAspects);
includedIntersect.retainAll(inclusiveAspects);
if (includedIntersect.isEmpty())
{
return false;
}
}
if (exclusiveAspects != null)
{
Set<QName> excludedIntersect = new HashSet<QName>(nodeAspects);
excludedIntersect.retainAll(exclusiveAspects);
if (excludedIntersect.isEmpty() == false)
{
return false;
}
}
return true;
}
protected void assertResolvablePath(String path, String toName)
{
NodeRefPathExpression pathExpression = nodeRefPathExpressionFactory.createInstance();
pathExpression.setPath(path);
NodeRef nodeRef = pathExpression.resolve();
assertNotNull(nodeRef);
Serializable theName = nodeService.getProperty(nodeRef,
ContentModel.PROP_NAME);
assertEquals("Unexpected name for path " + pathExpression,
toName,
theName);
}
@Override
public TopicInfo getTopic(NodeRef parentNodeRef, String topicName)
{
NodeRef topic = nodeService.getChildByName(parentNodeRef, ContentModel.ASSOC_CONTAINS, topicName);
if (topic != null)
{
return buildTopic(topic, parentNodeRef, topicName);
}
return null;
}
@Override
public NodeRef beforeBodyWrite(NodeRef body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
ServerHttpResponse response) {
response.getHeaders().add("TEST_ADVICE_APPLIED", "true");
return new NodeRef("a://a/b");
}
public NodeRef validateTag(StoreRef storeRef, String tagId)
{
NodeRef tagNodeRef = nodes.validateNode(storeRef, tagId);
if(tagNodeRef == null)
{
throw new EntityNotFoundException(tagId);
}
return tagNodeRef;
}