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

com.flextrade.jfixture.behaviours.recursion.RecursionGuard Maven / Gradle / Ivy

Go to download

JFixture is an open source library based on the popular .NET library, AutoFixture

There is a newer version: 2.7.2
Show newest version
package com.flextrade.jfixture.behaviours.recursion;

import com.flextrade.jfixture.SpecimenBuilder;
import com.flextrade.jfixture.SpecimenContext;
import com.flextrade.jfixture.utility.RequestFilter;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class RecursionGuard implements SpecimenBuilder {

    private final Stack monitoredRequests = new Stack();
    private final SpecimenBuilder builder;
    private final RecursionHandler recursionHandler;

    public RecursionGuard(SpecimenBuilder builder, RecursionHandler recursionHandler) {
        this.builder = builder;
        this.recursionHandler = recursionHandler;
    }

    @Override
    public Object create(Object request, SpecimenContext context) {

        for (Object monitoredRequest : this.monitoredRequests) {
            if(request.equals(monitoredRequest)) {
                return this.handleRecursiveRequest(request);
            }
        }

        this.monitoredRequests.push(request);
        try {
            return this.builder.create(request, context);
        }
        finally {
            this.monitoredRequests.pop();
        }
    }

    public SpecimenBuilder builder() {
        return this.builder;
    }

    public RecursionHandler handler() {
        return this.recursionHandler;
    }

    private Object handleRecursiveRequest(Object request) {
        List filtered = new ArrayList();
        RequestFilter filter = RequestFilter.onlyDefault();
        for (Object mr : this.monitoredRequests) {
            if (filter.allow(mr))
                filtered.add(mr);
        }

        return this.recursionHandler.handleRecursiveRequest(request, filtered);
    }
}