001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2022 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.io.util;
020
021import com.fasterxml.jackson.databind.ObjectMapper;
022import org.jgrapes.core.Channel;
023import org.jgrapes.core.EventPipeline;
024import org.jgrapes.io.util.events.DataInput;
025import org.jgrapes.io.util.events.JsonParsingError;
026
027/**
028 * A {@link ManagedBufferStreamer} that feeds the data to a JSON parser.
029 * When the data is fully parsed, it is made available by firing a
030 * {@link DataInput} event.
031 * 
032 * @since 2.8
033 */
034public class JsonReader extends ManagedBufferStreamer {
035
036    /**
037     * Instantiates a new JSON reader.
038     *
039     * @param <R> the result data type
040     * @param mapper the mapper
041     * @param resultType the result type
042     * @param pipeline the pipeline to use for sending the
043     * {@link DataInput} event
044     * @param channel the channel to use for sending the 
045     * {@link DataInput} event
046     */
047    @SuppressWarnings("PMD.AvoidCatchingGenericException")
048    public <R> JsonReader(ObjectMapper mapper, Class<R> resultType,
049            EventPipeline pipeline, Channel channel) {
050        super(r -> {
051            try {
052                pipeline.fire(new DataInput<>(mapper.readValue(r, resultType)),
053                    channel);
054            } catch (Exception e) {
055                pipeline.fire(new JsonParsingError(e), channel);
056            }
057        });
058    }
059
060    /**
061     * Instantiates a new JSON reader that uses a default object mapper.
062     *
063     * @param <R> the result data type
064     * @param resultType the result type
065     * @param pipeline the pipeline to use for sending the
066     * {@link DataInput} event
067     * @param channel the channel to use for sending the
068     * {@link DataInput} event
069     */
070    public <R> JsonReader(Class<R> resultType, EventPipeline pipeline,
071            Channel channel) {
072        this(new ObjectMapper(), resultType, pipeline, channel);
073    }
074}