1 package org
.argeo
.jcr
.tabular
;
3 import java
.io
.ByteArrayInputStream
;
4 import java
.io
.ByteArrayOutputStream
;
5 import java
.io
.InputStream
;
8 import javax
.jcr
.Binary
;
10 import javax
.jcr
.Property
;
11 import javax
.jcr
.PropertyType
;
12 import javax
.jcr
.RepositoryException
;
14 import org
.apache
.commons
.io
.IOUtils
;
15 import org
.argeo
.ArgeoException
;
16 import org
.argeo
.jcr
.ArgeoTypes
;
17 import org
.argeo
.jcr
.JcrUtils
;
18 import org
.argeo
.util
.CsvWriter
;
19 import org
.argeo
.util
.tabular
.TabularColumn
;
20 import org
.argeo
.util
.tabular
.TabularWriter
;
22 /** Write / reference tabular content in a JCR repository. */
23 public class JcrTabularWriter
implements TabularWriter
{
24 private Node contentNode
;
25 private ByteArrayOutputStream out
;
26 private CsvWriter csvWriter
;
27 private final List
<TabularColumn
> columns
;
29 /** Creates a table node */
30 public JcrTabularWriter(Node tableNode
, List
<TabularColumn
> columns
,
31 String contentNodeType
) {
33 this.columns
= columns
;
34 for (TabularColumn column
: columns
) {
35 String normalized
= JcrUtils
.replaceInvalidChars(column
37 Node columnNode
= tableNode
.addNode(normalized
,
38 ArgeoTypes
.ARGEO_COLUMN
);
39 columnNode
.setProperty(Property
.JCR_TITLE
, column
.getName());
40 if (column
.getType() != null)
41 columnNode
.setProperty(Property
.JCR_REQUIRED_TYPE
,
42 PropertyType
.nameFromValue(column
.getType()));
44 columnNode
.setProperty(Property
.JCR_REQUIRED_TYPE
,
45 PropertyType
.TYPENAME_STRING
);
47 contentNode
= tableNode
.addNode(Property
.JCR_CONTENT
,
49 if (contentNodeType
.equals(ArgeoTypes
.ARGEO_CSV
)) {
50 contentNode
.setProperty(Property
.JCR_MIMETYPE
, "text/csv");
51 contentNode
.setProperty(Property
.JCR_ENCODING
, "UTF-8");
52 out
= new ByteArrayOutputStream();
53 csvWriter
= new CsvWriter(out
);
55 } catch (RepositoryException e
) {
56 throw new ArgeoException("Cannot create table node " + tableNode
, e
);
60 public void appendRow(Object
[] row
) {
61 csvWriter
.writeLine(row
);
66 InputStream in
= null;
68 // TODO parallelize with pipes and writing from another thread
69 in
= new ByteArrayInputStream(out
.toByteArray());
70 binary
= contentNode
.getSession().getValueFactory()
72 contentNode
.setProperty(Property
.JCR_DATA
, binary
);
73 } catch (RepositoryException e
) {
74 throw new ArgeoException("Cannot store data in " + contentNode
, e
);
76 IOUtils
.closeQuietly(in
);
77 JcrUtils
.closeQuietly(binary
);