1   
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  
15  
16  package org.argeo.eclipse.ui.jcr.util;
17  
18  import java.io.InputStream;
19  
20  import javax.jcr.Node;
21  import javax.jcr.Property;
22  import javax.jcr.RepositoryException;
23  import javax.jcr.nodetype.NodeType;
24  
25  import org.apache.commons.io.IOUtils;
26  import org.argeo.eclipse.ui.EclipseUiException;
27  import org.argeo.eclipse.ui.FileProvider;
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  @SuppressWarnings("deprecation")
40  public class JcrFileProvider implements FileProvider {
41  
42  	
43  	private Node refNode;
44  
45  	
46  
47  
48  
49  
50  
51  
52  	public void setReferenceNode(Node refNode) {
53  		
54  		this.refNode = refNode;
55  	}
56  
57  	public byte[] getByteArrayFileFromId(String fileId) {
58  		InputStream fis = null;
59  		byte[] ba = null;
60  		Node child = getFileNodeFromId(fileId);
61  		try {
62  			fis = (InputStream) child.getProperty(Property.JCR_DATA).getBinary().getStream();
63  			ba = IOUtils.toByteArray(fis);
64  
65  		} catch (Exception e) {
66  			throw new EclipseUiException("Stream error while opening file", e);
67  		} finally {
68  			IOUtils.closeQuietly(fis);
69  		}
70  		return ba;
71  	}
72  
73  	public InputStream getInputStreamFromFileId(String fileId) {
74  		try {
75  			InputStream fis = null;
76  
77  			Node child = getFileNodeFromId(fileId);
78  			fis = (InputStream) child.getProperty(Property.JCR_DATA).getBinary().getStream();
79  			return fis;
80  		} catch (RepositoryException re) {
81  			throw new EclipseUiException("Cannot get stream from file node for Id " + fileId, re);
82  		}
83  	}
84  
85  	
86  
87  
88  
89  
90  
91  
92  
93  
94  	private Node getFileNodeFromId(String fileId) {
95  		try {
96  			Node result = refNode.getSession().getNodeByIdentifier(fileId);
97  
98  			
99  			
100 			
101 			
102 			
103 			
104 			
105 			
106 			
107 			
108 			
109 			
110 			
111 			
112 			
113 			
114 			
115 			
116 
117 			
118 			if (result == null)
119 				throw new EclipseUiException("File node not found for ID" + fileId);
120 
121 			Node child = null;
122 
123 			boolean isValid = true;
124 			if (!result.isNodeType(NodeType.NT_FILE))
125 				
126 				
127 				isValid = false;
128 			else {
129 				child = result.getNode(Property.JCR_CONTENT);
130 				if (!(child.isNodeType(NodeType.NT_RESOURCE) || child.hasProperty(Property.JCR_DATA)))
131 					isValid = false;
132 			}
133 
134 			if (!isValid)
135 				throw new EclipseUiException("ERROR: In the current implemented model, '" + NodeType.NT_FILE
136 						+ "' file node must have a child node named jcr:content "
137 						+ "that has a BINARY Property named jcr:data " + "where the actual data is stored");
138 			return child;
139 
140 		} catch (RepositoryException re) {
141 			throw new EclipseUiException("Erreur while getting file node of ID " + fileId, re);
142 		}
143 	}
144 }