/* * (c) Copyright 2010-2011 by Volker Bergmann. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, is permitted under the terms of the * GNU General Public License (GPL). * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * WITHOUT A WARRANTY OF ANY KIND. ALL EXPRESS OR IMPLIED CONDITIONS, * REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE * HEREBY EXCLUDED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.databene.benerator.wrapper; import java.util.Random; import org.databene.benerator.Generator; /** * {@link GeneratorProxy} implementation which injects a given quota of null values in the * original generator's results.<br/><br/> * Created: 26.01.2010 10:32:58 * @since 0.6.0 * @author Volker Bergmann */ public class NullInjectingGeneratorProxy<E> extends GeneratorProxy<E> { private float nullQuota; private Random random; boolean closed; public NullInjectingGeneratorProxy(Generator<E> source, double nullQuota) { super(source); if (nullQuota < 0 || nullQuota > 1) throw new IllegalArgumentException("Illegal null quota: " + nullQuota); this.nullQuota = (float) nullQuota; random = new Random(); closed = false; } /** * First checks if a null value should be returned, if so it returns a wrapper that wraps a null value, * otherwise a wrapper that wraps a value generated by the underlying source generator. If that generator * is not available any more, <code>null</code> is returned. */ @Override public ProductWrapper<E> generate(ProductWrapper<E> wrapper) { if (closed) return null; if (shouldNullify()) return wrapper.wrap(null); else return super.generate(wrapper); } protected boolean shouldNullify() { return random.nextFloat() < nullQuota; } @Override public String toString() { return getClass().getSimpleName() + "[" + nullQuota + ", " + getSource() + "]"; } }