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.
package org.optaplanner.examples.common.business;
import static java.util.stream.Collectors.toList;
import static org.optaplanner.core.api.solver.SolutionUpdatePolicy.NO_UPDATE;
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.constraint.ConstraintMatchTotal;
import org.optaplanner.core.api.score.constraint.Indictment;
import org.optaplanner.core.api.solver.SolutionManager;
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 final 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 SolutionManager solutionManager;
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.solutionManager = SolutionManager.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 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 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 solutionManager.update(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 solutionManager.explain(getSolution(), NO_UPDATE)
.getConstraintMatchTotalMap()
.values()
.stream()
.sorted()
.collect(toList());
}
public Map