MATSIM
EventWriterJson.java
Go to the documentation of this file.
1 package org.matsim.core.events.algorithms;
2 
3 import com.fasterxml.jackson.core.JsonFactory;
4 import com.fasterxml.jackson.core.JsonGenerator;
5 import com.fasterxml.jackson.core.util.MinimalPrettyPrinter;
9 
10 import java.io.File;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.io.UncheckedIOException;
14 import java.util.Map;
15 
20 public class EventWriterJson implements EventWriter, BasicEventHandler {
21  private OutputStream out = null;
22  private JsonGenerator jsonGenerator = null;
23 
24  public EventWriterJson(File outfile) {
25  try {
26  this.out = IOUtils.getOutputStream(outfile.toURI().toURL(), false);
27  this.jsonGenerator = new JsonFactory().createGenerator(this.out);
28  this.jsonGenerator.setPrettyPrinter(new MinimalPrettyPrinter("\n"));
29  } catch (IOException e) {
30  throw new UncheckedIOException(e);
31  }
32  }
33 
34  public EventWriterJson(OutputStream stream) {
35  try {
36  this.out = stream;
37  this.jsonGenerator = new JsonFactory().createGenerator(this.out);
38  this.jsonGenerator.setPrettyPrinter(new MinimalPrettyPrinter("\n"));
39  } catch (IOException e) {
40  throw new UncheckedIOException(e);
41  }
42  }
43 
44  @Override
45  public void closeFile() {
46  try {
47  this.jsonGenerator.close();
48  this.out.close();
49  } catch (IOException e) {
50  throw new UncheckedIOException(e);
51  }
52  }
53 
54  @Override
55  public void handleEvent(final Event event) {
56  try {
57  this.jsonGenerator.writeStartObject();
58  Map<String, String> attr = event.getAttributes();
59  for(Map.Entry<String, String> entry : attr.entrySet()) {
60  this.jsonGenerator.writeStringField(entry.getKey(), entry.getValue());
61  }
62  this.jsonGenerator.writeEndObject();
63  } catch (IOException e) {
64  throw new UncheckedIOException(e);
65  }
66  }
67 
68  @Override
69  public void reset(final int iter) {
70  }
71 
72 }
static OutputStream getOutputStream(URL url, boolean append)
Definition: IOUtils.java:344