All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.nlab.json.stream.consumer.JsonConsumer Maven / Gradle / Ivy

package org.nlab.json.stream.consumer;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Stream;

import org.jooq.lambda.fi.util.function.CheckedFunction;
import org.nlab.exception.UncheckedExecutionException;
import org.nlab.json.stream.JsonStream;
import org.nlab.json.stream.context.StreamContext;
import org.nlab.json.stream.matcher.EventMatcher;
import org.nlab.json.stream.matcher.EventMatchers;


public class JsonConsumer {

	private final JsonStream stream;

	private final List> consumers = new ArrayList<>();

	public JsonConsumer(JsonStream stream) {
		this.stream = Objects.requireNonNull(stream);
	}


	public JsonConsumer matchJsonPath(String query, CheckedConsumeAndContinueConsumer consumer) {
		addConsumer(EventMatchers.jsonPath(query, consumer));
		return this;
	}

	public JsonConsumer matchJsonPath(String query, CheckedFunction consumer) {
		addConsumer(EventMatchers.jsonPath(query, consumer));
		return this;
	}


	public JsonConsumer matchObjects(String[] elements, CheckedFunction consumer) {
		addConsumer(EventMatchers.objects(elements, consumer));
		return this;
	}

	public JsonConsumer matchObjects(String[] elements, CheckedConsumeAndContinueConsumer consumer) {
		addConsumer(EventMatchers.objects(elements, consumer));
		return this;
	}


	public JsonConsumer matchObject(String element, CheckedFunction consumer) {
		addConsumer(EventMatchers.object(element, consumer));
		return this;
	}

	public JsonConsumer matchObject(String element, CheckedConsumeAndContinueConsumer consumer) {
		addConsumer(EventMatchers.object(element, consumer));
		return this;
	}

	public JsonConsumer match(Predicate predicate, CheckedFunction consumer) {
		addConsumer(new EventMatcher(predicate, consumer));
		return this;
	}

	public JsonConsumer match(Predicate predicate, CheckedConsumeAndContinueConsumer consumer) {
		addConsumer(new EventMatcher(predicate, consumer));
		return this;
	}
	
	
	public JsonConsumer addConsumer(CheckedFunction consumer) {
		consumers.add(consumer);
		return this;
	}


	/**
	 * Consume the Stream
	 *
	 */
	public void consume() {

		try (Stream stream = this.stream) {
			stream.forEach(c -> {
				for (CheckedFunction consumer : consumers) {
                    try {
                        if (!consumer.apply(c)) {
                            break;
                        }
                    } catch (Throwable throwable) {
                        throw new UncheckedExecutionException(throwable);
                    }
                }
			});
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy