-
Notifications
You must be signed in to change notification settings - Fork 29
/
JcrContext.java
444 lines (408 loc) · 16.9 KB
/
JcrContext.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*
* Copyright (C) 2000 - 2022 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "https://www.silverpeas.org/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.silverpeas.core.contribution.attachment.repository;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.tika.mime.MimeTypes;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.silverpeas.core.contribution.attachment.AttachmentServiceProvider;
import org.silverpeas.core.contribution.attachment.model.SimpleAttachment;
import org.silverpeas.core.contribution.attachment.model.SimpleDocument;
import org.silverpeas.core.contribution.attachment.model.SimpleDocumentPK;
import org.silverpeas.core.index.indexing.IndexFileManager;
import org.silverpeas.core.jcr.JCRSession;
import org.silverpeas.core.util.Charsets;
import org.silverpeas.core.util.ServiceProvider;
import org.silverpeas.core.util.StringUtil;
import org.silverpeas.core.util.file.FileRepositoryManager;
import javax.jcr.*;
import javax.jcr.nodetype.NodeType;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
/**
* This class handle a JCR test.<br>
* The repository is created before and deleted after each test.<br>
* The registered physical files are also deleted.
* @author Yohann Chastagnier
*/
public class JcrContext implements TestRule {
@Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
base.evaluate();
} finally {
clearJcrRepository();
clearFileSystem();
}
}
};
}
private void clearJcrRepository() throws RepositoryException {
try (JCRSession session = JCRSession.openSystemSession()) {
System.out.println("CLEAR JCR REPOSITORY CONTENT...");
NodeIterator i = session.getRootNode().getNodes();
while(i.hasNext()) {
Node node = i.nextNode();
if (node.getPrimaryNodeType().isNodeType(NodeType.NT_FOLDER)) {
System.out.println("REMOVE NODE " + node.getName());
node.remove();
}
}
session.save();
}
}
private void clearFileSystem() {
File file = new File(FileRepositoryManager.getAbsolutePath(""));
FileUtils.deleteQuietly(file);
File index = new File(IndexFileManager.getIndexUpLoadPath());
FileUtils.deleteQuietly(index);
}
/*
TOOLS
*/
private final Date testStartDate = new Date();
private final DocumentConverter converter = new DocumentConverter();
private DocumentRepository getDocumentRepository() {
return ServiceProvider.getService(DocumentRepository.class);
}
public Date getTestStartDate() {
return testStartDate;
}
/**
* Common method to assert a document existence.
* @param uuId the uuId to retrieve the document.
*/
@SuppressWarnings("unused")
public void assertDocumentExists(String uuId) throws Exception {
SimpleDocument document = getDocumentById(uuId);
assertThat(document, notNullValue());
}
/**
* Common method to assert a document existence.
* @param uuId the uuId to retrieve the document.
*/
@SuppressWarnings("unused")
public void assertDocumentDoesNotExist(String uuId) throws Exception {
SimpleDocument document = getDocumentById(uuId);
assertThat(document, nullValue());
}
/**
* Common method to assert the content for a language of a document.
* @param uuId the uuId to retrieve the document.
* @param language the language in which the content must be verified.
* @param expectedContent if null, the content for the language does not exist.
* @return the document loaded for assertions.
*/
public SimpleDocument assertContent(String uuId, String language, String expectedContent)
throws Exception {
SimpleDocument document = getDocumentById(uuId, language);
assertThat(document, notNullValue());
final File physicalContent;
if (document.getAttachment() != null) {
physicalContent = new File(FileRepositoryManager.getAbsolutePath(document.getInstanceId()),
document.getNodeName() + "/" +
document.getMajorVersion() + "_" + document.getMinorVersion() + "/" + language + "/" +
document.getFilename()
);
} else {
physicalContent = new File(FileRepositoryManager.getAbsolutePath(document.getInstanceId()),
document.getNodeName() + "/" +
document.getMajorVersion() + "_" + document.getMinorVersion() + "/" + language
);
}
if (expectedContent == null) {
assertThat(document.getAttachment(), nullValue());
assertThat(physicalContent.exists(), is(false));
} else {
assertThat(document.getAttachment(), notNullValue());
assertThat(document.getLanguage(), is(language));
assertThat(physicalContent.exists(), is(true));
ByteArrayOutputStream content = new ByteArrayOutputStream();
AttachmentServiceProvider.getAttachmentService()
.getBinaryContent(content, document.getPk(), language);
assertThat(content.toString(Charsets.UTF_8),
is(expectedContent));
}
return document;
}
public SimpleDocument getDocumentById(String uuId, String language) throws Exception {
try (JCRSession session = JCRSession.openSystemSession()) {
SimpleDocument document =
getDocumentRepository().findDocumentById(session, new SimpleDocumentPK(uuId), language);
if (StringUtil.isDefined(language) && document != null &&
!language.equals(document.getLanguage())) {
document.setAttachment(null);
}
return document;
}
}
protected SimpleDocument getDocumentById(String uuId) throws Exception {
return getDocumentById(uuId, null);
}
@SuppressWarnings("SameParameterValue")
protected SimpleDocument defaultDocument(String instanceId, String foreignId,
SimpleAttachment file) {
SimpleDocument document = new SimpleDocument();
document.setPK(new SimpleDocumentPK("-1", instanceId));
document.setForeignId(foreignId);
document.setAttachment(file);
return document;
}
public SimpleDocument defaultDocument(String instanceId, String foreignId) {
return defaultDocument(instanceId, foreignId, null);
}
public SimpleAttachment defaultENContent() {
return SimpleAttachment.builder("en")
.setFilename("test.pdf")
.setTitle("My test document")
.setDescription("This is a test document")
.setSize("This is a test document".getBytes(Charsets.UTF_8).length)
.setContentType(MimeTypes.OCTET_STREAM)
.setCreationData("0", randomDate())
.setFormId("18")
.build();
}
public SimpleAttachment defaultFRContent() {
return SimpleAttachment.builder("fr")
.setFilename("test.odp")
.setTitle("Mon document de test")
.setDescription("Ceci est un document de test")
.setSize("Ceci est un document de test".getBytes(Charsets.UTF_8).length)
.setContentType(MimeTypes.PLAIN_TEXT)
.setCreationData("10", randomDate())
.setFormId("5")
.build();
}
@SuppressWarnings("unused")
public SimpleAttachment defaultDEContent() {
return SimpleAttachment.builder("de")
.setFilename("test.docx")
.setTitle("Mein Test-Dokument")
.setDescription("Dies ist ein Testdokument")
.setSize("Dies ist ein Testdokument".getBytes(Charsets.UTF_8).length)
.setContentType(MimeTypes.XML)
.setCreationData("10", randomDate())
.setFormId("2")
.build();
}
protected Date randomDate() {
long offset = Timestamp.valueOf("2014-01-01 00:00:00").getTime();
long end = Timestamp.valueOf("2014-04-30 00:00:00").getTime();
long diff = end - offset + 1;
return new Timestamp(offset + (long) (Math.random() * diff));
}
public SimpleDocument createAttachmentForTest(SimpleDocument document,
SimpleAttachment attachment, String content) throws Exception {
document.setAttachment(attachment);
return createDocumentIntoJcr(document, content);
}
public SimpleDocument updateAttachmentForTest(SimpleDocument document, String language,
String content) throws Exception {
SimpleDocument documentToUpdate = new SimpleDocument(document);
documentToUpdate.setLanguage(language);
return updateDocumentIntoJcr(documentToUpdate, content);
}
@SuppressWarnings("unused")
protected SimpleDocument updateAttachmentForTest(SimpleDocument document) throws Exception {
SimpleDocument documentToUpdate = new SimpleDocument(document);
return updateDocumentIntoJcr(documentToUpdate, null);
}
private SimpleDocument createDocumentIntoJcr(SimpleDocument document, String content)
throws Exception {
try (JCRSession session = JCRSession.openSystemSession()) {
SimpleDocumentPK createdPk = getDocumentRepository().createDocument(session, document);
session.save();
long contentSizeWritten = getDocumentRepository().storeContent(document,
new ByteArrayInputStream(content.getBytes(Charsets.UTF_8)));
assertThat(contentSizeWritten, is((long) content.length()));
SimpleDocument createdDocument =
getDocumentRepository().findDocumentById(session, createdPk, document.getLanguage());
assertThat(createdDocument, notNullValue());
assertThat(createdDocument.getOrder(), is(document.getOrder()));
assertThat(createdDocument.getLanguage(), is(document.getLanguage()));
return createdDocument;
}
}
private SimpleDocument updateDocumentIntoJcr(SimpleDocument document, String content)
throws Exception {
assertThat(document.getPk(), notNullValue());
assertThat(document.getId(), not(is(emptyString())));
assertThat(document.getInstanceId(), not(emptyString()));
assertThat(document.getOldSilverpeasId(), greaterThan(0L));
try (JCRSession session = JCRSession.openSystemSession()) {
Node documentNode = session.getNodeByIdentifier(document.getPk().getId());
converter.fillNode(document, documentNode);
session.save();
if (content != null) {
long contentSizeWritten = getDocumentRepository().storeContent(document,
new ByteArrayInputStream(content.getBytes(Charsets.UTF_8)));
assertThat(contentSizeWritten, is((long) content.length()));
}
SimpleDocument updatedDocument = getDocumentRepository()
.findDocumentById(session, document.getPk(), document.getLanguage());
assertThat(updatedDocument, notNullValue());
assertThat(updatedDocument.getLanguage(), is(document.getLanguage()));
return updatedDocument;
}
}
/**
* Gets the single child node of a node.
* If no node exists or several node exists, a failed assertion is performed.
* @param node the parent node.
* @return the single child node.
* @throws Exception if an error occurs
*/
public Node getSingleChildNode(Node node) throws Exception {
assertThat("getTheOnlyOneChildNode - no child node exists", node.hasNodes(), is(true));
NodeIterator singleChildNodeIt = node.getNodes();
Node singleChildNode = singleChildNodeIt.nextNode();
assertThat("getTheOnlyOneChildNode - several child nodes exists", singleChildNodeIt.hasNext(),
is(false));
return singleChildNode;
}
/**
* Gets the {@link Binary} content of a JCR node property as a {@link String}.
* @param property the JCR property that must contains a binary content.
* @return the binary content as a {@link String}.
* @throws Exception if an error occurs
*/
public String getBinaryContentAsString(Property property) throws Exception {
return new String(getBinaryContent(property), Charsets.UTF_8);
}
/**
* Gets the {@link Binary} content of a JCR node property.
* @param property the JCR property that must contains a binary content.
* @return the binary content.
* @throws Exception if an error occurs
*/
protected byte[] getBinaryContent(Property property) throws Exception {
ByteArrayOutputStream byteContent = new ByteArrayOutputStream();
Binary content = property.getBinary();
InputStream in = content.getStream();
try {
IOUtils.copy(in, byteContent);
} finally {
IOUtils.closeQuietly(in);
content.dispose();
}
return byteContent.toByteArray();
}
/**
* Sets the {@link Binary} content of a JCR node property.
* @param property the JCR property that must contains a binary content.
* @throws Exception if an error occurs
*/
public void setBinaryContent(Property property, byte[] content) throws Exception {
InputStream in = new ByteArrayInputStream(content);
try {
Binary attachmentBinary = property.getSession().getValueFactory().createBinary(in);
property.setValue(attachmentBinary);
} finally {
IOUtils.closeQuietly(in);
}
}
/**
* Gets from the specified parent node the child node that satisfies the given jcrPath.
* @param parentNode the parent node from which the JCR path is guessed.
* @param jcrPath the JCR path to find.
* @return the JCR node instance if it exists, null otherwise.
*/
public Node getRelativeNode(Node parentNode, String jcrPath) {
try {
return parentNode.getNode(jcrPath);
} catch (RepositoryException re) {
return null;
}
}
/**
* Lists all entire paths that exists from the specified node (recursive treatment).
* @param parentNode the parent node.
* @return the list of entire paths, null if the specified node does not exist anymore.
* @throws RepositoryException if an error occurs
*/
public List<String> listPathsFrom(Node parentNode) throws RepositoryException {
return listPathsFrom(parentNode, -1);
}
/**
* Lists all entire paths that exists from the specified node (recursive treatment).
* @param parentNode the parent node.
* @param deep the maximum number sub-nodes to reach.
* @return the list of entire paths, null if the specified node does not exist anymore.
* @throws RepositoryException if an error occurs
*/
@SuppressWarnings("SameParameterValue")
protected List<String> listPathsFrom(Node parentNode, int deep) throws RepositoryException {
return listPathsFrom(parentNode, deep, 0);
}
/**
* Lists all entire paths that exists from the specified node (recursive treatment).
* @param parentNode the parent node.
* @param maximumDeep the maximum number of sub-nodes to reach.
* @param currentDeep the current sub-node position from the initial parent.
* @return the list of entire paths, null if the specified node does not exist anymore.
* @throws RepositoryException if an error occurs
*/
private List<String> listPathsFrom(Node parentNode, int maximumDeep, int currentDeep)
throws RepositoryException {
try {
parentNode.getPath();
} catch (RepositoryException re) {
// Node does not exist anymore.
return null;
}
if ((maximumDeep >= 0 && currentDeep >= maximumDeep)) {
return Collections.emptyList();
}
NodeIterator nodeIt = parentNode.getNodes();
List<String> paths = new ArrayList<>();
Set<String> uuidNodePerformed = new HashSet<>();
boolean willMaximumDeepBeReached = (maximumDeep >= 0 && (currentDeep + 1) >= maximumDeep);
while (nodeIt.hasNext()) {
Node node = nodeIt.nextNode();
if (node.hasNodes()) {
if (!willMaximumDeepBeReached) {
paths.addAll(Objects.requireNonNull(listPathsFrom(node, maximumDeep, currentDeep + 1)));
} else if (!uuidNodePerformed.contains(node.getIdentifier())) {
uuidNodePerformed.add(node.getIdentifier());
paths.add(node.getPath());
}
} else if (!uuidNodePerformed.contains(node.getIdentifier())) {
uuidNodePerformed.add(node.getIdentifier());
paths.add(node.getPath());
}
}
return paths;
}
}