]> git.argeo.org Git - lgpl/argeo-commons.git/blob - JcrTabularWriter.java
0727b784e617507dd8e2dc171d1b671371fab91a
[lgpl/argeo-commons.git] / 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
28 /** Creates a table node */
29 public JcrTabularWriter(Node tableNode, List<TabularColumn> columns,
30 String contentNodeType) {
31 try {
32 for (TabularColumn column : columns) {
33 String normalized = JcrUtils.replaceInvalidChars(column
34 .getName());
35 Node columnNode = tableNode.addNode(normalized,
36 ArgeoTypes.ARGEO_COLUMN);
37 columnNode.setProperty(Property.JCR_TITLE, column.getName());
38 if (column.getType() != null)
39 columnNode.setProperty(Property.JCR_REQUIRED_TYPE,
40 PropertyType.nameFromValue(column.getType()));
41 else
42 columnNode.setProperty(Property.JCR_REQUIRED_TYPE,
43 PropertyType.TYPENAME_STRING);
44 }
45 contentNode = tableNode.addNode(Property.JCR_CONTENT,
46 contentNodeType);
47 if (contentNodeType.equals(ArgeoTypes.ARGEO_CSV)) {
48 contentNode.setProperty(Property.JCR_MIMETYPE, "text/csv");
49 contentNode.setProperty(Property.JCR_ENCODING, "UTF-8");
50 out = new ByteArrayOutputStream();
51 csvWriter = new CsvWriter(out);
52 }
53 } catch (RepositoryException e) {
54 throw new ArgeoException("Cannot create table node " + tableNode, e);
55 }
56 }
57
58 public void appendRow(Object[] row) {
59 csvWriter.writeLine(row);
60 }
61
62 public void close() {
63 Binary binary = null;
64 InputStream in = null;
65 try {
66 // TODO parallelize with pipes and writing from another thread
67 in = new ByteArrayInputStream(out.toByteArray());
68 binary = contentNode.getSession().getValueFactory()
69 .createBinary(in);
70 contentNode.setProperty(Property.JCR_DATA, binary);
71 } catch (RepositoryException e) {
72 throw new ArgeoException("Cannot store data in " + contentNode, e);
73 } finally {
74 IOUtils.closeQuietly(in);
75 JcrUtils.closeQuietly(binary);
76 }
77 }
78 }