]> git.argeo.org Git - lgpl/argeo-commons.git/blob - tabular/JcrTabularWriter.java
Prepare next development cycle
[lgpl/argeo-commons.git] / tabular / JcrTabularWriter.java
1 package org.argeo.jcr.tabular;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.ByteArrayOutputStream;
5 import java.io.InputStream;
6 import java.util.List;
7
8 import javax.jcr.Binary;
9 import javax.jcr.Node;
10 import javax.jcr.Property;
11 import javax.jcr.PropertyType;
12 import javax.jcr.RepositoryException;
13
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;
21
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;
28
29 /** Creates a table node */
30 public JcrTabularWriter(Node tableNode, List<TabularColumn> columns,
31 String contentNodeType) {
32 try {
33 this.columns = columns;
34 for (TabularColumn column : columns) {
35 String normalized = JcrUtils.replaceInvalidChars(column
36 .getName());
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()));
43 else
44 columnNode.setProperty(Property.JCR_REQUIRED_TYPE,
45 PropertyType.TYPENAME_STRING);
46 }
47 contentNode = tableNode.addNode(Property.JCR_CONTENT,
48 contentNodeType);
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);
54 }
55 } catch (RepositoryException e) {
56 throw new ArgeoException("Cannot create table node " + tableNode, e);
57 }
58 }
59
60 public void appendRow(Object[] row) {
61 csvWriter.writeLine(row);
62 }
63
64 public void close() {
65 Binary binary = null;
66 InputStream in = null;
67 try {
68 // TODO parallelize with pipes and writing from another thread
69 in = new ByteArrayInputStream(out.toByteArray());
70 binary = contentNode.getSession().getValueFactory()
71 .createBinary(in);
72 contentNode.setProperty(Property.JCR_DATA, binary);
73 } catch (RepositoryException e) {
74 throw new ArgeoException("Cannot store data in " + contentNode, e);
75 } finally {
76 IOUtils.closeQuietly(in);
77 JcrUtils.closeQuietly(binary);
78 }
79 }
80 }