1 /* 2 * Copyright (C) 2016 Hobrasoft s.r.o. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU Affero General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU Affero General Public License for more details. 13 * 14 * You should have received a copy of the GNU Affero General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 package cz.hobrasoft.pdfmu; 18 19 import com.fasterxml.jackson.databind.ObjectMapper; 20 import com.fasterxml.jackson.databind.SerializationFeature; 21 import java.io.IOException; 22 import java.io.OutputStream; 23 24 /** 25 * An {@link ObjectMapper} that writes JSON documents to an {@link OutputStream} 26 * 27 * <p> 28 * This class is a simple wrapper for {@link ObjectMapper} and 29 * {@link OutputStream}. 30 * 31 * @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a> 32 */ 33 public class WritingMapper { 34 35 private final ObjectMapper mapper; 36 private final OutputStream os; 37 38 /** 39 * Creates a {@link WritingMapper} 40 * 41 * @param mapper the {@link ObjectMapper} to use for writing JSON documents 42 * @param os the target {@link OutputStream} 43 */ 44 public WritingMapper(ObjectMapper mapper, OutputStream os) { 45 this.mapper = mapper; 46 this.os = os; 47 } 48 49 public WritingMapper() { 50 this.mapper = new ObjectMapper(); // Create a new mapper 51 mapper.enable(SerializationFeature.INDENT_OUTPUT); // Enable nice formatting 52 this.os = System.err; // Bind to `System.err` 53 } 54 55 /** 56 * Serializes a Java value as a JSON output, streaming it to the specified 57 * {@link OutputStream} 58 * 59 * @param value the Java value to be serialized 60 * @throws IOException if the underlying 61 * {@link ObjectMapper#writeValue(OutputStream, Object)} throws an 62 * {@link IOException} 63 */ 64 public void writeValue(Object value) throws IOException { 65 mapper.writeValue(os, value); 66 } 67 }