
com.github.fge.jsonschema.processing.ProcessorSelector Maven / Gradle / Ivy
/*
* Copyright (c) 2013, Francis Galiegue
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package com.github.fge.jsonschema.processing;
import com.github.fge.jsonschema.exceptions.ProcessingException;
import com.github.fge.jsonschema.report.MessageProvider;
import com.github.fge.jsonschema.report.ProcessingMessage;
import com.github.fge.jsonschema.report.ProcessingReport;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.util.Map;
public final class ProcessorSelector
{
final Map, Processor> choices;
private final Processor byDefault;
public ProcessorSelector()
{
choices = Maps.newLinkedHashMap();
byDefault = null;
}
private ProcessorSelector(
final Map, Processor> choices,
final Processor byDefault)
{
this.choices = Maps.newLinkedHashMap(choices);
this.byDefault = byDefault;
}
ProcessorSelector(final ProcessorSelectorPredicate selector)
{
this(selector.choices, selector.byDefault);
}
public ProcessorSelectorPredicate when(
final Predicate predicate)
{
return new ProcessorSelectorPredicate(this, predicate,
byDefault);
}
public ProcessorSelector otherwise(
final Processor byDefault)
{
return new ProcessorSelector(choices, byDefault);
}
public Processor getProcessor()
{
return new Chooser(choices, byDefault);
}
private static final class Chooser
implements Processor
{
private final Map, Processor> map;
private final Processor byDefault;
private Chooser(final Map, Processor> map,
final Processor byDefault)
{
this.map = ImmutableMap.copyOf(map);
this.byDefault = byDefault;
}
@Override
public Y process(final ProcessingReport report, final X input)
throws ProcessingException
{
Predicate predicate;
Processor processor;
for (final Map.Entry, Processor> entry:
map.entrySet()) {
predicate = entry.getKey();
processor = entry.getValue();
if (predicate.apply(input))
return processor.process(report, input);
}
if (byDefault != null)
return byDefault.process(report, input);
final ProcessingMessage message = input.newMessage()
.message("no suitable processor found for input");
throw new ProcessingException(message);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy