2013-06-05 38 views
3

使用吊索資源接口我試圖訪問保存爲二進制屬性到我的JCR節點的數據。目前我正在通過以下方式進行操作,這會返回空值。從JCR repo訪問資源數據

Resource dataResource = resourceResolver.getResource("/testNode/A/test.txt"); 
ValueMap properties = dataResource.adaptTo(ValueMap.class);   

String expected = properties.get("jcr:data").toString(); // null 
InputStream content = (InputStream) actualProp.get("jcr:data"); // null 

任何人都可以讓我知道缺少什麼,或者什麼是讀取作爲二進制數據存在的jcr:data屬性的最佳方法。 dataResource是一個nt:非結構化的之一。

它顯示輸出: - [email protected]4c8085

+0

你爲什麼不只是調試ValueMap,看看裏面有什麼? –

+0

對不起,你能讓我問你一個問題嗎?你有沒有試過我的代碼?結果如何?非常感謝! –

回答

1

如果我沒記錯的話,你的路徑應該更像:

Resource dataResource = resourceResolver.getResource("/testNode/A/test.txt/jcr:content"); 

我個人認爲適應資源的JCR節點(javax.jcr.Node),並使用JCR API從那裏(#getProperty()#getBinary()),但那可能是我的老同修說的話。

+0

不,實際上test.txt本身就是一個**:非結構化節點**,其所有元數據都被設置爲其屬性。文件內容也以二進制數據形式存在,我想閱讀它。希望它現在有一定意義。 – Raja

+0

啊,對不起,不知道爲什麼認爲它是* nt:file *。您是否嘗試過使用JCR API? –

+0

不,我正在使用sling的資源API用於此目的。 – Raja

1

下面的代碼爲我工作:

import java.io.BufferedInputStream; 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 

import javax.jcr.Node; 
import javax.jcr.RepositoryException; 
import javax.jcr.Session; 

//skip here 

Session session = (Session) resourceResolver.adaptTo(Session.class); 
Node root = session.getRootNode(); 
Node jcrContent = root.getNode("testNode/A/test.txt/jcr:content"); 

InputStream is = jcrContent.getProperty("jcr:data").getBinary().getStream(); 

BufferedInputStream bis = new BufferedInputStream(is); 
ByteArrayOutputStream buf = new ByteArrayOutputStream(); 
int result = bis.read(); 
while (result != -1) { 
    byte b = (byte) result; 
    buf.write(b); 
    result = bis.read(); 
} 

System.out.println("plain text: " + buf.toString()); 

您也可以在another post

+2

您應該保留對二進制對象的引用,以便在完成後關閉它。 – ehsavoie

+0

@ehsavoie你在說'InputStream is'嗎? –

+0

謝謝,它工作得很好,但只是在將資源適配到JCR節點(javax.jcr.Node)並使用JCR API之後,實際上我並不打算這樣做。 – Raja

8

你提到你使用吊索資源API,而不是JCR API找到更多的信息。只要資源是一個NT

Resource dataResource = resourceResolver.getResource("/testNode/A/test.txt/jcr:content"); 
InputStream is = dataResource.adaptTo(InputStream.class); 

:文件或NT:資源,在JCR的內容:數據屬性應返回一個可以直接從資源,像這樣調整資源的InputStream的InputStream。

從那裏你可以從InputStream中讀到Tuan在他的回答中提出的建議。

你可以看到從下面的單元測試此功能的示例: http://svn.apache.org/repos/asf/sling/whiteboard/fmeschbe/resource/jcr.resource/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResourceTest.java

+0

我嘗試了沒有jcr:內容,我能夠獲取資源。 。 – Jianhong