1 package org.lcsim.util.loop;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.Arrays;
6 import java.util.Collection;
7 import java.util.HashSet;
8 import java.util.Set;
9
10 import org.lcsim.event.EventHeader;
11 import org.lcsim.util.Driver;
12 import org.lcsim.lcio.LCIOWriter;
13
14
15
16
17
18
19
20
21
22
23
24 public class LCIODriver extends Driver {
25 private LCIOWriter writer;
26 private Set<String> listIgnore = new HashSet<String>();
27 private Set<String> listKeep = new HashSet<String>();
28 private File outputFile;
29
30 public LCIODriver(String file) {
31 this(addFileExtension(file), null);
32 }
33
34 public LCIODriver(File file) {
35 this(file, null);
36 }
37
38 public LCIODriver(String file, Collection<String> listIgnore) {
39 this(new File(addFileExtension(file)), listIgnore);
40 }
41
42 public LCIODriver(File file, Collection<String> listIgnore) {
43 this.outputFile = file;
44 if (listIgnore != null) {
45 this.listIgnore.addAll(listIgnore);
46 }
47 }
48
49 public LCIODriver() {
50 }
51
52 public void setOutputFilePath(String filePath) {
53 outputFile = new File(addFileExtension(filePath));
54 }
55
56 public void setIgnoreCollections(String[] ignoreCollections) {
57 listIgnore.addAll(Arrays.asList(ignoreCollections));
58 }
59
60 public void setWriteOnlyCollections(String[] keepCollections) {
61 listKeep.addAll(Arrays.asList(keepCollections));
62 }
63
64 public void setIgnoreCollection(String ignoreCollection) {
65 listIgnore.add(ignoreCollection);
66 }
67
68 public void setWriteOnlyCollection(String writeOnlyCollection) {
69 listKeep.add(writeOnlyCollection);
70 }
71
72 private void setupWriter() {
73
74 if (writer != null) {
75 try {
76 writer.flush();
77 writer.close();
78 writer = null;
79 } catch (IOException x) {
80 System.err.println(x.getMessage());
81 }
82 }
83
84
85 try {
86 writer = new LCIOWriter(outputFile);
87 } catch (IOException x) {
88 throw new RuntimeException("Error creating writer", x);
89 }
90 writer.addAllIgnore(listIgnore);
91 writer.addAllWriteOnly(listKeep);
92
93 try {
94 writer.reOpen();
95 } catch (IOException x) {
96 throw new RuntimeException("Error rewinding LCIO file", x);
97 }
98 }
99
100 protected void startOfData() {
101 setupWriter();
102 }
103
104 protected void endOfData() {
105 try {
106 writer.close();
107 } catch (IOException x) {
108 throw new RuntimeException("Error rewinding LCIO file", x);
109 }
110 }
111
112 protected void process(EventHeader event) {
113 try {
114 writer.write(event);
115 } catch (IOException x) {
116 throw new RuntimeException("Error writing LCIO file", x);
117 }
118 }
119
120 protected void suspend() {
121 try {
122 writer.flush();
123 } catch (IOException x) {
124 throw new RuntimeException("Error flushing LCIO file", x);
125 }
126 }
127
128 private static String addFileExtension(String filePath) {
129 if (!filePath.endsWith(".slcio")) {
130 return filePath + ".slcio";
131 } else
132 return filePath;
133 }
134 }