org.optaplanner.examples.common.business.SolutionBusiness Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of optaplanner-examples Show documentation
Show all versions of optaplanner-examples Show documentation
OptaPlanner solves planning problems.
This lightweight, embeddable planning engine implements powerful and scalable algorithms
to optimize business resource scheduling and planning.
This module contains the examples which demonstrate how to use it in a normal Java application.
/*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.examples.common.business;
import static java.util.stream.Collectors.toList;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.swing.SwingUtilities;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.score.ScoreManager;
import org.optaplanner.core.api.score.constraint.ConstraintMatchTotal;
import org.optaplanner.core.api.score.constraint.Indictment;
import org.optaplanner.core.api.solver.SolverFactory;
import org.optaplanner.core.api.solver.SolverJob;
import org.optaplanner.core.api.solver.SolverManager;
import org.optaplanner.core.api.solver.SolverStatus;
import org.optaplanner.core.api.solver.change.ProblemChange;
import org.optaplanner.core.impl.score.director.InnerScoreDirector;
import org.optaplanner.core.impl.solver.DefaultSolverFactory;
import org.optaplanner.core.impl.solver.change.DefaultProblemChangeDirector;
import org.optaplanner.examples.common.app.CommonApp;
import org.optaplanner.examples.common.persistence.AbstractSolutionExporter;
import org.optaplanner.examples.common.persistence.AbstractSolutionImporter;
import org.optaplanner.persistence.common.api.domain.solution.SolutionFileIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param the solution type, the class with the {@link PlanningSolution} annotation
*/
public class SolutionBusiness> implements AutoCloseable {
public static String getBaseFileName(File file) {
return getBaseFileName(file.getName());
}
public static String getBaseFileName(String name) {
int indexOfLastDot = name.lastIndexOf('.');
if (indexOfLastDot > 0) {
return name.substring(0, indexOfLastDot);
} else {
return name;
}
}
private static final Comparator FILE_COMPARATOR = new ProblemFileComparator();
private static final AtomicLong SOLVER_JOB_ID_COUNTER = new AtomicLong();
private static final Logger LOGGER = LoggerFactory.getLogger(SolutionBusiness.class);
private final CommonApp app;
private final DefaultSolverFactory solverFactory;
private final SolverManager solverManager;
private final ScoreManager scoreManager;
private final AtomicReference> solverJobRef = new AtomicReference<>();
private final AtomicReference workingSolutionRef = new AtomicReference<>();
private File dataDir;
private SolutionFileIO solutionFileIO;
private Set> importers;
private Set> exporters;
private File importDataDir;
private File unsolvedDataDir;
private File solvedDataDir;
private File exportDataDir;
private String solutionFileName = null;
public SolutionBusiness(CommonApp app, SolverFactory solverFactory) {
this.app = app;
this.solverFactory = ((DefaultSolverFactory) solverFactory);
this.solverManager = SolverManager.create(solverFactory);
this.scoreManager = ScoreManager.create(solverFactory);
}
private static List getFileList(File dataDir, String extension) {
try (Stream paths = Files.walk(dataDir.toPath(), FileVisitOption.FOLLOW_LINKS)) {
return paths.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith("." + extension))
.map(Path::toFile)
.sorted(FILE_COMPARATOR)
.collect(toList());
} catch (IOException e) {
throw new IllegalStateException("Error while crawling data directory (" + dataDir + ").", e);
}
}
public String getAppName() {
return app.getName();
}
public String getAppDescription() {
return app.getDescription();
}
public String getAppIconResource() {
return app.getIconResource();
}
public File getDataDir() {
return dataDir;
}
public void setDataDir(File dataDir) {
this.dataDir = dataDir;
}
public SolutionFileIO getSolutionFileIO() {
return solutionFileIO;
}
public void setSolutionFileIO(SolutionFileIO solutionFileIO) {
this.solutionFileIO = solutionFileIO;
}
public Set> getImporters() {
return importers;
}
public void setImporters(Set> importers) {
this.importers = importers;
}
public void addExporter(AbstractSolutionExporter exporter) {
this.exporters.add(exporter);
}
public Set> getExporters() {
return this.exporters;
}
public void setExporters(Set> exporters) {
if (exporters == null) {
throw new IllegalArgumentException("Passed exporters must not be null");
}
this.exporters = exporters;
}
public boolean hasImporter() {
return !importers.isEmpty();
}
public boolean hasExporter() {
return exporters != null && exporters.size() > 0;
}
public void updateDataDirs() {
if (hasImporter()) {
importDataDir = new File(dataDir, "import");
if (!importDataDir.exists()) {
throw new IllegalStateException("The directory importDataDir (" + importDataDir.getAbsolutePath()
+ ") does not exist.");
}
}
unsolvedDataDir = new File(dataDir, "unsolved");
if (!unsolvedDataDir.exists()) {
throw new IllegalStateException("The directory unsolvedDataDir (" + unsolvedDataDir.getAbsolutePath()
+ ") does not exist.");
}
solvedDataDir = new File(dataDir, "solved");
if (!solvedDataDir.exists() && !solvedDataDir.mkdir()) {
throw new IllegalStateException("The directory solvedDataDir (" + solvedDataDir.getAbsolutePath()
+ ") does not exist and could not be created.");
}
if (hasExporter()) {
exportDataDir = new File(dataDir, "export");
if (!exportDataDir.exists() && !exportDataDir.mkdir()) {
throw new IllegalStateException("The directory exportDataDir (" + exportDataDir.getAbsolutePath()
+ ") does not exist and could not be created.");
}
}
}
public File getImportDataDir() {
return importDataDir;
}
public File getUnsolvedDataDir() {
return unsolvedDataDir;
}
public File getSolvedDataDir() {
return solvedDataDir;
}
public File getExportDataDir() {
return exportDataDir;
}
public List getUnsolvedFileList() {
return getFileList(unsolvedDataDir, solutionFileIO.getInputFileExtension());
}
public List getSolvedFileList() {
return getFileList(solvedDataDir, solutionFileIO.getOutputFileExtension());
}
public Solution_ getSolution() {
return workingSolutionRef.get();
}
public void setSolution(Solution_ solution) {
workingSolutionRef.set(solution);
}
public String getSolutionFileName() {
return solutionFileName;
}
public void setSolutionFileName(String solutionFileName) {
this.solutionFileName = solutionFileName;
}
public Score_ getScore() {
return scoreManager.updateScore(getSolution());
}
public boolean isSolving() {
SolverJob solverJob = solverJobRef.get();
return solverJob != null && solverJob.getSolverStatus() == SolverStatus.SOLVING_ACTIVE;
}
public boolean isConstraintMatchEnabled() {
return applyScoreDirector(InnerScoreDirector::isConstraintMatchEnabled);
}
private Result_ applyScoreDirector(Function, Result_> function) {
try (InnerScoreDirector scoreDirector =
(InnerScoreDirector) solverFactory.getScoreDirectorFactory().buildScoreDirector(true,
true)) {
scoreDirector.setWorkingSolution(getSolution());
Result_ result = function.apply(scoreDirector);
scoreDirector.triggerVariableListeners();
scoreDirector.calculateScore();
setSolution(scoreDirector.getWorkingSolution());
return result;
}
}
public List> getConstraintMatchTotalList() {
return scoreManager.explainScore(getSolution())
.getConstraintMatchTotalMap()
.values()
.stream()
.sorted()
.collect(toList());
}
public Map