001/* 002 * Copyright (C) 2016 Hobrasoft s.r.o. 003 * 004 * This program is free software: you can redistribute it and/or modify 005 * it under the terms of the GNU Affero General Public License as published by 006 * the Free Software Foundation, either version 3 of the License, or 007 * (at your option) any later version. 008 * 009 * This program is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 012 * GNU Affero General Public License for more details. 013 * 014 * You should have received a copy of the GNU Affero General Public License 015 * along with this program. If not, see <http://www.gnu.org/licenses/>. 016 */ 017package cz.hobrasoft.pdfmu; 018 019import com.fasterxml.jackson.databind.ObjectMapper; 020import com.fasterxml.jackson.databind.SerializationFeature; 021import java.io.IOException; 022import java.io.OutputStream; 023 024/** 025 * An {@link ObjectMapper} that writes JSON documents to an {@link OutputStream} 026 * 027 * <p> 028 * This class is a simple wrapper for {@link ObjectMapper} and 029 * {@link OutputStream}. 030 * 031 * @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a> 032 */ 033public class WritingMapper { 034 035 private final ObjectMapper mapper; 036 private final OutputStream os; 037 038 /** 039 * Creates a {@link WritingMapper} 040 * 041 * @param mapper the {@link ObjectMapper} to use for writing JSON documents 042 * @param os the target {@link OutputStream} 043 */ 044 public WritingMapper(ObjectMapper mapper, OutputStream os) { 045 this.mapper = mapper; 046 this.os = os; 047 } 048 049 public WritingMapper() { 050 this.mapper = new ObjectMapper(); // Create a new mapper 051 mapper.enable(SerializationFeature.INDENT_OUTPUT); // Enable nice formatting 052 this.os = System.err; // Bind to `System.err` 053 } 054 055 /** 056 * Serializes a Java value as a JSON output, streaming it to the specified 057 * {@link OutputStream} 058 * 059 * @param value the Java value to be serialized 060 * @throws IOException if the underlying 061 * {@link ObjectMapper#writeValue(OutputStream, Object)} throws an 062 * {@link IOException} 063 */ 064 public void writeValue(Object value) throws IOException { 065 mapper.writeValue(os, value); 066 } 067}