001package org.matsim.core.events.algorithms;
002
003import com.fasterxml.jackson.core.JsonFactory;
004import com.fasterxml.jackson.core.JsonGenerator;
005import com.fasterxml.jackson.core.util.MinimalPrettyPrinter;
006import org.matsim.api.core.v01.events.Event;
007import org.matsim.core.events.handler.BasicEventHandler;
008import org.matsim.core.utils.io.IOUtils;
009import org.matsim.core.utils.io.UncheckedIOException;
010
011import java.io.File;
012import java.io.IOException;
013import java.io.OutputStream;
014import java.util.Map;
015
016/**
017 * @author mrieser / Simunto GmbH
018 * Code contributed by Data Foundry, LLC.
019 */
020public class EventWriterJson implements EventWriter, BasicEventHandler {
021        private OutputStream out = null;
022        private JsonGenerator jsonGenerator = null;
023
024        public EventWriterJson(File outfile) {
025                try {
026                        this.out = IOUtils.getOutputStream(outfile.toURI().toURL(), false);
027                        this.jsonGenerator = new JsonFactory().createGenerator(this.out);
028                        this.jsonGenerator.setPrettyPrinter(new MinimalPrettyPrinter("\n"));
029                } catch (UncheckedIOException | IOException e) {
030                        e.printStackTrace();
031                }
032        }
033
034        public EventWriterJson(OutputStream stream) {
035                try {
036                        this.out = stream;
037                        this.jsonGenerator = new JsonFactory().createGenerator(this.out);
038                        this.jsonGenerator.setPrettyPrinter(new MinimalPrettyPrinter("\n"));
039                } catch (IOException e) {
040                        e.printStackTrace();
041                }
042        }
043
044        @Override
045        public void closeFile() {
046                try {
047                        this.jsonGenerator.close();
048                        this.out.close();
049                } catch (IOException e) {
050                        throw new UncheckedIOException(e);
051                }
052        }
053
054        @Override
055        public void handleEvent(final Event event) {
056                try {
057                        this.jsonGenerator.writeStartObject();
058                        Map<String, String> attr = event.getAttributes();
059                        for(Map.Entry<String, String> entry : attr.entrySet()) {
060                                this.jsonGenerator.writeStringField(entry.getKey(), entry.getValue());
061                        }
062                        this.jsonGenerator.writeEndObject();
063                } catch (IOException e) {
064                        e.printStackTrace();
065                }
066        }
067
068        @Override
069        public void reset(final int iter) {
070        }
071
072}