2013-04-09 88 views
0

我正在使用此代碼在我的Modeshape JCR存儲庫中寫入文件。具有自定義屬性的JCR新節點類型

Session session = //some session 
Node folderNode = session.getRootNode(); 

//init some calendar and a file from fileSystem 
Calendar lastModified = Calendar.getInstance(); 
File myFile = new File("c://temp//pic.jpg");  

//create nt:file node 
Node fileNode = folderNode.addNode(myFile.getName(), "nt:file"); 

// create the mandatory child node - jcr:content 
Node resNode = fileNode.addNode("jcr:content", "nt:resource"); 
resNode.setProperty("jcr:mimeType", ""); 
resNode.setProperty("jcr:encoding", ""); 
resNode.setProperty("jcr:lastModified", lastModified); 

// add some binary data      
InputStream stream = new BufferedInputStream(new FileInputStream(myFile)); 
Binary binary = session.getValueFactory().createBinary(stream); 
lastModified.setTimeInMillis(myFile.lastModified()); 
resNode.setProperty("jcr:data", binary); 

我想添加一些自定義屬性這樣

resNode.setProperty("myCustomProperty", "some value", PropertyType.STRING) 

但正如所有文檔中描述的那樣,我得到一個ConstraintViolationException因爲試圖自定義屬性添加到本地JCR節點類型。

我試圖生成一個新的節點類型從本地nt:resource heritates,然後用我的自定義屬性擴展它:

Session session = //some session 
Workspace workspace = session.getWorkspace(); 
NodeTypeManager nodeTypeManager = workspace.getNodeTypeManager(); 
NodeTypeTemplate ndt = nodeTypeManager.createNodeTypeTemplate(); 

//i define my new custom propertie under the new nodeType 
PropertyDefinitionTemplate createPropertyDefinitionTemplate = nodeTypeManager.createPropertyDefinitionTemplate(); 
createPropertyDefinitionTemplate.setName("myCustomProperty"); 
createPropertyDefinitionTemplate.setRequiredType(PropertyType.STRING); 
ndt.getPropertyDefinitionTemplates().add(createPropertyDefinitionTemplate); 

String myNodeTypeName = "newCustimNodeType"; 
ndt.setName(myNodeTypeName); 
//heritates from nt:resource 
String[] str = {"nt:resource"}; 
ndt.setDeclaredSuperTypeNames(str); 
nodeTypeManager.registerNodeType(ndt, true); 
session.save(); 

這樣做,我們避免ConstraintViolationException但現在我們得到了一個RepositoryException因爲JCR不能在文件系統中保存我的新類型的節點與消息:

「有效的主要類型是NT:文件,NT:文件夾中,NT:資源和DNA:種源」

所以我想我不帥客從superClass nt:resource一口氣吟誦新的newNode。

這是將自定義屬性添加到節點的正確方法嗎? 這是定義從jcr原生一個新的nodeType的正確方法嗎?

回答

2

您不需要創建自定義節點類型。相反,您可以使用JCR mixins爲內置的「nt:file」和「nt:folder」節點類型添加更多屬性。看到這個解釋如何做到這一點的blog post

至於定義您自己的自定義「nt:file」和「nt:folder」子類型的問題,聽起來像您正在使用較舊版本的ModeShape(2.x而不是3.x),並且您正在使用文件系統連接器。後者旨在通過ModeShape和JCR API公開文件系統上的現有文件,因此它受限於其工作節點的主要類型。使用博客文章中提到的mixins將解決此限制。或者,考慮其他沒有此限制的連接器。

+0

由於我們不使用CND文件,有創建和註冊這些新的mixin的方式編程方式? – Marcos 2013-04-10 08:52:21

+0

是的。 JCR API的NodeTypeManager提供了一種通過可變「模板」創建節點類型定義的方法。這些模板是定義,可以使用管理器進行註冊。 – 2013-04-10 12:21:46