index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/timefold/solver/timefold-solver-jpa/1.26.1/ai/timefold/solver/jpa/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jpa/1.26.1/ai/timefold/solver/jpa/api/score/buildin/hardsoftlong/HardSoftLongScoreConverter.java | package ai.timefold.solver.jpa.api.score.buildin.hardsoftlong;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
@Converter
public class HardSoftLongScoreConverter implements AttributeConverter<HardSoftLongScore, String> {
@Override
public String convertToDatabaseColumn(HardSoftLongScore score) {
if (score == null) {
return null;
}
return score.toString();
}
@Override
public HardSoftLongScore convertToEntityAttribute(String scoreString) {
if (scoreString == null) {
return null;
}
return HardSoftLongScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jpa/1.26.1/ai/timefold/solver/jpa/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jpa/1.26.1/ai/timefold/solver/jpa/api/score/buildin/simple/SimpleScoreConverter.java | package ai.timefold.solver.jpa.api.score.buildin.simple;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
@Converter
public class SimpleScoreConverter implements AttributeConverter<SimpleScore, String> {
@Override
public String convertToDatabaseColumn(SimpleScore score) {
if (score == null) {
return null;
}
return score.toString();
}
@Override
public SimpleScore convertToEntityAttribute(String scoreString) {
if (scoreString == null) {
return null;
}
return SimpleScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jpa/1.26.1/ai/timefold/solver/jpa/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jpa/1.26.1/ai/timefold/solver/jpa/api/score/buildin/simplebigdecimal/SimpleBigDecimalScoreConverter.java | package ai.timefold.solver.jpa.api.score.buildin.simplebigdecimal;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore;
@Converter
public class SimpleBigDecimalScoreConverter implements AttributeConverter<SimpleBigDecimalScore, String> {
@Override
public String convertToDatabaseColumn(SimpleBigDecimalScore score) {
if (score == null) {
return null;
}
return score.toString();
}
@Override
public SimpleBigDecimalScore convertToEntityAttribute(String scoreString) {
if (scoreString == null) {
return null;
}
return SimpleBigDecimalScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jpa/1.26.1/ai/timefold/solver/jpa/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jpa/1.26.1/ai/timefold/solver/jpa/api/score/buildin/simplelong/SimpleLongScoreConverter.java | package ai.timefold.solver.jpa.api.score.buildin.simplelong;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import ai.timefold.solver.core.api.score.buildin.simplelong.SimpleLongScore;
@Converter
public class SimpleLongScoreConverter implements AttributeConverter<SimpleLongScore, String> {
@Override
public String convertToDatabaseColumn(SimpleLongScore score) {
if (score == null) {
return null;
}
return score.toString();
}
@Override
public SimpleLongScore convertToEntityAttribute(String scoreString) {
if (scoreString == null) {
return null;
}
return SimpleLongScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/TimefoldJsonbConfig.java | package ai.timefold.solver.jsonb.api;
import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;
import jakarta.json.bind.JsonbConfig;
import jakarta.json.bind.adapter.JsonbAdapter;
import ai.timefold.solver.jsonb.api.score.buildin.bendable.BendableScoreJsonbAdapter;
import ai.timefold.solver.jsonb.api.score.buildin.bendablebigdecimal.BendableBigDecimalScoreJsonbAdapter;
import ai.timefold.solver.jsonb.api.score.buildin.bendablelong.BendableLongScoreJsonbAdapter;
import ai.timefold.solver.jsonb.api.score.buildin.hardmediumsoft.HardMediumSoftScoreJsonbAdapter;
import ai.timefold.solver.jsonb.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScoreJsonbAdapter;
import ai.timefold.solver.jsonb.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScoreJsonbAdapter;
import ai.timefold.solver.jsonb.api.score.buildin.hardsoft.HardSoftScoreJsonbAdapter;
import ai.timefold.solver.jsonb.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScoreJsonbAdapter;
import ai.timefold.solver.jsonb.api.score.buildin.hardsoftlong.HardSoftLongScoreJsonbAdapter;
import ai.timefold.solver.jsonb.api.score.buildin.simple.SimpleScoreJsonbAdapter;
import ai.timefold.solver.jsonb.api.score.buildin.simplebigdecimal.SimpleBigDecimalScoreJsonbAdapter;
import ai.timefold.solver.jsonb.api.score.buildin.simplelong.SimpleLongScoreJsonbAdapter;
/**
* This class adds all JSON-B adapters.
*/
public class TimefoldJsonbConfig {
/**
* @return never null, use it to create a {@link Jsonb} instance with {@link JsonbBuilder#create(JsonbConfig)}.
*/
public static JsonbConfig createConfig() {
JsonbConfig config = new JsonbConfig()
.withAdapters(new BendableScoreJsonbAdapter(),
new BendableBigDecimalScoreJsonbAdapter(),
new BendableLongScoreJsonbAdapter(),
new HardMediumSoftScoreJsonbAdapter(),
new HardMediumSoftBigDecimalScoreJsonbAdapter(),
new HardMediumSoftLongScoreJsonbAdapter(),
new HardSoftScoreJsonbAdapter(),
new HardSoftBigDecimalScoreJsonbAdapter(),
new HardSoftLongScoreJsonbAdapter(),
new SimpleScoreJsonbAdapter(),
new SimpleBigDecimalScoreJsonbAdapter(),
new SimpleLongScoreJsonbAdapter());
return config;
}
/**
* @return never null, use it to customize a {@link JsonbConfig} instance with
* {@link JsonbConfig#withAdapters(JsonbAdapter[])}.
*/
public static JsonbAdapter[] getScoreJsonbAdapters() {
return new JsonbAdapter[] {
new BendableScoreJsonbAdapter(),
new BendableBigDecimalScoreJsonbAdapter(),
new BendableLongScoreJsonbAdapter(),
new HardMediumSoftScoreJsonbAdapter(),
new HardMediumSoftBigDecimalScoreJsonbAdapter(),
new HardMediumSoftLongScoreJsonbAdapter(),
new HardSoftScoreJsonbAdapter(),
new HardSoftBigDecimalScoreJsonbAdapter(),
new HardSoftLongScoreJsonbAdapter(),
new SimpleScoreJsonbAdapter(),
new SimpleBigDecimalScoreJsonbAdapter(),
new SimpleLongScoreJsonbAdapter() };
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/package-info.java |
/**
* JSON-B bindings for {@link ai.timefold.solver.core.api.score.Score}.
*/
package ai.timefold.solver.jsonb.api;
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/AbstractScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score;
import jakarta.json.bind.adapter.JsonbAdapter;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.jsonb.api.TimefoldJsonbConfig;
/**
* JSON-B binding support for a {@link Score} type.
* <p>
* For example: use {@code @JsonbTypeAdapter(HardSoftScoreJsonbAdapter.class)}
* on a {@code HardSoftScore score} field and it will be serialized to JSON as {@code "score":"-999hard/-999soft"}.
* Or better yet, use {@link TimefoldJsonbConfig} instead.
*
* @see Score
* @param <Score_> the actual score type
*/
public abstract class AbstractScoreJsonbAdapter<Score_ extends Score<Score_>> implements JsonbAdapter<Score_, String> {
@Override
public String adaptToJson(Score_ score) {
return score.toString();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin/bendable/BendableScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score.buildin.bendable;
import ai.timefold.solver.core.api.score.buildin.bendable.BendableScore;
import ai.timefold.solver.jsonb.api.score.AbstractScoreJsonbAdapter;
public class BendableScoreJsonbAdapter extends AbstractScoreJsonbAdapter<BendableScore> {
@Override
public BendableScore adaptFromJson(String scoreString) {
return BendableScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin/bendablebigdecimal/BendableBigDecimalScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score.buildin.bendablebigdecimal;
import ai.timefold.solver.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore;
import ai.timefold.solver.jsonb.api.score.AbstractScoreJsonbAdapter;
public class BendableBigDecimalScoreJsonbAdapter extends AbstractScoreJsonbAdapter<BendableBigDecimalScore> {
@Override
public BendableBigDecimalScore adaptFromJson(String scoreString) {
return BendableBigDecimalScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin/bendablelong/BendableLongScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score.buildin.bendablelong;
import ai.timefold.solver.core.api.score.buildin.bendablelong.BendableLongScore;
import ai.timefold.solver.jsonb.api.score.AbstractScoreJsonbAdapter;
public class BendableLongScoreJsonbAdapter extends AbstractScoreJsonbAdapter<BendableLongScore> {
@Override
public BendableLongScore adaptFromJson(String scoreString) {
return BendableLongScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin/hardmediumsoft/HardMediumSoftScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score.buildin.hardmediumsoft;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
import ai.timefold.solver.jsonb.api.score.AbstractScoreJsonbAdapter;
public class HardMediumSoftScoreJsonbAdapter extends AbstractScoreJsonbAdapter<HardMediumSoftScore> {
@Override
public HardMediumSoftScore adaptFromJson(String scoreString) {
return HardMediumSoftScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin/hardmediumsoftbigdecimal/HardMediumSoftBigDecimalScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score.buildin.hardmediumsoftbigdecimal;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScore;
import ai.timefold.solver.jsonb.api.score.AbstractScoreJsonbAdapter;
public class HardMediumSoftBigDecimalScoreJsonbAdapter extends AbstractScoreJsonbAdapter<HardMediumSoftBigDecimalScore> {
@Override
public HardMediumSoftBigDecimalScore adaptFromJson(String scoreString) {
return HardMediumSoftBigDecimalScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin/hardmediumsoftlong/HardMediumSoftLongScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score.buildin.hardmediumsoftlong;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore;
import ai.timefold.solver.jsonb.api.score.AbstractScoreJsonbAdapter;
public class HardMediumSoftLongScoreJsonbAdapter extends AbstractScoreJsonbAdapter<HardMediumSoftLongScore> {
@Override
public HardMediumSoftLongScore adaptFromJson(String scoreString) {
return HardMediumSoftLongScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin/hardsoft/HardSoftScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score.buildin.hardsoft;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.jsonb.api.score.AbstractScoreJsonbAdapter;
public class HardSoftScoreJsonbAdapter extends AbstractScoreJsonbAdapter<HardSoftScore> {
@Override
public HardSoftScore adaptFromJson(String scoreString) {
return HardSoftScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin/hardsoftbigdecimal/HardSoftBigDecimalScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score.buildin.hardsoftbigdecimal;
import ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore;
import ai.timefold.solver.jsonb.api.score.AbstractScoreJsonbAdapter;
public class HardSoftBigDecimalScoreJsonbAdapter extends AbstractScoreJsonbAdapter<HardSoftBigDecimalScore> {
@Override
public HardSoftBigDecimalScore adaptFromJson(String scoreString) {
return HardSoftBigDecimalScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin/hardsoftlong/HardSoftLongScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score.buildin.hardsoftlong;
import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
import ai.timefold.solver.jsonb.api.score.AbstractScoreJsonbAdapter;
public class HardSoftLongScoreJsonbAdapter extends AbstractScoreJsonbAdapter<HardSoftLongScore> {
@Override
public HardSoftLongScore adaptFromJson(String scoreString) {
return HardSoftLongScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin/simple/SimpleScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score.buildin.simple;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
import ai.timefold.solver.jsonb.api.score.AbstractScoreJsonbAdapter;
public class SimpleScoreJsonbAdapter extends AbstractScoreJsonbAdapter<SimpleScore> {
@Override
public SimpleScore adaptFromJson(String scoreString) {
return SimpleScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin/simplebigdecimal/SimpleBigDecimalScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score.buildin.simplebigdecimal;
import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore;
import ai.timefold.solver.jsonb.api.score.AbstractScoreJsonbAdapter;
public class SimpleBigDecimalScoreJsonbAdapter extends AbstractScoreJsonbAdapter<SimpleBigDecimalScore> {
@Override
public SimpleBigDecimalScore adaptFromJson(String scoreString) {
return SimpleBigDecimalScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin | java-sources/ai/timefold/solver/timefold-solver-jsonb/1.26.1/ai/timefold/solver/jsonb/api/score/buildin/simplelong/SimpleLongScoreJsonbAdapter.java | package ai.timefold.solver.jsonb.api.score.buildin.simplelong;
import ai.timefold.solver.core.api.score.buildin.simplelong.SimpleLongScore;
import ai.timefold.solver.jsonb.api.score.AbstractScoreJsonbAdapter;
public class SimpleLongScoreJsonbAdapter extends AbstractScoreJsonbAdapter<SimpleLongScore> {
@Override
public SimpleLongScore adaptFromJson(String scoreString) {
return SimpleLongScore.parseScore(scoreString);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration/AbstractRecipe.java | package ai.timefold.solver.migration;
import org.openrewrite.Recipe;
import org.openrewrite.java.JavaParser;
public abstract class AbstractRecipe extends Recipe {
public static final JavaParser.Builder<?, ?> JAVA_PARSER = JavaParser.fromJavaVersion()
.classpath(JavaParser.runtimeClasspath());
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration/fork/TimefoldChangeDependencies.java | package ai.timefold.solver.migration.fork;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.migration.AbstractRecipe;
import org.openrewrite.Recipe;
import org.openrewrite.gradle.ChangeDependencyArtifactId;
import org.openrewrite.gradle.ChangeDependencyGroupId;
import org.openrewrite.maven.ChangeDependencyGroupIdAndArtifactId;
import org.openrewrite.maven.ChangeManagedDependencyGroupIdAndArtifactId;
public final class TimefoldChangeDependencies extends AbstractRecipe {
private static final String[] ARTIFACT_SUFFIXES = new String[] {
"parent",
"bom",
"ide-config",
"build-parent",
"core-parent",
"core-impl",
"constraint-streams-common",
"constraint-streams-bavet",
"constraint-streams-drools",
"constraint-drl",
"core",
"persistence",
"persistence-common",
"persistence-xstream",
"persistence-jaxb",
"persistence-jackson",
"persistence-jpa",
"persistence-jsonb",
"benchmark",
"test",
"spring-integration",
"spring-boot-autoconfigure",
"spring-boot-starter",
"quarkus-integration",
"quarkus-parent",
"quarkus",
"quarkus-deployment",
"quarkus-integration-test",
"quarkus-reflection-integration-test",
"quarkus-devui-integration-test",
"quarkus-drl-integration-test",
"quarkus-benchmark-parent",
"quarkus-benchmark",
"quarkus-benchmark-deployment",
"quarkus-benchmark-integration-test",
"quarkus-jackson-parent",
"quarkus-jackson",
"quarkus-jackson-deployment",
"quarkus-jackson-integration-test",
"quarkus-jsonb-parent",
"quarkus-jsonb",
"quarkus-jsonb-deployment",
"quarkus-jsonb-integration-test",
"migration",
"examples",
"docs"
};
private final List<Recipe> recipeList = new ArrayList<>();
public TimefoldChangeDependencies() {
String oldGroupId = "org.optaplanner";
String newGroupId = "ai.timefold.solver";
for (String artifactSuffix : ARTIFACT_SUFFIXES) {
String oldArtifactId = "optaplanner-" + artifactSuffix;
String newArtifactSuffix;
if (artifactSuffix.equals("persistence")) {
newArtifactSuffix = "persistence-parent";
} else if (artifactSuffix.startsWith("persistence-")) {
if (artifactSuffix.equals("persistence-common")) {
newArtifactSuffix = artifactSuffix;
} else {
newArtifactSuffix = artifactSuffix.substring("persistence-".length());
}
} else {
newArtifactSuffix = artifactSuffix;
}
String newArtifactId = "timefold-solver-" + newArtifactSuffix;
// Maven
recipeList.add(new ChangeManagedDependencyGroupIdAndArtifactId(oldGroupId, oldArtifactId, newGroupId, newArtifactId,
null));
recipeList.add(
new ChangeDependencyGroupIdAndArtifactId(oldGroupId, oldArtifactId, newGroupId, newArtifactId, null, null));
// Gradle
recipeList.add(new ChangeDependencyArtifactId(oldGroupId, oldArtifactId, newArtifactId, null));
}
// TODO Do not use "*" approach. This is a workaround for https://github.com/openrewrite/rewrite/issues/2994
recipeList.add(new ChangeDependencyGroupId(oldGroupId, "*", newGroupId, null));
}
@Override
public String getDisplayName() {
return "Migrate all Maven and Gradle groupIds and artifactIds from OptaPlanner to Timefold";
}
@Override
public String getDescription() {
return getDisplayName() + ".";
}
@Override
public List<Recipe> getRecipeList() {
return recipeList;
}
@Override
public boolean equals(Object o) {
return o instanceof TimefoldChangeDependencies other && recipeList.equals(other.recipeList);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), recipeList);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration/v8/AsConstraintRecipe.java | package ai.timefold.solver.migration.v8;
import java.util.Arrays;
import java.util.Objects;
import java.util.regex.Pattern;
import ai.timefold.solver.migration.AbstractRecipe;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class AsConstraintRecipe extends AbstractRecipe {
private static final Logger LOGGER = LoggerFactory.getLogger(AsConstraintRecipe.class);
private static final MatcherMeta[] MATCHER_METAS = {
new MatcherMeta("ConstraintStream", "penalize(String, Score)"),
new MatcherMeta("ConstraintStream", "penalize(String, String, Score)"),
new MatcherMeta("ConstraintStream", "penalizeConfigurable(String)"),
new MatcherMeta("ConstraintStream", "penalizeConfigurable(String, String)"),
new MatcherMeta("ConstraintStream", "reward(String, Score)"),
new MatcherMeta("ConstraintStream", "reward(String, String, Score)"),
new MatcherMeta("ConstraintStream", "rewardConfigurable(String)"),
new MatcherMeta("ConstraintStream", "rewardConfigurable(String, String)"),
new MatcherMeta("ConstraintStream", "impact(String, Score)"),
new MatcherMeta("ConstraintStream", "impact(String, String, Score)"),
new MatcherMeta("ConstraintStream", "impactConfigurable(String)"),
new MatcherMeta("ConstraintStream", "impactConfigurable(String, String)"),
new MatcherMeta("UniConstraintStream", "penalize(String, Score, ToIntFunction)"),
new MatcherMeta("UniConstraintStream", "penalize(String, String, Score, ToIntFunction)"),
new MatcherMeta("UniConstraintStream", "penalizeConfigurable(String, ToIntFunction)"),
new MatcherMeta("UniConstraintStream", "penalizeConfigurable(String, String, ToIntFunction)"),
new MatcherMeta("UniConstraintStream", "penalizeLong(String, Score, ToLongFunction)"),
new MatcherMeta("UniConstraintStream", "penalizeLong(String, String, Score, ToLongFunction)"),
new MatcherMeta("UniConstraintStream", "penalizeConfigurableLong(String, ToLongFunction)"),
new MatcherMeta("UniConstraintStream", "penalizeConfigurableLong(String, String, ToLongFunction)"),
new MatcherMeta("UniConstraintStream", "penalizeBigDecimal(String, Score, Function)"),
new MatcherMeta("UniConstraintStream", "penalizeBigDecimal(String, String, Score, Function)"),
new MatcherMeta("UniConstraintStream", "penalizeConfigurableBigDecimal(String, Function)"),
new MatcherMeta("UniConstraintStream", "penalizeConfigurableBigDecimal(String, String, Function)"),
new MatcherMeta("UniConstraintStream", "reward(String, Score, ToIntFunction)"),
new MatcherMeta("UniConstraintStream", "reward(String, String, Score, ToIntFunction)"),
new MatcherMeta("UniConstraintStream", "rewardConfigurable(String, ToIntFunction)"),
new MatcherMeta("UniConstraintStream", "rewardConfigurable(String, String, ToIntFunction)"),
new MatcherMeta("UniConstraintStream", "rewardLong(String, Score, ToLongFunction)"),
new MatcherMeta("UniConstraintStream", "rewardLong(String, String, Score, ToLongFunction)"),
new MatcherMeta("UniConstraintStream", "rewardConfigurableLong(String, ToLongFunction)"),
new MatcherMeta("UniConstraintStream", "rewardConfigurableLong(String, String, ToLongFunction)"),
new MatcherMeta("UniConstraintStream", "rewardBigDecimal(String, Score, Function)"),
new MatcherMeta("UniConstraintStream", "rewardBigDecimal(String, String, Score, Function)"),
new MatcherMeta("UniConstraintStream", "rewardConfigurableBigDecimal(String, Function)"),
new MatcherMeta("UniConstraintStream", "rewardConfigurableBigDecimal(String, String, Function)"),
new MatcherMeta("UniConstraintStream", "impact(String, Score, ToIntFunction)"),
new MatcherMeta("UniConstraintStream", "impact(String, String, Score, ToIntFunction)"),
new MatcherMeta("UniConstraintStream", "impactConfigurable(String, ToIntFunction)"),
new MatcherMeta("UniConstraintStream", "impactConfigurable(String, String, ToIntFunction)"),
new MatcherMeta("UniConstraintStream", "impactLong(String, Score, ToLongFunction)"),
new MatcherMeta("UniConstraintStream", "impactLong(String, String, Score, ToLongFunction)"),
new MatcherMeta("UniConstraintStream", "impactConfigurableLong(String, ToLongFunction)"),
new MatcherMeta("UniConstraintStream", "impactConfigurableLong(String, String, ToLongFunction)"),
new MatcherMeta("UniConstraintStream", "impactBigDecimal(String, Score, Function)"),
new MatcherMeta("UniConstraintStream", "impactBigDecimal(String, String, Score, Function)"),
new MatcherMeta("UniConstraintStream", "impactConfigurableBigDecimal(String, Function)"),
new MatcherMeta("UniConstraintStream", "impactConfigurableBigDecimal(String, String, Function)"),
new MatcherMeta("BiConstraintStream", "penalize(String, Score, ToIntBiFunction)"),
new MatcherMeta("BiConstraintStream", "penalize(String, String, Score, ToIntBiFunction)"),
new MatcherMeta("BiConstraintStream", "penalizeConfigurable(String, ToIntBiFunction)"),
new MatcherMeta("BiConstraintStream", "penalizeConfigurable(String, String, ToIntBiFunction)"),
new MatcherMeta("BiConstraintStream", "penalizeLong(String, Score, ToLongBiFunction)"),
new MatcherMeta("BiConstraintStream", "penalizeLong(String, String, Score, ToLongBiFunction)"),
new MatcherMeta("BiConstraintStream", "penalizeConfigurableLong(String, ToLongBiFunction)"),
new MatcherMeta("BiConstraintStream", "penalizeConfigurableLong(String, String, ToLongBiFunction)"),
new MatcherMeta("BiConstraintStream", "penalizeBigDecimal(String, Score, BiFunction)"),
new MatcherMeta("BiConstraintStream", "penalizeBigDecimal(String, String, Score, BiFunction)"),
new MatcherMeta("BiConstraintStream", "penalizeConfigurableBigDecimal(String, BiFunction)"),
new MatcherMeta("BiConstraintStream", "penalizeConfigurableBigDecimal(String, String, BiFunction)"),
new MatcherMeta("BiConstraintStream", "reward(String, Score, ToIntBiFunction)"),
new MatcherMeta("BiConstraintStream", "reward(String, String, Score, ToIntBiFunction)"),
new MatcherMeta("BiConstraintStream", "rewardConfigurable(String, ToIntBiFunction)"),
new MatcherMeta("BiConstraintStream", "rewardConfigurable(String, String, ToIntBiFunction)"),
new MatcherMeta("BiConstraintStream", "rewardLong(String, Score, ToLongBiFunction)"),
new MatcherMeta("BiConstraintStream", "rewardLong(String, String, Score, ToLongBiFunction)"),
new MatcherMeta("BiConstraintStream", "rewardConfigurableLong(String, ToLongBiFunction)"),
new MatcherMeta("BiConstraintStream", "rewardConfigurableLong(String, String, ToLongBiFunction)"),
new MatcherMeta("BiConstraintStream", "rewardBigDecimal(String, Score, BiFunction)"),
new MatcherMeta("BiConstraintStream", "rewardBigDecimal(String, String, Score, BiFunction)"),
new MatcherMeta("BiConstraintStream", "rewardConfigurableBigDecimal(String, BiFunction)"),
new MatcherMeta("BiConstraintStream", "rewardConfigurableBigDecimal(String, String, BiFunction)"),
new MatcherMeta("BiConstraintStream", "impact(String, Score, ToIntBiFunction)"),
new MatcherMeta("BiConstraintStream", "impact(String, String, Score, ToIntBiFunction)"),
new MatcherMeta("BiConstraintStream", "impactConfigurable(String, ToIntBiFunction)"),
new MatcherMeta("BiConstraintStream", "impactConfigurable(String, String, ToIntBiFunction)"),
new MatcherMeta("BiConstraintStream", "impactLong(String, Score, ToLongBiFunction)"),
new MatcherMeta("BiConstraintStream", "impactLong(String, String, Score, ToLongBiFunction)"),
new MatcherMeta("BiConstraintStream", "impactConfigurableLong(String, ToLongBiFunction)"),
new MatcherMeta("BiConstraintStream", "impactConfigurableLong(String, String, ToLongBiFunction)"),
new MatcherMeta("BiConstraintStream", "impactBigDecimal(String, Score, BiFunction)"),
new MatcherMeta("BiConstraintStream", "impactBigDecimal(String, String, Score, BiFunction)"),
new MatcherMeta("BiConstraintStream", "impactConfigurableBigDecimal(String, BiFunction)"),
new MatcherMeta("BiConstraintStream", "impactConfigurableBigDecimal(String, String, BiFunction)"),
new MatcherMeta("TriConstraintStream", "penalize(String, Score, ToIntTriFunction)"),
new MatcherMeta("TriConstraintStream", "penalize(String, String, Score, ToIntTriFunction)"),
new MatcherMeta("TriConstraintStream", "penalizeConfigurable(String, ToIntTriFunction)"),
new MatcherMeta("TriConstraintStream", "penalizeConfigurable(String, String, ToIntTriFunction)"),
new MatcherMeta("TriConstraintStream", "penalizeLong(String, Score, ToLongTriFunction)"),
new MatcherMeta("TriConstraintStream", "penalizeLong(String, String, Score, ToLongTriFunction)"),
new MatcherMeta("TriConstraintStream", "penalizeConfigurableLong(String, ToLongTriFunction)"),
new MatcherMeta("TriConstraintStream", "penalizeConfigurableLong(String, String, ToLongTriFunction)"),
new MatcherMeta("TriConstraintStream", "penalizeBigDecimal(String, Score, TriFunction)"),
new MatcherMeta("TriConstraintStream", "penalizeBigDecimal(String, String, Score, TriFunction)"),
new MatcherMeta("TriConstraintStream", "penalizeConfigurableBigDecimal(String, TriFunction)"),
new MatcherMeta("TriConstraintStream", "penalizeConfigurableBigDecimal(String, String, TriFunction)"),
new MatcherMeta("TriConstraintStream", "reward(String, Score, ToIntTriFunction)"),
new MatcherMeta("TriConstraintStream", "reward(String, String, Score, ToIntTriFunction)"),
new MatcherMeta("TriConstraintStream", "rewardConfigurable(String, ToIntTriFunction)"),
new MatcherMeta("TriConstraintStream", "rewardConfigurable(String, String, ToIntTriFunction)"),
new MatcherMeta("TriConstraintStream", "rewardLong(String, Score, ToLongTriFunction)"),
new MatcherMeta("TriConstraintStream", "rewardLong(String, String, Score, ToLongTriFunction)"),
new MatcherMeta("TriConstraintStream", "rewardConfigurableLong(String, ToLongTriFunction)"),
new MatcherMeta("TriConstraintStream", "rewardConfigurableLong(String, String, ToLongTriFunction)"),
new MatcherMeta("TriConstraintStream", "rewardBigDecimal(String, Score, TriFunction)"),
new MatcherMeta("TriConstraintStream", "rewardBigDecimal(String, String, Score, TriFunction)"),
new MatcherMeta("TriConstraintStream", "rewardConfigurableBigDecimal(String, TriFunction)"),
new MatcherMeta("TriConstraintStream", "rewardConfigurableBigDecimal(String, String, TriFunction)"),
new MatcherMeta("TriConstraintStream", "impact(String, Score, ToIntTriFunction)"),
new MatcherMeta("TriConstraintStream", "impact(String, String, Score, ToIntTriFunction)"),
new MatcherMeta("TriConstraintStream", "impactConfigurable(String, ToIntTriFunction)"),
new MatcherMeta("TriConstraintStream", "impactConfigurable(String, String, ToIntTriFunction)"),
new MatcherMeta("TriConstraintStream", "impactLong(String, Score, ToLongTriFunction)"),
new MatcherMeta("TriConstraintStream", "impactLong(String, String, Score, ToLongTriFunction)"),
new MatcherMeta("TriConstraintStream", "impactConfigurableLong(String, ToLongTriFunction)"),
new MatcherMeta("TriConstraintStream", "impactConfigurableLong(String, String, ToLongTriFunction)"),
new MatcherMeta("TriConstraintStream", "impactBigDecimal(String, Score, TriFunction)"),
new MatcherMeta("TriConstraintStream", "impactBigDecimal(String, String, Score, TriFunction)"),
new MatcherMeta("TriConstraintStream", "impactConfigurableBigDecimal(String, TriFunction)"),
new MatcherMeta("TriConstraintStream", "impactConfigurableBigDecimal(String, String, TriFunction)"),
new MatcherMeta("QuadConstraintStream", "penalize(String, Score, ToIntQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "penalize(String, String, Score, ToIntQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "penalizeConfigurable(String, ToIntQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "penalizeConfigurable(String, String, ToIntQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "penalizeLong(String, Score, ToLongQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "penalizeLong(String, String, Score, ToLongQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "penalizeConfigurableLong(String, ToLongQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "penalizeConfigurableLong(String, String, ToLongQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "penalizeBigDecimal(String, Score, QuadFunction)"),
new MatcherMeta("QuadConstraintStream", "penalizeBigDecimal(String, String, Score, QuadFunction)"),
new MatcherMeta("QuadConstraintStream", "penalizeConfigurableBigDecimal(String, QuadFunction)"),
new MatcherMeta("QuadConstraintStream", "penalizeConfigurableBigDecimal(String, String, QuadFunction)"),
new MatcherMeta("QuadConstraintStream", "reward(String, Score, ToIntQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "reward(String, String, Score, ToIntQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "rewardConfigurable(String, ToIntQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "rewardConfigurable(String, String, ToIntQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "rewardLong(String, Score, ToLongQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "rewardLong(String, String, Score, ToLongQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "rewardConfigurableLong(String, ToLongQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "rewardConfigurableLong(String, String, ToLongQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "rewardBigDecimal(String, Score, QuadFunction)"),
new MatcherMeta("QuadConstraintStream", "rewardBigDecimal(String, String, Score, QuadFunction)"),
new MatcherMeta("QuadConstraintStream", "rewardConfigurableBigDecimal(String, QuadFunction)"),
new MatcherMeta("QuadConstraintStream", "rewardConfigurableBigDecimal(String, String, QuadFunction)"),
new MatcherMeta("QuadConstraintStream", "impact(String, Score, ToIntQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "impact(String, String, Score, ToIntQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "impactConfigurable(String, ToIntQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "impactConfigurable(String, String, ToIntQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "impactLong(String, Score, ToLongQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "impactLong(String, String, Score, ToLongQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "impactConfigurableLong(String, ToLongQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "impactConfigurableLong(String, String, ToLongQuadFunction)"),
new MatcherMeta("QuadConstraintStream", "impactBigDecimal(String, Score, QuadFunction)"),
new MatcherMeta("QuadConstraintStream", "impactBigDecimal(String, String, Score, QuadFunction)"),
new MatcherMeta("QuadConstraintStream", "impactConfigurableBigDecimal(String, QuadFunction)"),
new MatcherMeta("QuadConstraintStream", "impactConfigurableBigDecimal(String, String, QuadFunction)"),
};
@Override
public String getDisplayName() {
return "ConstraintStreams: use asConstraint() methods to define constraints";
}
@Override
public String getDescription() {
return "Use `penalize().asConstraint()` and `reward().asConstraint()`" +
" instead of the deprecated `penalize()` and `reward()` methods.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
TreeVisitor<?, ExecutionContext>[] visitors = Arrays.stream(MATCHER_METAS)
.map(m -> new UsesMethod<>(m.methodMatcher))
.toArray(TreeVisitor[]::new);
return Preconditions.check(
Preconditions.or(visitors),
new JavaIsoVisitor<>() {
private final Pattern uniConstraintStreamPattern = Pattern.compile(
"ai.timefold.solver.core.api.score.stream.uni.UniConstraintStream");
private final Pattern biConstraintStreamPattern = Pattern.compile(
"ai.timefold.solver.core.api.score.stream.bi.BiConstraintStream");
private final Pattern triConstraintStreamPattern = Pattern.compile(
"ai.timefold.solver.core.api.score.stream.tri.TriConstraintStream");
private final Pattern quadConstraintStreamPattern = Pattern.compile(
"ai.timefold.solver.core.api.score.stream.quad.QuadConstraintStream");
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation originalMethod,
ExecutionContext executionContext) {
var method = super.visitMethodInvocation(originalMethod, executionContext);
var matcherMeta = Arrays.stream(MATCHER_METAS)
.filter(m -> m.methodMatcher.matches(method))
.findFirst()
.orElse(null);
if (matcherMeta == null) {
return method;
}
var select = Objects.requireNonNull(method.getSelect());
var arguments = method.getArguments();
String templateCode;
var selectType = Objects.requireNonNull(select.getType());
if (selectType.isAssignableFrom(uniConstraintStreamPattern)) {
templateCode = "#{any(ai.timefold.solver.core.api.score.stream.uni.UniConstraintStream)}\n";
} else if (selectType.isAssignableFrom(biConstraintStreamPattern)) {
templateCode = "#{any(ai.timefold.solver.core.api.score.stream.bi.BiConstraintStream)}\n";
} else if (selectType.isAssignableFrom(triConstraintStreamPattern)) {
templateCode = "#{any(ai.timefold.solver.core.api.score.stream.tri.TriConstraintStream)}\n";
} else if (selectType.isAssignableFrom(quadConstraintStreamPattern)) {
templateCode = "#{any(ai.timefold.solver.core.api.score.stream.quad.QuadConstraintStream)}\n";
} else {
LOGGER.warn("Cannot refactor to asConstraint() method for deprecated method ({}).", method);
return method;
}
if (!matcherMeta.configurable) {
if (!matcherMeta.matchWeigherIncluded) {
templateCode +=
"." + matcherMeta.methodName + "(#{any(ai.timefold.solver.core.api.score.Score)})\n";
} else {
templateCode +=
"." + matcherMeta.methodName + "(#{any(ai.timefold.solver.core.api.score.Score)}," +
" #{any(" + matcherMeta.functionType + ")})\n";
}
} else {
if (!matcherMeta.matchWeigherIncluded) {
templateCode += "." + matcherMeta.methodName + "()\n";
} else {
templateCode += "." + matcherMeta.methodName + "(" +
"#{any(" + matcherMeta.functionType + ")})\n";
}
}
if (!matcherMeta.constraintPackageIncluded) {
templateCode += ".asConstraint(#{any(String)})";
} else {
templateCode += ".asConstraint(\"#{}\")";
}
var template = JavaTemplate.builder(templateCode)
.javaParser(JAVA_PARSER)
.build();
if (!matcherMeta.constraintPackageIncluded) {
if (!matcherMeta.configurable) {
if (!matcherMeta.matchWeigherIncluded) {
return template.apply(getCursor(),
method.getCoordinates().replace(), select,
arguments.get(1), arguments.get(0));
} else {
return template.apply(getCursor(),
method.getCoordinates().replace(), select,
arguments.get(1), arguments.get(2), arguments.get(0));
}
} else {
if (!matcherMeta.matchWeigherIncluded) {
return template.apply(getCursor(),
method.getCoordinates().replace(), select,
arguments.get(0));
} else {
return template.apply(getCursor(),
method.getCoordinates().replace(), select,
arguments.get(1), arguments.get(0));
}
}
} else {
if (!matcherMeta.configurable) {
if (!matcherMeta.matchWeigherIncluded) {
return template.apply(getCursor(),
method.getCoordinates().replace(), select,
arguments.get(2), mergeExpressions(arguments.get(0), arguments.get(1)));
} else {
return template.apply(getCursor(),
method.getCoordinates().replace(), select,
arguments.get(2), arguments.get(3),
mergeExpressions(arguments.get(0), arguments.get(1)));
}
} else {
if (!matcherMeta.matchWeigherIncluded) {
return template.apply(getCursor(),
method.getCoordinates().replace(), select,
mergeExpressions(arguments.get(0), arguments.get(1)));
} else {
return template.apply(getCursor(),
method.getCoordinates().replace(), select,
arguments.get(2), mergeExpressions(arguments.get(0), arguments.get(1)));
}
}
}
}
});
}
private String mergeExpressions(Expression constraintPackage, Expression constraintName) {
return constraintPackage.toString() + "." + constraintName.toString();
}
private static class MatcherMeta {
public final MethodMatcher methodMatcher;
public final boolean constraintPackageIncluded;
public final boolean configurable;
public final boolean matchWeigherIncluded;
public final String methodName; // penalize, reward or impact
public final String functionType;
public MatcherMeta(String select, String method) {
String signature;
if (select.equals("ConstraintStream")) {
signature = "ai.timefold.solver.core.api.score.stream.ConstraintStream";
} else if (select.equals("UniConstraintStream")) {
signature = "ai.timefold.solver.core.api.score.stream.uni.UniConstraintStream";
} else if (select.equals("BiConstraintStream")) {
signature = "ai.timefold.solver.core.api.score.stream.bi.BiConstraintStream";
} else if (select.equals("TriConstraintStream")) {
signature = "ai.timefold.solver.core.api.score.stream.tri.TriConstraintStream";
} else if (select.equals("QuadConstraintStream")) {
signature = "ai.timefold.solver.core.api.score.stream.quad.QuadConstraintStream";
} else {
throw new IllegalArgumentException("Invalid select (" + select + ").");
}
signature += " " + method.replace(" Score", " ai.timefold.solver.core.api.score.Score")
.replace(" ToIntFunction", " java.util.function.ToIntFunction")
.replace(" ToLongFunction", " java.util.function.ToLongFunction")
.replace(" Function", " java.util.function.Function")
.replace(" ToIntBiFunction", " java.util.function.ToIntBiFunction")
.replace(" ToLongBiFunction", " java.util.function.ToLongBiFunction")
.replace(" BiFunction", " java.util.function.BiFunction")
.replace(" ToIntTriFunction", " ai.timefold.solver.core.api.function.ToIntTriFunction")
.replace(" ToLongTriFunction", " ai.timefold.solver.core.api.function.ToLongTriFunction")
.replace(" TriFunction", " ai.timefold.solver.core.api.function.TriFunction")
.replace(" ToIntQuadFunction", " ai.timefold.solver.core.api.function.ToIntQuadFunction")
.replace(" ToLongQuadFunction", " ai.timefold.solver.core.api.function.ToLongQuadFunction")
.replace(" QuadFunction", " ai.timefold.solver.core.api.function.QuadFunction");
methodMatcher = new MethodMatcher(signature);
constraintPackageIncluded = method.contains("String, String");
configurable = method.contains("Configurable");
matchWeigherIncluded = method.contains("Function");
if (matchWeigherIncluded) {
this.functionType = signature.replaceFirst("^.* ([\\w\\.]+Function)\\)$", "$1");
} else {
this.functionType = null;
}
this.methodName = method.replaceFirst("\\(.*$", "");
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration/v8/ConstraintRefRecipe.java | package ai.timefold.solver.migration.v8;
import java.util.Arrays;
import ai.timefold.solver.migration.AbstractRecipe;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
public final class ConstraintRefRecipe extends AbstractRecipe {
private static final MatcherMeta[] MATCHER_METAS = {
new MatcherMeta("Constraint", "getConstraintId()", "constraintId()"),
new MatcherMeta("Constraint", "getConstraintName()", "constraintName()"),
new MatcherMeta("Constraint", "getConstraintPackage()", "packageName()"),
new MatcherMeta("ConstraintMatch", "getConstraintId()", "constraintId()"),
new MatcherMeta("ConstraintMatch", "getConstraintName()", "constraintName()"),
new MatcherMeta("ConstraintMatch", "getConstraintPackage()", "packageName()"),
new MatcherMeta("ConstraintMatchTotal", "getConstraintId()", "constraintId()"),
new MatcherMeta("ConstraintMatchTotal", "getConstraintName()", "constraintName()"),
new MatcherMeta("ConstraintMatchTotal", "getConstraintPackage()", "packageName()"),
};
@Override
public String getDisplayName() {
return "Replace getConstraint*() with getConstraintRef()";
}
@Override
public String getDescription() {
return "Use `getConstraintRef()` instead of `getConstraintId()` et al.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
TreeVisitor<?, ExecutionContext>[] visitors = Arrays.stream(MATCHER_METAS)
.map(m -> new UsesMethod<>(m.methodMatcher))
.toArray(TreeVisitor[]::new);
return Preconditions.check(
Preconditions.or(visitors),
new JavaIsoVisitor<>() {
@Override
public Expression visitExpression(Expression expression, ExecutionContext executionContext) {
final Expression e = super.visitExpression(expression, executionContext);
MatcherMeta matcherMeta = Arrays.stream(MATCHER_METAS).filter(m -> m.methodMatcher.matches(e))
.findFirst().orElse(null);
if (matcherMeta == null) {
return e;
}
J.MethodInvocation mi = (J.MethodInvocation) e;
Expression select = mi.getSelect();
String clz = "#{any(" + matcherMeta.scoreClassFqn + ")}";
String pattern = clz + ".getConstraintRef()." + matcherMeta.newMethodName;
maybeAddImport("ai.timefold.solver.core.api.score.constraint.ConstraintRef");
return JavaTemplate.builder(pattern)
.javaParser(JAVA_PARSER)
.build()
.apply(getCursor(), e.getCoordinates().replace(), select);
}
});
}
private static final class MatcherMeta {
public final String scoreClassFqn;
public final MethodMatcher methodMatcher;
public final String methodName;
public final String newMethodName;
public MatcherMeta(String select, String method, String newMethod) {
String className = switch (select) {
case "ConstraintMatch", "ConstraintMatchTotal" ->
"ai.timefold.solver.core.api.score.constraint." + select;
case "Constraint" -> "ai.timefold.solver.core.api.score.stream." + select;
default -> throw new IllegalArgumentException("Unexpected value: " + select);
};
this.scoreClassFqn = className;
this.methodMatcher = new MethodMatcher(scoreClassFqn + " " + method);
this.methodName = method;
this.newMethodName = newMethod;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration/v8/NullableRecipe.java | package ai.timefold.solver.migration.v8;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import ai.timefold.solver.migration.AbstractRecipe;
import org.openrewrite.Recipe;
import org.openrewrite.java.ChangeAnnotationAttributeName;
import org.openrewrite.java.ChangeMethodName;
public final class NullableRecipe extends AbstractRecipe {
@Override
public String getDisplayName() {
return "PlanningVariable's `nullable` is newly called `unassignedValues`";
}
@Override
public String getDescription() {
return "Removes references to null vars and replace them with unassigned values.";
}
@Override
public List<Recipe> getRecipeList() {
var packageName = "ai.timefold.solver.core.api.score.stream";
var methodsToRename = List.of(
Map.entry("ConstraintFactory forEachIncludingNullVars(Class)",
"forEachIncludingUnassigned"),
Map.entry("uni.UniConstraintStream ifExistsIncludingNullVars(..)",
"ifExistsIncludingUnassigned"),
Map.entry("uni.UniConstraintStream ifExistsOtherIncludingNullVars(..)",
"ifExistsOtherIncludingUnassigned"),
Map.entry("uni.UniConstraintStream ifNotExistsIncludingNullVars(..)",
"ifNotExistsIncludingUnassigned"),
Map.entry("uni.UniConstraintStream ifNotExistsOtherIncludingNullVars(..)",
"ifNotExistsOtherIncludingUnassigned"),
Map.entry("bi.BiConstraintStream ifExistsIncludingNullVars(..)",
"ifExistsIncludingUnassigned"),
Map.entry("bi.BiConstraintStream ifNotExistsIncludingNullVars(..)",
"ifNotExistsIncludingUnassigned"),
Map.entry("tri.TriConstraintStream ifExistsIncludingNullVars(..)",
"ifExistsIncludingUnassigned"),
Map.entry("tri.TriConstraintStream ifNotExistsIncludingNullVars(..)",
"ifNotExistsIncludingUnassigned"),
Map.entry("quad.QuadConstraintStream ifExistsIncludingNullVars(..)",
"ifExistsIncludingUnassigned"),
Map.entry("quad.QuadConstraintStream ifNotExistsIncludingNullVars(..)",
"ifNotExistsIncludingUnassigned"));
var result = new ArrayList<Recipe>();
methodsToRename.forEach(entry -> {
var pattern = packageName + "." + entry.getKey();
result.add(new ChangeMethodName(pattern, entry.getValue(), null, null));
});
result.add(new ChangeAnnotationAttributeName("ai.timefold.solver.core.api.domain.variable.PlanningVariable", "nullable",
"allowsUnassigned"));
return result;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration/v8/RemoveConstraintPackageRecipe.java | package ai.timefold.solver.migration.v8;
import java.util.List;
import ai.timefold.solver.migration.AbstractRecipe;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
public final class RemoveConstraintPackageRecipe extends AbstractRecipe {
@Override
public String getDisplayName() {
return "Constraint Streams: don't use package name in the asConstraint() method";
}
@Override
public String getDescription() {
return "Remove the use of constraint package from `asConstraint(package, name)`.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(
Preconditions.or(new UsesMethod<>(new MethodMatcher(
"ai.timefold.solver.core.api.score.stream.ConstraintBuilder asConstraint(String, String)"))),
new JavaIsoVisitor<>() {
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
Expression select = method.getSelect();
List<Expression> arguments = method.getArguments();
String templateCode = "#{any(ai.timefold.solver.core.api.score.stream.ConstraintBuilder)}\n" +
".asConstraint(\"#{}\")";
JavaTemplate template = JavaTemplate.builder(templateCode)
.javaParser(JAVA_PARSER)
.build();
return template.apply(getCursor(),
method.getCoordinates().replace(), select,
mergeExpressions(arguments.get(0), arguments.get(1)));
}
});
}
private String mergeExpressions(Expression constraintPackage, Expression constraintName) {
return constraintPackage.toString() + "." + constraintName.toString();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration/v8/ScoreGettersRecipe.java | package ai.timefold.solver.migration.v8;
import java.util.Arrays;
import java.util.List;
import ai.timefold.solver.migration.AbstractRecipe;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
public final class ScoreGettersRecipe extends AbstractRecipe {
private static final MatcherMeta[] MATCHER_METAS = {
new MatcherMeta("IBendableScore", "getHardLevelsSize()"),
new MatcherMeta("IBendableScore", "getSoftLevelsSize()"),
new MatcherMeta("IBendableScore", "getLevelsSize()"),
new MatcherMeta("Score", "getInitScore()"),
new MatcherMeta("BendableScore", "getHardScores()"),
new MatcherMeta("BendableScore", "getHardScore(int)"),
new MatcherMeta("BendableScore", "getSoftScores()"),
new MatcherMeta("BendableScore", "getSoftScore(int)"),
new MatcherMeta("BendableBigDecimalScore", "getHardScores()"),
new MatcherMeta("BendableBigDecimalScore", "getHardScore(int)"),
new MatcherMeta("BendableBigDecimalScore", "getSoftScores()"),
new MatcherMeta("BendableBigDecimalScore", "getSoftScore(int)"),
new MatcherMeta("BendableLongScore", "getHardScores()"),
new MatcherMeta("BendableLongScore", "getHardScore(int)"),
new MatcherMeta("BendableLongScore", "getSoftScores()"),
new MatcherMeta("BendableLongScore", "getSoftScore(int)"),
new MatcherMeta("HardMediumSoftScore", "getHardScore()"),
new MatcherMeta("HardMediumSoftScore", "getMediumScore()"),
new MatcherMeta("HardMediumSoftScore", "getSoftScore()"),
new MatcherMeta("HardMediumSoftBigDecimalScore", "getHardScore()"),
new MatcherMeta("HardMediumSoftBigDecimalScore", "getMediumScore()"),
new MatcherMeta("HardMediumSoftBigDecimalScore", "getSoftScore()"),
new MatcherMeta("HardMediumSoftLongScore", "getHardScore()"),
new MatcherMeta("HardMediumSoftLongScore", "getMediumScore()"),
new MatcherMeta("HardMediumSoftLongScore", "getSoftScore()"),
new MatcherMeta("HardSoftScore", "getHardScore()"),
new MatcherMeta("HardSoftScore", "getSoftScore()"),
new MatcherMeta("HardSoftBigDecimalScore", "getHardScore()"),
new MatcherMeta("HardSoftBigDecimalScore", "getSoftScore()"),
new MatcherMeta("HardSoftLongScore", "getHardScore()"),
new MatcherMeta("HardSoftLongScore", "getSoftScore()"),
new MatcherMeta("SimpleScore", "getScore()"),
new MatcherMeta("SimpleBigDecimalScore", "getScore()"),
new MatcherMeta("SimpleLongScore", "getScore()"),
};
@Override
public String getDisplayName() {
return "Score: use shorter getters";
}
@Override
public String getDescription() {
return "Use `score()` instead of `getScore()` on `Score` implementations.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
TreeVisitor<?, ExecutionContext>[] visitors = Arrays.stream(MATCHER_METAS)
.map(m -> new UsesMethod<>(m.methodMatcher))
.toArray(TreeVisitor[]::new);
return Preconditions.check(
Preconditions.or(visitors),
new JavaIsoVisitor<>() {
@Override
public Expression visitExpression(Expression expression, ExecutionContext executionContext) {
final Expression e = super.visitExpression(expression, executionContext);
MatcherMeta matcherMeta = Arrays.stream(MATCHER_METAS).filter(m -> m.methodMatcher.matches(e))
.findFirst().orElse(null);
if (matcherMeta == null) {
return e;
}
J.MethodInvocation mi = (J.MethodInvocation) e;
Expression select = mi.getSelect();
List<Expression> arguments = mi.getArguments();
String score = "#{any(" + matcherMeta.scoreClassFqn + ")}";
String getterWithoutGet =
matcherMeta.methodName.substring(3, 4).toLowerCase() +
matcherMeta.methodName.substring(4);
String pattern = score + "." + getterWithoutGet;
if (getterWithoutGet.contains("(int)")) {
pattern = pattern.replace("(int)", "(#{any(int)})");
return JavaTemplate.builder(pattern)
.javaParser(JAVA_PARSER)
.build()
.apply(getCursor(), e.getCoordinates().replace(), select, arguments.get(0));
} else {
return JavaTemplate.builder(pattern)
.javaParser(JAVA_PARSER)
.build()
.apply(getCursor(), e.getCoordinates().replace(), select);
}
}
});
}
private static final class MatcherMeta {
public final String scoreClassFqn;
public final MethodMatcher methodMatcher;
public final String methodName;
public MatcherMeta(String select, String method) {
String className;
switch (select) {
case "Score":
case "IBendableScore":
className = "ai.timefold.solver.core.api.score." + select;
break;
default:
className = "ai.timefold.solver.core.api.score.buildin."
+ select.toLowerCase().replace("score", "")
+ "."
+ select;
}
this.scoreClassFqn = className;
this.methodMatcher = new MethodMatcher(scoreClassFqn + " " + method);
this.methodName = method;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration/v8/ScoreManagerMethodsRecipe.java | package ai.timefold.solver.migration.v8;
import java.util.Arrays;
import java.util.List;
import ai.timefold.solver.migration.AbstractRecipe;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
public class ScoreManagerMethodsRecipe extends AbstractRecipe {
private static final MatcherMeta[] MATCHER_METAS = {
new MatcherMeta("getSummary(..)"),
new MatcherMeta("explainScore(..)"),
new MatcherMeta("updateScore(..)")
};
@Override
public String getDisplayName() {
return "ScoreManager: explain(), update()";
}
@Override
public String getDescription() {
return "Use `explain()` and `update()` " +
" instead of `explainScore()`, `updateScore()` and `getSummary()`.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
TreeVisitor<?, ExecutionContext>[] visitors = Arrays.stream(MATCHER_METAS)
.map(m -> new UsesMethod<>(m.methodMatcher))
.toArray(TreeVisitor[]::new);
return Preconditions.check(
Preconditions.or(visitors),
new JavaIsoVisitor<>() {
@Override
public Expression visitExpression(Expression expression, ExecutionContext executionContext) {
final Expression e = super.visitExpression(expression, executionContext);
MatcherMeta matcherMeta = Arrays.stream(MATCHER_METAS).filter(m -> m.methodMatcher.matches(e))
.findFirst().orElse(null);
if (matcherMeta == null) {
return e;
}
J.MethodInvocation mi = (J.MethodInvocation) e;
Expression select = mi.getSelect();
List<Expression> arguments = mi.getArguments();
String pattern = "#{any(" + matcherMeta.classFqn + ")}." +
(matcherMeta.methodName.contains("Summary")
? "explain(#{any()}, SolutionUpdatePolicy.UPDATE_SCORE_ONLY).getSummary()"
: matcherMeta.methodName.replace(")", ", SolutionUpdatePolicy.UPDATE_SCORE_ONLY)")
.replace("..", "#{any()}")
.replace("Score(", "("));
maybeAddImport("ai.timefold.solver.core.api.solver.SolutionUpdatePolicy");
return JavaTemplate.builder(pattern)
.javaParser(JAVA_PARSER)
.imports("ai.timefold.solver.core.api.solver.SolutionUpdatePolicy")
.build()
.apply(getCursor(), e.getCoordinates().replace(), select, arguments.get(0));
}
});
}
private static final class MatcherMeta {
public final String classFqn;
public final MethodMatcher methodMatcher;
public final String methodName;
public MatcherMeta(String method) {
this.classFqn = "ai.timefold.solver.core.api.score.ScoreManager";
this.methodMatcher = new MethodMatcher(classFqn + " " + method);
this.methodName = method;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration/v8/SingleConstraintAssertionMethodsRecipe.java | package ai.timefold.solver.migration.v8;
import java.util.ArrayList;
import java.util.List;
import ai.timefold.solver.migration.AbstractRecipe;
import org.openrewrite.Recipe;
import org.openrewrite.java.ReorderMethodArguments;
public final class SingleConstraintAssertionMethodsRecipe extends AbstractRecipe {
@Override
public String getDisplayName() {
return "Use non-deprecated SingleConstraintAssertion methods";
}
@Override
public String getDescription() {
return "Use `penalizesBy/rewardsWith(String, int)` instead of `penalizesBy/rewardsWith(int, String)` on `SingleConstraintAssertion` tests.";
}
@Override
public List<Recipe> getRecipeList() {
var methodsToReorder = List.of(
new String[] { "ai.timefold.solver.test.api.score.stream.SingleConstraintAssertion *(int, String)",
"message,matchWeightTotal",
"matchWeightTotal,message" },
new String[] { "ai.timefold.solver.test.api.score.stream.SingleConstraintAssertion *(long, String)",
"message,matchWeightTotal",
"matchWeightTotal,message" },
new String[] {
"ai.timefold.solver.test.api.score.stream.SingleConstraintAssertion *(java.math.BigDecimal, String)",
"message,matchWeightTotal",
"matchWeightTotal,message" });
var result = new ArrayList<Recipe>();
methodsToReorder.forEach(method -> result
.add(new ReorderMethodArguments(method[0], method[1].split(","), method[2].split(","), null, null)));
return result;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration/v8/SolutionManagerRecommendAssignmentRecipe.java | package ai.timefold.solver.migration.v8;
import java.util.List;
import ai.timefold.solver.migration.AbstractRecipe;
import org.openrewrite.Recipe;
import org.openrewrite.java.ChangeMethodName;
import org.openrewrite.java.ChangeType;
public final class SolutionManagerRecommendAssignmentRecipe extends AbstractRecipe {
@Override
public String getDisplayName() {
return "Recommended Fit API becomes Assignment Recommendation API";
}
@Override
public String getDescription() {
return "Use recommendAssignment() instead of recommendFit().";
}
@Override
public List<Recipe> getRecipeList() {
var changeMethodName = new ChangeMethodName(
"ai.timefold.solver.core.api.solver.SolutionManager recommendFit(" +
"java.lang.Object, " +
"java.lang.Object, " +
"java.util.function.Function)",
"recommendAssignment", true, false);
var changeMethodName2 = new ChangeMethodName(
"ai.timefold.solver.core.api.solver.SolutionManager recommendFit(" +
"java.lang.Object, java.lang.Object, " +
"java.util.function.Function, " +
"ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy)",
"recommendAssignment", true, false);
var changeType = new ChangeType("ai.timefold.solver.core.api.solver.RecommendedFit",
"ai.timefold.solver.core.api.solver.RecommendedAssignment", false);
return List.of(changeMethodName, changeMethodName2, changeType);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration | java-sources/ai/timefold/solver/timefold-solver-migration/1.26.1/ai/timefold/solver/migration/v8/SolverManagerBuilderRecipe.java | package ai.timefold.solver.migration.v8;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import ai.timefold.solver.migration.AbstractRecipe;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
public final class SolverManagerBuilderRecipe extends AbstractRecipe {
private static final MatcherMeta[] MATCHER_METAS = {
new MatcherMeta(
"solve(*..*,java.util.function.Function,java.util.function.Consumer,java.util.function.BiConsumer)",
".solveBuilder().withProblemId(#{any()}).withProblemFinder(#{any()}).withFinalBestSolutionConsumer(#{any(java.util.function.Consumer)}).withExceptionHandler(#{any(java.util.function.BiConsumer)}).run()"),
new MatcherMeta("solve(*..*,*..*,java.util.function.Consumer,java.util.function.BiConsumer)",
".solveBuilder().withProblemId(#{any()}).withProblem(#{any()}).withFinalBestSolutionConsumer(#{any(java.util.function.Consumer)}).withExceptionHandler(#{any(java.util.function.BiConsumer)}).run()"),
new MatcherMeta("solve(*..*,java.util.function.Function,java.util.function.Consumer)",
".solveBuilder().withProblemId(#{any()}).withProblemFinder(#{any()}).withFinalBestSolutionConsumer(#{any(java.util.function.Consumer)}).run()"),
new MatcherMeta("solveAndListen(*..*,java.util.function.Function,java.util.function.Consumer)",
".solveBuilder().withProblemId(#{any()}).withProblemFinder(#{any()}).withBestSolutionConsumer(#{any(java.util.function.Consumer)}).run()"),
new MatcherMeta(
"solveAndListen(*..*,java.util.function.Function,java.util.function.Consumer,java.util.function.BiConsumer)",
".solveBuilder().withProblemId(#{any()}).withProblemFinder(#{any()}).withBestSolutionConsumer(#{any(java.util.function.Consumer)}).withExceptionHandler(#{any(java.util.function.BiConsumer)}).run()"),
new MatcherMeta(
"solveAndListen(*..*,java.util.function.Function,java.util.function.Consumer,java.util.function.Consumer,java.util.function.BiConsumer)",
".solveBuilder().withProblemId(#{any()}).withProblemFinder(#{any()}).withBestSolutionConsumer(#{any(java.util.function.Consumer)}).withFinalBestSolutionConsumer(#{any(java.util.function.Consumer)}).withExceptionHandler(#{any(java.util.function.BiConsumer)}).run()"),
};
@Override
public String getDisplayName() {
return "SolverManager: use builder API";
}
@Override
public String getDescription() {
return "Use `solveBuilder()` instead of deprecated solve methods on `SolveManager`.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
TreeVisitor<?, ExecutionContext>[] visitors = Arrays.stream(MATCHER_METAS)
.map(m -> new UsesMethod<>(m.methodMatcher))
.toArray(TreeVisitor[]::new);
return Preconditions.check(
Preconditions.or(visitors),
new JavaIsoVisitor<>() {
@Override
public Expression visitExpression(Expression expression, ExecutionContext executionContext) {
final Expression e = super.visitExpression(expression, executionContext);
MatcherMeta matcherMeta = Arrays.stream(MATCHER_METAS).filter(m -> m.methodMatcher.matches(e))
.findFirst().orElse(null);
if (matcherMeta == null) {
return e;
}
J.MethodInvocation mi = (J.MethodInvocation) e;
Expression select = mi.getSelect();
List<Expression> arguments = mi.getArguments();
String pattern = "#{any(" + matcherMeta.classFqn + ")}" + matcherMeta.pattern;
return JavaTemplate.builder(pattern)
.javaParser(JAVA_PARSER)
.build()
.apply(getCursor(), e.getCoordinates().replace(),
Stream.concat(Stream.of(select), arguments.stream()).toArray());
}
});
}
private static final class MatcherMeta {
private final String classFqn;
public final MethodMatcher methodMatcher;
public final String methodName;
private final String pattern;
public MatcherMeta(String method, String pattern) {
this.classFqn = "ai.timefold.solver.core.api.solver.SolverManager";
this.methodMatcher = new MethodMatcher(classFqn + " " + method);
this.methodName = method;
this.pattern = pattern;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-persistence-common/1.26.1/ai/timefold/solver/persistence/common/api/domain | java-sources/ai/timefold/solver/timefold-solver-persistence-common/1.26.1/ai/timefold/solver/persistence/common/api/domain/solution/SolutionFileIO.java | package ai.timefold.solver.persistence.common.api.domain.solution;
import java.io.File;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
/**
* Reads or writes a {@link PlanningSolution} from or to a {@link File}.
* <p>
* An implementation must be thread-safe.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public interface SolutionFileIO<Solution_> {
/**
* Every {@link PlanningSolution} type potentially has its own file extension.
* If no specific file extension is defined by the use case, the following are recommended:
* <ul>
* <li>If this {@link SolutionFileIO} implementation serializes to XML, use file extension "xml".</li>
* <li>If this {@link SolutionFileIO} implementation serializes to text, use file extension "txt".</li>
* <li>If this {@link SolutionFileIO} implementation serializes to binary, use file extension "dat".</li>
* </ul>
* <p>
* It's good practice that both the input and the output file have the same file extension,
* because a good output file is able to function as an input file.
* Therefore {@link #getOutputFileExtension} defaults to returning the same as this method.
* <p>
* The file extension does not include the dot that separates it from the base name.
* <p>
* This method is thread-safe.
*
* @return never null, for example "xml"
*/
String getInputFileExtension();
/**
* It's highly recommended that this method returns the same value as {@link #getInputFileExtension()},
* which it does by default unless it's overridden,
* because a good output file is able to function as an input file.
*
* @return never null, for example "xml"
* @see #getInputFileExtension()
*/
default String getOutputFileExtension() {
return getInputFileExtension();
}
/**
* This method is thread-safe.
*
* @param inputSolutionFile never null
* @return never null
*/
Solution_ read(File inputSolutionFile);
/**
* This method is thread-safe.
*
* @param solution never null
* @param outputSolutionFile never null, parent directory already exists
*/
void write(Solution_ solution, File outputSolutionFile);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/DaemonThreadFactory.java | package ai.timefold.solver.python;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* There a Catch-22 that occurs on shutdown:
* <p>
* - In order for Python to free its variables, it must be terminated.
* - In order for Python to be terminated, the JVM must be terminated.
* - In order for the JVM to be terminated, all its non-daemon threads must be terminated.
* - Executors keep all its threads alive until it is freed/have no more references.
* - In order for the Executor to be freed/have no more references, it cannot have a reference in Python.
* - To not have a reference in Python means Python must free its variables, creating the Catch-22
* <p>
* Thus, if non-daemon threads are used, and a {@link ai.timefold.solver.core.api.solver.SolverManager}
* solves at least one problem (creating a keep-alive thread in its {@link java.util.concurrent.ThreadPoolExecutor}),
* Python cannot shut down gracefully and will become unresponsive when interrupted.
* <p>
* This class uses {@link Executors#defaultThreadFactory()} to create a new thread, but sets the created
* thread to daemon mode so Python can shut down gracefully.
*/
public class DaemonThreadFactory implements ThreadFactory {
private static final ThreadFactory THREAD_FACTORY = Executors.defaultThreadFactory();
@Override
public Thread newThread(Runnable runnable) {
Thread out = THREAD_FACTORY.newThread(runnable);
out.setDaemon(true);
return out;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/PythonValueRangeFactory.java | package ai.timefold.solver.python;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.Random;
import java.util.function.Function;
import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean;
import ai.timefold.jpyinterpreter.types.numeric.PythonFloat;
import ai.timefold.jpyinterpreter.types.numeric.PythonInteger;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeFactory;
import org.jspecify.annotations.NonNull;
@SuppressWarnings("unused")
public class PythonValueRangeFactory {
private PythonValueRangeFactory() {
}
private record IteratorMapper<From_, To_>(Iterator<From_> sourceIterator, Function<From_, To_> valueConvertor)
implements
Iterator<To_> {
@Override
public boolean hasNext() {
return sourceIterator.hasNext();
}
@Override
public To_ next() {
return valueConvertor.apply(sourceIterator.next());
}
}
private record ValueRangeMapper<From_, To_>(CountableValueRange<From_> sourceValueRange,
Function<From_, To_> valueConvertor, Function<To_, From_> inverseValueConvertor)
implements
CountableValueRange<To_> {
@Override
public long getSize() {
return sourceValueRange.getSize();
}
@Override
public To_ get(long index) {
return valueConvertor.apply(sourceValueRange.get(index));
}
@Override
public @NonNull Iterator<To_> createOriginalIterator() {
return new IteratorMapper<>(sourceValueRange.createOriginalIterator(), valueConvertor);
}
@Override
public boolean isEmpty() {
return sourceValueRange.isEmpty();
}
@Override
public boolean contains(To_ value) {
return sourceValueRange.contains(inverseValueConvertor.apply(value));
}
@Override
public @NonNull Iterator<To_> createRandomIterator(@NonNull Random random) {
return new IteratorMapper<>(sourceValueRange.createRandomIterator(random), valueConvertor);
}
}
public static CountableValueRange<PythonInteger> createIntValueRange(BigInteger from, BigInteger to) {
return new ValueRangeMapper<>(ValueRangeFactory.createBigIntegerValueRange(from, to),
PythonInteger::valueOf,
pythonInteger -> pythonInteger.value);
}
public static CountableValueRange<PythonInteger> createIntValueRange(BigInteger from, BigInteger to, BigInteger step) {
return new ValueRangeMapper<>(ValueRangeFactory.createBigIntegerValueRange(from, to, step),
PythonInteger::valueOf,
pythonInteger -> pythonInteger.value);
}
public static CountableValueRange<PythonFloat> createFloatValueRange(BigDecimal from, BigDecimal to) {
return new ValueRangeMapper<>(ValueRangeFactory.createBigDecimalValueRange(from, to),
decimal -> PythonFloat.valueOf(decimal.doubleValue()),
pythonFloat -> BigDecimal.valueOf(pythonFloat.value));
}
public static CountableValueRange<PythonFloat> createFloatValueRange(BigDecimal from, BigDecimal to, BigDecimal step) {
return new ValueRangeMapper<>(ValueRangeFactory.createBigDecimalValueRange(from, to, step),
decimal -> PythonFloat.valueOf(decimal.doubleValue()),
pythonFloat -> BigDecimal.valueOf(pythonFloat.value));
}
public static CountableValueRange<PythonBoolean> createBooleanValueRange() {
return new ValueRangeMapper<>(ValueRangeFactory.createBooleanValueRange(),
PythonBoolean::valueOf,
PythonBoolean::getBooleanValue);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/PythonWrapperGenerator.java | package ai.timefold.solver.python;
import static ai.timefold.jpyinterpreter.PythonBytecodeToJavaBytecodeTranslator.writeClassOutput;
import static ai.timefold.jpyinterpreter.types.BuiltinTypes.asmClassLoader;
import static ai.timefold.jpyinterpreter.types.BuiltinTypes.classNameToBytecode;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.api.score.calculator.ConstraintMatchAwareIncrementalScoreCalculator;
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 io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.ClassOutput;
import io.quarkus.gizmo.FieldDescriptor;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
public class PythonWrapperGenerator {
@SuppressWarnings("unused")
public static ClassLoader getClassLoaderForAliasMap(Map<String, Class<?>> aliasMap) {
return new ClassLoader() {
// getName() is an abstract method in Java 11 but not in Java 8
public String getName() {
return "Timefold Alias Map ClassLoader";
}
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
if (aliasMap.containsKey(name)) {
// Gizmo generated class
return aliasMap.get(name);
} else {
// Not a Gizmo generated class; load from parent class loader
return asmClassLoader.loadClass(name);
}
}
};
}
private static ClassOutput getClassOutput(AtomicReference<byte[]> bytesReference) {
return (path, byteCode) -> {
bytesReference.set(byteCode);
};
}
/**
* Creates a class that looks like this:
*
* class JavaWrapper implements NaryFunction<A0,A1,A2,...,AN> {
* public static NaryFunction<A0,A1,A2,...,AN> delegate;
*
* #64;Override
* public AN apply(A0 arg0, A1 arg1, ..., A(N-1) finalArg) {
* return delegate.apply(arg0,arg1,...,finalArg);
* }
* }
*
* @param className The simple name of the generated class
* @param baseInterface the base interface
* @param delegate The Python function to delegate to
* @return never null
*/
@SuppressWarnings({ "unused", "unchecked" })
public static <A> Class<? extends A> defineWrapperFunction(String className, Class<A> baseInterface,
Object delegate) {
Method[] interfaceMethods = baseInterface.getMethods();
if (interfaceMethods.length != 1) {
throw new IllegalArgumentException("Can only call this function for functional interfaces (only 1 method)");
}
if (classNameToBytecode.containsKey(className)) {
try {
return (Class<? extends A>) asmClassLoader.loadClass(className);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(
"Impossible State: the class (" + className + ") should exists since it was created");
}
}
AtomicReference<byte[]> classBytecodeHolder = new AtomicReference<>();
ClassOutput classOutput = getClassOutput(classBytecodeHolder);
// holds the delegate (static; same one is reused; should be stateless)
FieldDescriptor delegateField;
try (ClassCreator classCreator = ClassCreator.builder()
.className(className)
.interfaces(baseInterface)
.classOutput(classOutput)
.build()) {
delegateField = classCreator.getFieldCreator("delegate", baseInterface)
.setModifiers(Modifier.STATIC | Modifier.PUBLIC)
.getFieldDescriptor();
MethodCreator methodCreator = classCreator.getMethodCreator(MethodDescriptor.ofMethod(interfaceMethods[0]));
ResultHandle pythonProxy = methodCreator.readStaticField(delegateField);
ResultHandle[] args = new ResultHandle[interfaceMethods[0].getParameterCount()];
for (int i = 0; i < args.length; i++) {
args[i] = methodCreator.getMethodParam(i);
}
ResultHandle constraints = methodCreator.invokeInterfaceMethod(
MethodDescriptor.ofMethod(interfaceMethods[0]),
pythonProxy, args);
methodCreator.returnValue(constraints);
} catch (Exception e) {
throw new IllegalStateException(e);
}
writeClassOutput(classNameToBytecode, className, classBytecodeHolder.get());
try {
// Now that the class created, we need to set it static field to the delegate function
Class<? extends A> out = (Class<? extends A>) asmClassLoader.loadClass(className);
out.getField(delegateField.getName()).set(null, delegate);
return out;
} catch (Exception e) {
throw new IllegalStateException(
"Impossible State: the class (" + className + ") should exists since it was just created");
}
}
/**
* Creates a class that looks like this:
*
* class JavaWrapper implements SomeInterface {
* public static Supplier<SomeInterface> supplier;
*
* private SomeInterface delegate;
*
* public JavaWrapper() {
* delegate = supplier.get(); classNameToBytecode.put(className, classBytecodeHolder.get());
* }
*
* #64;Override
* public Result interfaceMethod1(A0 arg0, A1 arg1, ..., A(N-1) finalArg) {
* return delegate.interfaceMethod1(arg0,arg1,...,finalArg);
* }
*
* #64;Override
* public Result interfaceMethod2(A0 arg0, A1 arg1, ..., A(N-1) finalArg) {
* return delegate.interfaceMethod2(arg0,arg1,...,finalArg);
* }
* }
*
* @param className The simple name of the generated class
* @param baseInterface the base interface
* @param delegateSupplier The Python class to delegate to
* @return never null
*/
@SuppressWarnings({ "unused", "unchecked" })
public static <A> Class<? extends A> defineWrapperClass(String className, Class<? extends A> baseInterface,
Supplier<? extends A> delegateSupplier) {
Method[] interfaceMethods = baseInterface.getMethods();
if (classNameToBytecode.containsKey(className)) {
try {
return (Class<? extends A>) asmClassLoader.loadClass(className);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(
"Impossible State: the class (" + className + ") should exists since it was created");
}
}
AtomicReference<byte[]> classBytecodeHolder = new AtomicReference<>();
ClassOutput classOutput = getClassOutput(classBytecodeHolder);
// holds the supplier of the delegate (static)
FieldDescriptor supplierField;
// holds the delegate (instance; new one created for each instance)
FieldDescriptor delegateField;
try (ClassCreator classCreator = ClassCreator.builder()
.className(className)
.interfaces(baseInterface)
.classOutput(classOutput)
.build()) {
supplierField = classCreator.getFieldCreator("delegateSupplier", Supplier.class)
.setModifiers(Modifier.STATIC | Modifier.PUBLIC)
.getFieldDescriptor();
delegateField = classCreator.getFieldCreator("delegate", baseInterface)
.setModifiers(Modifier.PUBLIC | Modifier.FINAL)
.getFieldDescriptor();
MethodCreator constructorCreator =
classCreator.getMethodCreator(MethodDescriptor.ofConstructor(classCreator.getClassName()));
constructorCreator.invokeSpecialMethod(MethodDescriptor.ofConstructor(Object.class), constructorCreator.getThis());
constructorCreator.writeInstanceField(delegateField, constructorCreator.getThis(),
constructorCreator.invokeInterfaceMethod(MethodDescriptor.ofMethod(Supplier.class, "get", Object.class),
constructorCreator.readStaticField(supplierField)));
constructorCreator.returnValue(constructorCreator.getThis());
for (Method method : interfaceMethods) {
MethodCreator methodCreator = classCreator.getMethodCreator(MethodDescriptor.ofMethod(method));
ResultHandle pythonProxy = methodCreator.readInstanceField(delegateField, methodCreator.getThis());
ResultHandle[] args = new ResultHandle[method.getParameterCount()];
for (int i = 0; i < args.length; i++) {
args[i] = methodCreator.getMethodParam(i);
}
ResultHandle result = methodCreator.invokeInterfaceMethod(
MethodDescriptor.ofMethod(method),
pythonProxy, args);
methodCreator.returnValue(result);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
writeClassOutput(classNameToBytecode, className, classBytecodeHolder.get());
try {
// Now that the class created, we need to set it static field to the supplier of the delegate
Class<? extends A> out = (Class<? extends A>) asmClassLoader.loadClass(className);
out.getField(supplierField.getName()).set(null, delegateSupplier);
return out;
} catch (Exception e) {
throw new IllegalStateException(
"Impossible State: the class (" + className + ") should exists since it was just created");
}
}
/**
* Creates a class that looks like this:
*
* class PythonConstraintProvider implements ConstraintProvider {
* public static Function<ConstraintFactory, Constraint[]> defineConstraintsImpl;
*
* @Override
* public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
* return defineConstraintsImpl.apply(constraintFactory);
* }
* }
*
* @param className The simple name of the generated class
* @param defineConstraintsImpl The Python function that return the list of constraints
* @return never null
*/
@SuppressWarnings("unused")
public static Class<?> defineConstraintProviderClass(String className,
ConstraintProvider defineConstraintsImpl) {
return defineWrapperFunction(className, ConstraintProvider.class, defineConstraintsImpl);
}
/**
* Creates a class that looks like this:
*
* class PythonEasyScoreCalculator implements EasyScoreCalculator {
* public static EasyScoreCalculator easyScoreCalculatorImpl;
*
* @Override
* public Score calculateScore(Solution solution) {
* return easyScoreCalculatorImpl.calculateScore(solution);
* }
* }
*
* @param className The simple name of the generated class
* @param easyScoreCalculatorImpl The Python function that return the score for the solution
* @return never null
*/
@SuppressWarnings("unused")
public static Class<?> defineEasyScoreCalculatorClass(String className,
EasyScoreCalculator easyScoreCalculatorImpl) {
return defineWrapperFunction(className, EasyScoreCalculator.class, easyScoreCalculatorImpl);
}
/**
* Creates a class that looks like this:
*
* class PythonIncrementalScoreCalculator implements IncrementalScoreCalculator {
* public static Supplier<IncrementalScoreCalculator> supplier;
* public final IncrementalScoreCalculator delegate;
*
* public PythonIncrementalScoreCalculator() {
* delegate = supplier.get();
* }
*
* @Override
* public Score calculateScore(Solution solution) {
* return delegate.calculateScore(solution);
* }
*
* ...
* }
*
* @param className The simple name of the generated class
* @param incrementalScoreCalculatorSupplier A supplier that returns a new instance of the incremental score calculator on
* each call
* @return never null
*/
@SuppressWarnings("unused")
public static Class<?> defineIncrementalScoreCalculatorClass(String className,
Supplier<? extends IncrementalScoreCalculator> incrementalScoreCalculatorSupplier,
boolean constraintMatchAware) {
if (constraintMatchAware) {
return defineWrapperClass(className, ConstraintMatchAwareIncrementalScoreCalculator.class,
(Supplier<ConstraintMatchAwareIncrementalScoreCalculator>) incrementalScoreCalculatorSupplier);
}
return defineWrapperClass(className, IncrementalScoreCalculator.class, incrementalScoreCalculatorSupplier);
}
/**
* Creates a class that looks like this:
*
* class PythonVariableListener implements VariableListener {
* public static Supplier<VariableListener> supplier;
* public final VariableListener delegate;
*
* public PythonVariableListener() {
* delegate = supplier.get();
* }
*
* public void afterVariableChange(scoreDirector, entity) {
* delegate.afterVariableChange(scoreDirector, entity);
* }
* ...
* }
*
* @param className The simple name of the generated class
* @param variableListenerSupplier A supplier that returns a new instance of the variable listener on
* each call
* @return never null
*/
@SuppressWarnings("unused")
public static Class<?> defineVariableListenerClass(String className,
Supplier<? extends VariableListener> variableListenerSupplier) {
return defineWrapperClass(className, VariableListener.class, variableListenerSupplier);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/domain/ConstraintWeightOverridesTypeMapping.java | package ai.timefold.solver.python.domain;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import ai.timefold.jpyinterpreter.PythonLikeObject;
import ai.timefold.jpyinterpreter.types.PythonJavaTypeMapping;
import ai.timefold.jpyinterpreter.types.PythonLikeType;
import ai.timefold.jpyinterpreter.types.wrappers.JavaObjectWrapper;
import ai.timefold.solver.core.api.domain.solution.ConstraintWeightOverrides;
@SuppressWarnings("rawtypes")
public class ConstraintWeightOverridesTypeMapping
implements PythonJavaTypeMapping<PythonLikeObject, ConstraintWeightOverrides> {
private final PythonLikeType type;
private final Constructor<?> constructor;
private final Field delegateField;
public ConstraintWeightOverridesTypeMapping(PythonLikeType type)
throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException {
this.type = type;
Class<?> clazz = type.getJavaClass();
constructor = clazz.getConstructor();
delegateField = clazz.getField("_delegate");
}
@Override
public PythonLikeType getPythonType() {
return type;
}
@Override
@SuppressWarnings("rawtypes")
public Class<? extends ConstraintWeightOverrides> getJavaType() {
return ConstraintWeightOverrides.class;
}
@Override
@SuppressWarnings("rawtypes")
public PythonLikeObject toPythonObject(ConstraintWeightOverrides javaObject) {
try {
PythonLikeObject instance = (PythonLikeObject) constructor.newInstance();
delegateField.set(instance, new JavaObjectWrapper(javaObject));
return instance;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
@Override
public ConstraintWeightOverrides<?> toJavaObject(PythonLikeObject pythonObject) {
try {
JavaObjectWrapper out = (JavaObjectWrapper) delegateField.get(pythonObject);
return (ConstraintWeightOverrides<?>) out.getWrappedObject();
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/logging/PythonDelegateAppender.java | package ai.timefold.solver.python.logging;
import java.util.function.Consumer;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
public class PythonDelegateAppender extends AppenderBase<ILoggingEvent> {
private static Consumer<PythonLoggingEvent> logEventConsumer;
public static void setLogEventConsumer(Consumer<PythonLoggingEvent> logEventConsumer) {
PythonDelegateAppender.logEventConsumer = logEventConsumer;
}
@Override
protected void append(ILoggingEvent eventObject) {
logEventConsumer.accept(
new PythonLoggingEvent(
PythonLogLevel.fromJavaLevel(eventObject.getLevel()),
eventObject.getFormattedMessage()));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/logging/PythonLogLevel.java | package ai.timefold.solver.python.logging;
import ch.qos.logback.classic.Level;
public enum PythonLogLevel {
CRITICAL(50, Level.ERROR),
ERROR(40, Level.ERROR),
WARNING(30, Level.WARN),
INFO(20, Level.INFO),
DEBUG(10, Level.DEBUG),
TRACE(5, Level.TRACE),
NOTSET(0, Level.INFO);
final int pythonLevelNumber;
final Level javaLogLevel;
PythonLogLevel(int pythonLevelNumber, Level javaLogLevel) {
this.pythonLevelNumber = pythonLevelNumber;
this.javaLogLevel = javaLogLevel;
}
public int getPythonLevelNumber() {
return pythonLevelNumber;
}
public Level getJavaLogLevel() {
return javaLogLevel;
}
public static PythonLogLevel fromJavaLevel(Level level) {
// Check INFO and ERROR first, since they have multiple corresponding
// Python levels
if (level.equals(Level.INFO)) {
return INFO;
} else if (level.equals(Level.ERROR)) {
return ERROR;
} else {
int levelNumber = level.toInt();
for (PythonLogLevel pythonLogLevel : PythonLogLevel.values()) {
if (pythonLogLevel.getJavaLogLevel().toInt() == levelNumber) {
return pythonLogLevel;
}
}
throw new IllegalStateException("Unmatched log level (" + level + ") with level number (" + level.toInt() + ").");
}
}
public static PythonLogLevel fromPythonLevelNumber(int levelNumber) {
PythonLogLevel bestMatch = PythonLogLevel.CRITICAL;
int bestMatchLevelNumber = 50;
for (PythonLogLevel pythonLogLevel : PythonLogLevel.values()) {
if (pythonLogLevel.pythonLevelNumber >= levelNumber && pythonLogLevel.pythonLevelNumber < bestMatchLevelNumber) {
bestMatch = pythonLogLevel;
}
}
return bestMatch;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/logging/PythonLoggingEvent.java | package ai.timefold.solver.python.logging;
public record PythonLoggingEvent(PythonLogLevel level, String message) {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/logging/PythonLoggingToLogbackAdapter.java | package ai.timefold.solver.python.logging;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
public class PythonLoggingToLogbackAdapter {
private static final Logger LOGGER = ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger("ai.timefold");
public static void setLevel(int logLevel) {
PythonLogLevel pythonLogLevel = PythonLogLevel.fromPythonLevelNumber(logLevel);
LOGGER.setLevel(pythonLogLevel.getJavaLogLevel());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/score/BendableDecimalScorePythonJavaTypeMapping.java | package ai.timefold.solver.python.score;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import ai.timefold.jpyinterpreter.PythonLikeObject;
import ai.timefold.jpyinterpreter.types.PythonJavaTypeMapping;
import ai.timefold.jpyinterpreter.types.PythonLikeType;
import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple;
import ai.timefold.jpyinterpreter.types.numeric.PythonDecimal;
import ai.timefold.solver.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore;
public final class BendableDecimalScorePythonJavaTypeMapping
implements PythonJavaTypeMapping<PythonLikeObject, BendableBigDecimalScore> {
private final PythonLikeType type;
private final Constructor<?> constructor;
private final Field hardScoresField;
private final Field softScoresField;
public BendableDecimalScorePythonJavaTypeMapping(PythonLikeType type)
throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
this.type = type;
var clazz = type.getJavaClass();
constructor = clazz.getConstructor();
hardScoresField = clazz.getField("hard_scores");
softScoresField = clazz.getField("soft_scores");
}
@Override
public PythonLikeType getPythonType() {
return type;
}
@Override
public Class<? extends BendableBigDecimalScore> getJavaType() {
return BendableBigDecimalScore.class;
}
private static PythonLikeTuple<PythonDecimal> toPythonList(BigDecimal[] scores) {
var out = new PythonLikeTuple<PythonDecimal>();
for (var score : scores) {
out.add(new PythonDecimal(score));
}
return out;
}
@Override
public PythonLikeObject toPythonObject(BendableBigDecimalScore javaObject) {
try {
var instance = constructor.newInstance();
hardScoresField.set(instance, toPythonList(javaObject.hardScores()));
softScoresField.set(instance, toPythonList(javaObject.softScores()));
return (PythonLikeObject) instance;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
@Override
public BendableBigDecimalScore toJavaObject(PythonLikeObject pythonObject) {
try {
var hardScoreTuple = (PythonLikeTuple) hardScoresField.get(pythonObject);
var softScoreTuple = (PythonLikeTuple) softScoresField.get(pythonObject);
var hardScores = new BigDecimal[hardScoreTuple.size()];
var softScores = new BigDecimal[softScoreTuple.size()];
for (var i = 0; i < hardScores.length; i++) {
hardScores[i] = ((PythonDecimal) hardScoreTuple.get(i)).value;
}
for (var i = 0; i < softScores.length; i++) {
softScores[i] = ((PythonDecimal) softScoreTuple.get(i)).value;
}
return BendableBigDecimalScore.of(hardScores, softScores);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/score/BendableScorePythonJavaTypeMapping.java | package ai.timefold.solver.python.score;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import ai.timefold.jpyinterpreter.PythonLikeObject;
import ai.timefold.jpyinterpreter.types.PythonJavaTypeMapping;
import ai.timefold.jpyinterpreter.types.PythonLikeType;
import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple;
import ai.timefold.jpyinterpreter.types.numeric.PythonInteger;
import ai.timefold.solver.core.api.score.buildin.bendablelong.BendableLongScore;
public final class BendableScorePythonJavaTypeMapping implements PythonJavaTypeMapping<PythonLikeObject, BendableLongScore> {
private final PythonLikeType type;
private final Constructor<?> constructor;
private final Field hardScoresField;
private final Field softScoresField;
public BendableScorePythonJavaTypeMapping(PythonLikeType type)
throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
this.type = type;
var clazz = type.getJavaClass();
constructor = clazz.getConstructor();
hardScoresField = clazz.getField("hard_scores");
softScoresField = clazz.getField("soft_scores");
}
@Override
public PythonLikeType getPythonType() {
return type;
}
@Override
public Class<? extends BendableLongScore> getJavaType() {
return BendableLongScore.class;
}
private static PythonLikeTuple<PythonInteger> toPythonList(long[] scores) {
var out = new PythonLikeTuple<PythonInteger>();
for (var score : scores) {
out.add(PythonInteger.valueOf(score));
}
return out;
}
@Override
public PythonLikeObject toPythonObject(BendableLongScore javaObject) {
try {
var instance = constructor.newInstance();
hardScoresField.set(instance, toPythonList(javaObject.hardScores()));
softScoresField.set(instance, toPythonList(javaObject.softScores()));
return (PythonLikeObject) instance;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
@Override
public BendableLongScore toJavaObject(PythonLikeObject pythonObject) {
try {
var hardScoreTuple = (PythonLikeTuple) hardScoresField.get(pythonObject);
var softScoreTuple = (PythonLikeTuple) softScoresField.get(pythonObject);
var hardScores = new long[hardScoreTuple.size()];
var softScores = new long[softScoreTuple.size()];
for (var i = 0; i < hardScores.length; i++) {
hardScores[i] = ((PythonInteger) hardScoreTuple.get(i)).value.longValue();
}
for (var i = 0; i < softScores.length; i++) {
softScores[i] = ((PythonInteger) softScoreTuple.get(i)).value.longValue();
}
return BendableLongScore.of(hardScores, softScores);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/score/HardMediumSoftDecimalScorePythonJavaTypeMapping.java | package ai.timefold.solver.python.score;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import ai.timefold.jpyinterpreter.PythonLikeObject;
import ai.timefold.jpyinterpreter.types.PythonJavaTypeMapping;
import ai.timefold.jpyinterpreter.types.PythonLikeType;
import ai.timefold.jpyinterpreter.types.numeric.PythonDecimal;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScore;
public final class HardMediumSoftDecimalScorePythonJavaTypeMapping
implements PythonJavaTypeMapping<PythonLikeObject, HardMediumSoftBigDecimalScore> {
private final PythonLikeType type;
private final Constructor<?> constructor;
private final Field hardScoreField;
private final Field mediumScoreField;
private final Field softScoreField;
public HardMediumSoftDecimalScorePythonJavaTypeMapping(PythonLikeType type)
throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
this.type = type;
var clazz = type.getJavaClass();
constructor = clazz.getConstructor();
hardScoreField = clazz.getField("hard_score");
mediumScoreField = clazz.getField("medium_score");
softScoreField = clazz.getField("soft_score");
}
@Override
public PythonLikeType getPythonType() {
return type;
}
@Override
public Class<? extends HardMediumSoftBigDecimalScore> getJavaType() {
return HardMediumSoftBigDecimalScore.class;
}
@Override
public PythonLikeObject toPythonObject(HardMediumSoftBigDecimalScore javaObject) {
try {
var instance = constructor.newInstance();
hardScoreField.set(instance, new PythonDecimal(javaObject.hardScore()));
mediumScoreField.set(instance, new PythonDecimal(javaObject.mediumScore()));
softScoreField.set(instance, new PythonDecimal(javaObject.softScore()));
return (PythonLikeObject) instance;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
@Override
public HardMediumSoftBigDecimalScore toJavaObject(PythonLikeObject pythonObject) {
try {
var hardScore = ((PythonDecimal) hardScoreField.get(pythonObject)).value;
var mediumScore = ((PythonDecimal) mediumScoreField.get(pythonObject)).value;
var softScore = ((PythonDecimal) softScoreField.get(pythonObject)).value;
return HardMediumSoftBigDecimalScore.of(hardScore, mediumScore, softScore);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/score/HardMediumSoftScorePythonJavaTypeMapping.java | package ai.timefold.solver.python.score;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import ai.timefold.jpyinterpreter.PythonLikeObject;
import ai.timefold.jpyinterpreter.types.PythonJavaTypeMapping;
import ai.timefold.jpyinterpreter.types.PythonLikeType;
import ai.timefold.jpyinterpreter.types.numeric.PythonInteger;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore;
public final class HardMediumSoftScorePythonJavaTypeMapping
implements PythonJavaTypeMapping<PythonLikeObject, HardMediumSoftLongScore> {
private final PythonLikeType type;
private final Constructor<?> constructor;
private final Field hardScoreField;
private final Field mediumScoreField;
private final Field softScoreField;
public HardMediumSoftScorePythonJavaTypeMapping(PythonLikeType type)
throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
this.type = type;
var clazz = type.getJavaClass();
constructor = clazz.getConstructor();
hardScoreField = clazz.getField("hard_score");
mediumScoreField = clazz.getField("medium_score");
softScoreField = clazz.getField("soft_score");
}
@Override
public PythonLikeType getPythonType() {
return type;
}
@Override
public Class<? extends HardMediumSoftLongScore> getJavaType() {
return HardMediumSoftLongScore.class;
}
@Override
public PythonLikeObject toPythonObject(HardMediumSoftLongScore javaObject) {
try {
var instance = constructor.newInstance();
hardScoreField.set(instance, PythonInteger.valueOf(javaObject.hardScore()));
mediumScoreField.set(instance, PythonInteger.valueOf(javaObject.mediumScore()));
softScoreField.set(instance, PythonInteger.valueOf(javaObject.softScore()));
return (PythonLikeObject) instance;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
@Override
public HardMediumSoftLongScore toJavaObject(PythonLikeObject pythonObject) {
try {
var hardScore = ((PythonInteger) hardScoreField.get(pythonObject)).value.longValue();
var mediumScore = ((PythonInteger) mediumScoreField.get(pythonObject)).value.longValue();
var softScore = ((PythonInteger) softScoreField.get(pythonObject)).value.longValue();
return HardMediumSoftLongScore.of(hardScore, mediumScore, softScore);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/score/HardSoftDecimalScorePythonJavaTypeMapping.java | package ai.timefold.solver.python.score;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import ai.timefold.jpyinterpreter.PythonLikeObject;
import ai.timefold.jpyinterpreter.types.PythonJavaTypeMapping;
import ai.timefold.jpyinterpreter.types.PythonLikeType;
import ai.timefold.jpyinterpreter.types.numeric.PythonDecimal;
import ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore;
public final class HardSoftDecimalScorePythonJavaTypeMapping
implements PythonJavaTypeMapping<PythonLikeObject, HardSoftBigDecimalScore> {
private final PythonLikeType type;
private final Constructor<?> constructor;
private final Field hardScoreField;
private final Field softScoreField;
public HardSoftDecimalScorePythonJavaTypeMapping(PythonLikeType type)
throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
this.type = type;
var clazz = type.getJavaClass();
constructor = clazz.getConstructor();
hardScoreField = clazz.getField("hard_score");
softScoreField = clazz.getField("soft_score");
}
@Override
public PythonLikeType getPythonType() {
return type;
}
@Override
public Class<? extends HardSoftBigDecimalScore> getJavaType() {
return HardSoftBigDecimalScore.class;
}
@Override
public PythonLikeObject toPythonObject(HardSoftBigDecimalScore javaObject) {
try {
var instance = constructor.newInstance();
hardScoreField.set(instance, new PythonDecimal(javaObject.hardScore()));
softScoreField.set(instance, new PythonDecimal(javaObject.softScore()));
return (PythonLikeObject) instance;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
@Override
public HardSoftBigDecimalScore toJavaObject(PythonLikeObject pythonObject) {
try {
var hardScore = ((PythonDecimal) hardScoreField.get(pythonObject)).value;
var softScore = ((PythonDecimal) softScoreField.get(pythonObject)).value;
return HardSoftBigDecimalScore.of(hardScore, softScore);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/score/HardSoftScorePythonJavaTypeMapping.java | package ai.timefold.solver.python.score;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import ai.timefold.jpyinterpreter.PythonLikeObject;
import ai.timefold.jpyinterpreter.types.PythonJavaTypeMapping;
import ai.timefold.jpyinterpreter.types.PythonLikeType;
import ai.timefold.jpyinterpreter.types.numeric.PythonInteger;
import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
public final class HardSoftScorePythonJavaTypeMapping implements PythonJavaTypeMapping<PythonLikeObject, HardSoftLongScore> {
private final PythonLikeType type;
private final Constructor<?> constructor;
private final Field hardScoreField;
private final Field softScoreField;
public HardSoftScorePythonJavaTypeMapping(PythonLikeType type)
throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
this.type = type;
var clazz = type.getJavaClass();
constructor = clazz.getConstructor();
hardScoreField = clazz.getField("hard_score");
softScoreField = clazz.getField("soft_score");
}
@Override
public PythonLikeType getPythonType() {
return type;
}
@Override
public Class<? extends HardSoftLongScore> getJavaType() {
return HardSoftLongScore.class;
}
@Override
public PythonLikeObject toPythonObject(HardSoftLongScore javaObject) {
try {
var instance = constructor.newInstance();
hardScoreField.set(instance, PythonInteger.valueOf(javaObject.hardScore()));
softScoreField.set(instance, PythonInteger.valueOf(javaObject.softScore()));
return (PythonLikeObject) instance;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
@Override
public HardSoftLongScore toJavaObject(PythonLikeObject pythonObject) {
try {
var hardScore = ((PythonInteger) hardScoreField.get(pythonObject)).value.longValue();
var softScore = ((PythonInteger) softScoreField.get(pythonObject)).value.longValue();
return HardSoftLongScore.of(hardScore, softScore);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/score/SimpleDecimalScorePythonJavaTypeMapping.java | package ai.timefold.solver.python.score;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import ai.timefold.jpyinterpreter.PythonLikeObject;
import ai.timefold.jpyinterpreter.types.PythonJavaTypeMapping;
import ai.timefold.jpyinterpreter.types.PythonLikeType;
import ai.timefold.jpyinterpreter.types.numeric.PythonDecimal;
import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore;
public final class SimpleDecimalScorePythonJavaTypeMapping
implements PythonJavaTypeMapping<PythonLikeObject, SimpleBigDecimalScore> {
private final PythonLikeType type;
private final Constructor<?> constructor;
private final Field scoreField;
public SimpleDecimalScorePythonJavaTypeMapping(PythonLikeType type)
throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
this.type = type;
var clazz = type.getJavaClass();
constructor = clazz.getConstructor();
scoreField = clazz.getField("score");
}
@Override
public PythonLikeType getPythonType() {
return type;
}
@Override
public Class<? extends SimpleBigDecimalScore> getJavaType() {
return SimpleBigDecimalScore.class;
}
@Override
public PythonLikeObject toPythonObject(SimpleBigDecimalScore javaObject) {
try {
var instance = constructor.newInstance();
scoreField.set(instance, new PythonDecimal(javaObject.score()));
return (PythonLikeObject) instance;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
@Override
public SimpleBigDecimalScore toJavaObject(PythonLikeObject pythonObject) {
try {
var score = ((PythonDecimal) scoreField.get(pythonObject)).value;
return SimpleBigDecimalScore.of(score);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python | java-sources/ai/timefold/solver/timefold-solver-python-core/1.24.0/ai/timefold/solver/python/score/SimpleScorePythonJavaTypeMapping.java | package ai.timefold.solver.python.score;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import ai.timefold.jpyinterpreter.PythonLikeObject;
import ai.timefold.jpyinterpreter.types.PythonJavaTypeMapping;
import ai.timefold.jpyinterpreter.types.PythonLikeType;
import ai.timefold.jpyinterpreter.types.numeric.PythonInteger;
import ai.timefold.solver.core.api.score.buildin.simplelong.SimpleLongScore;
public final class SimpleScorePythonJavaTypeMapping implements PythonJavaTypeMapping<PythonLikeObject, SimpleLongScore> {
private final PythonLikeType type;
private final Constructor<?> constructor;
private final Field scoreField;
public SimpleScorePythonJavaTypeMapping(PythonLikeType type)
throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
this.type = type;
var clazz = type.getJavaClass();
constructor = clazz.getConstructor();
scoreField = clazz.getField("score");
}
@Override
public PythonLikeType getPythonType() {
return type;
}
@Override
public Class<? extends SimpleLongScore> getJavaType() {
return SimpleLongScore.class;
}
@Override
public PythonLikeObject toPythonObject(SimpleLongScore javaObject) {
try {
var instance = constructor.newInstance();
scoreField.set(instance, PythonInteger.valueOf(javaObject.score()));
return (PythonLikeObject) instance;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
@Override
public SimpleLongScore toJavaObject(PythonLikeObject pythonObject) {
try {
var score = ((PythonInteger) scoreField.get(pythonObject)).value.longValue();
return SimpleLongScore.of(score);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/TimefoldRecorder.java | package ai.timefold.solver.quarkus;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
import jakarta.inject.Named;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
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.config.solver.termination.DiminishedReturnsTerminationConfig;
import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.quarkus.config.DiminishedReturnsRuntimeConfig;
import ai.timefold.solver.quarkus.config.SolverRuntimeConfig;
import ai.timefold.solver.quarkus.config.TimefoldRuntimeConfig;
import org.jspecify.annotations.Nullable;
import io.quarkus.runtime.RuntimeValue;
import io.quarkus.runtime.annotations.Recorder;
@Recorder
public class TimefoldRecorder {
final RuntimeValue<TimefoldRuntimeConfig> timefoldRuntimeConfig;
public TimefoldRecorder(final RuntimeValue<TimefoldRuntimeConfig> timefoldRuntimeConfig) {
this.timefoldRuntimeConfig = timefoldRuntimeConfig;
}
public static void assertNoUnmatchedProperties(Set<String> expectedNames, Set<String> actualNames) {
var allExpectedNames = new HashSet<>(expectedNames);
allExpectedNames.add(TimefoldRuntimeConfig.DEFAULT_SOLVER_NAME);
if (!allExpectedNames.containsAll(actualNames)) {
var expectedNamesSorted = expectedNames.stream()
.sorted()
.toList();
var unmatchedNamesSorted = actualNames.stream()
.filter(Predicate.not(allExpectedNames::contains))
.sorted()
.toList();
throw new IllegalStateException("""
Some names defined in properties (%s) do not have \
a corresponding @%s injection point (%s). Maybe you \
misspelled them?
""".formatted(unmatchedNamesSorted, Named.class.getSimpleName(),
expectedNamesSorted));
}
}
public void assertNoUnmatchedRuntimeProperties(Set<String> names) {
assertNoUnmatchedProperties(names, timefoldRuntimeConfig.getValue().solver().keySet());
}
public Supplier<SolverConfig> solverConfigSupplier(final String solverName,
final SolverConfig solverConfig,
Map<String, RuntimeValue<MemberAccessor>> generatedGizmoMemberAccessorMap,
Map<String, RuntimeValue<SolutionCloner>> generatedGizmoSolutionClonerMap) {
return () -> {
updateSolverConfigWithRuntimeProperties(solverName, solverConfig);
Map<String, MemberAccessor> memberAccessorMap = new HashMap<>();
Map<String, SolutionCloner> solutionClonerMap = new HashMap<>();
generatedGizmoMemberAccessorMap
.forEach((className, runtimeValue) -> memberAccessorMap.put(className, runtimeValue.getValue()));
generatedGizmoSolutionClonerMap
.forEach((className, runtimeValue) -> solutionClonerMap.put(className, runtimeValue.getValue()));
solverConfig.setGizmoMemberAccessorMap(memberAccessorMap);
solverConfig.setGizmoSolutionClonerMap(solutionClonerMap);
return solverConfig;
};
}
public Supplier<SolverManagerConfig> solverManagerConfig(final SolverManagerConfig solverManagerConfig) {
return () -> {
updateSolverManagerConfigWithRuntimeProperties(solverManagerConfig);
return solverManagerConfig;
};
}
public <Solution_, ProblemId_> Supplier<SolverManager<Solution_, ProblemId_>> solverManager(final String solverName,
final SolverConfig solverConfig,
Map<String, RuntimeValue<MemberAccessor>> generatedGizmoMemberAccessorMap,
Map<String, RuntimeValue<SolutionCloner>> generatedGizmoSolutionClonerMap) {
return () -> {
updateSolverConfigWithRuntimeProperties(solverName, solverConfig);
Map<String, MemberAccessor> memberAccessorMap = new HashMap<>();
Map<String, SolutionCloner> solutionClonerMap = new HashMap<>();
generatedGizmoMemberAccessorMap
.forEach((className, runtimeValue) -> memberAccessorMap.put(className, runtimeValue.getValue()));
generatedGizmoSolutionClonerMap
.forEach((className, runtimeValue) -> solutionClonerMap.put(className, runtimeValue.getValue()));
solverConfig.setGizmoMemberAccessorMap(memberAccessorMap);
solverConfig.setGizmoSolutionClonerMap(solutionClonerMap);
SolverManagerConfig solverManagerConfig = new SolverManagerConfig();
updateSolverManagerConfigWithRuntimeProperties(solverManagerConfig);
SolverFactory<Solution_> solverFactory = SolverFactory.create(solverConfig);
return (SolverManager<Solution_, ProblemId_>) SolverManager.create(solverFactory, solverManagerConfig);
};
}
private void updateSolverConfigWithRuntimeProperties(String solverName, SolverConfig solverConfig) {
updateSolverConfigWithRuntimeProperties(solverConfig, timefoldRuntimeConfig.getValue()
.getSolverRuntimeConfig(solverName).orElse(null));
}
public static void updateSolverConfigWithRuntimeProperties(SolverConfig solverConfig,
@Nullable SolverRuntimeConfig solverRuntimeConfig) {
TerminationConfig terminationConfig = solverConfig.getTerminationConfig();
if (terminationConfig == null) {
terminationConfig = new TerminationConfig();
solverConfig.setTerminationConfig(terminationConfig);
}
var maybeSolverRuntimeConfig = Optional.ofNullable(solverRuntimeConfig);
maybeSolverRuntimeConfig.flatMap(config -> config.termination().spentLimit())
.ifPresent(terminationConfig::setSpentLimit);
maybeSolverRuntimeConfig.flatMap(config -> config.termination().unimprovedSpentLimit())
.ifPresent(terminationConfig::setUnimprovedSpentLimit);
maybeSolverRuntimeConfig.flatMap(config -> config.termination().bestScoreLimit())
.ifPresent(terminationConfig::setBestScoreLimit);
maybeSolverRuntimeConfig.flatMap(SolverRuntimeConfig::environmentMode)
.ifPresent(solverConfig::setEnvironmentMode);
maybeSolverRuntimeConfig.flatMap(SolverRuntimeConfig::daemon)
.ifPresent(solverConfig::setDaemon);
maybeSolverRuntimeConfig.flatMap(SolverRuntimeConfig::moveThreadCount)
.ifPresent(solverConfig::setMoveThreadCount);
maybeSolverRuntimeConfig.flatMap(SolverRuntimeConfig::randomSeed)
.ifPresent(solverConfig::setRandomSeed);
maybeSolverRuntimeConfig.flatMap(config -> config.termination().diminishedReturns())
.ifPresent(diminishedReturnsConfig -> setDiminishedReturns(solverConfig, diminishedReturnsConfig));
}
private static void setDiminishedReturns(SolverConfig solverConfig,
DiminishedReturnsRuntimeConfig diminishedReturnsRuntimeConfig) {
// If we are here, at least one of enabled, sliding-window, or minimum-improvement-ratio is set.
if (!diminishedReturnsRuntimeConfig.enabled().orElse(
diminishedReturnsRuntimeConfig.minimumImprovementRatio().isPresent() ||
diminishedReturnsRuntimeConfig.slidingWindowDuration().isPresent())) {
return;
}
var terminationConfig = solverConfig.getTerminationConfig();
if (terminationConfig == null) {
terminationConfig = new TerminationConfig();
solverConfig.setTerminationConfig(terminationConfig);
}
var diminishedReturnsConfig = new DiminishedReturnsTerminationConfig();
diminishedReturnsRuntimeConfig.slidingWindowDuration()
.ifPresent(diminishedReturnsConfig::setSlidingWindowDuration);
diminishedReturnsRuntimeConfig.minimumImprovementRatio()
.ifPresent(diminishedReturnsConfig::setMinimumImprovementRatio);
terminationConfig.setDiminishedReturnsConfig(diminishedReturnsConfig);
}
private void updateSolverManagerConfigWithRuntimeProperties(SolverManagerConfig solverManagerConfig) {
timefoldRuntimeConfig.getValue().solverManager().parallelSolverCount()
.ifPresent(solverManagerConfig::setParallelSolverCount);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/bean/BeanUtil.java | package ai.timefold.solver.quarkus.bean;
import java.util.Objects;
import ai.timefold.solver.core.api.score.stream.ConstraintMetaModel;
import ai.timefold.solver.core.api.solver.SolverFactory;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.core.impl.solver.DefaultSolverFactory;
public class BeanUtil {
public static ConstraintMetaModel buildConstraintMetaModel(SolverFactory<?> solverFactory) {
if (Objects.requireNonNull(solverFactory) instanceof DefaultSolverFactory<?> defaultSolverFactory) {
var scoreDirectorFactory = defaultSolverFactory.getScoreDirectorFactory();
if (scoreDirectorFactory instanceof AbstractConstraintStreamScoreDirectorFactory<?, ?, ?> 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()));
}
} else {
throw new IllegalStateException(
"%s is not supported by the solver factory (%s)."
.formatted(ConstraintMetaModel.class.getSimpleName(), solverFactory.getClass().getName()));
}
}
private BeanUtil() {
throw new IllegalStateException("Utility class");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/bean/DefaultTimefoldBeanProvider.java | package ai.timefold.solver.quarkus.bean;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.Dependent;
import jakarta.enterprise.inject.Produces;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.ScoreManager;
import ai.timefold.solver.core.api.score.buildin.bendable.BendableScore;
import ai.timefold.solver.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.bendablelong.BendableLongScore;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.simplelong.SimpleLongScore;
import ai.timefold.solver.core.api.score.stream.ConstraintMetaModel;
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.solver.SolverConfig;
import ai.timefold.solver.core.config.solver.SolverManagerConfig;
import io.quarkus.arc.DefaultBean;
import io.quarkus.arc.Lock;
/**
* Provider for managed resources of the default solver.
*/
@ApplicationScoped
@Lock(Lock.Type.WRITE)
public class DefaultTimefoldBeanProvider {
private SolverFactory<?> solverFactory;
private ConstraintMetaModel constraintMetaModel;
private SolverManager<?, ?> solverManager;
private SolutionManager<?, ?> solutionManager;
private ScoreManager<?, ?> scoreManager;
@SuppressWarnings("unchecked")
@DefaultBean
@Dependent
@Produces
<Solution_> SolverFactory<Solution_> solverFactory(SolverConfig solverConfig) {
if (solverFactory == null) {
solverFactory = SolverFactory.create(solverConfig);
}
return (SolverFactory<Solution_>) solverFactory;
}
@DefaultBean
@Dependent
@Produces
ConstraintMetaModel constraintProviderMetaModel(SolverFactory<?> solverFactory) {
if (constraintMetaModel == null) {
// The metamodel is not compatible with Quarkus code recording, thus we need to rebuild it at runtime.
constraintMetaModel = BeanUtil.buildConstraintMetaModel(solverFactory);
}
return constraintMetaModel;
}
@SuppressWarnings("unchecked")
@DefaultBean
@Dependent
@Produces
<Solution_, ProblemId_> SolverManager<Solution_, ProblemId_> solverManager(SolverFactory<Solution_> solverFactory,
SolverManagerConfig solverManagerConfig) {
if (solverManager == null) {
solverManager = SolverManager.create(solverFactory, solverManagerConfig);
}
return (SolverManager<Solution_, ProblemId_>) solverManager;
}
// Quarkus-ARC-Weld can't deal with enum pattern generics such as Score<S extends Score<S>>.
// See https://github.com/quarkusio/quarkus/pull/12137
// @DefaultBean
// @Dependent
// @Produces
@SuppressWarnings("unchecked")
@Deprecated(forRemoval = true)
<Solution_, Score_ extends Score<Score_>> ScoreManager<Solution_, Score_>
scoreManager(SolverFactory<Solution_> solverFactory) {
if (scoreManager == null) {
scoreManager = ScoreManager.create(solverFactory);
}
return (ScoreManager<Solution_, Score_>) scoreManager;
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, SimpleScore> scoreManager_workaroundSimpleScore(
SolverFactory<Solution_> solverFactory) {
return scoreManager(solverFactory);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, SimpleLongScore> scoreManager_workaroundSimpleLongScore(
SolverFactory<Solution_> solverFactory) {
return scoreManager(solverFactory);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, SimpleBigDecimalScore> scoreManager_workaroundSimpleBigDecimalScore(
SolverFactory<Solution_> solverFactory) {
return scoreManager(solverFactory);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, HardSoftScore> scoreManager_workaroundHardSoftScore(
SolverFactory<Solution_> solverFactory) {
return scoreManager(solverFactory);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, HardSoftLongScore> scoreManager_workaroundHardSoftLongScore(
SolverFactory<Solution_> solverFactory) {
return scoreManager(solverFactory);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, HardSoftBigDecimalScore> scoreManager_workaroundHardSoftBigDecimalScore(
SolverFactory<Solution_> solverFactory) {
return scoreManager(solverFactory);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, HardMediumSoftScore> scoreManager_workaroundHardMediumSoftScore(
SolverFactory<Solution_> solverFactory) {
return scoreManager(solverFactory);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, HardMediumSoftLongScore> scoreManager_workaroundHardMediumSoftLongScore(
SolverFactory<Solution_> solverFactory) {
return scoreManager(solverFactory);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, HardMediumSoftBigDecimalScore> scoreManager_workaroundHardMediumSoftBigDecimalScore(
SolverFactory<Solution_> solverFactory) {
return scoreManager(solverFactory);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, BendableScore> scoreManager_workaroundBendableScore(
SolverFactory<Solution_> solverFactory) {
return scoreManager(solverFactory);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, BendableLongScore> scoreManager_workaroundBendableLongScore(
SolverFactory<Solution_> solverFactory) {
return scoreManager(solverFactory);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, BendableBigDecimalScore> scoreManager_workaroundBendableBigDecimalScore(
SolverFactory<Solution_> solverFactory) {
return scoreManager(solverFactory);
}
// Quarkus-ARC-Weld can't deal with enum pattern generics such as Score<S extends Score<S>>.
// See https://github.com/quarkusio/quarkus/pull/12137
// @DefaultBean
// @Dependent
// @Produces
@SuppressWarnings("unchecked")
<Solution_, Score_ extends Score<Score_>> SolutionManager<Solution_, Score_> solutionManager(
SolverFactory<Solution_> solverFactory) {
if (solutionManager == null) {
solutionManager = SolutionManager.create(solverFactory);
}
return (SolutionManager<Solution_, Score_>) solutionManager;
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, SimpleScore> solutionManager_workaroundSimpleScore(
SolverFactory<Solution_> solverFactory) {
return solutionManager(solverFactory);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, SimpleLongScore> solutionManager_workaroundSimpleLongScore(
SolverFactory<Solution_> solverFactory) {
return solutionManager(solverFactory);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, SimpleBigDecimalScore> solutionManager_workaroundSimpleBigDecimalScore(
SolverFactory<Solution_> solverFactory) {
return solutionManager(solverFactory);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, HardSoftScore> solutionManager_workaroundHardSoftScore(
SolverFactory<Solution_> solverFactory) {
return solutionManager(solverFactory);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, HardSoftLongScore> solutionManager_workaroundHardSoftLongScore(
SolverFactory<Solution_> solverFactory) {
return solutionManager(solverFactory);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, HardSoftBigDecimalScore> solutionManager_workaroundHardSoftBigDecimalScore(
SolverFactory<Solution_> solverFactory) {
return solutionManager(solverFactory);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, HardMediumSoftScore> solutionManager_workaroundHardMediumSoftScore(
SolverFactory<Solution_> solverFactory) {
return solutionManager(solverFactory);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, HardMediumSoftLongScore> solutionManager_workaroundHardMediumSoftLongScore(
SolverFactory<Solution_> solverFactory) {
return solutionManager(solverFactory);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, HardMediumSoftBigDecimalScore>
solutionManager_workaroundHardMediumSoftBigDecimalScore(SolverFactory<Solution_> solverFactory) {
return solutionManager(solverFactory);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, BendableScore> solutionManager_workaroundBendableScore(
SolverFactory<Solution_> solverFactory) {
return solutionManager(solverFactory);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, BendableLongScore> solutionManager_workaroundBendableLongScore(
SolverFactory<Solution_> solverFactory) {
return solutionManager(solverFactory);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, BendableBigDecimalScore> solutionManager_workaroundBendableBigDecimalScore(
SolverFactory<Solution_> solverFactory) {
return solutionManager(solverFactory);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/bean/TimefoldSolverBannerBean.java | package ai.timefold.solver.quarkus.bean;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService;
import org.jboss.logging.Logger;
import io.quarkus.runtime.StartupEvent;
@ApplicationScoped
public class TimefoldSolverBannerBean {
private static final Logger LOGGER = Logger.getLogger(TimefoldSolverBannerBean.class);
void onStart(@Observes StartupEvent ev) {
LOGGER.info("Using Timefold Solver " + TimefoldSolverEnterpriseService.identifySolverVersion() + ".");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/bean/UnavailableTimefoldBeanProvider.java | package ai.timefold.solver.quarkus.bean;
import jakarta.enterprise.context.Dependent;
import jakarta.enterprise.inject.Produces;
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.ScoreManager;
import ai.timefold.solver.core.api.score.buildin.bendable.BendableScore;
import ai.timefold.solver.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.bendablelong.BendableLongScore;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.simplelong.SimpleLongScore;
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 io.quarkus.arc.DefaultBean;
/**
* Throws an exception if an application tries to inject beans and the Timefold Quarkus extension is skipped
* due to missing domain classes.
*/
public class UnavailableTimefoldBeanProvider {
@DefaultBean
@Dependent
@Produces
<Solution_> SolverFactory<Solution_> solverFactory() {
throw createException(SolverFactory.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_, ProblemId_> SolverManager<Solution_, ProblemId_> solverManager() {
throw createException(SolverManager.class);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, SimpleScore> scoreManager_workaroundSimpleScore() {
throw createException(ScoreManager.class);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, SimpleLongScore> scoreManager_workaroundSimpleLongScore() {
throw createException(ScoreManager.class);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, SimpleBigDecimalScore> scoreManager_workaroundSimpleBigDecimalScore() {
throw createException(ScoreManager.class);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, HardSoftScore> scoreManager_workaroundHardSoftScore() {
throw createException(ScoreManager.class);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, HardSoftLongScore> scoreManager_workaroundHardSoftLongScore() {
throw createException(ScoreManager.class);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, HardSoftBigDecimalScore> scoreManager_workaroundHardSoftBigDecimalScore() {
throw createException(ScoreManager.class);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, HardMediumSoftScore> scoreManager_workaroundHardMediumSoftScore() {
throw createException(ScoreManager.class);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, HardMediumSoftLongScore> scoreManager_workaroundHardMediumSoftLongScore() {
throw createException(ScoreManager.class);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, HardMediumSoftBigDecimalScore>
scoreManager_workaroundHardMediumSoftBigDecimalScore() {
throw createException(ScoreManager.class);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, BendableScore> scoreManager_workaroundBendableScore() {
throw createException(ScoreManager.class);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, BendableLongScore> scoreManager_workaroundBendableLongScore() {
throw createException(ScoreManager.class);
}
@Deprecated(forRemoval = true)
@DefaultBean
@Dependent
@Produces
<Solution_> ScoreManager<Solution_, BendableBigDecimalScore> scoreManager_workaroundBendableBigDecimalScore() {
throw createException(ScoreManager.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, SimpleScore> solutionManager_workaroundSimpleScore() {
throw createException(SolutionManager.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, SimpleLongScore> solutionManager_workaroundSimpleLongScore() {
throw createException(SolutionManager.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, SimpleBigDecimalScore> solutionManager_workaroundSimpleBigDecimalScore() {
throw createException(SolutionManager.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, HardSoftScore> solutionManager_workaroundHardSoftScore() {
throw createException(SolutionManager.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, HardSoftLongScore> solutionManager_workaroundHardSoftLongScore() {
throw createException(SolutionManager.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, HardSoftBigDecimalScore> solutionManager_workaroundHardSoftBigDecimalScore() {
throw createException(SolutionManager.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, HardMediumSoftScore> solutionManager_workaroundHardMediumSoftScore() {
throw createException(SolutionManager.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, HardMediumSoftLongScore> solutionManager_workaroundHardMediumSoftLongScore() {
throw createException(SolutionManager.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, HardMediumSoftBigDecimalScore>
solutionManager_workaroundHardMediumSoftBigDecimalScore() {
throw createException(SolutionManager.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, BendableScore> solutionManager_workaroundBendableScore() {
throw createException(SolutionManager.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, BendableLongScore> solutionManager_workaroundBendableLongScore() {
throw createException(SolutionManager.class);
}
@DefaultBean
@Dependent
@Produces
<Solution_> SolutionManager<Solution_, BendableBigDecimalScore> solutionManager_workaroundBendableBigDecimalScore() {
throw createException(SolutionManager.class);
}
private RuntimeException createException(Class<?> beanClass) {
return new IllegalStateException("The " + beanClass.getName() + " is not available as there are no @"
+ PlanningSolution.class.getSimpleName() + " or @" + PlanningEntity.class.getSimpleName()
+ " annotated classes."
+ "\nIf your domain classes are located in a dependency of this project, maybe try generating"
+ " the Jandex index by using the jandex-maven-plugin in that dependency, or by adding"
+ "application.properties entries (quarkus.index-dependency.<name>.group-id"
+ " and quarkus.index-dependency.<name>.artifact-id).");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/config/DiminishedReturnsRuntimeConfig.java | package ai.timefold.solver.quarkus.config;
import java.time.Duration;
import java.util.Optional;
import java.util.OptionalDouble;
import io.quarkus.runtime.annotations.ConfigGroup;
@ConfigGroup
public interface DiminishedReturnsRuntimeConfig {
/**
* 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.
*/
Optional<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.
*/
Optional<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.
*/
OptionalDouble minimumImprovementRatio();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/config/SolverManagerRuntimeConfig.java | package ai.timefold.solver.quarkus.config;
import java.util.Optional;
import ai.timefold.solver.core.config.solver.SolverManagerConfig;
import io.quarkus.runtime.annotations.ConfigGroup;
import io.smallrye.config.WithDefault;
/**
* During build time, this is translated into Timefold's {@link SolverManagerConfig}.
*/
@ConfigGroup
public interface SolverManagerRuntimeConfig {
/**
* The number of solvers that run in parallel. This directly influences CPU consumption.
* Defaults to {@value SolverManagerConfig#PARALLEL_SOLVER_COUNT_AUTO}.
* Other options include a number or formula based on the available processor count.
*/
@WithDefault("AUTO")
Optional<String> parallelSolverCount();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/config/SolverRuntimeConfig.java | package ai.timefold.solver.quarkus.config;
import java.util.Optional;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.config.solver.SolverConfig;
import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
import io.quarkus.runtime.annotations.ConfigGroup;
/**
* During run time, this overrides some of Timefold's {@link SolverConfig}
* properties.
*/
@ConfigGroup
public interface SolverRuntimeConfig {
/**
* Enable runtime assertions to detect common bugs in your implementation during development.
* Defaults to {@link EnvironmentMode#PHASE_ASSERT}.
*/
Optional<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".
*/
Optional<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 {@value SolverConfig#MOVE_THREAD_COUNT_NONE}.
* Other options include {@value SolverConfig#MOVE_THREAD_COUNT_AUTO}, a number
* or formula based on the available processor count.
*/
Optional<String> moveThreadCount();
/**
* Configuration properties that overwrite {@link TerminationConfig}.
*/
TerminationRuntimeConfig termination();
/**
* Configuration of the random seed.
*/
Optional<Long> randomSeed();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/config/TerminationRuntimeConfig.java | package ai.timefold.solver.quarkus.config;
import java.time.Duration;
import java.util.Optional;
import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
import io.quarkus.runtime.annotations.ConfigGroup;
/**
* Translated into Timefold's {@link TerminationConfig} at startup.
*/
@ConfigGroup
public interface TerminationRuntimeConfig {
/**
* 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 {@link Duration}.
*/
Optional<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 {@link Duration}.
*/
Optional<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.
*/
Optional<String> bestScoreLimit();
/**
* Configuration properties for the diminished returns termination.
*/
Optional<DiminishedReturnsRuntimeConfig> diminishedReturns();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/config/TimefoldRuntimeConfig.java | package ai.timefold.solver.quarkus.config;
import java.util.Map;
import java.util.Optional;
import ai.timefold.solver.core.config.solver.SolverConfig;
import ai.timefold.solver.core.config.solver.SolverManagerConfig;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;
import io.quarkus.runtime.annotations.StaticInitSafe;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.WithDefaults;
import io.smallrye.config.WithUnnamedKey;
@ConfigMapping(prefix = "quarkus.timefold")
@ConfigRoot(phase = ConfigPhase.RUN_TIME)
@StaticInitSafe
public interface TimefoldRuntimeConfig {
String DEFAULT_SOLVER_NAME = "default";
/**
* During run time, this is translated into {@link SolverConfig} runtime properties per solver.
* If a solver name is not explicitly specified, the solver name will default to {@link #DEFAULT_SOLVER_NAME}.
*/
@WithUnnamedKey(DEFAULT_SOLVER_NAME)
Map<String, SolverRuntimeConfig> solver();
/**
* Configuration properties that overwrite {@link SolverManagerConfig}.
*/
@WithDefaults
SolverManagerRuntimeConfig solverManager();
default Optional<SolverRuntimeConfig> getSolverRuntimeConfig(String solverName) {
return Optional.ofNullable(solver().get(solverName));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/devui/DevUISolverConfig.java | package ai.timefold.solver.quarkus.devui;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ai.timefold.solver.core.api.solver.SolverFactory;
public class DevUISolverConfig {
private final Map<String, String> solverConfigFiles;
private final Map<String, SolverFactory<?>> solverFactories;
public DevUISolverConfig() {
this.solverConfigFiles = new HashMap<>();
this.solverFactories = new HashMap<>();
}
public void setFactory(String solverName, SolverFactory<?> factory) {
this.solverFactories.put(solverName, factory);
}
public SolverFactory getFactory(String solverName) {
return this.solverFactories.get(solverName);
}
public void setSolverConfigFile(String solverName, String content) {
this.solverConfigFiles.put(solverName, content);
}
public String getSolverConfigFile(String solverName) {
return this.solverConfigFiles.getOrDefault(solverName, "");
}
public List<String> getSolverNames() {
return this.solverConfigFiles.keySet().stream().toList();
}
public boolean isEmpty() {
return this.solverConfigFiles.isEmpty();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/devui/TimefoldDevUIProperties.java | package ai.timefold.solver.quarkus.devui;
import java.util.List;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
public class TimefoldDevUIProperties { // TODO make record?
private final TimefoldModelProperties timefoldModelProperties;
private final String effectiveSolverConfigXML;
private final List<ConstraintRef> constraintList;
public TimefoldDevUIProperties(TimefoldModelProperties timefoldModelProperties, String effectiveSolverConfigXML,
List<ConstraintRef> constraintList) {
this.timefoldModelProperties = timefoldModelProperties;
this.effectiveSolverConfigXML = effectiveSolverConfigXML;
this.constraintList = constraintList;
}
public TimefoldModelProperties getTimefoldModelProperties() {
return timefoldModelProperties;
}
public String getEffectiveSolverConfig() {
return effectiveSolverConfigXML;
}
public List<ConstraintRef> getConstraintList() {
return constraintList;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/devui/TimefoldDevUIPropertiesRPCService.java | package ai.timefold.solver.quarkus.devui;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
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.constraint.ConstraintRef;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.solver.SolverFactory;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.core.impl.solver.DefaultSolverFactory;
import ai.timefold.solver.quarkus.config.TimefoldRuntimeConfig;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
@ApplicationScoped
public class TimefoldDevUIPropertiesRPCService {
private final DevUISolverConfig devUISolverConfig;
private final Map<String, TimefoldDevUIProperties> devUIProperties;
@Inject
public TimefoldDevUIPropertiesRPCService(DevUISolverConfig devUISolverConfig) {
this.devUISolverConfig = devUISolverConfig;
this.devUIProperties = new HashMap<>();
}
@PostConstruct
public void init() {
if (devUISolverConfig != null && !devUISolverConfig.isEmpty()) {
// SolverConfigIO does not work at runtime,
// but the build time SolverConfig does not have properties
// that can be set at runtime (ex: termination), so the
// effective solver config will be missing some properties
this.devUISolverConfig.getSolverNames().forEach(key -> this.devUIProperties.put(key,
new TimefoldDevUIProperties(buildModelInfo(devUISolverConfig.getFactory(key)),
buildXmlContentWithComment(devUISolverConfig.getSolverConfigFile(key),
"Properties that can be set at runtime are not included"),
buildConstraintList(devUISolverConfig.getFactory(key)))));
} else {
devUIProperties.put(TimefoldRuntimeConfig.DEFAULT_SOLVER_NAME, new TimefoldDevUIProperties(
buildModelInfo(null),
"<!-- Plugin execution was skipped " + "because there are no @" + PlanningSolution.class.getSimpleName()
+ " or @" + PlanningEntity.class.getSimpleName() + " annotated classes. -->\n<solver />",
Collections.emptyList()));
}
}
public JsonObject getConfig() {
var out = new JsonObject();
var config = new JsonObject();
out.put("config", config);
devUIProperties.forEach((key, value) -> config.put(key, value.getEffectiveSolverConfig()));
return out;
}
public JsonObject getConstraints() {
var out = new JsonObject();
devUIProperties.forEach((key, value) -> out.put(key, JsonArray.of(value.getConstraintList()
.stream()
.map(ConstraintRef::constraintId)
.toArray())));
return out;
}
public JsonObject getModelInfo() {
JsonObject out = new JsonObject();
devUIProperties.forEach((key, value) -> {
JsonObject property = new JsonObject();
TimefoldModelProperties modelProperties = value.getTimefoldModelProperties();
property.put("solutionClass", modelProperties.solutionClass);
property.put("entityClassList", JsonArray.of(modelProperties.entityClassList.toArray()));
property.put("entityClassToGenuineVariableListMap",
new JsonObject(modelProperties.entityClassToGenuineVariableListMap.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> JsonArray.of(entry.getValue().toArray())))));
property.put("entityClassToShadowVariableListMap",
new JsonObject(modelProperties.entityClassToShadowVariableListMap.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> JsonArray.of(entry.getValue().toArray())))));
out.put(key, property);
});
return out;
}
private TimefoldModelProperties buildModelInfo(SolverFactory<?> solverFactory) {
if (solverFactory != null) {
var solutionDescriptor =
((DefaultSolverFactory<?>) solverFactory).getScoreDirectorFactory().getSolutionDescriptor();
var out = new TimefoldModelProperties();
out.setSolutionClass(solutionDescriptor.getSolutionClass().getName());
var entityClassList = new ArrayList<String>();
var entityClassToGenuineVariableListMap = new HashMap<String, List<String>>();
var entityClassToShadowVariableListMap = new HashMap<String, List<String>>();
for (var entityDescriptor : solutionDescriptor.getEntityDescriptors()) {
entityClassList.add(entityDescriptor.getEntityClass().getName());
var entityClassToGenuineVariableList = new ArrayList<String>();
var entityClassToShadowVariableList = new ArrayList<String>();
for (var variableDescriptor : entityDescriptor.getDeclaredVariableDescriptors()) {
if (variableDescriptor instanceof GenuineVariableDescriptor) {
entityClassToGenuineVariableList.add(variableDescriptor.getVariableName());
} else {
entityClassToShadowVariableList.add(variableDescriptor.getVariableName());
}
}
entityClassToGenuineVariableListMap.put(entityDescriptor.getEntityClass().getName(),
entityClassToGenuineVariableList);
entityClassToShadowVariableListMap.put(entityDescriptor.getEntityClass().getName(),
entityClassToShadowVariableList);
}
out.setEntityClassList(entityClassList);
out.setEntityClassToGenuineVariableListMap(entityClassToGenuineVariableListMap);
out.setEntityClassToShadowVariableListMap(entityClassToShadowVariableListMap);
return out;
} else {
return new TimefoldModelProperties();
}
}
private List<ConstraintRef> buildConstraintList(SolverFactory<?> solverFactory) {
if (solverFactory != null) {
var scoreDirectorFactory = ((DefaultSolverFactory<?>) solverFactory).getScoreDirectorFactory();
if (scoreDirectorFactory instanceof AbstractConstraintStreamScoreDirectorFactory<?, ?, ?> castScoreDirectorFactory) {
return castScoreDirectorFactory.getConstraintMetaModel().getConstraints()
.stream()
.map(Constraint::getConstraintRef)
.toList();
}
}
return Collections.emptyList();
}
private String buildXmlContentWithComment(String effectiveSolverConfigXml, String comment) {
var indexOfPreambleEnd = effectiveSolverConfigXml.indexOf("?>");
if (indexOfPreambleEnd != -1) {
return effectiveSolverConfigXml.substring(0, indexOfPreambleEnd + 2) +
"\n<!--" + comment + "-->\n"
+ effectiveSolverConfigXml.substring(indexOfPreambleEnd + 2);
} else {
return "<!--" + comment + "-->\n" + effectiveSolverConfigXml;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/devui/TimefoldDevUIRecorder.java | package ai.timefold.solver.quarkus.devui;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.api.solver.SolverFactory;
import ai.timefold.solver.core.config.solver.SolverConfig;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.io.jaxb.SolverConfigIO;
import ai.timefold.solver.quarkus.TimefoldRecorder;
import ai.timefold.solver.quarkus.config.TimefoldRuntimeConfig;
import io.quarkus.runtime.RuntimeValue;
import io.quarkus.runtime.annotations.Recorder;
@Recorder
public class TimefoldDevUIRecorder {
final RuntimeValue<TimefoldRuntimeConfig> timefoldRuntimeConfig;
public TimefoldDevUIRecorder(final RuntimeValue<TimefoldRuntimeConfig> timefoldRuntimeConfig) {
this.timefoldRuntimeConfig = timefoldRuntimeConfig;
}
public Supplier<DevUISolverConfig> solverConfigSupplier(Map<String, SolverConfig> allSolverConfig,
Map<String, RuntimeValue<MemberAccessor>> generatedGizmoMemberAccessorMap,
Map<String, RuntimeValue<SolutionCloner>> generatedGizmoSolutionClonerMap) {
return () -> {
DevUISolverConfig uiSolverConfig = new DevUISolverConfig();
allSolverConfig.forEach((solverName, solverConfig) -> {
updateSolverConfigWithRuntimeProperties(solverName, solverConfig);
Map<String, MemberAccessor> memberAccessorMap = new HashMap<>();
Map<String, SolutionCloner> solutionClonerMap = new HashMap<>();
generatedGizmoMemberAccessorMap
.forEach((className, runtimeValue) -> memberAccessorMap.put(className, runtimeValue.getValue()));
generatedGizmoSolutionClonerMap
.forEach((className, runtimeValue) -> solutionClonerMap.put(className, runtimeValue.getValue()));
solverConfig.setGizmoMemberAccessorMap(memberAccessorMap);
solverConfig.setGizmoSolutionClonerMap(solutionClonerMap);
StringWriter effectiveSolverConfigWriter = new StringWriter();
SolverConfigIO solverConfigIO = new SolverConfigIO();
solverConfigIO.write(solverConfig, effectiveSolverConfigWriter);
uiSolverConfig.setSolverConfigFile(solverName, effectiveSolverConfigWriter.toString());
uiSolverConfig.setFactory(solverName, SolverFactory.create(solverConfig));
});
return uiSolverConfig;
};
}
private void updateSolverConfigWithRuntimeProperties(String solverName, SolverConfig solverConfig) {
TimefoldRecorder.updateSolverConfigWithRuntimeProperties(solverConfig,
timefoldRuntimeConfig.getValue().getSolverRuntimeConfig(solverName).orElse(null));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/devui/TimefoldModelProperties.java | package ai.timefold.solver.quarkus.devui;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class TimefoldModelProperties {
String solutionClass;
List<String> entityClassList;
Map<String, List<String>> entityClassToGenuineVariableListMap;
Map<String, List<String>> entityClassToShadowVariableListMap;
public TimefoldModelProperties() {
solutionClass = "null";
entityClassList = Collections.emptyList();
entityClassToGenuineVariableListMap = Collections.emptyMap();
entityClassToShadowVariableListMap = Collections.emptyMap();
}
public String getSolutionClass() {
return solutionClass;
}
public void setSolutionClass(String solutionClass) {
this.solutionClass = solutionClass;
}
public List<String> getEntityClassList() {
return entityClassList;
}
public void setEntityClassList(List<String> entityClassList) {
this.entityClassList = entityClassList;
}
public Map<String, List<String>> getEntityClassToGenuineVariableListMap() {
return entityClassToGenuineVariableListMap;
}
public void setEntityClassToGenuineVariableListMap(
Map<String, List<String>> entityClassToGenuineVariableListMap) {
this.entityClassToGenuineVariableListMap = entityClassToGenuineVariableListMap;
}
public Map<String, List<String>> getEntityClassToShadowVariableListMap() {
return entityClassToShadowVariableListMap;
}
public void setEntityClassToShadowVariableListMap(
Map<String, List<String>> entityClassToShadowVariableListMap) {
this.entityClassToShadowVariableListMap = entityClassToShadowVariableListMap;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/gizmo/TimefoldGizmoBeanFactory.java | package ai.timefold.solver.quarkus.gizmo;
public interface TimefoldGizmoBeanFactory {
<T> T newInstance(Class<T> clazz);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus/1.26.1/ai/timefold/solver/quarkus/nativeimage/Substitute_ConfigUtils.java | package ai.timefold.solver.quarkus.nativeimage;
import java.util.function.Supplier;
import jakarta.enterprise.inject.spi.CDI;
import ai.timefold.solver.quarkus.gizmo.TimefoldGizmoBeanFactory;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
@TargetClass(className = "ai.timefold.solver.core.config.util.ConfigUtils")
public final class Substitute_ConfigUtils {
@Substitute
public static <T> T newInstance(Supplier<String> ownerDescriptor, String propertyName, Class<T> clazz) {
T out = CDI.current().getBeanManager().createInstance().select(TimefoldGizmoBeanFactory.class)
.get().newInstance(clazz);
if (out != null) {
return out;
} else {
throw new IllegalArgumentException("Impossible state: could not find the " + ownerDescriptor.get() +
"'s " + propertyName + " (" + clazz.getName() + ") generated Gizmo supplier.");
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark/1.26.1/ai/timefold/solver/benchmark | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark/1.26.1/ai/timefold/solver/benchmark/quarkus/TimefoldBenchmarkBeanProvider.java | package ai.timefold.solver.benchmark.quarkus;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Singleton;
import ai.timefold.solver.benchmark.api.PlannerBenchmarkFactory;
import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig;
import io.quarkus.arc.DefaultBean;
public class TimefoldBenchmarkBeanProvider {
@DefaultBean
@Singleton
@Produces
PlannerBenchmarkFactory benchmarkFactory(PlannerBenchmarkConfig plannerBenchmarkConfig) {
return PlannerBenchmarkFactory.create(plannerBenchmarkConfig);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark/1.26.1/ai/timefold/solver/benchmark | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark/1.26.1/ai/timefold/solver/benchmark/quarkus/TimefoldBenchmarkRecorder.java | package ai.timefold.solver.benchmark.quarkus;
import java.io.File;
import java.util.Collections;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig;
import ai.timefold.solver.benchmark.config.SolverBenchmarkConfig;
import ai.timefold.solver.benchmark.quarkus.config.TimefoldBenchmarkRuntimeConfig;
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.TerminationConfig;
import io.quarkus.arc.Arc;
import io.quarkus.runtime.annotations.Recorder;
@Recorder
public class TimefoldBenchmarkRecorder {
public Supplier<PlannerBenchmarkConfig> benchmarkConfigSupplier(PlannerBenchmarkConfig benchmarkConfig,
TimefoldBenchmarkRuntimeConfig timefoldRuntimeConfig) {
return () -> {
var solverConfig =
Arc.container().instance(SolverConfig.class).get();
// If the termination configuration is set and the created benchmark configuration has no configuration item,
// we need to add at least one configuration; otherwise, we will fail to recognize the runtime termination setting.
if (benchmarkConfig != null && benchmarkConfig.getSolverBenchmarkConfigList() == null &&
timefoldRuntimeConfig != null && timefoldRuntimeConfig.termination() != null) {
benchmarkConfig.setSolverBenchmarkConfigList(Collections.singletonList(new SolverBenchmarkConfig()));
}
return updateBenchmarkConfigWithRuntimeProperties(benchmarkConfig, timefoldRuntimeConfig, solverConfig);
};
}
private PlannerBenchmarkConfig updateBenchmarkConfigWithRuntimeProperties(PlannerBenchmarkConfig plannerBenchmarkConfig,
TimefoldBenchmarkRuntimeConfig benchmarkRuntimeConfig,
SolverConfig solverConfig) {
if (plannerBenchmarkConfig == null) { // no benchmarkConfig.xml provided
// Can't do this in processor; SolverConfig is not completed yet (has some runtime properties)
plannerBenchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig);
}
if (benchmarkRuntimeConfig != null && benchmarkRuntimeConfig.resultDirectory() != null) {
plannerBenchmarkConfig.setBenchmarkDirectory(new File(benchmarkRuntimeConfig.resultDirectory()));
}
var inheritedBenchmarkConfig = plannerBenchmarkConfig.getInheritedSolverBenchmarkConfig();
if (plannerBenchmarkConfig.getSolverBenchmarkBluePrintConfigList() != null) {
if (inheritedBenchmarkConfig == null) {
inheritedBenchmarkConfig = new SolverBenchmarkConfig();
plannerBenchmarkConfig.setInheritedSolverBenchmarkConfig(inheritedBenchmarkConfig);
inheritedBenchmarkConfig.setSolverConfig(solverConfig.copyConfig());
}
TerminationConfig inheritedTerminationConfig;
if (inheritedBenchmarkConfig.getSolverConfig().getTerminationConfig() != null) {
inheritedTerminationConfig = inheritedBenchmarkConfig.getSolverConfig().getTerminationConfig();
} else {
inheritedTerminationConfig = new TerminationConfig();
inheritedBenchmarkConfig.getSolverConfig().setTerminationConfig(inheritedTerminationConfig);
}
if (benchmarkRuntimeConfig != null && benchmarkRuntimeConfig.termination() != null) {
benchmarkRuntimeConfig.termination().spentLimit().ifPresent(inheritedTerminationConfig::setSpentLimit);
benchmarkRuntimeConfig.termination().unimprovedSpentLimit()
.ifPresent(inheritedTerminationConfig::setUnimprovedSpentLimit);
benchmarkRuntimeConfig.termination().bestScoreLimit().ifPresent(inheritedTerminationConfig::setBestScoreLimit);
}
}
TerminationConfig inheritedTerminationConfig = null;
if (inheritedBenchmarkConfig != null && inheritedBenchmarkConfig.getSolverConfig() != null &&
inheritedBenchmarkConfig.getSolverConfig().getTerminationConfig() != null) {
inheritedTerminationConfig = inheritedBenchmarkConfig.getSolverConfig().getTerminationConfig();
}
if (inheritedTerminationConfig == null || !inheritedTerminationConfig.isConfigured()) {
var solverBenchmarkConfigList = plannerBenchmarkConfig.getSolverBenchmarkConfigList();
if (solverBenchmarkConfigList == null) {
throw new IllegalStateException("At least one of the properties " +
"quarkus.timefold.benchmark.solver.termination.spent-limit, " +
"quarkus.timefold.benchmark.solver.termination.best-score-limit, " +
"quarkus.timefold.benchmark.solver.termination.unimproved-spent-limit " +
"is required if termination is not configured in the " +
"inherited solver benchmark config and solverBenchmarkBluePrint is used.");
}
for (var solverBenchmarkConfig : solverBenchmarkConfigList) {
var solverConfig_ = Objects.requireNonNullElseGet(solverBenchmarkConfig.getSolverConfig(), SolverConfig::new);
solverBenchmarkConfig.setSolverConfig(solverConfig_); // In case it was null before.
var terminationConfig = solverConfig_.getTerminationConfig();
if (terminationConfig == null) {
terminationConfig = new TerminationConfig();
solverConfig_.setTerminationConfig(terminationConfig);
} else if (terminationConfig.isConfigured()) {
continue;
}
if (benchmarkRuntimeConfig != null && benchmarkRuntimeConfig.termination() != null) {
benchmarkRuntimeConfig.termination().spentLimit().ifPresent(terminationConfig::setSpentLimit);
benchmarkRuntimeConfig.termination().unimprovedSpentLimit()
.ifPresent(terminationConfig::setUnimprovedSpentLimit);
benchmarkRuntimeConfig.termination().bestScoreLimit().ifPresent(terminationConfig::setBestScoreLimit);
}
if (!terminationConfig.isConfigured() && !solverConfig_.canTerminate()) {
throw new IllegalStateException("At least one of the solver benchmarks is not configured to terminate. " +
"At least one of the properties " +
"quarkus.timefold.benchmark.solver.termination.spent-limit, " +
"quarkus.timefold.benchmark.solver.termination.best-score-limit, " +
"quarkus.timefold.benchmark.solver.termination.unimproved-spent-limit " +
"is required if termination is not configured in a solver benchmark and the " +
"inherited solver benchmark config.");
}
}
}
if (plannerBenchmarkConfig.getSolverBenchmarkConfigList() != null) {
for (var childBenchmarkConfig : plannerBenchmarkConfig.getSolverBenchmarkConfigList()) {
if (childBenchmarkConfig.getSolverConfig() == null) {
childBenchmarkConfig.setSolverConfig(new SolverConfig());
}
inheritPropertiesFromSolverConfig(childBenchmarkConfig, inheritedBenchmarkConfig, solverConfig);
}
}
if (plannerBenchmarkConfig.getSolverBenchmarkConfigList() == null
&& plannerBenchmarkConfig.getSolverBenchmarkBluePrintConfigList() == null) {
plannerBenchmarkConfig.setSolverBenchmarkConfigList(Collections.singletonList(new SolverBenchmarkConfig()));
}
return plannerBenchmarkConfig;
}
private void inheritPropertiesFromSolverConfig(SolverBenchmarkConfig childBenchmarkConfig,
SolverBenchmarkConfig inheritedBenchmarkConfig,
SolverConfig solverConfig) {
inheritProperty(childBenchmarkConfig, inheritedBenchmarkConfig, solverConfig,
SolverConfig::getSolutionClass, SolverConfig::setSolutionClass);
inheritProperty(childBenchmarkConfig, inheritedBenchmarkConfig, solverConfig,
SolverConfig::getEntityClassList, SolverConfig::setEntityClassList);
inheritScoreCalculation(childBenchmarkConfig, inheritedBenchmarkConfig, solverConfig);
}
private <T> void inheritProperty(SolverBenchmarkConfig childBenchmarkConfig,
SolverBenchmarkConfig inheritedBenchmarkConfig,
SolverConfig solverConfig,
Function<SolverConfig, T> getter,
BiConsumer<SolverConfig, T> setter) {
if (getter.apply(childBenchmarkConfig.getSolverConfig()) != null) {
return;
}
if (inheritedBenchmarkConfig != null && inheritedBenchmarkConfig.getSolverConfig() != null &&
getter.apply(inheritedBenchmarkConfig.getSolverConfig()) != null) {
return;
}
setter.accept(childBenchmarkConfig.getSolverConfig(), getter.apply(solverConfig));
}
private void inheritScoreCalculation(SolverBenchmarkConfig childBenchmarkConfig,
SolverBenchmarkConfig inheritedBenchmarkConfig,
SolverConfig solverConfig) {
if (isScoreCalculationDefined(childBenchmarkConfig.getSolverConfig())) {
return;
}
if (inheritedBenchmarkConfig != null && inheritedBenchmarkConfig.getSolverConfig() != null &&
isScoreCalculationDefined(inheritedBenchmarkConfig.getSolverConfig())) {
return;
}
var childScoreDirectorFactoryConfig = Objects.requireNonNull(childBenchmarkConfig.getSolverConfig())
.getScoreDirectorFactoryConfig();
var inheritedScoreDirectorFactoryConfig = Objects.requireNonNull(solverConfig.getScoreDirectorFactoryConfig());
if (childScoreDirectorFactoryConfig == null) {
childScoreDirectorFactoryConfig = new ScoreDirectorFactoryConfig();
Objects.requireNonNull(childBenchmarkConfig.getSolverConfig())
.setScoreDirectorFactoryConfig(childScoreDirectorFactoryConfig);
}
childScoreDirectorFactoryConfig.inherit(inheritedScoreDirectorFactoryConfig);
}
private boolean isScoreCalculationDefined(SolverConfig solverConfig) {
if (solverConfig == null) {
return false;
}
var scoreDirectorFactoryConfig = solverConfig.getScoreDirectorFactoryConfig();
if (scoreDirectorFactoryConfig == null) {
return false;
}
return scoreDirectorFactoryConfig.getEasyScoreCalculatorClass() != null ||
scoreDirectorFactoryConfig.getIncrementalScoreCalculatorClass() != null ||
scoreDirectorFactoryConfig.getConstraintProviderClass() != null;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark/1.26.1/ai/timefold/solver/benchmark | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark/1.26.1/ai/timefold/solver/benchmark/quarkus/UnavailableTimefoldBenchmarkBeanProvider.java | package ai.timefold.solver.benchmark.quarkus;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Singleton;
import ai.timefold.solver.benchmark.api.PlannerBenchmarkFactory;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import io.quarkus.arc.DefaultBean;
public class UnavailableTimefoldBenchmarkBeanProvider {
@DefaultBean
@Singleton
@Produces
PlannerBenchmarkFactory benchmarkFactory() {
throw new IllegalStateException("The " + PlannerBenchmarkFactory.class.getName() + " is not available as there are no @"
+ PlanningSolution.class.getSimpleName() + " or @" + PlanningEntity.class.getSimpleName()
+ " annotated classes."
+ "\nIf your domain classes are located in a dependency of this project, maybe try generating"
+ " the Jandex index by using the jandex-maven-plugin in that dependency, or by adding"
+ "application.properties entries (quarkus.index-dependency.<name>.group-id"
+ " and quarkus.index-dependency.<name>.artifact-id).");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark/1.26.1/ai/timefold/solver/benchmark/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark/1.26.1/ai/timefold/solver/benchmark/quarkus/config/TimefoldBenchmarkRuntimeConfig.java | package ai.timefold.solver.benchmark.quarkus.config;
import ai.timefold.solver.quarkus.config.TerminationRuntimeConfig;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.WithDefault;
import io.smallrye.config.WithName;
@ConfigMapping(prefix = "quarkus.timefold.benchmark")
@ConfigRoot(phase = ConfigPhase.RUN_TIME)
public interface TimefoldBenchmarkRuntimeConfig {
String DEFAULT_BENCHMARK_RESULT_DIRECTORY = "target/benchmarks";
/**
* Where the benchmark results are written to. Defaults to
* {@link #DEFAULT_BENCHMARK_RESULT_DIRECTORY}.
*/
@WithDefault(DEFAULT_BENCHMARK_RESULT_DIRECTORY)
String resultDirectory();
/**
* Termination configuration for the solvers run in the benchmark.
*/
@WithName("solver.termination")
TerminationRuntimeConfig termination();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-deployment/1.26.1/ai/timefold/solver/benchmark/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-deployment/1.26.1/ai/timefold/solver/benchmark/quarkus/deployment/BenchmarkConfigBuildItem.java | package ai.timefold.solver.benchmark.quarkus.deployment;
import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig;
import io.quarkus.builder.item.SimpleBuildItem;
public final class BenchmarkConfigBuildItem extends SimpleBuildItem {
private final PlannerBenchmarkConfig benchmarkConfig;
public BenchmarkConfigBuildItem(PlannerBenchmarkConfig benchmarkConfig) {
this.benchmarkConfig = benchmarkConfig;
}
public PlannerBenchmarkConfig getBenchmarkConfig() {
return benchmarkConfig;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-deployment/1.26.1/ai/timefold/solver/benchmark/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-deployment/1.26.1/ai/timefold/solver/benchmark/quarkus/deployment/TimefoldBenchmarkBuildTimeConfig.java | package ai.timefold.solver.benchmark.quarkus.deployment;
import java.util.Optional;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;
import io.smallrye.config.ConfigMapping;
/**
* During build time, this is translated into Timefold's Config classes.
*/
@ConfigMapping(prefix = "quarkus.timefold.benchmark")
@ConfigRoot(phase = ConfigPhase.BUILD_TIME)
public interface TimefoldBenchmarkBuildTimeConfig {
String DEFAULT_SOLVER_BENCHMARK_CONFIG_URL = "solverBenchmarkConfig.xml";
/**
* A classpath resource to read the benchmark configuration XML.
* Defaults to {@value DEFAULT_SOLVER_BENCHMARK_CONFIG_URL}.
* If this property isn't specified, that solverBenchmarkConfig.xml is optional.
*/
Optional<String> solverBenchmarkConfigXml();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-deployment/1.26.1/ai/timefold/solver/benchmark/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-deployment/1.26.1/ai/timefold/solver/benchmark/quarkus/deployment/TimefoldBenchmarkProcessor$$accessor.java | package ai.timefold.solver.benchmark.quarkus.deployment;
@io.quarkus.Generated("Quarkus annotation processor")
public final class TimefoldBenchmarkProcessor$$accessor {
private TimefoldBenchmarkProcessor$$accessor() {}
@SuppressWarnings("unchecked")
public static Object get_timefoldBenchmarkBuildTimeConfig(Object __instance) {
return ((TimefoldBenchmarkProcessor)__instance).timefoldBenchmarkBuildTimeConfig;
}
@SuppressWarnings("unchecked")
public static void set_timefoldBenchmarkBuildTimeConfig(Object __instance, Object timefoldBenchmarkBuildTimeConfig) {
((TimefoldBenchmarkProcessor)__instance).timefoldBenchmarkBuildTimeConfig = (TimefoldBenchmarkBuildTimeConfig)timefoldBenchmarkBuildTimeConfig;
}
public static Object construct() {
return new TimefoldBenchmarkProcessor();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-deployment/1.26.1/ai/timefold/solver/benchmark/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-deployment/1.26.1/ai/timefold/solver/benchmark/quarkus/deployment/TimefoldBenchmarkProcessor.java | package ai.timefold.solver.benchmark.quarkus.deployment;
import java.util.Optional;
import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig;
import ai.timefold.solver.benchmark.quarkus.TimefoldBenchmarkBeanProvider;
import ai.timefold.solver.benchmark.quarkus.TimefoldBenchmarkRecorder;
import ai.timefold.solver.benchmark.quarkus.UnavailableTimefoldBenchmarkBeanProvider;
import ai.timefold.solver.benchmark.quarkus.config.TimefoldBenchmarkRuntimeConfig;
import ai.timefold.solver.core.config.solver.SolverConfig;
import ai.timefold.solver.quarkus.deployment.SolverConfigBuildItem;
import org.jboss.logging.Logger;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.arc.deployment.SyntheticBeanBuildItem;
import io.quarkus.arc.deployment.UnremovableBeanBuildItem;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.HotDeploymentWatchedFileBuildItem;
import io.quarkus.runtime.configuration.ConfigurationException;
class TimefoldBenchmarkProcessor {
private static final Logger log = Logger.getLogger(TimefoldBenchmarkProcessor.class.getName());
TimefoldBenchmarkBuildTimeConfig timefoldBenchmarkBuildTimeConfig;
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem("timefold-solver-benchmark");
}
@BuildStep
HotDeploymentWatchedFileBuildItem watchSolverBenchmarkConfigXml() {
String solverBenchmarkConfigXML = timefoldBenchmarkBuildTimeConfig.solverBenchmarkConfigXml()
.orElse(TimefoldBenchmarkBuildTimeConfig.DEFAULT_SOLVER_BENCHMARK_CONFIG_URL);
return new HotDeploymentWatchedFileBuildItem(solverBenchmarkConfigXML);
}
@BuildStep
BenchmarkConfigBuildItem registerAdditionalBeans(BuildProducer<AdditionalBeanBuildItem> additionalBeans,
BuildProducer<UnremovableBeanBuildItem> unremovableBeans,
SolverConfigBuildItem solverConfigBuildItem) {
// We don't support benchmarking for multiple solvers
if (solverConfigBuildItem.getSolverConfigMap().size() > 1) {
throw new ConfigurationException("""
When defining multiple solvers, the benchmark feature is not enabled.
Consider using separate <solverBenchmark> instances for evaluating different solver configurations.""");
}
if (solverConfigBuildItem.getGeneratedGizmoClasses() == null) {
log.warn("Skipping Timefold Benchmark extension because the Timefold extension was skipped.");
additionalBeans.produce(new AdditionalBeanBuildItem(UnavailableTimefoldBenchmarkBeanProvider.class));
return new BenchmarkConfigBuildItem(null);
}
PlannerBenchmarkConfig benchmarkConfig;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Optional<String> benchmarkConfigFile = timefoldBenchmarkBuildTimeConfig.solverBenchmarkConfigXml();
if (benchmarkConfigFile.isPresent()) {
String solverBenchmarkConfigXML = benchmarkConfigFile.get();
if (classLoader.getResource(solverBenchmarkConfigXML) == null) {
throw new ConfigurationException("Invalid quarkus.timefold.benchmark.solver-benchmark-config-xml property ("
+ solverBenchmarkConfigXML + "): that classpath resource does not exist.");
}
benchmarkConfig = PlannerBenchmarkConfig.createFromXmlResource(solverBenchmarkConfigXML);
} else if (classLoader.getResource(TimefoldBenchmarkBuildTimeConfig.DEFAULT_SOLVER_BENCHMARK_CONFIG_URL) != null) {
benchmarkConfig = PlannerBenchmarkConfig.createFromXmlResource(
TimefoldBenchmarkBuildTimeConfig.DEFAULT_SOLVER_BENCHMARK_CONFIG_URL);
} else {
benchmarkConfig = null;
}
additionalBeans.produce(new AdditionalBeanBuildItem(TimefoldBenchmarkBeanProvider.class));
unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(TimefoldBenchmarkRuntimeConfig.class));
unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(SolverConfig.class));
return new BenchmarkConfigBuildItem(benchmarkConfig);
}
@BuildStep
@Record(ExecutionTime.RUNTIME_INIT)
void registerRuntimeBeans(TimefoldBenchmarkRecorder recorder, BuildProducer<SyntheticBeanBuildItem> syntheticBeans,
SolverConfigBuildItem solverConfigBuildItem, BenchmarkConfigBuildItem benchmarkConfigBuildItem,
TimefoldBenchmarkRuntimeConfig runtimeConfig) {
if (solverConfigBuildItem.getGeneratedGizmoClasses() == null) {
return;
}
syntheticBeans.produce(SyntheticBeanBuildItem.configure(PlannerBenchmarkConfig.class)
.supplier(recorder.benchmarkConfigSupplier(benchmarkConfigBuildItem.getBenchmarkConfig(), runtimeConfig))
.setRuntimeInit()
.done());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-integration-test/1.26.1/ai/timefold/solver/quarkus/benchmark | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-integration-test/1.26.1/ai/timefold/solver/quarkus/benchmark/it/TimefoldBenchmarkTestResource.java | package ai.timefold.solver.quarkus.benchmark.it;
import java.util.List;
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.benchmark.api.PlannerBenchmark;
import ai.timefold.solver.benchmark.api.PlannerBenchmarkException;
import ai.timefold.solver.benchmark.api.PlannerBenchmarkFactory;
import ai.timefold.solver.benchmark.impl.DefaultPlannerBenchmark;
import ai.timefold.solver.quarkus.benchmark.it.domain.TestdataListValueShadowEntity;
import ai.timefold.solver.quarkus.benchmark.it.domain.TestdataStringLengthShadowEntity;
import ai.timefold.solver.quarkus.benchmark.it.domain.TestdataStringLengthShadowSolution;
@Path("/timefold/test")
public class TimefoldBenchmarkTestResource {
private final PlannerBenchmarkFactory benchmarkFactory;
@Inject
public TimefoldBenchmarkTestResource(PlannerBenchmarkFactory benchmarkFactory) {
this.benchmarkFactory = benchmarkFactory;
}
@POST
@Path("/benchmark")
@Produces(MediaType.TEXT_PLAIN)
public String benchmark() {
TestdataStringLengthShadowSolution planningProblem = new TestdataStringLengthShadowSolution();
planningProblem.setEntityList(List.of(
new TestdataStringLengthShadowEntity(1L),
new TestdataStringLengthShadowEntity(2L)));
planningProblem.setValueList(List.of(new TestdataListValueShadowEntity("a"), new TestdataListValueShadowEntity("bb"),
new TestdataListValueShadowEntity("ccc")));
PlannerBenchmark benchmark = benchmarkFactory.buildPlannerBenchmark(planningProblem);
try {
return benchmark.benchmark().toPath().toAbsolutePath().toString();
} catch (PlannerBenchmarkException e) {
// ignore the exception
return ((DefaultPlannerBenchmark) benchmark).getBenchmarkDirectory().getAbsolutePath();
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-integration-test/1.26.1/ai/timefold/solver/quarkus/benchmark/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-integration-test/1.26.1/ai/timefold/solver/quarkus/benchmark/it/domain/StringLengthVariableListener.java | package ai.timefold.solver.quarkus.benchmark.it.domain;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import org.jspecify.annotations.NonNull;
public class StringLengthVariableListener
implements VariableListener<TestdataStringLengthShadowSolution, TestdataListValueShadowEntity> {
@Override
public void beforeEntityAdded(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataListValueShadowEntity entity) {
/* Nothing to do */
}
@Override
public void afterEntityAdded(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataListValueShadowEntity entity) {
/* Nothing to do */
}
@Override
public void beforeVariableChanged(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataListValueShadowEntity entity) {
/* Nothing to do */
}
@Override
public void afterVariableChanged(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataListValueShadowEntity entity) {
int oldLength = (entity.getLength() != null) ? entity.getLength() : 0;
int newLength =
entity.getEntity() != null
? entity.getEntity().getValues().stream().map(TestdataListValueShadowEntity::getValue)
.mapToInt(StringLengthVariableListener::getLength).sum()
: 0;
if (oldLength != newLength) {
scoreDirector.beforeVariableChanged(entity, "length");
entity.setLength(newLength);
scoreDirector.afterVariableChanged(entity, "length");
}
}
@Override
public void beforeEntityRemoved(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataListValueShadowEntity entity) {
/* Nothing to do */
}
@Override
public void afterEntityRemoved(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataListValueShadowEntity entity) {
/* Nothing to do */
}
private static int getLength(String value) {
if (value != null) {
return value.length();
} else {
return 0;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-integration-test/1.26.1/ai/timefold/solver/quarkus/benchmark/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-integration-test/1.26.1/ai/timefold/solver/quarkus/benchmark/it/domain/TestdataListValueShadowEntity.java | package ai.timefold.solver.quarkus.benchmark.it.domain;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
@PlanningEntity
public class TestdataListValueShadowEntity {
private String value;
@InverseRelationShadowVariable(sourceVariableName = "values")
private TestdataStringLengthShadowEntity entity;
@ShadowVariable(variableListenerClass = StringLengthVariableListener.class, sourceVariableName = "entity")
private Integer length;
public TestdataListValueShadowEntity() {
}
public TestdataListValueShadowEntity(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public TestdataStringLengthShadowEntity getEntity() {
return entity;
}
public void setEntity(TestdataStringLengthShadowEntity entity) {
this.entity = entity;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-integration-test/1.26.1/ai/timefold/solver/quarkus/benchmark/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-integration-test/1.26.1/ai/timefold/solver/quarkus/benchmark/it/domain/TestdataStringLengthShadowEntity.java | package ai.timefold.solver.quarkus.benchmark.it.domain;
import java.util.ArrayList;
import java.util.List;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.lookup.PlanningId;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
@PlanningEntity
public class TestdataStringLengthShadowEntity {
@PlanningId
private Long id;
@PlanningListVariable
private List<TestdataListValueShadowEntity> values;
public TestdataStringLengthShadowEntity() {
}
public TestdataStringLengthShadowEntity(Long id) {
this.id = id;
this.values = new ArrayList<>();
}
// ************************************************************************
// Getters/setters
// ************************************************************************
public Long getId() {
return id;
}
public List<TestdataListValueShadowEntity> getValues() {
return values;
}
public void setValues(List<TestdataListValueShadowEntity> values) {
this.values = values;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-integration-test/1.26.1/ai/timefold/solver/quarkus/benchmark/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-integration-test/1.26.1/ai/timefold/solver/quarkus/benchmark/it/domain/TestdataStringLengthShadowSolution.java | package ai.timefold.solver.quarkus.benchmark.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.hardsoft.HardSoftScore;
@PlanningSolution
public class TestdataStringLengthShadowSolution {
@PlanningEntityCollectionProperty
@ValueRangeProvider
private List<TestdataListValueShadowEntity> valueList;
@PlanningEntityCollectionProperty
private List<TestdataStringLengthShadowEntity> entityList;
@PlanningScore
private HardSoftScore score;
// ************************************************************************
// Getters/setters
// ************************************************************************
public List<TestdataListValueShadowEntity> getValueList() {
return valueList;
}
public void setValueList(List<TestdataListValueShadowEntity> valueList) {
this.valueList = valueList;
}
public List<TestdataStringLengthShadowEntity> getEntityList() {
return entityList;
}
public void setEntityList(List<TestdataStringLengthShadowEntity> 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-benchmark-integration-test/1.26.1/ai/timefold/solver/quarkus/benchmark/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-benchmark-integration-test/1.26.1/ai/timefold/solver/quarkus/benchmark/it/solver/TestdataStringLengthConstraintProvider.java | package ai.timefold.solver.quarkus.benchmark.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.quarkus.benchmark.it.domain.TestdataListValueShadowEntity;
import ai.timefold.solver.quarkus.benchmark.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.forEachUniquePair(TestdataStringLengthShadowEntity.class)
.filter((a, b) -> a.getValues().stream().anyMatch(v -> b.getValues().contains(v)))
.penalize(HardSoftScore.ONE_HARD)
.asConstraint("Don't assign 2 entities the same value."),
factory.forEach(TestdataListValueShadowEntity.class)
.reward(HardSoftScore.ONE_SOFT, a -> a.getLength())
.asConstraint("Maximize value length")
};
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment/DetermineIfNativeBuildItem.java | package ai.timefold.solver.quarkus.deployment;
import io.quarkus.builder.item.SimpleBuildItem;
public final class DetermineIfNativeBuildItem extends SimpleBuildItem {
private final boolean isNative;
public DetermineIfNativeBuildItem(boolean isNative) {
this.isNative = isNative;
}
public boolean isNative() {
return isNative;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment/DotNames.java | package ai.timefold.solver.quarkus.deployment;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import jakarta.inject.Named;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfigurationProvider;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintWeight;
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.entity.PlanningPinToIndex;
import ai.timefold.solver.core.api.domain.lookup.PlanningId;
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.PlanningEntityProperty;
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.solution.ProblemFactCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.ProblemFactProperty;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
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.PlanningVariableReference;
import ai.timefold.solver.core.api.domain.variable.PreviousElementShadowVariable;
import ai.timefold.solver.core.api.domain.variable.ShadowSources;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
import ai.timefold.solver.core.api.domain.variable.ShadowVariablesInconsistent;
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.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 org.jboss.jandex.DotName;
public final class DotNames {
// Jakarta classes
static final DotName NAMED = DotName.createSimple(Named.class);
// Timefold classes
static final DotName PLANNING_SOLUTION = DotName.createSimple(PlanningSolution.class.getName());
static final DotName PLANNING_ENTITY_COLLECTION_PROPERTY =
DotName.createSimple(PlanningEntityCollectionProperty.class.getName());
static final DotName PLANNING_ENTITY_PROPERTY = DotName.createSimple(PlanningEntityProperty.class.getName());
static final DotName PLANNING_SCORE = DotName.createSimple(PlanningScore.class.getName());
static final DotName PROBLEM_FACT_COLLECTION_PROPERTY = DotName.createSimple(ProblemFactCollectionProperty.class.getName());
static final DotName PROBLEM_FACT_PROPERTY = DotName.createSimple(ProblemFactProperty.class.getName());
static final DotName EASY_SCORE_CALCULATOR = DotName.createSimple(EasyScoreCalculator.class.getName());
static final DotName CONSTRAINT_PROVIDER = DotName.createSimple(ConstraintProvider.class.getName());
static final DotName INCREMENTAL_SCORE_CALCULATOR =
DotName.createSimple(IncrementalScoreCalculator.class.getName());
static final DotName CONSTRAINT_CONFIGURATION_PROVIDER =
DotName.createSimple(ConstraintConfigurationProvider.class.getName());
static final DotName CONSTRAINT_WEIGHT = DotName.createSimple(ConstraintWeight.class.getName());
static final DotName CONSTRAINT_WEIGHT_OVERRIDES = DotName.createSimple(ConstraintWeightOverrides.class.getName());
static final DotName PLANNING_ENTITY = DotName.createSimple(PlanningEntity.class.getName());
static final DotName PLANNING_PIN = DotName.createSimple(PlanningPin.class.getName());
static final DotName PLANNING_PIN_TO_INDEX = DotName.createSimple(PlanningPinToIndex.class.getName());
static final DotName PLANNING_ID = DotName.createSimple(PlanningId.class.getName());
static final DotName PLANNING_VARIABLE = DotName.createSimple(PlanningVariable.class.getName());
static final DotName PLANNING_LIST_VARIABLE = DotName.createSimple(PlanningListVariable.class.getName());
static final DotName PLANNING_VARIABLE_REFERENCE = DotName.createSimple(PlanningVariableReference.class.getName());
static final DotName VALUE_RANGE_PROVIDER = DotName.createSimple(ValueRangeProvider.class.getName());
static final DotName ANCHOR_SHADOW_VARIABLE = DotName.createSimple(AnchorShadowVariable.class.getName());
static final DotName CUSTOM_SHADOW_VARIABLE = DotName.createSimple(CustomShadowVariable.class.getName());
static final DotName INDEX_SHADOW_VARIABLE = DotName.createSimple(IndexShadowVariable.class.getName());
static final DotName INVERSE_RELATION_SHADOW_VARIABLE = DotName.createSimple(InverseRelationShadowVariable.class.getName());
static final DotName NEXT_ELEMENT_SHADOW_VARIABLE = DotName.createSimple(NextElementShadowVariable.class.getName());
static final DotName PIGGYBACK_SHADOW_VARIABLE = DotName.createSimple(PiggybackShadowVariable.class.getName());
static final DotName PREVIOUS_ELEMENT_SHADOW_VARIABLE = DotName.createSimple(PreviousElementShadowVariable.class.getName());
static final DotName SHADOW_VARIABLE = DotName.createSimple(ShadowVariable.class.getName());
static final DotName SHADOW_VARIABLES_INCONSISTENT = DotName.createSimple(ShadowVariablesInconsistent.class.getName());
static final DotName CASCADING_UPDATE_SHADOW_VARIABLE =
DotName.createSimple(CascadingUpdateShadowVariable.class.getName());
static final DotName SHADOW_SOURCES = DotName.createSimple(ShadowSources.class.getName());
static final DotName SOLVER_CONFIG = DotName.createSimple(SolverConfig.class.getName());
static final DotName SOLVER_MANAGER_CONFIG = DotName.createSimple(SolverManagerConfig.class.getName());
static final DotName SOLVER_FACTORY = DotName.createSimple(SolverFactory.class.getName());
static final DotName SOLVER_MANAGER = DotName.createSimple(SolverManager.class.getName());
// Need to use String since timefold-solver-test is not on the compile classpath
static final DotName CONSTRAINT_VERIFIER =
DotName.createSimple("ai.timefold.solver.test.api.score.stream.ConstraintVerifier");
static final DotName[] PLANNING_ENTITY_FIELD_ANNOTATIONS = {
PLANNING_PIN,
PLANNING_PIN_TO_INDEX,
PLANNING_VARIABLE,
PLANNING_LIST_VARIABLE,
ANCHOR_SHADOW_VARIABLE,
CUSTOM_SHADOW_VARIABLE,
INDEX_SHADOW_VARIABLE,
INVERSE_RELATION_SHADOW_VARIABLE,
NEXT_ELEMENT_SHADOW_VARIABLE,
PIGGYBACK_SHADOW_VARIABLE,
PREVIOUS_ELEMENT_SHADOW_VARIABLE,
SHADOW_VARIABLE,
SHADOW_VARIABLES_INCONSISTENT,
CASCADING_UPDATE_SHADOW_VARIABLE
};
static final DotName[] GIZMO_MEMBER_ACCESSOR_ANNOTATIONS = {
PLANNING_ENTITY_COLLECTION_PROPERTY,
PLANNING_ENTITY_PROPERTY,
PLANNING_SCORE,
PROBLEM_FACT_COLLECTION_PROPERTY,
PROBLEM_FACT_PROPERTY,
CONSTRAINT_CONFIGURATION_PROVIDER,
CONSTRAINT_WEIGHT,
PLANNING_PIN,
PLANNING_PIN_TO_INDEX,
PLANNING_ID,
PLANNING_VARIABLE,
PLANNING_LIST_VARIABLE,
PLANNING_VARIABLE_REFERENCE,
VALUE_RANGE_PROVIDER,
ANCHOR_SHADOW_VARIABLE,
CUSTOM_SHADOW_VARIABLE,
INDEX_SHADOW_VARIABLE,
INVERSE_RELATION_SHADOW_VARIABLE,
NEXT_ELEMENT_SHADOW_VARIABLE,
PIGGYBACK_SHADOW_VARIABLE,
PREVIOUS_ELEMENT_SHADOW_VARIABLE,
SHADOW_VARIABLE,
SHADOW_VARIABLES_INCONSISTENT,
CASCADING_UPDATE_SHADOW_VARIABLE
};
static final Set<DotName> SOLVER_INJECTABLE_TYPES = Set.of(
SOLVER_CONFIG,
SOLVER_MANAGER_CONFIG,
SOLVER_FACTORY,
SOLVER_MANAGER);
public enum BeanDefiningAnnotations {
PLANNING_SCORE(DotNames.PLANNING_SCORE, "scoreDefinitionClass"),
PLANNING_SOLUTION(DotNames.PLANNING_SOLUTION, "solutionCloner"),
PLANNING_ENTITY(DotNames.PLANNING_ENTITY, "pinningFilter", "difficultyComparatorClass",
"difficultyWeightFactoryClass"),
PLANNING_VARIABLE(DotNames.PLANNING_VARIABLE, "strengthComparatorClass",
"strengthWeightFactoryClass"),
CUSTOM_SHADOW_VARIABLE(DotNames.CUSTOM_SHADOW_VARIABLE, "variableListenerClass"),
SHADOW_VARIABLE(DotNames.SHADOW_VARIABLE, "variableListenerClass");
private final DotName annotationDotName;
private final List<String> parameterNames;
BeanDefiningAnnotations(DotName annotationDotName, String... parameterNames) {
this.annotationDotName = annotationDotName;
this.parameterNames = Arrays.asList(parameterNames);
}
public DotName getAnnotationDotName() {
return annotationDotName;
}
public List<String> getParameterNames() {
return parameterNames;
}
}
private DotNames() {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment/GeneratedGizmoClasses.java | package ai.timefold.solver.quarkus.deployment;
import java.util.Set;
public class GeneratedGizmoClasses {
Set<String> generatedGizmoMemberAccessorClassSet;
Set<String> generatedGizmoSolutionClonerClassSet;
public GeneratedGizmoClasses(Set<String> generatedGizmoMemberAccessorClassSet,
Set<String> generatedGizmoSolutionClonerClassSet) {
this.generatedGizmoMemberAccessorClassSet = generatedGizmoMemberAccessorClassSet;
this.generatedGizmoSolutionClonerClassSet = generatedGizmoSolutionClonerClassSet;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment/GizmoMemberAccessorEntityEnhancer.java | package ai.timefold.solver.quarkus.deployment;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.ILOAD;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.PUTFIELD;
import static org.objectweb.asm.Opcodes.RETURN;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import jakarta.enterprise.context.ApplicationScoped;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.common.accessor.gizmo.GizmoMemberAccessorFactory;
import ai.timefold.solver.core.impl.domain.common.accessor.gizmo.GizmoMemberAccessorImplementor;
import ai.timefold.solver.core.impl.domain.common.accessor.gizmo.GizmoMemberDescriptor;
import ai.timefold.solver.core.impl.domain.common.accessor.gizmo.GizmoMemberInfo;
import ai.timefold.solver.core.impl.domain.solution.cloner.gizmo.GizmoCloningUtils;
import ai.timefold.solver.core.impl.domain.solution.cloner.gizmo.GizmoSolutionCloner;
import ai.timefold.solver.core.impl.domain.solution.cloner.gizmo.GizmoSolutionClonerFactory;
import ai.timefold.solver.core.impl.domain.solution.cloner.gizmo.GizmoSolutionClonerImplementor;
import ai.timefold.solver.core.impl.domain.solution.cloner.gizmo.GizmoSolutionOrEntityDescriptor;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.quarkus.gizmo.TimefoldGizmoBeanFactory;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.builditem.BytecodeTransformerBuildItem;
import io.quarkus.deployment.recording.RecorderContext;
import io.quarkus.gizmo.BranchResult;
import io.quarkus.gizmo.BytecodeCreator;
import io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.ClassOutput;
import io.quarkus.gizmo.DescriptorUtils;
import io.quarkus.gizmo.FieldDescriptor;
import io.quarkus.gizmo.Gizmo;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
import io.quarkus.runtime.RuntimeValue;
final class GizmoMemberAccessorEntityEnhancer {
private final Set<Class<?>> visitedClasses = new HashSet<>();
// This keep track of fields we add virtual getters/setters for
private final Set<Field> visitedFields = new HashSet<>();
// This keep track of what fields we made non-final
private final Set<Field> visitedFinalFields = new HashSet<>();
private final Set<MethodInfo> visitedMethods = new HashSet<>();
private static String getVirtualGetterName(boolean isField, String name) {
return "$get$timefold$__" + ((isField) ? "field$__" : "method$__") + name;
}
private static String getVirtualSetterName(boolean isField, String name) {
return "$set$timefold$__" + ((isField) ? "field$__" : "method$__") + name;
}
/**
* Generates the bytecode for the member accessor for the specified field.
* Additionally enhances the class that declares the field with public simple
* getters/setters methods for the field if the field is private.
*
* @param annotationInstance The annotations on the field
* @param classOutput Where to output the bytecode
* @param fieldInfo The field to generate the MemberAccessor for
* @param transformers BuildProducer of BytecodeTransformers
*/
public String generateFieldAccessor(AnnotationInstance annotationInstance, ClassOutput classOutput, FieldInfo fieldInfo,
BuildProducer<BytecodeTransformerBuildItem> transformers) throws ClassNotFoundException, NoSuchFieldException {
Class<?> declaringClass = Class.forName(fieldInfo.declaringClass().name().toString(), false,
Thread.currentThread().getContextClassLoader());
Field fieldMember = declaringClass.getDeclaredField(fieldInfo.name());
GizmoMemberDescriptor member = createMemberDescriptorForField(fieldMember, transformers);
GizmoMemberInfo memberInfo = new GizmoMemberInfo(member, true,
(Class<? extends Annotation>) Class.forName(annotationInstance.name().toString(), false,
Thread.currentThread().getContextClassLoader()));
String generatedClassName = GizmoMemberAccessorFactory.getGeneratedClassName(fieldMember);
GizmoMemberAccessorImplementor.defineAccessorFor(generatedClassName, classOutput, memberInfo);
return generatedClassName;
}
private void addVirtualFieldGetter(Class<?> classInfo, Field fieldInfo,
BuildProducer<BytecodeTransformerBuildItem> transformers) {
if (!visitedFields.contains(fieldInfo)) {
transformers.produce(new BytecodeTransformerBuildItem(classInfo.getName(),
(className, classVisitor) -> new TimefoldFieldEnhancingClassVisitor(classInfo, classVisitor,
fieldInfo)));
visitedFields.add(fieldInfo);
}
}
private void makeFieldNonFinal(Field finalField, BuildProducer<BytecodeTransformerBuildItem> transformers) {
if (visitedFinalFields.contains(finalField)) {
return;
}
transformers.produce(new BytecodeTransformerBuildItem(finalField.getDeclaringClass().getName(),
(className, classVisitor) -> new TimefoldFinalFieldEnhancingClassVisitor(classVisitor, finalField)));
visitedFinalFields.add(finalField);
}
private static String getMemberName(Member member) {
return Objects.requireNonNullElse(ReflectionHelper.getGetterPropertyName(member), member.getName());
}
private static Optional<MethodDescriptor> getSetterDescriptor(ClassInfo classInfo, MethodInfo methodInfo, String name) {
if (methodInfo.name().startsWith("get") || methodInfo.name().startsWith("is")) {
// ex: for methodInfo = Integer getValue(), name = value,
// return void setValue(Integer value)
// i.e. capitalize first letter of name, and take a parameter
// of the getter return type.
return Optional.ofNullable(classInfo.method("set" + name.substring(0, 1)
.toUpperCase(Locale.ROOT) +
name.substring(1),
methodInfo.returnType())).map(MethodDescriptor::of);
} else {
return Optional.empty();
}
}
/**
* Generates the bytecode for the member accessor for the specified method.
* Additionally enhances the class that declares the method with public simple
* read/(optionally write if getter method and setter present) methods for the method
* if the method is private.
*
* @param annotationInstance The annotations on the field
* @param classOutput Where to output the bytecode
* @param classInfo The declaring class for the field
* @param methodInfo The method to generate the MemberAccessor for
* @param transformers BuildProducer of BytecodeTransformers
*/
public String generateMethodAccessor(AnnotationInstance annotationInstance, ClassOutput classOutput,
ClassInfo classInfo, MethodInfo methodInfo, boolean requiredReturnType,
BuildProducer<BytecodeTransformerBuildItem> transformers)
throws ClassNotFoundException, NoSuchMethodException {
Class<?> declaringClass = Class.forName(methodInfo.declaringClass().name().toString(), false,
Thread.currentThread().getContextClassLoader());
Method methodMember = declaringClass.getDeclaredMethod(methodInfo.name());
String generatedClassName = GizmoMemberAccessorFactory.getGeneratedClassName(methodMember);
GizmoMemberDescriptor member;
String name = getMemberName(methodMember);
Optional<MethodDescriptor> setterDescriptor = getSetterDescriptor(classInfo, methodInfo, name);
MethodDescriptor memberDescriptor = MethodDescriptor.of(methodInfo);
if (Modifier.isPublic(methodInfo.flags())) {
member = new GizmoMemberDescriptor(name, memberDescriptor, declaringClass, setterDescriptor.orElse(null));
} else {
setterDescriptor = addVirtualMethodGetter(classInfo, methodInfo, name, setterDescriptor, transformers);
String methodName = getVirtualGetterName(false, name);
MethodDescriptor newMethodDescriptor =
MethodDescriptor.ofMethod(declaringClass, methodName, memberDescriptor.getReturnType());
member = new GizmoMemberDescriptor(name, newMethodDescriptor, memberDescriptor, declaringClass,
setterDescriptor.orElse(null));
}
Class<? extends Annotation> annotationClass = null;
if (requiredReturnType || annotationInstance != null) {
annotationClass = (Class<? extends Annotation>) Class.forName(annotationInstance.name().toString(), false,
Thread.currentThread().getContextClassLoader());
}
GizmoMemberInfo memberInfo = new GizmoMemberInfo(member, requiredReturnType, annotationClass);
GizmoMemberAccessorImplementor.defineAccessorFor(generatedClassName, classOutput, memberInfo);
return generatedClassName;
}
private Optional<MethodDescriptor> addVirtualMethodGetter(ClassInfo classInfo, MethodInfo methodInfo, String name,
Optional<MethodDescriptor> setterDescriptor,
BuildProducer<BytecodeTransformerBuildItem> transformers) {
if (!visitedMethods.contains(methodInfo)) {
transformers.produce(new BytecodeTransformerBuildItem(classInfo.name().toString(),
(className, classVisitor) -> new TimefoldMethodEnhancingClassVisitor(classInfo, classVisitor, methodInfo,
name, setterDescriptor)));
visitedMethods.add(methodInfo);
}
return setterDescriptor.map(md -> MethodDescriptor
.ofMethod(classInfo.name().toString(), getVirtualSetterName(false, name),
md.getReturnType(), md.getParameterTypes()));
}
public String generateSolutionCloner(SolutionDescriptor solutionDescriptor, ClassOutput classOutput,
IndexView indexView, BuildProducer<BytecodeTransformerBuildItem> transformers) {
String generatedClassName = GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor);
try (ClassCreator classCreator = ClassCreator
.builder()
.className(generatedClassName)
.interfaces(GizmoSolutionCloner.class)
.classOutput(classOutput)
.setFinal(true)
.build()) {
Set<Class<?>> solutionSubclassSet =
indexView.getAllKnownSubclasses(DotName.createSimple(solutionDescriptor.getSolutionClass().getName()))
.stream()
.map(classInfo -> {
try {
return Class.forName(classInfo.name().toString(), false,
Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Unable to find class (" + classInfo.name() +
"), which is a known subclass of the solution class (" +
solutionDescriptor.getSolutionClass() + ").", e);
}
}).collect(Collectors.toCollection(LinkedHashSet::new));
solutionSubclassSet.add(solutionDescriptor.getSolutionClass());
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedGizmoSolutionOrEntityDescriptorForClassMap =
new HashMap<>();
for (Class<?> solutionSubclass : solutionSubclassSet) {
getGizmoSolutionOrEntityDescriptorForEntity(solutionDescriptor,
solutionSubclass,
memoizedGizmoSolutionOrEntityDescriptorForClassMap,
transformers);
}
// IDEA gave error on entityClass being a Class...
for (Object entityClass : solutionDescriptor.getEntityClassSet()) {
getGizmoSolutionOrEntityDescriptorForEntity(solutionDescriptor,
(Class<?>) entityClass,
memoizedGizmoSolutionOrEntityDescriptorForClassMap,
transformers);
}
Set<Class<?>> solutionAndEntitySubclassSet = new HashSet<>(solutionSubclassSet);
for (Object entityClassObject : solutionDescriptor.getEntityClassSet()) {
Class<?> entityClass = (Class<?>) entityClassObject;
Collection<ClassInfo> classInfoCollection;
// getAllKnownSubclasses returns an empty collection for interfaces (silent failure); thus:
// for interfaces, we use getAllKnownImplementors; otherwise we use getAllKnownSubclasses
if (entityClass.isInterface()) {
classInfoCollection = indexView.getAllKnownImplementors(DotName.createSimple(entityClass.getName()));
} else {
classInfoCollection = indexView.getAllKnownSubclasses(DotName.createSimple(entityClass.getName()));
}
classInfoCollection.stream().map(classInfo -> {
try {
return Class.forName(classInfo.name().toString(), false,
Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Unable to find class (" + classInfo.name() +
"), which is a known subclass of the entity class (" +
entityClass + ").", e);
}
}).forEach(solutionAndEntitySubclassSet::add);
}
Set<Class<?>> deepClonedClassSet =
GizmoCloningUtils.getDeepClonedClasses(solutionDescriptor, solutionAndEntitySubclassSet);
for (Class<?> deepCloningClass : deepClonedClassSet) {
makeConstructorAccessible(deepCloningClass, transformers);
if (!memoizedGizmoSolutionOrEntityDescriptorForClassMap.containsKey(deepCloningClass)) {
getGizmoSolutionOrEntityDescriptorForEntity(solutionDescriptor,
deepCloningClass,
memoizedGizmoSolutionOrEntityDescriptorForClassMap,
transformers);
}
}
GizmoSolutionClonerImplementor.defineClonerFor(QuarkusGizmoSolutionClonerImplementor::new,
classCreator,
solutionDescriptor, solutionSubclassSet,
memoizedGizmoSolutionOrEntityDescriptorForClassMap, deepClonedClassSet);
}
return generatedClassName;
}
private void makeConstructorAccessible(Class<?> clazz, BuildProducer<BytecodeTransformerBuildItem> transformers) {
try {
if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
return;
}
Constructor<?> constructor = clazz.getDeclaredConstructor();
if (!Modifier.isPublic(constructor.getModifiers()) && !visitedClasses.contains(clazz)) {
transformers.produce(new BytecodeTransformerBuildItem(clazz.getName(),
(className, classVisitor) -> new TimefoldConstructorEnhancingClassVisitor(classVisitor)));
visitedClasses.add(clazz);
}
} catch (NoSuchMethodException e) {
throw new IllegalStateException(
"Class (" + clazz.getName() + ") must have a no-args constructor so it can be constructed by Timefold.");
}
}
private GizmoSolutionOrEntityDescriptor getGizmoSolutionOrEntityDescriptorForEntity(
SolutionDescriptor solutionDescriptor, Class<?> entityClass,
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedMap,
BuildProducer<BytecodeTransformerBuildItem> transformers) {
Map<Field, GizmoMemberDescriptor> solutionFieldToMemberDescriptor = new HashMap<>();
Class<?> currentClass = entityClass;
while (currentClass != null) {
for (Field field : currentClass.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
solutionFieldToMemberDescriptor.put(field, createMemberDescriptorForField(field, transformers));
}
currentClass = currentClass.getSuperclass();
}
GizmoSolutionOrEntityDescriptor out =
new GizmoSolutionOrEntityDescriptor(solutionDescriptor, entityClass, solutionFieldToMemberDescriptor);
memoizedMap.put(entityClass, out);
return out;
}
private GizmoMemberDescriptor createMemberDescriptorForField(Field field,
BuildProducer<BytecodeTransformerBuildItem> transformers) {
if (Modifier.isFinal(field.getModifiers())) {
makeFieldNonFinal(field, transformers);
}
Class<?> declaringClass = field.getDeclaringClass();
FieldDescriptor memberDescriptor = FieldDescriptor.of(field);
String name = field.getName();
// Not being recorded, so can use Type and annotated element directly
if (Modifier.isPublic(field.getModifiers())) {
return new GizmoMemberDescriptor(name, memberDescriptor, declaringClass);
} else {
addVirtualFieldGetter(declaringClass, field, transformers);
String getterName = getVirtualGetterName(true, name);
MethodDescriptor getterDescriptor =
MethodDescriptor.ofMethod(declaringClass.getName(), getterName, field.getType());
String setterName = getVirtualSetterName(true, name);
MethodDescriptor setterDescriptor =
MethodDescriptor.ofMethod(declaringClass.getName(), setterName, "void", field.getType());
return new GizmoMemberDescriptor(name, getterDescriptor, memberDescriptor, declaringClass, setterDescriptor);
}
}
public static Map<String, RuntimeValue<MemberAccessor>> getGeneratedGizmoMemberAccessorMap(RecorderContext recorderContext,
Set<String> generatedMemberAccessorsClassNames) {
Map<String, RuntimeValue<MemberAccessor>> generatedGizmoMemberAccessorNameToInstanceMap = new HashMap<>();
for (String className : generatedMemberAccessorsClassNames) {
generatedGizmoMemberAccessorNameToInstanceMap.put(className, recorderContext.newInstance(className));
}
return generatedGizmoMemberAccessorNameToInstanceMap;
}
public static Map<String, RuntimeValue<SolutionCloner>> getGeneratedSolutionClonerMap(RecorderContext recorderContext,
Set<String> generatedSolutionClonersClassNames) {
Map<String, RuntimeValue<SolutionCloner>> generatedGizmoSolutionClonerNameToInstanceMap = new HashMap<>();
for (String className : generatedSolutionClonersClassNames) {
generatedGizmoSolutionClonerNameToInstanceMap.put(className, recorderContext.newInstance(className));
}
return generatedGizmoSolutionClonerNameToInstanceMap;
}
public String generateGizmoBeanFactory(ClassOutput classOutput, Set<Class<?>> beanClasses,
BuildProducer<BytecodeTransformerBuildItem> transformers) {
String generatedClassName = TimefoldGizmoBeanFactory.class.getName() + "$Implementation";
ClassCreator classCreator = ClassCreator
.builder()
.className(generatedClassName)
.interfaces(TimefoldGizmoBeanFactory.class)
.classOutput(classOutput)
.build();
classCreator.addAnnotation(ApplicationScoped.class);
MethodCreator methodCreator = classCreator.getMethodCreator(MethodDescriptor.ofMethod(TimefoldGizmoBeanFactory.class,
"newInstance", Object.class, Class.class));
ResultHandle query = methodCreator.getMethodParam(0);
BytecodeCreator currentBranch = methodCreator;
for (Class<?> beanClass : beanClasses) {
if (beanClass.isInterface() || Modifier.isAbstract(beanClass.getModifiers())) {
continue;
}
makeConstructorAccessible(beanClass, transformers);
ResultHandle beanClassHandle = currentBranch.loadClass(beanClass);
ResultHandle isTarget = currentBranch.invokeVirtualMethod(
MethodDescriptor.ofMethod(Object.class, "equals", boolean.class, Object.class),
beanClassHandle, query);
BranchResult isQueryBranchResult = currentBranch.ifTrue(isTarget);
BytecodeCreator isQueryBranch = isQueryBranchResult.trueBranch();
ResultHandle beanInstance =
isQueryBranch.newInstance(MethodDescriptor.ofConstructor(beanClass));
isQueryBranch.returnValue(beanInstance);
currentBranch = isQueryBranchResult.falseBranch();
}
currentBranch.returnValue(currentBranch.loadNull());
classCreator.close();
return generatedClassName;
}
private static class TimefoldFinalFieldEnhancingClassVisitor extends ClassVisitor {
final Field finalField;
public TimefoldFinalFieldEnhancingClassVisitor(ClassVisitor outputClassVisitor, Field finalField) {
super(Gizmo.ASM_API_VERSION, outputClassVisitor);
this.finalField = finalField;
}
@Override
public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
if (name.equals(finalField.getName())) {
// x & ~bitFlag = x without bitFlag set
return super.visitField(access & ~Opcodes.ACC_FINAL, name, descriptor, signature, value);
} else {
return super.visitField(access, name, descriptor, signature, value);
}
}
}
private static class TimefoldConstructorEnhancingClassVisitor extends ClassVisitor {
public TimefoldConstructorEnhancingClassVisitor(ClassVisitor outputClassVisitor) {
super(Gizmo.ASM_API_VERSION, outputClassVisitor);
}
@Override
public MethodVisitor visitMethod(
int access,
String name,
String desc,
String signature,
String[] exceptions) {
if (name.equals("<init>")) {
return cv.visitMethod(
ACC_PUBLIC,
name,
desc,
signature,
exceptions);
}
return cv.visitMethod(
access, name, desc, signature, exceptions);
}
}
private static class TimefoldFieldEnhancingClassVisitor extends ClassVisitor {
private final Field fieldInfo;
private final Class<?> clazz;
private final String fieldTypeDescriptor;
public TimefoldFieldEnhancingClassVisitor(Class<?> classInfo, ClassVisitor outputClassVisitor,
Field fieldInfo) {
super(Gizmo.ASM_API_VERSION, outputClassVisitor);
this.fieldInfo = fieldInfo;
clazz = classInfo;
fieldTypeDescriptor = Type.getDescriptor(fieldInfo.getType());
}
@Override
public void visitEnd() {
super.visitEnd();
addGetter(this.cv);
addSetter(this.cv);
}
private void addSetter(ClassVisitor classWriter) {
String methodName = getVirtualSetterName(true, fieldInfo.getName());
MethodVisitor mv;
mv = classWriter.visitMethod(ACC_PUBLIC, methodName, "(" + fieldTypeDescriptor + ")V",
null, null);
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(Type.getType(fieldTypeDescriptor).getOpcode(ILOAD), 1);
mv.visitFieldInsn(PUTFIELD, Type.getInternalName(clazz), fieldInfo.getName(), fieldTypeDescriptor);
mv.visitInsn(RETURN);
mv.visitMaxs(0, 0);
}
private void addGetter(ClassVisitor classWriter) {
String methodName = getVirtualGetterName(true, fieldInfo.getName());
MethodVisitor mv;
mv = classWriter.visitMethod(ACC_PUBLIC, methodName, "()" + fieldTypeDescriptor,
null, null);
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, Type.getInternalName(clazz), fieldInfo.getName(), fieldTypeDescriptor);
mv.visitInsn(Type.getType(fieldTypeDescriptor).getOpcode(IRETURN));
mv.visitMaxs(0, 0);
}
}
private static class TimefoldMethodEnhancingClassVisitor extends ClassVisitor {
private final MethodInfo methodInfo;
private final Class<?> clazz;
private final String returnTypeDescriptor;
private final MethodDescriptor setter;
private final String name;
public TimefoldMethodEnhancingClassVisitor(ClassInfo classInfo, ClassVisitor outputClassVisitor,
MethodInfo methodInfo, String name, Optional<MethodDescriptor> maybeSetter) {
super(Gizmo.ASM_API_VERSION, outputClassVisitor);
this.methodInfo = methodInfo;
this.name = name;
this.setter = maybeSetter.orElse(null);
try {
clazz = Class.forName(classInfo.name().toString(), false, Thread.currentThread().getContextClassLoader());
returnTypeDescriptor = DescriptorUtils.typeToString(methodInfo.returnType());
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
@Override
public void visitEnd() {
super.visitEnd();
addGetter(this.cv);
if (setter != null) {
addSetter(this.cv);
}
}
private void addGetter(ClassVisitor classWriter) {
String methodName = getVirtualGetterName(false, name);
MethodVisitor mv;
mv = classWriter.visitMethod(ACC_PUBLIC, methodName, "()" + returnTypeDescriptor,
null, null);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(clazz), methodInfo.name(),
"()" + returnTypeDescriptor, false);
mv.visitInsn(Type.getType(returnTypeDescriptor).getOpcode(IRETURN));
mv.visitMaxs(0, 0);
}
private void addSetter(ClassVisitor classWriter) {
if (setter == null) {
return;
}
String methodName = getVirtualSetterName(false, name);
MethodVisitor mv;
mv = classWriter.visitMethod(ACC_PUBLIC, methodName, setter.getDescriptor(),
null, null);
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, 1);
mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(clazz), setter.getName(),
setter.getDescriptor(), false);
mv.visitInsn(RETURN);
mv.visitMaxs(0, 0);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment/QuarkusGizmoSolutionClonerImplementor.java | package ai.timefold.solver.quarkus.deployment;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.SortedSet;
import ai.timefold.solver.core.impl.domain.solution.cloner.gizmo.GizmoSolutionCloner;
import ai.timefold.solver.core.impl.domain.solution.cloner.gizmo.GizmoSolutionClonerImplementor;
import ai.timefold.solver.core.impl.domain.solution.cloner.gizmo.GizmoSolutionOrEntityDescriptor;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import io.quarkus.gizmo.BranchResult;
import io.quarkus.gizmo.BytecodeCreator;
import io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
class QuarkusGizmoSolutionClonerImplementor extends GizmoSolutionClonerImplementor {
@Override
protected void createFields(ClassCreator classCreator) {
// do nothing, we don't need a shallow cloner
}
protected void createSetSolutionDescriptor(ClassCreator classCreator, SolutionDescriptor<?> solutionDescriptor) {
// do nothing, we don't need to create a shallow cloner
MethodCreator methodCreator = classCreator.getMethodCreator(
MethodDescriptor.ofMethod(GizmoSolutionCloner.class, "setSolutionDescriptor", void.class,
SolutionDescriptor.class));
methodCreator.returnValue(null);
}
@Override
protected BytecodeCreator createUnknownClassHandler(BytecodeCreator bytecodeCreator,
SolutionDescriptor<?> solutionDescriptor,
Class<?> entityClass,
ResultHandle toClone,
ResultHandle cloneMap) {
// do nothing, since we cannot encounter unknown classes
return bytecodeCreator;
}
@Override
protected void createAbstractDeepCloneHelperMethod(ClassCreator classCreator,
Class<?> entityClass,
SolutionDescriptor<?> solutionDescriptor,
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedSolutionOrEntityDescriptorMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
MethodCreator methodCreator =
classCreator.getMethodCreator(getEntityHelperMethodName(entityClass), entityClass, entityClass, Map.class);
methodCreator.setModifiers(Modifier.STATIC | Modifier.PRIVATE);
GizmoSolutionOrEntityDescriptor entityDescriptor =
memoizedSolutionOrEntityDescriptorMap.computeIfAbsent(entityClass,
(key) -> new GizmoSolutionOrEntityDescriptor(solutionDescriptor, entityClass));
ResultHandle toClone = methodCreator.getMethodParam(0);
ResultHandle cloneMap = methodCreator.getMethodParam(1);
ResultHandle maybeClone = methodCreator.invokeInterfaceMethod(
GET_METHOD, cloneMap, toClone);
BranchResult hasCloneBranchResult = methodCreator.ifNotNull(maybeClone);
BytecodeCreator hasCloneBranch = hasCloneBranchResult.trueBranch();
hasCloneBranch.returnValue(maybeClone);
BytecodeCreator noCloneBranch = hasCloneBranchResult.falseBranch();
ResultHandle errorMessageBuilder = noCloneBranch.newInstance(MethodDescriptor.ofConstructor(StringBuilder.class));
noCloneBranch.invokeVirtualMethod(
MethodDescriptor.ofMethod(StringBuilder.class, "append", StringBuilder.class, String.class),
errorMessageBuilder, noCloneBranch.load("Impossible state: encountered unknown subclass ("));
noCloneBranch.invokeVirtualMethod(
MethodDescriptor.ofMethod(StringBuilder.class, "append", StringBuilder.class, Object.class),
errorMessageBuilder,
noCloneBranch.invokeVirtualMethod(MethodDescriptor.ofMethod(Object.class, "getClass", Class.class),
toClone));
noCloneBranch.invokeVirtualMethod(
MethodDescriptor.ofMethod(StringBuilder.class, "append", StringBuilder.class, String.class),
errorMessageBuilder, noCloneBranch.load(") of (" + entityClass + ") in Quarkus."));
ResultHandle error =
noCloneBranch.newInstance(MethodDescriptor.ofConstructor(IllegalStateException.class, String.class),
noCloneBranch.invokeVirtualMethod(
MethodDescriptor.ofMethod(StringBuilder.class, "toString", String.class),
errorMessageBuilder));
noCloneBranch.throwException(error);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment/SolverConfigBuildItem.java | package ai.timefold.solver.quarkus.deployment;
import java.util.Map;
import ai.timefold.solver.core.config.solver.SolverConfig;
import ai.timefold.solver.quarkus.deployment.config.TimefoldBuildTimeConfig;
import io.quarkus.builder.item.SimpleBuildItem;
public final class SolverConfigBuildItem extends SimpleBuildItem {
private final Map<String, SolverConfig> solverConfigurations;
private final GeneratedGizmoClasses generatedGizmoClasses;
/**
* Constructor for multiple solver configurations.
*/
public SolverConfigBuildItem(Map<String, SolverConfig> solverConfig, GeneratedGizmoClasses generatedGizmoClasses) {
// Defensive copy to avoid changing the map in dependent build items.
this.solverConfigurations = Map.copyOf(solverConfig);
this.generatedGizmoClasses = generatedGizmoClasses;
}
public boolean isDefaultSolverConfig(String solverName) {
return solverConfigurations.size() <= 1 || TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME.equals(solverName);
}
public Map<String, SolverConfig> getSolverConfigMap() {
return solverConfigurations;
}
public GeneratedGizmoClasses getGeneratedGizmoClasses() {
return generatedGizmoClasses;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment/TimefoldProcessor$$accessor.java | package ai.timefold.solver.quarkus.deployment;
@io.quarkus.Generated("Quarkus annotation processor")
public final class TimefoldProcessor$$accessor {
private TimefoldProcessor$$accessor() {}
@SuppressWarnings("unchecked")
public static Object get_timefoldBuildTimeConfig(Object __instance) {
return ((TimefoldProcessor)__instance).timefoldBuildTimeConfig;
}
@SuppressWarnings("unchecked")
public static void set_timefoldBuildTimeConfig(Object __instance, Object timefoldBuildTimeConfig) {
((TimefoldProcessor)__instance).timefoldBuildTimeConfig = (ai.timefold.solver.quarkus.deployment.config.TimefoldBuildTimeConfig)timefoldBuildTimeConfig;
}
public static Object construct() {
return new TimefoldProcessor();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment/TimefoldProcessor.java | package ai.timefold.solver.quarkus.deployment;
import static io.quarkus.deployment.annotations.ExecutionTime.RUNTIME_INIT;
import static java.lang.String.format;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Singleton;
import ai.timefold.solver.core.api.domain.autodiscover.AutoDiscoverMemberType;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
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.solution.ProblemFactCollectionProperty;
import ai.timefold.solver.core.api.domain.variable.ShadowSources;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
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.ConstraintMetaModel;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
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.PreviewFeature;
import ai.timefold.solver.core.config.solver.SolverConfig;
import ai.timefold.solver.core.config.solver.SolverManagerConfig;
import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.variable.declarative.RootVariableSource;
import ai.timefold.solver.core.impl.heuristic.selector.common.nearby.NearbyDistanceMeter;
import ai.timefold.solver.quarkus.TimefoldRecorder;
import ai.timefold.solver.quarkus.bean.BeanUtil;
import ai.timefold.solver.quarkus.bean.DefaultTimefoldBeanProvider;
import ai.timefold.solver.quarkus.bean.TimefoldSolverBannerBean;
import ai.timefold.solver.quarkus.bean.UnavailableTimefoldBeanProvider;
import ai.timefold.solver.quarkus.config.TimefoldRuntimeConfig;
import ai.timefold.solver.quarkus.deployment.api.ConstraintMetaModelBuildItem;
import ai.timefold.solver.quarkus.deployment.config.SolverBuildTimeConfig;
import ai.timefold.solver.quarkus.deployment.config.TimefoldBuildTimeConfig;
import ai.timefold.solver.quarkus.devui.DevUISolverConfig;
import ai.timefold.solver.quarkus.devui.TimefoldDevUIPropertiesRPCService;
import ai.timefold.solver.quarkus.devui.TimefoldDevUIRecorder;
import ai.timefold.solver.quarkus.gizmo.TimefoldGizmoBeanFactory;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.ParameterizedType;
import org.jboss.jandex.Type;
import org.jboss.jandex.TypeVariable;
import org.jboss.logging.Logger;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.arc.deployment.GeneratedBeanBuildItem;
import io.quarkus.arc.deployment.GeneratedBeanGizmoAdaptor;
import io.quarkus.arc.deployment.SyntheticBeanBuildItem;
import io.quarkus.arc.deployment.UnremovableBeanBuildItem;
import io.quarkus.deployment.GeneratedClassGizmoAdaptor;
import io.quarkus.deployment.IsDevelopment;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.BytecodeTransformerBuildItem;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.GeneratedClassBuildItem;
import io.quarkus.deployment.builditem.HotDeploymentWatchedFileBuildItem;
import io.quarkus.deployment.builditem.IndexDependencyBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveHierarchyBuildItem;
import io.quarkus.deployment.pkg.steps.NativeBuild;
import io.quarkus.deployment.recording.RecorderContext;
import io.quarkus.devui.spi.JsonRPCProvidersBuildItem;
import io.quarkus.devui.spi.page.CardPageBuildItem;
import io.quarkus.devui.spi.page.Page;
import io.quarkus.gizmo.ClassOutput;
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.runtime.configuration.ConfigurationException;
class TimefoldProcessor {
private static final Logger log = Logger.getLogger(TimefoldProcessor.class.getName());
TimefoldBuildTimeConfig timefoldBuildTimeConfig;
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem("timefold-solver");
}
@BuildStep
void watchSolverConfigXml(BuildProducer<HotDeploymentWatchedFileBuildItem> hotDeploymentWatchedFiles) {
var solverConfigXML = timefoldBuildTimeConfig.solverConfigXml()
.orElse(TimefoldBuildTimeConfig.DEFAULT_SOLVER_CONFIG_URL);
var solverCongigXmlFileSet = new HashSet<String>();
solverCongigXmlFileSet.add(solverConfigXML);
timefoldBuildTimeConfig.solver().values().stream()
.map(SolverBuildTimeConfig::solverConfigXml)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(solverCongigXmlFileSet::add);
solverCongigXmlFileSet.forEach(file -> hotDeploymentWatchedFiles.produce(new HotDeploymentWatchedFileBuildItem(file)));
}
@BuildStep
IndexDependencyBuildItem indexDependencyBuildItem() {
// Add @PlanningEntity and other annotations in the Jandex index for Gizmo
return new IndexDependencyBuildItem("ai.timefold.solver", "timefold-solver-core");
}
@BuildStep(onlyIf = NativeBuild.class)
void makeGizmoBeanFactoryUnremovable(BuildProducer<UnremovableBeanBuildItem> unremovableBeans) {
unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(TimefoldGizmoBeanFactory.class));
}
@BuildStep(onlyIfNot = NativeBuild.class)
DetermineIfNativeBuildItem ifNotNativeBuild() {
return new DetermineIfNativeBuildItem(false);
}
@BuildStep(onlyIf = NativeBuild.class)
DetermineIfNativeBuildItem ifNativeBuild() {
return new DetermineIfNativeBuildItem(true);
}
@BuildStep(onlyIf = IsDevelopment.class)
public CardPageBuildItem registerDevUICard() {
var cardPageBuildItem = new CardPageBuildItem();
cardPageBuildItem.addPage(Page.webComponentPageBuilder()
.title("Configuration")
.icon("font-awesome-solid:wrench")
.componentLink("config-component.js"));
cardPageBuildItem.addPage(Page.webComponentPageBuilder()
.title("Model")
.icon("font-awesome-solid:wrench")
.componentLink("model-component.js"));
cardPageBuildItem.addPage(Page.webComponentPageBuilder()
.title("Constraints")
.icon("font-awesome-solid:wrench")
.componentLink("constraints-component.js"));
return cardPageBuildItem;
}
@BuildStep(onlyIf = IsDevelopment.class)
public JsonRPCProvidersBuildItem registerRPCService() {
return new JsonRPCProvidersBuildItem("Timefold Solver", TimefoldDevUIPropertiesRPCService.class);
}
/**
* The DevConsole injects the SolverFactory bean programmatically, which is not detected by ArC. As a result,
* the bean is removed as unused unless told otherwise via the {@link UnremovableBeanBuildItem}.
*/
@BuildStep(onlyIf = IsDevelopment.class)
void makeSolverFactoryUnremovableInDevMode(BuildProducer<UnremovableBeanBuildItem> unremovableBeans) {
unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(SolverFactory.class));
}
@BuildStep
SolverConfigBuildItem recordAndRegisterBuildTimeBeans(CombinedIndexBuildItem combinedIndex,
BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchyClass,
BuildProducer<SyntheticBeanBuildItem> syntheticBeanBuildItemBuildProducer,
BuildProducer<AdditionalBeanBuildItem> additionalBeans,
BuildProducer<UnremovableBeanBuildItem> unremovableBeans,
BuildProducer<GeneratedBeanBuildItem> generatedBeans,
BuildProducer<GeneratedClassBuildItem> generatedClasses,
BuildProducer<BytecodeTransformerBuildItem> transformers) {
var indexView = combinedIndex.getIndex();
// Step 0 - determine list of names used for injected solver components
var solverNames = new HashSet<String>();
var solverConfigMap = new HashMap<String, SolverConfig>();
for (var namedItem : indexView.getAnnotations(DotNames.NAMED)) {
var target = namedItem.target();
var type = switch (target.kind()) {
case CLASS -> target.asClass().name();
case FIELD -> target.asField().type().name();
case METHOD_PARAMETER -> target.asMethodParameter().type().name();
case RECORD_COMPONENT -> target.asRecordComponent().type().name();
case TYPE, METHOD -> null;
};
if (type != null && DotNames.SOLVER_INJECTABLE_TYPES.contains(type)) {
var annotationValue = namedItem.value();
var value = (annotationValue != null) ? annotationValue.asString() : "";
solverNames.add(value);
}
}
// Only skip this extension if everything is missing. Otherwise, if some parts are missing, fail fast later.
if (indexView.getAnnotations(DotNames.PLANNING_SOLUTION).isEmpty()
&& indexView.getAnnotations(DotNames.PLANNING_ENTITY).isEmpty()) {
log.warn(
"""
Skipping Timefold extension because there are no @%s or @%s annotated classes.
If your domain classes are located in a dependency of this project, maybe try generating the \
Jandex index by using the jandex-maven-plugin in that dependency, or by addingapplication.properties entries \
(quarkus.index-dependency.<name>.group-id and quarkus.index-dependency.<name>.artifact-id)."""
.formatted(PlanningSolution.class.getSimpleName(), PlanningEntity.class.getSimpleName()));
additionalBeans.produce(new AdditionalBeanBuildItem(UnavailableTimefoldBeanProvider.class));
solverNames.forEach(solverName -> solverConfigMap.put(solverName, null));
return new SolverConfigBuildItem(solverConfigMap, null);
}
// Quarkus extensions must always use getContextClassLoader()
// Internally, Timefold defaults the ClassLoader to getContextClassLoader() too
var classLoader = Thread.currentThread().getContextClassLoader();
TimefoldRecorder.assertNoUnmatchedProperties(solverNames,
timefoldBuildTimeConfig.solver().keySet());
// Step 1 - create all SolverConfig
// If the config map is empty, we build the config using the default solver name
if (solverNames.isEmpty()) {
solverConfigMap.put(TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME,
createSolverConfig(classLoader, TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME));
} else {
// One config per solver mapped name
solverNames.forEach(solverName -> solverConfigMap.put(solverName,
createSolverConfig(classLoader, solverName)));
}
// Step 2 - validate all SolverConfig definitions
assertNoMemberAnnotationWithoutClassAnnotation(indexView);
assertNodeSharingDisabled(solverConfigMap);
assertSolverConfigSolutionClasses(indexView, solverConfigMap);
assertSolverConfigEntityClasses(indexView);
assertSolverConfigConstraintClasses(indexView, solverConfigMap);
// Step 3 - load all additional information per SolverConfig
Set<Class<?>> reflectiveClassSet = new LinkedHashSet<>();
solverConfigMap.forEach((solverName, solverConfig) -> loadSolverConfig(indexView, reflectiveHierarchyClass,
solverConfig, solverName, reflectiveClassSet));
// Register all annotated domain model classes
registerClassesFromAnnotations(indexView, reflectiveClassSet);
// Register only distinct constraint providers
solverConfigMap.values()
.stream()
.filter(config -> config.getScoreDirectorFactoryConfig().getConstraintProviderClass() != null)
.map(config -> config.getScoreDirectorFactoryConfig().getConstraintProviderClass().getName())
.distinct()
.map(constraintName -> solverConfigMap.entrySet().stream().filter(entryConfig -> entryConfig.getValue()
.getScoreDirectorFactoryConfig().getConstraintProviderClass().getName().equals(constraintName))
.findFirst().get())
.forEach(
entryConfig -> generateConstraintVerifier(entryConfig.getValue(), syntheticBeanBuildItemBuildProducer));
GeneratedGizmoClasses generatedGizmoClasses = generateDomainAccessors(solverConfigMap, indexView, generatedBeans,
generatedClasses, transformers, reflectiveClassSet);
additionalBeans.produce(new AdditionalBeanBuildItem(TimefoldSolverBannerBean.class));
if (solverConfigMap.size() <= 1) {
// Only registered for the default solver
additionalBeans.produce(new AdditionalBeanBuildItem(DefaultTimefoldBeanProvider.class));
}
unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(TimefoldRuntimeConfig.class));
return new SolverConfigBuildItem(solverConfigMap, generatedGizmoClasses);
}
private void assertNoMemberAnnotationWithoutClassAnnotation(IndexView indexView) {
Collection<AnnotationInstance> timefoldFieldAnnotationCollection = new HashSet<>();
for (DotName annotationName : DotNames.PLANNING_ENTITY_FIELD_ANNOTATIONS) {
timefoldFieldAnnotationCollection.addAll(indexView.getAnnotationsWithRepeatable(annotationName, indexView));
}
for (AnnotationInstance annotationInstance : timefoldFieldAnnotationCollection) {
var annotationTarget = annotationInstance.target();
ClassInfo declaringClass;
String prefix;
declaringClass = switch (annotationTarget.kind()) {
case FIELD -> {
prefix = "The field (%s)".formatted(annotationTarget.asField().name());
yield annotationTarget.asField().declaringClass();
}
case METHOD -> {
prefix = "The method (%s)".formatted(annotationTarget.asMethod().name());
yield annotationTarget.asMethod().declaringClass();
}
default -> throw new IllegalStateException(
"Member annotation @%s is on (%s), which is an invalid target type (%s) for @%s.".formatted(
annotationInstance.name().withoutPackagePrefix(), annotationTarget, annotationTarget.kind(),
annotationInstance.name().withoutPackagePrefix()));
};
if (!declaringClass.annotationsMap().containsKey(DotNames.PLANNING_ENTITY)) {
throw new IllegalStateException(
"""
%s with a @%s annotation is in a class (%s) that does not have a @%s annotation.
Maybe add a @%s annotation on the class (%s)."""
.formatted(prefix, annotationInstance.name().withoutPackagePrefix(), declaringClass.name(),
PlanningEntity.class.getSimpleName(), PlanningEntity.class.getSimpleName(),
declaringClass.name()));
}
}
}
private void assertSolverConfigSolutionClasses(IndexView indexView, Map<String, SolverConfig> solverConfigMap) {
// Validate the solution class
// No solution class
assertEmptyInstances(indexView, DotNames.PLANNING_SOLUTION);
// Multiple classes and single solver
var annotationInstanceList = getAllConcreteSolutionClasses(indexView);
var firstConfig = solverConfigMap.values().stream().findFirst().orElse(null);
if (annotationInstanceList.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(
convertAnnotationInstancesToString(annotationInstanceList), 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 (annotationInstanceList.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(),
convertAnnotationInstancesToString(annotationInstanceList)));
}
// Unused solution classes
// When inheritance is used, we ignore the parent classes.
var unusedSolutionClassList = annotationInstanceList.stream()
.map(planningClass -> planningClass.target().asClass().name().toString())
.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 (annotationInstanceList.size() > 1 && !unusedSolutionClassList.isEmpty()) {
throw new IllegalStateException(
"Unused classes ([%s]) found with a @%s annotation.".formatted(String.join(", ", unusedSolutionClassList),
PlanningSolution.class.getSimpleName()));
}
}
private void assertNodeSharingDisabled(Map<String, SolverConfig> solverConfigMap) {
for (var entry : solverConfigMap.entrySet()) {
var solverConfig = entry.getValue();
var scoreDirectorFactoryConfig = solverConfig.getScoreDirectorFactoryConfig();
if (scoreDirectorFactoryConfig != null &&
Boolean.TRUE.equals(scoreDirectorFactoryConfig.getConstraintStreamAutomaticNodeSharing())) {
throw new IllegalStateException("""
SolverConfig %s enabled automatic node sharing via SolverConfig, which is not allowed.
Enable automatic node sharing with the property %s instead."""
.formatted(
entry.getKey(),
"quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true"));
}
}
}
private void assertSolverConfigEntityClasses(IndexView indexView) {
// No entity classes
assertEmptyInstances(indexView, DotNames.PLANNING_ENTITY);
}
private void assertSolverConfigConstraintClasses(IndexView indexView, Map<String, SolverConfig> solverConfigMap) {
// We filter out abstract classes
var simpleScoreClassCollection = indexView.getAllKnownImplementations(DotNames.EASY_SCORE_CALCULATOR)
.stream().filter(clazz -> !clazz.isAbstract())
.toList();
var constraintScoreClassCollection =
indexView.getAllKnownImplementations(DotNames.CONSTRAINT_PROVIDER)
.stream().filter(clazz -> !clazz.isAbstract())
.toList();
var incrementalScoreClassCollection =
indexView.getAllKnownImplementations(DotNames.INCREMENTAL_SCORE_CALCULATOR)
.stream().filter(clazz -> !clazz.isAbstract())
.toList();
// No score classes
if (simpleScoreClassCollection.isEmpty() && constraintScoreClassCollection.isEmpty()
&& incrementalScoreClassCollection.isEmpty()) {
throw new IllegalStateException(
"No classes found that implement %s, %s, or %s.".formatted(EasyScoreCalculator.class.getSimpleName(),
ConstraintProvider.class.getSimpleName(), IncrementalScoreCalculator.class.getSimpleName()));
}
// Multiple classes and single solver
var errorMessage = "Multiple score classes classes (%s) that implements %s were found in the classpath.";
if (simpleScoreClassCollection.size() > 1 && solverConfigMap.size() == 1) {
throw new IllegalStateException(errorMessage.formatted(
simpleScoreClassCollection.stream().map(c -> c.name().toString()).collect(Collectors.joining(", ")),
EasyScoreCalculator.class.getSimpleName()));
}
if (constraintScoreClassCollection.size() > 1 && solverConfigMap.size() == 1) {
throw new IllegalStateException(errorMessage.formatted(
constraintScoreClassCollection.stream().map(c -> c.name().toString()).collect(Collectors.joining(", ")),
ConstraintProvider.class.getSimpleName()));
}
if (incrementalScoreClassCollection.size() > 1 && solverConfigMap.size() == 1) {
throw new IllegalStateException(errorMessage.formatted(
incrementalScoreClassCollection.stream().map(c -> c.name().toString()).collect(Collectors.joining(", ")),
IncrementalScoreCalculator.class.getSimpleName()));
}
// Multiple classes and at least one solver config does not specify the score class
errorMessage = """
Some solver configs (%s) don't specify a %s score 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 classes to the XML files,
or remove the unnecessary score classes 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 (simpleScoreClassCollection.size() > 1 && !solverConfigWithoutConstraintClassList.isEmpty()) {
throw new IllegalStateException(errorMessage.formatted(
String.join(", ", solverConfigWithoutConstraintClassList),
EasyScoreCalculator.class.getSimpleName(),
simpleScoreClassCollection.stream().map(c -> c.name().toString()).collect(Collectors.joining(", "))));
}
solverConfigWithoutConstraintClassList = solverConfigMap.entrySet().stream()
.filter(e -> e.getValue().getScoreDirectorFactoryConfig() == null
|| e.getValue().getScoreDirectorFactoryConfig().getConstraintProviderClass() == null)
.map(Map.Entry::getKey)
.toList();
if (constraintScoreClassCollection.size() > 1 && !solverConfigWithoutConstraintClassList.isEmpty()) {
throw new IllegalStateException(errorMessage.formatted(
String.join(", ", solverConfigWithoutConstraintClassList),
ConstraintProvider.class.getSimpleName(),
constraintScoreClassCollection.stream().map(c -> c.name().toString()).collect(Collectors.joining(", "))));
}
solverConfigWithoutConstraintClassList = solverConfigMap.entrySet().stream()
.filter(e -> e.getValue().getScoreDirectorFactoryConfig() == null
|| e.getValue().getScoreDirectorFactoryConfig().getIncrementalScoreCalculatorClass() == null)
.map(Map.Entry::getKey)
.toList();
if (incrementalScoreClassCollection.size() > 1 && !solverConfigWithoutConstraintClassList.isEmpty()) {
throw new IllegalStateException(errorMessage.formatted(
String.join(", ", solverConfigWithoutConstraintClassList),
IncrementalScoreCalculator.class.getSimpleName(),
incrementalScoreClassCollection.stream().map(c -> c.name().toString()).collect(Collectors.joining(", "))));
}
// Unused score classes
var solverConfigWithUnusedSolutionClassList = simpleScoreClassCollection.stream()
.map(clazz -> clazz.name().toString())
.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 (simpleScoreClassCollection.size() > 1 && !solverConfigWithUnusedSolutionClassList.isEmpty()) {
throw new IllegalStateException(errorMessage.formatted(String.join(", ", solverConfigWithUnusedSolutionClassList),
EasyScoreCalculator.class.getSimpleName()));
}
solverConfigWithUnusedSolutionClassList = constraintScoreClassCollection.stream()
.map(clazz -> clazz.name().toString())
.filter(className -> solverConfigMap.values().stream()
.filter(c -> c.getScoreDirectorFactoryConfig() != null
&& c.getScoreDirectorFactoryConfig().getConstraintProviderClass() != null)
.noneMatch(c -> c.getScoreDirectorFactoryConfig().getConstraintProviderClass().getName()
.equals(className)))
.toList();
if (constraintScoreClassCollection.size() > 1 && !solverConfigWithUnusedSolutionClassList.isEmpty()) {
throw new IllegalStateException(errorMessage.formatted(String.join(", ", solverConfigWithUnusedSolutionClassList),
ConstraintProvider.class.getSimpleName()));
}
solverConfigWithUnusedSolutionClassList = incrementalScoreClassCollection.stream()
.map(clazz -> clazz.name().toString())
.filter(className -> solverConfigMap.values().stream()
.filter(c -> c.getScoreDirectorFactoryConfig() != null
&& c.getScoreDirectorFactoryConfig().getIncrementalScoreCalculatorClass() != null)
.noneMatch(c -> c.getScoreDirectorFactoryConfig().getIncrementalScoreCalculatorClass().getName()
.equals(className)))
.toList();
if (incrementalScoreClassCollection.size() > 1 && !solverConfigWithUnusedSolutionClassList.isEmpty()) {
throw new IllegalStateException(errorMessage.formatted(String.join(", ", solverConfigWithUnusedSolutionClassList),
IncrementalScoreCalculator.class.getSimpleName()));
}
}
private void assertEmptyInstances(IndexView indexView, DotName dotName) {
var annotationInstanceCollection = indexView.getAnnotations(dotName);
if (annotationInstanceCollection.isEmpty()) {
try {
throw new IllegalStateException(
"No classes were found with a @%s annotation."
.formatted(Class.forName(dotName.local()).getSimpleName()));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
private SolverConfig createSolverConfig(ClassLoader classLoader, String solverName) {
// 1 - The solver configuration takes precedence over root and default settings
var solverConfigXml = this.timefoldBuildTimeConfig.getSolverConfig(solverName)
.flatMap(SolverBuildTimeConfig::solverConfigXml);
// 2 - Root settings
if (solverConfigXml.isEmpty()) {
solverConfigXml = this.timefoldBuildTimeConfig.solverConfigXml();
}
SolverConfig solverConfig;
if (solverConfigXml.isPresent()) {
String solverUrl = solverConfigXml.get();
if (classLoader.getResource(solverUrl) == null) {
String message =
"Invalid quarkus.timefold.solverConfigXML property (%s): that classpath resource does not exist."
.formatted(solverUrl);
if (!solverName.equals(TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME)) {
message =
"Invalid quarkus.timefold.solver.\"%s\".solverConfigXML property (%s): that classpath resource does not exist."
.formatted(solverName, solverUrl);
}
throw new ConfigurationException(message);
}
solverConfig = SolverConfig.createFromXmlResource(solverUrl);
} else if (classLoader.getResource(TimefoldBuildTimeConfig.DEFAULT_SOLVER_CONFIG_URL) != null) {
// 3 - Default file URL
solverConfig = SolverConfig.createFromXmlResource(
TimefoldBuildTimeConfig.DEFAULT_SOLVER_CONFIG_URL);
} else {
solverConfig = new SolverConfig();
}
return solverConfig;
}
private SolverConfig loadSolverConfig(IndexView indexView,
BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchyClass, SolverConfig solverConfig, String solverName,
Set<Class<?>> reflectiveClassSet) {
// Configure planning problem models and score director per solver
applySolverProperties(indexView, solverName, solverConfig);
var solutionClass = solverConfig.getSolutionClass();
if (solutionClass != null) {
// Need to register even when using GIZMO so annotations are preserved
Type jandexType = Type.create(DotName.createSimple(solutionClass.getName()), Type.Kind.CLASS);
reflectiveHierarchyClass.produce(new ReflectiveHierarchyBuildItem.Builder()
.type(jandexType)
// Ignore only the packages from timefold-solver-core
// (Can cause a hard to diagnose issue when creating a test/example
// in the package "ai.timefold.solver").
.ignoreTypePredicate(
dotName -> ReflectiveHierarchyBuildItem.DefaultIgnoreTypePredicate.INSTANCE.test(dotName)
|| dotName.toString().startsWith("ai.timefold.solver.api")
|| dotName.toString().startsWith("ai.timefold.solver.config")
|| dotName.toString().startsWith("ai.timefold.solver.impl"))
.build());
}
// Register solver's specific custom classes
registerCustomClassesFromSolverConfig(solverConfig, reflectiveClassSet);
return solverConfig;
}
@BuildStep
void buildConstraintMetaModel(SolverConfigBuildItem solverConfigBuildItem,
BuildProducer<ConstraintMetaModelBuildItem> constraintMetaModelBuildItemBuildProducer) {
if (solverConfigBuildItem.getSolverConfigMap().isEmpty()) {
return;
}
var constraintMetaModelsBySolverNames = new HashMap<String, ConstraintMetaModel>();
solverConfigBuildItem.getSolverConfigMap().forEach((solverName, solverConfig) -> {
// Gizmo-generated member accessors are not yet available at build time.
var originalDomainAccessType = solverConfig.getDomainAccessType();
solverConfig.setDomainAccessType(DomainAccessType.REFLECTION);
var solverFactory = SolverFactory.create(solverConfig);
var constraintMetaModel = BeanUtil.buildConstraintMetaModel(solverFactory);
// Avoid changing the original solver config.
solverConfig.setDomainAccessType(originalDomainAccessType);
constraintMetaModelsBySolverNames.put(solverName, constraintMetaModel);
});
constraintMetaModelBuildItemBuildProducer.produce(new ConstraintMetaModelBuildItem(constraintMetaModelsBySolverNames));
}
@BuildStep
@Record(RUNTIME_INIT)
void recordAndRegisterRuntimeBeans(TimefoldRecorder recorder, RecorderContext recorderContext,
BuildProducer<SyntheticBeanBuildItem> syntheticBeanBuildItemBuildProducer,
SolverConfigBuildItem solverConfigBuildItem) {
// Skip this extension if everything is missing.
if (solverConfigBuildItem.getGeneratedGizmoClasses() == null) {
return;
}
recorder.assertNoUnmatchedRuntimeProperties(solverConfigBuildItem.getSolverConfigMap().keySet());
// Using the same name for synthetic beans is impossible, even if they are different types.
// Therefore, we allow only the injection of SolverManager, except for the default solver,
// which can inject all resources to be retro-compatible.
solverConfigBuildItem.getSolverConfigMap().forEach((key, value) -> {
if (solverConfigBuildItem.isDefaultSolverConfig(key)) {
// The two configuration resources are required for DefaultTimefoldBeanProvider
// to produce all available managed beans for the default solver.
syntheticBeanBuildItemBuildProducer.produce(SyntheticBeanBuildItem.configure(SolverConfig.class)
.scope(Singleton.class)
.supplier(recorder.solverConfigSupplier(key, value,
GizmoMemberAccessorEntityEnhancer.getGeneratedGizmoMemberAccessorMap(recorderContext,
solverConfigBuildItem
.getGeneratedGizmoClasses().generatedGizmoMemberAccessorClassSet),
GizmoMemberAccessorEntityEnhancer.getGeneratedSolutionClonerMap(recorderContext,
solverConfigBuildItem
.getGeneratedGizmoClasses().generatedGizmoSolutionClonerClassSet)))
.setRuntimeInit()
.defaultBean()
.done());
var solverManagerConfig = new SolverManagerConfig();
syntheticBeanBuildItemBuildProducer.produce(SyntheticBeanBuildItem.configure(SolverManagerConfig.class)
.scope(Singleton.class)
.supplier(recorder.solverManagerConfig(solverManagerConfig))
.setRuntimeInit()
.defaultBean()
.done());
}
if (!TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME.equals(key)) {
// The default SolverManager instance is generated by DefaultTimefoldBeanProvider
syntheticBeanBuildItemBuildProducer.produce(
// We generate all required resources only to create a SolverManager and set it as managed bean
SyntheticBeanBuildItem.configure(SolverManager.class)
.scope(Singleton.class)
.addType(ParameterizedType.create(DotName.createSimple(SolverManager.class.getName()),
Type.create(DotName.createSimple(value.getSolutionClass().getName()),
Type.Kind.CLASS),
TypeVariable.create(Object.class.getName())))
.supplier(recorder.solverManager(key, value,
GizmoMemberAccessorEntityEnhancer.getGeneratedGizmoMemberAccessorMap(recorderContext,
solverConfigBuildItem
.getGeneratedGizmoClasses().generatedGizmoMemberAccessorClassSet),
GizmoMemberAccessorEntityEnhancer.getGeneratedSolutionClonerMap(recorderContext,
solverConfigBuildItem
.getGeneratedGizmoClasses().generatedGizmoSolutionClonerClassSet)))
.setRuntimeInit()
.named(key)
.done());
}
});
}
@BuildStep(onlyIf = IsDevelopment.class)
@Record(RUNTIME_INIT)
public void recordAndRegisterDevUIBean(
TimefoldDevUIRecorder devUIRecorder,
RecorderContext recorderContext,
SolverConfigBuildItem solverConfigBuildItem,
BuildProducer<SyntheticBeanBuildItem> syntheticBeans) {
if (solverConfigBuildItem.getGeneratedGizmoClasses() == null) {
// Extension was skipped, so no solver configs
syntheticBeans.produce(SyntheticBeanBuildItem.configure(DevUISolverConfig.class)
.scope(ApplicationScoped.class)
.supplier(devUIRecorder.solverConfigSupplier(Collections.emptyMap(),
Collections.emptyMap(),
Collections.emptyMap()))
.defaultBean()
.setRuntimeInit()
.done());
return;
}
syntheticBeans.produce(SyntheticBeanBuildItem.configure(DevUISolverConfig.class)
.scope(ApplicationScoped.class)
.supplier(devUIRecorder.solverConfigSupplier(solverConfigBuildItem.getSolverConfigMap(),
GizmoMemberAccessorEntityEnhancer.getGeneratedGizmoMemberAccessorMap(recorderContext,
solverConfigBuildItem
.getGeneratedGizmoClasses().generatedGizmoMemberAccessorClassSet),
GizmoMemberAccessorEntityEnhancer.getGeneratedSolutionClonerMap(recorderContext,
solverConfigBuildItem
.getGeneratedGizmoClasses().generatedGizmoSolutionClonerClassSet)))
.defaultBean()
.setRuntimeInit()
.done());
}
private void generateConstraintVerifier(SolverConfig solverConfig,
BuildProducer<SyntheticBeanBuildItem> syntheticBeanBuildItemBuildProducer) {
var constraintVerifierClassName = DotNames.CONSTRAINT_VERIFIER.toString();
var scoreDirectorFactoryConfig = Objects.requireNonNull(solverConfig.getScoreDirectorFactoryConfig());
var constraintProviderClass = scoreDirectorFactoryConfig.getConstraintProviderClass();
if (constraintProviderClass != null && isClassDefined(constraintVerifierClassName)) {
final var planningSolutionClass = Objects.requireNonNull(solverConfig.getSolutionClass());
final var planningEntityClassList = Objects.requireNonNull(solverConfig.getEntityClassList());
// TODO Don't duplicate defaults by using ConstraintVerifier.create(solverConfig) instead
SyntheticBeanBuildItem.ExtendedBeanConfigurator constraintDescriptor =
SyntheticBeanBuildItem.configure(DotNames.CONSTRAINT_VERIFIER)
.scope(Singleton.class)
.creator(methodCreator -> {
var constraintProviderResultHandle =
methodCreator.newInstance(MethodDescriptor.ofConstructor(constraintProviderClass));
var planningSolutionClassResultHandle = methodCreator.loadClass(planningSolutionClass);
var planningEntityClassesResultHandle =
methodCreator.newArray(Class.class, planningEntityClassList.size());
for (var i = 0; i < planningEntityClassList.size(); i++) {
var planningEntityClassResultHandle =
methodCreator.loadClass(planningEntityClassList.get(i));
methodCreator.writeArrayValue(planningEntityClassesResultHandle, i,
planningEntityClassResultHandle);
}
var enabledPreviewFeatureSet = methodCreator.invokeStaticMethod(
MethodDescriptor.ofMethod(
EnumSet.class, "noneOf", EnumSet.class, Class.class),
methodCreator.loadClass(PreviewFeature.class));
if (solverConfig.getEnablePreviewFeatureSet() != null) {
for (var enabledPreviewFeature : solverConfig.getEnablePreviewFeatureSet()) {
methodCreator.invokeVirtualMethod(
MethodDescriptor.ofMethod(EnumSet.class, "add", boolean.class, Object.class),
enabledPreviewFeatureSet, methodCreator.load(enabledPreviewFeature));
}
}
for (var i = 0; i < planningEntityClassList.size(); i++) {
var planningEntityClassResultHandle =
methodCreator.loadClass(planningEntityClassList.get(i));
methodCreator.writeArrayValue(planningEntityClassesResultHandle, i,
planningEntityClassResultHandle);
}
// Got incompatible class change error when trying to invoke static method on
// ConstraintVerifier.build(ConstraintProvider, Class, Class...)
var solutionDescriptorResultHandle = methodCreator.invokeStaticMethod(
MethodDescriptor.ofMethod(SolutionDescriptor.class, "buildSolutionDescriptor",
SolutionDescriptor.class, Set.class, Class.class, Class[].class),
enabledPreviewFeatureSet, planningSolutionClassResultHandle,
planningEntityClassesResultHandle);
var constraintVerifierResultHandle = methodCreator.newInstance(
MethodDescriptor.ofConstructor(
"ai.timefold.solver.test.impl.score.stream.DefaultConstraintVerifier",
ConstraintProvider.class, SolutionDescriptor.class),
constraintProviderResultHandle, solutionDescriptorResultHandle);
methodCreator.returnValue(constraintVerifierResultHandle);
})
.addType(ParameterizedType.create(DotNames.CONSTRAINT_VERIFIER,
new Type[] {
Type.create(DotName.createSimple(constraintProviderClass.getName()),
Type.Kind.CLASS),
Type.create(DotName.createSimple(planningSolutionClass.getName()), Type.Kind.CLASS)
}, null))
.forceApplicationClass()
.defaultBean();
syntheticBeanBuildItemBuildProducer.produce(constraintDescriptor.done());
}
}
private void applySolverProperties(IndexView indexView, String solverName, SolverConfig solverConfig) {
if (solverConfig.getSolutionClass() == null) {
solverConfig.setSolutionClass(findFirstSolutionClass(indexView));
}
if (solverConfig.getEntityClassList() == null) {
solverConfig.setEntityClassList(findEntityClassList(indexView));
}
applyScoreDirectorFactoryProperties(indexView, solverConfig);
// Override the current configuration with values from the solver properties
timefoldBuildTimeConfig.getSolverConfig(solverName).flatMap(SolverBuildTimeConfig::domainAccessType)
.ifPresent(solverConfig::setDomainAccessType);
if (solverConfig.getDomainAccessType() == null) {
solverConfig.setDomainAccessType(DomainAccessType.GIZMO);
}
timefoldBuildTimeConfig.getSolverConfig(solverName)
.flatMap(SolverBuildTimeConfig::enabledPreviewFeatures)
.ifPresent(solverConfig::setEnablePreviewFeatureSet);
timefoldBuildTimeConfig.getSolverConfig(solverName)
.flatMap(SolverBuildTimeConfig::nearbyDistanceMeterClass)
.ifPresent(clazz -> {
// We need to check the data type, as the Smallrye converter does not enforce it
if (!NearbyDistanceMeter.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(
"The Nearby Selection Meter class (%s) of the solver config (%s) does not implement NearbyDistanceMeter."
.formatted(clazz, solverName));
}
solverConfig.withNearbyDistanceMeterClass((Class<? extends NearbyDistanceMeter<?, ?>>) clazz);
});
// Termination properties are set at runtime
}
private static List<AnnotationInstance> getAllConcreteSolutionClasses(IndexView indexView) {
return indexView.getAnnotations(DotNames.PLANNING_SOLUTION).stream()
.filter(annotationInstance -> !annotationInstance.target().asClass().isAbstract())
.toList();
}
private Class<?> findFirstSolutionClass(IndexView indexView) {
var annotationInstanceCollection = getAllConcreteSolutionClasses(indexView);
var solutionTarget = annotationInstanceCollection.iterator().next().target();
return convertClassInfoToClass(solutionTarget.asClass());
}
private List<Class<?>> findEntityClassList(IndexView indexView) {
// All annotated classes
var entityList = new ArrayList<Class<?>>(indexView.getAnnotations(DotNames.PLANNING_ENTITY).stream()
.map(AnnotationInstance::target)
.map(target -> (Class<?>) convertClassInfoToClass(target.asClass()))
.toList());
// Now we search for child classes as well
var childEntityList = new ArrayList<>(entityList);
while (!childEntityList.isEmpty()) {
var entityClass = childEntityList.remove(0);
// Check all subclasses
var childEntityClassList = indexView.getAllKnownSubclasses(entityClass).stream()
.map(target -> (Class<?>) convertClassInfoToClass(target.asClass()))
.toList();
if (!childEntityClassList.isEmpty()) {
entityList.addAll(childEntityClassList.stream().filter(c -> !entityList.contains(c)).toList());
childEntityList.addAll(childEntityClassList);
}
// Check all subinterfaces
var childEntityInterfaceList = indexView.getAllKnownSubinterfaces(entityClass).stream()
.map(target -> (Class<?>) convertClassInfoToClass(target.asClass()))
.toList();
if (!childEntityInterfaceList.isEmpty()) {
entityList.addAll(childEntityInterfaceList.stream().filter(c -> !entityList.contains(c)).toList());
childEntityList.addAll(childEntityInterfaceList);
}
// Check all implementors
var childEntityImplementorList = indexView.getAllKnownImplementations(entityClass).stream()
.map(target -> (Class<?>) convertClassInfoToClass(target.asClass()))
.toList();
if (!childEntityImplementorList.isEmpty()) {
entityList.addAll(childEntityImplementorList.stream().filter(c -> !entityList.contains(c)).toList());
childEntityList.addAll(childEntityImplementorList);
}
}
return entityList;
}
private void registerClassesFromAnnotations(IndexView indexView, Set<Class<?>> reflectiveClassSet) {
for (var beanDefiningAnnotation : DotNames.BeanDefiningAnnotations.values()) {
for (var annotationInstance : indexView
.getAnnotationsWithRepeatable(beanDefiningAnnotation.getAnnotationDotName(), indexView)) {
for (var parameterName : beanDefiningAnnotation.getParameterNames()) {
var value = annotationInstance.value(parameterName);
// We don't care about the default/null type.
if (value != null) {
var type = value.asClass();
try {
var beanClass = Class.forName(type.name().toString(), false,
Thread.currentThread().getContextClassLoader());
reflectiveClassSet.add(beanClass);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find bean class (%s) referenced in annotation (%s)."
.formatted(type.name(), annotationInstance));
}
}
}
}
}
}
protected void applyScoreDirectorFactoryProperties(IndexView indexView, SolverConfig solverConfig) {
if (solverConfig.getScoreDirectorFactoryConfig() == null) {
var scoreDirectorFactoryConfig = defaultScoreDirectoryFactoryConfig(indexView);
solverConfig.setScoreDirectorFactoryConfig(scoreDirectorFactoryConfig);
}
}
private boolean isClassDefined(String className) {
var classLoader = Thread.currentThread().getContextClassLoader();
try {
Class.forName(className, false, classLoader);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
private ScoreDirectorFactoryConfig defaultScoreDirectoryFactoryConfig(IndexView indexView) {
var scoreDirectorFactoryConfig = new ScoreDirectorFactoryConfig();
scoreDirectorFactoryConfig.setEasyScoreCalculatorClass(
findFirstImplementingConcreteClass(DotNames.EASY_SCORE_CALCULATOR, indexView));
scoreDirectorFactoryConfig.setConstraintProviderClass(
findFirstImplementingConcreteClass(DotNames.CONSTRAINT_PROVIDER, indexView));
scoreDirectorFactoryConfig.setIncrementalScoreCalculatorClass(
findFirstImplementingConcreteClass(DotNames.INCREMENTAL_SCORE_CALCULATOR, indexView));
return scoreDirectorFactoryConfig;
}
private <T> Class<? extends T> findFirstImplementingConcreteClass(DotName targetDotName, IndexView indexView) {
var classInfoCollection = indexView.getAllKnownImplementations(targetDotName).stream()
.filter(classInfo -> !classInfo.isAbstract())
.toList();
if (classInfoCollection.isEmpty()) {
return null;
}
var classInfo = classInfoCollection.iterator().next();
return convertClassInfoToClass(classInfo);
}
private String convertAnnotationInstancesToString(Collection<AnnotationInstance> annotationInstanceCollection) {
return "[%s]".formatted(annotationInstanceCollection.stream().map(instance -> instance.target().toString())
.collect(Collectors.joining(", ")));
}
private <T> Class<? extends T> convertClassInfoToClass(ClassInfo classInfo) {
var className = classInfo.name().toString();
var classLoader = Thread.currentThread().getContextClassLoader();
try {
return (Class<? extends T>) classLoader.loadClass(className);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("The class (%s) cannot be created during deployment.".formatted(className), e);
}
}
private GeneratedGizmoClasses generateDomainAccessors(Map<String, SolverConfig> solverConfigMap, IndexView indexView,
BuildProducer<GeneratedBeanBuildItem> generatedBeans,
BuildProducer<GeneratedClassBuildItem> generatedClasses,
BuildProducer<BytecodeTransformerBuildItem> transformers, Set<Class<?>> reflectiveClassSet) {
// Use mvn quarkus:dev -Dquarkus.debug.generated-classes-dir=dump-classes
// to dump generated classes
var classOutput = new GeneratedClassGizmoAdaptor(generatedClasses, true);
var beanClassOutput = new GeneratedBeanGizmoAdaptor(generatedBeans);
var generatedMemberAccessorsClassNameSet = new HashSet<String>();
var gizmoSolutionClonerClassNameSet = new HashSet<String>();
/*
* TODO consistently change the name "entity" to something less confusing
* "entity" in this context means both "planning solution",
* "planning entity" and other things as well.
*/
assertSolverDomainAccessType(solverConfigMap);
var entityEnhancer = new GizmoMemberAccessorEntityEnhancer();
if (solverConfigMap.values().stream().anyMatch(c -> c.getDomainAccessType() == DomainAccessType.GIZMO)) {
var membersToGeneratedAccessorsForCollection = new ArrayList<AnnotationInstance>();
// Every entity and solution gets scanned for annotations.
// Annotated members get their accessors generated.
for (var dotName : DotNames.GIZMO_MEMBER_ACCESSOR_ANNOTATIONS) {
membersToGeneratedAccessorsForCollection.addAll(indexView.getAnnotationsWithRepeatable(dotName, indexView));
}
generateDomainAccessorsForShadowSources(indexView, membersToGeneratedAccessorsForCollection);
membersToGeneratedAccessorsForCollection.removeIf(this::shouldIgnoreMember);
// Fail fast on auto-discovery.
var planningSolutionAnnotationInstanceCollection = getAllConcreteSolutionClasses(indexView);
var unconfiguredSolverConfigList = solverConfigMap.entrySet().stream()
.filter(e -> e.getValue().getSolutionClass() == null)
.map(Map.Entry::getKey)
.toList();
var unusedSolutionClassList = planningSolutionAnnotationInstanceCollection.stream()
.map(planningClass -> planningClass.target().asClass().name().toString())
.filter(planningClassName -> reflectiveClassSet.stream()
.noneMatch(clazz -> clazz.getName().equals(planningClassName)))
.toList();
if (planningSolutionAnnotationInstanceCollection.isEmpty()) {
throw new IllegalStateException(
"No classes found with a @%s annotation.".formatted(PlanningSolution.class.getSimpleName()));
} else if (planningSolutionAnnotationInstanceCollection.size() > 1 && !unconfiguredSolverConfigList.isEmpty()
&& !unusedSolutionClassList.isEmpty()) {
throw new IllegalStateException(
"Unused classes (%s) found with a @%s annotation.".formatted(String.join(", ", unusedSolutionClassList),
PlanningSolution.class.getSimpleName()));
}
planningSolutionAnnotationInstanceCollection.forEach(planningSolutionAnnotationInstance -> {
var autoDiscoverMemberType = planningSolutionAnnotationInstance.values().stream()
.filter(v -> v.name().equals("autoDiscoverMemberType"))
.findFirst()
.map(AnnotationValue::asEnum)
.map(AutoDiscoverMemberType::valueOf)
.orElse(AutoDiscoverMemberType.NONE);
if (autoDiscoverMemberType != AutoDiscoverMemberType.NONE) {
throw new UnsupportedOperationException("""
Auto-discovery of members using %s is not supported under Quarkus.
Remove the autoDiscoverMemberType property from the @%s annotation
and explicitly annotate the fields or getters with annotations such as @%s, @%s or @%s."""
.strip()
.formatted(
AutoDiscoverMemberType.class.getSimpleName(),
PlanningSolution.class.getSimpleName(),
PlanningScore.class.getSimpleName(),
PlanningEntityCollectionProperty.class.getSimpleName(),
ProblemFactCollectionProperty.class.getSimpleName()));
}
});
for (var annotatedMember : membersToGeneratedAccessorsForCollection) {
ClassInfo classInfo = null;
String memberName = null;
switch (annotatedMember.target().kind()) {
case FIELD -> {
var fieldInfo = annotatedMember.target().asField();
classInfo = fieldInfo.declaringClass();
memberName = fieldInfo.name();
buildFieldAccessor(annotatedMember, generatedMemberAccessorsClassNameSet, entityEnhancer, classOutput,
classInfo, fieldInfo, transformers);
}
case METHOD -> {
var methodInfo = annotatedMember.target().asMethod();
classInfo = methodInfo.declaringClass();
memberName = methodInfo.name();
buildMethodAccessor(annotatedMember, generatedMemberAccessorsClassNameSet, entityEnhancer, classOutput,
classInfo, methodInfo, true, transformers);
}
default -> {
throw new IllegalStateException(
"The member (%s) is not on a field or method.".formatted(annotatedMember));
}
}
if (annotatedMember.name().equals(DotNames.CASCADING_UPDATE_SHADOW_VARIABLE)) {
// The source method name also must be included
// targetMethodName is a required field and is always present
var targetMethodName = annotatedMember.value("targetMethodName").asString();
var methodInfo = classInfo.method(targetMethodName);
buildMethodAccessor(null, generatedMemberAccessorsClassNameSet, entityEnhancer, classOutput,
classInfo, methodInfo, false, transformers);
} else if (annotatedMember.name().equals(DotNames.SHADOW_VARIABLE)
&& annotatedMember.value("supplierName") != null) {
// The source method name also must be included
var targetMethodName = annotatedMember.value("supplierName")
.asString();
var methodInfo = classInfo.method(targetMethodName);
if (methodInfo == null) {
throw new IllegalArgumentException("""
@%s (%s) defines a supplierMethod (%s) that does not exist inside its declaring class (%s).
Maybe you misspelled the supplierMethod name?"""
.formatted(ShadowVariable.class.getSimpleName(), memberName, targetMethodName,
classInfo.name().toString()));
}
buildMethodAccessor(annotatedMember, generatedMemberAccessorsClassNameSet, entityEnhancer,
classOutput,
classInfo, methodInfo, true, transformers);
}
}
// The ConstraintWeightOverrides field is not annotated, but it needs a member accessor
var solutionClassInstance = planningSolutionAnnotationInstanceCollection.iterator().next();
var solutionClassInfo = solutionClassInstance.target().asClass();
var constraintFieldInfo = solutionClassInfo.fields().stream()
.filter(f -> f.type().name().equals(DotNames.CONSTRAINT_WEIGHT_OVERRIDES))
.findFirst()
.orElse(null);
if (constraintFieldInfo != null) {
// Prefer method to field
var solutionClass = convertClassInfoToClass(solutionClassInfo);
var constraintMethod =
ReflectionHelper.getGetterMethod(solutionClass, constraintFieldInfo.name());
var constraintMethodInfo = solutionClassInfo.methods().stream()
.filter(m -> constraintMethod != null && m.name().equals(constraintMethod.getName())
&& m.parametersCount() == 0)
.findFirst()
.orElse(null);
if (constraintMethodInfo != null) {
buildMethodAccessor(solutionClassInstance, generatedMemberAccessorsClassNameSet, entityEnhancer,
classOutput, solutionClassInfo, constraintMethodInfo, true, transformers);
} else {
buildFieldAccessor(solutionClassInstance, generatedMemberAccessorsClassNameSet, entityEnhancer, classOutput,
solutionClassInfo, constraintFieldInfo, transformers);
}
}
// Using REFLECTION domain access type so Timefold doesn't try to generate GIZMO code
solverConfigMap.values().forEach(c -> {
var solutionDescriptor = SolutionDescriptor.buildSolutionDescriptor(
c.getEnablePreviewFeatureSet(), DomainAccessType.REFLECTION,
c.getSolutionClass(), null, null, c.getEntityClassList());
gizmoSolutionClonerClassNameSet
.add(entityEnhancer.generateSolutionCloner(solutionDescriptor, classOutput, indexView, transformers));
});
}
entityEnhancer.generateGizmoBeanFactory(beanClassOutput, reflectiveClassSet, transformers);
return new GeneratedGizmoClasses(generatedMemberAccessorsClassNameSet, gizmoSolutionClonerClassNameSet);
}
private static void generateDomainAccessorsForShadowSources(IndexView indexView,
List<AnnotationInstance> membersToGeneratedAccessorsForCollection) {
for (var shadowSources : indexView.getAnnotations(DotNames.SHADOW_SOURCES)) {
Class<?> rootType;
try {
rootType = Thread.currentThread().getContextClassLoader().loadClass(
shadowSources.target().asMethod().declaringClass().name().toString());
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Unable to load class (%s) which has a @%s annotation."
.formatted(shadowSources.target().asMethod().declaringClass().name(),
ShadowSources.class.getSimpleName()));
}
var sources = shadowSources.value().asStringArray();
var alignmentKey = shadowSources.value("alignmentKey");
if (alignmentKey != null && !alignmentKey.asString().isEmpty()) {
generateDomainAccessorsForSourcePath(indexView, rootType, alignmentKey.asString(),
membersToGeneratedAccessorsForCollection);
}
for (var source : sources) {
generateDomainAccessorsForSourcePath(indexView, rootType, source, membersToGeneratedAccessorsForCollection);
}
}
}
private static void generateDomainAccessorsForSourcePath(IndexView indexView, Class<?> rootType, String source,
List<AnnotationInstance> membersToGeneratedAccessorsForCollection) {
for (var iterator = RootVariableSource.pathIterator(rootType, source); iterator.hasNext();) {
var member = iterator.next().member();
AnnotationTarget target;
if (member instanceof Field field) {
target = indexView.getClassByName(field.getDeclaringClass()).field(field.getName());
} else if (member instanceof Method method) {
target = indexView.getClassByName(method.getDeclaringClass()).method(method.getName());
} else {
throw new IllegalStateException("Member (%s) is not on a field or method."
.formatted(member));
}
// Create a fake annotation for it
membersToGeneratedAccessorsForCollection.add(
AnnotationInstance.builder(DotNames.SHADOW_SOURCES)
.value(source)
.buildWithTarget(target));
}
}
private static void buildFieldAccessor(AnnotationInstance annotatedMember, Set<String> generatedMemberAccessorsClassNameSet,
GizmoMemberAccessorEntityEnhancer entityEnhancer, ClassOutput classOutput, ClassInfo classInfo, FieldInfo fieldInfo,
BuildProducer<BytecodeTransformerBuildItem> transformers) {
try {
generatedMemberAccessorsClassNameSet.add(
entityEnhancer.generateFieldAccessor(annotatedMember, classOutput, fieldInfo,
transformers));
} catch (ClassNotFoundException | NoSuchFieldException e) {
throw new IllegalStateException("Fail to generate member accessor for field (%s) of the class(%s)."
.formatted(fieldInfo.name(), classInfo.name().toString()), e);
}
}
private static void buildMethodAccessor(AnnotationInstance annotatedMember,
Set<String> generatedMemberAccessorsClassNameSet,
GizmoMemberAccessorEntityEnhancer entityEnhancer, ClassOutput classOutput, ClassInfo classInfo,
MethodInfo methodInfo, boolean requiredReturnType, BuildProducer<BytecodeTransformerBuildItem> transformers) {
try {
generatedMemberAccessorsClassNameSet.add(entityEnhancer.generateMethodAccessor(annotatedMember,
classOutput, classInfo, methodInfo, requiredReturnType, transformers));
} catch (ClassNotFoundException | NoSuchMethodException e) {
throw new IllegalStateException(
"Failed to generate member accessor for the method (%s) of the class (%s)."
.formatted(methodInfo.name(), classInfo.name()),
e);
}
}
private void assertSolverDomainAccessType(Map<String, SolverConfig> solverConfigMap) {
// All solver must use the same domain access type
if (solverConfigMap.values().stream().map(SolverConfig::getDomainAccessType).distinct().count() > 1) {
throw new ConfigurationException(
"""
The domain access type must be unique across all Solver configurations.
%s""".formatted(solverConfigMap.entrySet().stream()
.map(e -> format("quarkus.timefold.\"%s\".domain-access-type=%s",
e.getKey(), e.getValue().getDomainAccessType()))
.collect(Collectors.joining("\n"))));
}
}
private boolean shouldIgnoreMember(AnnotationInstance annotationInstance) {
switch (annotationInstance.target().kind()) {
case FIELD:
return (annotationInstance.target().asField().flags() & Modifier.STATIC) != 0;
case METHOD:
return (annotationInstance.target().asMethod().flags() & Modifier.STATIC) != 0;
default:
throw new IllegalArgumentException(
"Annotation (%s) can only be applied to methods and fields.".formatted(annotationInstance.name()));
}
}
private void registerCustomClassesFromSolverConfig(SolverConfig solverConfig, Set<Class<?>> reflectiveClassSet) {
solverConfig.visitReferencedClasses(clazz -> {
if (clazz != null) {
reflectiveClassSet.add(clazz);
}
});
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment/api/ConstraintMetaModelBuildItem.java | package ai.timefold.solver.quarkus.deployment.api;
import java.util.Map;
import ai.timefold.solver.core.api.score.stream.ConstraintMetaModel;
import io.quarkus.builder.item.SimpleBuildItem;
/**
* Represents a {@link ai.timefold.solver.core.api.score.stream.ConstraintMetaModel} at the build time for the purpose
* of Quarkus augmentation.
*/
public final class ConstraintMetaModelBuildItem extends SimpleBuildItem {
private final Map<String, ConstraintMetaModel> constraintMetaModelsBySolverNames;
public ConstraintMetaModelBuildItem(Map<String, ConstraintMetaModel> constraintMetaModelsBySolverNames) {
this.constraintMetaModelsBySolverNames = Map.copyOf(constraintMetaModelsBySolverNames);
}
public Map<String, ConstraintMetaModel> constraintMetaModelsBySolverNames() {
return constraintMetaModelsBySolverNames;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment/api/package-info.java | /**
* Public {@link io.quarkus.builder.item.BuildItem}s consumable by other Quarkus extensions.
* <p>
* All classes in this package are part of the public API of this extension.
* Moreover, the extension is responsible for creating instances of these classes during the build phase.
*/
package ai.timefold.solver.quarkus.deployment.api;
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment/config/SolverBuildTimeConfig.java | package ai.timefold.solver.quarkus.deployment.config;
import java.util.Optional;
import java.util.Set;
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.PreviewFeature;
import ai.timefold.solver.core.config.solver.SolverConfig;
import ai.timefold.solver.quarkus.config.SolverRuntimeConfig;
import io.quarkus.runtime.annotations.ConfigGroup;
/**
* During build time, this is translated into Timefold's {@link SolverConfig}
* (except for termination properties which are translated at bootstrap time).
*
* @see SolverRuntimeConfig
*/
@ConfigGroup
public interface SolverBuildTimeConfig {
/**
* A classpath resource to read the specific solver configuration XML.
* If this property isn't specified, that solverConfig.xml is optional.
*/
// Build time - classes in the SolverConfig are visited by SolverConfig.visitReferencedClasses
// which generates the constructor of classes used by Quarkus
Optional<String> solverConfigXml();
/**
* Determines how to access the fields and methods of domain classes.
* Defaults to {@link DomainAccessType#GIZMO}.
*/
// Build time - GIZMO classes are only generated if at least one solver
// has domain access type GIZMO
Optional<DomainAccessType> domainAccessType();
/**
* Enable the Nearby Selection quick configuration.
*/
// Build time - visited by SolverConfig.visitReferencedClasses
// which generates the constructor used by Quarkus
Optional<Class<?>> nearbyDistanceMeterClass();
/**
* What preview features to enable.
* The list of available preview features should not
* be considered stable and may change between releases.
*/
Optional<Set<PreviewFeature>> enabledPreviewFeatures();
/**
* What constraint stream implementation to use. Defaults to {@link ConstraintStreamImplType#BAVET}.
*
* @deprecated Not used anymore.
*/
@Deprecated(forRemoval = true, since = "1.4.0")
Optional<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".
*/
// Build time - modifies the ConstraintProvider class if set
Optional<Boolean> constraintStreamAutomaticNodeSharing();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment | java-sources/ai/timefold/solver/timefold-solver-quarkus-deployment/1.26.1/ai/timefold/solver/quarkus/deployment/config/TimefoldBuildTimeConfig.java | package ai.timefold.solver.quarkus.deployment.config;
import java.util.Map;
import java.util.Optional;
import ai.timefold.solver.core.config.solver.SolverConfig;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.WithUnnamedKey;
/**
* During build time, this is translated into Timefold's Config classes.
*/
@ConfigMapping(prefix = "quarkus.timefold")
@ConfigRoot(phase = ConfigPhase.BUILD_TIME)
public interface TimefoldBuildTimeConfig {
String DEFAULT_SOLVER_CONFIG_URL = "solverConfig.xml";
String DEFAULT_SOLVER_NAME = "default";
/**
* A classpath resource to read the solver configuration XML.
* Defaults to {@value DEFAULT_SOLVER_CONFIG_URL}.
* If this property isn't specified, that solverConfig.xml is optional.
*/
Optional<String> solverConfigXml();
/**
* Configuration properties that overwrite {@link SolverConfig} per Solver.
* If a solver name is not explicitly specified, the solver name will default to {@link #DEFAULT_SOLVER_NAME}.
*/
@WithUnnamedKey(DEFAULT_SOLVER_NAME)
Map<String, SolverBuildTimeConfig> solver();
default Optional<SolverBuildTimeConfig> getSolverConfig(String solverName) {
return Optional.ofNullable(solver().get(solverName));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-devui-integration-test/1.26.1/ai/timefold/solver/quarkus/it/devui | java-sources/ai/timefold/solver/timefold-solver-quarkus-devui-integration-test/1.26.1/ai/timefold/solver/quarkus/it/devui/domain/StringLengthVariableListener.java | package ai.timefold.solver.quarkus.it.devui.domain;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import org.jspecify.annotations.NonNull;
public class StringLengthVariableListener
implements VariableListener<TestdataStringLengthShadowSolution, TestdataStringLengthShadowEntity> {
@Override
public void beforeEntityAdded(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataStringLengthShadowEntity entity) {
/* Nothing to do */
}
@Override
public void afterEntityAdded(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataStringLengthShadowEntity entity) {
/* Nothing to do */
}
@Override
public void beforeVariableChanged(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataStringLengthShadowEntity entity) {
/* Nothing to do */
}
@Override
public void afterVariableChanged(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataStringLengthShadowEntity entity) {
int oldLength = (entity.getLength() != null) ? entity.getLength() : 0;
int newLength = getLength(entity.getValue());
if (oldLength != newLength) {
scoreDirector.beforeVariableChanged(entity, "length");
entity.setLength(getLength(entity.getValue()));
scoreDirector.afterVariableChanged(entity, "length");
}
}
@Override
public void beforeEntityRemoved(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataStringLengthShadowEntity entity) {
/* Nothing to do */
}
@Override
public void afterEntityRemoved(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataStringLengthShadowEntity entity) {
/* Nothing to do */
}
private static int getLength(String value) {
if (value != null) {
return value.length();
} else {
return 0;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-devui-integration-test/1.26.1/ai/timefold/solver/quarkus/it/devui | java-sources/ai/timefold/solver/timefold-solver-quarkus-devui-integration-test/1.26.1/ai/timefold/solver/quarkus/it/devui/domain/TestdataStringLengthShadowEntity.java | package ai.timefold.solver.quarkus.it.devui.domain;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
@PlanningEntity
public class TestdataStringLengthShadowEntity {
@PlanningVariable(valueRangeProviderRefs = "valueRange")
private String value;
@ShadowVariable(variableListenerClass = StringLengthVariableListener.class,
sourceEntityClass = TestdataStringLengthShadowEntity.class, sourceVariableName = "value")
private Integer length;
// ************************************************************************
// Getters/setters
// ************************************************************************
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-devui-integration-test/1.26.1/ai/timefold/solver/quarkus/it/devui | java-sources/ai/timefold/solver/timefold-solver-quarkus-devui-integration-test/1.26.1/ai/timefold/solver/quarkus/it/devui/domain/TestdataStringLengthShadowSolution.java | package ai.timefold.solver.quarkus.it.devui.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 TestdataStringLengthShadowSolution {
@ValueRangeProvider(id = "valueRange")
private List<String> valueList;
@PlanningEntityCollectionProperty
private List<TestdataStringLengthShadowEntity> entityList;
@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 HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-devui-integration-test/1.26.1/ai/timefold/solver/quarkus/it/devui | java-sources/ai/timefold/solver/timefold-solver-quarkus-devui-integration-test/1.26.1/ai/timefold/solver/quarkus/it/devui/solver/TestdataStringLengthConstraintProvider.java | package ai.timefold.solver.quarkus.it.devui.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.devui.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-drl-integration-test/0.8.42/ai/timefold/solver/quarkus/drl | java-sources/ai/timefold/solver/timefold-solver-quarkus-drl-integration-test/0.8.42/ai/timefold/solver/quarkus/drl/it/TimefoldTestResource.java | package ai.timefold.solver.quarkus.drl.it;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import javax.inject.Inject;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.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.drl.it.domain.TestdataQuarkusEntity;
import ai.timefold.solver.quarkus.drl.it.domain.TestdataQuarkusSolution;
@Path("/timefold/test")
public class TimefoldTestResource {
@Inject
SolverManager<TestdataQuarkusSolution, Long> solverManager;
@POST
@Path("/solver-factory")
@Produces(MediaType.TEXT_PLAIN)
public String solveWithSolverFactory() throws InterruptedException {
TestdataQuarkusSolution planningProblem = new TestdataQuarkusSolution();
planningProblem.setEntityList(Arrays.asList(
new TestdataQuarkusEntity(),
new TestdataQuarkusEntity()));
planningProblem.setLeftValueList(Arrays.asList("a", "b", "c"));
planningProblem.setRightValueList(Arrays.asList("1", "2", "3"));
SolverJob<TestdataQuarkusSolution, Long> solverJob = solverManager.solve(1L, planningProblem);
try {
TestdataQuarkusSolution sol = solverJob.getFinalBestSolution();
StringBuilder out = new StringBuilder();
out.append("score=").append(sol.getScore()).append('\n');
for (int i = 0; i < sol.getEntityList().size(); i++) {
out.append("entity." + i + ".fullValue=").append(sol.getEntityList().get(i).getFullValue()).append('\n');
}
return out.toString();
} catch (ExecutionException e) {
throw new IllegalStateException("Solving failed.", e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-drl-integration-test/0.8.42/ai/timefold/solver/quarkus/drl/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-drl-integration-test/0.8.42/ai/timefold/solver/quarkus/drl/it/domain/TestdataQuarkusEntity.java | package ai.timefold.solver.quarkus.drl.it.domain;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
@PlanningEntity
public class TestdataQuarkusEntity {
@PlanningVariable(valueRangeProviderRefs = "leftValueRange")
public String leftValue;
@PlanningVariable(valueRangeProviderRefs = "rightValueRange")
public String rightValue;
public String getLeftValue() {
return leftValue;
}
public String getRightValue() {
return rightValue;
}
public void setLeftValue(String leftValue) {
this.leftValue = leftValue;
}
public void setRightValue(String rightValue) {
this.rightValue = rightValue;
}
public String getFullValue() {
return Objects.requireNonNullElse(leftValue, "") + Objects.requireNonNullElse(rightValue, "");
}
@Override
public String toString() {
return "TestdataQuarkusEntity(" + "leftValue=" + leftValue + ";rightValue=" + rightValue + ";)";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-drl-integration-test/0.8.42/ai/timefold/solver/quarkus/drl/it | java-sources/ai/timefold/solver/timefold-solver-quarkus-drl-integration-test/0.8.42/ai/timefold/solver/quarkus/drl/it/domain/TestdataQuarkusSolution.java | package ai.timefold.solver.quarkus.drl.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.solution.ProblemFactCollectionProperty;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
@PlanningSolution
public class TestdataQuarkusSolution {
private List<String> leftValueList;
private List<String> rightValueList;
private List<TestdataQuarkusEntity> entityList;
private SimpleScore score;
@ValueRangeProvider(id = "leftValueRange")
@ProblemFactCollectionProperty
public List<String> getLeftValueList() {
return leftValueList;
}
public void setLeftValueList(List<String> valueList) {
this.leftValueList = valueList;
}
@ValueRangeProvider(id = "rightValueRange")
@ProblemFactCollectionProperty
public List<String> getRightValueList() {
return rightValueList;
}
public void setRightValueList(List<String> valueList) {
this.rightValueList = valueList;
}
@PlanningEntityCollectionProperty
public List<TestdataQuarkusEntity> getEntityList() {
return entityList;
}
public void setEntityList(List<TestdataQuarkusEntity> entityList) {
this.entityList = entityList;
}
@PlanningScore
public SimpleScore getScore() {
return score;
}
public void setScore(SimpleScore score) {
this.score = score;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-quarkus-integration-test/1.26.1/ai/timefold/solver/quarkus | java-sources/ai/timefold/solver/timefold-solver-quarkus-integration-test/1.26.1/ai/timefold/solver/quarkus/it/TimefoldTestResource.java | package ai.timefold.solver.quarkus.it;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.time.Duration;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.core.api.solver.SolverConfigOverride;
import ai.timefold.solver.core.api.solver.SolverManager;
import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
import ai.timefold.solver.core.impl.solver.DefaultSolverJob;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.quarkus.it.domain.TestdataStringLengthShadowEntity;
import ai.timefold.solver.quarkus.it.domain.TestdataStringLengthShadowSolution;
@Path("/timefold/test")
public class TimefoldTestResource {
private final SolverManager<TestdataStringLengthShadowSolution, Long> solverManager;
@Inject
public TimefoldTestResource(SolverManager<TestdataStringLengthShadowSolution, Long> solverManager) {
this.solverManager = solverManager;
}
private static TestdataStringLengthShadowSolution generateProblem() {
var planningProblem = new TestdataStringLengthShadowSolution();
planningProblem.setEntityList(Arrays.asList(
new TestdataStringLengthShadowEntity(),
new TestdataStringLengthShadowEntity()));
planningProblem.setValueList(Arrays.asList("a", "bb", "ccc"));
return planningProblem;
}
@POST
@Path("/solver-factory")
@Produces(MediaType.TEXT_PLAIN)
public String solveWithSolverFactory() {
var solverJob = solverManager.solve(1L, generateProblem());
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);
}
}
@GET
@Path("/solver-factory/override")
@Produces(MediaType.TEXT_PLAIN)
public String solveWithOverriddenTime(@QueryParam("seconds") Integer seconds) {
var solverJobBuilder = solverManager.solveBuilder()
.withProblemId(1L)
.withProblem(generateProblem())
.withConfigOverride(
new SolverConfigOverride<TestdataStringLengthShadowSolution>()
.withTerminationConfig(new TerminationConfig()
.withSpentLimit(Duration.ofSeconds(seconds))));
var solverJob = (DefaultSolverJob<TestdataStringLengthShadowSolution, Long>) solverJobBuilder.run();
SolverScope<TestdataStringLengthShadowSolution> customScope = new SolverScope<>() {
@Override
public long calculateTimeMillisSpentUpToNow() {
// Return five seconds to make the time gradient predictable
return 5000L;
}
};
// We ensure the best-score limit won't take priority
customScope.setStartingInitializedScore(HardSoftScore.of(-1, -1));
customScope.setInitializedBestScore(HardSoftScore.of(-1, -1));
try {
var score = solverJob.getFinalBestSolution().getScore().toString();
var decimalFormatSymbols = DecimalFormatSymbols.getInstance();
decimalFormatSymbols.setDecimalSeparator('.');
var decimalFormat = new DecimalFormat("0.00", decimalFormatSymbols);
var gradientTime = solverJob.getSolverTermination().calculateSolverTimeGradient(customScope);
solverManager.terminateEarly(1L);
return String.format("%s,%s", score, decimalFormat.format(gradientTime));
} 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-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/StringLengthVariableListener.java | package ai.timefold.solver.quarkus.it.domain;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import org.jspecify.annotations.NonNull;
public class StringLengthVariableListener
implements VariableListener<TestdataStringLengthShadowSolution, TestdataStringLengthShadowEntity> {
@Override
public void beforeEntityAdded(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataStringLengthShadowEntity entity) {
/* Nothing to do */
}
@Override
public void afterEntityAdded(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataStringLengthShadowEntity entity) {
/* Nothing to do */
}
@Override
public void beforeVariableChanged(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataStringLengthShadowEntity entity) {
/* Nothing to do */
}
@Override
public void afterVariableChanged(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataStringLengthShadowEntity entity) {
int oldLength = (entity.getLength() != null) ? entity.getLength() : 0;
int newLength = getLength(entity.getValue());
if (oldLength != newLength) {
scoreDirector.beforeVariableChanged(entity, "length");
entity.setLength(getLength(entity.getValue()));
scoreDirector.afterVariableChanged(entity, "length");
}
}
@Override
public void beforeEntityRemoved(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataStringLengthShadowEntity entity) {
/* Nothing to do */
}
@Override
public void afterEntityRemoved(@NonNull ScoreDirector<TestdataStringLengthShadowSolution> scoreDirector,
@NonNull TestdataStringLengthShadowEntity entity) {
/* Nothing to do */
}
private static int getLength(String value) {
if (value != null) {
return value.length();
} else {
return 0;
}
}
}
|
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/TestdataStringLengthShadowEntity.java | package ai.timefold.solver.quarkus.it.domain;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
@PlanningEntity
public class TestdataStringLengthShadowEntity {
@PlanningVariable(valueRangeProviderRefs = "valueRange")
private String value;
@ShadowVariable(variableListenerClass = StringLengthVariableListener.class,
sourceEntityClass = TestdataStringLengthShadowEntity.class, sourceVariableName = "value")
private Integer length;
// ************************************************************************
// Getters/setters
// ************************************************************************
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.