/******************************************************************************* | |
* Copyright (C) 2018 ANSYS medini Technologies AG | |
* | |
* This program and the accompanying materials are made | |
* available under the terms of the Eclipse Public License 2.0 | |
* which is available at https://www.eclipse.org/legal/epl-2.0/ | |
* | |
* SPDX-License-Identifier: EPL-2.0 | |
* | |
* Contributors: | |
* ANSYS medini Technologies AG - initial API and implementation | |
******************************************************************************/ | |
package org.eclipse.opencert.elastic.search; | |
import java.util.HashSet; | |
import java.util.Set; | |
/** | |
* Abstraction layer to resolve any "Hit" back to an object using an | |
* {@link ObjectResolver} within a given context. | |
* | |
* @author mauersberger | |
*/ | |
public class HitResolution<T> { | |
// the context we are working on, e.g. a list of objects or a tree or a database | |
private Object context; | |
// the resolver to do the real job | |
private ObjectResolver<? extends T> objectResolver; | |
/** | |
* Factory to create a new {@link HitResolution} object working on the given | |
* context | |
* | |
* @param context | |
* an arbitrary context that can be interpreted by the | |
* {@link ObjectResolver} | |
* @return the new {@link HitResolution} | |
*/ | |
public static <T> HitResolution<T> on(Object context) { | |
HitResolution<T> resolution = new HitResolution<>(); | |
// XXX hack | |
resolution.context = DummyData.INSTANCE.convert(context); | |
return resolution; | |
} | |
/** | |
* Use the given {@link ObjectResolver} when resolving a hit. | |
* | |
* @param resolver | |
* the resolver (should match the context) | |
* @return this | |
*/ | |
public HitResolution<T> using(ObjectResolver<? extends T> resolver) { | |
objectResolver = resolver; | |
return this; | |
} | |
public T resolve(Hit hit) { | |
if (objectResolver == null) { | |
throw new IllegalStateException("an object resolver is missing - use with(...) before"); //$NON-NLS-1$ | |
} | |
return objectResolver.resolve(hit.objectId, context); | |
} | |
public Set<T> resolve(Set<Hit> hits, int minScore) { | |
Set<T> resolvedAll = new HashSet<>(); | |
for (Hit hit : hits) { | |
if (hit.score < minScore) { | |
// filter hits with low score | |
continue; | |
} | |
T resolved = this.resolve(hit); | |
if (resolved != null) { | |
resolvedAll.add(resolved); | |
} | |
} | |
return resolvedAll; | |
} | |
} |