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 */
034@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
035public class JsonReader extends ManagedBufferStreamer {
036
037    /**
038     * Instantiates a new JSON reader.
039     *
040     * @param <R> the result data type
041     * @param mapper the mapper
042     * @param resultType the result type
043     * @param pipeline the pipeline to use for sending the
044     * {@link DataInput} event
045     * @param channel the channel to use for sending the 
046     * {@link DataInput} event
047     */
048    @SuppressWarnings("PMD.AvoidCatchingGenericException")
049    public <R> JsonReader(ObjectMapper mapper, Class<R> resultType,
050            EventPipeline pipeline, Channel channel) {
051        super(r -> {
052            try {
053                pipeline.fire(new DataInput<R>(mapper.readValue(r, resultType)),
054                    channel);
055            } catch (Exception e) {
056                pipeline.fire(new JsonParsingError(e), channel);
057            }
058        });
059    }
060
061    /**
062     * Instantiates a new JSON reader that uses a default object mapper.
063     *
064     * @param <R> the result data type
065     * @param resultType the result type
066     * @param pipeline the pipeline to use for sending the
067     * {@link DataInput} event
068     * @param channel the channel to use for sending the
069     * {@link DataInput} event
070     */
071    public <R> JsonReader(Class<R> resultType, EventPipeline pipeline,
072            Channel channel) {
073        this(new ObjectMapper(), resultType, pipeline, channel);
074    }
075}