org.carrot2.util.factory.FallbackFactory Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of carrot2-mini Show documentation
Show all versions of carrot2-mini Show documentation
Carrot2 search results clustering framework. Minimal functional subset
(core algorithms and infrastructure, no document sources).
/*
* Carrot2 project.
*
* Copyright (C) 2002-2013, Dawid Weiss, Stanisław Osiński.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* http://www.carrot2.org/carrot2.LICENSE
*/
package org.carrot2.util.factory;
import org.slf4j.Logger;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
/**
* Fallback to the first factory that returns a value.
*/
public final class FallbackFactory implements IFactory
{
private final IFactory defaultFactory;
private final IFactory fallbackFactory;
private final String failureMessage;
private final Logger logger;
/** Verifies if T instances are functional or if fallback should be used. */
private final Predicate verifier;
public FallbackFactory(
IFactory defaultFactory, IFactory fallbackFactory, Predicate verifier,
Logger logger, String failureMessage)
{
this.defaultFactory = defaultFactory;
this.fallbackFactory = fallbackFactory;
this.failureMessage = failureMessage;
this.logger = logger;
this.verifier = verifier;
}
/**
* Creates an instance of T
, making sure it is functional.
*/
@Override
public final T createInstance()
{
try
{
T instance = defaultFactory.createInstance();
if (verifier.apply(instance))
{
return instance;
}
logger.warn(failureMessage, "(false from predicate)");
return fallbackFactory.createInstance();
}
catch (Throwable t)
{
if (logger.isDebugEnabled())
logger.warn(failureMessage, t.toString() + "\n" + Throwables.getStackTraceAsString(t));
else
logger.warn(failureMessage, t.toString());
return fallbackFactory.createInstance();
}
}
}