index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-integration-test/1.26.1/ai/timefold/solver/quarkus/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-integration-test/1.26.1/ai/timefold/solver/quarkus/it/domain/TestdataStringLengthShadowSolution.java | package ai.timefold.solver.quarkus.it.domain;
import java.util.List;
import java.util.Map;
import ai.timefold.solver.core.api.domain.solution.ConstraintWeightOverrides;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
@PlanningSolution
public class TestdataStringLengthShadowSolution {
@ValueRangeProvider(id = "valueRange")
private List<String> valueList;
@PlanningEntityCollectionProperty
private List<TestdataStringLengthShadowEntity> entityList;
ConstraintWeightOverrides<HardSoftScore> constraintWeightOverrides = ConstraintWeightOverrides.of(
Map.of("Don't assign 2 entities the same value.", HardSoftScore.ofHard(1)));
@PlanningScore
private HardSoftScore score;
// ************************************************************************
// Getters/setters
// ************************************************************************
public List<String> getValueList() {
return valueList;
}
public void setValueList(List<String> valueList) {
this.valueList = valueList;
}
public List<TestdataStringLengthShadowEntity> getEntityList() {
return entityList;
}
public void setEntityList(List<TestdataStringLengthShadowEntity> entityList) {
this.entityList = entityList;
}
public ConstraintWeightOverrides<HardSoftScore> getConstraintWeightOverrides() {
return constraintWeightOverrides;
}
public void setConstraintWeightOverrides(ConstraintWeightOverrides<HardSoftScore> constraintWeightOverrides) {
this.constraintWeightOverrides = constraintWeightOverrides;
}
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-integration-test/1.26.1/ai/timefold/solver/quarkus/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-integration-test/1.26.1/ai/timefold/solver/quarkus/it/solver/TestdataStringLengthConstraintProvider.java | package ai.timefold.solver.quarkus.it.solver;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.score.stream.Joiners;
import ai.timefold.solver.quarkus.it.domain.TestdataStringLengthShadowEntity;
import org.jspecify.annotations.NonNull;
public class TestdataStringLengthConstraintProvider implements ConstraintProvider {
@Override
public Constraint @NonNull [] defineConstraints(@NonNull ConstraintFactory factory) {
return new Constraint[] {
factory.forEach(TestdataStringLengthShadowEntity.class)
.join(TestdataStringLengthShadowEntity.class, Joiners.equal(TestdataStringLengthShadowEntity::getValue))
.filter((a, b) -> a != b)
.penalize(HardSoftScore.ONE_HARD)
.asConstraint("Don't assign 2 entities the same value."),
factory.forEach(TestdataStringLengthShadowEntity.class)
.reward(HardSoftScore.ONE_SOFT, TestdataStringLengthShadowEntity::getLength)
.asConstraint("Maximize value length")
};
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jackson-deployment/1.26.1/ai/timefold/solver/quarkus/jackson | java-sources/ai/timefold/solver/timefold-solver-quarkus-jackson-deployment/1.26.1/ai/timefold/solver/quarkus/jackson/deployment/TimefoldJacksonProcessor$$accessor.java | package ai.timefold.solver.quarkus.jackson.deployment;
@io.quarkus.Generated("Quarkus annotation processor")
public final class TimefoldJacksonProcessor$$accessor {
private TimefoldJacksonProcessor$$accessor() {}
public static Object construct() {
return new TimefoldJacksonProcessor();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jackson-deployment/1.26.1/ai/timefold/solver/quarkus/jackson | java-sources/ai/timefold/solver/timefold-solver-quarkus-jackson-deployment/1.26.1/ai/timefold/solver/quarkus/jackson/deployment/TimefoldJacksonProcessor.java | package ai.timefold.solver.quarkus.jackson.deployment;
import ai.timefold.solver.jackson.api.TimefoldJacksonModule;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.jackson.spi.ClassPathJacksonModuleBuildItem;
class TimefoldJacksonProcessor {
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem("timefold-solver-jackson");
}
@BuildStep
ClassPathJacksonModuleBuildItem registerTimefoldJacksonModule() {
// Make timefold-solver-jackson discoverable by quarkus-rest
// https://quarkus.io/guides/rest-migration#service-loading
return new ClassPathJacksonModuleBuildItem(TimefoldJacksonModule.class.getName());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jackson-integration-test/1.26.1/ai/timefold/solver/quarkus/jackson | java-sources/ai/timefold/solver/timefold-solver-quarkus-jackson-integration-test/1.26.1/ai/timefold/solver/quarkus/jackson/it/TimefoldTestResource.java | package ai.timefold.solver.quarkus.jackson.it;
import java.util.concurrent.ExecutionException;
import jakarta.inject.Inject;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import ai.timefold.solver.core.api.solver.SolverJob;
import ai.timefold.solver.core.api.solver.SolverManager;
import ai.timefold.solver.quarkus.jackson.it.domain.ITestdataPlanningSolution;
@Path("/timefold/test")
public class TimefoldTestResource {
private final SolverManager<ITestdataPlanningSolution, Long> solverManager;
@Inject
public TimefoldTestResource(SolverManager<ITestdataPlanningSolution, Long> solverManager) {
this.solverManager = solverManager;
}
@POST
@Path("/solver-factory")
public ITestdataPlanningSolution solveWithSolverFactory(ITestdataPlanningSolution problem) {
SolverJob<ITestdataPlanningSolution, Long> solverJob = solverManager.solve(1L, problem);
try {
return solverJob.getFinalBestSolution();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Solving was interrupted.", e);
} catch (ExecutionException e) {
throw new IllegalStateException("Solving failed.", e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jackson-integration-test/1.26.1/ai/timefold/solver/quarkus/jackson/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-jackson-integration-test/1.26.1/ai/timefold/solver/quarkus/jackson/it/domain/ITestdataPlanningEntity.java | package ai.timefold.solver.quarkus.jackson.it.domain;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
@PlanningEntity
public class ITestdataPlanningEntity {
@PlanningVariable(valueRangeProviderRefs = "valueRange")
private String value;
// ************************************************************************
// Getters/setters
// ************************************************************************
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jackson-integration-test/1.26.1/ai/timefold/solver/quarkus/jackson/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-jackson-integration-test/1.26.1/ai/timefold/solver/quarkus/jackson/it/domain/ITestdataPlanningSolution.java | package ai.timefold.solver.quarkus.jackson.it.domain;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
@PlanningSolution
public class ITestdataPlanningSolution {
@ValueRangeProvider(id = "valueRange")
private List<String> valueList;
@PlanningEntityCollectionProperty
private List<ITestdataPlanningEntity> entityList;
@PlanningScore
private SimpleScore score;
// ************************************************************************
// Getters/setters
// ************************************************************************
public List<String> getValueList() {
return valueList;
}
public void setValueList(List<String> valueList) {
this.valueList = valueList;
}
public List<ITestdataPlanningEntity> getEntityList() {
return entityList;
}
public void setEntityList(List<ITestdataPlanningEntity> entityList) {
this.entityList = entityList;
}
public SimpleScore getScore() {
return score;
}
public void setScore(SimpleScore score) {
this.score = score;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jackson-integration-test/1.26.1/ai/timefold/solver/quarkus/jackson/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-jackson-integration-test/1.26.1/ai/timefold/solver/quarkus/jackson/it/solver/ITestdataPlanningConstraintProvider.java | package ai.timefold.solver.quarkus.jackson.it.solver;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.score.stream.Joiners;
import ai.timefold.solver.quarkus.jackson.it.domain.ITestdataPlanningEntity;
import org.jspecify.annotations.NonNull;
public class ITestdataPlanningConstraintProvider implements ConstraintProvider {
@Override
public Constraint @NonNull [] defineConstraints(@NonNull ConstraintFactory factory) {
return new Constraint[] {
factory.forEach(ITestdataPlanningEntity.class)
.join(ITestdataPlanningEntity.class, Joiners.equal(ITestdataPlanningEntity::getValue))
.filter((a, b) -> a != b)
.penalize(SimpleScore.ONE)
.asConstraint("Don't assign 2 entities the same value.")
};
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb/1.26.1/ai/timefold/solver/quarkus/jsonb/TimefoldJsonbConfigCustomizer.java | package ai.timefold.solver.quarkus.jsonb;
import jakarta.inject.Singleton;
import jakarta.json.bind.JsonbConfig;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.jsonb.api.TimefoldJsonbConfig;
import io.quarkus.jsonb.JsonbConfigCustomizer;
/**
* Timefold doesn't use JSON-B, but it does have optional JSON-B support for {@link Score}, etc.
*
* @deprecated Prefer Jackson integration instead.
*/
@Singleton
@Deprecated(forRemoval = true, since = "1.4.0")
public class TimefoldJsonbConfigCustomizer implements JsonbConfigCustomizer {
@Override
public void customize(JsonbConfig config) {
config.withAdapters(TimefoldJsonbConfig.getScoreJsonbAdapters());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb-deployment/1.26.1/ai/timefold/solver/quarkus/jsonb | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb-deployment/1.26.1/ai/timefold/solver/quarkus/jsonb/deployment/TimefoldJsonbProcessor$$accessor.java | package ai.timefold.solver.quarkus.jsonb.deployment;
@io.quarkus.Generated("Quarkus annotation processor")
public final class TimefoldJsonbProcessor$$accessor {
private TimefoldJsonbProcessor$$accessor() {}
public static Object construct() {
return new TimefoldJsonbProcessor();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb-deployment/1.26.1/ai/timefold/solver/quarkus/jsonb | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb-deployment/1.26.1/ai/timefold/solver/quarkus/jsonb/deployment/TimefoldJsonbProcessor.java | package ai.timefold.solver.quarkus.jsonb.deployment;
import ai.timefold.solver.quarkus.jsonb.TimefoldJsonbConfigCustomizer;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.FeatureBuildItem;
/**
* @deprecated Prefer Jackson integration instead.
*/
@Deprecated(forRemoval = true, since = "1.4.0")
class TimefoldJsonbProcessor {
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem("timefold-solver-jsonb");
}
@BuildStep
void registerTimefoldJsonbConfig(BuildProducer<AdditionalBeanBuildItem> additionalBeans) {
additionalBeans.produce(new AdditionalBeanBuildItem(TimefoldJsonbConfigCustomizer.class));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb-integration-test/1.26.1/ai/timefold/solver/quarkus/jsonb | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb-integration-test/1.26.1/ai/timefold/solver/quarkus/jsonb/it/TimefoldTestResource.java | package ai.timefold.solver.quarkus.jsonb.it;
import java.util.concurrent.ExecutionException;
import jakarta.inject.Inject;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import ai.timefold.solver.core.api.solver.SolverJob;
import ai.timefold.solver.core.api.solver.SolverManager;
import ai.timefold.solver.quarkus.jsonb.it.domain.ITestdataPlanningSolution;
@Path("/timefold/test")
public class TimefoldTestResource {
private final SolverManager<ITestdataPlanningSolution, Long> solverManager;
@Inject
public TimefoldTestResource(SolverManager<ITestdataPlanningSolution, Long> solverManager) {
this.solverManager = solverManager;
}
@POST
@Path("/solver-factory")
public ITestdataPlanningSolution solveWithSolverFactory(ITestdataPlanningSolution problem) {
SolverJob<ITestdataPlanningSolution, Long> solverJob = solverManager.solve(1L, problem);
try {
return solverJob.getFinalBestSolution();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Solving was interrupted.", e);
} catch (ExecutionException e) {
throw new IllegalStateException("Solving failed.", e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb-integration-test/1.26.1/ai/timefold/solver/quarkus/jsonb/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb-integration-test/1.26.1/ai/timefold/solver/quarkus/jsonb/it/domain/ITestdataPlanningEntity.java | package ai.timefold.solver.quarkus.jsonb.it.domain;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
@PlanningEntity
public class ITestdataPlanningEntity {
@PlanningVariable(valueRangeProviderRefs = "valueRange")
private String value;
// ************************************************************************
// Getters/setters
// ************************************************************************
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb-integration-test/1.26.1/ai/timefold/solver/quarkus/jsonb/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb-integration-test/1.26.1/ai/timefold/solver/quarkus/jsonb/it/domain/ITestdataPlanningSolution.java | package ai.timefold.solver.quarkus.jsonb.it.domain;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
@PlanningSolution
public class ITestdataPlanningSolution {
@ValueRangeProvider(id = "valueRange")
private List<String> valueList;
@PlanningEntityCollectionProperty
private List<ITestdataPlanningEntity> entityList;
@PlanningScore
private SimpleScore score;
// ************************************************************************
// Getters/setters
// ************************************************************************
public List<String> getValueList() {
return valueList;
}
public void setValueList(List<String> valueList) {
this.valueList = valueList;
}
public List<ITestdataPlanningEntity> getEntityList() {
return entityList;
}
public void setEntityList(List<ITestdataPlanningEntity> entityList) {
this.entityList = entityList;
}
public SimpleScore getScore() {
return score;
}
public void setScore(SimpleScore score) {
this.score = score;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb-integration-test/1.26.1/ai/timefold/solver/quarkus/jsonb/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-jsonb-integration-test/1.26.1/ai/timefold/solver/quarkus/jsonb/it/solver/ITestdataPlanningConstraintProvider.java | package ai.timefold.solver.quarkus.jsonb.it.solver;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.score.stream.Joiners;
import ai.timefold.solver.quarkus.jsonb.it.domain.ITestdataPlanningEntity;
import org.jspecify.annotations.NonNull;
public class ITestdataPlanningConstraintProvider implements ConstraintProvider {
@Override
public Constraint @NonNull [] defineConstraints(@NonNull ConstraintFactory factory) {
return new Constraint[] {
factory.forEach(ITestdataPlanningEntity.class)
.join(ITestdataPlanningEntity.class, Joiners.equal(ITestdataPlanningEntity::getValue))
.filter((a, b) -> a != b)
.penalize(SimpleScore.ONE)
.asConstraint("Don't assign 2 entities the same value.")
};
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-reflection-integration-test/1.26.1/ai/timefold/solver/quarkus/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-reflection-integration-test/1.26.1/ai/timefold/solver/quarkus/it/reflection/TimefoldTestResource.java | package ai.timefold.solver.quarkus.it.reflection;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import jakarta.inject.Inject;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import ai.timefold.solver.core.api.solver.SolverJob;
import ai.timefold.solver.core.api.solver.SolverManager;
import ai.timefold.solver.quarkus.it.reflection.domain.TestdataReflectionEntity;
import ai.timefold.solver.quarkus.it.reflection.domain.TestdataReflectionSolution;
@Path("/timefold/test")
public class TimefoldTestResource {
private final SolverManager<TestdataReflectionSolution, Long> solverManager;
@Inject
public TimefoldTestResource(SolverManager<TestdataReflectionSolution, Long> solverManager) {
this.solverManager = solverManager;
}
@POST
@Path("/solver-factory")
@Produces(MediaType.TEXT_PLAIN)
public String solveWithSolverFactory() {
TestdataReflectionSolution planningProblem = new TestdataReflectionSolution();
planningProblem.setEntityList(Arrays.asList(
new TestdataReflectionEntity(),
new TestdataReflectionEntity()));
planningProblem.setFieldValueList(Arrays.asList("a", "bb", "ccc"));
planningProblem.setMethodValueList(Arrays.asList("a", "bb", "ccc", "ddd"));
SolverJob<TestdataReflectionSolution, Long> solverJob = solverManager.solve(1L, planningProblem);
try {
return solverJob.getFinalBestSolution().getScore().toString();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Solving was interrupted.", e);
} catch (ExecutionException e) {
throw new IllegalStateException("Solving failed.", e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-reflection-integration-test/1.26.1/ai/timefold/solver/quarkus/it/reflection | java-sources/ai/timefold/solver/timefold-solver-quarkus-reflection-integration-test/1.26.1/ai/timefold/solver/quarkus/it/reflection/domain/TestdataReflectionEntity.java | package ai.timefold.solver.quarkus.it.reflection.domain;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
@PlanningEntity
public class TestdataReflectionEntity {
@PlanningVariable(valueRangeProviderRefs = "fieldValueRange")
public String fieldValue;
private String methodValueField;
// ************************************************************************
// Getters/setters
// ************************************************************************
@PlanningVariable(valueRangeProviderRefs = "methodValueRange")
public String getMethodValue() {
return methodValueField;
}
public void setMethodValue(String methodValueField) {
this.methodValueField = methodValueField;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-reflection-integration-test/1.26.1/ai/timefold/solver/quarkus/it/reflection | java-sources/ai/timefold/solver/timefold-solver-quarkus-reflection-integration-test/1.26.1/ai/timefold/solver/quarkus/it/reflection/domain/TestdataReflectionSolution.java | package ai.timefold.solver.quarkus.it.reflection.domain;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
@PlanningSolution
public class TestdataReflectionSolution {
@ValueRangeProvider(id = "fieldValueRange")
private List<String> fieldValueList;
private List<String> methodValueList;
@PlanningEntityCollectionProperty
private List<TestdataReflectionEntity> entityList;
@PlanningScore
private HardSoftScore score;
// ************************************************************************
// Getters/setters
// ************************************************************************
public List<String> getFieldValueList() {
return fieldValueList;
}
public void setFieldValueList(List<String> fieldValueList) {
this.fieldValueList = fieldValueList;
}
public List<String> getMethodValueList() {
return methodValueList;
}
public void setMethodValueList(List<String> methodValueList) {
this.methodValueList = methodValueList;
}
@ValueRangeProvider(id = "methodValueRange")
public List<String> readMethodValueList() {
return methodValueList;
}
public List<TestdataReflectionEntity> getEntityList() {
return entityList;
}
public void setEntityList(List<TestdataReflectionEntity> entityList) {
this.entityList = entityList;
}
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-reflection-integration-test/1.26.1/ai/timefold/solver/quarkus/it/reflection | java-sources/ai/timefold/solver/timefold-solver-quarkus-reflection-integration-test/1.26.1/ai/timefold/solver/quarkus/it/reflection/solver/TestdataStringLengthConstraintProvider.java | package ai.timefold.solver.quarkus.it.reflection.solver;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.score.stream.Joiners;
import ai.timefold.solver.quarkus.it.reflection.domain.TestdataReflectionEntity;
import org.jspecify.annotations.NonNull;
public class TestdataStringLengthConstraintProvider implements ConstraintProvider {
@Override
public Constraint @NonNull [] defineConstraints(@NonNull ConstraintFactory factory) {
return new Constraint[] {
factory.forEach(TestdataReflectionEntity.class)
.join(TestdataReflectionEntity.class, Joiners.equal(TestdataReflectionEntity::getMethodValue))
.filter((a, b) -> !a.fieldValue.equals(b.fieldValue))
.penalize(HardSoftScore.ONE_HARD)
.asConstraint("Entities with equal method values should have equal field values"),
factory.forEach(TestdataReflectionEntity.class)
.reward(HardSoftScore.ONE_SOFT, entity -> entity.getMethodValue().length())
.asConstraint("Maximize method value length")
};
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/IncludeAbstractClassesEntityScanner.java | package ai.timefold.solver.spring.boot.autoconfigure;
import static ai.timefold.solver.spring.boot.autoconfigure.util.LambdaUtils.rethrowFunction;
import static java.util.Collections.emptyList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.boot.autoconfigure.domain.EntityScanPackages;
import org.springframework.boot.autoconfigure.domain.EntityScanner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.util.ClassUtils;
public class IncludeAbstractClassesEntityScanner extends EntityScanner {
private final ApplicationContext context;
public IncludeAbstractClassesEntityScanner(ApplicationContext context) {
super(context);
this.context = context;
}
public <T> Class<? extends T> findFirstImplementingClass(Class<T> targetClass) {
List<Class<? extends T>> classes = findImplementingClassList(targetClass);
if (!classes.isEmpty()) {
return classes.get(0);
}
return null;
}
private Set<String> findPackages() {
Set<String> packages = new HashSet<>();
packages.addAll(AutoConfigurationPackages.get(context));
EntityScanPackages entityScanPackages = EntityScanPackages.get(context);
packages.addAll(entityScanPackages.getPackageNames());
return packages;
}
public <T> List<Class<? extends T>> findImplementingClassList(Class<T> targetClass) {
if (!AutoConfigurationPackages.has(context)) {
return emptyList();
}
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.setEnvironment(context.getEnvironment());
scanner.setResourceLoader(context);
scanner.addIncludeFilter(new AssignableTypeFilter(targetClass));
Set<String> packages = findPackages();
return packages.stream()
.flatMap(basePackage -> scanner.findCandidateComponents(basePackage).stream())
// findCandidateComponents can return the same package for different base packages
.distinct()
.sorted(Comparator.comparing(BeanDefinition::getBeanClassName))
.map(candidate -> {
try {
return (Class<? extends T>) ClassUtils.forName(candidate.getBeanClassName(), context.getClassLoader())
.asSubclass(targetClass);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("The %s class (%s) cannot be found."
.formatted(targetClass.getSimpleName(), candidate.getBeanClassName()), e);
}
})
.collect(Collectors.toList());
}
@SafeVarargs
public final List<Class<?>> findClassesWithAnnotation(Class<? extends Annotation>... annotations) {
if (!AutoConfigurationPackages.has(context)) {
return emptyList();
}
Set<String> packages = findPackages();
return packages.stream().flatMap(rethrowFunction(
basePackage -> findAllClassesUsingClassLoader(this.context.getClassLoader(), basePackage).stream()))
.filter(clazz -> hasAnyFieldOrMethodWithAnnotation(clazz, annotations))
.toList();
}
private boolean hasAnyFieldOrMethodWithAnnotation(Class<?> clazz, Class<? extends Annotation>[] annotations) {
List<Field> fieldList = List.of(clazz.getDeclaredFields());
List<Method> methodList = List.of(clazz.getDeclaredMethods());
return List.of(annotations).stream().anyMatch(a -> fieldList.stream().anyMatch(f -> f.getAnnotation(a) != null)
|| methodList.stream().anyMatch(m -> m.getDeclaredAnnotation(a) != null));
}
public boolean hasSolutionOrEntityClasses() {
try {
return !scan(PlanningSolution.class).isEmpty() || !scan(PlanningEntity.class).isEmpty();
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Scanning for @%s and @%s annotations failed."
.formatted(PlanningSolution.class.getSimpleName(), PlanningEntity.class.getSimpleName()), e);
}
}
public Class<?> findFirstSolutionClass() {
Set<Class<?>> solutionClassSet;
try {
solutionClassSet = scan(PlanningSolution.class);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(
"Scanning for @%s annotations failed.".formatted(PlanningSolution.class.getSimpleName()), e);
}
if (solutionClassSet.isEmpty()) {
return null;
}
return solutionClassSet.stream()
.filter(c -> !Modifier.isAbstract(c.getModifiers()))
.findFirst()
.orElse(null);
}
public List<Class<?>> findEntityClassList() {
try {
// Add all annotated classes
var entityClassSet = new HashSet<>(scan(PlanningEntity.class));
var childEntityList = new ArrayList<>(entityClassSet);
// Now we search for child classes as well
while (!childEntityList.isEmpty()) {
var entityClass = childEntityList.remove(0);
// Check all subclasses
var childEntityClassList = findImplementingClassList(entityClass).stream()
.filter(c -> !c.equals(entityClass))
.toList();
if (!childEntityClassList.isEmpty()) {
entityClassSet.addAll(childEntityClassList);
childEntityList.addAll(childEntityClassList);
}
}
return new ArrayList<>(entityClassSet);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Scanning for @%s failed.".formatted(PlanningEntity.class.getSimpleName()), e);
}
}
private Set<Class<?>> findAllClassesUsingClassLoader(ClassLoader classLoader, String packageName) throws IOException {
try (InputStream stream = classLoader.getResourceAsStream(packageName.replaceAll("[.]", "/"));
BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
return reader.lines()
.filter(line -> line.endsWith(".class"))
.map(className -> packageName + "." + className.substring(0, className.lastIndexOf('.')))
.map(className -> getClass(classLoader, className))
.collect(Collectors.toSet());
}
}
private Class<?> getClass(ClassLoader classLoader, String className) {
try {
return Class.forName(className, false, classLoader);
} catch (ClassNotFoundException e) {
// ignore the exception
}
return null;
}
@Override
protected ClassPathScanningCandidateComponentProvider
createClassPathScanningCandidateComponentProvider(ApplicationContext context) {
return new ClassPathScanningCandidateComponentProvider(false) {
@Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
AnnotationMetadata metadata = beanDefinition.getMetadata();
// Do not exclude abstract classes nor interfaces
return metadata.isIndependent();
}
};
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/TimefoldBenchmarkAutoConfiguration.java | package ai.timefold.solver.spring.boot.autoconfigure;
import static java.util.Objects.requireNonNullElse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import ai.timefold.solver.benchmark.api.PlannerBenchmarkFactory;
import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig;
import ai.timefold.solver.benchmark.config.SolverBenchmarkConfig;
import ai.timefold.solver.core.config.solver.SolverConfig;
import ai.timefold.solver.spring.boot.autoconfigure.config.BenchmarkProperties;
import ai.timefold.solver.spring.boot.autoconfigure.config.TimefoldProperties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
@Configuration
@AutoConfigureAfter(TimefoldSolverAutoConfiguration.class)
@ConditionalOnClass({ PlannerBenchmarkFactory.class })
@ConditionalOnMissingBean({ PlannerBenchmarkFactory.class })
@EnableConfigurationProperties({ TimefoldProperties.class })
public class TimefoldBenchmarkAutoConfiguration implements BeanClassLoaderAware, ApplicationContextAware {
private final TimefoldProperties timefoldProperties;
private ClassLoader beanClassLoader;
private ApplicationContext context;
protected TimefoldBenchmarkAutoConfiguration(TimefoldProperties timefoldProperties) {
this.timefoldProperties = timefoldProperties;
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.context = context;
}
@Bean
@Lazy
public PlannerBenchmarkConfig plannerBenchmarkConfig() {
assertSingleSolver();
SolverConfig solverConfig = context.getBean(SolverConfig.class);
PlannerBenchmarkConfig benchmarkConfig;
if (timefoldProperties.getBenchmark() != null
&& timefoldProperties.getBenchmark().getSolverBenchmarkConfigXml() != null) {
if (beanClassLoader.getResource(timefoldProperties.getBenchmark().getSolverBenchmarkConfigXml()) == null) {
throw new IllegalStateException(
"Invalid timefold.benchmark.solverBenchmarkConfigXml property ("
+ timefoldProperties.getBenchmark().getSolverBenchmarkConfigXml()
+ "): that classpath resource does not exist.");
}
benchmarkConfig = PlannerBenchmarkConfig
.createFromXmlResource(timefoldProperties.getBenchmark().getSolverBenchmarkConfigXml(), beanClassLoader);
} else if (beanClassLoader.getResource(BenchmarkProperties.DEFAULT_SOLVER_BENCHMARK_CONFIG_URL) != null) {
benchmarkConfig = PlannerBenchmarkConfig.createFromXmlResource(
TimefoldProperties.DEFAULT_SOLVER_BENCHMARK_CONFIG_URL, beanClassLoader);
} else {
benchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig);
benchmarkConfig.setBenchmarkDirectory(new File(BenchmarkProperties.DEFAULT_BENCHMARK_RESULT_DIRECTORY));
}
if (timefoldProperties.getBenchmark() != null && timefoldProperties.getBenchmark().getResultDirectory() != null) {
benchmarkConfig.setBenchmarkDirectory(new File(timefoldProperties.getBenchmark().getResultDirectory()));
}
if (benchmarkConfig.getBenchmarkDirectory() == null) {
benchmarkConfig.setBenchmarkDirectory(new File(BenchmarkProperties.DEFAULT_BENCHMARK_RESULT_DIRECTORY));
}
var inheritedBenchmarkConfig = benchmarkConfig.getInheritedSolverBenchmarkConfig();
if (inheritedBenchmarkConfig == null) {
inheritedBenchmarkConfig = new SolverBenchmarkConfig();
benchmarkConfig.setInheritedSolverBenchmarkConfig(inheritedBenchmarkConfig);
inheritedBenchmarkConfig.setSolverConfig(solverConfig.copyConfig());
}
var inheritedBenchmarkSolverConfig = Objects.requireNonNull(inheritedBenchmarkConfig.getSolverConfig());
if (timefoldProperties.getBenchmark() != null && timefoldProperties.getBenchmark().getSolver() != null) {
TimefoldSolverAutoConfiguration.applyTerminationProperties(inheritedBenchmarkSolverConfig,
timefoldProperties.getBenchmark().getSolver().getTermination());
}
var inheritedTerminationConfig = inheritedBenchmarkSolverConfig.getTerminationConfig();
if (inheritedTerminationConfig == null || !inheritedTerminationConfig.isConfigured()) {
List<SolverBenchmarkConfig> solverBenchmarkConfigList = benchmarkConfig.getSolverBenchmarkConfigList();
List<String> unconfiguredTerminationSolverBenchmarkList = new ArrayList<>();
if (solverBenchmarkConfigList == null) {
throw new IllegalStateException("At least one of the properties " +
"timefold.benchmark.solver.termination.spent-limit, " +
"timefold.benchmark.solver.termination.best-score-limit, " +
"timefold.benchmark.solver.termination.unimproved-spent-limit " +
"is required if termination is not configured in the " +
"inherited solver benchmark config and solverBenchmarkBluePrint is used.");
}
if (solverBenchmarkConfigList.size() == 1 && solverBenchmarkConfigList.get(0).getSolverConfig() == null) {
// Benchmark config was created from solver config, which means only the inherited solver config exists.
if (!inheritedBenchmarkSolverConfig.canTerminate()) {
String benchmarkConfigName =
requireNonNullElse(inheritedBenchmarkConfig.getName(), "InheritedSolverBenchmarkConfig");
unconfiguredTerminationSolverBenchmarkList.add(benchmarkConfigName);
}
} else {
for (int i = 0; i < solverBenchmarkConfigList.size(); i++) {
SolverBenchmarkConfig solverBenchmarkConfig = solverBenchmarkConfigList.get(i);
if (!solverConfig.canTerminate()) {
String benchmarkConfigName =
requireNonNullElse(solverBenchmarkConfig.getName(), "SolverBenchmarkConfig" + i);
unconfiguredTerminationSolverBenchmarkList.add(benchmarkConfigName);
}
}
}
if (!unconfiguredTerminationSolverBenchmarkList.isEmpty()) {
throw new IllegalStateException("The following " + SolverBenchmarkConfig.class.getSimpleName() + " do not " +
"have termination configured: " +
unconfiguredTerminationSolverBenchmarkList.stream()
.collect(Collectors.joining(", ", "[", "]"))
+ ". " +
"At least one of the properties " +
"timefold.benchmark.solver.termination.spent-limit, " +
"timefold.benchmark.solver.termination.best-score-limit, " +
"timefold.benchmark.solver.termination.unimproved-spent-limit " +
"is required if termination is not configured in a solver benchmark and the " +
"inherited solver benchmark config.");
}
}
return benchmarkConfig;
}
@Bean
@Lazy
public PlannerBenchmarkFactory plannerBenchmarkFactory(PlannerBenchmarkConfig benchmarkConfig) {
if (benchmarkConfig == null) {
return null;
}
assertSingleSolver();
return PlannerBenchmarkFactory.create(benchmarkConfig);
}
private void assertSingleSolver() {
if (timefoldProperties.getSolver() != null && timefoldProperties.getSolver().size() > 1) {
throw new IllegalStateException("""
When defining multiple solvers, the benchmark feature is not enabled.
Consider using separate <solverBenchmark> instances for evaluating different solver configurations.""");
}
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.beanClassLoader = classLoader;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/TimefoldSolverAotContribution.java | package ai.timefold.solver.spring.boot.autoconfigure;
import java.util.Map;
import ai.timefold.solver.core.config.solver.SolverConfig;
import org.springframework.aot.generate.GenerationContext;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.ReflectionHints;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
import org.springframework.beans.factory.aot.BeanFactoryInitializationCode;
public class TimefoldSolverAotContribution implements BeanFactoryInitializationAotContribution {
private final Map<String, SolverConfig> solverConfigMap;
public TimefoldSolverAotContribution(Map<String, SolverConfig> solverConfigMap) {
this.solverConfigMap = solverConfigMap;
}
/**
* Register a type for reflection, allowing introspection
* of its members at runtime in a native build.
*/
private static void registerType(ReflectionHints reflectionHints, Class<?> type) {
reflectionHints.registerType(type,
MemberCategory.INTROSPECT_PUBLIC_METHODS,
MemberCategory.INTROSPECT_DECLARED_METHODS,
MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS,
MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS,
MemberCategory.PUBLIC_FIELDS,
MemberCategory.DECLARED_FIELDS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_PUBLIC_METHODS);
}
@Override
public void applyTo(GenerationContext generationContext, BeanFactoryInitializationCode beanFactoryInitializationCode) {
ReflectionHints reflectionHints = generationContext.getRuntimeHints().reflection();
for (SolverConfig solverConfig : solverConfigMap.values()) {
solverConfig.visitReferencedClasses(type -> {
if (type != null) {
registerType(reflectionHints, type);
}
});
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/TimefoldSolverAotFactory.java | package ai.timefold.solver.spring.boot.autoconfigure;
import java.io.StringReader;
import ai.timefold.solver.core.api.solver.SolverFactory;
import ai.timefold.solver.core.api.solver.SolverManager;
import ai.timefold.solver.core.config.solver.SolverConfig;
import ai.timefold.solver.core.config.solver.SolverManagerConfig;
import ai.timefold.solver.core.impl.io.jaxb.SolverConfigIO;
import ai.timefold.solver.spring.boot.autoconfigure.config.SolverManagerProperties;
import ai.timefold.solver.spring.boot.autoconfigure.config.TimefoldProperties;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
public class TimefoldSolverAotFactory implements EnvironmentAware {
private TimefoldProperties timefoldProperties;
@Override
public void setEnvironment(Environment environment) {
// We need the environment to set run time properties of SolverFactory and SolverManager
BindResult<TimefoldProperties> result = Binder.get(environment).bind("timefold", TimefoldProperties.class);
this.timefoldProperties = result.orElseGet(TimefoldProperties::new);
}
public <Solution_, ProblemId_> SolverManager<Solution_, ProblemId_> solverManagerSupplier(String solverConfigXml) {
SolverFactory<Solution_> solverFactory = SolverFactory.create(solverConfigSupplier(solverConfigXml));
SolverManagerConfig solverManagerConfig = new SolverManagerConfig();
SolverManagerProperties solverManagerProperties = timefoldProperties.getSolverManager();
if (solverManagerProperties != null && solverManagerProperties.getParallelSolverCount() != null) {
solverManagerConfig.setParallelSolverCount(solverManagerProperties.getParallelSolverCount());
}
return SolverManager.create(solverFactory, solverManagerConfig);
}
public SolverConfig solverConfigSupplier(String solverConfigXml) {
SolverConfigIO solverConfigIO = new SolverConfigIO();
return solverConfigIO.read(new StringReader(solverConfigXml));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/TimefoldSolverAutoConfiguration.java | package ai.timefold.solver.spring.boot.autoconfigure;
import static ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptorValidator.assertValidPlanningVariables;
import static java.util.stream.Collectors.joining;
import java.io.StringWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.entity.PlanningPin;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.AnchorShadowVariable;
import ai.timefold.solver.core.api.domain.variable.CascadingUpdateShadowVariable;
import ai.timefold.solver.core.api.domain.variable.CustomShadowVariable;
import ai.timefold.solver.core.api.domain.variable.IndexShadowVariable;
import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable;
import ai.timefold.solver.core.api.domain.variable.NextElementShadowVariable;
import ai.timefold.solver.core.api.domain.variable.PiggybackShadowVariable;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.api.domain.variable.PreviousElementShadowVariable;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
import ai.timefold.solver.core.api.score.ScoreManager;
import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator;
import ai.timefold.solver.core.api.score.calculator.IncrementalScoreCalculator;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.solver.SolutionManager;
import ai.timefold.solver.core.api.solver.SolverFactory;
import ai.timefold.solver.core.api.solver.SolverManager;
import ai.timefold.solver.core.config.score.director.ScoreDirectorFactoryConfig;
import ai.timefold.solver.core.config.solver.SolverConfig;
import ai.timefold.solver.core.config.solver.termination.DiminishedReturnsTerminationConfig;
import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.io.jaxb.SolverConfigIO;
import ai.timefold.solver.spring.boot.autoconfigure.config.DiminishedReturnsProperties;
import ai.timefold.solver.spring.boot.autoconfigure.config.SolverProperties;
import ai.timefold.solver.spring.boot.autoconfigure.config.TerminationProperties;
import ai.timefold.solver.spring.boot.autoconfigure.config.TimefoldProperties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.NativeDetector;
import org.springframework.core.env.Environment;
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ SolverConfig.class, SolverFactory.class, ScoreManager.class, SolutionManager.class, SolverManager.class })
@ConditionalOnMissingBean({ SolverConfig.class, SolverFactory.class, ScoreManager.class, SolutionManager.class,
SolverManager.class })
@EnableConfigurationProperties({ TimefoldProperties.class })
public class TimefoldSolverAutoConfiguration
implements BeanClassLoaderAware, ApplicationContextAware, EnvironmentAware, BeanFactoryInitializationAotProcessor,
BeanDefinitionRegistryPostProcessor {
private static final Log LOG = LogFactory.getLog(TimefoldSolverAutoConfiguration.class);
private static final String DEFAULT_SOLVER_CONFIG_NAME = "getSolverConfig";
private static final Class<? extends Annotation>[] PLANNING_ENTITY_FIELD_ANNOTATIONS = new Class[] {
PlanningPin.class,
PlanningVariable.class,
PlanningListVariable.class,
AnchorShadowVariable.class,
CustomShadowVariable.class,
IndexShadowVariable.class,
InverseRelationShadowVariable.class,
NextElementShadowVariable.class,
PiggybackShadowVariable.class,
PreviousElementShadowVariable.class,
ShadowVariable.class,
CascadingUpdateShadowVariable.class
};
private ApplicationContext context;
private ClassLoader beanClassLoader;
private TimefoldProperties timefoldProperties;
protected TimefoldSolverAutoConfiguration() {
}
@Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
this.beanClassLoader = beanClassLoader;
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.context = context;
}
@Override
public void setEnvironment(Environment environment) {
// postProcessBeanFactory runs before creating any bean, but we need TimefoldProperties.
// Therefore, we use the Environment to load the properties
BindResult<TimefoldProperties> result = Binder.get(environment).bind("timefold", TimefoldProperties.class);
this.timefoldProperties = result.orElseGet(TimefoldProperties::new);
}
private Map<String, SolverConfig> getSolverConfigMap() {
var entityScanner = new IncludeAbstractClassesEntityScanner(this.context);
if (!entityScanner.hasSolutionOrEntityClasses()) {
LOG.warn(
"""
Skipping Timefold loading because there are no @%s or @%s annotated classes.
Maybe your annotated classes are not in a subpackage of your @%s annotated class's package.
Maybe move your planning solution and entity classes to your application class's (sub)package (or use @%s)."""
.formatted(PlanningSolution.class.getSimpleName(), PlanningEntity.class.getSimpleName(),
SpringBootApplication.class.getSimpleName(), EntityScan.class.getSimpleName()));
return Map.of();
}
var solverConfigMap = new HashMap<String, SolverConfig>();
// Step 1 - create all SolverConfig
// If the config map is empty, we build the config using the default solver name
if (timefoldProperties.getSolver() == null || timefoldProperties.getSolver().isEmpty()) {
solverConfigMap.put(TimefoldProperties.DEFAULT_SOLVER_NAME,
createSolverConfig(timefoldProperties, TimefoldProperties.DEFAULT_SOLVER_NAME));
} else {
timefoldProperties.getSolver().keySet()
.forEach(solverName -> solverConfigMap.put(solverName, createSolverConfig(timefoldProperties, solverName)));
}
// Step 2 - first pass of validations
assertValidaPlanningVariables(entityScanner);
assertSolverConfigSolutionClasses(entityScanner, solverConfigMap);
assertSolverConfigConstraintClasses(entityScanner, solverConfigMap);
// Step 3 - load all additional information per SolverConfig
solverConfigMap.forEach(
(solverName, solverConfig) -> loadSolverConfig(entityScanner, timefoldProperties, solverName, solverConfig));
// Step 4 - second pass of validations
assertEmptySolutionClasses(solverConfigMap);
assertMutableSolutionClasses(solverConfigMap);
assertSolverConfigEntityClasses(solverConfigMap);
return solverConfigMap;
}
@Override
public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
var solverConfigMap = getSolverConfigMap();
return new TimefoldSolverAotContribution(solverConfigMap);
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
var solverConfigMap = getSolverConfigMap();
var solverConfigIO = new SolverConfigIO();
registry.registerBeanDefinition(TimefoldSolverAotFactory.class.getName(),
new RootBeanDefinition(TimefoldSolverAotFactory.class));
if (solverConfigMap.isEmpty()) {
var rootBeanDefinition = new RootBeanDefinition(SolverConfig.class);
rootBeanDefinition.setFactoryBeanName(TimefoldSolverAotFactory.class.getName());
rootBeanDefinition.setFactoryMethodName("solverConfigSupplier");
var solverXmlOutput = new StringWriter();
solverConfigIO.write(new SolverConfig(), solverXmlOutput);
rootBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue(
solverXmlOutput.toString());
registry.registerBeanDefinition(DEFAULT_SOLVER_CONFIG_NAME, rootBeanDefinition);
return;
}
if (timefoldProperties.getSolver() == null || timefoldProperties.getSolver().size() == 1) {
var rootBeanDefinition = new RootBeanDefinition(SolverConfig.class);
rootBeanDefinition.setFactoryBeanName(TimefoldSolverAotFactory.class.getName());
rootBeanDefinition.setFactoryMethodName("solverConfigSupplier");
var solverXmlOutput = new StringWriter();
solverConfigIO.write(solverConfigMap.values().iterator().next(), solverXmlOutput);
rootBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue(
solverXmlOutput.toString());
registry.registerBeanDefinition(DEFAULT_SOLVER_CONFIG_NAME, rootBeanDefinition);
} else {
// Only SolverManager can be injected for multiple solver configurations
solverConfigMap.forEach((solverName, solverConfig) -> {
var rootBeanDefinition = new RootBeanDefinition(SolverManager.class);
rootBeanDefinition.setFactoryBeanName(TimefoldSolverAotFactory.class.getName());
rootBeanDefinition.setFactoryMethodName("solverManagerSupplier");
var solverXmlOutput = new StringWriter();
solverConfigIO.write(solverConfig, solverXmlOutput);
rootBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue(
solverXmlOutput.toString());
registry.registerBeanDefinition(solverName, rootBeanDefinition);
});
}
}
private SolverConfig createSolverConfig(TimefoldProperties timefoldProperties, String solverName) {
// 1 - The solver configuration takes precedence over root and default settings
var solverConfigXml = timefoldProperties.getSolverConfig(solverName)
.map(SolverProperties::getSolverConfigXml);
// 2 - Root settings
if (solverConfigXml.isEmpty()) {
solverConfigXml = Optional.ofNullable(timefoldProperties.getSolverConfigXml());
}
SolverConfig solverConfig;
if (solverConfigXml.isPresent()) {
String solverUrl = solverConfigXml.get();
if (beanClassLoader.getResource(solverUrl) == null) {
String message =
"Invalid timefold.solverConfigXml property (%s): that classpath resource does not exist."
.formatted(solverUrl);
if (!solverName.equals(TimefoldProperties.DEFAULT_SOLVER_NAME)) {
message =
"Invalid timefold.solver.\"%s\".solverConfigXML property (%s): that classpath resource does not exist."
.formatted(solverName, solverUrl);
}
throw new IllegalStateException(message);
}
solverConfig = SolverConfig.createFromXmlResource(solverUrl);
} else if (beanClassLoader.getResource(TimefoldProperties.DEFAULT_SOLVER_CONFIG_URL) != null) {
// 3 - Default file URL
solverConfig = SolverConfig.createFromXmlResource(
TimefoldProperties.DEFAULT_SOLVER_CONFIG_URL);
} else {
solverConfig = new SolverConfig(beanClassLoader);
}
return solverConfig;
}
private void loadSolverConfig(IncludeAbstractClassesEntityScanner entityScanner, TimefoldProperties timefoldProperties,
String solverName, SolverConfig solverConfig) {
if (solverConfig.getSolutionClass() == null) {
solverConfig.setSolutionClass(entityScanner.findFirstSolutionClass());
}
var solverEntityClassList = solverConfig.getEntityClassList();
if (solverEntityClassList == null) {
solverConfig.setEntityClassList(entityScanner.findEntityClassList());
}
timefoldProperties.getSolverConfig(solverName)
.ifPresentOrElse(
solverProperties -> applyScoreDirectorFactoryProperties(entityScanner, solverConfig, solverProperties),
() -> applyScoreDirectorFactoryProperties(entityScanner, solverConfig));
}
private void applyScoreDirectorFactoryProperties(IncludeAbstractClassesEntityScanner entityScanner,
SolverConfig solverConfig, SolverProperties solverProperties) {
applyScoreDirectorFactoryProperties(entityScanner, solverConfig);
if (solverProperties.getConstraintStreamAutomaticNodeSharing() != null
&& solverProperties.getConstraintStreamAutomaticNodeSharing()) {
if (NativeDetector.inNativeImage()) {
throw new UnsupportedOperationException(
"Constraint stream automatic node sharing is unsupported in a Spring native image.");
}
Objects.requireNonNull(solverConfig.getScoreDirectorFactoryConfig())
.setConstraintStreamAutomaticNodeSharing(true);
}
if (solverProperties.getEnvironmentMode() != null) {
solverConfig.setEnvironmentMode(solverProperties.getEnvironmentMode());
}
if (solverProperties.getDomainAccessType() != null) {
solverConfig.setDomainAccessType(solverProperties.getDomainAccessType());
}
if (solverProperties.getEnabledPreviewFeatures() != null) {
solverConfig.setEnablePreviewFeatureSet(new HashSet<>(solverProperties.getEnabledPreviewFeatures()));
}
if (solverProperties.getNearbyDistanceMeterClass() != null) {
solverConfig.setNearbyDistanceMeterClass(solverProperties.getNearbyDistanceMeterClass());
}
if (solverProperties.getDaemon() != null) {
solverConfig.setDaemon(solverProperties.getDaemon());
}
if (solverProperties.getMoveThreadCount() != null) {
solverConfig.setMoveThreadCount(solverProperties.getMoveThreadCount());
}
applyTerminationProperties(solverConfig, solverProperties.getTermination());
}
private void applyScoreDirectorFactoryProperties(IncludeAbstractClassesEntityScanner entityScanner,
SolverConfig solverConfig) {
if (solverConfig.getScoreDirectorFactoryConfig() == null) {
solverConfig.setScoreDirectorFactoryConfig(defaultScoreDirectoryFactoryConfig(entityScanner));
}
}
private static ScoreDirectorFactoryConfig
defaultScoreDirectoryFactoryConfig(IncludeAbstractClassesEntityScanner entityScanner) {
var scoreDirectorFactoryConfig = new ScoreDirectorFactoryConfig();
scoreDirectorFactoryConfig
.setEasyScoreCalculatorClass(entityScanner.findFirstImplementingClass(EasyScoreCalculator.class));
scoreDirectorFactoryConfig
.setConstraintProviderClass(entityScanner.findFirstImplementingClass(ConstraintProvider.class));
scoreDirectorFactoryConfig
.setIncrementalScoreCalculatorClass(entityScanner.findFirstImplementingClass(IncrementalScoreCalculator.class));
return scoreDirectorFactoryConfig;
}
static void applyTerminationProperties(SolverConfig solverConfig, TerminationProperties terminationProperties) {
var terminationConfig = solverConfig.getTerminationConfig();
if (terminationConfig == null) {
terminationConfig = new TerminationConfig();
solverConfig.setTerminationConfig(terminationConfig);
}
if (terminationProperties != null) {
if (terminationProperties.getSpentLimit() != null) {
terminationConfig.overwriteSpentLimit(terminationProperties.getSpentLimit());
}
if (terminationProperties.getUnimprovedSpentLimit() != null) {
terminationConfig.overwriteUnimprovedSpentLimit(terminationProperties.getUnimprovedSpentLimit());
}
if (terminationProperties.getBestScoreLimit() != null) {
terminationConfig.setBestScoreLimit(terminationProperties.getBestScoreLimit());
}
if (terminationProperties.getDiminishedReturns() != null) {
applyDiminishedReturnsProperties(solverConfig, terminationProperties.getDiminishedReturns());
}
}
}
static void applyDiminishedReturnsProperties(SolverConfig solverConfig,
DiminishedReturnsProperties diminishedReturnsProperties) {
if (Objects.equals(false, diminishedReturnsProperties.getEnabled())) {
// do nothing if explicitly disabled
return;
}
var terminationConfig = solverConfig.getTerminationConfig();
if (terminationConfig == null) {
terminationConfig = new TerminationConfig();
solverConfig.setTerminationConfig(terminationConfig);
}
terminationConfig.setDiminishedReturnsConfig(new DiminishedReturnsTerminationConfig()
.withSlidingWindowDuration(diminishedReturnsProperties.getSlidingWindowDuration())
.withMinimumImprovementRatio(diminishedReturnsProperties.getMinimumImprovementRatio()));
}
private static void assertValidaPlanningVariables(IncludeAbstractClassesEntityScanner entityScanner) {
var timefoldFieldAnnotationList =
entityScanner.findClassesWithAnnotation(PLANNING_ENTITY_FIELD_ANNOTATIONS);
for (var clazz : timefoldFieldAnnotationList) {
assertValidPlanningVariables(clazz);
}
}
private static void assertSolverConfigSolutionClasses(IncludeAbstractClassesEntityScanner entityScanner,
Map<String, SolverConfig> solverConfigMap) {
// Multiple classes and single solver
try {
var classes = entityScanner.scan(PlanningSolution.class).stream()
.filter(c -> !Modifier.isAbstract(c.getModifiers()))
.toList();
var firstConfig = solverConfigMap.values().stream().findFirst().orElse(null);
if (classes.size() > 1 && solverConfigMap.size() == 1 && firstConfig != null
&& firstConfig.getSolutionClass() == null) {
throw new IllegalStateException(
"Multiple classes ([%s]) found in the classpath with a @%s annotation.".formatted(
classes.stream().map(Class::getSimpleName).collect(joining(", ")),
PlanningSolution.class.getSimpleName()));
}
// Multiple classes and at least one solver config do not specify the solution class
// We do not fail if all configurations define the solution,
// even though there are additional "unused" solution classes in the classpath.
var unconfiguredSolverConfigList = solverConfigMap.entrySet().stream()
.filter(e -> e.getValue().getSolutionClass() == null)
.map(Map.Entry::getKey)
.toList();
if (classes.size() > 1 && !unconfiguredSolverConfigList.isEmpty()) {
throw new IllegalStateException(
"""
Some solver configs (%s) don't specify a %s class, yet there are multiple available (%s) on the classpath.
Maybe set the XML config file to the related solver configs, or add the missing solution classes to the XML files,
or remove the unnecessary solution classes from the classpath."""
.formatted(String.join(", ", unconfiguredSolverConfigList),
PlanningSolution.class.getSimpleName(),
classes.stream().map(Class::getSimpleName).collect(joining(", "))));
}
// Unused solution classes
// When inheritance is used, we ignore the parent classes
var unusedSolutionClassList = classes.stream()
.map(Class::getName)
.filter(planningClassName -> solverConfigMap.values().stream().filter(c -> c.getSolutionClass() != null)
.noneMatch(c -> c.getSolutionClass().getName().equals(planningClassName)
|| c.getSolutionClass().getSuperclass().getName().equals(planningClassName)))
.toList();
if (classes.size() > 1 && !unusedSolutionClassList.isEmpty()) {
throw new IllegalStateException(
"Unused classes ([%s]) found with a @%s annotation.".formatted(
String.join(", ", unusedSolutionClassList),
PlanningSolution.class.getSimpleName()));
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException(
"Scanning for @%s annotations failed.".formatted(PlanningSolution.class.getSimpleName()), e);
}
}
private static void assertEmptySolutionClasses(Map<String, SolverConfig> solverConfigMap) {
// No solution class
for (var config : solverConfigMap.values()) {
if (config.getSolutionClass() == null) {
throw new IllegalStateException(
"No classes were found with a @%s annotation.".formatted(PlanningSolution.class.getSimpleName()));
}
}
}
private static void assertMutableSolutionClasses(Map<String, SolverConfig> solverConfigMap) {
// Assert it is mutable
for (var config : solverConfigMap.values()) {
SolutionDescriptor.assertMutable(config.getSolutionClass(), "solutionClass");
}
}
private static void assertSolverConfigEntityClasses(Map<String, SolverConfig> solverConfigMap) {
// No Entity class
for (var config : solverConfigMap.values()) {
// Assert if the list is empty
var entityList = config.getEntityClassList();
if (entityList == null || entityList.isEmpty()) {
throw new IllegalStateException(
"No classes were found with a @%s annotation.".formatted(PlanningEntity.class.getSimpleName()));
}
// Assert the entity target and planning variables
for (var clazz : entityList) {
SolutionDescriptor.assertMutable(clazz, "entityClass");
assertValidPlanningVariables(clazz);
}
}
}
private static void assertSolverConfigConstraintClasses(
IncludeAbstractClassesEntityScanner entityScanner, Map<String, SolverConfig> solverConfigMap) {
List<Class<? extends EasyScoreCalculator>> simpleScoreClassList =
entityScanner.findImplementingClassList(EasyScoreCalculator.class);
List<Class<? extends ConstraintProvider>> constraintScoreClassList =
entityScanner.findImplementingClassList(ConstraintProvider.class);
List<Class<? extends IncrementalScoreCalculator>> incrementalScoreClassList =
entityScanner.findImplementingClassList(IncrementalScoreCalculator.class);
// No score calculators
if (simpleScoreClassList.isEmpty() && constraintScoreClassList.isEmpty()
&& incrementalScoreClassList.isEmpty()) {
throw new IllegalStateException(
"""
No classes found that implement %s, %s, or %s.
Maybe your %s class is not in a subpackage of your @%s annotated class's package."
Maybe move your %s class to your application class's (sub)package (or use @%s)."""
.formatted(EasyScoreCalculator.class.getSimpleName(),
ConstraintProvider.class.getSimpleName(), IncrementalScoreCalculator.class.getSimpleName(),
ConstraintProvider.class.getSimpleName(), SpringBootApplication.class.getSimpleName(),
ConstraintProvider.class.getSimpleName(), EntityScan.class.getSimpleName()));
}
assertSolverConfigsSpecifyScoreCalculatorWhenAmbigious(solverConfigMap, simpleScoreClassList, constraintScoreClassList,
incrementalScoreClassList);
assertNoUnusedScoreClasses(solverConfigMap, simpleScoreClassList, constraintScoreClassList, incrementalScoreClassList);
}
private static void assertSolverConfigsSpecifyScoreCalculatorWhenAmbigious(Map<String, SolverConfig> solverConfigMap,
List<Class<? extends EasyScoreCalculator>> simpleScoreClassList,
List<Class<? extends ConstraintProvider>> constraintScoreClassList,
List<Class<? extends IncrementalScoreCalculator>> incrementalScoreClassList) {
// Single solver, multiple score calculators
var errorMessage = "Multiple score calculator classes (%s) that implements %s were found in the classpath.";
if (simpleScoreClassList.size() > 1 && solverConfigMap.size() == 1) {
throw new IllegalStateException(errorMessage.formatted(
simpleScoreClassList.stream().map(Class::getSimpleName).collect(joining(", ")),
EasyScoreCalculator.class.getSimpleName()));
}
if (constraintScoreClassList.size() > 1 && solverConfigMap.size() == 1) {
throw new IllegalStateException(errorMessage.formatted(
constraintScoreClassList.stream().map(Class::getSimpleName).collect(joining(", ")),
ConstraintProvider.class.getSimpleName()));
}
if (incrementalScoreClassList.size() > 1 && solverConfigMap.size() == 1) {
throw new IllegalStateException(errorMessage.formatted(
incrementalScoreClassList.stream().map(Class::getSimpleName).collect(joining(", ")),
IncrementalScoreCalculator.class.getSimpleName()));
}
// Multiple solvers, multiple score calculators
errorMessage =
"""
Some solver configs (%s) don't specify a %s score calculator class, yet there are multiple available (%s) on the classpath.
Maybe set the XML config file to the related solver configs, or add the missing score calculator to the XML files,
or remove the unnecessary score calculator from the classpath.""";
var solverConfigWithoutConstraintClassList = solverConfigMap.entrySet().stream()
.filter(e -> e.getValue().getScoreDirectorFactoryConfig() == null
|| e.getValue().getScoreDirectorFactoryConfig().getEasyScoreCalculatorClass() == null)
.map(Map.Entry::getKey)
.toList();
if (simpleScoreClassList.size() > 1 && !solverConfigWithoutConstraintClassList.isEmpty()) {
throw new IllegalStateException(errorMessage.formatted(
String.join(", ", solverConfigWithoutConstraintClassList),
EasyScoreCalculator.class.getSimpleName(),
simpleScoreClassList.stream().map(Class::getSimpleName).collect(joining(", "))));
}
solverConfigWithoutConstraintClassList = solverConfigMap.entrySet().stream()
.filter(e -> e.getValue().getScoreDirectorFactoryConfig() == null
|| e.getValue().getScoreDirectorFactoryConfig().getConstraintProviderClass() == null)
.map(Map.Entry::getKey)
.toList();
if (constraintScoreClassList.size() > 1 && !solverConfigWithoutConstraintClassList.isEmpty()) {
throw new IllegalStateException(errorMessage.formatted(
String.join(", ", solverConfigWithoutConstraintClassList),
ConstraintProvider.class.getSimpleName(),
constraintScoreClassList.stream().map(Class::getSimpleName).collect(joining(", "))));
}
solverConfigWithoutConstraintClassList = solverConfigMap.entrySet().stream()
.filter(e -> e.getValue().getScoreDirectorFactoryConfig() == null
|| e.getValue().getScoreDirectorFactoryConfig().getIncrementalScoreCalculatorClass() == null)
.map(Map.Entry::getKey)
.toList();
if (incrementalScoreClassList.size() > 1 && !solverConfigWithoutConstraintClassList.isEmpty()) {
throw new IllegalStateException(errorMessage.formatted(
String.join(", ", solverConfigWithoutConstraintClassList),
IncrementalScoreCalculator.class.getSimpleName(),
incrementalScoreClassList.stream().map(Class::getSimpleName).collect(joining(", "))));
}
}
private static void assertNoUnusedScoreClasses(Map<String, SolverConfig> solverConfigMap,
List<Class<? extends EasyScoreCalculator>> simpleScoreClassList,
List<Class<? extends ConstraintProvider>> constraintScoreClassList,
List<Class<? extends IncrementalScoreCalculator>> incrementalScoreClassList) {
String errorMessage;
var solverConfigWithUnusedSolutionClassList = simpleScoreClassList.stream()
.map(Class::getName)
.filter(className -> solverConfigMap.values().stream()
.filter(c -> c.getScoreDirectorFactoryConfig() != null
&& c.getScoreDirectorFactoryConfig().getEasyScoreCalculatorClass() != null)
.noneMatch(c -> c.getScoreDirectorFactoryConfig().getEasyScoreCalculatorClass().getName()
.equals(className)))
.toList();
errorMessage = "Unused classes ([%s]) that implements %s were found.";
if (simpleScoreClassList.size() > 1 && !solverConfigWithUnusedSolutionClassList.isEmpty()) {
throw new IllegalStateException(errorMessage.formatted(String.join(", ", solverConfigWithUnusedSolutionClassList),
EasyScoreCalculator.class.getSimpleName()));
}
solverConfigWithUnusedSolutionClassList = constraintScoreClassList.stream()
.map(Class::getName)
.filter(className -> solverConfigMap.values().stream()
.filter(c -> c.getScoreDirectorFactoryConfig() != null
&& c.getScoreDirectorFactoryConfig().getConstraintProviderClass() != null)
.noneMatch(c -> c.getScoreDirectorFactoryConfig().getConstraintProviderClass().getName()
.equals(className)))
.toList();
if (constraintScoreClassList.size() > 1 && !solverConfigWithUnusedSolutionClassList.isEmpty()) {
throw new IllegalStateException(errorMessage.formatted(String.join(", ", solverConfigWithUnusedSolutionClassList),
ConstraintProvider.class.getSimpleName()));
}
solverConfigWithUnusedSolutionClassList = incrementalScoreClassList.stream()
.map(Class::getName)
.filter(className -> solverConfigMap.values().stream()
.filter(c -> c.getScoreDirectorFactoryConfig() != null
&& c.getScoreDirectorFactoryConfig().getIncrementalScoreCalculatorClass() != null)
.noneMatch(c -> c.getScoreDirectorFactoryConfig().getIncrementalScoreCalculatorClass().getName()
.equals(className)))
.toList();
if (incrementalScoreClassList.size() > 1 && !solverConfigWithUnusedSolutionClassList.isEmpty()) {
throw new IllegalStateException(errorMessage.formatted(String.join(", ", solverConfigWithUnusedSolutionClassList),
IncrementalScoreCalculator.class.getSimpleName()));
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/TimefoldSolverBannerBean.java | package ai.timefold.solver.spring.boot.autoconfigure;
import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class TimefoldSolverBannerBean implements InitializingBean {
private static final Log LOG = LogFactory.getLog(TimefoldSolverBannerBean.class);
@Override
public void afterPropertiesSet() {
LOG.info("Using Timefold Solver " + TimefoldSolverEnterpriseService.identifySolverVersion() + ".");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/TimefoldSolverBeanFactory.java | package ai.timefold.solver.spring.boot.autoconfigure;
import java.util.function.BiFunction;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.ScoreManager;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintMetaModel;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.solver.SolutionManager;
import ai.timefold.solver.core.api.solver.SolverFactory;
import ai.timefold.solver.core.api.solver.SolverManager;
import ai.timefold.solver.core.config.score.director.ScoreDirectorFactoryConfig;
import ai.timefold.solver.core.config.solver.SolverConfig;
import ai.timefold.solver.core.config.solver.SolverManagerConfig;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.core.impl.solver.DefaultSolverFactory;
import ai.timefold.solver.jackson.api.TimefoldJacksonModule;
import ai.timefold.solver.spring.boot.autoconfigure.config.SolverManagerProperties;
import ai.timefold.solver.spring.boot.autoconfigure.config.TimefoldProperties;
import ai.timefold.solver.test.api.score.stream.ConstraintVerifier;
import ai.timefold.solver.test.api.score.stream.MultiConstraintVerification;
import ai.timefold.solver.test.api.score.stream.SingleConstraintVerification;
import org.jspecify.annotations.NonNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import com.fasterxml.jackson.databind.Module;
/**
* Must be seperated from {@link TimefoldSolverAutoConfiguration} since
* {@link TimefoldSolverAutoConfiguration} will not be available at runtime
* for a native image (since it is a {@link BeanFactoryInitializationAotProcessor}/
* {@link BeanFactoryPostProcessor}).
*/
@Configuration
public class TimefoldSolverBeanFactory implements ApplicationContextAware, EnvironmentAware {
private ApplicationContext context;
private TimefoldProperties timefoldProperties;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.context = context;
}
@Override
public void setEnvironment(Environment environment) {
// We need the environment to set run time properties of SolverFactory and SolverManager
BindResult<TimefoldProperties> result = Binder.get(environment).bind("timefold", TimefoldProperties.class);
this.timefoldProperties = result.orElseGet(TimefoldProperties::new);
}
private void failInjectionWithMultipleSolvers(String resourceName) {
if (timefoldProperties.getSolver() != null && timefoldProperties.getSolver().size() > 1) {
throw new BeanCreationException(
"No qualifying bean of type '%s' available".formatted(resourceName));
}
}
@Bean
@Lazy
public TimefoldSolverBannerBean getBanner() {
return new TimefoldSolverBannerBean();
}
@Bean
@Lazy
@ConditionalOnMissingBean
public <Solution_> SolverFactory<Solution_> getSolverFactory() {
failInjectionWithMultipleSolvers(SolverFactory.class.getName());
SolverConfig solverConfig = context.getBean(SolverConfig.class);
if (solverConfig.getSolutionClass() == null) {
return null;
}
return SolverFactory.create(solverConfig);
}
@Bean
@Lazy
@ConditionalOnMissingBean
public <Solution_, ProblemId_> SolverManager<Solution_, ProblemId_> solverManager(SolverFactory solverFactory) {
// TODO supply ThreadFactory
if (solverFactory == null) {
return null;
}
SolverManagerConfig solverManagerConfig = new SolverManagerConfig();
SolverManagerProperties solverManagerProperties = timefoldProperties.getSolverManager();
if (solverManagerProperties != null && solverManagerProperties.getParallelSolverCount() != null) {
solverManagerConfig.setParallelSolverCount(solverManagerProperties.getParallelSolverCount());
}
return SolverManager.create(solverFactory, solverManagerConfig);
}
@Bean
@Lazy
@ConditionalOnMissingBean
@Deprecated(forRemoval = true)
/**
* @deprecated Use {@link SolutionManager} instead.
*/
public <Solution_, Score_ extends Score<Score_>> ScoreManager<Solution_, Score_> scoreManager() {
failInjectionWithMultipleSolvers(ScoreManager.class.getName());
SolverFactory<Solution_> solverFactory = context.getBean(SolverFactory.class);
return ScoreManager.create(solverFactory);
}
@Bean
@Lazy
@ConditionalOnMissingBean
public <Solution_, Score_ extends Score<Score_>> SolutionManager<Solution_, Score_> solutionManager() {
failInjectionWithMultipleSolvers(SolutionManager.class.getName());
SolverFactory<Solution_> solverFactory = context.getBean(SolverFactory.class);
return SolutionManager.create(solverFactory);
}
@Bean
@Lazy
@ConditionalOnMissingBean
public <Solution_> ConstraintMetaModel constraintMetaModel() {
failInjectionWithMultipleSolvers(ConstraintMetaModel.class.getName());
var solverFactory = (DefaultSolverFactory<Solution_>) context.getBean(SolverFactory.class);
var scoreDirectorFactory = solverFactory.getScoreDirectorFactory();
if (scoreDirectorFactory instanceof AbstractConstraintStreamScoreDirectorFactory<Solution_, ?, ?> castScoreDirectorFactory) {
return castScoreDirectorFactory.getConstraintMetaModel();
} else {
throw new IllegalStateException(
"Cannot provide %s because the score director does not use the Constraint Streams API."
.formatted(ConstraintMetaModel.class.getSimpleName()));
}
}
// @Bean wrapped by static class to avoid classloading issues if dependencies are absent
@ConditionalOnClass({ ConstraintVerifier.class })
@ConditionalOnMissingBean({ ConstraintVerifier.class })
@AutoConfigureAfter(TimefoldSolverAutoConfiguration.class)
class TimefoldConstraintVerifierConfiguration {
private final ApplicationContext context;
protected TimefoldConstraintVerifierConfiguration(ApplicationContext context) {
this.context = context;
}
private record UnsupportedConstraintVerifier<ConstraintProvider_ extends ConstraintProvider, SolutionClass_>(
String errorMessage)
implements
ConstraintVerifier<ConstraintProvider_, SolutionClass_> {
@NonNull
@Override
public SingleConstraintVerification<SolutionClass_>
verifyThat(
@NonNull BiFunction<ConstraintProvider_, ConstraintFactory, Constraint> constraintFunction) {
throw new UnsupportedOperationException(errorMessage);
}
@NonNull
@Override
public MultiConstraintVerification<SolutionClass_> verifyThat() {
throw new UnsupportedOperationException(errorMessage);
}
}
@Bean
@Lazy
@SuppressWarnings("unchecked")
<ConstraintProvider_ extends ConstraintProvider, SolutionClass_>
ConstraintVerifier<ConstraintProvider_, SolutionClass_> constraintVerifier() {
// Using SolverConfig as an injected parameter here leads to an injection failure on an empty app,
// so we need to get the SolverConfig from context
failInjectionWithMultipleSolvers(ConstraintProvider.class.getName());
SolverConfig solverConfig;
try {
solverConfig = context.getBean(SolverConfig.class);
} catch (BeansException exception) {
solverConfig = null;
}
ScoreDirectorFactoryConfig scoreDirectorFactoryConfig =
(solverConfig != null) ? solverConfig.getScoreDirectorFactoryConfig() : null;
if (scoreDirectorFactoryConfig == null || scoreDirectorFactoryConfig.getConstraintProviderClass() == null) {
// Return a mock ConstraintVerifier so not having ConstraintProvider doesn't crash tests
// (Cannot create custom condition that checks SolverConfig, since that
// requires TimefoldSolverAutoConfiguration to have a no-args constructor)
final String noConstraintProviderErrorMsg = (scoreDirectorFactoryConfig != null)
? "Cannot provision a ConstraintVerifier because there is no ConstraintProvider class."
: "Cannot provision a ConstraintVerifier because there is no PlanningSolution or PlanningEntity classes.";
return new UnsupportedConstraintVerifier<>(noConstraintProviderErrorMsg);
}
return ConstraintVerifier.create(solverConfig);
}
}
// @Bean wrapped by static class to avoid classloading issues if dependencies are absent
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Jackson2ObjectMapperBuilder.class, Score.class })
static class TimefoldJacksonConfiguration {
@Bean
Module jacksonModule() {
return TimefoldJacksonModule.createModule();
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/config/BenchmarkProperties.java | package ai.timefold.solver.spring.boot.autoconfigure.config;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
public class BenchmarkProperties {
public static final String DEFAULT_SOLVER_BENCHMARK_CONFIG_URL = TimefoldProperties.DEFAULT_SOLVER_BENCHMARK_CONFIG_URL;
public static final String DEFAULT_BENCHMARK_RESULT_DIRECTORY = "target/benchmarks";
/**
* A classpath resource to read the benchmark configuration XML.
* Defaults to solverBenchmarkConfig.xml.
* If this property isn't specified, the file is optional.
*/
private String solverBenchmarkConfigXml;
/**
* The directory to which to write the benchmark HTML report and graphs,
* relative from the working directory.
*/
private String resultDirectory;
@NestedConfigurationProperty
private BenchmarkSolverProperties solver;
// ************************************************************************
// Getters/setters
// ************************************************************************
public String getSolverBenchmarkConfigXml() {
return solverBenchmarkConfigXml;
}
public void setSolverBenchmarkConfigXml(String solverBenchmarkConfigXml) {
this.solverBenchmarkConfigXml = solverBenchmarkConfigXml;
}
public String getResultDirectory() {
return resultDirectory;
}
public void setResultDirectory(String resultDirectory) {
this.resultDirectory = resultDirectory;
}
public BenchmarkSolverProperties getSolver() {
return solver;
}
public void setSolver(BenchmarkSolverProperties solver) {
this.solver = solver;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/config/BenchmarkSolverProperties.java | package ai.timefold.solver.spring.boot.autoconfigure.config;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
public class BenchmarkSolverProperties {
@NestedConfigurationProperty
private TerminationProperties termination;
// ************************************************************************
// Getters/setters
// ************************************************************************
public TerminationProperties getTermination() {
return termination;
}
public void setTermination(TerminationProperties termination) {
this.termination = termination;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/config/DiminishedReturnsProperties.java | package ai.timefold.solver.spring.boot.autoconfigure.config;
import java.time.Duration;
import java.util.Map;
import java.util.TreeSet;
public class DiminishedReturnsProperties {
/**
* If set to true, adds a termination to the local search
* phase that records the initial improvement after a duration,
* and terminates when the ratio new improvement/initial improvement
* is below a specified ratio.
*/
private Boolean enabled;
/**
* Specify the best score from how long ago should the current best
* score be compared to.
* For "30s", the current best score is compared against
* the best score from 30 seconds ago to calculate the improvement.
* "5m" is 5 minutes. "2h" is 2 hours. "1d" is 1 day.
* Also supports ISO-8601 format, see {@link Duration}.
* <br/>
* Default to 30s.
*/
private Duration slidingWindowDuration;
/**
* Specify the minimum ratio between the current improvement and the
* initial improvement. Must be positive.
* <br/>
* For example, if the {@link #slidingWindowDuration} is "30s",
* the {@link #minimumImprovementRatio} is 0.25, and the
* score improves by 100soft during the first 30 seconds of local search,
* then the local search phase will terminate when the difference between
* the current best score and the best score from 30 seconds ago is less than
* 25soft (= 0.25 * 100soft).
* <br/>
* Defaults to 0.0001.
*/
private Double minimumImprovementRatio;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Duration getSlidingWindowDuration() {
return slidingWindowDuration;
}
public void setSlidingWindowDuration(Duration slidingWindowDuration) {
this.slidingWindowDuration = slidingWindowDuration;
}
public Double getMinimumImprovementRatio() {
return minimumImprovementRatio;
}
public void setMinimumImprovementRatio(Double minimumImprovementRatio) {
this.minimumImprovementRatio = minimumImprovementRatio;
}
public void loadProperties(Map<String, Object> properties) {
// Check if the keys are valid
var invalidKeySet = new TreeSet<>(properties.keySet());
invalidKeySet.removeAll(DiminishedReturnsProperty.getValidPropertyNames());
if (!invalidKeySet.isEmpty()) {
throw new IllegalStateException("""
The termination's diminished returns properties [%s] are not valid.
Maybe try changing the property name to kebab-case.
Here is the list of valid properties: %s"""
.formatted(invalidKeySet, String.join(", ", DiminishedReturnsProperty.getValidPropertyNames())));
}
properties.forEach(this::loadProperty);
}
private void loadProperty(String key, Object value) {
if (value == null) {
return;
}
var property = DiminishedReturnsProperty.forPropertyName(key);
property.update(this, value);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/config/DiminishedReturnsProperty.java | package ai.timefold.solver.spring.boot.autoconfigure.config;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.boot.convert.DurationStyle;
public enum DiminishedReturnsProperty {
ENABLED("enabled", DiminishedReturnsProperties::setEnabled,
value -> Boolean.parseBoolean((String) value)),
SLIDING_WINDOW_DURATION("sliding-window-duration", DiminishedReturnsProperties::setSlidingWindowDuration,
value -> DurationStyle.detectAndParse((String) value)),
MINIMUM_IMPROVEMENT_RATIO("minimum-improvement-ratio", DiminishedReturnsProperties::setMinimumImprovementRatio,
value -> Double.valueOf((String) value)),;
private final String propertyName;
private final BiConsumer<DiminishedReturnsProperties, Object> propertyUpdater;
private static final Set<String> PROPERTY_NAMES = Stream.of(DiminishedReturnsProperty.values())
.map(DiminishedReturnsProperty::getPropertyName)
.collect(Collectors.toCollection(TreeSet::new));
<T> DiminishedReturnsProperty(String propertyName, BiConsumer<DiminishedReturnsProperties, T> propertySetter,
Function<Object, T> propertyConvertor) {
this.propertyName = propertyName;
this.propertyUpdater = (properties, object) -> propertySetter.accept(properties, propertyConvertor.apply(object));
}
public String getPropertyName() {
return propertyName;
}
public void update(DiminishedReturnsProperties properties, Object value) {
propertyUpdater.accept(properties, value);
}
public static Set<String> getValidPropertyNames() {
return Collections.unmodifiableSet(PROPERTY_NAMES);
}
public static DiminishedReturnsProperty forPropertyName(String propertyName) {
for (var property : values()) {
if (property.getPropertyName().equals(propertyName)) {
return property;
}
}
throw new IllegalArgumentException("No property with the name (%s). Valid properties are %s."
.formatted(propertyName, PROPERTY_NAMES));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/config/SolverManagerProperties.java | package ai.timefold.solver.spring.boot.autoconfigure.config;
public class SolverManagerProperties {
/**
* The number of solvers that run in parallel. This directly influences CPU consumption.
* Defaults to "AUTO".
* Other options include a number or formula based on the available processor count.
*/
private String parallelSolverCount;
// ************************************************************************
// Getters/setters
// ************************************************************************
public String getParallelSolverCount() {
return parallelSolverCount;
}
public void setParallelSolverCount(String parallelSolverCount) {
this.parallelSolverCount = parallelSolverCount;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/config/SolverProperties.java | package ai.timefold.solver.spring.boot.autoconfigure.config;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.score.stream.ConstraintStreamImplType;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.config.solver.PreviewFeature;
import ai.timefold.solver.core.impl.heuristic.selector.common.nearby.NearbyDistanceMeter;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
public class SolverProperties {
/**
* A classpath resource to read the specific solver configuration XML.
* If this property isn't specified, that solverConfig.xml is optional.
*/
private String solverConfigXml;
/**
* Enable runtime assertions to detect common bugs in your implementation during development.
* Defaults to {@link EnvironmentMode#PHASE_ASSERT}.
*/
private EnvironmentMode environmentMode;
/**
* Enable daemon mode. In daemon mode, non-early termination pauses the solver instead of stopping it,
* until the next problem fact change arrives. This is often useful for real-time planning.
* Defaults to "false".
*/
private Boolean daemon;
/**
* Note: this setting is only available
* for <a href="https://timefold.ai/docs/timefold-solver/latest/enterprise-edition/enterprise-edition">Timefold Solver
* Enterprise Edition</a>.
* Enable multithreaded solving for a single problem, which increases CPU consumption.
* Defaults to "NONE".
* Other options include "AUTO", a number or formula based on the available processor count.
*/
private String moveThreadCount;
/**
* Determines how to access the fields and methods of domain classes.
* Defaults to REFLECTION.
* <p>
* To use GIZMO, io.quarkus.gizmo:gizmo must be in your classpath,
* and all planning annotations must be on public members.
*/
private DomainAccessType domainAccessType;
private List<PreviewFeature> enabledPreviewFeatures;
/**
* Enable the Nearby Selection quick configuration.
*/
private Class<? extends NearbyDistanceMeter<?, ?>> nearbyDistanceMeterClass;
/**
* What constraint stream implementation to use. Defaults to BAVET.
*
* @deprecated No longer used.
*/
@Deprecated(forRemoval = true, since = "1.4.0")
private ConstraintStreamImplType constraintStreamImplType;
/**
* Note: this setting is only available
* for <a href="https://timefold.ai/docs/timefold-solver/latest/enterprise-edition/enterprise-edition">Timefold Solver
* Enterprise Edition</a>.
* Enable rewriting the {@link ai.timefold.solver.core.api.score.stream.ConstraintProvider} class
* so nodes share lambdas when possible, improving performance.
* When enabled, breakpoints placed in the {@link ai.timefold.solver.core.api.score.stream.ConstraintProvider}
* will no longer be triggered.
* Defaults to "false".
*/
private Boolean constraintStreamAutomaticNodeSharing;
@NestedConfigurationProperty
private TerminationProperties termination;
// ************************************************************************
// Getters/setters
// ************************************************************************
public String getSolverConfigXml() {
return solverConfigXml;
}
public void setSolverConfigXml(String solverConfigXml) {
this.solverConfigXml = solverConfigXml;
}
public EnvironmentMode getEnvironmentMode() {
return environmentMode;
}
public void setEnvironmentMode(EnvironmentMode environmentMode) {
this.environmentMode = environmentMode;
}
public Boolean getDaemon() {
return daemon;
}
public void setDaemon(Boolean daemon) {
this.daemon = daemon;
}
public String getMoveThreadCount() {
return moveThreadCount;
}
public void setMoveThreadCount(String moveThreadCount) {
this.moveThreadCount = moveThreadCount;
}
public DomainAccessType getDomainAccessType() {
return domainAccessType;
}
public void setDomainAccessType(DomainAccessType domainAccessType) {
this.domainAccessType = domainAccessType;
}
public List<PreviewFeature> getEnabledPreviewFeatures() {
return enabledPreviewFeatures;
}
public void setEnabledPreviewFeatures(List<PreviewFeature> enabledPreviewFeatures) {
this.enabledPreviewFeatures = enabledPreviewFeatures;
}
public Class<? extends NearbyDistanceMeter<?, ?>> getNearbyDistanceMeterClass() {
return nearbyDistanceMeterClass;
}
public void setNearbyDistanceMeterClass(Class<? extends NearbyDistanceMeter<?, ?>> nearbyDistanceMeterClass) {
this.nearbyDistanceMeterClass = nearbyDistanceMeterClass;
}
/**
* @deprecated No longer used.
*/
@Deprecated(forRemoval = true, since = "1.4.0")
public ConstraintStreamImplType getConstraintStreamImplType() {
return constraintStreamImplType;
}
/**
* @deprecated No longer used.
*/
@Deprecated(forRemoval = true, since = "1.4.0")
public void setConstraintStreamImplType(ConstraintStreamImplType constraintStreamImplType) {
this.constraintStreamImplType = constraintStreamImplType;
}
public Boolean getConstraintStreamAutomaticNodeSharing() {
return constraintStreamAutomaticNodeSharing;
}
public void setConstraintStreamAutomaticNodeSharing(Boolean constraintStreamAutomaticNodeSharing) {
this.constraintStreamAutomaticNodeSharing = constraintStreamAutomaticNodeSharing;
}
public TerminationProperties getTermination() {
return termination;
}
public void setTermination(TerminationProperties termination) {
this.termination = termination;
}
public void loadProperties(Map<String, Object> properties) {
// Check if the keys are valid
var invalidKeySet = new TreeSet<>(properties.keySet());
invalidKeySet.removeAll(SolverProperty.getValidPropertyNames());
if (!invalidKeySet.isEmpty()) {
throw new IllegalStateException("""
The properties [%s] are not valid.
Maybe try changing the property name to kebab-case.
Here is the list of valid properties: %s"""
.formatted(invalidKeySet, String.join(", ", SolverProperty.getValidPropertyNames())));
}
properties.forEach(this::loadProperty);
}
private void loadProperty(String key, Object value) {
if (value == null) {
return;
}
SolverProperty property = SolverProperty.forPropertyName(key);
property.update(this, value);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/config/SolverProperty.java | package ai.timefold.solver.spring.boot.autoconfigure.config;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.score.stream.ConstraintStreamImplType;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.config.solver.PreviewFeature;
import ai.timefold.solver.core.impl.heuristic.selector.common.nearby.NearbyDistanceMeter;
public enum SolverProperty {
SOLVER_CONFIG_XML("solver-config-xml", SolverProperties::setSolverConfigXml, Object::toString),
ENVIRONMENT_MODE("environment-mode", SolverProperties::setEnvironmentMode,
value -> EnvironmentMode.valueOf(value.toString())),
DAEMON("daemon", SolverProperties::setDaemon, value -> Boolean.valueOf(value.toString())),
MOVE_THREAD_COUNT("move-thread-count", SolverProperties::setMoveThreadCount, Object::toString),
DOMAIN_ACCESS_TYPE("domain-access-type", SolverProperties::setDomainAccessType,
value -> DomainAccessType.valueOf(value.toString())),
ENABLED_PREVIEW_FEATURES("enabled-preview-features", SolverProperties::setEnabledPreviewFeatures,
value -> Arrays.stream(value.toString().split(",")).map(PreviewFeature::valueOf).toList()),
NEARBY_DISTANCE_METER_CLASS("nearby-distance-meter-class", SolverProperties::setNearbyDistanceMeterClass,
value -> {
try {
@SuppressWarnings("rawtypes")
Class nearbyClass = Class.forName(value.toString(), false,
Thread.currentThread().getContextClassLoader());
if (!NearbyDistanceMeter.class.isAssignableFrom(nearbyClass)) {
throw new IllegalStateException(
"The Nearby Selection Meter class (%s) does not implement NearbyDistanceMeter."
.formatted(value.toString()));
}
return nearbyClass;
} catch (ClassNotFoundException e) {
throw new IllegalStateException(
"Cannot find the Nearby Selection Meter class (%s).".formatted(value.toString()));
}
}),
/**
* @deprecated No longer used.
*/
@Deprecated(forRemoval = true, since = "1.4.0")
CONSTRAINT_STREAM_IMPL_TYPE("constraint-stream-impl-type", SolverProperties::setConstraintStreamImplType,
value -> ConstraintStreamImplType.valueOf(value.toString())),
CONSTRAINT_STREAM_AUTOMATIC_NODE_SHARING("constraint-stream-automatic-node-sharing",
SolverProperties::setConstraintStreamAutomaticNodeSharing, value -> Boolean.valueOf(value.toString())),
TERMINATION("termination", SolverProperties::setTermination, value -> {
if (value instanceof TerminationProperties terminationProperties) {
return terminationProperties;
} else if (value instanceof Map<?, ?> map) {
TerminationProperties terminationProperties = new TerminationProperties();
terminationProperties.loadProperties((Map<String, Object>) map);
return terminationProperties;
} else {
throw new IllegalStateException(
"The termination value (%s) is not valid. Expected an instance of %s or %s, but got an instance of %s."
.formatted(value, Map.class.getSimpleName(), TerminationProperties.class.getSimpleName(),
value.getClass().getName()));
}
});
private final String propertyName;
private final BiConsumer<SolverProperties, Object> propertyUpdater;
private static final Set<String> PROPERTY_NAMES = Stream.of(SolverProperty.values())
.map(SolverProperty::getPropertyName)
.collect(Collectors.toCollection(TreeSet::new));
<T> SolverProperty(String propertyName, BiConsumer<SolverProperties, T> propertySetter,
Function<Object, T> propertyConvertor) {
this.propertyName = propertyName;
this.propertyUpdater = (properties, object) -> propertySetter.accept(properties, propertyConvertor.apply(object));
}
public String getPropertyName() {
return propertyName;
}
public void update(SolverProperties properties, Object value) {
propertyUpdater.accept(properties, value);
}
public static Set<String> getValidPropertyNames() {
return Collections.unmodifiableSet(PROPERTY_NAMES);
}
public static SolverProperty forPropertyName(String propertyName) {
for (var property : values()) {
if (property.getPropertyName().equals(propertyName)) {
return property;
}
}
throw new IllegalArgumentException("No property with the name (%s). Valid properties are %s."
.formatted(propertyName, PROPERTY_NAMES));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/config/TerminationProperties.java | package ai.timefold.solver.spring.boot.autoconfigure.config;
import java.time.Duration;
import java.util.Map;
import java.util.TreeSet;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
public class TerminationProperties {
/**
* How long the solver can run.
* For example: "30s" is 30 seconds. "5m" is 5 minutes. "2h" is 2 hours. "1d" is 1 day.
* Also supports ISO-8601 format, see java.time.Duration.
*/
private Duration spentLimit;
/**
* How long the solver can run without finding a new best solution after finding a new best solution.
* For example: "30s" is 30 seconds. "5m" is 5 minutes. "2h" is 2 hours. "1d" is 1 day.
* Also supports ISO-8601 format, see java.time.Duration.
*/
private Duration unimprovedSpentLimit;
/**
* Terminates the solver when a specific or higher score has been reached.
* For example: "0hard/-1000soft" terminates when the best score changes from "0hard/-1200soft" to "0hard/-900soft".
* Wildcards are supported to replace numbers.
* For example: "0hard/*soft" to terminate when any feasible score is reached.
*/
private String bestScoreLimit;
@NestedConfigurationProperty
private DiminishedReturnsProperties diminishedReturns;
// ************************************************************************
// Getters/setters
// ************************************************************************
public Duration getSpentLimit() {
return spentLimit;
}
public void setSpentLimit(Duration spentLimit) {
this.spentLimit = spentLimit;
}
public Duration getUnimprovedSpentLimit() {
return unimprovedSpentLimit;
}
public void setUnimprovedSpentLimit(Duration unimprovedSpentLimit) {
this.unimprovedSpentLimit = unimprovedSpentLimit;
}
public String getBestScoreLimit() {
return bestScoreLimit;
}
public void setBestScoreLimit(String bestScoreLimit) {
this.bestScoreLimit = bestScoreLimit;
}
public DiminishedReturnsProperties getDiminishedReturns() {
return diminishedReturns;
}
public void setDiminishedReturns(DiminishedReturnsProperties diminishedReturns) {
this.diminishedReturns = diminishedReturns;
}
public void loadProperties(Map<String, Object> properties) {
// Check if the keys are valid
var invalidKeySet = new TreeSet<>(properties.keySet());
invalidKeySet.removeAll(TerminationProperty.getValidPropertyNames());
if (!invalidKeySet.isEmpty()) {
throw new IllegalStateException("""
The termination properties [%s] are not valid.
Maybe try changing the property name to kebab-case.
Here is the list of valid properties: %s"""
.formatted(invalidKeySet, String.join(", ", TerminationProperty.getValidPropertyNames())));
}
properties.forEach(this::loadProperty);
}
private void loadProperty(String key, Object value) {
if (value == null) {
return;
}
var property = TerminationProperty.forPropertyName(key);
property.update(this, value);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/config/TerminationProperty.java | package ai.timefold.solver.spring.boot.autoconfigure.config;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.boot.convert.DurationStyle;
public enum TerminationProperty {
SPENT_LIMIT("spent-limit", TerminationProperties::setSpentLimit,
value -> DurationStyle.detectAndParse((String) value)),
UNIMPROVED_SPENT_LIMIT("unimproved-spent-limit", TerminationProperties::setUnimprovedSpentLimit,
value -> DurationStyle.detectAndParse((String) value)),
BEST_SCORE_LIMIT("best-score-limit", TerminationProperties::setBestScoreLimit, Object::toString),
DIMINISHED_RETURNS("diminished-returns", TerminationProperties::setDiminishedReturns,
value -> {
var out = new DiminishedReturnsProperties();
if (value instanceof Map<?, ?> map) {
out.loadProperties((Map<String, Object>) map);
} else {
throw new IllegalArgumentException("%s is a Map, not a %s."
.formatted("timefold.solver.termination.diminished-returns",
value.getClass().getSimpleName()));
}
return out;
});
private final String propertyName;
private final BiConsumer<TerminationProperties, Object> propertyUpdater;
private static final Set<String> PROPERTY_NAMES = Stream.of(TerminationProperty.values())
.map(TerminationProperty::getPropertyName)
.collect(Collectors.toCollection(TreeSet::new));
<T> TerminationProperty(String propertyName, BiConsumer<TerminationProperties, T> propertySetter,
Function<Object, T> propertyConvertor) {
this.propertyName = propertyName;
this.propertyUpdater = (properties, object) -> propertySetter.accept(properties, propertyConvertor.apply(object));
}
public String getPropertyName() {
return propertyName;
}
public void update(TerminationProperties properties, Object value) {
propertyUpdater.accept(properties, value);
}
public static Set<String> getValidPropertyNames() {
return Collections.unmodifiableSet(PROPERTY_NAMES);
}
public static TerminationProperty forPropertyName(String propertyName) {
for (var property : values()) {
if (property.getPropertyName().equals(propertyName)) {
return property;
}
}
throw new IllegalArgumentException("No property with the name (%s). Valid properties are %s."
.formatted(propertyName, PROPERTY_NAMES));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/config/TimefoldProperties.java | package ai.timefold.solver.spring.boot.autoconfigure.config;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
@ConfigurationProperties(value = "timefold", ignoreUnknownFields = false)
public class TimefoldProperties {
public static final String DEFAULT_SOLVER_CONFIG_URL = "solverConfig.xml";
public static final String DEFAULT_SOLVER_BENCHMARK_CONFIG_URL = "solverBenchmarkConfig.xml";
public static final String DEFAULT_SOLVER_NAME = "default";
@NestedConfigurationProperty
private SolverManagerProperties solverManager;
/**
* A classpath resource to read the solver configuration XML.
* Defaults to solverConfig.xml.
* If this property isn't specified, that file is optional.
*/
private String solverConfigXml;
@NestedConfigurationProperty
private Map<String, SolverProperties> solver;
@NestedConfigurationProperty
private BenchmarkProperties benchmark;
// ************************************************************************
// Getters/setters
// ************************************************************************
public SolverManagerProperties getSolverManager() {
return solverManager;
}
public void setSolverManager(SolverManagerProperties solverManager) {
this.solverManager = solverManager;
}
public String getSolverConfigXml() {
return solverConfigXml;
}
public void setSolverConfigXml(String solverConfigXml) {
this.solverConfigXml = solverConfigXml;
}
public Map<String, SolverProperties> getSolver() {
return solver;
}
public void setSolver(Map<String, Object> solver) {
// Solver properties can be configured for a single solver or multiple solvers. The namespace timefold.solver.*
// defines the default properties for a single solver and timefold.solver.solver-name.* allows configuring
// multiple solvers
this.solver = new HashMap<>();
// Check if it is a single solver
if (SolverProperty.getValidPropertyNames().containsAll(solver.keySet())) {
SolverProperties solverProperties = new SolverProperties();
solverProperties.loadProperties(solver);
this.solver.put(DEFAULT_SOLVER_NAME, solverProperties);
} else {
// The values must be an instance of map
var invalidKeySet = solver.entrySet().stream()
.filter(e -> e.getValue() != null && !(e.getValue() instanceof Map<?, ?>))
.map(Map.Entry::getKey)
.collect(Collectors.toCollection(TreeSet::new));
if (!invalidKeySet.isEmpty()) {
throw new IllegalStateException("""
Cannot use global solver properties with named solvers.
Expected all values to be maps, but values for key(s) %s are not map(s).
Maybe try changing the property name to kebab-case.
Here is the list of valid global solver properties: %s"""
.formatted(invalidKeySet, String.join(", ", SolverProperty.getValidPropertyNames())));
}
// Multiple solvers. We load the properties per key (or solver config)
solver.forEach((key, value) -> {
SolverProperties solverProperties = new SolverProperties();
if (value != null) {
solverProperties.loadProperties((Map<String, Object>) value);
}
this.solver.put(key, solverProperties);
});
}
}
public BenchmarkProperties getBenchmark() {
return benchmark;
}
public void setBenchmark(BenchmarkProperties benchmark) {
this.benchmark = benchmark;
}
public Optional<SolverProperties> getSolverConfig(String solverName) {
return Optional.ofNullable(this.solver).map(s -> s.get(solverName));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure | java-sources/ai/timefold/solver/timefold-solver-spring-boot-autoconfigure/1.26.1/ai/timefold/solver/spring/boot/autoconfigure/util/LambdaUtils.java | package ai.timefold.solver.spring.boot.autoconfigure.util;
import java.util.function.Function;
public class LambdaUtils {
public static <T, R> Function<T, R> rethrowFunction(ThrowingFunction<T, R> throwingFunction) {
return v -> {
try {
return throwingFunction.apply(v);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
};
}
@FunctionalInterface
public interface ThrowingFunction<T, R> {
R apply(T t) throws Exception;
}
private LambdaUtils() {
// No external instances.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score/stream/ConstraintVerifier.java | package ai.timefold.solver.test.api.score.stream;
import static java.util.Objects.requireNonNull;
import java.util.Objects;
import java.util.function.BiFunction;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.score.stream.ConstraintStreamImplType;
import ai.timefold.solver.core.config.solver.SolverConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.test.impl.score.stream.DefaultConstraintVerifier;
import org.jspecify.annotations.NonNull;
/**
* Implementations must be thread-safe, in order to enable parallel test execution.
*
* @param <ConstraintProvider_>
* @param <Solution_>
*/
public interface ConstraintVerifier<ConstraintProvider_ extends ConstraintProvider, Solution_> {
/**
* Entry point to the API.
*
* @param constraintProvider {@link PlanningEntity} used by the {@link PlanningSolution}
* @param planningSolutionClass {@link PlanningSolution}-annotated class associated with the constraints
* @param entityClasses at least one, {@link PlanningEntity} types used by the {@link PlanningSolution}
* @param <ConstraintProvider_> type of the {@link ConstraintProvider}
* @param <Solution_> type of the {@link PlanningSolution}-annotated class
*/
static <ConstraintProvider_ extends ConstraintProvider, Solution_>
@NonNull ConstraintVerifier<ConstraintProvider_, Solution_> build(
@NonNull ConstraintProvider_ constraintProvider,
@NonNull Class<Solution_> planningSolutionClass, @NonNull Class<?> @NonNull... entityClasses) {
requireNonNull(constraintProvider);
var solutionDescriptor = SolutionDescriptor
.buildSolutionDescriptor(requireNonNull(planningSolutionClass), entityClasses);
return new DefaultConstraintVerifier<>(constraintProvider, solutionDescriptor);
}
/**
* Uses a {@link SolverConfig} to build a {@link ConstraintVerifier}.
* Alternative to {@link #build(ConstraintProvider, Class, Class[])}.
*
* @param solverConfig must have a {@link PlanningSolution} class, {@link PlanningEntity} classes
* and a {@link ConstraintProvider} configured.
* @param <ConstraintProvider_> type of the {@link ConstraintProvider}
* @param <Solution_> type of the {@link PlanningSolution}-annotated class
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
static <ConstraintProvider_ extends ConstraintProvider, Solution_>
@NonNull ConstraintVerifier<ConstraintProvider_, Solution_>
create(@NonNull SolverConfig solverConfig) {
var nonNullSolverConfig = requireNonNull(solverConfig);
var entityClassList = Objects.requireNonNull(nonNullSolverConfig.getEntityClassList());
var solutionDescriptor =
SolutionDescriptor.buildSolutionDescriptor(
nonNullSolverConfig.getEnablePreviewFeatureSet(),
requireNonNull(nonNullSolverConfig.getSolutionClass()),
entityClassList.toArray(new Class<?>[] {}));
var scoreDirectorFactoryConfig = requireNonNull(nonNullSolverConfig.getScoreDirectorFactoryConfig());
var constraintProviderClass = requireNonNull(scoreDirectorFactoryConfig.getConstraintProviderClass());
var constraintProvider = ConfigUtils.newInstance(scoreDirectorFactoryConfig::toString, "constraintProviderClass",
constraintProviderClass);
ConfigUtils.applyCustomProperties(constraintProvider, "constraintProviderClass",
scoreDirectorFactoryConfig.getConstraintProviderCustomProperties(), "constraintProviderCustomProperties");
return new DefaultConstraintVerifier(constraintProvider, solutionDescriptor);
}
/**
* All subsequent calls to {@link #verifyThat(BiFunction)} and {@link #verifyThat()}
* use the given {@link ConstraintStreamImplType}.
*
* @return this
* @deprecated There is only one implementation, so this method is deprecated.
* This method no longer has any effect.
*/
@NonNull
@Deprecated(forRemoval = true, since = "1.16.0")
default ConstraintVerifier<ConstraintProvider_, Solution_> withConstraintStreamImplType(
@NonNull ConstraintStreamImplType constraintStreamImplType) {
return this;
}
/**
* Creates a constraint verifier for a given {@link Constraint} of the {@link ConstraintProvider}.
*/
@NonNull
SingleConstraintVerification<Solution_> verifyThat(
@NonNull BiFunction<ConstraintProvider_, ConstraintFactory, Constraint> constraintFunction);
/**
* Creates a constraint verifier for all constraints of the {@link ConstraintProvider}.
*/
@NonNull
MultiConstraintVerification<Solution_> verifyThat();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score/stream/MultiConstraintAssertion.java | package ai.timefold.solver.test.api.score.stream;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
public interface MultiConstraintAssertion {
/**
* Asserts that the {@link ConstraintProvider} under test, given a set of facts, results in a specific {@link Score}.
*
* @param score total score calculated for the given set of facts
* @throws AssertionError when the expected score does not match the calculated score
*/
default void scores(@NonNull Score<?> score) {
scores(score, null);
}
/**
* As defined by {@link #scores(Score)}.
*
* @param score total score calculated for the given set of facts
* @param message description of the scenario being asserted
* @throws AssertionError when the expected score does not match the calculated score
*/
void scores(@NonNull Score<?> score, @Nullable String message);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score/stream/MultiConstraintVerification.java | package ai.timefold.solver.test.api.score.stream;
import org.jspecify.annotations.NonNull;
public interface MultiConstraintVerification<Solution_> {
/**
* As defined by {@link SingleConstraintVerification#given(Object...)}.
*
* @param facts at least one
*/
@NonNull
MultiConstraintAssertion given(@NonNull Object @NonNull... facts);
/**
* As defined by {@link SingleConstraintVerification#givenSolution(Object)}.
*/
@NonNull
ShadowVariableAwareMultiConstraintAssertion givenSolution(@NonNull Solution_ solution);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score/stream/ShadowVariableAwareMultiConstraintAssertion.java | package ai.timefold.solver.test.api.score.stream;
public interface ShadowVariableAwareMultiConstraintAssertion extends MultiConstraintAssertion {
/**
* The method allows the code under test that uses any type of shadow variables
* to execute all related listeners and update the planning entities.
* As a result, all shadow variables associated with the given solution will be updated.
*/
MultiConstraintAssertion settingAllShadowVariables();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score/stream/ShadowVariableAwareSingleConstraintAssertion.java | package ai.timefold.solver.test.api.score.stream;
public interface ShadowVariableAwareSingleConstraintAssertion extends SingleConstraintAssertion {
/**
* The method allows the code under test that uses any type of shadow variables
* to execute all related listeners and update the planning entities.
* As a result, all shadow variables associated with the given solution will be updated.
*/
SingleConstraintAssertion settingAllShadowVariables();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score/stream/SingleConstraintAssertion.java | package ai.timefold.solver.test.api.score.stream;
import java.math.BigDecimal;
import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
public interface SingleConstraintAssertion {
/**
* As defined by {@link #justifiesWith(ConstraintJustification...)}.
*
* @param justifications the expected justification.
* @param message description of the scenario being asserted
* @throws AssertionError when the expected penalty is not observed
*/
@NonNull
SingleConstraintAssertion justifiesWith(@Nullable String message,
@NonNull ConstraintJustification @NonNull... justifications);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts, results in a given
* {@link ConstraintJustification}.
*
* @param justifications the expected justifications.
* @throws AssertionError when the expected penalty is not observed
*/
default @NonNull SingleConstraintAssertion justifiesWith(@NonNull ConstraintJustification @NonNull... justifications) {
return justifiesWith(null, justifications);
}
/**
* As defined by {@link #justifiesWithExactly(ConstraintJustification...)}.
*
* @param justifications the expected justification.
* @param message description of the scenario being asserted
* @throws AssertionError when the expected penalty is not observed
*/
@NonNull
SingleConstraintAssertion justifiesWithExactly(@Nullable String message,
@NonNull ConstraintJustification @NonNull... justifications);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts, results in a given
* {@link ConstraintJustification} and nothing else.
*
* @param justifications the expected justifications.
* @throws AssertionError when the expected penalty is not observed
*/
default @NonNull SingleConstraintAssertion
justifiesWithExactly(@NonNull ConstraintJustification @NonNull... justifications) {
return justifiesWithExactly(null, justifications);
}
/**
* Asserts that the {@link Constraint} being tested, given a set of facts, results in the given indictments.
*
* @param indictments the expected indictments.
* @throws AssertionError when the expected penalty is not observed
*/
default @NonNull SingleConstraintAssertion indictsWith(@NonNull Object @NonNull... indictments) {
return indictsWith(null, indictments);
}
/**
* As defined by {@link #indictsWith(Object...)}.
*
* @param message description of the scenario being asserted
* @param indictments the expected indictments.
* @throws AssertionError when the expected penalty is not observed
*/
@NonNull
SingleConstraintAssertion indictsWith(@Nullable String message, @NonNull Object @NonNull... indictments);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts, results in the given indictments and
* nothing else.
*
* @param indictments the expected indictments.
* @throws AssertionError when the expected penalty is not observed
*/
default @NonNull SingleConstraintAssertion indictsWithExactly(@NonNull Object @NonNull... indictments) {
return indictsWithExactly(null, indictments);
}
/**
* As defined by {@link #indictsWithExactly(Object...)}.
*
* @param message description of the scenario being asserted
* @param indictments the expected indictments.
* @throws AssertionError when the expected penalty is not observed
*/
@NonNull
SingleConstraintAssertion indictsWithExactly(@Nullable String message, @NonNull Object @NonNull... indictments);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts, results in a specific penalty.
* <p>
* Ignores the constraint weight: it only asserts the match weights.
* For example: a match with a match weight of {@code 10} on a constraint with a constraint weight of {@code -2hard}
* reduces the score by {@code -20hard}. In that case, this assertion checks for {@code 10}.
* <p>
* An {@code int matchWeightTotal} automatically casts to {@code long} for {@link HardSoftLongScore long scores}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesBy(int matchWeightTotal) {
penalizesBy(null, matchWeightTotal);
}
/**
* As defined by {@link #penalizesBy(int)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @param message sometimes null, description of the scenario being asserted
* @throws AssertionError when the expected penalty is not observed
* @deprecated Use {@link #penalizesBy(String, int)} instead.
*/
@Deprecated(forRemoval = true, since = "1.8.0")
default void penalizesBy(int matchWeightTotal, String message) {
penalizesBy(message, matchWeightTotal);
}
/**
* As defined by {@link #penalizesBy(int)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
void penalizesBy(@Nullable String message, int matchWeightTotal);
/**
* As defined by {@link #penalizesBy(int)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesBy(long matchWeightTotal) {
penalizesBy(null, matchWeightTotal);
}
/**
* As defined by {@link #penalizesBy(long)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @param message sometimes null, description of the scenario being asserted
* @throws AssertionError when the expected penalty is not observed
*
* @deprecated Use {@link #penalizesBy(String, long)} instead.
*/
@Deprecated(forRemoval = true, since = "1.8.0")
default void penalizesBy(long matchWeightTotal, String message) {
penalizesBy(message, matchWeightTotal);
}
/**
* As defined by {@link #penalizesBy(long)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
void penalizesBy(@Nullable String message, long matchWeightTotal);
/**
* As defined by {@link #penalizesBy(long)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesBy(@NonNull BigDecimal matchWeightTotal) {
penalizesBy(null, matchWeightTotal);
}
/**
* As defined by {@link #penalizesBy(BigDecimal)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @param message sometimes null, description of the scenario being asserted
* @throws AssertionError when the expected penalty is not observed
*
* @deprecated Use {@link #penalizesBy(String, BigDecimal)} instead.
*/
@Deprecated(forRemoval = true, since = "1.8.0")
default void penalizesBy(BigDecimal matchWeightTotal, String message) {
penalizesBy(message, matchWeightTotal);
}
/**
* As defined by {@link #penalizesBy(BigDecimal)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
void penalizesBy(@Nullable String message, @NonNull BigDecimal matchWeightTotal);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts, results in a given number of penalties.
* <p>
* Ignores the constraint and match weights: it only asserts the number of matches
* For example: if there are two matches with weight of {@code 10} each, this assertion will check for 2 matches.
*
* @param times at least 0, expected number of times that the constraint will penalize
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizes(long times) {
penalizes(null, times);
}
/**
* As defined by {@link #penalizes(long)}.
*
* @param times at least 0, expected number of times that the constraint will penalize
* @param message sometimes null, description of the scenario being asserted
* @throws AssertionError when the expected penalty is not observed
*
* @deprecated Use {@link #penalizes(String, long)} instead.
*/
@Deprecated(forRemoval = true, since = "1.8.0")
default void penalizes(long times, String message) {
penalizes(message, times);
}
/**
* As defined by {@link #penalizes(long)}.
*
* @param message description of the scenario being asserted
* @param times at least 0, expected number of times that the constraint will penalize
* @throws AssertionError when the expected penalty is not observed
*/
void penalizes(@Nullable String message, long times);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts, results in any number of penalties.
* <p>
* Ignores the constraint and match weights: it only asserts the number of matches
* For example: if there are two matches with weight of {@code 10} each, this assertion will succeed.
* If there are no matches, it will fail.
*
* @throws AssertionError when there are no penalties
*/
default void penalizes() {
penalizes(null);
}
/**
* As defined by {@link #penalizes()}.
*
* @param message description of the scenario being asserted
* @throws AssertionError when there are no penalties
*/
void penalizes(@Nullable String message);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts, results in a specific reward.
* <p>
* Ignores the constraint weight: it only asserts the match weights.
* For example: a match with a match weight of {@code 10} on a constraint with a constraint weight of {@code -2hard}
* reduces the score by {@code -20hard}. In that case, this assertion checks for {@code 10}.
* <p>
* An {@code int matchWeightTotal} automatically casts to {@code long} for {@link HardSoftLongScore long scores}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
default void rewardsWith(int matchWeightTotal) {
rewardsWith(null, matchWeightTotal);
}
/**
* As defined by {@link #rewardsWith(int)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @param message sometimes null, description of the scenario being asserted
* @throws AssertionError when the expected reward is not observed
*
* @deprecated Use {@link #rewardsWith(String, int)} instead.
*/
@Deprecated(forRemoval = true, since = "1.8.0")
default void rewardsWith(int matchWeightTotal, String message) {
rewardsWith(message, matchWeightTotal);
}
/**
* As defined by {@link #rewardsWith(int)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
void rewardsWith(@Nullable String message, int matchWeightTotal);
/**
* As defined by {@link #rewardsWith(int)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
default void rewardsWith(long matchWeightTotal) {
rewardsWith(null, matchWeightTotal);
}
/**
* As defined by {@link #rewardsWith(long)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @param message sometimes null, description of the scenario being asserted
* @throws AssertionError when the expected reward is not observed
*
* @deprecated Use {@link #rewardsWith(String, long)} instead.
*/
@Deprecated(forRemoval = true, since = "1.8.0")
default void rewardsWith(long matchWeightTotal, String message) {
rewardsWith(message, matchWeightTotal);
}
/**
* As defined by {@link #rewardsWith(long)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
void rewardsWith(@Nullable String message, long matchWeightTotal);
/**
* As defined by {@link #rewardsWith(int)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
default void rewardsWith(@NonNull BigDecimal matchWeightTotal) {
rewardsWith(null, matchWeightTotal);
}
/**
* As defined by {@link #rewardsWith(BigDecimal)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @param message sometimes null, description of the scenario being asserted
* @throws AssertionError when the expected reward is not observed
*
* @deprecated Use {@link #rewardsWith(String, BigDecimal)} instead.
*/
@Deprecated(forRemoval = true, since = "1.8.0")
default void rewardsWith(BigDecimal matchWeightTotal, String message) {
rewardsWith(message, matchWeightTotal);
}
/**
* As defined by {@link #rewardsWith(BigDecimal)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
void rewardsWith(@Nullable String message, @NonNull BigDecimal matchWeightTotal);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts, results in a given number of rewards.
* <p>
* Ignores the constraint and match weights: it only asserts the number of matches
* For example: if there are two matches with weight of {@code 10} each, this assertion will check for 2 matches.
*
* @param times at least 0, expected number of times that the constraint will reward
* @throws AssertionError when the expected reward is not observed
*/
default void rewards(long times) {
rewards(null, times);
}
/**
* As defined by {@link #rewards(long)}.
*
* @param times at least 0, expected number of times that the constraint will reward
* @param message sometimes null, description of the scenario being asserted
* @throws AssertionError when the expected reward is not observed
*
* @deprecated Use {@link #rewards(String, long)} instead.
*/
@Deprecated(forRemoval = true, since = "1.8.0")
default void rewards(long times, String message) {
rewards(message, times);
}
/**
* As defined by {@link #rewards(long)}.
*
* @param message description of the scenario being asserted
* @param times at least 0, expected number of times that the constraint will reward
* @throws AssertionError when the expected reward is not observed
*/
void rewards(@Nullable String message, long times);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts, results in any number of rewards.
* <p>
* Ignores the constraint and match weights: it only asserts the number of matches
* For example: if there are two matches with weight of {@code 10} each, this assertion will succeed.
* If there are no matches, it will fail.
*
* @throws AssertionError when there are no rewards
*/
default void rewards() {
rewards(null);
}
/**
* As defined by {@link #rewards()}.
*
* @param message description of the scenario being asserted
* @throws AssertionError when there are no rewards
*/
void rewards(@Nullable String message);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts,
* results in a specific penalty larger than given.
* <p>
* Ignores the constraint weight: it only asserts the match weights.
* For example:
* a match with a match weight of {@code 10} on a constraint with a constraint weight of {@code -2hard}
* reduces the score by {@code -20hard}.
* In that case, this assertion checks for {@code 10}.
* <p>
* An {@code int matchWeightTotal} automatically casts to {@code long} for {@link HardSoftLongScore long scores}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesByMoreThan(int matchWeightTotal) {
penalizesByMoreThan(null, matchWeightTotal);
}
/**
* As defined by {@link #penalizesByMoreThan(int)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
void penalizesByMoreThan(@Nullable String message, int matchWeightTotal);
/**
* As defined by {@link #penalizesByMoreThan(int)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesByMoreThan(long matchWeightTotal) {
penalizesByMoreThan(null, matchWeightTotal);
}
/**
* As defined by {@link #penalizesByMoreThan(long)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
void penalizesByMoreThan(@Nullable String message, long matchWeightTotal);
/**
* As defined by {@link #penalizesByMoreThan(long)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesByMoreThan(@NonNull BigDecimal matchWeightTotal) {
penalizesByMoreThan(null, matchWeightTotal);
}
/**
* As defined by {@link #penalizesByMoreThan(BigDecimal)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
void penalizesByMoreThan(@Nullable String message, @NonNull BigDecimal matchWeightTotal);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts,
* results in a number of rewards larger than given.
* <p>
* Ignores the constraint and match weights: it only asserts the number of matches.
* For example:
* if there are two matches with weight of {@code 10} each,
* this assertion will check for 2 matches.
*
* @param times at least 0, expected number of times that the constraint will penalize
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesMoreThan(long times) {
penalizesMoreThan(null, times);
}
/**
* As defined by {@link #penalizesMoreThan(long)}.
*
* @param message description of the scenario being asserted
* @param times at least 0, expected number of times that the constraint will penalize
* @throws AssertionError when the expected penalty is not observed
*/
void penalizesMoreThan(@Nullable String message, long times);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts,
* results in a specific reward larger than given.
* <p>
* Ignores the constraint weight: it only asserts the match weights.
* For example: a match with a match weight of {@code 10} on a constraint with a constraint weight of {@code -2hard}
* reduces the score by {@code -20hard}.
* In that case, this assertion checks for {@code 10}.
* <p>
* An {@code int matchWeightTotal} automatically casts to {@code long} for {@link HardSoftLongScore long scores}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
default void rewardsWithMoreThan(int matchWeightTotal) {
rewardsWithMoreThan(null, matchWeightTotal);
}
/**
* As defined by {@link #rewardsWithMoreThan(int)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
void rewardsWithMoreThan(@Nullable String message, int matchWeightTotal);
/**
* As defined by {@link #rewardsWithMoreThan(int)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
default void rewardsWithMoreThan(long matchWeightTotal) {
rewardsWithMoreThan(null, matchWeightTotal);
}
/**
* As defined by {@link #rewardsWithMoreThan(long)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
void rewardsWithMoreThan(@Nullable String message, long matchWeightTotal);
/**
* As defined by {@link #rewardsWithMoreThan(int)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
default void rewardsWithMoreThan(@NonNull BigDecimal matchWeightTotal) {
rewardsWithMoreThan(null, matchWeightTotal);
}
/**
* As defined by {@link #rewardsWithMoreThan(BigDecimal)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
void rewardsWithMoreThan(@Nullable String message, @NonNull BigDecimal matchWeightTotal);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts,
* results in a number of rewards larger than given.
* <p>
* Ignores the constraint and match weights: it only asserts the number of matches
* For example:
* if there are two matches with weight of {@code 10} each,
* this assertion will check for 2 matches.
*
* @param times at least 0, expected number of times that the constraint will reward
* @throws AssertionError when the expected reward is not observed
*/
default void rewardsMoreThan(long times) {
rewardsMoreThan(null, times);
}
/**
* As defined by {@link #rewardsMoreThan(long)}.
*
* @param message description of the scenario being asserted
* @param times at least 0, expected number of times that the constraint will reward
* @throws AssertionError when the expected reward is not observed
*/
void rewardsMoreThan(@Nullable String message, long times);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts,
* results in a specific penalty smaller than given.
* <p>
* Ignores the constraint weight: it only asserts the match weights.
* For example:
* a match with a match weight of {@code 10} on a constraint with a constraint weight of {@code -2hard}
* reduces the score by {@code -20hard}.
* In that case, this assertion checks for {@code 10}.
* <p>
* An {@code int matchWeightTotal} automatically casts to {@code long} for {@link HardSoftLongScore long scores}.
*
* @param matchWeightTotal at least 1, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesByLessThan(int matchWeightTotal) {
penalizesByLessThan(null, matchWeightTotal);
}
/**
* As defined by {@link #penalizesByLessThan(int)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 1, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
void penalizesByLessThan(@Nullable String message, int matchWeightTotal);
/**
* As defined by {@link #penalizesByLessThan(int)}.
*
* @param matchWeightTotal at least 1, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesByLessThan(long matchWeightTotal) {
penalizesByLessThan(null, matchWeightTotal);
}
/**
* As defined by {@link #penalizesByLessThan(long)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 1, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
void penalizesByLessThan(@Nullable String message, long matchWeightTotal);
/**
* As defined by {@link #penalizesByLessThan(long)}.
*
* @param matchWeightTotal at least 1, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesByLessThan(@NonNull BigDecimal matchWeightTotal) {
penalizesByLessThan(null, matchWeightTotal);
}
/**
* As defined by {@link #penalizesByLessThan(BigDecimal)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 1, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected penalty is not observed
*/
void penalizesByLessThan(@Nullable String message, @NonNull BigDecimal matchWeightTotal);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts,
* results in a number of rewards smaller than given.
* <p>
* Ignores the constraint and match weights: it only asserts the number of matches.
* For example:
* if there are two matches with weight of {@code 10} each,
* this assertion will check for 2 matches.
*
* @param times at least 1, expected number of times that the constraint will penalize
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesLessThan(long times) {
penalizesLessThan(null, times);
}
/**
* As defined by {@link #penalizesLessThan(long)}.
*
* @param message description of the scenario being asserted
* @param times at least 1, expected number of times that the constraint will penalize
* @throws AssertionError when the expected penalty is not observed
*/
void penalizesLessThan(@Nullable String message, long times);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts,
* results in a specific reward smaller than given.
* <p>
* Ignores the constraint weight: it only asserts the match weights.
* For example: a match with a match weight of {@code 10} on a constraint with a constraint weight of {@code -2hard}
* reduces the score by {@code -20hard}.
* In that case, this assertion checks for {@code 10}.
* <p>
* An {@code int matchWeightTotal} automatically casts to {@code long} for {@link HardSoftLongScore long scores}.
*
* @param matchWeightTotal at least 1, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
default void rewardsWithLessThan(int matchWeightTotal) {
rewardsWithLessThan(null, matchWeightTotal);
}
/**
* As defined by {@link #rewardsWithLessThan(int)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 1, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
void rewardsWithLessThan(@Nullable String message, int matchWeightTotal);
/**
* As defined by {@link #rewardsWithLessThan(int)}.
*
* @param matchWeightTotal at least 1, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
default void rewardsWithLessThan(long matchWeightTotal) {
rewardsWithLessThan(null, matchWeightTotal);
}
/**
* As defined by {@link #rewardsWithLessThan(long)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 1, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
void rewardsWithLessThan(@Nullable String message, long matchWeightTotal);
/**
* As defined by {@link #rewardsWithLessThan(int)}.
*
* @param matchWeightTotal at least 1, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
default void rewardsWithLessThan(@NonNull BigDecimal matchWeightTotal) {
rewardsWithLessThan(null, matchWeightTotal);
}
/**
* As defined by {@link #rewardsWithLessThan(BigDecimal)}.
*
* @param message description of the scenario being asserted
* @param matchWeightTotal at least 1, expected sum of match weights of matches of the constraint.
* @throws AssertionError when the expected reward is not observed
*/
void rewardsWithLessThan(@Nullable String message, @NonNull BigDecimal matchWeightTotal);
/**
* Asserts that the {@link Constraint} being tested, given a set of facts,
* results in a number of rewards smaller than given.
* <p>
* Ignores the constraint and match weights: it only asserts the number of matches
* For example:
* if there are two matches with weight of {@code 10} each,
* this assertion will check for 2 matches.
*
* @param times at least 1, expected number of times that the constraint will reward
* @throws AssertionError when the expected reward is not observed
*/
default void rewardsLessThan(long times) {
rewardsLessThan(null, times);
}
/**
* As defined by {@link #rewardsLessThan(long)}.
*
* @param message description of the scenario being asserted
* @param times at least 1, expected number of times that the constraint will reward
* @throws AssertionError when the expected reward is not observed
*/
void rewardsLessThan(@Nullable String message, long times);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/score/stream/SingleConstraintVerification.java | package ai.timefold.solver.test.api.score.stream;
import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import org.jspecify.annotations.NonNull;
public interface SingleConstraintVerification<Solution_> {
/**
* If the code under test uses {@link PlanningListVariable},
* the facts provided to this method need to meet either one of the following criteria:
*
* <ul>
* <li>It needs to include both the planning entity and the planning value(s),
* and the planning entity needs to have its list variable correctly filled.</li>
* <li>The planning values need to have their {@link InverseRelationShadowVariable} set to the entity
* with the relevant list variable.</li>
* </ul>
*
* In case none of these are met,
* the values will be reported as unassigned
* and therefore will be filtered out by the {@link ConstraintFactory#forEach(Class)} check.
* {@link ConstraintFactory#forEachIncludingUnassigned(Class)} will include them regardless.
*
* @param facts at least one
*/
@NonNull
SingleConstraintAssertion given(@NonNull Object @NonNull... facts);
@NonNull
ShadowVariableAwareSingleConstraintAssertion givenSolution(@NonNull Solution_ solution);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/solver | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/api/solver/change/MockProblemChangeDirector.java | package ai.timefold.solver.test.api.solver.change;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import ai.timefold.solver.core.api.solver.change.ProblemChangeDirector;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
/**
* Use for unit-testing {@link ai.timefold.solver.core.api.solver.change.ProblemChange}s.
*
* Together with Mockito this class makes it possible to verify that a
* {@link ai.timefold.solver.core.api.solver.change.ProblemChange} implementation correctly calls methods of
* the {@link ProblemChangeDirector}.
*
* Example of usage:
*
* <pre>
* {@code java
* MockProblemChangeDirector mockProblemChangeDirector = spy(new MockProblemChangeDirector());
* ProblemChange problemChange = new MyProblemChange(removedEntity);
* problemChange.doChange(solution, mockProblemChangeDirector);
* verify(mockProblemChangeDirector).removeEntity(same(removedEntity), any());
* }
* </pre>
*/
public class MockProblemChangeDirector implements ProblemChangeDirector {
private Map<Object, Object> lookUpTable = new IdentityHashMap<>();
@Override
public <Entity> void addEntity(@NonNull Entity entity, @NonNull Consumer<Entity> entityConsumer) {
entityConsumer.accept(lookUpWorkingObjectOrFail(entity));
}
@Override
public <Entity> void removeEntity(@NonNull Entity entity, Consumer<Entity> entityConsumer) {
entityConsumer.accept(lookUpWorkingObjectOrFail(entity));
}
@Override
public <Entity> void changeVariable(@NonNull Entity entity, @NonNull String variableName,
@NonNull Consumer<Entity> entityConsumer) {
entityConsumer.accept(lookUpWorkingObjectOrFail(entity));
}
@Override
public <ProblemFact> void addProblemFact(@NonNull ProblemFact problemFact,
@NonNull Consumer<ProblemFact> problemFactConsumer) {
problemFactConsumer.accept(lookUpWorkingObjectOrFail(problemFact));
}
@Override
public <ProblemFact> void removeProblemFact(@NonNull ProblemFact problemFact,
@NonNull Consumer<ProblemFact> problemFactConsumer) {
problemFactConsumer.accept(lookUpWorkingObjectOrFail(problemFact));
}
@Override
public <EntityOrProblemFact> void changeProblemProperty(@NonNull EntityOrProblemFact problemFactOrEntity,
@NonNull Consumer<EntityOrProblemFact> problemFactOrEntityConsumer) {
problemFactOrEntityConsumer.accept(lookUpWorkingObjectOrFail(problemFactOrEntity));
}
/**
* If the look-up result has been provided by a {@link #whenLookingUp(Object)} call, returns the defined object.
* Otherwise, returns the original externalObject.
*
* @param externalObject entity or problem fact to look up
*/
@Override
public <EntityOrProblemFact> @Nullable EntityOrProblemFact
lookUpWorkingObjectOrFail(@Nullable EntityOrProblemFact externalObject) {
EntityOrProblemFact entityOrProblemFact = (EntityOrProblemFact) lookUpTable.get(externalObject);
return entityOrProblemFact == null ? externalObject : entityOrProblemFact;
}
/**
* If the look-up result has been provided by a {@link #whenLookingUp(Object)} call, returns the defined object.
* Otherwise, returns null.
*
* @param externalObject entity or problem fact to look up
*/
@Override
public <EntityOrProblemFact> Optional<EntityOrProblemFact>
lookUpWorkingObject(@Nullable EntityOrProblemFact externalObject) {
return Optional.ofNullable((EntityOrProblemFact) lookUpTable.get(externalObject));
}
@Override
public void updateShadowVariables() {
// Do nothing.
}
/**
* Defines what {@link #lookUpWorkingObjectOrFail(Object)} returns.
*/
public @NonNull LookUpMockBuilder whenLookingUp(Object forObject) {
return new LookUpMockBuilder(forObject);
}
public final class LookUpMockBuilder {
private final Object forObject;
public LookUpMockBuilder(Object forObject) {
this.forObject = forObject;
}
public MockProblemChangeDirector thenReturn(Object returnObject) {
lookUpTable.put(forObject, returnObject);
return MockProblemChangeDirector.this;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/AbstractConstraintAssertion.java | package ai.timefold.solver.test.impl.score.stream;
import java.util.Map;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.api.score.constraint.Indictment;
import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy;
import ai.timefold.solver.core.impl.score.director.InnerScore;
import ai.timefold.solver.core.impl.score.director.stream.BavetConstraintStreamScoreDirector;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
public abstract class AbstractConstraintAssertion<Solution_, Score_ extends Score<Score_>> {
private boolean initialized = false;
private final AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory;
protected AbstractConstraintAssertion(
AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory) {
this.scoreDirectorFactory = scoreDirectorFactory;
}
abstract Solution_ getSolution();
abstract void update(InnerScore<Score_> score, Map<String, ConstraintMatchTotal<Score_>> constraintMatchTotalMap,
Map<Object, Indictment<Score_>> indictmentMap);
/**
* The logic ensures the solution is initialized only once.
* This is necessary because settingAllShadowVariables can also initialize the score and constraint data.
* Therefore, we might miss listener events if we call the initialization steps for an already initialized solution.
*/
void ensureInitialized() {
if (initialized) {
return;
}
// Most score directors don't need derived status; CS will override this.
try (var scoreDirector = scoreDirectorFactory.createScoreDirectorBuilder()
.withConstraintMatchPolicy(ConstraintMatchPolicy.ENABLED)
.buildDerived()) {
// Users use settingAllShadowVariables to set shadow variables
var solution = getSolution();
BavetConstraintStreamScoreDirector<Solution_, Score_> bavetConstraintStreamScoreDirector = null;
if (scoreDirector instanceof BavetConstraintStreamScoreDirector) {
bavetConstraintStreamScoreDirector = (BavetConstraintStreamScoreDirector<Solution_, Score_>) scoreDirector;
}
if (bavetConstraintStreamScoreDirector != null) {
bavetConstraintStreamScoreDirector.updateConsistencyFromSolution(solution);
}
scoreDirector.setWorkingSolutionWithoutUpdatingShadows(solution);
// When models include custom listeners,
// the notification queue may no longer be empty
// because the shadow variable might be linked to a source
// that has changed during the solution initialization.
// As a result,
// any validation using a solution would never work in these cases
// due to an error when calling calculateScore().
// Calling scoreDirector.triggerVariableListeners() runs the custom listeners and clears the queue.
// However, to maintain API consistency,
// we will only trigger the listeners
// if the user opts to use settingAllShadowVariables.
if (bavetConstraintStreamScoreDirector != null) {
bavetConstraintStreamScoreDirector.clearShadowVariablesListenerQueue();
}
update(scoreDirector.calculateScore(), scoreDirector.getConstraintMatchTotalMap(),
scoreDirector.getIndictmentMap());
initialized = true;
}
}
void toggleInitialized() {
this.initialized = true;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/AbstractConstraintVerification.java | package ai.timefold.solver.test.impl.score.stream;
import java.util.Arrays;
import java.util.Collection;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
abstract class AbstractConstraintVerification<Solution_, Score_ extends Score<Score_>> {
protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
protected final AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory;
protected final SessionBasedAssertionBuilder<Solution_, Score_> sessionBasedAssertionBuilder;
AbstractConstraintVerification(AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory) {
this.scoreDirectorFactory = scoreDirectorFactory;
this.sessionBasedAssertionBuilder = new SessionBasedAssertionBuilder<>(scoreDirectorFactory);
}
protected void assertCorrectArguments(Object... facts) {
Class<?> solutionClass = scoreDirectorFactory.getSolutionDescriptor().getSolutionClass();
if (facts.length == 1 && facts[0].getClass() == solutionClass) {
LOGGER.warn("Called given() with the planning solution instance ({}) as an argument." +
"This will treat the solution as a fact, which is likely not intended.\n" +
"Maybe call givenSolution() instead?", facts[0]);
}
Arrays.stream(facts)
.filter(fact -> fact instanceof Collection)
.findFirst()
.ifPresent(collection -> LOGGER.warn("Called given() with collection ({}) as argument." +
"This will treat the collection itself as a fact, and not its contents.\n" +
"Maybe enumerate the contents instead?", collection));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/AbstractMultiConstraintAssertion.java | package ai.timefold.solver.test.impl.score.stream;
import static java.util.Objects.requireNonNull;
import java.util.Collection;
import java.util.Map;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.api.score.constraint.Indictment;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.impl.score.DefaultScoreExplanation;
import ai.timefold.solver.core.impl.score.director.InnerScore;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.test.api.score.stream.MultiConstraintAssertion;
import org.jspecify.annotations.NonNull;
public abstract sealed class AbstractMultiConstraintAssertion<Solution_, Score_ extends Score<Score_>>
extends AbstractConstraintAssertion<Solution_, Score_>
implements MultiConstraintAssertion
permits DefaultMultiConstraintAssertion, DefaultShadowVariableAwareMultiConstraintAssertion {
private final ConstraintProvider constraintProvider;
private InnerScore<Score_> actualScore;
private Collection<ConstraintMatchTotal<Score_>> constraintMatchTotalCollection;
private Collection<Indictment<Score_>> indictmentCollection;
AbstractMultiConstraintAssertion(ConstraintProvider constraintProvider,
AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory) {
super(scoreDirectorFactory);
this.constraintProvider = requireNonNull(constraintProvider);
}
@Override
final void update(InnerScore<Score_> innerScore, Map<String, ConstraintMatchTotal<Score_>> constraintMatchTotalMap,
Map<Object, Indictment<Score_>> indictmentMap) {
this.actualScore = InnerScore.fullyAssigned(requireNonNull(innerScore).raw()); // Strip initialization information.
this.constraintMatchTotalCollection = requireNonNull(constraintMatchTotalMap).values();
this.indictmentCollection = requireNonNull(indictmentMap).values();
toggleInitialized();
}
@Override
public void scores(@NonNull Score<?> score, String message) {
ensureInitialized();
if (actualScore.raw().equals(score)) {
return;
}
var constraintProviderClass = constraintProvider.getClass();
var expectation = message == null ? "Broken expectation." : message;
throw new AssertionError("""
%s
Constraint provider: %s
Expected score: %s (%s)
Actual score: %s (%s)
%s"""
.formatted(expectation, constraintProviderClass, score, score.getClass(), actualScore,
actualScore.getClass(),
DefaultScoreExplanation.explainScore(actualScore, constraintMatchTotalCollection,
indictmentCollection)));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/AbstractSingleConstraintAssertion.java | package ai.timefold.solver.test.impl.score.stream;
import static java.util.Collections.emptyList;
import static java.util.Objects.requireNonNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.api.score.constraint.Indictment;
import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
import ai.timefold.solver.core.impl.score.DefaultScoreExplanation;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.score.director.InnerScore;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.core.impl.score.stream.common.ScoreImpactType;
import ai.timefold.solver.core.impl.util.Pair;
import ai.timefold.solver.test.api.score.stream.SingleConstraintAssertion;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
public abstract sealed class AbstractSingleConstraintAssertion<Solution_, Score_ extends Score<Score_>>
extends AbstractConstraintAssertion<Solution_, Score_>
implements SingleConstraintAssertion
permits DefaultSingleConstraintAssertion, DefaultShadowVariableAwareSingleConstraintAssertion {
private final AbstractConstraint<Solution_, ?, ?> constraint;
private final ScoreDefinition<Score_> scoreDefinition;
private InnerScore<Score_> actualScore;
private Collection<ConstraintMatchTotal<Score_>> constraintMatchTotalCollection;
private Collection<ConstraintJustification> justificationCollection;
private Collection<Indictment<Score_>> indictmentCollection;
@SuppressWarnings("unchecked")
AbstractSingleConstraintAssertion(AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory) {
super(scoreDirectorFactory);
this.constraint = (AbstractConstraint<Solution_, ?, ?>) scoreDirectorFactory.getConstraintMetaModel()
.getConstraints()
.stream()
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Impossible state: no constraint found."));
this.scoreDefinition = scoreDirectorFactory.getScoreDefinition();
}
@Override
final void update(InnerScore<Score_> innerScore, Map<String, ConstraintMatchTotal<Score_>> constraintMatchTotalMap,
Map<Object, Indictment<Score_>> indictmentMap) {
this.actualScore = InnerScore.fullyAssigned(requireNonNull(innerScore).raw()); // Strip initialization information.
this.constraintMatchTotalCollection = new ArrayList<>(requireNonNull(constraintMatchTotalMap).values());
this.indictmentCollection = new ArrayList<>(requireNonNull(indictmentMap).values());
this.justificationCollection = this.constraintMatchTotalCollection.stream()
.flatMap(c -> c.getConstraintMatchSet().stream())
.map(c -> (ConstraintJustification) c.getJustification())
.distinct()
.toList();
toggleInitialized();
}
@Override
public @NonNull SingleConstraintAssertion justifiesWith(String message,
@NonNull ConstraintJustification @NonNull... justifications) {
ensureInitialized();
assertJustification(message, false, justifications);
return this;
}
@Override
public @NonNull SingleConstraintAssertion indictsWith(@Nullable String message, @NonNull Object @NonNull... indictments) {
ensureInitialized();
assertIndictments(message, false, indictments);
return this;
}
@Override
public @NonNull SingleConstraintAssertion justifiesWithExactly(@Nullable String message,
@NonNull ConstraintJustification @NonNull... justifications) {
ensureInitialized();
assertJustification(message, true, justifications);
return this;
}
@Override
public @NonNull SingleConstraintAssertion indictsWithExactly(@Nullable String message,
@NonNull Object @NonNull... indictments) {
ensureInitialized();
assertIndictments(message, true, indictments);
return this;
}
@Override
public void penalizesBy(@Nullable String message, int matchWeightTotal) {
ensureInitialized();
validateMatchWeighTotal(matchWeightTotal);
assertImpact(ScoreImpactType.PENALTY, matchWeightTotal, message);
}
@Override
public void penalizesBy(@Nullable String message, long matchWeightTotal) {
ensureInitialized();
validateMatchWeighTotal(matchWeightTotal);
assertImpact(ScoreImpactType.PENALTY, matchWeightTotal, message);
}
@Override
public void penalizesBy(@Nullable String message, @NonNull BigDecimal matchWeightTotal) {
ensureInitialized();
validateMatchWeighTotal(matchWeightTotal);
assertImpact(ScoreImpactType.PENALTY, matchWeightTotal, message);
}
@Override
public void penalizes(@Nullable String message, long times) {
ensureInitialized();
assertMatchCount(ScoreImpactType.PENALTY, times, message);
}
@Override
public void penalizes(@Nullable String message) {
ensureInitialized();
assertMatch(ScoreImpactType.PENALTY, message);
}
@Override
public void rewardsWith(@Nullable String message, int matchWeightTotal) {
ensureInitialized();
validateMatchWeighTotal(matchWeightTotal);
assertImpact(ScoreImpactType.REWARD, matchWeightTotal, message);
}
@Override
public void rewardsWith(@Nullable String message, long matchWeightTotal) {
ensureInitialized();
validateMatchWeighTotal(matchWeightTotal);
assertImpact(ScoreImpactType.REWARD, matchWeightTotal, message);
}
@Override
public void rewardsWith(@Nullable String message, @NonNull BigDecimal matchWeightTotal) {
ensureInitialized();
validateMatchWeighTotal(matchWeightTotal);
assertImpact(ScoreImpactType.REWARD, matchWeightTotal, message);
}
private static void validateMatchWeighTotal(Number matchWeightTotal) {
if (matchWeightTotal.doubleValue() < 0) {
throw new IllegalArgumentException("The matchWeightTotal (%s) must be positive.".formatted(matchWeightTotal));
}
}
@Override
public void rewards(@Nullable String message, long times) {
ensureInitialized();
assertMatchCount(ScoreImpactType.REWARD, times, message);
}
@Override
public void rewards(String message) {
ensureInitialized();
assertMatch(ScoreImpactType.REWARD, message);
}
@Override
public void penalizesByMoreThan(@Nullable String message, int matchWeightTotal) {
ensureInitialized();
validateMatchWeighTotal(matchWeightTotal);
assertMoreThanImpact(ScoreImpactType.PENALTY, matchWeightTotal, message);
}
@Override
public void penalizesByMoreThan(String message, long matchWeightTotal) {
ensureInitialized();
validateMatchWeighTotal(matchWeightTotal);
assertMoreThanImpact(ScoreImpactType.PENALTY, matchWeightTotal, message);
}
@Override
public void penalizesByMoreThan(@Nullable String message, @NonNull BigDecimal matchWeightTotal) {
ensureInitialized();
validateMatchWeighTotal(matchWeightTotal);
assertMoreThanImpact(ScoreImpactType.PENALTY, matchWeightTotal, message);
}
@Override
public void penalizesMoreThan(@Nullable String message, long times) {
ensureInitialized();
assertMoreThanMatchCount(ScoreImpactType.PENALTY, times, message);
}
@Override
public void rewardsWithMoreThan(@Nullable String message, int matchWeightTotal) {
ensureInitialized();
validateMatchWeighTotal(matchWeightTotal);
assertMoreThanImpact(ScoreImpactType.REWARD, matchWeightTotal, message);
}
@Override
public void rewardsWithMoreThan(@Nullable String message, long matchWeightTotal) {
ensureInitialized();
validateMatchWeighTotal(matchWeightTotal);
assertMoreThanImpact(ScoreImpactType.REWARD, matchWeightTotal, message);
}
@Override
public void rewardsWithMoreThan(@Nullable String message, @NonNull BigDecimal matchWeightTotal) {
ensureInitialized();
validateMatchWeighTotal(matchWeightTotal);
assertMoreThanImpact(ScoreImpactType.REWARD, matchWeightTotal, message);
}
@Override
public void rewardsMoreThan(@Nullable String message, long times) {
ensureInitialized();
assertMoreThanMatchCount(ScoreImpactType.REWARD, times, message);
}
@Override
public void penalizesByLessThan(@Nullable String message, int matchWeightTotal) {
ensureInitialized();
validateLessThanMatchWeighTotal(matchWeightTotal);
assertLessThanImpact(ScoreImpactType.PENALTY, matchWeightTotal, message);
}
@Override
public void penalizesByLessThan(@Nullable String message, long matchWeightTotal) {
ensureInitialized();
validateLessThanMatchWeighTotal(matchWeightTotal);
assertLessThanImpact(ScoreImpactType.PENALTY, matchWeightTotal, message);
}
@Override
public void penalizesByLessThan(@Nullable String message, @NonNull BigDecimal matchWeightTotal) {
ensureInitialized();
validateLessThanMatchWeighTotal(matchWeightTotal);
assertLessThanImpact(ScoreImpactType.PENALTY, matchWeightTotal, message);
}
@Override
public void penalizesLessThan(@Nullable String message, long times) {
ensureInitialized();
validateLessThanMatchCount(times);
assertLessThanMatchCount(ScoreImpactType.PENALTY, times, message);
}
@Override
public void rewardsWithLessThan(@Nullable String message, int matchWeightTotal) {
ensureInitialized();
validateLessThanMatchWeighTotal(matchWeightTotal);
assertLessThanImpact(ScoreImpactType.REWARD, matchWeightTotal, message);
}
@Override
public void rewardsWithLessThan(String message, long matchWeightTotal) {
ensureInitialized();
validateLessThanMatchWeighTotal(matchWeightTotal);
assertLessThanImpact(ScoreImpactType.REWARD, matchWeightTotal, message);
}
@Override
public void rewardsWithLessThan(@Nullable String message, @NonNull BigDecimal matchWeightTotal) {
ensureInitialized();
validateLessThanMatchWeighTotal(matchWeightTotal);
assertLessThanImpact(ScoreImpactType.REWARD, matchWeightTotal, message);
}
private static void validateLessThanMatchWeighTotal(Number matchWeightTotal) {
if (matchWeightTotal.doubleValue() < 1) {
throw new IllegalArgumentException("The matchWeightTotal (%s) must be greater than 0.".formatted(matchWeightTotal));
}
}
@Override
public void rewardsLessThan(String message, long times) {
ensureInitialized();
validateLessThanMatchCount(times);
assertLessThanMatchCount(ScoreImpactType.REWARD, times, message);
}
private static void validateLessThanMatchCount(Number matchCount) {
if (matchCount.doubleValue() < 1) {
throw new IllegalArgumentException("The match count (%s) must be greater than 0.".formatted(matchCount));
}
}
private void assertImpact(ScoreImpactType scoreImpactType, Number matchWeightTotal, String message) {
var equalityPredicate = NumberEqualityUtil.getEqualityPredicate(scoreDefinition, matchWeightTotal);
var deducedImpacts = deduceImpact();
var impact = deducedImpacts.key();
var actualScoreImpactType = constraint.getScoreImpactType();
if (actualScoreImpactType == ScoreImpactType.MIXED) {
// Impact means we need to check for expected impact type and actual impact match.
if (requireNonNull(scoreImpactType) == ScoreImpactType.REWARD) {
var negatedImpact = deducedImpacts.value();
if (equalityPredicate.test(matchWeightTotal, negatedImpact)) {
return;
}
} else if (scoreImpactType == ScoreImpactType.PENALTY && equalityPredicate.test(matchWeightTotal, impact)) {
return;
}
} else if (actualScoreImpactType == scoreImpactType && equalityPredicate.test(matchWeightTotal, impact)) {
// Reward and positive or penalty and negative means all is OK.
return;
}
var constraintId = constraint.getConstraintRef().constraintId();
var assertionMessage = buildAssertionErrorMessage(scoreImpactType, matchWeightTotal, actualScoreImpactType,
impact, constraintId, message);
throw new AssertionError(assertionMessage);
}
private void assertMoreThanImpact(ScoreImpactType scoreImpactType, Number matchWeightTotal, String message) {
var comparator = NumberEqualityUtil.getComparison(matchWeightTotal);
var deducedImpacts = deduceImpact();
var impact = deducedImpacts.key();
var actualScoreImpactType = constraint.getScoreImpactType();
if (actualScoreImpactType == ScoreImpactType.MIXED) {
// Impact means we need to check for expected impact type and actual impact match.
if (requireNonNull(scoreImpactType) == ScoreImpactType.REWARD) {
var negatedImpact = deducedImpacts.value();
if (comparator.compare(matchWeightTotal, negatedImpact) < 0) {
return;
}
} else if (scoreImpactType == ScoreImpactType.PENALTY && comparator.compare(matchWeightTotal, impact) < 0) {
return;
}
} else if (actualScoreImpactType == scoreImpactType && comparator.compare(matchWeightTotal, impact) < 0) {
// Reward and positive or penalty and negative means all is OK.
return;
}
var constraintId = constraint.getConstraintRef().constraintId();
var assertionMessage = buildMoreThanAssertionErrorMessage(scoreImpactType, matchWeightTotal, actualScoreImpactType,
impact, constraintId, message);
throw new AssertionError(assertionMessage);
}
private void assertLessThanImpact(ScoreImpactType scoreImpactType, Number matchWeightTotal, String message) {
var comparator = NumberEqualityUtil.getComparison(matchWeightTotal);
var deducedImpacts = deduceImpact();
var impact = deducedImpacts.key();
var actualScoreImpactType = constraint.getScoreImpactType();
if (actualScoreImpactType == ScoreImpactType.MIXED) {
// Impact means we need to check for expected impact type and actual impact match.
if (requireNonNull(scoreImpactType) == ScoreImpactType.REWARD) {
var negatedImpact = deducedImpacts.value();
if (comparator.compare(matchWeightTotal, negatedImpact) > 0) {
return;
}
} else if (scoreImpactType == ScoreImpactType.PENALTY && comparator.compare(matchWeightTotal, impact) > 0) {
return;
}
} else if (actualScoreImpactType == scoreImpactType && comparator.compare(matchWeightTotal, impact) > 0) {
// Reward and positive or penalty and negative means all is OK.
return;
}
var constraintId = constraint.getConstraintRef().constraintId();
var assertionMessage = buildLessThanAssertionErrorMessage(scoreImpactType, matchWeightTotal, actualScoreImpactType,
impact, constraintId, message);
throw new AssertionError(assertionMessage);
}
private void assertJustification(String message, boolean completeValidation, ConstraintJustification... justifications) {
// Valid empty comparison
var emptyJustifications = justifications == null || justifications.length == 0;
if (emptyJustifications && justificationCollection.isEmpty()) {
return;
}
// No justifications
if (emptyJustifications) {
var assertionMessage = buildAssertionErrorMessage("Justification", constraint.getConstraintRef().constraintId(),
justificationCollection, emptyList(), emptyList(), justificationCollection, message);
throw new AssertionError(assertionMessage);
}
// Empty justifications
if (justificationCollection.isEmpty()) {
var assertionMessage = buildAssertionErrorMessage("Justification", constraint.getConstraintRef().constraintId(),
emptyList(), Arrays.asList(justifications), Arrays.asList(justifications), emptyList(), message);
throw new AssertionError(assertionMessage);
}
var expectedNotFound = new ArrayList<>(justificationCollection.size());
for (var justification : justifications) {
// Test invalid match
if (justificationCollection.stream().noneMatch(justification::equals)) {
expectedNotFound.add(justification);
}
}
List<ConstraintJustification> unexpectedFound = emptyList();
if (completeValidation) {
unexpectedFound = justificationCollection.stream()
.filter(justification -> Stream.of(justifications).noneMatch(justification::equals))
.toList();
}
if (expectedNotFound.isEmpty() && unexpectedFound.isEmpty()) {
return;
}
var assertionMessage = buildAssertionErrorMessage("Justification", constraint.getConstraintRef().constraintId(),
unexpectedFound, expectedNotFound, Arrays.asList(justifications), justificationCollection, message);
throw new AssertionError(assertionMessage);
}
private void assertIndictments(String message, boolean completeValidation, Object... indictments) {
var emptyIndictments = indictments == null || indictments.length == 0;
// Valid empty comparison
if (emptyIndictments && indictmentCollection.isEmpty()) {
return;
}
// No indictments
var indictmentObjectList = indictmentCollection.stream().map(Indictment::getIndictedObject).toList();
if (emptyIndictments && !indictmentObjectList.isEmpty()) {
var assertionMessage = buildAssertionErrorMessage("Indictment", constraint.getConstraintRef().constraintId(),
indictmentObjectList, emptyList(), emptyList(), indictmentObjectList, message);
throw new AssertionError(assertionMessage);
}
// Empty indictments
if (indictmentObjectList.isEmpty()) {
var assertionMessage = buildAssertionErrorMessage("Indictment", constraint.getConstraintRef().constraintId(),
emptyList(), Arrays.asList(indictments), Arrays.asList(indictments), emptyList(), message);
throw new AssertionError(assertionMessage);
}
var expectedNotFound = new ArrayList<>(indictmentObjectList.size());
for (var indictment : indictments) {
// Test invalid match
if (indictmentObjectList.stream().noneMatch(indictment::equals)) {
expectedNotFound.add(indictment);
}
}
var unexpectedFound = emptyList();
if (completeValidation) {
unexpectedFound = indictmentObjectList.stream()
.filter(indictment -> Arrays.stream(indictments).noneMatch(indictment::equals))
.toList();
}
if (expectedNotFound.isEmpty() && unexpectedFound.isEmpty()) {
return;
}
var assertionMessage = buildAssertionErrorMessage("Indictment", constraint.getConstraintRef().constraintId(),
unexpectedFound, expectedNotFound, Arrays.asList(indictments), indictmentObjectList, message);
throw new AssertionError(assertionMessage);
}
/**
* Returns sum total of constraint match impacts,
* deduced from constraint matches.
*
* @return never null; key is the deduced impact, the value its negation
*/
private Pair<Number, Number> deduceImpact() {
var zeroScore = scoreDefinition.getZeroScore();
var zero = zeroScore.toLevelNumbers()[0]; // Zero in the exact numeric type expected by the caller.
if (constraintMatchTotalCollection.isEmpty()) {
return new Pair<>(zero, zero);
}
// We do not know the matchWeight, so we need to deduce it.
// Constraint matches give us a score, whose levels are in the form of (matchWeight * constraintWeight).
// Here, we strip the constraintWeight.
var totalMatchWeightedScore = constraintMatchTotalCollection.stream()
.map(matchScore -> scoreDefinition.divideBySanitizedDivisor(matchScore.getScore(),
matchScore.getConstraintWeight()))
.reduce(zeroScore, Score::add);
// Each level of the resulting score now has to be the same number, the matchWeight.
// Except for where the number is zero.
var deducedImpact = retrieveImpact(totalMatchWeightedScore, zero);
if (deducedImpact.equals(zero)) {
return new Pair<>(zero, zero);
}
var negatedDeducedImpact = retrieveImpact(totalMatchWeightedScore.negate(), zero);
return new Pair<>(deducedImpact, negatedDeducedImpact);
}
private Number retrieveImpact(Score_ score, Number zero) {
var levelNumbers = score.toLevelNumbers();
var impacts = Arrays.stream(levelNumbers)
.distinct()
.filter(matchWeight -> !Objects.equals(matchWeight, zero))
.toList();
return switch (impacts.size()) {
case 0 -> zero;
case 1 -> impacts.get(0);
default -> throw new IllegalStateException(
"Impossible state: expecting at most one match weight (%d) in matchWeightedScore level numbers (%s)."
.formatted(impacts.size(), Arrays.toString(levelNumbers)));
};
}
private void assertMatchCount(ScoreImpactType scoreImpactType, long expectedMatchCount, String message) {
var actualMatchCount = determineMatchCount(scoreImpactType);
if (actualMatchCount == expectedMatchCount) {
return;
}
var constraintId = constraint.getConstraintRef().constraintId();
var assertionMessage =
buildAssertionErrorMessage(scoreImpactType, expectedMatchCount, actualMatchCount, constraintId, message);
throw new AssertionError(assertionMessage);
}
private void assertMoreThanMatchCount(ScoreImpactType scoreImpactType, long expectedMatchCount, String message) {
var actualMatchCount = determineMatchCount(scoreImpactType);
if (actualMatchCount > expectedMatchCount) {
return;
}
var constraintId = constraint.getConstraintRef().constraintId();
var assertionMessage = buildMoreThanAssertionErrorMessage(scoreImpactType, expectedMatchCount, actualMatchCount,
constraintId, message);
throw new AssertionError(assertionMessage);
}
private void assertLessThanMatchCount(ScoreImpactType scoreImpactType, long expectedMatchCount, String message) {
var actualMatchCount = determineMatchCount(scoreImpactType);
if (actualMatchCount < expectedMatchCount) {
return;
}
var constraintId = constraint.getConstraintRef().constraintId();
var assertionMessage = buildLessThanAssertionErrorMessage(scoreImpactType, expectedMatchCount, actualMatchCount,
constraintId, message);
throw new AssertionError(assertionMessage);
}
private void assertMatch(ScoreImpactType scoreImpactType, String message) {
if (determineMatchCount(scoreImpactType) > 0) {
return;
}
var constraintId = constraint.getConstraintRef().constraintId();
var assertionMessage = buildAssertionErrorMessage(scoreImpactType, constraintId, message);
throw new AssertionError(assertionMessage);
}
private long determineMatchCount(ScoreImpactType scoreImpactType) {
if (constraintMatchTotalCollection.isEmpty()) {
return 0;
}
var actualImpactType = constraint.getScoreImpactType();
if (actualImpactType != scoreImpactType && actualImpactType != ScoreImpactType.MIXED) {
return 0;
}
var zeroScore = scoreDefinition.getZeroScore();
return constraintMatchTotalCollection.stream()
.mapToLong(constraintMatchTotal -> {
if (actualImpactType == ScoreImpactType.MIXED) {
var isImpactPositive = constraintMatchTotal.getScore().compareTo(zeroScore) > 0;
var isImpactNegative = constraintMatchTotal.getScore().compareTo(zeroScore) < 0;
if (isImpactPositive && scoreImpactType == ScoreImpactType.PENALTY) {
return constraintMatchTotal.getConstraintMatchSet().size();
} else if (isImpactNegative && scoreImpactType == ScoreImpactType.REWARD) {
return constraintMatchTotal.getConstraintMatchSet().size();
} else {
return 0;
}
} else {
return constraintMatchTotal.getConstraintMatchSet().size();
}
})
.sum();
}
private String buildAssertionErrorMessage(ScoreImpactType expectedImpactType, Number expectedImpact,
ScoreImpactType actualImpactType, Number actualImpact, String constraintId, String message) {
var expectation = message != null ? message : "Broken expectation.";
var preformattedMessage = "%s%n%18s: %s%n%18s: %s (%s)%n%18s: %s (%s)%n%n %s";
var expectedImpactLabel = "Expected " + getImpactTypeLabel(expectedImpactType);
var actualImpactLabel = "Actual " + getImpactTypeLabel(actualImpactType);
return String.format(preformattedMessage,
expectation,
"Constraint", constraintId,
expectedImpactLabel, expectedImpact, expectedImpact.getClass(),
actualImpactLabel, actualImpact, actualImpact.getClass(),
DefaultScoreExplanation.explainScore(actualScore, constraintMatchTotalCollection, indictmentCollection));
}
private String buildMoreThanAssertionErrorMessage(ScoreImpactType expectedImpactType, Number expectedImpact,
ScoreImpactType actualImpactType, Number actualImpact, String constraintId, String message) {
return buildMoreOrLessThanAssertionErrorMessage(expectedImpactType, "more than", expectedImpact, actualImpactType,
actualImpact, constraintId, message);
}
private String buildLessThanAssertionErrorMessage(ScoreImpactType expectedImpactType, Number expectedImpact,
ScoreImpactType actualImpactType, Number actualImpact, String constraintId, String message) {
return buildMoreOrLessThanAssertionErrorMessage(expectedImpactType, "less than", expectedImpact, actualImpactType,
actualImpact, constraintId, message);
}
private String buildMoreOrLessThanAssertionErrorMessage(ScoreImpactType expectedImpactType, String moreOrLessThan,
Number expectedImpact, ScoreImpactType actualImpactType, Number actualImpact, String constraintId, String message) {
var expectation = message != null ? message : "Broken expectation.";
var preformattedMessage = "%s%n%28s: %s%n%28s: %s (%s)%n%28s: %s (%s)%n%n %s";
var expectedImpactLabel = "Expected " + getImpactTypeLabel(expectedImpactType) + " " + moreOrLessThan;
var actualImpactLabel = "Actual " + getImpactTypeLabel(actualImpactType);
return String.format(preformattedMessage,
expectation,
"Constraint", constraintId,
expectedImpactLabel, expectedImpact, expectedImpact.getClass(),
actualImpactLabel, actualImpact, actualImpact.getClass(),
DefaultScoreExplanation.explainScore(actualScore, constraintMatchTotalCollection, indictmentCollection));
}
private String buildAssertionErrorMessage(ScoreImpactType impactType, long expectedTimes, long actualTimes,
String constraintId, String message) {
var expectation = message != null ? message : "Broken expectation.";
var preformattedMessage = "%s%n%18s: %s%n%18s: %s time(s)%n%18s: %s time(s)%n%n %s";
var expectedImpactLabel = "Expected " + getImpactTypeLabel(impactType);
var actualImpactLabel = "Actual " + getImpactTypeLabel(impactType);
return String.format(preformattedMessage,
expectation,
"Constraint", constraintId,
expectedImpactLabel, expectedTimes,
actualImpactLabel, actualTimes,
DefaultScoreExplanation.explainScore(actualScore, constraintMatchTotalCollection, indictmentCollection));
}
private String buildMoreThanAssertionErrorMessage(ScoreImpactType impactType, long expectedTimes, long actualTimes,
String constraintId, String message) {
return buildMoreOrLessThanAssertionErrorMessage(impactType, "more than", expectedTimes, actualTimes, constraintId,
message);
}
private String buildLessThanAssertionErrorMessage(ScoreImpactType impactType, long expectedTimes, long actualTimes,
String constraintId, String message) {
return buildMoreOrLessThanAssertionErrorMessage(impactType, "less than", expectedTimes, actualTimes, constraintId,
message);
}
private String buildMoreOrLessThanAssertionErrorMessage(ScoreImpactType impactType, String moreOrLessThan,
long expectedTimes, long actualTimes,
String constraintId, String message) {
var expectation = message != null ? message : "Broken expectation.";
var preformattedMessage = "%s%n%28s: %s%n%28s: %s time(s)%n%28s: %s time(s)%n%n %s";
var expectedImpactLabel = "Expected " + getImpactTypeLabel(impactType) + " " + moreOrLessThan;
var actualImpactLabel = "Actual " + getImpactTypeLabel(impactType);
return String.format(preformattedMessage,
expectation,
"Constraint", constraintId,
expectedImpactLabel, expectedTimes,
actualImpactLabel, actualTimes,
DefaultScoreExplanation.explainScore(actualScore, constraintMatchTotalCollection, indictmentCollection));
}
private String buildAssertionErrorMessage(ScoreImpactType impactType, String constraintId, String message) {
var expectation = message != null ? message : "Broken expectation.";
var preformattedMessage = "%s%n%18s: %s%n%18s but there was none.%n%n %s";
var expectedImpactLabel = "Expected " + getImpactTypeLabel(impactType);
return String.format(preformattedMessage,
expectation,
"Constraint", constraintId,
expectedImpactLabel,
DefaultScoreExplanation.explainScore(actualScore, constraintMatchTotalCollection, indictmentCollection));
}
private static String buildAssertionErrorMessage(String type, String constraintId, Collection<?> unexpectedFound,
Collection<?> expectedNotFound, Collection<?> expectedCollection, Collection<?> actualCollection,
String message) {
var expectation = message != null ? message : "Broken expectation.";
var preformattedMessage = new StringBuilder("%s%n")
.append("%18s: %s%n");
var params = new ArrayList<>();
params.add(expectation);
params.add(type);
params.add(constraintId);
preformattedMessage.append("%24s%n");
params.add("Expected:");
if (expectedCollection.isEmpty()) {
preformattedMessage.append("%26s%s%n");
params.add("");
params.add("No " + type);
} else {
expectedCollection.forEach(actual -> {
preformattedMessage.append("%26s%s%n");
params.add("");
params.add(actual);
});
}
preformattedMessage.append("%24s%n");
params.add("Actual:");
if (actualCollection.isEmpty()) {
preformattedMessage.append("%26s%s%n");
params.add("");
params.add("No " + type);
} else {
actualCollection.forEach(actual -> {
preformattedMessage.append("%26s%s%n");
params.add("");
params.add(actual);
});
}
if (!expectedNotFound.isEmpty()) {
preformattedMessage.append("%24s%n");
params.add("Expected but not found:");
expectedNotFound.forEach(indictment -> {
preformattedMessage.append("%26s%s%n");
params.add("");
params.add(indictment);
});
}
if (!unexpectedFound.isEmpty()) {
preformattedMessage.append("%24s%n");
params.add("Unexpected but found:");
unexpectedFound.forEach(indictment -> {
preformattedMessage.append("%26s%s%n");
params.add("");
params.add(indictment);
});
}
return String.format(preformattedMessage.toString(), params.toArray());
}
private static String getImpactTypeLabel(ScoreImpactType scoreImpactType) {
if (scoreImpactType == ScoreImpactType.PENALTY) {
return "penalty";
} else if (scoreImpactType == ScoreImpactType.REWARD) {
return "reward";
} else { // Needs to work with null.
return "impact";
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/ConfiguredConstraintVerifier.java | package ai.timefold.solver.test.impl.score.stream;
import static java.util.Objects.requireNonNull;
import java.util.UUID;
import java.util.function.BiFunction;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.test.api.score.stream.ConstraintVerifier;
/**
* Represents a {@link ConstraintVerifier} with pre-set values.
* A new instance of this class will be created should this change.
* <p>
* This class still needs to be thread-safe, as {@link ScoreDirectorFactoryCache} is not.
* Failure to do so will lead to intermittent failures in tests when run in parallel.
*
* @param <ConstraintProvider_>
* @param <Solution_>
* @param <Score_>
*/
final class ConfiguredConstraintVerifier<ConstraintProvider_ extends ConstraintProvider, Solution_, Score_ extends Score<Score_>> {
// Exists so that people can not, even by accident, pick the same constraint ID as the default cache key.
private final ConstraintRef defaultScoreDirectorFactoryMapKey =
ConstraintRef.of(UUID.randomUUID().toString(), UUID.randomUUID().toString());
private final ConstraintProvider_ constraintProvider;
@SuppressWarnings("java:S5164") // Suppress SonarCloud ThreadLocal warning; this is safe in the context of tests.
private final ThreadLocal<ScoreDirectorFactoryCache<ConstraintProvider_, Solution_, Score_>> scoreDirectorFactoryContainerThreadLocal;
public ConfiguredConstraintVerifier(ConstraintProvider_ constraintProvider,
SolutionDescriptor<Solution_> solutionDescriptor) {
this.constraintProvider = constraintProvider;
this.scoreDirectorFactoryContainerThreadLocal =
ThreadLocal.withInitial(() -> new ScoreDirectorFactoryCache<>(solutionDescriptor));
}
public DefaultSingleConstraintVerification<Solution_, Score_> verifyThat(
BiFunction<ConstraintProvider_, ConstraintFactory, Constraint> constraintFunction) {
requireNonNull(constraintFunction);
var scoreDirectorFactory = scoreDirectorFactoryContainerThreadLocal.get().getScoreDirectorFactory(constraintFunction,
constraintProvider, EnvironmentMode.FULL_ASSERT);
return new DefaultSingleConstraintVerification<>(scoreDirectorFactory);
}
public DefaultMultiConstraintVerification<Solution_, Score_> verifyThat() {
var scoreDirectorFactory = scoreDirectorFactoryContainerThreadLocal.get()
.getScoreDirectorFactory(defaultScoreDirectorFactoryMapKey, constraintProvider, EnvironmentMode.FULL_ASSERT);
return new DefaultMultiConstraintVerification<>(scoreDirectorFactory, constraintProvider);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/DefaultConstraintVerifier.java | package ai.timefold.solver.test.impl.score.stream;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.score.stream.ConstraintStreamImplType;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.test.api.score.stream.ConstraintVerifier;
import org.jspecify.annotations.NonNull;
public final class DefaultConstraintVerifier<ConstraintProvider_ extends ConstraintProvider, Solution_, Score_ extends Score<Score_>>
implements ConstraintVerifier<ConstraintProvider_, Solution_> {
private final ConstraintProvider_ constraintProvider;
private final SolutionDescriptor<Solution_> solutionDescriptor;
/**
* {@link ConstraintVerifier} is mutable,
* due to {@link #withConstraintStreamImplType(ConstraintStreamImplType)}.
* Since this method can be run at any time, possibly invalidating the pre-built score director factories,
* the easiest way of dealing with the issue is to keep an internal immutable constraint verifier instance
* and clearing it every time the configuration changes.
* The code that was using the old configuration will continue running on the old instance,
* which will eventually be garbage-collected.
* Any new code will get a new instance with the new configuration applied.
*/
private final AtomicReference<ConfiguredConstraintVerifier<ConstraintProvider_, Solution_, Score_>> configuredConstraintVerifierRef =
new AtomicReference<>();
public DefaultConstraintVerifier(ConstraintProvider_ constraintProvider, SolutionDescriptor<Solution_> solutionDescriptor) {
this.constraintProvider = constraintProvider;
this.solutionDescriptor = solutionDescriptor;
}
// ************************************************************************
// Verify methods
// ************************************************************************
@Override
public @NonNull DefaultSingleConstraintVerification<Solution_, Score_> verifyThat(
@NonNull BiFunction<ConstraintProvider_, ConstraintFactory, Constraint> constraintFunction) {
return getOrCreateConfiguredConstraintVerifier().verifyThat(constraintFunction);
}
private ConfiguredConstraintVerifier<ConstraintProvider_, Solution_, Score_> getOrCreateConfiguredConstraintVerifier() {
return configuredConstraintVerifierRef.updateAndGet(v -> {
if (v == null) {
return new ConfiguredConstraintVerifier<>(constraintProvider, solutionDescriptor);
}
return v;
});
}
@Override
public @NonNull DefaultMultiConstraintVerification<Solution_, Score_> verifyThat() {
return getOrCreateConfiguredConstraintVerifier().verifyThat();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/DefaultMultiConstraintAssertion.java | package ai.timefold.solver.test.impl.score.stream;
import java.util.Map;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.api.score.constraint.Indictment;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.impl.score.director.InnerScore;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
public final class DefaultMultiConstraintAssertion<Solution_, Score_ extends Score<Score_>>
extends AbstractMultiConstraintAssertion<Solution_, Score_> {
DefaultMultiConstraintAssertion(ConstraintProvider constraintProvider,
AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory, Score_ actualScore,
Map<String, ConstraintMatchTotal<Score_>> constraintMatchTotalMap,
Map<Object, Indictment<Score_>> indictmentMap) {
super(constraintProvider, scoreDirectorFactory);
update(InnerScore.fullyAssigned(actualScore), constraintMatchTotalMap, indictmentMap);
}
@Override
Solution_ getSolution() {
throw new IllegalStateException("Impossible state as the solution is initialized at the constructor.");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/DefaultMultiConstraintVerification.java | package ai.timefold.solver.test.impl.score.stream;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.test.api.score.stream.MultiConstraintVerification;
import org.jspecify.annotations.NonNull;
public final class DefaultMultiConstraintVerification<Solution_, Score_ extends Score<Score_>>
extends AbstractConstraintVerification<Solution_, Score_>
implements MultiConstraintVerification<Solution_> {
private final ConstraintProvider constraintProvider;
DefaultMultiConstraintVerification(AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory,
ConstraintProvider constraintProvider) {
super(scoreDirectorFactory);
this.constraintProvider = constraintProvider;
}
@Override
public @NonNull DefaultMultiConstraintAssertion<Solution_, Score_> given(@NonNull Object @NonNull... facts) {
assertCorrectArguments(facts);
return sessionBasedAssertionBuilder.multiConstraintGiven(constraintProvider, facts);
}
@Override
public @NonNull DefaultShadowVariableAwareMultiConstraintAssertion<Solution_, Score_>
givenSolution(@NonNull Solution_ solution) {
return new DefaultShadowVariableAwareMultiConstraintAssertion<>(constraintProvider, scoreDirectorFactory, solution);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/DefaultShadowVariableAwareMultiConstraintAssertion.java | package ai.timefold.solver.test.impl.score.stream;
import static java.util.Objects.requireNonNull;
import java.util.Objects;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.test.api.score.stream.MultiConstraintAssertion;
import ai.timefold.solver.test.api.score.stream.ShadowVariableAwareMultiConstraintAssertion;
public final class DefaultShadowVariableAwareMultiConstraintAssertion<Solution_, Score_ extends Score<Score_>>
extends AbstractMultiConstraintAssertion<Solution_, Score_> implements ShadowVariableAwareMultiConstraintAssertion {
private final AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory;
private final Solution_ solution;
DefaultShadowVariableAwareMultiConstraintAssertion(ConstraintProvider constraintProvider,
AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory,
Solution_ solution) {
super(constraintProvider, scoreDirectorFactory);
this.scoreDirectorFactory = requireNonNull(scoreDirectorFactory);
this.solution = Objects.requireNonNull(solution);
}
@Override
public MultiConstraintAssertion settingAllShadowVariables() {
// Most score directors don't need derived status; CS will override this.
try (var scoreDirector = scoreDirectorFactory.createScoreDirectorBuilder()
.withConstraintMatchPolicy(ConstraintMatchPolicy.ENABLED)
.buildDerived()) {
scoreDirector.setWorkingSolution(solution);
update(scoreDirector.calculateScore(), scoreDirector.getConstraintMatchTotalMap(),
scoreDirector.getIndictmentMap());
toggleInitialized();
return this;
}
}
@Override
Solution_ getSolution() {
return solution;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/DefaultShadowVariableAwareSingleConstraintAssertion.java | package ai.timefold.solver.test.impl.score.stream;
import java.util.Objects;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.test.api.score.stream.ShadowVariableAwareSingleConstraintAssertion;
import ai.timefold.solver.test.api.score.stream.SingleConstraintAssertion;
public final class DefaultShadowVariableAwareSingleConstraintAssertion<Solution_, Score_ extends Score<Score_>>
extends AbstractSingleConstraintAssertion<Solution_, Score_> implements ShadowVariableAwareSingleConstraintAssertion {
private final AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory;
private final Solution_ solution;
DefaultShadowVariableAwareSingleConstraintAssertion(
AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory,
Solution_ solution) {
super(scoreDirectorFactory);
this.scoreDirectorFactory = scoreDirectorFactory;
this.solution = Objects.requireNonNull(solution);
}
@Override
public SingleConstraintAssertion settingAllShadowVariables() {
// Most score directors don't need derived status; CS will override this.
try (var scoreDirector = scoreDirectorFactory.createScoreDirectorBuilder()
.withConstraintMatchPolicy(ConstraintMatchPolicy.ENABLED)
.buildDerived()) {
scoreDirector.setWorkingSolution(solution);
update(scoreDirector.calculateScore(), scoreDirector.getConstraintMatchTotalMap(),
scoreDirector.getIndictmentMap());
toggleInitialized();
return this;
}
}
@Override
Solution_ getSolution() {
return solution;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/DefaultSingleConstraintAssertion.java | package ai.timefold.solver.test.impl.score.stream;
import java.util.Map;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.api.score.constraint.Indictment;
import ai.timefold.solver.core.impl.score.director.InnerScore;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
public final class DefaultSingleConstraintAssertion<Solution_, Score_ extends Score<Score_>>
extends AbstractSingleConstraintAssertion<Solution_, Score_> {
DefaultSingleConstraintAssertion(AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory,
Score_ score, Map<String, ConstraintMatchTotal<Score_>> constraintMatchTotalMap,
Map<Object, Indictment<Score_>> indictmentMap) {
super(scoreDirectorFactory);
update(InnerScore.fullyAssigned(score), constraintMatchTotalMap, indictmentMap);
}
@Override
Solution_ getSolution() {
throw new IllegalStateException("Impossible state as the solution is initialized at the constructor.");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/DefaultSingleConstraintVerification.java | package ai.timefold.solver.test.impl.score.stream;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.test.api.score.stream.SingleConstraintVerification;
import org.jspecify.annotations.NonNull;
public final class DefaultSingleConstraintVerification<Solution_, Score_ extends Score<Score_>>
extends AbstractConstraintVerification<Solution_, Score_>
implements SingleConstraintVerification<Solution_> {
DefaultSingleConstraintVerification(
AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> scoreDirectorFactory) {
super(scoreDirectorFactory);
}
@Override
public @NonNull DefaultSingleConstraintAssertion<Solution_, Score_> given(@NonNull Object @NonNull... facts) {
assertCorrectArguments(facts);
return sessionBasedAssertionBuilder.singleConstraintGiven(facts);
}
@Override
public @NonNull DefaultShadowVariableAwareSingleConstraintAssertion<Solution_, Score_>
givenSolution(@NonNull Solution_ solution) {
return new DefaultShadowVariableAwareSingleConstraintAssertion<>(scoreDirectorFactory, solution);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/NumberEqualityUtil.java | package ai.timefold.solver.test.impl.score.stream;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.function.BiPredicate;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
final class NumberEqualityUtil {
/**
* Return the correct predicate to compare two unknown subtypes of {@link Number}.
* Supports {@link Integer}, {@link Long} and {@link BigDecimal}.
* If two numbers are not equal but still represent the same point on the number line
* (such as int 1, long 1 and {@link BigDecimal#ONE}
* the predicate will accept.
*
* @param scoreDefinition never null; will determine the type of number we receive from the score
* @param expectedImpact never null; user-provided type to check that number against
* @return never null
* @param <Score_>
*/
public static <Score_ extends Score<Score_>> BiPredicate<Number, Number>
getEqualityPredicate(ScoreDefinition<Score_> scoreDefinition, Number expectedImpact) {
if (expectedImpact instanceof Integer) {
return getIntEqualityPredicate(scoreDefinition);
} else if (expectedImpact instanceof Long) {
return getLongEqualityPredicate(scoreDefinition);
} else if (expectedImpact instanceof BigDecimal) {
return getBigDecimalEqualityPredicate(scoreDefinition);
} else {
throw new IllegalStateException("Impossible state: unknown impact type class (" + expectedImpact.getClass()
+ ") for impact (" + expectedImpact + ").");
}
}
private static <Score_ extends Score<Score_>> BiPredicate<Number, Number>
getIntEqualityPredicate(ScoreDefinition<Score_> scoreDefinition) {
Class<?> actualImpactType = scoreDefinition.getNumericType();
if (actualImpactType == int.class) {
return (Number expected, Number actual) -> expected.intValue() == actual.intValue();
} else if (actualImpactType == long.class) {
return (Number expected, Number actual) -> expected.longValue() == actual.longValue();
} else if (actualImpactType == BigDecimal.class) {
return (Number expected,
Number actual) -> (BigDecimal.valueOf(expected.intValue())).compareTo((BigDecimal) actual) == 0;
} else {
throw new IllegalStateException("Impossible state: unknown numeric type (" + actualImpactType
+ ") for score definition (" + scoreDefinition.getClass() + ").");
}
}
private static <Score_ extends Score<Score_>> BiPredicate<Number, Number>
getLongEqualityPredicate(ScoreDefinition<Score_> scoreDefinition) {
Class<?> actualImpactType = scoreDefinition.getNumericType();
if (actualImpactType == int.class) {
return (Number expected, Number actual) -> expected.longValue() == actual.intValue();
} else if (actualImpactType == long.class) {
return (Number expected, Number actual) -> expected.longValue() == actual.longValue();
} else if (actualImpactType == BigDecimal.class) {
return (Number expected,
Number actual) -> (BigDecimal.valueOf(expected.longValue())).compareTo((BigDecimal) actual) == 0;
} else {
throw new IllegalStateException("Impossible state: unknown numeric type (" + actualImpactType
+ ") for score definition (" + scoreDefinition.getClass() + ").");
}
}
private static <Score_ extends Score<Score_>> BiPredicate<Number, Number>
getBigDecimalEqualityPredicate(ScoreDefinition<Score_> scoreDefinition) {
Class<?> actualImpactType = scoreDefinition.getNumericType();
if (actualImpactType == int.class) {
return (Number expected,
Number actual) -> ((BigDecimal) expected).compareTo(BigDecimal.valueOf(actual.intValue())) == 0;
} else if (actualImpactType == long.class) {
return (Number expected,
Number actual) -> ((BigDecimal) expected).compareTo(BigDecimal.valueOf(actual.longValue())) == 0;
} else if (actualImpactType == BigDecimal.class) {
return (Number expected, Number actual) -> ((BigDecimal) expected).compareTo((BigDecimal) actual) == 0;
} else {
throw new IllegalStateException("Impossible state: unknown numeric type (" + actualImpactType
+ ") for score definition (" + scoreDefinition.getClass() + ").");
}
}
/**
* Return the correct predicate to compare two unknown subtypes of {@link Number}.
* Supports {@link Integer}, {@link Long} and {@link BigDecimal}.
* If two numbers are not equal but still represent the same point on the number line
* (such as int 1, long 1 and {@link BigDecimal#ONE}
* the predicate will accept.
*
* @param expectedImpact never null; user-provided type to check that number against
* @return never null
*/
public static Comparator<Number> getComparison(Number expectedImpact) {
return Comparator.comparing(a -> {
if (a instanceof BigDecimal bigDecimal) {
return bigDecimal;
} else {
return BigDecimal.valueOf(a.longValue());
}
});
}
private NumberEqualityUtil() {
// No external instances.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/ScoreDirectorFactoryCache.java | package ai.timefold.solver.test.impl.score.stream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiFunction;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.score.director.stream.BavetConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.core.impl.score.stream.bavet.BavetConstraintFactory;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.core.impl.score.stream.common.InnerConstraintFactory;
/**
* Designed for access from a single thread.
* Callers are responsible for ensuring that instances are never run from a thread other than that which created them.
*
* @param <ConstraintProvider_>
* @param <Solution_>
* @param <Score_>
*/
final class ScoreDirectorFactoryCache<ConstraintProvider_ extends ConstraintProvider, Solution_, Score_ extends Score<Score_>> {
/**
* Score director factory creation is expensive; we cache it.
* The cache needs to be recomputed every time that the parent's configuration changes.
*/
private final Map<ConstraintRef, AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?>> scoreDirectorFactoryMap =
new HashMap<>();
private final SolutionDescriptor<Solution_> solutionDescriptor;
public ScoreDirectorFactoryCache(SolutionDescriptor<Solution_> solutionDescriptor) {
this.solutionDescriptor = Objects.requireNonNull(solutionDescriptor);
}
/**
* Retrieve {@link AbstractConstraintStreamScoreDirectorFactory} from the cache,
* or create and cache a new instance.
* Cache key is the ID of the single constraint returned by calling the constraintFunction.
*
* @param constraintFunction never null, determines the single constraint to be used from the constraint provider
* @param constraintProvider never null, determines the constraint provider to be used
* @return never null
*/
public AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> getScoreDirectorFactory(
BiFunction<ConstraintProvider_, ConstraintFactory, Constraint> constraintFunction,
ConstraintProvider_ constraintProvider, EnvironmentMode environmentMode) {
/*
* Apply all validations on the constraint factory before extracting the one constraint.
* This step is only necessary to perform validation of the constraint provider;
* if we only wanted the one constraint, we could just call constraintFunction directly.
*/
InnerConstraintFactory<Solution_, ?> fullConstraintFactory =
new BavetConstraintFactory<>(solutionDescriptor, environmentMode);
List<Constraint> constraints = (List<Constraint>) fullConstraintFactory.buildConstraints(constraintProvider);
Constraint expectedConstraint = constraintFunction.apply(constraintProvider, fullConstraintFactory);
Constraint result = constraints.stream()
.filter(c -> Objects.equals(c.getConstraintRef(), expectedConstraint.getConstraintRef()))
.findFirst()
.orElseThrow(() -> new IllegalStateException("Impossible state: Constraint provider (" + constraintProvider
+ ") has no constraint (" + expectedConstraint + ")."));
return getScoreDirectorFactory(result.getConstraintRef(),
constraintFactory -> new Constraint[] {
result
}, environmentMode);
}
/**
* Retrieve {@link AbstractConstraintStreamScoreDirectorFactory} from the cache,
* or create and cache a new instance.
*
* @param constraintRef never null, unique identifier of the factory in the cache
* @param constraintProvider never null, constraint provider to create the factory from; ignored on cache hit
* @return never null
*/
public AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> getScoreDirectorFactory(
ConstraintRef constraintRef,
ConstraintProvider constraintProvider, EnvironmentMode environmentMode) {
return scoreDirectorFactoryMap.computeIfAbsent(constraintRef,
k -> new BavetConstraintStreamScoreDirectorFactory<>(solutionDescriptor, constraintProvider, environmentMode));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score | java-sources/ai/timefold/solver/timefold-solver-test/1.26.1/ai/timefold/solver/test/impl/score/stream/SessionBasedAssertionBuilder.java | package ai.timefold.solver.test.impl.score.stream;
import java.util.Objects;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
final class SessionBasedAssertionBuilder<Solution_, Score_ extends Score<Score_>> {
private final AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> constraintStreamScoreDirectorFactory;
public SessionBasedAssertionBuilder(
AbstractConstraintStreamScoreDirectorFactory<Solution_, Score_, ?> constraintStreamScoreDirectorFactory) {
this.constraintStreamScoreDirectorFactory = Objects.requireNonNull(constraintStreamScoreDirectorFactory);
}
public DefaultMultiConstraintAssertion<Solution_, Score_> multiConstraintGiven(ConstraintProvider constraintProvider,
Object... facts) {
var scoreInliner = constraintStreamScoreDirectorFactory.fireAndForget(facts);
return new DefaultMultiConstraintAssertion<>(constraintProvider, constraintStreamScoreDirectorFactory,
scoreInliner.extractScore(), scoreInliner.getConstraintIdToConstraintMatchTotalMap(),
scoreInliner.getIndictmentMap());
}
public DefaultSingleConstraintAssertion<Solution_, Score_> singleConstraintGiven(Object... facts) {
var scoreInliner = constraintStreamScoreDirectorFactory.fireAndForget(facts);
return new DefaultSingleConstraintAssertion<>(constraintStreamScoreDirectorFactory,
scoreInliner.extractScore(), scoreInliner.getConstraintIdToConstraintMatchTotalMap(),
scoreInliner.getIndictmentMap());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/AbstractScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score;
import ai.timefold.solver.xstream.api.score.buildin.bendable.BendableScoreXStreamConverter;
import ai.timefold.solver.xstream.api.score.buildin.bendablebigdecimal.BendableBigDecimalScoreXStreamConverter;
import ai.timefold.solver.xstream.api.score.buildin.bendablelong.BendableLongScoreXStreamConverter;
import ai.timefold.solver.xstream.api.score.buildin.hardmediumsoft.HardMediumSoftScoreXStreamConverter;
import ai.timefold.solver.xstream.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScoreXStreamConverter;
import ai.timefold.solver.xstream.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScoreXStreamConverter;
import ai.timefold.solver.xstream.api.score.buildin.hardsoft.HardSoftScoreXStreamConverter;
import ai.timefold.solver.xstream.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScoreXStreamConverter;
import ai.timefold.solver.xstream.api.score.buildin.hardsoftlong.HardSoftLongScoreXStreamConverter;
import ai.timefold.solver.xstream.api.score.buildin.simple.SimpleScoreXStreamConverter;
import ai.timefold.solver.xstream.api.score.buildin.simplebigdecimal.SimpleBigDecimalScoreXStreamConverter;
import ai.timefold.solver.xstream.api.score.buildin.simplelong.SimpleLongScoreXStreamConverter;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public abstract class AbstractScoreXStreamConverter implements Converter {
public static void registerScoreConverters(XStream xStream) {
xStream.registerConverter(new SimpleScoreXStreamConverter());
xStream.registerConverter(new SimpleLongScoreXStreamConverter());
xStream.registerConverter(new SimpleBigDecimalScoreXStreamConverter());
xStream.registerConverter(new HardSoftScoreXStreamConverter());
xStream.registerConverter(new HardSoftLongScoreXStreamConverter());
xStream.registerConverter(new HardSoftBigDecimalScoreXStreamConverter());
xStream.registerConverter(new HardMediumSoftScoreXStreamConverter());
xStream.registerConverter(new HardMediumSoftLongScoreXStreamConverter());
xStream.registerConverter(new HardMediumSoftBigDecimalScoreXStreamConverter());
xStream.registerConverter(new BendableScoreXStreamConverter());
xStream.registerConverter(new BendableLongScoreXStreamConverter());
xStream.registerConverter(new BendableBigDecimalScoreXStreamConverter());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin/bendable/BendableScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score.buildin.bendable;
import ai.timefold.solver.core.api.score.buildin.bendable.BendableScore;
import ai.timefold.solver.xstream.api.score.AbstractScoreXStreamConverter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class BendableScoreXStreamConverter extends AbstractScoreXStreamConverter {
@Override
public boolean canConvert(Class type) {
return BendableScore.class.isAssignableFrom(type);
}
@Override
public void marshal(Object scoreObject, HierarchicalStreamWriter writer, MarshallingContext context) {
BendableScore score = (BendableScore) scoreObject;
writer.setValue(score.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String scoreString = reader.getValue();
return BendableScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin/bendablebigdecimal/BendableBigDecimalScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score.buildin.bendablebigdecimal;
import ai.timefold.solver.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore;
import ai.timefold.solver.xstream.api.score.AbstractScoreXStreamConverter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class BendableBigDecimalScoreXStreamConverter extends AbstractScoreXStreamConverter {
@Override
public boolean canConvert(Class type) {
return BendableBigDecimalScore.class.isAssignableFrom(type);
}
@Override
public void marshal(Object scoreObject, HierarchicalStreamWriter writer, MarshallingContext context) {
BendableBigDecimalScore score = (BendableBigDecimalScore) scoreObject;
writer.setValue(score.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String scoreString = reader.getValue();
return BendableBigDecimalScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin/bendablelong/BendableLongScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score.buildin.bendablelong;
import ai.timefold.solver.core.api.score.buildin.bendablelong.BendableLongScore;
import ai.timefold.solver.xstream.api.score.AbstractScoreXStreamConverter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class BendableLongScoreXStreamConverter extends AbstractScoreXStreamConverter {
@Override
public boolean canConvert(Class type) {
return BendableLongScore.class.isAssignableFrom(type);
}
@Override
public void marshal(Object scoreObject, HierarchicalStreamWriter writer, MarshallingContext context) {
BendableLongScore score = (BendableLongScore) scoreObject;
writer.setValue(score.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String scoreString = reader.getValue();
return BendableLongScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin/hardmediumsoft/HardMediumSoftScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score.buildin.hardmediumsoft;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
import ai.timefold.solver.xstream.api.score.AbstractScoreXStreamConverter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class HardMediumSoftScoreXStreamConverter extends AbstractScoreXStreamConverter {
@Override
public boolean canConvert(Class type) {
return HardMediumSoftScore.class.isAssignableFrom(type);
}
@Override
public void marshal(Object scoreObject, HierarchicalStreamWriter writer, MarshallingContext context) {
HardMediumSoftScore score = (HardMediumSoftScore) scoreObject;
writer.setValue(score.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String scoreString = reader.getValue();
return HardMediumSoftScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin/hardmediumsoftbigdecimal/HardMediumSoftBigDecimalScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score.buildin.hardmediumsoftbigdecimal;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScore;
import ai.timefold.solver.xstream.api.score.AbstractScoreXStreamConverter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class HardMediumSoftBigDecimalScoreXStreamConverter extends AbstractScoreXStreamConverter {
@Override
public boolean canConvert(Class type) {
return HardMediumSoftBigDecimalScore.class.isAssignableFrom(type);
}
@Override
public void marshal(Object scoreObject, HierarchicalStreamWriter writer, MarshallingContext context) {
HardMediumSoftBigDecimalScore score = (HardMediumSoftBigDecimalScore) scoreObject;
writer.setValue(score.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String scoreString = reader.getValue();
return HardMediumSoftBigDecimalScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin/hardmediumsoftlong/HardMediumSoftLongScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score.buildin.hardmediumsoftlong;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore;
import ai.timefold.solver.xstream.api.score.AbstractScoreXStreamConverter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class HardMediumSoftLongScoreXStreamConverter extends AbstractScoreXStreamConverter {
@Override
public boolean canConvert(Class type) {
return HardMediumSoftLongScore.class.isAssignableFrom(type);
}
@Override
public void marshal(Object scoreObject, HierarchicalStreamWriter writer, MarshallingContext context) {
HardMediumSoftLongScore score = (HardMediumSoftLongScore) scoreObject;
writer.setValue(score.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String scoreString = reader.getValue();
return HardMediumSoftLongScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin/hardsoft/HardSoftScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score.buildin.hardsoft;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.xstream.api.score.AbstractScoreXStreamConverter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class HardSoftScoreXStreamConverter extends AbstractScoreXStreamConverter {
@Override
public boolean canConvert(Class type) {
return HardSoftScore.class.isAssignableFrom(type);
}
@Override
public void marshal(Object scoreObject, HierarchicalStreamWriter writer, MarshallingContext context) {
HardSoftScore score = (HardSoftScore) scoreObject;
writer.setValue(score.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String scoreString = reader.getValue();
return HardSoftScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin/hardsoftbigdecimal/HardSoftBigDecimalScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score.buildin.hardsoftbigdecimal;
import ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore;
import ai.timefold.solver.xstream.api.score.AbstractScoreXStreamConverter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class HardSoftBigDecimalScoreXStreamConverter extends AbstractScoreXStreamConverter {
@Override
public boolean canConvert(Class type) {
return HardSoftBigDecimalScore.class.isAssignableFrom(type);
}
@Override
public void marshal(Object scoreObject, HierarchicalStreamWriter writer, MarshallingContext context) {
HardSoftBigDecimalScore score = (HardSoftBigDecimalScore) scoreObject;
writer.setValue(score.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String scoreString = reader.getValue();
return HardSoftBigDecimalScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin/hardsoftlong/HardSoftLongScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score.buildin.hardsoftlong;
import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
import ai.timefold.solver.xstream.api.score.AbstractScoreXStreamConverter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class HardSoftLongScoreXStreamConverter extends AbstractScoreXStreamConverter {
@Override
public boolean canConvert(Class type) {
return HardSoftLongScore.class.isAssignableFrom(type);
}
@Override
public void marshal(Object scoreObject, HierarchicalStreamWriter writer, MarshallingContext context) {
HardSoftLongScore score = (HardSoftLongScore) scoreObject;
writer.setValue(score.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String scoreString = reader.getValue();
return HardSoftLongScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin/simple/SimpleScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score.buildin.simple;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
import ai.timefold.solver.xstream.api.score.AbstractScoreXStreamConverter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class SimpleScoreXStreamConverter extends AbstractScoreXStreamConverter {
@Override
public boolean canConvert(Class type) {
return SimpleScore.class.isAssignableFrom(type);
}
@Override
public void marshal(Object scoreObject, HierarchicalStreamWriter writer, MarshallingContext context) {
SimpleScore score = (SimpleScore) scoreObject;
writer.setValue(score.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String scoreString = reader.getValue();
return SimpleScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin/simplebigdecimal/SimpleBigDecimalScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score.buildin.simplebigdecimal;
import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore;
import ai.timefold.solver.xstream.api.score.AbstractScoreXStreamConverter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class SimpleBigDecimalScoreXStreamConverter extends AbstractScoreXStreamConverter {
@Override
public boolean canConvert(Class type) {
return SimpleBigDecimalScore.class.isAssignableFrom(type);
}
@Override
public void marshal(Object scoreObject, HierarchicalStreamWriter writer, MarshallingContext context) {
SimpleBigDecimalScore score = (SimpleBigDecimalScore) scoreObject;
writer.setValue(score.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String scoreString = reader.getValue();
return SimpleBigDecimalScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/api/score/buildin/simplelong/SimpleLongScoreXStreamConverter.java | package ai.timefold.solver.xstream.api.score.buildin.simplelong;
import ai.timefold.solver.core.api.score.buildin.simplelong.SimpleLongScore;
import ai.timefold.solver.xstream.api.score.AbstractScoreXStreamConverter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class SimpleLongScoreXStreamConverter extends AbstractScoreXStreamConverter {
@Override
public boolean canConvert(Class type) {
return SimpleLongScore.class.isAssignableFrom(type);
}
@Override
public void marshal(Object scoreObject, HierarchicalStreamWriter writer, MarshallingContext context) {
SimpleLongScore score = (SimpleLongScore) scoreObject;
writer.setValue(score.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String scoreString = reader.getValue();
return SimpleLongScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/impl/domain | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/impl/domain/solution/XStreamSolutionFileIO.java | package ai.timefold.solver.xstream.impl.domain.solution;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.XStreamException;
import com.thoughtworks.xstream.security.AnyTypePermission;
/**
* Security warning: only use this class with XML files from a trusted source,
* because {@link XStream} is configured to allow all permissions,
* which can be exploited if the XML comes from an untrusted source.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @deprecated Prefer JAXB for serialization into XML.
*/
@Deprecated(forRemoval = true)
public class XStreamSolutionFileIO<Solution_> implements SolutionFileIO<Solution_> {
protected XStream xStream;
public XStreamSolutionFileIO(Class... xStreamAnnotatedClasses) {
xStream = new XStream();
xStream.setMode(XStream.ID_REFERENCES);
xStream.processAnnotations(xStreamAnnotatedClasses);
XStream.setupDefaultSecurity(xStream);
// Presume the XML file comes from a trusted source so it works out of the box. See class javadoc.
xStream.addPermission(new AnyTypePermission());
}
public XStream getXStream() {
return xStream;
}
@Override
public String getInputFileExtension() {
return "xml";
}
@Override
public Solution_ read(File inputSolutionFile) {
try (InputStream inputSolutionStream = Files.newInputStream(inputSolutionFile.toPath())) {
return read(inputSolutionStream);
} catch (Exception e) {
throw new IllegalArgumentException("Failed reading inputSolutionFile (" + inputSolutionFile + ").", e);
}
}
public Solution_ read(InputStream inputSolutionStream) {
// xStream.fromXml(InputStream) does not use UTF-8
try (Reader reader = new InputStreamReader(inputSolutionStream, StandardCharsets.UTF_8)) {
return (Solution_) xStream.fromXML(reader);
} catch (XStreamException | IOException e) {
throw new IllegalArgumentException("Failed reading inputSolutionStream.", e);
}
}
@Override
public void write(Solution_ solution, File outputSolutionFile) {
try (Writer writer = new OutputStreamWriter(new FileOutputStream(outputSolutionFile), StandardCharsets.UTF_8)) {
xStream.toXML(solution, writer);
} catch (IOException e) {
throw new IllegalArgumentException("Failed writing outputSolutionFile (" + outputSolutionFile + ").", e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/runtime | java-sources/ai/timefold/solver/timefold-solver-xstream/0.8.42/ai/timefold/solver/xstream/runtime/graal/XStreamSubstitutions.java | package ai.timefold.solver.xstream.runtime.graal;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
@TargetClass(className = "com.thoughtworks.xstream.converters.reflection.SerializableConverter")
final class Target_SerializableConverter {
@Substitute
public Object doUnmarshal(final Object result, final Target_HierarchicalStreamReader reader,
final Target_UnmarshallingContext context) {
return null;
}
@Substitute
public void doMarshal(final Object source, final Target_HierarchicalStreamWriter writer,
final Target_MarshallingContext context) {
}
}
@TargetClass(className = "com.thoughtworks.xstream.io.HierarchicalStreamReader")
final class Target_HierarchicalStreamReader {
}
@TargetClass(className = "com.thoughtworks.xstream.converters.UnmarshallingContext")
final class Target_UnmarshallingContext {
}
@TargetClass(className = "com.thoughtworks.xstream.io.HierarchicalStreamWriter")
final class Target_HierarchicalStreamWriter {
}
@TargetClass(className = "com.thoughtworks.xstream.converters.MarshallingContext")
final class Target_MarshallingContext {
}
@TargetClass(className = "com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider")
final class Target_PureJavaReflectionProvider {
@Substitute
private Object instantiateUsingSerialization(final Class type) {
return null;
}
}
class XStreamSubstitutions {
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/AbstractRequestParameters.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.util.Map;
import java.util.stream.Collectors;
public class AbstractRequestParameters {
protected final Map<String, Object> filterNulls(Map<String, Object> source) {
return source.entrySet()
.stream()
.filter(e -> e.getValue() != null)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/BatchCreateResult.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
public class BatchCreateResult<T> {
private Map<Integer, T> items;
@JsonProperty("validation_errors")
private Map<Integer, Map<String, FieldValidationError>> validationsErrors;
public Map<Integer, T> getItems() {
return items;
}
public Map<Integer, Map<String, FieldValidationError>> getValidationsErrors() {
return validationsErrors;
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/CountryIso3166.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.fasterxml.jackson.annotation.JsonCreator;
/**
* Implemented not with enum because of possibility to get unknown country from server
* <a href="http://www.iso.org/iso/country_codes.htm">Country codes ISO 3166</a>
*/
public final class CountryIso3166 extends FlexibleEnum<CountryIso3166> {
public static final CountryIso3166 AB = new CountryIso3166("AB");
public static final CountryIso3166 AD = new CountryIso3166("AD");
public static final CountryIso3166 AE = new CountryIso3166("AE");
public static final CountryIso3166 AF = new CountryIso3166("AF");
public static final CountryIso3166 AG = new CountryIso3166("AG");
public static final CountryIso3166 AI = new CountryIso3166("AI");
public static final CountryIso3166 AL = new CountryIso3166("AL");
public static final CountryIso3166 AM = new CountryIso3166("AM");
public static final CountryIso3166 AN = new CountryIso3166("AN");
public static final CountryIso3166 AO = new CountryIso3166("AO");
public static final CountryIso3166 AQ = new CountryIso3166("AQ");
public static final CountryIso3166 AR = new CountryIso3166("AR");
public static final CountryIso3166 AS = new CountryIso3166("AS");
public static final CountryIso3166 AT = new CountryIso3166("AT");
public static final CountryIso3166 AU = new CountryIso3166("AU");
public static final CountryIso3166 AW = new CountryIso3166("AW");
public static final CountryIso3166 AX = new CountryIso3166("AX");
public static final CountryIso3166 AZ = new CountryIso3166("AZ");
public static final CountryIso3166 BA = new CountryIso3166("BA");
public static final CountryIso3166 BB = new CountryIso3166("BB");
public static final CountryIso3166 BD = new CountryIso3166("BD");
public static final CountryIso3166 BE = new CountryIso3166("BE");
public static final CountryIso3166 BF = new CountryIso3166("BF");
public static final CountryIso3166 BG = new CountryIso3166("BG");
public static final CountryIso3166 BH = new CountryIso3166("BH");
public static final CountryIso3166 BI = new CountryIso3166("BI");
public static final CountryIso3166 BJ = new CountryIso3166("BJ");
public static final CountryIso3166 BL = new CountryIso3166("BL");
public static final CountryIso3166 BM = new CountryIso3166("BM");
public static final CountryIso3166 BN = new CountryIso3166("BN");
public static final CountryIso3166 BO = new CountryIso3166("BO");
public static final CountryIso3166 BQ = new CountryIso3166("BQ");
public static final CountryIso3166 BR = new CountryIso3166("BR");
public static final CountryIso3166 BS = new CountryIso3166("BS");
public static final CountryIso3166 BT = new CountryIso3166("BT");
public static final CountryIso3166 BV = new CountryIso3166("BV");
public static final CountryIso3166 BW = new CountryIso3166("BW");
public static final CountryIso3166 BY = new CountryIso3166("BY");
public static final CountryIso3166 BZ = new CountryIso3166("BZ");
public static final CountryIso3166 CA = new CountryIso3166("CA");
public static final CountryIso3166 CC = new CountryIso3166("CC");
public static final CountryIso3166 CD = new CountryIso3166("CD");
public static final CountryIso3166 CF = new CountryIso3166("CF");
public static final CountryIso3166 CG = new CountryIso3166("CG");
public static final CountryIso3166 CH = new CountryIso3166("CH");
public static final CountryIso3166 CI = new CountryIso3166("CI");
public static final CountryIso3166 CK = new CountryIso3166("CK");
public static final CountryIso3166 CL = new CountryIso3166("CL");
public static final CountryIso3166 CM = new CountryIso3166("CM");
public static final CountryIso3166 CN = new CountryIso3166("CN");
public static final CountryIso3166 CO = new CountryIso3166("CO");
public static final CountryIso3166 CR = new CountryIso3166("CR");
public static final CountryIso3166 CS = new CountryIso3166("CS");
public static final CountryIso3166 CU = new CountryIso3166("CU");
public static final CountryIso3166 CV = new CountryIso3166("CV");
public static final CountryIso3166 CW = new CountryIso3166("CW");
public static final CountryIso3166 CX = new CountryIso3166("CX");
public static final CountryIso3166 CY = new CountryIso3166("CY");
public static final CountryIso3166 CZ = new CountryIso3166("CZ");
public static final CountryIso3166 DE = new CountryIso3166("DE");
public static final CountryIso3166 DJ = new CountryIso3166("DJ");
public static final CountryIso3166 DK = new CountryIso3166("DK");
public static final CountryIso3166 DM = new CountryIso3166("DM");
public static final CountryIso3166 DO = new CountryIso3166("DO");
public static final CountryIso3166 DZ = new CountryIso3166("DZ");
public static final CountryIso3166 EC = new CountryIso3166("EC");
public static final CountryIso3166 EE = new CountryIso3166("EE");
public static final CountryIso3166 EG = new CountryIso3166("EG");
public static final CountryIso3166 EH = new CountryIso3166("EH");
public static final CountryIso3166 ER = new CountryIso3166("ER");
public static final CountryIso3166 ES = new CountryIso3166("ES");
public static final CountryIso3166 ET = new CountryIso3166("ET");
public static final CountryIso3166 FI = new CountryIso3166("FI");
public static final CountryIso3166 FJ = new CountryIso3166("FJ");
public static final CountryIso3166 FK = new CountryIso3166("FK");
public static final CountryIso3166 FM = new CountryIso3166("FM");
public static final CountryIso3166 FO = new CountryIso3166("FO");
public static final CountryIso3166 FR = new CountryIso3166("FR");
public static final CountryIso3166 GA = new CountryIso3166("GA");
public static final CountryIso3166 GB = new CountryIso3166("GB");
public static final CountryIso3166 GD = new CountryIso3166("GD");
public static final CountryIso3166 GE = new CountryIso3166("GE");
public static final CountryIso3166 GF = new CountryIso3166("GF");
public static final CountryIso3166 GG = new CountryIso3166("GG");
public static final CountryIso3166 GH = new CountryIso3166("GH");
public static final CountryIso3166 GI = new CountryIso3166("GI");
public static final CountryIso3166 GL = new CountryIso3166("GL");
public static final CountryIso3166 GM = new CountryIso3166("GM");
public static final CountryIso3166 GN = new CountryIso3166("GN");
public static final CountryIso3166 GP = new CountryIso3166("GP");
public static final CountryIso3166 GQ = new CountryIso3166("GQ");
public static final CountryIso3166 GR = new CountryIso3166("GR");
public static final CountryIso3166 GS = new CountryIso3166("GS");
public static final CountryIso3166 GT = new CountryIso3166("GT");
public static final CountryIso3166 GU = new CountryIso3166("GU");
public static final CountryIso3166 GW = new CountryIso3166("GW");
public static final CountryIso3166 GY = new CountryIso3166("GY");
public static final CountryIso3166 HK = new CountryIso3166("HK");
public static final CountryIso3166 HM = new CountryIso3166("HM");
public static final CountryIso3166 HN = new CountryIso3166("HN");
public static final CountryIso3166 HR = new CountryIso3166("HR");
public static final CountryIso3166 HT = new CountryIso3166("HT");
public static final CountryIso3166 HU = new CountryIso3166("HU");
public static final CountryIso3166 ID = new CountryIso3166("ID");
public static final CountryIso3166 IE = new CountryIso3166("IE");
public static final CountryIso3166 IL = new CountryIso3166("IL");
public static final CountryIso3166 IM = new CountryIso3166("IM");
public static final CountryIso3166 IN = new CountryIso3166("IN");
public static final CountryIso3166 IO = new CountryIso3166("IO");
public static final CountryIso3166 IQ = new CountryIso3166("IQ");
public static final CountryIso3166 IR = new CountryIso3166("IR");
public static final CountryIso3166 IS = new CountryIso3166("IS");
public static final CountryIso3166 IT = new CountryIso3166("IT");
public static final CountryIso3166 JE = new CountryIso3166("JE");
public static final CountryIso3166 JM = new CountryIso3166("JM");
public static final CountryIso3166 JO = new CountryIso3166("JO");
public static final CountryIso3166 JP = new CountryIso3166("JP");
public static final CountryIso3166 KE = new CountryIso3166("KE");
public static final CountryIso3166 KG = new CountryIso3166("KG");
public static final CountryIso3166 KH = new CountryIso3166("KH");
public static final CountryIso3166 KI = new CountryIso3166("KI");
public static final CountryIso3166 KM = new CountryIso3166("KM");
public static final CountryIso3166 KN = new CountryIso3166("KN");
public static final CountryIso3166 KP = new CountryIso3166("KP");
public static final CountryIso3166 KR = new CountryIso3166("KR");
public static final CountryIso3166 KW = new CountryIso3166("KW");
public static final CountryIso3166 KY = new CountryIso3166("KY");
public static final CountryIso3166 KZ = new CountryIso3166("KZ");
public static final CountryIso3166 LA = new CountryIso3166("LA");
public static final CountryIso3166 LB = new CountryIso3166("LB");
public static final CountryIso3166 LC = new CountryIso3166("LC");
public static final CountryIso3166 LI = new CountryIso3166("LI");
public static final CountryIso3166 LK = new CountryIso3166("LK");
public static final CountryIso3166 LR = new CountryIso3166("LR");
public static final CountryIso3166 LS = new CountryIso3166("LS");
public static final CountryIso3166 LT = new CountryIso3166("LT");
public static final CountryIso3166 LU = new CountryIso3166("LU");
public static final CountryIso3166 LV = new CountryIso3166("LV");
public static final CountryIso3166 LY = new CountryIso3166("LY");
public static final CountryIso3166 MA = new CountryIso3166("MA");
public static final CountryIso3166 MC = new CountryIso3166("MC");
public static final CountryIso3166 MD = new CountryIso3166("MD");
public static final CountryIso3166 ME = new CountryIso3166("ME");
public static final CountryIso3166 MF = new CountryIso3166("MF");
public static final CountryIso3166 MG = new CountryIso3166("MG");
public static final CountryIso3166 MH = new CountryIso3166("MH");
public static final CountryIso3166 MK = new CountryIso3166("MK");
public static final CountryIso3166 ML = new CountryIso3166("ML");
public static final CountryIso3166 MM = new CountryIso3166("MM");
public static final CountryIso3166 MN = new CountryIso3166("MN");
public static final CountryIso3166 MO = new CountryIso3166("MO");
public static final CountryIso3166 MP = new CountryIso3166("MP");
public static final CountryIso3166 MQ = new CountryIso3166("MQ");
public static final CountryIso3166 MR = new CountryIso3166("MR");
public static final CountryIso3166 MS = new CountryIso3166("MS");
public static final CountryIso3166 MT = new CountryIso3166("MT");
public static final CountryIso3166 MU = new CountryIso3166("MU");
public static final CountryIso3166 MV = new CountryIso3166("MV");
public static final CountryIso3166 MW = new CountryIso3166("MW");
public static final CountryIso3166 MX = new CountryIso3166("MX");
public static final CountryIso3166 MY = new CountryIso3166("MY");
public static final CountryIso3166 MZ = new CountryIso3166("MZ");
public static final CountryIso3166 NA = new CountryIso3166("NA");
public static final CountryIso3166 NC = new CountryIso3166("NC");
public static final CountryIso3166 NE = new CountryIso3166("NE");
public static final CountryIso3166 NF = new CountryIso3166("NF");
public static final CountryIso3166 NG = new CountryIso3166("NG");
public static final CountryIso3166 NI = new CountryIso3166("NI");
public static final CountryIso3166 NL = new CountryIso3166("NL");
public static final CountryIso3166 NO = new CountryIso3166("NO");
public static final CountryIso3166 NP = new CountryIso3166("NP");
public static final CountryIso3166 NR = new CountryIso3166("NR");
public static final CountryIso3166 NU = new CountryIso3166("NU");
public static final CountryIso3166 NZ = new CountryIso3166("NZ");
public static final CountryIso3166 OM = new CountryIso3166("OM");
public static final CountryIso3166 OS = new CountryIso3166("OS");
public static final CountryIso3166 PA = new CountryIso3166("PA");
public static final CountryIso3166 PE = new CountryIso3166("PE");
public static final CountryIso3166 PF = new CountryIso3166("PF");
public static final CountryIso3166 PG = new CountryIso3166("PG");
public static final CountryIso3166 PH = new CountryIso3166("PH");
public static final CountryIso3166 PK = new CountryIso3166("PK");
public static final CountryIso3166 PL = new CountryIso3166("PL");
public static final CountryIso3166 PM = new CountryIso3166("PM");
public static final CountryIso3166 PN = new CountryIso3166("PN");
public static final CountryIso3166 PR = new CountryIso3166("PR");
public static final CountryIso3166 PS = new CountryIso3166("PS");
public static final CountryIso3166 PT = new CountryIso3166("PT");
public static final CountryIso3166 PW = new CountryIso3166("PW");
public static final CountryIso3166 PY = new CountryIso3166("PY");
public static final CountryIso3166 QA = new CountryIso3166("QA");
public static final CountryIso3166 RE = new CountryIso3166("RE");
public static final CountryIso3166 RO = new CountryIso3166("RO");
public static final CountryIso3166 RS = new CountryIso3166("RS");
public static final CountryIso3166 RU = new CountryIso3166("RU");
public static final CountryIso3166 RW = new CountryIso3166("RW");
public static final CountryIso3166 SA = new CountryIso3166("SA");
public static final CountryIso3166 SB = new CountryIso3166("SB");
public static final CountryIso3166 SC = new CountryIso3166("SC");
public static final CountryIso3166 SD = new CountryIso3166("SD");
public static final CountryIso3166 SE = new CountryIso3166("SE");
public static final CountryIso3166 SG = new CountryIso3166("SG");
public static final CountryIso3166 SH = new CountryIso3166("SH");
public static final CountryIso3166 SI = new CountryIso3166("SI");
public static final CountryIso3166 SJ = new CountryIso3166("SJ");
public static final CountryIso3166 SK = new CountryIso3166("SK");
public static final CountryIso3166 SL = new CountryIso3166("SL");
public static final CountryIso3166 SM = new CountryIso3166("SM");
public static final CountryIso3166 SN = new CountryIso3166("SN");
public static final CountryIso3166 SO = new CountryIso3166("SO");
public static final CountryIso3166 SR = new CountryIso3166("SR");
public static final CountryIso3166 SS = new CountryIso3166("SS");
public static final CountryIso3166 ST = new CountryIso3166("ST");
public static final CountryIso3166 SV = new CountryIso3166("SV");
public static final CountryIso3166 SX = new CountryIso3166("SX");
public static final CountryIso3166 SY = new CountryIso3166("SY");
public static final CountryIso3166 SZ = new CountryIso3166("SZ");
public static final CountryIso3166 TC = new CountryIso3166("TC");
public static final CountryIso3166 TD = new CountryIso3166("TD");
public static final CountryIso3166 TF = new CountryIso3166("TF");
public static final CountryIso3166 TG = new CountryIso3166("TG");
public static final CountryIso3166 TH = new CountryIso3166("TH");
public static final CountryIso3166 TJ = new CountryIso3166("TJ");
public static final CountryIso3166 TK = new CountryIso3166("TK");
public static final CountryIso3166 TL = new CountryIso3166("TL");
public static final CountryIso3166 TM = new CountryIso3166("TM");
public static final CountryIso3166 TN = new CountryIso3166("TN");
public static final CountryIso3166 TO = new CountryIso3166("TO");
public static final CountryIso3166 TR = new CountryIso3166("TR");
public static final CountryIso3166 TT = new CountryIso3166("TT");
public static final CountryIso3166 TV = new CountryIso3166("TV");
public static final CountryIso3166 TW = new CountryIso3166("TW");
public static final CountryIso3166 TZ = new CountryIso3166("TZ");
public static final CountryIso3166 UA = new CountryIso3166("UA");
public static final CountryIso3166 UG = new CountryIso3166("UG");
public static final CountryIso3166 UM = new CountryIso3166("UM");
public static final CountryIso3166 US = new CountryIso3166("US");
public static final CountryIso3166 UY = new CountryIso3166("UY");
public static final CountryIso3166 UZ = new CountryIso3166("UZ");
public static final CountryIso3166 VA = new CountryIso3166("VA");
public static final CountryIso3166 VC = new CountryIso3166("VC");
public static final CountryIso3166 VE = new CountryIso3166("VE");
public static final CountryIso3166 VG = new CountryIso3166("VG");
public static final CountryIso3166 VI = new CountryIso3166("VI");
public static final CountryIso3166 VN = new CountryIso3166("VN");
public static final CountryIso3166 VU = new CountryIso3166("VU");
public static final CountryIso3166 WF = new CountryIso3166("WF");
public static final CountryIso3166 WS = new CountryIso3166("WS");
public static final CountryIso3166 YE = new CountryIso3166("YE");
public static final CountryIso3166 YT = new CountryIso3166("YT");
public static final CountryIso3166 ZA = new CountryIso3166("ZA");
public static final CountryIso3166 ZM = new CountryIso3166("ZM");
public static final CountryIso3166 ZW = new CountryIso3166("ZW");
private CountryIso3166(String name) {
super(name);
}
private static final CountryIso3166[] VALUES = {
AB, AD, AE, AF, AG, AI, AL, AM, AN, AO, AQ, AR, AS, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI,
BJ, BL, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BY, BZ, CA, CC, CD, CF, CG, CH, CI, CK, CL, CM, CN, CO, CR,
CS, CU, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, ET, FI, FJ, FK, FM, FO, FR,
GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GU, GW, GY, HK, HM, HN, HR, HT, HU, ID,
IE, IL, IM, IN, IO, IQ, IR, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KP, KR, KW, KY, KZ, LA, LB,
LC, LI, LK, LR, LS, LT, LU, LV, LY, MA, MC, MD, ME, MF, MG, MH, MK, ML, MM, MN, MO, MP, MQ, MR, MS, MT,
MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NI, NL, NO, NP, NR, NU, NZ, OM, OS, PA, PE, PF, PG, PH, PK,
PL, PM, PN, PR, PS, PT, PW, PY, QA, RE, RO, RS, RU, RW, SA, SB, SC, SD, SE, SG, SH, SI, SJ, SK, SL, SM,
SN, SO, SR, SS, ST, SV, SX, SY, SZ, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TR, TT, TV, TW, TZ, UA,
UG, UM, US, UY, UZ, VA, VC, VE, VG, VI, VN, VU, WF, WS, YE, YT, ZA, ZM, ZW};
private static final ConcurrentMap<String, CountryIso3166> DISCOVERED_VALUES = new ConcurrentHashMap<>();
public static CountryIso3166[] values() {
return values(VALUES, DISCOVERED_VALUES.values(), CountryIso3166.class);
}
@JsonCreator
public static CountryIso3166 valueOf(String name) {
return valueOf(VALUES, DISCOVERED_VALUES, name, new FlexibleEnum.NewEnumCreator<CountryIso3166>() {
@Override public CountryIso3166 create(String name) {
return new CountryIso3166(name);
}
});
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/FieldValidationError.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class FieldValidationError {
private final String code;
private final String message;
private final List<Object> params;
@JsonCreator
public FieldValidationError(@JsonProperty("code") String code, @JsonProperty("message") String message,
@JsonProperty("params") List<Object> params) {
this.code = code;
this.message = message;
this.params = params != null ? params : new ArrayList<>();
}
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
public List<Object> getParams() {
return params;
}
@Override public String toString() {
return "FieldValidationError{"
+ "code='" + code + '\''
+ ", message='" + message + '\''
+ ", params=" + params
+ '}';
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/FilterParam.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
public interface FilterParam {
String parameter();
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/FlexibleEnum.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentMap;
import com.fasterxml.jackson.annotation.JsonValue;
public abstract class FlexibleEnum<E extends FlexibleEnum<E>> implements Comparable<E> {
private final String name;
protected FlexibleEnum(String name) {
this.name = name;
}
@JsonValue
public String name() {
return name;
}
@Override public String toString() {
return name();
}
@Override public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FlexibleEnum that = (FlexibleEnum) o;
return Objects.equals(name, that.name);
}
@Override public int hashCode() {
return Objects.hash(name);
}
@Override public int compareTo(E o) {
return name.compareTo(o.name());
}
protected static <T extends FlexibleEnum<T>> T[] values(T[] knownValues,
Collection<T> discoveredValues,
Class<T> clazz) {
// make a snapshot of concurrent structure to prevent out of bound
List<T> copy = new ArrayList<>(discoveredValues);
@SuppressWarnings("unchecked")
T[] out = (T[]) Array.newInstance(clazz, knownValues.length + copy.size());
copy.toArray(out);
for (int i = 0; i < knownValues.length; i++) {
out[i + copy.size()] = knownValues[i];
}
return out;
}
protected interface NewEnumCreator<T extends FlexibleEnum<T>> {
T create(String name);
}
protected static <T extends FlexibleEnum<T>> T valueOf(T[] knownValues,
ConcurrentMap<String, T> discoveredValues,
String name,
NewEnumCreator<T> enumCreator) {
if (name == null) {
throw new NullPointerException("Name is null");
}
// try to find existing one
for (T t : knownValues) {
if (t.name().equals(name)) {
return t;
}
}
T value = discoveredValues.get(name);
if (value != null) {
return value;
}
// enum missed. Create new one and cache it
T created = enumCreator.create(name);
discoveredValues.putIfAbsent(name, created);
return discoveredValues.get(name);
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/LangIso639.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.fasterxml.jackson.annotation.JsonCreator;
/**
* Implemented not with enum because of possibility to get unknown country from server
* <a href="https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes">Language codes ISO 639-1</a>
*/
public final class LangIso639 extends FlexibleEnum<LangIso639> {
public static final LangIso639 AA = new LangIso639("AA");
public static final LangIso639 AB = new LangIso639("AB");
public static final LangIso639 AE = new LangIso639("AE");
public static final LangIso639 AF = new LangIso639("AF");
public static final LangIso639 AK = new LangIso639("AK");
public static final LangIso639 AM = new LangIso639("AM");
public static final LangIso639 AN = new LangIso639("AN");
public static final LangIso639 AR = new LangIso639("AR");
public static final LangIso639 AS = new LangIso639("AS");
public static final LangIso639 AV = new LangIso639("AV");
public static final LangIso639 AY = new LangIso639("AY");
public static final LangIso639 AZ = new LangIso639("AZ");
public static final LangIso639 BA = new LangIso639("BA");
public static final LangIso639 BE = new LangIso639("BE");
public static final LangIso639 BG = new LangIso639("BG");
public static final LangIso639 BH = new LangIso639("BH");
public static final LangIso639 BI = new LangIso639("BI");
public static final LangIso639 BM = new LangIso639("BM");
public static final LangIso639 BN = new LangIso639("BN");
public static final LangIso639 BO = new LangIso639("BO");
public static final LangIso639 BR = new LangIso639("BR");
public static final LangIso639 BS = new LangIso639("BS");
public static final LangIso639 CA = new LangIso639("CA");
public static final LangIso639 CE = new LangIso639("CE");
public static final LangIso639 CH = new LangIso639("CH");
public static final LangIso639 CO = new LangIso639("CO");
public static final LangIso639 CR = new LangIso639("CR");
public static final LangIso639 CS = new LangIso639("CS");
public static final LangIso639 CU = new LangIso639("CU");
public static final LangIso639 CV = new LangIso639("CV");
public static final LangIso639 CY = new LangIso639("CY");
public static final LangIso639 DA = new LangIso639("DA");
public static final LangIso639 DE = new LangIso639("DE");
public static final LangIso639 DV = new LangIso639("DV");
public static final LangIso639 DZ = new LangIso639("DZ");
public static final LangIso639 EE = new LangIso639("EE");
public static final LangIso639 EL = new LangIso639("EL");
public static final LangIso639 EN = new LangIso639("EN");
public static final LangIso639 EO = new LangIso639("EO");
public static final LangIso639 ES = new LangIso639("ES");
public static final LangIso639 ET = new LangIso639("ET");
public static final LangIso639 EU = new LangIso639("EU");
public static final LangIso639 FA = new LangIso639("FA");
public static final LangIso639 FF = new LangIso639("FF");
public static final LangIso639 FI = new LangIso639("FI");
public static final LangIso639 FJ = new LangIso639("FJ");
public static final LangIso639 FO = new LangIso639("FO");
public static final LangIso639 FR = new LangIso639("FR");
public static final LangIso639 FY = new LangIso639("FY");
public static final LangIso639 GA = new LangIso639("GA");
public static final LangIso639 GD = new LangIso639("GD");
public static final LangIso639 GL = new LangIso639("GL");
public static final LangIso639 GN = new LangIso639("GN");
public static final LangIso639 GU = new LangIso639("GU");
public static final LangIso639 GV = new LangIso639("GV");
public static final LangIso639 HA = new LangIso639("HA");
public static final LangIso639 HE = new LangIso639("HE");
public static final LangIso639 HI = new LangIso639("HI");
public static final LangIso639 HO = new LangIso639("HO");
public static final LangIso639 HR = new LangIso639("HR");
public static final LangIso639 HT = new LangIso639("HT");
public static final LangIso639 HU = new LangIso639("HU");
public static final LangIso639 HY = new LangIso639("HY");
public static final LangIso639 HZ = new LangIso639("HZ");
public static final LangIso639 IA = new LangIso639("IA");
public static final LangIso639 ID = new LangIso639("ID");
public static final LangIso639 IE = new LangIso639("IE");
public static final LangIso639 IG = new LangIso639("IG");
public static final LangIso639 II = new LangIso639("II");
public static final LangIso639 IK = new LangIso639("IK");
public static final LangIso639 IN = new LangIso639("IN");
public static final LangIso639 IO = new LangIso639("IO");
public static final LangIso639 IS = new LangIso639("IS");
public static final LangIso639 IT = new LangIso639("IT");
public static final LangIso639 IU = new LangIso639("IU");
public static final LangIso639 IW = new LangIso639("IW");
public static final LangIso639 JA = new LangIso639("JA");
public static final LangIso639 JI = new LangIso639("JI");
public static final LangIso639 JV = new LangIso639("JV");
public static final LangIso639 KA = new LangIso639("KA");
public static final LangIso639 KG = new LangIso639("KG");
public static final LangIso639 KI = new LangIso639("KI");
public static final LangIso639 KJ = new LangIso639("KJ");
public static final LangIso639 KK = new LangIso639("KK");
public static final LangIso639 KL = new LangIso639("KL");
public static final LangIso639 KM = new LangIso639("KM");
public static final LangIso639 KN = new LangIso639("KN");
public static final LangIso639 KO = new LangIso639("KO");
public static final LangIso639 KR = new LangIso639("KR");
public static final LangIso639 KS = new LangIso639("KS");
public static final LangIso639 KU = new LangIso639("KU");
public static final LangIso639 KV = new LangIso639("KV");
public static final LangIso639 KW = new LangIso639("KW");
public static final LangIso639 KY = new LangIso639("KY");
public static final LangIso639 LA = new LangIso639("LA");
public static final LangIso639 LB = new LangIso639("LB");
public static final LangIso639 LG = new LangIso639("LG");
public static final LangIso639 LI = new LangIso639("LI");
public static final LangIso639 LN = new LangIso639("LN");
public static final LangIso639 LO = new LangIso639("LO");
public static final LangIso639 LT = new LangIso639("LT");
public static final LangIso639 LU = new LangIso639("LU");
public static final LangIso639 LV = new LangIso639("LV");
public static final LangIso639 MG = new LangIso639("MG");
public static final LangIso639 MH = new LangIso639("MH");
public static final LangIso639 MI = new LangIso639("MI");
public static final LangIso639 MK = new LangIso639("MK");
public static final LangIso639 ML = new LangIso639("ML");
public static final LangIso639 MN = new LangIso639("MN");
public static final LangIso639 MO = new LangIso639("MO");
public static final LangIso639 MR = new LangIso639("MR");
public static final LangIso639 MS = new LangIso639("MS");
public static final LangIso639 MT = new LangIso639("MT");
public static final LangIso639 MY = new LangIso639("MY");
public static final LangIso639 NA = new LangIso639("NA");
public static final LangIso639 NB = new LangIso639("NB");
public static final LangIso639 ND = new LangIso639("ND");
public static final LangIso639 NE = new LangIso639("NE");
public static final LangIso639 NG = new LangIso639("NG");
public static final LangIso639 NL = new LangIso639("NL");
public static final LangIso639 NN = new LangIso639("NN");
public static final LangIso639 NO = new LangIso639("NO");
public static final LangIso639 NR = new LangIso639("NR");
public static final LangIso639 NV = new LangIso639("NV");
public static final LangIso639 NY = new LangIso639("NY");
public static final LangIso639 OC = new LangIso639("OC");
public static final LangIso639 OJ = new LangIso639("OJ");
public static final LangIso639 OM = new LangIso639("OM");
public static final LangIso639 OR = new LangIso639("OR");
public static final LangIso639 OS = new LangIso639("OS");
public static final LangIso639 PA = new LangIso639("PA");
public static final LangIso639 PI = new LangIso639("PI");
public static final LangIso639 PL = new LangIso639("PL");
public static final LangIso639 PS = new LangIso639("PS");
public static final LangIso639 PT = new LangIso639("PT");
public static final LangIso639 PT_BR = new LangIso639("PT-BR");
public static final LangIso639 QU = new LangIso639("QU");
public static final LangIso639 RM = new LangIso639("RM");
public static final LangIso639 RN = new LangIso639("RN");
public static final LangIso639 RO = new LangIso639("RO");
public static final LangIso639 RU = new LangIso639("RU");
public static final LangIso639 RW = new LangIso639("RW");
public static final LangIso639 SA = new LangIso639("SA");
public static final LangIso639 SC = new LangIso639("SC");
public static final LangIso639 SD = new LangIso639("SD");
public static final LangIso639 SE = new LangIso639("SE");
public static final LangIso639 SG = new LangIso639("SG");
public static final LangIso639 SI = new LangIso639("SI");
public static final LangIso639 SK = new LangIso639("SK");
public static final LangIso639 SL = new LangIso639("SL");
public static final LangIso639 SM = new LangIso639("SM");
public static final LangIso639 SN = new LangIso639("SN");
public static final LangIso639 SO = new LangIso639("SO");
public static final LangIso639 SQ = new LangIso639("SQ");
public static final LangIso639 SR = new LangIso639("SR");
public static final LangIso639 SS = new LangIso639("SS");
public static final LangIso639 ST = new LangIso639("ST");
public static final LangIso639 SU = new LangIso639("SU");
public static final LangIso639 SV = new LangIso639("SV");
public static final LangIso639 SW = new LangIso639("SW");
public static final LangIso639 TA = new LangIso639("TA");
public static final LangIso639 TE = new LangIso639("TE");
public static final LangIso639 TG = new LangIso639("TG");
public static final LangIso639 TH = new LangIso639("TH");
public static final LangIso639 TI = new LangIso639("TI");
public static final LangIso639 TK = new LangIso639("TK");
public static final LangIso639 TL = new LangIso639("TL");
public static final LangIso639 TN = new LangIso639("TN");
public static final LangIso639 TO = new LangIso639("TO");
public static final LangIso639 TR = new LangIso639("TR");
public static final LangIso639 TS = new LangIso639("TS");
public static final LangIso639 TT = new LangIso639("TT");
public static final LangIso639 TW = new LangIso639("TW");
public static final LangIso639 TY = new LangIso639("TY");
public static final LangIso639 UG = new LangIso639("UG");
public static final LangIso639 UK = new LangIso639("UK");
public static final LangIso639 UR = new LangIso639("UR");
public static final LangIso639 UZ = new LangIso639("UZ");
public static final LangIso639 VE = new LangIso639("VE");
public static final LangIso639 VI = new LangIso639("VI");
public static final LangIso639 VO = new LangIso639("VO");
public static final LangIso639 WA = new LangIso639("WA");
public static final LangIso639 WO = new LangIso639("WO");
public static final LangIso639 XH = new LangIso639("XH");
public static final LangIso639 YI = new LangIso639("YI");
public static final LangIso639 YO = new LangIso639("YO");
public static final LangIso639 ZA = new LangIso639("ZA");
public static final LangIso639 ZH = new LangIso639("ZH");
public static final LangIso639 ZH_HANS = new LangIso639("ZH-HANS");
public static final LangIso639 ZU = new LangIso639("ZU");
private LangIso639(String name) {
super(name);
}
private static final LangIso639[] VALUES = {
AA, AB, AE, AF, AK, AM, AN, AR, AS, AV, AY, AZ, BA, BE, BG, BH, BI, BM, BN, BO, BR, BS, CA, CE, CH, CO,
CR, CS, CU, CV, CY, DA, DE, DV, DZ, EE, EL, EN, EO, ES, ET, EU, FA, FF, FI, FJ, FO, FR, FY, GA, GD, GL,
GN, GU, GV, HA, HE, HI, HO, HR, HT, HU, HY, HZ, IA, ID, IE, IG, II, IK, IN, IO, IS, IT, IU, IW, JA, JI,
JV, KA, KG, KI, KJ, KK, KL, KM, KN, KO, KR, KS, KU, KV, KW, KY, LA, LB, LG, LI, LN, LO, LT, LU, LV, MG,
MH, MI, MK, ML, MN, MO, MR, MS, MT, MY, NA, NB, ND, NE, NG, NL, NN, NO, NR, NV, NY, OC, OJ, OM, OR, OS,
PA, PI, PL, PS, PT, QU, RM, RN, RO, RU, RW, SA, SC, SD, SE, SG, SI, SK, SL, SM, SN, SO, SQ, SR, SS, ST,
SU, SV, SW, TA, TE, TG, TH, TI, TK, TL, TN, TO, TR, TS, TT, TW, TY, UG, UK, UR, UZ, VE, VI, VO, WA, WO,
XH, YI, YO, ZA, ZH, ZH_HANS, ZU,
PT_BR
};
private static final ConcurrentMap<String, LangIso639> DISCOVERED_VALUES = new ConcurrentHashMap<>();
public static LangIso639[] values() {
return values(VALUES, DISCOVERED_VALUES.values(), LangIso639.class);
}
@JsonCreator
public static LangIso639 valueOf(String name) {
return valueOf(VALUES, DISCOVERED_VALUES, name, new FlexibleEnum.NewEnumCreator<LangIso639>() {
@Override public LangIso639 create(String name) {
return new LangIso639(name);
}
});
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/ModificationResult.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
public class ModificationResult<T> {
private final T result;
private final boolean newCreated;
public ModificationResult(T result, boolean newCreated) {
this.result = result;
this.newCreated = newCreated;
}
public boolean isNewCreated() {
return newCreated;
}
public T getResult() {
return result;
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/NotFoundException.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
public class NotFoundException extends TlkException {
public NotFoundException(TlkError<?> error, int statusCode) {
super(error, statusCode);
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/OperationRequestResult.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import ai.toloka.client.v1.operation.Operation;
public abstract class OperationRequestResult<T extends Operation<?, ?>> {
private final T operation;
public OperationRequestResult(T operation) {
this.operation = operation;
}
public T getOperation() {
return operation;
}
public boolean isSuccess() {
return operation == null || operation.isSuccess();
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/Owner.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Owner {
private String id;
private boolean myself;
@JsonProperty("company_id")
private String companyId;
public String getId() {
return id;
}
public boolean isMyself() {
return myself;
}
public String getCompanyId() {
return companyId;
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/RangeOperator.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
public enum RangeOperator {
gt, gte, lt, lte
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/RangeParam.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
public interface RangeParam {
String parameter();
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/Region.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
public class Region {
private final Long regionCode;
@JsonCreator
public Region(Long regionCode) {
this.regionCode = regionCode;
}
@JsonValue
public Long regionCode() {
return regionCode;
}
@Override public String toString() {
return regionCode.toString();
}
@Override public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Region region = (Region) o;
return Objects.equals(regionCode, region.regionCode);
}
@Override public int hashCode() {
return Objects.hash(regionCode);
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/RequestParameters.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.util.Map;
public interface RequestParameters {
Map<String, Object> getQueryParameters();
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/SearchRequest.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public abstract class SearchRequest extends AbstractRequestParameters implements RequestParameters {
private static final String SORT_PARAMETER = "sort";
private static final String LIMIT_PARAMETER = "limit";
private final Map<String, Object> filterParameters;
private final Map<String, Object> rangeParameters;
private final String sortParameter;
private final Integer limit;
protected SearchRequest(Map<String, Object> filterParameters, Map<String, Object> rangeParameters,
String sortParameter, Integer limit) {
this.filterParameters = filterParameters;
this.rangeParameters = rangeParameters;
this.sortParameter = sortParameter;
this.limit = limit;
}
@Override public Map<String, Object> getQueryParameters() {
Map<String, Object> params = new HashMap<>();
params.putAll(filterParameters);
params.putAll(rangeParameters);
params.put(SORT_PARAMETER, sortParameter);
params.put(LIMIT_PARAMETER, limit);
return filterNulls(params);
}
public abstract static class Builder<
G extends SearchRequest,
T extends Builder,
F extends FilterBuilder<?, T, ?>,
R extends RangeBuilder<?, T, ?>,
S extends SortBuilder<?, T, ?>> {
protected final F filterBuilder;
protected final R rangeBuilder;
protected final S sortBuilder;
private Integer limit;
protected Builder(F filterBuilder, R rangeBuilder, S sortBuilder) {
this.filterBuilder = filterBuilder;
this.filterBuilder.setBuilder(this);
this.rangeBuilder = rangeBuilder;
this.rangeBuilder.setBuilder(this);
this.sortBuilder = sortBuilder;
this.sortBuilder.setBuilder(this);
}
public F filter() {
return filterBuilder;
}
public R range() {
return rangeBuilder;
}
public S sort() {
return sortBuilder;
}
@SuppressWarnings("unchecked")
public T limit(int limit) {
this.limit = limit;
return (T) this;
}
public abstract G done();
protected Integer getLimit() {
return limit;
}
}
abstract static class SegmentBuilder<B extends Builder> {
private B builder;
public B and() {
return builder;
}
@SuppressWarnings("unchecked")
void setBuilder(Builder searchRequestBuilder) {
this.builder = (B) searchRequestBuilder;
}
}
public abstract static class FilterBuilder<
T extends FilterBuilder, B extends Builder, P extends FilterParam> extends SegmentBuilder<B> {
private Map<String, Object> filters = new LinkedHashMap<>();
public Map<String, Object> getFilterParameters() {
return filters;
}
protected void put(String property, Object value) {
filters.put(property, value);
}
@SuppressWarnings("unchecked")
public T by(P param, Object value) {
put(param.parameter(), value);
return (T) this;
}
}
public abstract static class RangeBuilder<T extends RangeBuilder, B extends Builder, P extends RangeParam>
extends SegmentBuilder<B> {
private Set<RangeItem> ranges = new LinkedHashSet<>();
@SuppressWarnings("unchecked")
public T by(P param, Object value, RangeOperator operator) {
return (T) new RangeItemBuilder<>(param.parameter(), value, this).withOperator(operator);
}
@SuppressWarnings("unchecked")
protected RangeItemBuilder<T> by(P param, Object value) {
return (RangeItemBuilder<T>) new RangeItemBuilder<>(param.parameter(), value, this);
}
public Map<String, Object> getRangeParameters() {
Map<String, Object> rangeParameters = new LinkedHashMap<>();
for (RangeItem range : ranges) {
rangeParameters.put(getRangeKey(range), range.getValue());
}
return rangeParameters;
}
void add(RangeItemBuilder<T> rangeItemBuilder) {
ranges.add(new RangeItem(rangeItemBuilder.name, rangeItemBuilder.value, rangeItemBuilder.operator));
}
private String getRangeKey(RangeItem rangeItem) {
return rangeItem.name + "_" + rangeItem.operator.name();
}
public class RangeItemBuilder<R extends RangeBuilder> {
private final String name;
private final Object value;
private RangeOperator operator;
private final R rangeBuilder;
RangeItemBuilder(String name, Object value, R rangeBuilder) {
this.name = name;
this.rangeBuilder = rangeBuilder;
this.value = value;
}
@SuppressWarnings("unchecked")
public R gt() {
operator = RangeOperator.gt;
rangeBuilder.add(this);
return rangeBuilder;
}
@SuppressWarnings("unchecked")
public R gte() {
operator = RangeOperator.gte;
rangeBuilder.add(this);
return rangeBuilder;
}
@SuppressWarnings("unchecked")
public R lt() {
operator = RangeOperator.lt;
rangeBuilder.add(this);
return rangeBuilder;
}
@SuppressWarnings("unchecked")
public R lte() {
operator = RangeOperator.lte;
rangeBuilder.add(this);
return rangeBuilder;
}
@SuppressWarnings("unchecked")
public R withOperator(RangeOperator operator) {
this.operator = operator;
rangeBuilder.add(this);
return rangeBuilder;
}
}
private class RangeItem {
private final String name;
private final Object value;
private final RangeOperator operator;
RangeItem(String name, Object value, RangeOperator operator) {
this.name = name;
this.value = value;
this.operator = operator;
}
public String getName() {
return name;
}
public Object getValue() {
return value;
}
public RangeOperator getOperator() {
return operator;
}
@Override public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
@SuppressWarnings("unchecked") RangeItem rangeItem = (RangeItem) o;
return Objects.equals(name, rangeItem.name)
&& Objects.equals(value, rangeItem.value)
&& operator == rangeItem.operator;
}
@Override public int hashCode() {
return Objects.hash(name, value, operator);
}
}
}
public abstract static class SortBuilder<T extends SortBuilder, B extends Builder, P extends SortParam>
extends SegmentBuilder<B> {
private Map<String, SortItem<T>> sorts = new LinkedHashMap<>();
@SuppressWarnings("unchecked")
public T by(P param, SortDirection direction) {
return put(param.parameter(), new SortItem<>((T) this)).direction(direction);
}
@SuppressWarnings("unchecked")
public SortItem<T> by(P param) {
return put(param.parameter(), new SortItem<>((T) this));
}
public String getSortParameter() {
if (!sorts.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, SortItem<T>> sort : sorts.entrySet()) {
if (sb.length() > 0) {
sb.append(',');
}
sb.append(getSortProperty(sort.getKey(), sort.getValue().isAscending()));
}
return sb.toString();
}
return null;
}
protected SortItem<T> put(String property, SortItem<T> sortItem) {
sorts.put(property, sortItem);
return sortItem;
}
private String getSortProperty(String property, boolean ascending) {
return ascending ? property : "-" + property;
}
public class SortItem<S extends SortBuilder> {
private final S sortBuilder;
private boolean ascending;
SortItem(S sortBuilder) {
this.sortBuilder = sortBuilder;
}
public S asc() {
ascending = true;
return sortBuilder;
}
public S desc() {
ascending = false;
return sortBuilder;
}
public boolean isAscending() {
return ascending;
}
public S direction(SortDirection direction) {
ascending = direction == SortDirection.asc;
return sortBuilder;
}
}
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/SearchResult.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class SearchResult<T> {
private List<T> items = new ArrayList<>();
@JsonProperty("has_more")
private boolean hasMore;
public List<T> getItems() {
return items;
}
public boolean isHasMore() {
return hasMore;
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/ServiceUnavailableException.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
public class ServiceUnavailableException extends TlkException {
public ServiceUnavailableException(TlkError<?> error, int statusCode) {
super(error, statusCode);
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/SortDirection.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
public enum SortDirection {
asc, desc
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/SortParam.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
public interface SortParam {
String parameter();
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/TlkError.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "code",
defaultImpl = TlkError.class, visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = ValidationError.class, name = ValidationError.VALIDATION_ERROR_CODE)
})
public class TlkError<P> {
public static final String NOT_FOUND_CODE = "NOT_FOUND";
public static final String METHOD_NOT_ALLOWED_CODE = "METHOD_NOT_ALLOWED";
public static final String NOT_ACCEPTABLE_CODE = "NOT_ACCEPTABLE";
public static final String UNSUPPORTED_MEDIA_TYPE_CODE = "UNSUPPORTED_MEDIA_TYPE";
public static final String AUTHENTICATION_ERROR_CODE = "AUTHENTICATION_ERROR";
public static final String ACCESS_DENIED_CODE = "ACCESS_DENIED";
public static final String DOES_NOT_EXIST_CODE = "DOES_NOT_EXIST";
public static final String CONFLICT_STATE_CODE = "CONFLICT_STATE";
public static final String VALIDATION_ERROR_CODE = "VALIDATION_ERROR";
public static final String TOO_MANY_REQUESTS_CODE = "TOO_MANY_REQUESTS";
public static final String ENTITY_TOO_LARGE_CODE = "ENTITY_TOO_LARGE";
public static final String REMOTE_SERVICE_UNAVAILABLE_CODE = "REMOTE_SERVICE_UNAVAILABLE";
public static final String INTERNAL_ERROR_CODE = "INTERNAL_ERROR";
public static final String NGINX_ERROR_CODE = "NGINX_ERROR";
/**
* Operation is not allowed because of unarchived pools. Please, archive all active pools before you proceed.
*/
public static final String UNARCHIVED_POOLS_CONFLICT_CODE = "UNARCHIVED_POOLS_CONFLICT";
/**
* Project is in an inappropriate status. Operation is not allowed.
*/
public static final String PROJECT_INAPPROPRIATE_STATUS_CODE = "PROJECT_INAPPROPRIATE_STATUS";
/**
* Pool contains no tasks. Operation is not allowed.
*/
public static final String EMPTY_POOL_CODE = "EMPTY_POOL";
/**
* There are submitted assignments which are not accepted.
*/
public static final String SUBMITTED_ASSIGNMENTS_CONFLICT_CODE = "SUBMITTED_ASSIGNMENTS_CONFLICT";
/**
* Pool is in an inappropriate status. Operation is not allowed.
*/
public static final String POOL_INAPPROPRIATE_STATUS_CODE = "POOL_INAPPROPRIATE_STATUS";
/**
* Pool must contain mixer config to perform request.
*/
public static final String MIXER_CONFIG_REQUIRED_CODE = "MIXER_CONFIG_REQUIRED";
/**
* Limit of task suites in pool have been exceeded.
*/
public static final String POOL_TASK_SUITES_COUNT_EXCEEDED_CODE = "POOL_TASK_SUITES_COUNT_EXCEEDED";
/**
* Limit of tasks in pool have been exceeded.
*/
public static final String POOL_TASKS_COUNT_EXCEEDED_CODE = "POOL_TASKS_COUNT_EXCEEDED";
/**
* Assignments count is already greater than requested value.
*/
public static final String ASSIGNMENTS_COUNT_CONFLICT_CODE = "ASSIGNMENTS_COUNT_CONFLICT";
/**
* Operation forbidden while pool locked by another operation.
*/
public static final String POOL_LOCKED_BY_ANOTHER_OPERATION_CODE = "POOL_LOCKED_BY_ANOTHER_OPERATION";
/**
* Restrictions in 'SYSTEM' scope are forbidden to modify.
*/
public static final String SYSTEM_SCOPE_MODIFICATION_CODE = "SYSTEM_SCOPE_MODIFICATION";
/**
* Batch processing may not be continued.
*/
public static final String BATCH_INITIALIZATION_ERROR_CODE = "BATCH_INITIALIZATION_ERROR";
/**
* Operation execution failed because of internal error. Operation will be terminated. Please contact support.
*/
public static final String OPERATION_EXECUTION_ERROR_CODE = "OPERATION_EXECUTION_ERROR";
/**
* Operation with provided id already exists.
*/
public static final String OPERATION_ALREADY_EXISTS_CODE = "OPERATION_ALREADY_EXISTS";
private final String code;
private final String requestId;
private final String message;
private final Map<String, P> payload;
@JsonCreator
public TlkError(@JsonProperty("code") String code, @JsonProperty("request_id") String requestId,
@JsonProperty("message") String message, @JsonProperty("property") Map<String, P> payload) {
this.code = code;
this.requestId = requestId;
this.message = message;
this.payload = payload;
}
public TlkError(String code, String message, Map<String, P> payload) {
this.code = code;
this.message = message;
this.payload = payload;
this.requestId = null;
}
public TlkError(String code, String message) {
this.code = code;
this.message = message;
this.requestId = null;
this.payload = null;
}
public String getCode() {
return code;
}
/**
* @return id of failed associated request, or null if no id was provided
*/
public String getRequestId() {
return requestId;
}
public String getMessage() {
return message;
}
/**
* @return payload of an error, or null if no payload provided
*/
public Map<String, P> getPayload() {
return payload;
}
@Override public String toString() {
return "TlkError{"
+ "code='" + code + '\''
+ ", requestId='" + requestId + '\''
+ ", message='" + message + '\''
+ ", payload=" + payload
+ '}';
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/TlkException.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
public class TlkException extends RuntimeException {
private final TlkError<?> error;
private final int statusCode;
public TlkException(TlkError<?> error, int statusCode) {
this.error = error;
this.statusCode = statusCode;
}
public TlkError<?> getError() {
return error;
}
public String getCode() {
return error.getCode();
}
public String getRequestId() {
return error.getRequestId();
}
public String getServerMessage() {
return error.getMessage();
}
public Object getPayload() {
return error.getPayload();
}
public int getStatusCode() {
return statusCode;
}
@Override public String getMessage() {
return toString();
}
@Override public String toString() {
return "TlkException{"
+ "error=" + error
+ ",statusCode=" + statusCode
+ '}';
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/TolokaClientFactory.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import ai.toloka.client.v1.aggregatedsolutions.AggregatedSolutionClient;
import ai.toloka.client.v1.assignment.AssignmentClient;
import ai.toloka.client.v1.attachment.AttachmentClient;
import ai.toloka.client.v1.messagethread.MessageThreadClient;
import ai.toloka.client.v1.metadata.UserMetadataClient;
import ai.toloka.client.v1.operation.OperationClient;
import ai.toloka.client.v1.pool.PoolClient;
import ai.toloka.client.v1.project.ProjectClient;
import ai.toloka.client.v1.requester.RequesterClient;
import ai.toloka.client.v1.skill.SkillClient;
import ai.toloka.client.v1.task.TaskClient;
import ai.toloka.client.v1.tasksuite.TaskSuiteClient;
import ai.toloka.client.v1.training.TrainingClient;
import ai.toloka.client.v1.userbonus.UserBonusClient;
import ai.toloka.client.v1.userrestriction.UserRestrictionClient;
import ai.toloka.client.v1.userskill.UserSkillClient;
import ai.toloka.client.v1.webhooksubscription.WebhookSubscriptionClient;
public interface TolokaClientFactory {
RequesterClient getRequesterClient();
ProjectClient getProjectClient();
PoolClient getPoolClient();
TrainingClient getTrainingClient();
TaskClient getTaskClient();
TaskSuiteClient getTaskSuiteClient();
AssignmentClient getAssignmentClient();
AggregatedSolutionClient getAggregatedSolutionClient();
UserSkillClient getUserSkillClient();
UserRestrictionClient getUserRestrictionClient();
AttachmentClient getAttachmentClient();
OperationClient getOperationClient();
SkillClient getSkillClient();
UserBonusClient getUserBonusClient();
MessageThreadClient getMessageThreadClient();
WebhookSubscriptionClient getWebhookSubscriptionClient();
UserMetadataClient getUserMetadataClient();
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/TolokaRequestIOException.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.io.IOException;
public class TolokaRequestIOException extends RuntimeException {
public TolokaRequestIOException(final IOException e) {
super(e);
}
}
|
0 | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client | java-sources/ai/toloka/toloka-java-sdk/0.0.7/ai/toloka/client/v1/ValidationError.java | /*
* Copyright 2021 YANDEX LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.toloka.client.v1;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ValidationError extends TlkError<FieldValidationError> {
public static final String VALIDATION_ERROR_CODE = "VALIDATION_ERROR";
@JsonCreator
public ValidationError(@JsonProperty("code") String code,
@JsonProperty("request_id") String requestId,
@JsonProperty("message") String message,
@JsonProperty("property") Map<String, FieldValidationError> payload) {
super(code, requestId, message, payload);
}
public ValidationError(String code, String message, Map<String, FieldValidationError> payload) {
super(code, message, payload);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.