proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tennis/persistence/TennisGenerator.java
TennisGenerator
createTennisSolution
class TennisGenerator extends LoggingMain { public static void main(String[] args) { new TennisGenerator().generate(); } protected final SolutionFileIO<TennisSolution> solutionFileIO = new TennisSolutionFileIO(); protected final File outputDir; public TennisGenerator() { this.outputDir = new File(CommonApp.determineDataDir(TennisApp.DATA_DIR_NAME), "unsolved"); } public void generate() { File outputFile = new File(outputDir, "munich-7teams.json"); TennisSolution tennisSolution = createTennisSolution(); solutionFileIO.write(tennisSolution, outputFile); logger.info("Saved: {}", outputFile); } public TennisSolution createTennisSolution() {<FILL_FUNCTION_BODY>} }
TennisSolution tennisSolution = new TennisSolution(0L); List<Team> teamList = new ArrayList<>(); teamList.add(new Team(0L, "Micha")); teamList.add(new Team(1L, "Angelika")); teamList.add(new Team(2L, "Katrin")); teamList.add(new Team(3L, "Susi")); teamList.add(new Team(4L, "Irene")); teamList.add(new Team(5L, "Kristina")); teamList.add(new Team(6L, "Tobias")); tennisSolution.setTeamList(teamList); List<Day> dayList = new ArrayList<>(); for (int i = 0; i < 18; i++) { dayList.add(new Day(i, i)); } tennisSolution.setDayList(dayList); List<UnavailabilityPenalty> unavailabilityPenaltyList = new ArrayList<>(); unavailabilityPenaltyList.add(new UnavailabilityPenalty(0L, teamList.get(4), dayList.get(0))); unavailabilityPenaltyList.add(new UnavailabilityPenalty(1L, teamList.get(6), dayList.get(1))); unavailabilityPenaltyList.add(new UnavailabilityPenalty(2L, teamList.get(2), dayList.get(2))); unavailabilityPenaltyList.add(new UnavailabilityPenalty(3L, teamList.get(4), dayList.get(3))); unavailabilityPenaltyList.add(new UnavailabilityPenalty(4L, teamList.get(4), dayList.get(5))); unavailabilityPenaltyList.add(new UnavailabilityPenalty(5L, teamList.get(2), dayList.get(6))); unavailabilityPenaltyList.add(new UnavailabilityPenalty(6L, teamList.get(1), dayList.get(8))); unavailabilityPenaltyList.add(new UnavailabilityPenalty(7L, teamList.get(2), dayList.get(9))); unavailabilityPenaltyList.add(new UnavailabilityPenalty(8L, teamList.get(4), dayList.get(10))); unavailabilityPenaltyList.add(new UnavailabilityPenalty(9L, teamList.get(4), dayList.get(11))); unavailabilityPenaltyList.add(new UnavailabilityPenalty(10L, teamList.get(6), dayList.get(12))); unavailabilityPenaltyList.add(new UnavailabilityPenalty(11L, teamList.get(5), dayList.get(15))); tennisSolution.setUnavailabilityPenaltyList(unavailabilityPenaltyList); List<TeamAssignment> teamAssignmentList = new ArrayList<>(); long id = 0L; for (Day day : dayList) { for (int i = 0; i < 4; i++) { teamAssignmentList.add(new TeamAssignment(id, day, i)); id++; } } tennisSolution.setTeamAssignmentList(teamAssignmentList); BigInteger possibleSolutionSize = BigInteger.valueOf(teamList.size()).pow( teamAssignmentList.size()); logger.info("Tennis {} has {} teams, {} days, {} unavailabilityPenalties and {} teamAssignments" + " with a search space of {}.", "munich-7teams", teamList.size(), dayList.size(), unavailabilityPenaltyList.size(), teamAssignmentList.size(), AbstractSolutionImporter.getFlooredPossibleSolutionSize(possibleSolutionSize)); return tennisSolution;
225
974
1,199
<methods>public non-sealed void <init>() <variables>protected final transient Logger logger
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tennis/swingui/TennisPanel.java
TeamAssignmentAction
actionPerformed
class TeamAssignmentAction extends AbstractAction { private TeamAssignment teamAssignment; public TeamAssignmentAction(TeamAssignment teamAssignment) { super("Play"); this.teamAssignment = teamAssignment; } @Override public void actionPerformed(ActionEvent e) {<FILL_FUNCTION_BODY>} }
JPanel listFieldsPanel = new JPanel(new GridLayout(2, 2)); listFieldsPanel.add(new JLabel("Team:")); List<Team> teamList = getSolution().getTeamList(); // Add 1 to array size to add null, which makes the entity unassigned JComboBox teamListField = new JComboBox( teamList.toArray(new Object[teamList.size() + 1])); LabeledComboBoxRenderer.applyToComboBox(teamListField); teamListField.setSelectedItem(teamAssignment.getTeam()); listFieldsPanel.add(teamListField); listFieldsPanel.add(new JLabel("Pinned:")); JCheckBox pinnedField = new JCheckBox("cannot move during solving"); pinnedField.setSelected(teamAssignment.isPinned()); listFieldsPanel.add(pinnedField); int result = JOptionPane.showConfirmDialog(TennisPanel.this.getRootPane(), listFieldsPanel, "Select team", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { Team toTeam = (Team) teamListField.getSelectedItem(); if (teamAssignment.getTeam() != toTeam) { doProblemChange((workingSolution, problemChangeDirector) -> problemChangeDirector .changeVariable(teamAssignment, "team", ta -> ta.setTeam(toTeam))); } boolean toPinned = pinnedField.isSelected(); if (teamAssignment.isPinned() != toPinned) { doProblemChange((workingSolution, problemChangeDirector) -> problemChangeDirector .changeProblemProperty(teamAssignment, ta -> ta.setPinned(toPinned))); } solverAndPersistenceFrame.resetScreen(); }
93
468
561
<methods>public non-sealed void <init>() ,public java.awt.Color determinePlanningEntityColor(java.lang.Object, java.lang.Object) ,public java.lang.String determinePlanningEntityTooltip(java.lang.Object) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.tennis.domain.TennisSolution>) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.tennis.domain.TennisSolution>, boolean) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public org.optaplanner.examples.tennis.domain.TennisSolution getSolution() ,public SolutionBusiness<org.optaplanner.examples.tennis.domain.TennisSolution,?> getSolutionBusiness() ,public SolverAndPersistenceFrame<org.optaplanner.examples.tennis.domain.TennisSolution> getSolverAndPersistenceFrame() ,public java.lang.String getUsageExplanationPath() ,public boolean isIndictmentHeatMapEnabled() ,public boolean isUseIndictmentColor() ,public boolean isWrapInScrollPane() ,public abstract void resetPanel(org.optaplanner.examples.tennis.domain.TennisSolution) ,public void setSolutionBusiness(SolutionBusiness<org.optaplanner.examples.tennis.domain.TennisSolution,?>) ,public void setSolverAndPersistenceFrame(SolverAndPersistenceFrame<org.optaplanner.examples.tennis.domain.TennisSolution>) ,public void setUseIndictmentColor(boolean) ,public void updatePanel(org.optaplanner.examples.tennis.domain.TennisSolution) <variables>protected static final java.awt.Color[][] INDICTMENT_COLORS,public static final java.awt.Dimension PREFERRED_SCROLLABLE_VIEWPORT_SIZE,protected static final java.lang.String USAGE_EXPLANATION_PATH,protected double[] indictmentMinimumLevelNumbers,protected final transient Logger logger,protected org.optaplanner.swing.impl.TangoColorFactory normalColorFactory,protected SolutionBusiness<org.optaplanner.examples.tennis.domain.TennisSolution,?> solutionBusiness,protected SolverAndPersistenceFrame<org.optaplanner.examples.tennis.domain.TennisSolution> solverAndPersistenceFrame,protected boolean useIndictmentColor
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/travelingtournament/persistence/TravelingTournamentExporter.java
TravelingTournamentOutputBuilder
writeSolution
class TravelingTournamentOutputBuilder extends TxtOutputBuilder<TravelingTournament> { @Override public void writeSolution() throws IOException {<FILL_FUNCTION_BODY>} }
int maximumTeamNameLength = 0; for (Team team : solution.getTeamList()) { if (team.getName().length() > maximumTeamNameLength) { maximumTeamNameLength = team.getName().length(); } } for (Team team : solution.getTeamList()) { bufferedWriter.write(String.format("%-" + (maximumTeamNameLength + 3) + "s", team.getName())); } bufferedWriter.write("\n"); for (Team team : solution.getTeamList()) { bufferedWriter.write( String.format("%-" + (maximumTeamNameLength + 3) + "s", team.getName().replaceAll("[\\w\\d]", "-"))); } bufferedWriter.write("\n"); for (Day day : solution.getDayList()) { for (Team team : solution.getTeamList()) { // this could be put in a hashmap first for performance boolean opponentIsHome = false; Team opponentTeam = null; for (Match match : solution.getMatchList()) { if (match.getDay().equals(day)) { if (match.getHomeTeam().equals(team)) { opponentIsHome = false; opponentTeam = match.getAwayTeam(); } else if (match.getAwayTeam().equals(team)) { opponentIsHome = true; opponentTeam = match.getHomeTeam(); } } } if (opponentTeam != null) { String opponentName = (opponentIsHome ? "@" : "") + opponentTeam.getName(); bufferedWriter.write(String.format("%-" + (maximumTeamNameLength + 3) + "s", opponentName)); } } bufferedWriter.write("\n"); }
53
448
501
<methods>public non-sealed void <init>() ,public abstract TxtOutputBuilder<org.optaplanner.examples.travelingtournament.domain.TravelingTournament> createTxtOutputBuilder() ,public java.lang.String getOutputFileSuffix() ,public void writeSolution(org.optaplanner.examples.travelingtournament.domain.TravelingTournament, java.io.File) <variables>protected static final java.lang.String DEFAULT_OUTPUT_FILE_SUFFIX
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/travelingtournament/persistence/TravelingTournamentImporter.java
TravelingTournamentInputBuilder
createDayList
class TravelingTournamentInputBuilder extends TxtInputBuilder<TravelingTournament> { @Override public TravelingTournament readSolution() throws IOException { TravelingTournament travelingTournament = new TravelingTournament(0L); int n = readN(); readTeamList(travelingTournament, n); createDayList(travelingTournament, n); List<List<Integer>> outerDistanceList = readOuterDistanceList(travelingTournament); // TODO setting the distances should be a separate method createMatchListAndSetDistancesInTeamList(travelingTournament, outerDistanceList); initializeMatchDays(travelingTournament); BigInteger a = factorial(2 * (n - 1)); BigInteger possibleSolutionSize = (a == null) ? null : a.pow(n / 2); logger.info("TravelingTournament {} has {} days, {} teams and {} matches with a search space of {}.", getInputId(), travelingTournament.getDayList().size(), travelingTournament.getTeamList().size(), travelingTournament.getMatchList().size(), getFlooredPossibleSolutionSize(possibleSolutionSize)); return travelingTournament; } private int readN() throws IOException { return Integer.parseInt(bufferedReader.readLine()); } private void readTeamList(TravelingTournament travelingTournament, int n) throws IOException { List<Team> teamList = new ArrayList<>(); for (int i = 0; i < n; i++) { Team team = new Team(i, bufferedReader.readLine()); team.setDistanceToTeamMap(new LinkedHashMap<>()); teamList.add(team); } travelingTournament.setTeamList(teamList); } private List<List<Integer>> readOuterDistanceList(TravelingTournament travelingTournament) throws IOException { List<List<Integer>> outerDistanceList = new ArrayList<>(); String line = bufferedReader.readLine(); while (line != null && !line.replaceAll("\\s+", "").equals("")) { StringTokenizer tokenizer = new StringTokenizer(line.replaceAll("\\s+", " ").trim()); List<Integer> innerDistanceList = new ArrayList<>(); while (tokenizer.hasMoreTokens()) { int distance = Integer.parseInt(tokenizer.nextToken()); innerDistanceList.add(distance); } outerDistanceList.add(innerDistanceList); line = bufferedReader.readLine(); } return outerDistanceList; } private void createDayList(TravelingTournament travelingTournament, int n) {<FILL_FUNCTION_BODY>} private void createMatchListAndSetDistancesInTeamList(TravelingTournament travelingTournament, List<List<Integer>> outerDistanceList) { List<Team> teamList = travelingTournament.getTeamList(); List<Match> matchList = new ArrayList<>(); int i = 0; long matchId = 0; for (Team homeTeam : teamList) { int j = 0; for (Team awayTeam : teamList) { int distance = outerDistanceList.get(i).get(j); homeTeam.getDistanceToTeamMap().put(awayTeam, distance); if (i != j) { Match match = new Match(matchId, homeTeam, awayTeam); matchId++; matchList.add(match); } j++; } i++; } travelingTournament.setMatchList(matchList); } /** * Canonical pattern initialization (see papers). * * @param travelingTournament the traveling tournament */ protected void initializeMatchDays(TravelingTournament travelingTournament) { int n = travelingTournament.getN(); for (int i = 0; i < (n - 1); i++) { initializeMatchPairs(travelingTournament, (n - 1), i, i); } for (int startA = 1, startB = (n - 2); startA < (n - 1); startA += 2, startB -= 2) { for (int i = 0; i < (n - 1); i++) { int a = (startA + i) % (n - 1); int b = (startB + i) % (n - 1); initializeMatchPairs(travelingTournament, a, b, i); } } } private void initializeMatchPairs(TravelingTournament travelingTournament, int a, int b, int i) { if ((i % 6) >= 3) { // Might not be a 100% the canonical pattern // Swap them int oldA = a; a = b; b = oldA; } Team aTeam = travelingTournament.getTeamList().get(a); Team bTeam = travelingTournament.getTeamList().get(b); Match m1 = findMatch(travelingTournament.getMatchList(), aTeam, bTeam); m1.setDay(travelingTournament.getDayList().get(i)); Match m2 = findMatch(travelingTournament.getMatchList(), bTeam, aTeam); m2.setDay(travelingTournament.getDayList().get(i + travelingTournament.getN() - 1)); } private Match findMatch(List<Match> matchList, Team homeTeam, Team awayTeam) { for (Match match : matchList) { if (match.getHomeTeam().equals(homeTeam) && match.getAwayTeam().equals(awayTeam)) { return match; } } throw new IllegalStateException("Nothing found for: " + homeTeam + " and " + awayTeam); } }
List<Day> dayList = new ArrayList<>(); int daySize = (n - 1) * 2; // Play vs each team (except itself) twice (home and away) Day previousDay = null; for (int i = 0; i < daySize; i++) { Day day = new Day(i); dayList.add(day); if (previousDay != null) { previousDay.setNextDay(day); } previousDay = day; } travelingTournament.setDayList(dayList);
1,481
140
1,621
<methods>public non-sealed void <init>() ,public abstract TxtInputBuilder<org.optaplanner.examples.travelingtournament.domain.TravelingTournament> createTxtInputBuilder() ,public java.lang.String getInputFileSuffix() ,public org.optaplanner.examples.travelingtournament.domain.TravelingTournament readSolution(java.io.File) ,public org.optaplanner.examples.travelingtournament.domain.TravelingTournament readSolution(java.net.URL) <variables>private static final java.lang.String DEFAULT_INPUT_FILE_SUFFIX
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/travelingtournament/persistence/TravelingTournamentSolutionFileIO.java
TravelingTournamentSolutionFileIO
read
class TravelingTournamentSolutionFileIO extends AbstractJsonSolutionFileIO<TravelingTournament> { public TravelingTournamentSolutionFileIO() { super(TravelingTournament.class); } @Override public TravelingTournament read(File inputSolutionFile) {<FILL_FUNCTION_BODY>} }
TravelingTournament travelingTournament = super.read(inputSolutionFile); var teamsById = travelingTournament.getTeamList().stream() .collect(Collectors.toMap(Team::getId, Function.identity())); /* * Replace the duplicate team instances in the distanceToTeamMap by references to instances from * the teamList. */ for (Team team : travelingTournament.getTeamList()) { var newTravelDistanceMap = deduplicateMap(team.getDistanceToTeamMap(), teamsById, Team::getId); team.setDistanceToTeamMap(newTravelDistanceMap); } return travelingTournament;
90
163
253
<methods>public void <init>(Class<org.optaplanner.examples.travelingtournament.domain.TravelingTournament>) ,public void <init>(Class<org.optaplanner.examples.travelingtournament.domain.TravelingTournament>, ObjectMapper) <variables>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/travelingtournament/score/TravelingTournamentConstraintProvider.java
TravelingTournamentConstraintProvider
awayToEndHop
class TravelingTournamentConstraintProvider implements ConstraintProvider { @Override public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { return new Constraint[] { fourConsecutiveHomeMatches(constraintFactory), fourConsecutiveAwayMatches(constraintFactory), repeatMatchOnTheNextDay(constraintFactory), startToAwayHop(constraintFactory), homeToAwayHop(constraintFactory), awayToAwayHop(constraintFactory), awayToHomeHop(constraintFactory), awayToEndHop(constraintFactory) }; } private Constraint fourConsecutiveHomeMatches(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Match.class) .ifExists(Match.class, equal(Match::getHomeTeam), equal(match -> getDayIndex(match) + 1, TravelingTournamentConstraintProvider::getDayIndex)) .ifExists(Match.class, equal(Match::getHomeTeam), equal(match -> getDayIndex(match) + 2, TravelingTournamentConstraintProvider::getDayIndex)) .ifExists(Match.class, equal(Match::getHomeTeam), equal(match -> getDayIndex(match) + 3, TravelingTournamentConstraintProvider::getDayIndex)) .penalize(HardSoftScore.ONE_HARD) .asConstraint("4 consecutive home matches"); } private Constraint fourConsecutiveAwayMatches(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Match.class) .ifExists(Match.class, equal(Match::getAwayTeam), equal(match -> getDayIndex(match) + 1, TravelingTournamentConstraintProvider::getDayIndex)) .ifExists(Match.class, equal(Match::getAwayTeam), equal(match -> getDayIndex(match) + 2, TravelingTournamentConstraintProvider::getDayIndex)) .ifExists(Match.class, equal(Match::getAwayTeam), equal(match -> getDayIndex(match) + 3, TravelingTournamentConstraintProvider::getDayIndex)) .penalize(HardSoftScore.ONE_HARD) .asConstraint("4 consecutive away matches"); } private Constraint repeatMatchOnTheNextDay(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Match.class) .ifExists(Match.class, equal(Match::getHomeTeam, Match::getAwayTeam), equal(Match::getAwayTeam, Match::getHomeTeam), equal(match -> getDayIndex(match) + 1, TravelingTournamentConstraintProvider::getDayIndex)) .penalize(HardSoftScore.ONE_HARD) .asConstraint("Repeat match on the next day"); } private Constraint startToAwayHop(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Match.class) .ifNotExists(Day.class, equal(match -> getDayIndex(match) - 1, Day::getIndex)) .penalize(HardSoftScore.ONE_SOFT, match -> match.getAwayTeam().getDistance(match.getHomeTeam())) .asConstraint("Start to away hop"); } private Constraint homeToAwayHop(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Match.class) .join(Match.class, equal(Match::getHomeTeam, Match::getAwayTeam), equal(match -> getDayIndex(match) + 1, TravelingTournamentConstraintProvider::getDayIndex)) .penalize(HardSoftScore.ONE_SOFT, (match, otherMatch) -> match.getHomeTeam().getDistance(otherMatch.getHomeTeam())) .asConstraint("Home to away hop"); } private Constraint awayToAwayHop(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Match.class) .join(Match.class, equal(Match::getAwayTeam, Match::getAwayTeam), equal(match -> getDayIndex(match) + 1, TravelingTournamentConstraintProvider::getDayIndex)) .penalize(HardSoftScore.ONE_SOFT, (match, otherMatch) -> match.getHomeTeam().getDistance(otherMatch.getHomeTeam())) .asConstraint("Away to away hop"); } private Constraint awayToHomeHop(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Match.class) .join(Match.class, equal(Match::getAwayTeam, Match::getHomeTeam), equal(match -> getDayIndex(match) + 1, TravelingTournamentConstraintProvider::getDayIndex)) .penalize(HardSoftScore.ONE_SOFT, (match, otherMatch) -> match.getHomeTeam().getDistance(match.getAwayTeam())) .asConstraint("Away to home hop"); } private Constraint awayToEndHop(ConstraintFactory constraintFactory) {<FILL_FUNCTION_BODY>} private static int getDayIndex(Match match) { return match.getDay().getIndex(); } }
return constraintFactory.forEach(Match.class) .ifNotExists(Day.class, equal(match -> getDayIndex(match) + 1, Day::getIndex)) .penalize(HardSoftScore.ONE_SOFT, match -> match.getHomeTeam().getDistance(match.getAwayTeam())) .asConstraint("Away to end hop");
1,268
94
1,362
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/travelingtournament/solver/move/MatchChainRotationsMove.java
MatchChainRotationsMove
rotateList
class MatchChainRotationsMove extends AbstractMove<TravelingTournament> { private List<Match> firstMatchList; private List<Match> secondMatchList; public MatchChainRotationsMove(List<Match> firstMatchList, List<Match> secondMatchList) { this.firstMatchList = firstMatchList; this.secondMatchList = secondMatchList; } @Override public boolean isMoveDoable(ScoreDirector<TravelingTournament> scoreDirector) { return true; } @Override public MatchChainRotationsMove createUndoMove(ScoreDirector<TravelingTournament> scoreDirector) { List<Match> inverseFirstMatchList = new ArrayList<>(firstMatchList); Collections.reverse(inverseFirstMatchList); List<Match> inverseSecondMatchList = new ArrayList<>(secondMatchList); Collections.reverse(inverseSecondMatchList); return new MatchChainRotationsMove(inverseFirstMatchList, inverseSecondMatchList); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<TravelingTournament> scoreDirector) { rotateList(scoreDirector, firstMatchList); if (!secondMatchList.isEmpty()) { // TODO create SingleMatchListRotateMove rotateList(scoreDirector, secondMatchList); } } private void rotateList(ScoreDirector<TravelingTournament> scoreDirector, List<Match> matchList) {<FILL_FUNCTION_BODY>} @Override public MatchChainRotationsMove rebase(ScoreDirector<TravelingTournament> destinationScoreDirector) { return new MatchChainRotationsMove(rebaseList(firstMatchList, destinationScoreDirector), rebaseList(secondMatchList, destinationScoreDirector)); } @Override public Collection<? extends Object> getPlanningEntities() { return CollectionUtils.concat(firstMatchList, secondMatchList); } @Override public Collection<? extends Object> getPlanningValues() { List<Day> values = new ArrayList<>(firstMatchList.size() + secondMatchList.size()); for (Match match : firstMatchList) { values.add(match.getDay()); } for (Match match : secondMatchList) { values.add(match.getDay()); } return values; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final MatchChainRotationsMove other = (MatchChainRotationsMove) o; return Objects.equals(firstMatchList, other.firstMatchList) && Objects.equals(secondMatchList, other.secondMatchList); } @Override public int hashCode() { return Objects.hash(firstMatchList, secondMatchList); } @Override public String toString() { return "Rotation " + firstMatchList + " & Rotation " + secondMatchList; } }
Iterator<Match> it = matchList.iterator(); Match previousMatch = it.next(); Match match = null; Day firstDay = previousMatch.getDay(); while (it.hasNext()) { match = it.next(); TravelingTournamentMoveHelper.moveDay(scoreDirector, previousMatch, match.getDay()); previousMatch = match; } TravelingTournamentMoveHelper.moveDay(scoreDirector, match, firstDay);
791
119
910
<methods>public non-sealed void <init>() ,public final AbstractMove<org.optaplanner.examples.travelingtournament.domain.TravelingTournament> doMove(ScoreDirector<org.optaplanner.examples.travelingtournament.domain.TravelingTournament>) ,public final void doMoveOnly(ScoreDirector<org.optaplanner.examples.travelingtournament.domain.TravelingTournament>) ,public static java.lang.Object[] rebaseArray(java.lang.Object[], ScoreDirector<?>) ,public static List<E> rebaseList(List<E>, ScoreDirector<?>) <variables>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/travelingtournament/solver/move/factory/InverseMatchSwapMoveFilter.java
InverseMatchSwapMoveFilter
accept
class InverseMatchSwapMoveFilter implements SelectionFilter<TravelingTournament, SwapMove> { @Override public boolean accept(ScoreDirector<TravelingTournament> scoreDirector, SwapMove move) {<FILL_FUNCTION_BODY>} }
Match leftMatch = (Match) move.getLeftEntity(); Match rightMatch = (Match) move.getRightEntity(); return leftMatch.getHomeTeam().equals(rightMatch.getAwayTeam()) && leftMatch.getAwayTeam().equals(rightMatch.getHomeTeam());
71
73
144
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/travelingtournament/swingui/TravelingTournamentPanel.java
TravelingTournamentPanel
createButton
class TravelingTournamentPanel extends SolutionPanel<TravelingTournament> { public static final String LOGO_PATH = "/org/optaplanner/examples/travelingtournament/swingui/travelingTournamentLogo.png"; private ImageIcon awayMatchIcon; private final TimeTablePanel<Team, Day> teamsPanel; private TangoColorFactory tangoColorFactory; public TravelingTournamentPanel() { awayMatchIcon = new ImageIcon(getClass().getResource("awayMatch.png")); setLayout(new BorderLayout()); JTabbedPane tabbedPane = new JTabbedPane(); teamsPanel = new TimeTablePanel<>(); tabbedPane.add("Teams", new JScrollPane(teamsPanel)); add(tabbedPane, BorderLayout.CENTER); setPreferredSize(PREFERRED_SCROLLABLE_VIEWPORT_SIZE); } @Override public boolean isWrapInScrollPane() { return false; } @Override public void resetPanel(TravelingTournament travelingTournament) { teamsPanel.reset(); tangoColorFactory = new TangoColorFactory(); defineGrid(travelingTournament); fillCells(travelingTournament); repaint(); // Hack to force a repaint of TimeTableLayout during "refresh screen while solving" } private void defineGrid(TravelingTournament travelingTournament) { JButton footprint = SwingUtils.makeSmallButton(new JButton("MMMMM")); int footprintWidth = footprint.getPreferredSize().width; teamsPanel.defineColumnHeaderByKey(HEADER_COLUMN); // Day header for (Team team : travelingTournament.getTeamList()) { teamsPanel.defineColumnHeader(team, footprintWidth); } teamsPanel.defineColumnHeader(null, footprintWidth); // Unassigned teamsPanel.defineRowHeaderByKey(HEADER_ROW); // Team header for (Day day : travelingTournament.getDayList()) { teamsPanel.defineRowHeader(day); } teamsPanel.defineRowHeader(null); // Unassigned day } private void fillCells(TravelingTournament travelingTournament) { teamsPanel.addCornerHeader(HEADER_COLUMN, HEADER_ROW, createTableHeader(new JLabel("Day"))); fillTeamCells(travelingTournament); fillDayCells(travelingTournament); fillMatchCells(travelingTournament); } private void fillTeamCells(TravelingTournament travelingTournament) { for (Team team : travelingTournament.getTeamList()) { JPanel teamPanel = createTableHeader(new JLabel(team.getLabel(), SwingConstants.CENTER)); teamPanel.setBackground(tangoColorFactory.pickColor(team)); teamsPanel.addColumnHeader(team, HEADER_ROW, teamPanel); } teamsPanel.addColumnHeader(null, HEADER_ROW, createTableHeader(new JLabel("Unassigned", SwingConstants.CENTER))); } private void fillDayCells(TravelingTournament travelingTournament) { for (Day day : travelingTournament.getDayList()) { teamsPanel.addRowHeader(HEADER_COLUMN, day, createTableHeader(new JLabel(day.getLabel()))); } teamsPanel.addRowHeader(HEADER_COLUMN, null, createTableHeader(new JLabel("Unassigned"))); } private void fillMatchCells(TravelingTournament travelingTournament) { preparePlanningEntityColors(travelingTournament.getMatchList()); for (Match match : travelingTournament.getMatchList()) { Team homeTeam = match.getHomeTeam(); Team awayTeam = match.getAwayTeam(); String toolTip = determinePlanningEntityTooltip(match); teamsPanel.addCell(homeTeam, match.getDay(), createButton(match, homeTeam, awayTeam, toolTip)); teamsPanel.addCell(awayTeam, match.getDay(), createButton(match, awayTeam, homeTeam, toolTip)); } } private JPanel createTableHeader(JLabel label) { JPanel headerPanel = new JPanel(new BorderLayout()); headerPanel.add(label, BorderLayout.NORTH); headerPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(TangoColorFactory.ALUMINIUM_5), BorderFactory.createEmptyBorder(2, 2, 2, 2))); return headerPanel; } private JButton createButton(Match match, Team team, Team otherTeam, String toolTip) {<FILL_FUNCTION_BODY>} @Override public boolean isIndictmentHeatMapEnabled() { return true; } private class MatchAction extends AbstractAction { private Match match; public MatchAction(Match match, String label) { super(label); this.match = match; } @Override public void actionPerformed(ActionEvent e) { // TODO this allows the user to put the TTP in an inconsistent state, from which the solver cannot start List<Day> dayList = getSolution().getDayList(); // Add 1 to array size to add null, which makes the entity unassigned JComboBox dayListField = new JComboBox( dayList.toArray(new Object[dayList.size() + 1])); LabeledComboBoxRenderer.applyToComboBox(dayListField); dayListField.setSelectedItem(match.getDay()); int result = JOptionPane.showConfirmDialog(TravelingTournamentPanel.this.getRootPane(), dayListField, "Select day", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { Day toDay = (Day) dayListField.getSelectedItem(); doProblemChange((workingSolution, problemChangeDirector) -> problemChangeDirector.changeVariable(match, "day", m -> m.setDay(toDay))); solverAndPersistenceFrame.resetScreen(); } } } }
Color color = determinePlanningEntityColor(match, otherTeam); String label = otherTeam.getLabel(); JButton button = SwingUtils.makeSmallButton(new JButton(new MatchAction(match, label))); if (match.getAwayTeam() == team) { button.setIcon(awayMatchIcon); } button.setBackground(color); button.setToolTipText(toolTip); return button;
1,594
111
1,705
<methods>public non-sealed void <init>() ,public java.awt.Color determinePlanningEntityColor(java.lang.Object, java.lang.Object) ,public java.lang.String determinePlanningEntityTooltip(java.lang.Object) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.travelingtournament.domain.TravelingTournament>) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.travelingtournament.domain.TravelingTournament>, boolean) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public org.optaplanner.examples.travelingtournament.domain.TravelingTournament getSolution() ,public SolutionBusiness<org.optaplanner.examples.travelingtournament.domain.TravelingTournament,?> getSolutionBusiness() ,public SolverAndPersistenceFrame<org.optaplanner.examples.travelingtournament.domain.TravelingTournament> getSolverAndPersistenceFrame() ,public java.lang.String getUsageExplanationPath() ,public boolean isIndictmentHeatMapEnabled() ,public boolean isUseIndictmentColor() ,public boolean isWrapInScrollPane() ,public abstract void resetPanel(org.optaplanner.examples.travelingtournament.domain.TravelingTournament) ,public void setSolutionBusiness(SolutionBusiness<org.optaplanner.examples.travelingtournament.domain.TravelingTournament,?>) ,public void setSolverAndPersistenceFrame(SolverAndPersistenceFrame<org.optaplanner.examples.travelingtournament.domain.TravelingTournament>) ,public void setUseIndictmentColor(boolean) ,public void updatePanel(org.optaplanner.examples.travelingtournament.domain.TravelingTournament) <variables>protected static final java.awt.Color[][] INDICTMENT_COLORS,public static final java.awt.Dimension PREFERRED_SCROLLABLE_VIEWPORT_SIZE,protected static final java.lang.String USAGE_EXPLANATION_PATH,protected double[] indictmentMinimumLevelNumbers,protected final transient Logger logger,protected org.optaplanner.swing.impl.TangoColorFactory normalColorFactory,protected SolutionBusiness<org.optaplanner.examples.travelingtournament.domain.TravelingTournament,?> solutionBusiness,protected SolverAndPersistenceFrame<org.optaplanner.examples.travelingtournament.domain.TravelingTournament> solverAndPersistenceFrame,protected boolean useIndictmentColor
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/domain/Domicile.java
Domicile
toString
class Domicile extends AbstractPersistable implements Standstill { private Location location; public Domicile() { } public Domicile(long id) { super(id); } public Domicile(long id, Location location) { this(id); this.location = location; } @Override public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } // ************************************************************************ // Complex methods // ************************************************************************ /** * @param standstill never null * @return a positive number, the distance multiplied by 1000 to avoid floating point arithmetic rounding errors */ @Override public long getDistanceTo(Standstill standstill) { return location.getDistanceTo(standstill.getLocation()); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
if (location.getName() == null) { return super.toString(); } return location.getName();
259
32
291
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/domain/location/AirLocation.java
AirLocation
getDistanceTo
class AirLocation extends Location { public AirLocation() { } public AirLocation(long id, double latitude, double longitude) { super(id, latitude, longitude); } @Override public long getDistanceTo(Location location) {<FILL_FUNCTION_BODY>} }
double distance = getAirDistanceDoubleTo(location); // Multiplied by 1000 to avoid floating point arithmetic rounding errors return (long) (distance * 1000.0 + 0.5);
84
57
141
<methods>public double getAirDistanceDoubleTo(org.optaplanner.examples.tsp.domain.location.Location) ,public double getAngle(org.optaplanner.examples.tsp.domain.location.Location) ,public abstract long getDistanceTo(org.optaplanner.examples.tsp.domain.location.Location) ,public double getLatitude() ,public double getLongitude() ,public java.lang.String getName() ,public void setLatitude(double) ,public void setLongitude(double) ,public void setName(java.lang.String) ,public java.lang.String toString() <variables>protected double latitude,protected double longitude,protected java.lang.String name
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/domain/location/Location.java
Location
getAngle
class Location extends AbstractPersistable { protected String name = null; protected double latitude; protected double longitude; protected Location() { } protected Location(long id) { super(id); } protected Location(long id, double latitude, double longitude) { this(id); this.latitude = latitude; this.longitude = longitude; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } // ************************************************************************ // Complex methods // ************************************************************************ /** * The distance's unit of measurement depends on the {@link TspSolution}'s {@link DistanceType}. * It can be in miles or km, but for most cases it's in the TSPLIB's unit of measurement. * * @param location never null * @return a positive number, the distance multiplied by 1000 to avoid floating point arithmetic rounding errors */ @JsonIgnore public abstract long getDistanceTo(Location location); @JsonIgnore public double getAirDistanceDoubleTo(Location location) { // Implementation specified by TSPLIB http://www2.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/ // Euclidean distance (Pythagorean theorem) - not correct when the surface is a sphere double latitudeDifference = location.latitude - latitude; double longitudeDifference = location.longitude - longitude; return Math.sqrt( (latitudeDifference * latitudeDifference) + (longitudeDifference * longitudeDifference)); } /** * The angle relative to the direction EAST. * * @param location never null * @return in Cartesian coordinates */ @JsonIgnore public double getAngle(Location location) {<FILL_FUNCTION_BODY>} @Override public String toString() { if (name == null) { return super.toString(); } return name; } }
// Euclidean distance (Pythagorean theorem) - not correct when the surface is a sphere double latitudeDifference = location.latitude - latitude; double longitudeDifference = location.longitude - longitude; return Math.atan2(latitudeDifference, longitudeDifference);
640
77
717
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/domain/location/RoadLocation.java
RoadLocation
getDistanceTo
class RoadLocation extends Location { // Prefer Map over array or List because customers might be added and removed in real-time planning. protected Map<RoadLocation, Double> travelDistanceMap; public RoadLocation() { } public RoadLocation(long id) { super(id); } public RoadLocation(long id, double latitude, double longitude) { super(id, latitude, longitude); } @JsonSerialize(keyUsing = KeySerializer.class) @JsonDeserialize(keyUsing = RoadLocationKeyDeserializer.class) public Map<RoadLocation, Double> getTravelDistanceMap() { return travelDistanceMap; } public void setTravelDistanceMap(Map<RoadLocation, Double> travelDistanceMap) { this.travelDistanceMap = travelDistanceMap; } @Override public long getDistanceTo(Location location) {<FILL_FUNCTION_BODY>} }
if (this == location) { return 0L; } double distance = travelDistanceMap.get((RoadLocation) location); // Multiplied by 1000 to avoid floating point arithmetic rounding errors return (long) (distance * 1000.0 + 0.5);
247
80
327
<methods>public double getAirDistanceDoubleTo(org.optaplanner.examples.tsp.domain.location.Location) ,public double getAngle(org.optaplanner.examples.tsp.domain.location.Location) ,public abstract long getDistanceTo(org.optaplanner.examples.tsp.domain.location.Location) ,public double getLatitude() ,public double getLongitude() ,public java.lang.String getName() ,public void setLatitude(double) ,public void setLongitude(double) ,public void setName(java.lang.String) ,public java.lang.String toString() <variables>protected double latitude,protected double longitude,protected java.lang.String name
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/domain/solver/DomicileAngleVisitDifficultyWeightFactory.java
DomicileAngleVisitDifficultyWeightFactory
createSorterWeight
class DomicileAngleVisitDifficultyWeightFactory implements SelectionSorterWeightFactory<TspSolution, Visit> { @Override public DomicileAngleVisitDifficultyWeight createSorterWeight(TspSolution vehicleRoutingSolution, Visit visit) {<FILL_FUNCTION_BODY>} public static class DomicileAngleVisitDifficultyWeight implements Comparable<DomicileAngleVisitDifficultyWeight> { private static final Comparator<DomicileAngleVisitDifficultyWeight> COMPARATOR = comparingDouble( (DomicileAngleVisitDifficultyWeight weight) -> weight.domicileAngle) .thenComparingLong(weight -> weight.domicileRoundTripDistance) // Ascending (further from the depot are more difficult) .thenComparing(weight -> weight.visit, comparingLong(Visit::getId)); private final Visit visit; private final double domicileAngle; private final long domicileRoundTripDistance; public DomicileAngleVisitDifficultyWeight(Visit visit, double domicileAngle, long domicileRoundTripDistance) { this.visit = visit; this.domicileAngle = domicileAngle; this.domicileRoundTripDistance = domicileRoundTripDistance; } @Override public int compareTo(DomicileAngleVisitDifficultyWeight other) { return COMPARATOR.compare(this, other); } } }
Domicile domicile = vehicleRoutingSolution.getDomicile(); return new DomicileAngleVisitDifficultyWeight(visit, visit.getLocation().getAngle(domicile.getLocation()), visit.getLocation().getDistanceTo(domicile.getLocation()) + domicile.getLocation().getDistanceTo(visit.getLocation()));
394
97
491
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/domain/solver/DomicileDistanceStandstillStrengthWeightFactory.java
DomicileDistanceStandstillStrengthWeightFactory
createSorterWeight
class DomicileDistanceStandstillStrengthWeightFactory implements SelectionSorterWeightFactory<TspSolution, Standstill> { @Override public DomicileDistanceStandstillStrengthWeight createSorterWeight(TspSolution tspSolution, Standstill standstill) {<FILL_FUNCTION_BODY>} public static class DomicileDistanceStandstillStrengthWeight implements Comparable<DomicileDistanceStandstillStrengthWeight> { private static final Comparator<DomicileDistanceStandstillStrengthWeight> COMPARATOR = // Decreasing: closer to depot is stronger Comparator.comparingLong((DomicileDistanceStandstillStrengthWeight weight) -> -weight.domicileRoundTripDistance) .thenComparingDouble(weight -> weight.standstill.getLocation().getLatitude()) .thenComparingDouble(weight -> weight.standstill.getLocation().getLongitude()); private final Standstill standstill; private final long domicileRoundTripDistance; public DomicileDistanceStandstillStrengthWeight(Standstill standstill, long domicileRoundTripDistance) { this.standstill = standstill; this.domicileRoundTripDistance = domicileRoundTripDistance; } @Override public int compareTo(DomicileDistanceStandstillStrengthWeight other) { return COMPARATOR.compare(this, other); } } }
Domicile domicile = tspSolution.getDomicile(); long domicileRoundTripDistance = domicile.getDistanceTo(standstill) + standstill.getDistanceTo(domicile); return new DomicileDistanceStandstillStrengthWeight(standstill, domicileRoundTripDistance);
365
83
448
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/domain/solver/DomicileDistanceVisitDifficultyWeightFactory.java
DomicileDistanceVisitDifficultyWeightFactory
createSorterWeight
class DomicileDistanceVisitDifficultyWeightFactory implements SelectionSorterWeightFactory<TspSolution, Visit> { @Override public DomicileDistanceVisitDifficultyWeight createSorterWeight(TspSolution tspSolution, Visit visit) {<FILL_FUNCTION_BODY>} public static class DomicileDistanceVisitDifficultyWeight implements Comparable<DomicileDistanceVisitDifficultyWeight> { private static final Comparator<DomicileDistanceVisitDifficultyWeight> COMPARATOR = // Decreasing: closer to depot is stronger comparingLong((DomicileDistanceVisitDifficultyWeight weight) -> -weight.domicileRoundTripDistance) .thenComparingDouble(weight -> weight.visit.getLocation().getLatitude()) .thenComparing(weight -> weight.visit, comparingLong(Visit::getId)); private final Visit visit; private final long domicileRoundTripDistance; public DomicileDistanceVisitDifficultyWeight(Visit visit, long domicileRoundTripDistance) { this.visit = visit; this.domicileRoundTripDistance = domicileRoundTripDistance; } @Override public int compareTo(DomicileDistanceVisitDifficultyWeight other) { return COMPARATOR.compare(this, other); } } }
Domicile domicile = tspSolution.getDomicile(); long domicileRoundTripDistance = domicile.getDistanceTo(visit) + visit.getDistanceTo(domicile); return new DomicileDistanceVisitDifficultyWeight(visit, domicileRoundTripDistance);
349
82
431
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/optional/score/TspEasyScoreCalculator.java
TspEasyScoreCalculator
calculateScore
class TspEasyScoreCalculator implements EasyScoreCalculator<TspSolution, SimpleLongScore> { @Override public SimpleLongScore calculateScore(TspSolution tspSolution) {<FILL_FUNCTION_BODY>} }
List<Visit> visitList = tspSolution.getVisitList(); Set<Visit> tailVisitSet = new HashSet<>(visitList); long score = 0L; for (Visit visit : visitList) { Standstill previousStandstill = visit.getPreviousStandstill(); if (previousStandstill != null) { score -= visit.getDistanceFromPreviousStandstill(); if (previousStandstill instanceof Visit) { tailVisitSet.remove(previousStandstill); } } } Domicile domicile = tspSolution.getDomicile(); for (Visit tailVisit : tailVisitSet) { if (tailVisit.getPreviousStandstill() != null) { score -= tailVisit.getDistanceTo(domicile); } } return SimpleLongScore.of(score);
64
214
278
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/persistence/AbstractSvgTspOutputBuilder.java
AbstractSvgTspOutputBuilder
determineSizeAndOffset
class AbstractSvgTspOutputBuilder extends AbstractTxtSolutionExporter.TxtOutputBuilder<TspSolution> { double width = 0; double height = 0; double offsetX = 0; double offsetY = 0; void writeSvgHeader() throws IOException { bufferedWriter.write("<?xml version='1.0'?>\n"); bufferedWriter.write( "<svg xmlns='http://www.w3.org/2000/svg' version='1.2' baseProfile='tiny' \n"); bufferedWriter.write("width='" + (width + offsetX) + "px' height='" + (height + offsetY) + "px'>\n"); } void determineSizeAndOffset(TspSolution solution) {<FILL_FUNCTION_BODY>} Visit findNextVisit(Standstill standstill) { for (Visit visit : solution.getVisitList()) { if (visit.getPreviousStandstill() == standstill) { return visit; } } return null; } }
Standstill standstill = solution.getDomicile(); while (standstill != null) { Location location = standstill.getLocation(); if (location.getLongitude() > width) { width = location.getLongitude(); } if (location.getLatitude() > height) { height = location.getLatitude(); } if (location.getLongitude() < offsetX) { offsetX = location.getLongitude(); } if (location.getLatitude() < offsetY) { offsetY = location.getLatitude(); } standstill = findNextVisit(standstill); } // We provide a slightly bigger canvas height *= 1.05; width *= 1.05; offsetY = -offsetY; offsetX = -offsetX;
283
213
496
<methods>public non-sealed void <init>() ,public void setBufferedWriter(java.io.BufferedWriter) ,public void setSolution(org.optaplanner.examples.tsp.domain.TspSolution) ,public abstract void writeSolution() throws java.io.IOException<variables>protected java.io.BufferedWriter bufferedWriter,protected org.optaplanner.examples.tsp.domain.TspSolution solution
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/persistence/SvgTspLineAndCircleExporter.java
SvgTspOutputBuilder
writeSolution
class SvgTspOutputBuilder extends AbstractSvgTspOutputBuilder { @Override public void writeSolution() throws IOException {<FILL_FUNCTION_BODY>} }
determineSizeAndOffset(solution); writeSvgHeader(); bufferedWriter.write("<g stroke='black' stroke-width='1'>\n"); double oldLat = 0; double oldLong = 0; Standstill standstill = solution.getDomicile(); Location home = standstill.getLocation(); while (standstill != null) { bufferedWriter.write(" <line x1='" + (oldLat + offsetX) + "' y1='" + (height - (oldLong + offsetY)) + "' "); Location location = standstill.getLocation(); bufferedWriter.write("x2='" + (location.getLongitude() + offsetX) + "' y2='" + (height - (location.getLatitude() + offsetY)) + "' />\n"); bufferedWriter.write(" <circle r='3' "); bufferedWriter.write("cx='" + (location.getLongitude() + offsetX) + "' cy='" + (height - (location.getLatitude() + offsetY)) + "' />\n"); oldLat = location.getLongitude(); oldLong = location.getLatitude(); standstill = findNextVisit(standstill); } bufferedWriter.write(" <line x1='" + (oldLat + offsetX) + "' y1='" + (height - (oldLong + offsetY)) + "' "); bufferedWriter .write("x2='" + (home.getLongitude() + offsetX) + "' y2='" + (height - (home.getLatitude() + offsetY)) + "' />n"); bufferedWriter.write("</g>\n"); bufferedWriter.write("</svg>\n");
51
444
495
<methods>public non-sealed void <init>() ,public abstract TxtOutputBuilder<org.optaplanner.examples.tsp.domain.TspSolution> createTxtOutputBuilder() ,public java.lang.String getOutputFileSuffix() ,public void writeSolution(org.optaplanner.examples.tsp.domain.TspSolution, java.io.File) <variables>protected static final java.lang.String DEFAULT_OUTPUT_FILE_SUFFIX
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/persistence/TspExporter.java
TspOutputBuilder
writeSolution
class TspOutputBuilder extends TxtOutputBuilder<TspSolution> { @Override public void writeSolution() throws IOException {<FILL_FUNCTION_BODY>} private Visit findNextVisit(Standstill standstill) { for (Visit visit : solution.getVisitList()) { if (visit.getPreviousStandstill() == standstill) { return visit; } } return null; } }
bufferedWriter.write("NAME : " + solution.getName() + "\n"); bufferedWriter.write("TYPE : TOUR\n"); bufferedWriter.write("DIMENSION : " + solution.getLocationList().size() + "\n"); bufferedWriter.write("TOUR_SECTION\n"); Standstill standstill = solution.getDomicile(); while (standstill != null) { bufferedWriter.write(standstill.getLocation().getId() + "\n"); standstill = findNextVisit(standstill); } bufferedWriter.write("EOF\n");
114
154
268
<methods>public non-sealed void <init>() ,public abstract TxtOutputBuilder<org.optaplanner.examples.tsp.domain.TspSolution> createTxtOutputBuilder() ,public java.lang.String getOutputFileSuffix() ,public void writeSolution(org.optaplanner.examples.tsp.domain.TspSolution, java.io.File) <variables>protected static final java.lang.String DEFAULT_OUTPUT_FILE_SUFFIX
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/persistence/TspImageStipplerImporter.java
TspImageStipplerInputBuilder
floydSteinbergDithering
class TspImageStipplerInputBuilder extends PngInputBuilder<TspSolution> { private TspSolution tspSolution; private int locationListSize; @Override public TspSolution readSolution() throws IOException { tspSolution = new TspSolution(0L); tspSolution.setName(SolutionBusiness.getBaseFileName(inputFile)); floydSteinbergDithering(); createVisitList(); BigInteger possibleSolutionSize = factorial(tspSolution.getLocationList().size() - 1); logger.info("TspSolution {} has {} locations with a search space of {}.", getInputId(), tspSolution.getLocationList().size(), getFlooredPossibleSolutionSize(possibleSolutionSize)); return tspSolution; } /** * As described by <a href="https://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering">Floyd-Steinberg * dithering</a>. */ private void floydSteinbergDithering() {<FILL_FUNCTION_BODY>} private void createVisitList() { List<Location> locationList = tspSolution.getLocationList(); List<Visit> visitList = new ArrayList<>(locationList.size() - 1); int count = 0; for (Location location : locationList) { if (count < 1) { Domicile domicile = new Domicile(location.getId(), location); tspSolution.setDomicile(domicile); } else { Visit visit = new Visit(location.getId(), location); // Notice that we leave the PlanningVariable properties on null visitList.add(visit); } count++; } tspSolution.setVisitList(visitList); } }
tspSolution.setDistanceType(DistanceType.AIR_DISTANCE); tspSolution.setDistanceUnitOfMeasurement("distance"); int width = image.getWidth(); int height = image.getHeight(); double[][] errorDiffusion = new double[width][height]; List<Location> locationList = new ArrayList<>(1000); long id = 0L; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgb = image.getRGB(x, y); int r = (rgb) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = (rgb >> 16) & 0xFF; double originalGray = (r + g + b) / GRAY_MAXIMUM; double diffusedGray = originalGray + errorDiffusion[x][y]; double error; if (diffusedGray <= 0.5) { Location location = new AirLocation(id, -y, x); id++; locationList.add(location); error = diffusedGray; } else { error = diffusedGray - 1.0; } if (x + 1 < width) { errorDiffusion[x + 1][y] += error * 7.0 / 16.0; } if (y + 1 < height) { if (x - 1 >= 0) { errorDiffusion[x - 1][y + 1] += error * 3.0 / 16.0; } errorDiffusion[x][y + 1] += error * 5.0 / 16.0; if (x + 1 < width) { errorDiffusion[x + 1][y + 1] += error * 1.0 / 16.0; } } } } tspSolution.setLocationList(locationList);
491
512
1,003
<methods>public non-sealed void <init>() ,public abstract PngInputBuilder<org.optaplanner.examples.tsp.domain.TspSolution> createPngInputBuilder() ,public java.lang.String getInputFileSuffix() ,public org.optaplanner.examples.tsp.domain.TspSolution readSolution(java.io.File) <variables>private static final java.lang.String DEFAULT_INPUT_FILE_SUFFIX
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/score/TspConstraintProvider.java
TspConstraintProvider
distanceFromLastVisitToDomicile
class TspConstraintProvider implements ConstraintProvider { @Override public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { return new Constraint[] { distanceToPreviousStandstill(constraintFactory), distanceFromLastVisitToDomicile(constraintFactory) }; } private Constraint distanceToPreviousStandstill(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Visit.class) .penalizeLong(SimpleLongScore.ONE, Visit::getDistanceFromPreviousStandstill) .asConstraint("Distance to previous standstill"); } private Constraint distanceFromLastVisitToDomicile(ConstraintFactory constraintFactory) {<FILL_FUNCTION_BODY>} }
return constraintFactory.forEach(Visit.class) .ifNotExists(Visit.class, Joiners.equal(visit -> visit, Visit::getPreviousStandstill)) .join(Domicile.class) .penalizeLong(SimpleLongScore.ONE, Visit::getDistanceTo) .asConstraint("Distance from last visit to domicile");
175
94
269
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/swingui/TspListPanel.java
TspListPanel
resetPanel
class TspListPanel extends JPanel implements Scrollable { public static final Dimension PREFERRED_SCROLLABLE_VIEWPORT_SIZE = new Dimension(800, 600); private static final Color HEADER_COLOR = TangoColorFactory.BUTTER_1; private final TspPanel tspPanel; public TspListPanel(TspPanel tspPanel) { this.tspPanel = tspPanel; setLayout(new GridLayout(0, 1)); } public void resetPanel(TspSolution tspSolution) {<FILL_FUNCTION_BODY>} protected void addVisitButton(TspSolution tspSolution, Visit visit) { JPanel visitPanel = new JPanel(new GridLayout(1, 2)); JButton button = new JButton(new VisitAction(visit)); visitPanel.add(button); String distanceLabelString; if (visit.getPreviousStandstill() == null) { distanceLabelString = "Unassigned"; } else { distanceLabelString = visit.getDistanceFromPreviousStandstill() + " " + tspSolution.getDistanceUnitOfMeasurement(); } JLabel distanceLabel = new JLabel(distanceLabelString); distanceLabel.setHorizontalAlignment(SwingConstants.RIGHT); visitPanel.add(distanceLabel); add(visitPanel); } public void updatePanel(TspSolution tspSolution) { resetPanel(tspSolution); } private class VisitAction extends AbstractAction { private Visit visit; public VisitAction(Visit visit) { super(visit.getLocation().toString()); this.visit = visit; } @Override public void actionPerformed(ActionEvent e) { TspSolution tspSolution = tspPanel.getSolution(); JComboBox previousStandstillListField = new JComboBox(); for (Standstill previousStandstill : tspSolution.getVisitList()) { previousStandstillListField.addItem(previousStandstill); } previousStandstillListField.addItem(tspSolution.getDomicile()); previousStandstillListField.setSelectedItem(visit.getPreviousStandstill()); int result = JOptionPane.showConfirmDialog(TspListPanel.this.getRootPane(), previousStandstillListField, "Visit " + visit.getLocation() + " after", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { Standstill toStandstill = (Standstill) previousStandstillListField.getSelectedItem(); tspPanel.changePreviousStandstill(visit, toStandstill); tspPanel.getWorkflowFrame().resetScreen(); } } } @Override public Dimension getPreferredScrollableViewportSize() { return PREFERRED_SCROLLABLE_VIEWPORT_SIZE; } @Override public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return 20; } @Override public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { return 20; } @Override public boolean getScrollableTracksViewportWidth() { if (getParent() instanceof JViewport) { return (getParent().getWidth() > getPreferredSize().width); } return false; } @Override public boolean getScrollableTracksViewportHeight() { if (getParent() instanceof JViewport) { return (getParent().getHeight() > getPreferredSize().height); } return false; } }
removeAll(); if (tspSolution.getVisitList().size() > 1000) { JLabel tooBigLabel = new JLabel("The dataset is too big to show."); add(tooBigLabel); return; } Domicile domicile = tspSolution.getDomicile(); add(new JLabel(domicile.getLocation().toString())); // TODO If the model contains the nextVisit like in vehicle routing, use that instead Map<Standstill, Visit> nextVisitMap = new LinkedHashMap<>(); List<Visit> unassignedVisitList = new ArrayList<>(); for (Visit visit : tspSolution.getVisitList()) { if (visit.getPreviousStandstill() != null) { nextVisitMap.put(visit.getPreviousStandstill(), visit); } else { unassignedVisitList.add(visit); } } Visit lastVisit = null; for (Visit visit = nextVisitMap.get(domicile); visit != null; visit = nextVisitMap.get(visit)) { addVisitButton(tspSolution, visit); lastVisit = visit; } if (lastVisit != null) { JPanel backToDomicilePanel = new JPanel(new GridLayout(1, 2)); backToDomicilePanel.add(new JLabel("Back to " + domicile.getLocation())); JLabel distanceLabel = new JLabel( lastVisit.getDistanceTo(domicile) + " " + tspSolution.getDistanceUnitOfMeasurement()); distanceLabel.setHorizontalAlignment(SwingConstants.RIGHT); backToDomicilePanel.add(distanceLabel); add(backToDomicilePanel); } add(new JLabel("Unassigned")); for (Visit visit : unassignedVisitList) { addVisitButton(tspSolution, visit); }
960
485
1,445
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/tsp/swingui/TspPanel.java
TspPanel
insertLocationAndVisit
class TspPanel extends SolutionPanel<TspSolution> { public static final String LOGO_PATH = "/org/optaplanner/examples/tsp/swingui/tspLogo.png"; private TspWorldPanel tspWorldPanel; private TspListPanel tspListPanel; private Long nextLocationId = null; public TspPanel() { setLayout(new BorderLayout()); JTabbedPane tabbedPane = new JTabbedPane(); tspWorldPanel = new TspWorldPanel(this); tspWorldPanel.setPreferredSize(PREFERRED_SCROLLABLE_VIEWPORT_SIZE); tabbedPane.add("World", tspWorldPanel); tspListPanel = new TspListPanel(this); JScrollPane tspListScrollPane = new JScrollPane(tspListPanel); tabbedPane.add("List", tspListScrollPane); add(tabbedPane, BorderLayout.CENTER); } @Override public boolean isWrapInScrollPane() { return false; } @Override public void resetPanel(TspSolution tspSolution) { tspWorldPanel.resetPanel(tspSolution); tspListPanel.resetPanel(tspSolution); resetNextLocationId(); } private void resetNextLocationId() { long highestLocationId = 0L; for (Location location : getSolution().getLocationList()) { if (highestLocationId < location.getId()) { highestLocationId = location.getId(); } } nextLocationId = highestLocationId + 1L; } @Override public void updatePanel(TspSolution tspSolution) { tspWorldPanel.updatePanel(tspSolution); tspListPanel.updatePanel(tspSolution); } public SolverAndPersistenceFrame getWorkflowFrame() { return solverAndPersistenceFrame; } public void insertLocationAndVisit(double longitude, double latitude) {<FILL_FUNCTION_BODY>} public void connectStandstills(Standstill sourceStandstill, Standstill targetStandstill) { if (targetStandstill instanceof Domicile) { TspSolution tspSolution = getSolution(); Standstill lastStandstill = tspSolution.getDomicile(); for (Visit nextVisit = findNextVisit(tspSolution, lastStandstill); nextVisit != null; nextVisit = findNextVisit( tspSolution, lastStandstill)) { lastStandstill = nextVisit; } targetStandstill = sourceStandstill; sourceStandstill = lastStandstill; } if (targetStandstill instanceof Visit && (sourceStandstill instanceof Domicile || ((Visit) sourceStandstill).getPreviousStandstill() != null)) { changePreviousStandstill((Visit) targetStandstill, sourceStandstill); } solverAndPersistenceFrame.resetScreen(); } public Standstill findNearestStandstill(AirLocation clickLocation) { TspSolution tspSolution = getSolution(); Standstill standstill = tspSolution.getDomicile(); double minimumAirDistance = standstill.getLocation().getAirDistanceDoubleTo(clickLocation); for (Visit selectedVisit : tspSolution.getVisitList()) { double airDistance = selectedVisit.getLocation().getAirDistanceDoubleTo(clickLocation); if (airDistance < minimumAirDistance) { standstill = selectedVisit; minimumAirDistance = airDistance; } } return standstill; } private static Visit findNextVisit(TspSolution tspSolution, Standstill standstill) { // Using an @InverseRelationShadowVariable on the model like in vehicle routing is far more efficient for (Visit visit : tspSolution.getVisitList()) { if (visit.getPreviousStandstill() == standstill) { return visit; } } return null; } public void changePreviousStandstill(Visit visit, Standstill toStandstill) { doProblemChange((workingSolution, problemChangeDirector) -> problemChangeDirector.lookUpWorkingObject(visit) .ifPresentOrElse(workingVisit -> { Standstill workingToStandstill = problemChangeDirector.lookUpWorkingObjectOrFail(toStandstill); Visit oldNextVisit = findNextVisit(workingSolution, workingVisit); Visit newNextVisit = findNextVisit(workingSolution, workingToStandstill); Standstill oldPreviousStandstill = workingVisit.getPreviousStandstill(); // Close the old chain if (oldNextVisit != null) { problemChangeDirector.changeVariable( oldNextVisit, "previousStandstill", v -> v.setPreviousStandstill(oldPreviousStandstill)); } // Change the entity problemChangeDirector.changeVariable( workingVisit, "previousStandstill", v -> v.setPreviousStandstill(workingToStandstill)); // Reroute the new chain if (newNextVisit != null) { problemChangeDirector.changeVariable( newNextVisit, "previousStandstill", v -> v.setPreviousStandstill(workingVisit)); } }, () -> logger.info("Skipping problem change due to visit ({}) deleted.", visit))); } }
final Location newLocation; switch (getSolution().getDistanceType()) { case AIR_DISTANCE: newLocation = new AirLocation(nextLocationId, latitude, longitude); break; case ROAD_DISTANCE: logger.warn("Adding locations for a road distance dataset is not supported."); return; default: throw new IllegalStateException("The distanceType (" + getSolution().getDistanceType() + ") is not implemented."); } nextLocationId++; logger.info("Scheduling insertion of newLocation ({}).", newLocation); doProblemChange((tspSolution, problemChangeDirector) -> { // A SolutionCloner does not clone problem fact lists (such as locationList) // Shallow clone the locationList so only workingSolution is affected, not bestSolution or guiSolution tspSolution.setLocationList(new ArrayList<>(tspSolution.getLocationList())); // Add the problem fact itself problemChangeDirector.addProblemFact(newLocation, tspSolution.getLocationList()::add); Visit newVisit = new Visit(newLocation.getId(), newLocation); // A SolutionCloner clones planning entity lists (such as visitList), so no need to clone the visitList here // Add the planning entity itself problemChangeDirector.addEntity(newVisit, tspSolution.getVisitList()::add); });
1,352
358
1,710
<methods>public non-sealed void <init>() ,public java.awt.Color determinePlanningEntityColor(java.lang.Object, java.lang.Object) ,public java.lang.String determinePlanningEntityTooltip(java.lang.Object) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.tsp.domain.TspSolution>) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.tsp.domain.TspSolution>, boolean) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public org.optaplanner.examples.tsp.domain.TspSolution getSolution() ,public SolutionBusiness<org.optaplanner.examples.tsp.domain.TspSolution,?> getSolutionBusiness() ,public SolverAndPersistenceFrame<org.optaplanner.examples.tsp.domain.TspSolution> getSolverAndPersistenceFrame() ,public java.lang.String getUsageExplanationPath() ,public boolean isIndictmentHeatMapEnabled() ,public boolean isUseIndictmentColor() ,public boolean isWrapInScrollPane() ,public abstract void resetPanel(org.optaplanner.examples.tsp.domain.TspSolution) ,public void setSolutionBusiness(SolutionBusiness<org.optaplanner.examples.tsp.domain.TspSolution,?>) ,public void setSolverAndPersistenceFrame(SolverAndPersistenceFrame<org.optaplanner.examples.tsp.domain.TspSolution>) ,public void setUseIndictmentColor(boolean) ,public void updatePanel(org.optaplanner.examples.tsp.domain.TspSolution) <variables>protected static final java.awt.Color[][] INDICTMENT_COLORS,public static final java.awt.Dimension PREFERRED_SCROLLABLE_VIEWPORT_SIZE,protected static final java.lang.String USAGE_EXPLANATION_PATH,protected double[] indictmentMinimumLevelNumbers,protected final transient Logger logger,protected org.optaplanner.swing.impl.TangoColorFactory normalColorFactory,protected SolutionBusiness<org.optaplanner.examples.tsp.domain.TspSolution,?> solutionBusiness,protected SolverAndPersistenceFrame<org.optaplanner.examples.tsp.domain.TspSolution> solverAndPersistenceFrame,protected boolean useIndictmentColor
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/domain/Customer.java
Customer
getDistanceFromPreviousStandstill
class Customer extends AbstractPersistable implements LocationAware { protected Location location; protected int demand; // Shadow variables protected Vehicle vehicle; protected Customer previousCustomer; protected Customer nextCustomer; public Customer() { } public Customer(long id, Location location, int demand) { super(id); this.location = location; this.demand = demand; } @Override public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public int getDemand() { return demand; } public void setDemand(int demand) { this.demand = demand; } @InverseRelationShadowVariable(sourceVariableName = "customers") public Vehicle getVehicle() { return vehicle; } public void setVehicle(Vehicle vehicle) { this.vehicle = vehicle; } @PreviousElementShadowVariable(sourceVariableName = "customers") public Customer getPreviousCustomer() { return previousCustomer; } public void setPreviousCustomer(Customer previousCustomer) { this.previousCustomer = previousCustomer; } @NextElementShadowVariable(sourceVariableName = "customers") public Customer getNextCustomer() { return nextCustomer; } public void setNextCustomer(Customer nextCustomer) { this.nextCustomer = nextCustomer; } // ************************************************************************ // Complex methods // ************************************************************************ @JsonIgnore public long getDistanceFromPreviousStandstill() {<FILL_FUNCTION_BODY>} @JsonIgnore public long getDistanceToDepot() { return location.getDistanceTo(vehicle.getLocation()); } @Override public String toString() { if (location.getName() == null) { return super.toString(); } return location.getName(); } }
if (vehicle == null) { throw new IllegalStateException( "This method must not be called when the shadow variables are not initialized yet."); } if (previousCustomer == null) { return vehicle.getLocation().getDistanceTo(location); } return previousCustomer.getLocation().getDistanceTo(location);
524
85
609
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/domain/Depot.java
Depot
toString
class Depot extends AbstractPersistable { protected Location location; public Depot() { } public Depot(long id, Location location) { super(id); this.location = location; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
if (location.getName() == null) { return super.toString(); } return location.getName();
127
32
159
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/domain/Vehicle.java
Vehicle
toString
class Vehicle extends AbstractPersistable implements LocationAware { protected int capacity; protected Depot depot; @PlanningListVariable protected List<Customer> customers = new ArrayList<>(); public Vehicle() { } public Vehicle(long id, int capacity, Depot depot) { super(id); this.capacity = capacity; this.depot = depot; } public int getCapacity() { return capacity; } public void setCapacity(int capacity) { this.capacity = capacity; } public Depot getDepot() { return depot; } public void setDepot(Depot depot) { this.depot = depot; } public List<Customer> getCustomers() { return customers; } public void setCustomers(List<Customer> customers) { this.customers = customers; } // ************************************************************************ // Complex methods // ************************************************************************ @Override @JsonIgnore public Location getLocation() { return depot.getLocation(); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
Location location = getLocation(); if (location.getName() == null) { return super.toString(); } return location.getName() + "/" + super.toString();
329
48
377
<methods>public long getId() ,public java.lang.String toString() <variables>protected java.lang.Long id
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/domain/location/AirLocation.java
AirLocation
getDistanceTo
class AirLocation extends Location { public AirLocation() { } public AirLocation(long id, double latitude, double longitude) { super(id, latitude, longitude); } @Override public long getDistanceTo(Location location) {<FILL_FUNCTION_BODY>} }
double distance = getAirDistanceDoubleTo(location); // Multiplied by 1000 to avoid floating point arithmetic rounding errors return (long) (distance * 1000.0 + 0.5);
84
57
141
<methods>public void <init>() ,public void <init>(long) ,public void <init>(long, double, double) ,public double getAirDistanceDoubleTo(org.optaplanner.examples.vehiclerouting.domain.location.Location) ,public double getAngle(org.optaplanner.examples.vehiclerouting.domain.location.Location) ,public abstract long getDistanceTo(org.optaplanner.examples.vehiclerouting.domain.location.Location) ,public double getLatitude() ,public double getLongitude() ,public java.lang.String getName() ,public void setLatitude(double) ,public void setLongitude(double) ,public void setName(java.lang.String) ,public java.lang.String toString() <variables>protected double latitude,protected double longitude,protected java.lang.String name
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/domain/location/segmented/HubSegmentLocation.java
HubSegmentLocation
getDistanceDouble
class HubSegmentLocation extends Location { // Prefer Map over array or List because customers might be added and removed in real-time planning. protected Map<RoadSegmentLocation, Double> nearbyTravelDistanceMap; protected Map<HubSegmentLocation, Double> hubTravelDistanceMap; public HubSegmentLocation() { } public HubSegmentLocation(long id) { super(id); } public HubSegmentLocation(long id, double latitude, double longitude) { super(id, latitude, longitude); } @JsonSerialize(keyUsing = KeySerializer.class) @JsonDeserialize(keyUsing = RoadSegmentLocationKeyDeserializer.class) public Map<RoadSegmentLocation, Double> getNearbyTravelDistanceMap() { return nearbyTravelDistanceMap; } public void setNearbyTravelDistanceMap(Map<RoadSegmentLocation, Double> nearbyTravelDistanceMap) { this.nearbyTravelDistanceMap = nearbyTravelDistanceMap; } @JsonSerialize(keyUsing = KeySerializer.class) @JsonDeserialize(keyUsing = HubSegmentLocationKeyDeserializer.class) public Map<HubSegmentLocation, Double> getHubTravelDistanceMap() { return hubTravelDistanceMap; } public void setHubTravelDistanceMap(Map<HubSegmentLocation, Double> hubTravelDistanceMap) { this.hubTravelDistanceMap = hubTravelDistanceMap; } @Override public long getDistanceTo(Location location) { double distance; if (location instanceof RoadSegmentLocation) { distance = getDistanceDouble((RoadSegmentLocation) location); } else { distance = hubTravelDistanceMap.get((HubSegmentLocation) location); } // Multiplied by 1000 to avoid floating point arithmetic rounding errors return (long) (distance * 1000.0 + 0.5); } public double getDistanceDouble(RoadSegmentLocation location) {<FILL_FUNCTION_BODY>} protected double getShortestDistanceDoubleThroughOtherHub(RoadSegmentLocation location) { double shortestDistance = Double.MAX_VALUE; // Don't use location.getHubTravelDistanceMap().keySet() instead because distances aren't always paired for (Map.Entry<HubSegmentLocation, Double> otherHubEntry : hubTravelDistanceMap.entrySet()) { HubSegmentLocation otherHub = otherHubEntry.getKey(); Double otherHubNearbyDistance = otherHub.nearbyTravelDistanceMap.get(location); if (otherHubNearbyDistance != null) { double distance = otherHubEntry.getValue() + otherHubNearbyDistance; if (distance < shortestDistance) { shortestDistance = distance; } } } return shortestDistance; } }
Double distance = nearbyTravelDistanceMap.get(location); if (distance == null) { // location isn't nearby distance = getShortestDistanceDoubleThroughOtherHub(location); } return distance;
720
58
778
<methods>public void <init>() ,public void <init>(long) ,public void <init>(long, double, double) ,public double getAirDistanceDoubleTo(org.optaplanner.examples.vehiclerouting.domain.location.Location) ,public double getAngle(org.optaplanner.examples.vehiclerouting.domain.location.Location) ,public abstract long getDistanceTo(org.optaplanner.examples.vehiclerouting.domain.location.Location) ,public double getLatitude() ,public double getLongitude() ,public java.lang.String getName() ,public void setLatitude(double) ,public void setLongitude(double) ,public void setName(java.lang.String) ,public java.lang.String toString() <variables>protected double latitude,protected double longitude,protected java.lang.String name
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/domain/location/segmented/RoadSegmentLocation.java
RoadSegmentLocation
getShortestDistanceDoubleThroughHubs
class RoadSegmentLocation extends Location { // Prefer Map over array or List because customers might be added and removed in real-time planning. protected Map<RoadSegmentLocation, Double> nearbyTravelDistanceMap; protected Map<HubSegmentLocation, Double> hubTravelDistanceMap; public RoadSegmentLocation() { } public RoadSegmentLocation(long id) { super(id); } public RoadSegmentLocation(long id, double latitude, double longitude) { super(id, latitude, longitude); } @JsonSerialize(keyUsing = KeySerializer.class) @JsonDeserialize(keyUsing = RoadSegmentLocationKeyDeserializer.class) public Map<RoadSegmentLocation, Double> getNearbyTravelDistanceMap() { return nearbyTravelDistanceMap; } public void setNearbyTravelDistanceMap(Map<RoadSegmentLocation, Double> nearbyTravelDistanceMap) { this.nearbyTravelDistanceMap = nearbyTravelDistanceMap; } @JsonSerialize(keyUsing = KeySerializer.class) @JsonDeserialize(keyUsing = HubSegmentLocationKeyDeserializer.class) public Map<HubSegmentLocation, Double> getHubTravelDistanceMap() { return hubTravelDistanceMap; } public void setHubTravelDistanceMap(Map<HubSegmentLocation, Double> hubTravelDistanceMap) { this.hubTravelDistanceMap = hubTravelDistanceMap; } @Override public long getDistanceTo(Location location) { Double distance = getDistanceDouble((RoadSegmentLocation) location); // Multiplied by 1000 to avoid floating point arithmetic rounding errors return (long) (distance * 1000.0 + 0.5); } public Double getDistanceDouble(RoadSegmentLocation location) { Double distance = nearbyTravelDistanceMap.get(location); if (distance == null) { // location isn't nearby distance = getShortestDistanceDoubleThroughHubs(location); } return distance; } protected double getShortestDistanceDoubleThroughHubs(RoadSegmentLocation location) {<FILL_FUNCTION_BODY>} }
double shortestDistance = Double.MAX_VALUE; for (Map.Entry<HubSegmentLocation, Double> entry : hubTravelDistanceMap.entrySet()) { double distance = entry.getValue(); distance += entry.getKey().getDistanceDouble(location); if (distance < shortestDistance) { shortestDistance = distance; } } return shortestDistance;
558
98
656
<methods>public void <init>() ,public void <init>(long) ,public void <init>(long, double, double) ,public double getAirDistanceDoubleTo(org.optaplanner.examples.vehiclerouting.domain.location.Location) ,public double getAngle(org.optaplanner.examples.vehiclerouting.domain.location.Location) ,public abstract long getDistanceTo(org.optaplanner.examples.vehiclerouting.domain.location.Location) ,public double getLatitude() ,public double getLongitude() ,public java.lang.String getName() ,public void setLatitude(double) ,public void setLongitude(double) ,public void setName(java.lang.String) ,public java.lang.String toString() <variables>protected double latitude,protected double longitude,protected java.lang.String name
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/domain/solver/DepotAngleCustomerDifficultyWeightFactory.java
DepotAngleCustomerDifficultyWeightFactory
createSorterWeight
class DepotAngleCustomerDifficultyWeightFactory implements SelectionSorterWeightFactory<VehicleRoutingSolution, Customer> { @Override public DepotAngleCustomerDifficultyWeight createSorterWeight(VehicleRoutingSolution vehicleRoutingSolution, Customer customer) {<FILL_FUNCTION_BODY>} public static class DepotAngleCustomerDifficultyWeight implements Comparable<DepotAngleCustomerDifficultyWeight> { private static final Comparator<DepotAngleCustomerDifficultyWeight> COMPARATOR = comparingDouble( (DepotAngleCustomerDifficultyWeight weight) -> weight.depotAngle) .thenComparingLong(weight -> weight.depotRoundTripDistance) // Ascending (further from the depot are more difficult) .thenComparing(weight -> weight.customer, comparingLong(Customer::getId)); private final Customer customer; private final double depotAngle; private final long depotRoundTripDistance; public DepotAngleCustomerDifficultyWeight(Customer customer, double depotAngle, long depotRoundTripDistance) { this.customer = customer; this.depotAngle = depotAngle; this.depotRoundTripDistance = depotRoundTripDistance; } @Override public int compareTo(DepotAngleCustomerDifficultyWeight other) { return COMPARATOR.compare(this, other); } } }
Depot depot = vehicleRoutingSolution.getDepotList().get(0); return new DepotAngleCustomerDifficultyWeight(customer, customer.getLocation().getAngle(depot.getLocation()), customer.getLocation().getDistanceTo(depot.getLocation()) + depot.getLocation().getDistanceTo(customer.getLocation()));
382
93
475
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/domain/timewindowed/TimeWindowedCustomer.java
TimeWindowedCustomer
getTimeWindowGapTo
class TimeWindowedCustomer extends Customer { // Times are multiplied by 1000 to avoid floating point arithmetic rounding errors private long readyTime; private long dueTime; private long serviceDuration; // Shadow variable private Long arrivalTime; public TimeWindowedCustomer() { } public TimeWindowedCustomer(long id, Location location, int demand, long readyTime, long dueTime, long serviceDuration) { super(id, location, demand); this.readyTime = readyTime; this.dueTime = dueTime; this.serviceDuration = serviceDuration; } /** * @return a positive number, the time multiplied by 1000 to avoid floating point arithmetic rounding errors */ public long getReadyTime() { return readyTime; } public void setReadyTime(long readyTime) { this.readyTime = readyTime; } /** * @return a positive number, the time multiplied by 1000 to avoid floating point arithmetic rounding errors */ public long getDueTime() { return dueTime; } public void setDueTime(long dueTime) { this.dueTime = dueTime; } /** * @return a positive number, the time multiplied by 1000 to avoid floating point arithmetic rounding errors */ public long getServiceDuration() { return serviceDuration; } public void setServiceDuration(long serviceDuration) { this.serviceDuration = serviceDuration; } /** * @return a positive number, the time multiplied by 1000 to avoid floating point arithmetic rounding errors */ // Arguable, to adhere to API specs (although this works), nextCustomer should also be a source, // because this shadow must be triggered after nextCustomer (but there is no need to be triggered by nextCustomer) @ShadowVariable(variableListenerClass = ArrivalTimeUpdatingVariableListener.class, sourceVariableName = "vehicle") @ShadowVariable(variableListenerClass = ArrivalTimeUpdatingVariableListener.class, sourceVariableName = "previousCustomer") public Long getArrivalTime() { return arrivalTime; } public void setArrivalTime(Long arrivalTime) { this.arrivalTime = arrivalTime; } // ************************************************************************ // Complex methods // ************************************************************************ /** * @return a positive number, the time multiplied by 1000 to avoid floating point arithmetic rounding errors */ public Long getDepartureTime() { if (arrivalTime == null) { return null; } return Math.max(arrivalTime, readyTime) + serviceDuration; } public boolean isArrivalBeforeReadyTime() { return arrivalTime != null && arrivalTime < readyTime; } public boolean isArrivalAfterDueTime() { return arrivalTime != null && dueTime < arrivalTime; } /** * @return a positive number, the time multiplied by 1000 to avoid floating point arithmetic rounding errors */ public long getTimeWindowGapTo(TimeWindowedCustomer other) {<FILL_FUNCTION_BODY>} }
// dueTime doesn't account for serviceDuration long latestDepartureTime = dueTime + serviceDuration; long otherLatestDepartureTime = other.getDueTime() + other.getServiceDuration(); if (latestDepartureTime < other.getReadyTime()) { return other.getReadyTime() - latestDepartureTime; } if (otherLatestDepartureTime < readyTime) { return readyTime - otherLatestDepartureTime; } return 0L;
839
130
969
<methods>public void <init>() ,public void <init>(long, org.optaplanner.examples.vehiclerouting.domain.location.Location, int) ,public int getDemand() ,public long getDistanceFromPreviousStandstill() ,public long getDistanceToDepot() ,public org.optaplanner.examples.vehiclerouting.domain.location.Location getLocation() ,public org.optaplanner.examples.vehiclerouting.domain.Customer getNextCustomer() ,public org.optaplanner.examples.vehiclerouting.domain.Customer getPreviousCustomer() ,public org.optaplanner.examples.vehiclerouting.domain.Vehicle getVehicle() ,public void setDemand(int) ,public void setLocation(org.optaplanner.examples.vehiclerouting.domain.location.Location) ,public void setNextCustomer(org.optaplanner.examples.vehiclerouting.domain.Customer) ,public void setPreviousCustomer(org.optaplanner.examples.vehiclerouting.domain.Customer) ,public void setVehicle(org.optaplanner.examples.vehiclerouting.domain.Vehicle) ,public java.lang.String toString() <variables>protected int demand,protected org.optaplanner.examples.vehiclerouting.domain.location.Location location,protected org.optaplanner.examples.vehiclerouting.domain.Customer nextCustomer,protected org.optaplanner.examples.vehiclerouting.domain.Customer previousCustomer,protected org.optaplanner.examples.vehiclerouting.domain.Vehicle vehicle
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/domain/timewindowed/solver/ArrivalTimeUpdatingVariableListener.java
ArrivalTimeUpdatingVariableListener
afterEntityAdded
class ArrivalTimeUpdatingVariableListener implements VariableListener<VehicleRoutingSolution, Customer> { @Override public void beforeEntityAdded(ScoreDirector<VehicleRoutingSolution> scoreDirector, Customer customer) { // Do nothing } @Override public void afterEntityAdded(ScoreDirector<VehicleRoutingSolution> scoreDirector, Customer customer) {<FILL_FUNCTION_BODY>} @Override public void beforeVariableChanged(ScoreDirector<VehicleRoutingSolution> scoreDirector, Customer customer) { // Do nothing } @Override public void afterVariableChanged(ScoreDirector<VehicleRoutingSolution> scoreDirector, Customer customer) { if (customer instanceof TimeWindowedCustomer) { updateArrivalTime(scoreDirector, (TimeWindowedCustomer) customer); } } @Override public void beforeEntityRemoved(ScoreDirector<VehicleRoutingSolution> scoreDirector, Customer customer) { // Do nothing } @Override public void afterEntityRemoved(ScoreDirector<VehicleRoutingSolution> scoreDirector, Customer customer) { if (customer instanceof TimeWindowedCustomer) { updateArrivalTime(scoreDirector, (TimeWindowedCustomer) customer); } } protected void updateArrivalTime(ScoreDirector<VehicleRoutingSolution> scoreDirector, TimeWindowedCustomer sourceCustomer) { if (sourceCustomer.getVehicle() == null) { if (sourceCustomer.getArrivalTime() != null) { scoreDirector.beforeVariableChanged(sourceCustomer, "arrivalTime"); sourceCustomer.setArrivalTime(null); scoreDirector.afterVariableChanged(sourceCustomer, "arrivalTime"); } return; } Customer previousCustomer = sourceCustomer.getPreviousCustomer(); Long departureTime; if (previousCustomer == null) { departureTime = ((TimeWindowedDepot) sourceCustomer.getVehicle().getDepot()).getReadyTime(); } else { departureTime = ((TimeWindowedCustomer) previousCustomer).getDepartureTime(); } TimeWindowedCustomer shadowCustomer = sourceCustomer; Long arrivalTime = calculateArrivalTime(shadowCustomer, departureTime); while (shadowCustomer != null && !Objects.equals(shadowCustomer.getArrivalTime(), arrivalTime)) { scoreDirector.beforeVariableChanged(shadowCustomer, "arrivalTime"); shadowCustomer.setArrivalTime(arrivalTime); scoreDirector.afterVariableChanged(shadowCustomer, "arrivalTime"); departureTime = shadowCustomer.getDepartureTime(); shadowCustomer = (TimeWindowedCustomer) shadowCustomer.getNextCustomer(); arrivalTime = calculateArrivalTime(shadowCustomer, departureTime); } } private Long calculateArrivalTime(TimeWindowedCustomer customer, Long previousDepartureTime) { if (customer == null || previousDepartureTime == null) { return null; } return previousDepartureTime + customer.getDistanceFromPreviousStandstill(); } }
if (customer instanceof TimeWindowedCustomer) { updateArrivalTime(scoreDirector, (TimeWindowedCustomer) customer); }
799
38
837
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/persistence/VehicleRoutingSolutionFileIO.java
VehicleRoutingSolutionFileIO
deduplicateRoadLocations
class VehicleRoutingSolutionFileIO extends AbstractJsonSolutionFileIO<VehicleRoutingSolution> { public VehicleRoutingSolutionFileIO() { super(VehicleRoutingSolution.class); } @Override public VehicleRoutingSolution read(File inputSolutionFile) { VehicleRoutingSolution vehicleRoutingSolution = super.read(inputSolutionFile); if (vehicleRoutingSolution.getDistanceType() == DistanceType.ROAD_DISTANCE) { deduplicateRoadLocations(vehicleRoutingSolution); } else if (vehicleRoutingSolution.getDistanceType() == DistanceType.SEGMENTED_ROAD_DISTANCE) { deduplicateRoadSegments(vehicleRoutingSolution); } return vehicleRoutingSolution; } private void deduplicateRoadLocations(VehicleRoutingSolution vehicleRoutingSolution) {<FILL_FUNCTION_BODY>} private void deduplicateRoadSegments(VehicleRoutingSolution vehicleRoutingSolution) { var hubSegmentLocationList = vehicleRoutingSolution.getLocationList().stream() .filter(location -> location instanceof HubSegmentLocation) .map(location -> (HubSegmentLocation) location) .collect(Collectors.toList()); var roadSegmentLocationList = vehicleRoutingSolution.getLocationList().stream() .filter(location -> location instanceof RoadSegmentLocation) .map(location -> (RoadSegmentLocation) location) .collect(Collectors.toList()); var hubSegmentLocationsById = hubSegmentLocationList.stream() .collect(Collectors.toMap(HubSegmentLocation::getId, Function.identity())); var roadSegmentLocationsById = roadSegmentLocationList.stream() .collect(Collectors.toMap(RoadSegmentLocation::getId, Function.identity())); for (HubSegmentLocation hubSegmentLocation : hubSegmentLocationList) { var newHubTravelDistanceMap = deduplicateMap(hubSegmentLocation.getHubTravelDistanceMap(), hubSegmentLocationsById, HubSegmentLocation::getId); var newNearbyTravelDistanceMap = deduplicateMap(hubSegmentLocation.getNearbyTravelDistanceMap(), roadSegmentLocationsById, RoadSegmentLocation::getId); hubSegmentLocation.setHubTravelDistanceMap(newHubTravelDistanceMap); hubSegmentLocation.setNearbyTravelDistanceMap(newNearbyTravelDistanceMap); } for (RoadSegmentLocation roadSegmentLocation : roadSegmentLocationList) { var newHubTravelDistanceMap = deduplicateMap(roadSegmentLocation.getHubTravelDistanceMap(), hubSegmentLocationsById, HubSegmentLocation::getId); var newNearbyTravelDistanceMap = deduplicateMap(roadSegmentLocation.getNearbyTravelDistanceMap(), roadSegmentLocationsById, RoadSegmentLocation::getId); roadSegmentLocation.setHubTravelDistanceMap(newHubTravelDistanceMap); roadSegmentLocation.setNearbyTravelDistanceMap(newNearbyTravelDistanceMap); } } }
var roadLocationList = vehicleRoutingSolution.getLocationList().stream() .filter(location -> location instanceof RoadLocation) .map(location -> (RoadLocation) location) .collect(Collectors.toList()); var locationsById = roadLocationList.stream() .collect(Collectors.toMap(RoadLocation::getId, Function.identity())); /* * Replace the duplicate RoadLocation instances in the travelDistanceMap by references to instances from * the locationList. */ for (RoadLocation roadLocation : roadLocationList) { var newTravelDistanceMap = deduplicateMap(roadLocation.getTravelDistanceMap(), locationsById, RoadLocation::getId); roadLocation.setTravelDistanceMap(newTravelDistanceMap); }
786
194
980
<methods>public void <init>(Class<org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution>) ,public void <init>(Class<org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution>, ObjectMapper) <variables>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/score/VehicleRoutingConstraintProvider.java
VehicleRoutingConstraintProvider
vehicleCapacity
class VehicleRoutingConstraintProvider implements ConstraintProvider { @Override public Constraint[] defineConstraints(ConstraintFactory factory) { return new Constraint[] { vehicleCapacity(factory), distanceToPreviousStandstill(factory), distanceFromLastCustomerToDepot(factory), arrivalAfterDueTime(factory) }; } // ************************************************************************ // Hard constraints // ************************************************************************ protected Constraint vehicleCapacity(ConstraintFactory factory) {<FILL_FUNCTION_BODY>} // ************************************************************************ // Soft constraints // ************************************************************************ protected Constraint distanceToPreviousStandstill(ConstraintFactory factory) { return factory.forEach(Customer.class) .filter(customer -> customer.getVehicle() != null) .penalizeLong(HardSoftLongScore.ONE_SOFT, Customer::getDistanceFromPreviousStandstill) .asConstraint("distanceToPreviousStandstill"); } protected Constraint distanceFromLastCustomerToDepot(ConstraintFactory factory) { return factory.forEach(Customer.class) .filter(customer -> customer.getVehicle() != null && customer.getNextCustomer() == null) .penalizeLong(HardSoftLongScore.ONE_SOFT, Customer::getDistanceToDepot) .asConstraint("distanceFromLastCustomerToDepot"); } // ************************************************************************ // TimeWindowed: additional hard constraints // ************************************************************************ protected Constraint arrivalAfterDueTime(ConstraintFactory factory) { return factory.forEach(TimeWindowedCustomer.class) .filter(customer -> customer.getVehicle() != null && customer.getArrivalTime() > customer.getDueTime()) .penalizeLong(HardSoftLongScore.ONE_HARD, customer -> customer.getArrivalTime() - customer.getDueTime()) .asConstraint("arrivalAfterDueTime"); } }
return factory.forEach(Customer.class) .filter(customer -> customer.getVehicle() != null) .groupBy(Customer::getVehicle, sum(Customer::getDemand)) .filter((vehicle, demand) -> demand > vehicle.getCapacity()) .penalizeLong(HardSoftLongScore.ONE_HARD, (vehicle, demand) -> demand - vehicle.getCapacity()) .asConstraint("vehicleCapacity");
494
124
618
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/swingui/VehicleRoutingPanel.java
VehicleRoutingPanel
insertLocationAndCustomer
class VehicleRoutingPanel extends SolutionPanel<VehicleRoutingSolution> { public static final String LOGO_PATH = "/org/optaplanner/examples/vehiclerouting/swingui/vehicleRoutingLogo.png"; private final VehicleRoutingWorldPanel vehicleRoutingWorldPanel; private final Random demandRandom = new Random(37); private Long nextLocationId = null; public VehicleRoutingPanel() { setLayout(new BorderLayout()); JTabbedPane tabbedPane = new JTabbedPane(); vehicleRoutingWorldPanel = new VehicleRoutingWorldPanel(this); vehicleRoutingWorldPanel.setPreferredSize(PREFERRED_SCROLLABLE_VIEWPORT_SIZE); tabbedPane.add("World", vehicleRoutingWorldPanel); add(tabbedPane, BorderLayout.CENTER); } @Override public boolean isWrapInScrollPane() { return false; } @Override public void resetPanel(VehicleRoutingSolution solution) { vehicleRoutingWorldPanel.resetPanel(solution); resetNextLocationId(); } private void resetNextLocationId() { long highestLocationId = 0L; for (Location location : getSolution().getLocationList()) { if (highestLocationId < location.getId()) { highestLocationId = location.getId(); } } nextLocationId = highestLocationId + 1L; } @Override public void updatePanel(VehicleRoutingSolution solution) { vehicleRoutingWorldPanel.updatePanel(solution); } public void insertLocationAndCustomer(double longitude, double latitude) {<FILL_FUNCTION_BODY>} protected Customer createCustomer(VehicleRoutingSolution solution, Location newLocation) { int demand = demandRandom.nextInt(10) + 1; // Demand must not be 0. if (solution instanceof TimeWindowedVehicleRoutingSolution) { TimeWindowedDepot timeWindowedDepot = (TimeWindowedDepot) solution.getDepotList().get(0); long windowTime = (timeWindowedDepot.getDueTime() - timeWindowedDepot.getReadyTime()) / 4L; long readyTime = demandRandom.longs(0, windowTime * 3L) .findAny() .orElseThrow(); return new TimeWindowedCustomer(newLocation.getId(), newLocation, demand, readyTime, readyTime + windowTime, Math.min(10000L, windowTime / 2L)); } else { return new Customer(newLocation.getId(), newLocation, demand); } } }
final Location newLocation; switch (getSolution().getDistanceType()) { case AIR_DISTANCE: newLocation = new AirLocation(nextLocationId, latitude, longitude); break; case ROAD_DISTANCE: logger.warn("Adding locations for a road distance dataset is not supported."); return; case SEGMENTED_ROAD_DISTANCE: logger.warn("Adding locations for a segmented road distance dataset is not supported."); return; default: throw new IllegalStateException("The distanceType (" + getSolution().getDistanceType() + ") is not implemented."); } nextLocationId++; logger.info("Scheduling insertion of newLocation ({}).", newLocation); doProblemChange((vehicleRoutingSolution, problemChangeDirector) -> { // A SolutionCloner does not clone problem fact lists (such as locationList) // Shallow clone the locationList so only workingSolution is affected, not bestSolution or guiSolution vehicleRoutingSolution.setLocationList(new ArrayList<>(vehicleRoutingSolution.getLocationList())); // Add the problem fact itself problemChangeDirector.addProblemFact(newLocation, vehicleRoutingSolution.getLocationList()::add); Customer newCustomer = createCustomer(vehicleRoutingSolution, newLocation); // A SolutionCloner clones planning entity lists (such as customerList), so no need to clone the customerList here // Add the planning entity itself problemChangeDirector.addProblemFact(newCustomer, vehicleRoutingSolution.getCustomerList()::add); });
694
411
1,105
<methods>public non-sealed void <init>() ,public java.awt.Color determinePlanningEntityColor(java.lang.Object, java.lang.Object) ,public java.lang.String determinePlanningEntityTooltip(java.lang.Object) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution>) ,public void doProblemChange(ProblemChange<org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution>, boolean) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution getSolution() ,public SolutionBusiness<org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution,?> getSolutionBusiness() ,public SolverAndPersistenceFrame<org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution> getSolverAndPersistenceFrame() ,public java.lang.String getUsageExplanationPath() ,public boolean isIndictmentHeatMapEnabled() ,public boolean isUseIndictmentColor() ,public boolean isWrapInScrollPane() ,public abstract void resetPanel(org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution) ,public void setSolutionBusiness(SolutionBusiness<org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution,?>) ,public void setSolverAndPersistenceFrame(SolverAndPersistenceFrame<org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution>) ,public void setUseIndictmentColor(boolean) ,public void updatePanel(org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution) <variables>protected static final java.awt.Color[][] INDICTMENT_COLORS,public static final java.awt.Dimension PREFERRED_SCROLLABLE_VIEWPORT_SIZE,protected static final java.lang.String USAGE_EXPLANATION_PATH,protected double[] indictmentMinimumLevelNumbers,protected final transient Logger logger,protected org.optaplanner.swing.impl.TangoColorFactory normalColorFactory,protected SolutionBusiness<org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution,?> solutionBusiness,protected SolverAndPersistenceFrame<org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution> solverAndPersistenceFrame,protected boolean useIndictmentColor
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/swingui/VehicleRoutingWorldPanel.java
VehicleRoutingWorldPanel
mousePressed
class VehicleRoutingWorldPanel extends JPanel { private final VehicleRoutingPanel vehicleRoutingPanel; private VehicleRoutingSolutionPainter solutionPainter = new VehicleRoutingSolutionPainter(); public VehicleRoutingWorldPanel(VehicleRoutingPanel vehicleRoutingPanel) { this.vehicleRoutingPanel = vehicleRoutingPanel; solutionPainter = new VehicleRoutingSolutionPainter(); addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { // TODO Not thread-safe during solving VehicleRoutingSolution solution = VehicleRoutingWorldPanel.this.vehicleRoutingPanel.getSolution(); if (solution != null) { resetPanel(solution); } } }); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) {<FILL_FUNCTION_BODY>} }); } public void resetPanel(VehicleRoutingSolution solution) { solutionPainter.reset(solution, getSize(), this); repaint(); } public void updatePanel(VehicleRoutingSolution solution) { resetPanel(solution); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); BufferedImage canvas = solutionPainter.getCanvas(); if (canvas != null) { g.drawImage(canvas, 0, 0, this); } } }
if (e.getButton() == MouseEvent.BUTTON2 || e.getButton() == MouseEvent.BUTTON3) { LatitudeLongitudeTranslator translator = solutionPainter.getTranslator(); if (translator != null) { double longitude = translator.translateXToLongitude(e.getX()); double latitude = translator.translateYToLatitude(e.getY()); VehicleRoutingWorldPanel.this.vehicleRoutingPanel.insertLocationAndCustomer(longitude, latitude); } }
413
146
559
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-operator/src/main/java/org/optaplanner/operator/impl/solver/OptaPlannerSolverReconciler.java
OptaPlannerSolverReconciler
reconcile
class OptaPlannerSolverReconciler implements Reconciler<OptaPlannerSolver>, ErrorStatusHandler<OptaPlannerSolver>, EventSourceInitializer<OptaPlannerSolver> { private KubernetesClient kubernetesClient; private final DeploymentDependentResource deploymentDependentResource; private final ArtemisQueueDependentResource inputQueueDependentResource; private final ArtemisQueueDependentResource outputQueueDependentResource; private final ConfigMapDependentResource configMapDependentResource; private final TriggerAuthenticationDependentResource triggerAuthenticationDependentResource; private final ScaledObjectDependentResource scaledObjectDependentResource; @Inject public OptaPlannerSolverReconciler(KubernetesClient kubernetesClient) { deploymentDependentResource = new DeploymentDependentResource(kubernetesClient); inputQueueDependentResource = new ArtemisQueueDependentResource(MessageAddress.INPUT, kubernetesClient); outputQueueDependentResource = new ArtemisQueueDependentResource(MessageAddress.OUTPUT, kubernetesClient); configMapDependentResource = new ConfigMapDependentResource(kubernetesClient); triggerAuthenticationDependentResource = new TriggerAuthenticationDependentResource(kubernetesClient); scaledObjectDependentResource = new ScaledObjectDependentResource(kubernetesClient); inputQueueDependentResource.setResourceDiscriminator(new ResourceIDMatcherDiscriminator<>( optaPlannerSolver -> new ResourceID(optaPlannerSolver.getInputMessageAddressName(), optaPlannerSolver.getMetadata().getNamespace()))); outputQueueDependentResource.setResourceDiscriminator(new ResourceIDMatcherDiscriminator<>( optaPlannerSolver -> new ResourceID(optaPlannerSolver.getOutputMessageAddressName(), optaPlannerSolver.getMetadata().getNamespace()))); } @Override public Map<String, EventSource> prepareEventSources(EventSourceContext<OptaPlannerSolver> context) { return EventSourceInitializer.nameEventSources(deploymentDependentResource.initEventSource(context), inputQueueDependentResource.initEventSource(context), outputQueueDependentResource.initEventSource(context), configMapDependentResource.initEventSource(context), triggerAuthenticationDependentResource.initEventSource(context), scaledObjectDependentResource.initEventSource(context)); } @Override public UpdateControl<OptaPlannerSolver> reconcile(OptaPlannerSolver solver, Context<OptaPlannerSolver> context) {<FILL_FUNCTION_BODY>} @Override public ErrorStatusUpdateControl<OptaPlannerSolver> updateErrorStatus(OptaPlannerSolver solver, Context<OptaPlannerSolver> context, Exception e) { solver.setStatus(OptaPlannerSolverStatus.error(solver.getMetadata().getGeneration(), e)); return ErrorStatusUpdateControl.updateStatus(solver); } }
boolean isReady = true; deploymentDependentResource.reconcile(solver, context); inputQueueDependentResource.reconcile(solver, context); outputQueueDependentResource.reconcile(solver, context); if (solver.getSpec().getScaling().isDynamic()) { triggerAuthenticationDependentResource.reconcile(solver, context); scaledObjectDependentResource.reconcile(solver, context); if (scaledObjectDependentResource.getSecondaryResource(solver, context).isEmpty() || triggerAuthenticationDependentResource.getSecondaryResource(solver, context).isEmpty()) { isReady = false; } } Optional<ArtemisQueue> inputQueue = inputQueueDependentResource.getSecondaryResource(solver, context); Optional<ArtemisQueue> outputQueue = outputQueueDependentResource.getSecondaryResource(solver, context); if (inputQueue.isEmpty() || outputQueue.isEmpty()) { isReady = false; } if (inputQueue.isPresent() && outputQueue.isPresent()) { configMapDependentResource.reconcile(solver, context); if (configMapDependentResource.getSecondaryResource(solver, context).isEmpty()) { isReady = false; } } if (isReady) { solver.setStatus(OptaPlannerSolverStatus.ready(solver.getMetadata().getGeneration())); solver.getStatus().setInputMessageAddress(inputQueue.get().getSpec().getQueueName()); solver.getStatus().setOutputMessageAddress(outputQueue.get().getSpec().getQueueName()); } else { solver.setStatus(OptaPlannerSolverStatus.unknown(solver.getMetadata().getGeneration())); } return UpdateControl.updateStatus(solver);
753
462
1,215
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-operator/src/main/java/org/optaplanner/operator/impl/solver/model/ConfigMapDependentResource.java
ConfigMapDependentResource
desired
class ConfigMapDependentResource extends CRUDKubernetesDependentResource<ConfigMap, OptaPlannerSolver> { public static final String SOLVER_MESSAGE_INPUT_KEY = "solver.message.input"; public static final String SOLVER_MESSAGE_OUTPUT_KEY = "solver.message.output"; public static final String SOLVER_MESSAGE_AMQ_HOST_KEY = "solver.amq.host"; public static final String SOLVER_MESSAGE_AMQ_PORT_KEY = "solver.amq.port"; public ConfigMapDependentResource(KubernetesClient kubernetesClient) { super(ConfigMap.class); setKubernetesClient(kubernetesClient); } @Override protected ConfigMap desired(OptaPlannerSolver solver, Context<OptaPlannerSolver> context) {<FILL_FUNCTION_BODY>} @Override public ConfigMap update(ConfigMap actual, ConfigMap target, OptaPlannerSolver solver, Context<OptaPlannerSolver> context) { ConfigMap resultingConfigMap = super.update(actual, target, solver, context); String namespace = actual.getMetadata().getNamespace(); getKubernetesClient() .pods() .inNamespace(namespace) .withLabel("app", solver.getMetadata().getName()) .delete(); return resultingConfigMap; } }
Map<String, String> data = new HashMap<>(); data.put(SOLVER_MESSAGE_INPUT_KEY, solver.getInputMessageAddressName()); data.put(SOLVER_MESSAGE_OUTPUT_KEY, solver.getOutputMessageAddressName()); data.put(SOLVER_MESSAGE_AMQ_HOST_KEY, solver.getSpec().getAmqBroker().getHost()); data.put(SOLVER_MESSAGE_AMQ_PORT_KEY, String.valueOf(solver.getSpec().getAmqBroker().getPort())); return new ConfigMapBuilder() .withNewMetadata() .withName(solver.getConfigMapName()) .withNamespace(solver.getNamespace()) .endMetadata() .withData(data) .build();
364
213
577
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-operator/src/main/java/org/optaplanner/operator/impl/solver/model/keda/ScaledObjectDependentResource.java
ScaledObjectDependentResource
desired
class ScaledObjectDependentResource extends CRUDKubernetesDependentResource<ScaledObject, OptaPlannerSolver> { public static final String ARTEMIS_QUEUE_TRIGGER = "artemis-queue"; /** * Required to scale down to zero pods. */ private static final int MIN_REPLICAS = 0; private static final int POLLING_INTERVAL = 10; private static final int COOLDOWN_PERIOD = 10; /** * The scaler increases replicas if the queue message count is greater than this value per active replica. */ private static final int TARGET_QUEUE_LENGTH = 1; public ScaledObjectDependentResource(KubernetesClient kubernetesClient) { super(ScaledObject.class); setKubernetesClient(kubernetesClient); } @Override protected ScaledObject desired(OptaPlannerSolver optaPlannerSolver, Context<OptaPlannerSolver> context) {<FILL_FUNCTION_BODY>} private ObjectMeta buildMetadata(OptaPlannerSolver optaPlannerSolver) { return new ObjectMetaBuilder() .withName(optaPlannerSolver.getScaledObjectName()) .withNamespace(optaPlannerSolver.getNamespace()) .build(); } }
AmqBroker amqBroker = optaPlannerSolver.getSpec().getAmqBroker(); TriggerMetadata triggerMetadata = new TriggerMetadata(); triggerMetadata.setBrokerAddress(optaPlannerSolver.getInputMessageAddressName()); triggerMetadata.setQueueName(optaPlannerSolver.getInputMessageAddressName()); triggerMetadata.setQueueLength(String.valueOf(TARGET_QUEUE_LENGTH)); triggerMetadata.setBrokerName(amqBroker.getBrokerName()); triggerMetadata.setManagementEndpoint(amqBroker.getManagementEndpoint()); Trigger trigger = new Trigger(); trigger.setType(ARTEMIS_QUEUE_TRIGGER); trigger.setMetadata(triggerMetadata); trigger.setName(optaPlannerSolver.getScaledObjectTriggerName()); trigger.setAuthenticationRef(new ResourceNameReference(optaPlannerSolver.getTriggerAuthenticationName())); ScaledObjectSpec spec = new ScaledObjectSpec(); spec.withTrigger(trigger); spec.setScaleTargetRef(new ResourceNameReference(optaPlannerSolver.getDeploymentName())); spec.setMinReplicaCount(MIN_REPLICAS); spec.setMaxReplicaCount(optaPlannerSolver.getSpec().getScaling().getReplicas()); spec.setPollingInterval(POLLING_INTERVAL); spec.setCooldownPeriod(COOLDOWN_PERIOD); ScaledObject scaledObject = new ScaledObject(); scaledObject.setSpec(spec); scaledObject.setMetadata(buildMetadata(optaPlannerSolver)); scaledObject.setStatus(new ScaledObject.ScaledObjectStatus()); return scaledObject;
345
437
782
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-operator/src/main/java/org/optaplanner/operator/impl/solver/model/keda/TriggerAuthenticationDependentResource.java
TriggerAuthenticationDependentResource
desired
class TriggerAuthenticationDependentResource extends CRUDKubernetesDependentResource<TriggerAuthentication, OptaPlannerSolver> { public static final String PARAM_USERNAME = "username"; public static final String PARAM_PASSWORD = "password"; public TriggerAuthenticationDependentResource(KubernetesClient kubernetesClient) { super(TriggerAuthentication.class); setKubernetesClient(kubernetesClient); } @Override protected TriggerAuthentication desired(OptaPlannerSolver optaPlannerSolver, Context<OptaPlannerSolver> context) {<FILL_FUNCTION_BODY>} }
final SecretKeySelector amqUsernameSecretKeySelector = optaPlannerSolver.getSpec().getAmqBroker().getUsernameSecretRef(); final SecretKeySelector amqPasswordSecretKeySelector = optaPlannerSolver.getSpec().getAmqBroker().getPasswordSecretRef(); TriggerAuthenticationSpec spec = new TriggerAuthenticationSpec() .withSecretTargetRef(SecretTargetRef.fromSecretKeySelector(PARAM_USERNAME, amqUsernameSecretKeySelector)) .withSecretTargetRef(SecretTargetRef.fromSecretKeySelector(PARAM_PASSWORD, amqPasswordSecretKeySelector)); ObjectMeta metadata = new ObjectMetaBuilder() .withName(optaPlannerSolver.getTriggerAuthenticationName()) .withNamespace(optaPlannerSolver.getNamespace()) .build(); TriggerAuthentication triggerAuthentication = new TriggerAuthentication(); triggerAuthentication.setMetadata(metadata); triggerAuthentication.setSpec(spec); return triggerAuthentication;
162
242
404
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jackson/src/main/java/org/optaplanner/persistence/jackson/api/score/AbstractScoreJacksonSerializer.java
AbstractScoreJacksonSerializer
createContextual
class AbstractScoreJacksonSerializer<Score_ extends Score<Score_>> extends JsonSerializer<Score_> implements ContextualSerializer { @Override public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property) throws JsonMappingException {<FILL_FUNCTION_BODY>} @Override public void serialize(Score_ score, JsonGenerator generator, SerializerProvider serializers) throws IOException { generator.writeString(score.toString()); } }
JavaType propertyType = property.getType(); if (Score.class.equals(propertyType.getRawClass())) { // If the property type is Score (not HardSoftScore for example), // delegate to PolymorphicScoreJacksonSerializer instead to write the score type too // This presumes that OptaPlannerJacksonModule is registered return provider.findValueSerializer(propertyType); } return this;
122
107
229
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jackson/src/main/java/org/optaplanner/persistence/jackson/impl/domain/solution/JacksonSolutionFileIO.java
JacksonSolutionFileIO
write
class JacksonSolutionFileIO<Solution_> implements SolutionFileIO<Solution_> { private final Class<Solution_> clazz; private final ObjectMapper mapper; public JacksonSolutionFileIO(Class<Solution_> clazz) { this(clazz, new ObjectMapper()); } public JacksonSolutionFileIO(Class<Solution_> clazz, ObjectMapper mapper) { this.clazz = clazz; this.mapper = mapper; // Loads OptaPlannerJacksonModule via ServiceLoader, as well as any other Jackson modules on the classpath. mapper.findAndRegisterModules(); } @Override public String getInputFileExtension() { return "json"; } @Override public String getOutputFileExtension() { return "json"; } @Override public Solution_ read(File inputSolutionFile) { try { return mapper.readValue(inputSolutionFile, clazz); } catch (IOException e) { throw new IllegalArgumentException("Failed reading inputSolutionFile (" + inputSolutionFile + ").", e); } } public Solution_ read(InputStream inputSolutionStream) { try { return mapper.readValue(inputSolutionStream, clazz); } catch (IOException e) { throw new IllegalArgumentException("Failed reading inputSolutionStream.", e); } } @Override public void write(Solution_ solution, File file) {<FILL_FUNCTION_BODY>} }
try { mapper.writerWithDefaultPrettyPrinter().writeValue(file, solution); } catch (IOException e) { throw new IllegalArgumentException("Failed write", e); }
399
51
450
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jaxb/src/main/java/org/optaplanner/persistence/jaxb/api/score/PolymorphicScoreJaxbAdapter.java
PolymorphicScoreJaxbAdapter
unmarshal
class PolymorphicScoreJaxbAdapter extends XmlAdapter<PolymorphicScoreJaxbAdapter.JaxbAdaptedScore, Score> { @Override public Score unmarshal(JaxbAdaptedScore jaxbAdaptedScore) {<FILL_FUNCTION_BODY>} @Override public JaxbAdaptedScore marshal(Score score) { if (score == null) { return null; } return new JaxbAdaptedScore(score); } static class JaxbAdaptedScore { @XmlAttribute(name = "class") private String scoreClassName; @XmlValue private String scoreString; private JaxbAdaptedScore() { // Required by JAXB } public JaxbAdaptedScore(Score score) { this.scoreClassName = score.getClass().getName(); this.scoreString = score.toString(); } String getScoreClassName() { return scoreClassName; } String getScoreString() { return scoreString; } } }
if (jaxbAdaptedScore == null) { return null; } String scoreClassName = jaxbAdaptedScore.scoreClassName; String scoreString = jaxbAdaptedScore.scoreString; // TODO Can this delegate to ScoreUtils.parseScore()? if (scoreClassName.equals(SimpleScore.class.getName())) { return SimpleScore.parseScore(scoreString); } else if (scoreClassName.equals(SimpleLongScore.class.getName())) { return SimpleLongScore.parseScore(scoreString); } else if (scoreClassName.equals(SimpleBigDecimalScore.class.getName())) { return SimpleBigDecimalScore.parseScore(scoreString); } else if (scoreClassName.equals(HardSoftScore.class.getName())) { return HardSoftScore.parseScore(scoreString); } else if (scoreClassName.equals(HardSoftLongScore.class.getName())) { return HardSoftLongScore.parseScore(scoreString); } else if (scoreClassName.equals(HardSoftBigDecimalScore.class.getName())) { return HardSoftBigDecimalScore.parseScore(scoreString); } else if (scoreClassName.equals(HardMediumSoftScore.class.getName())) { return HardMediumSoftScore.parseScore(scoreString); } else if (scoreClassName.equals(HardMediumSoftLongScore.class.getName())) { return HardMediumSoftLongScore.parseScore(scoreString); } else if (scoreClassName.equals(HardMediumSoftBigDecimalScore.class.getName())) { return HardMediumSoftBigDecimalScore.parseScore(scoreString); } else if (scoreClassName.equals(BendableScore.class.getName())) { return BendableScore.parseScore(scoreString); } else if (scoreClassName.equals(BendableLongScore.class.getName())) { return BendableLongScore.parseScore(scoreString); } else if (scoreClassName.equals(BendableBigDecimalScore.class.getName())) { return BendableBigDecimalScore.parseScore(scoreString); } else { throw new IllegalArgumentException("Unrecognized scoreClassName (" + scoreClassName + ") for scoreString (" + scoreString + ")."); }
294
569
863
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jpa/src/main/java/org/optaplanner/persistence/jpa/api/score/buildin/bendable/BendableScoreConverter.java
BendableScoreConverter
convertToDatabaseColumn
class BendableScoreConverter implements AttributeConverter<BendableScore, String> { @Override public String convertToDatabaseColumn(BendableScore score) {<FILL_FUNCTION_BODY>} @Override public BendableScore convertToEntityAttribute(String scoreString) { if (scoreString == null) { return null; } return BendableScore.parseScore(scoreString); } }
if (score == null) { return null; } return score.toString();
113
28
141
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jpa/src/main/java/org/optaplanner/persistence/jpa/api/score/buildin/bendablelong/BendableLongScoreConverter.java
BendableLongScoreConverter
convertToDatabaseColumn
class BendableLongScoreConverter implements AttributeConverter<BendableLongScore, String> { @Override public String convertToDatabaseColumn(BendableLongScore score) {<FILL_FUNCTION_BODY>} @Override public BendableLongScore convertToEntityAttribute(String scoreString) { if (scoreString == null) { return null; } return BendableLongScore.parseScore(scoreString); } }
if (score == null) { return null; } return score.toString();
118
28
146
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jpa/src/main/java/org/optaplanner/persistence/jpa/api/score/buildin/hardmediumsoft/HardMediumSoftScoreConverter.java
HardMediumSoftScoreConverter
convertToEntityAttribute
class HardMediumSoftScoreConverter implements AttributeConverter<HardMediumSoftScore, String> { @Override public String convertToDatabaseColumn(HardMediumSoftScore score) { if (score == null) { return null; } return score.toString(); } @Override public HardMediumSoftScore convertToEntityAttribute(String scoreString) {<FILL_FUNCTION_BODY>} }
if (scoreString == null) { return null; } return HardMediumSoftScore.parseScore(scoreString);
109
37
146
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jpa/src/main/java/org/optaplanner/persistence/jpa/api/score/buildin/hardmediumsoftbigdecimal/HardMediumSoftBigDecimalScoreConverter.java
HardMediumSoftBigDecimalScoreConverter
convertToEntityAttribute
class HardMediumSoftBigDecimalScoreConverter implements AttributeConverter<HardMediumSoftBigDecimalScore, String> { @Override public String convertToDatabaseColumn(HardMediumSoftBigDecimalScore score) { if (score == null) { return null; } return score.toString(); } @Override public HardMediumSoftBigDecimalScore convertToEntityAttribute(String scoreString) {<FILL_FUNCTION_BODY>} }
if (scoreString == null) { return null; } return HardMediumSoftBigDecimalScore.parseScore(scoreString);
121
40
161
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jpa/src/main/java/org/optaplanner/persistence/jpa/api/score/buildin/hardmediumsoftlong/HardMediumSoftLongScoreConverter.java
HardMediumSoftLongScoreConverter
convertToEntityAttribute
class HardMediumSoftLongScoreConverter implements AttributeConverter<HardMediumSoftLongScore, String> { @Override public String convertToDatabaseColumn(HardMediumSoftLongScore score) { if (score == null) { return null; } return score.toString(); } @Override public HardMediumSoftLongScore convertToEntityAttribute(String scoreString) {<FILL_FUNCTION_BODY>} }
if (scoreString == null) { return null; } return HardMediumSoftLongScore.parseScore(scoreString);
113
38
151
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jpa/src/main/java/org/optaplanner/persistence/jpa/api/score/buildin/hardsoft/HardSoftScoreConverter.java
HardSoftScoreConverter
convertToEntityAttribute
class HardSoftScoreConverter implements AttributeConverter<HardSoftScore, String> { @Override public String convertToDatabaseColumn(HardSoftScore score) { if (score == null) { return null; } return score.toString(); } @Override public HardSoftScore convertToEntityAttribute(String scoreString) {<FILL_FUNCTION_BODY>} }
if (scoreString == null) { return null; } return HardSoftScore.parseScore(scoreString);
101
35
136
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jpa/src/main/java/org/optaplanner/persistence/jpa/api/score/buildin/hardsoftbigdecimal/HardSoftBigDecimalScoreConverter.java
HardSoftBigDecimalScoreConverter
convertToDatabaseColumn
class HardSoftBigDecimalScoreConverter implements AttributeConverter<HardSoftBigDecimalScore, String> { @Override public String convertToDatabaseColumn(HardSoftBigDecimalScore score) {<FILL_FUNCTION_BODY>} @Override public HardSoftBigDecimalScore convertToEntityAttribute(String scoreString) { if (scoreString == null) { return null; } return HardSoftBigDecimalScore.parseScore(scoreString); } }
if (score == null) { return null; } return score.toString();
123
28
151
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jpa/src/main/java/org/optaplanner/persistence/jpa/api/score/buildin/hardsoftlong/HardSoftLongScoreConverter.java
HardSoftLongScoreConverter
convertToDatabaseColumn
class HardSoftLongScoreConverter implements AttributeConverter<HardSoftLongScore, String> { @Override public String convertToDatabaseColumn(HardSoftLongScore score) {<FILL_FUNCTION_BODY>} @Override public HardSoftLongScore convertToEntityAttribute(String scoreString) { if (scoreString == null) { return null; } return HardSoftLongScore.parseScore(scoreString); } }
if (score == null) { return null; } return score.toString();
113
28
141
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jpa/src/main/java/org/optaplanner/persistence/jpa/api/score/buildin/simple/SimpleScoreConverter.java
SimpleScoreConverter
convertToDatabaseColumn
class SimpleScoreConverter implements AttributeConverter<SimpleScore, String> { @Override public String convertToDatabaseColumn(SimpleScore score) {<FILL_FUNCTION_BODY>} @Override public SimpleScore convertToEntityAttribute(String scoreString) { if (scoreString == null) { return null; } return SimpleScore.parseScore(scoreString); } }
if (score == null) { return null; } return score.toString();
103
28
131
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jpa/src/main/java/org/optaplanner/persistence/jpa/api/score/buildin/simplebigdecimal/SimpleBigDecimalScoreConverter.java
SimpleBigDecimalScoreConverter
convertToEntityAttribute
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) {<FILL_FUNCTION_BODY>} }
if (scoreString == null) { return null; } return SimpleBigDecimalScore.parseScore(scoreString);
109
37
146
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jpa/src/main/java/org/optaplanner/persistence/jpa/api/score/buildin/simplelong/SimpleLongScoreConverter.java
SimpleLongScoreConverter
convertToDatabaseColumn
class SimpleLongScoreConverter implements AttributeConverter<SimpleLongScore, String> { @Override public String convertToDatabaseColumn(SimpleLongScore score) {<FILL_FUNCTION_BODY>} @Override public SimpleLongScore convertToEntityAttribute(String scoreString) { if (scoreString == null) { return null; } return SimpleLongScore.parseScore(scoreString); } }
if (score == null) { return null; } return score.toString();
108
28
136
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jsonb/src/main/java/org/optaplanner/persistence/jsonb/api/OptaPlannerJsonbConfig.java
OptaPlannerJsonbConfig
getScoreJsonbAdapters
class OptaPlannerJsonbConfig { /** * @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() {<FILL_FUNCTION_BODY>} }
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() };
308
155
463
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-xstream/src/main/java/org/optaplanner/persistence/xstream/api/score/AbstractScoreXStreamConverter.java
AbstractScoreXStreamConverter
registerScoreConverters
class AbstractScoreXStreamConverter implements Converter { public static void registerScoreConverters(XStream xStream) {<FILL_FUNCTION_BODY>} }
xStream.registerConverter(new SimpleScoreXStreamConverter()); xStream.registerConverter(new SimpleLongScoreXStreamConverter()); xStream.registerConverter(new SimpleBigDecimalScoreXStreamConverter()); xStream.registerConverter(new HardSoftScoreXStreamConverter()); xStream.registerConverter(new HardSoftLongScoreXStreamConverter()); xStream.registerConverter(new HardSoftBigDecimalScoreXStreamConverter()); xStream.registerConverter(new HardMediumSoftScoreXStreamConverter()); xStream.registerConverter(new HardMediumSoftLongScoreXStreamConverter()); xStream.registerConverter(new HardMediumSoftBigDecimalScoreXStreamConverter()); xStream.registerConverter(new BendableScoreXStreamConverter()); xStream.registerConverter(new BendableLongScoreXStreamConverter()); xStream.registerConverter(new BendableBigDecimalScoreXStreamConverter());
44
220
264
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-xstream/src/main/java/org/optaplanner/persistence/xstream/impl/domain/solution/XStreamSolutionFileIO.java
XStreamSolutionFileIO
read
class XStreamSolutionFileIO<Solution_> implements SolutionFileIO<Solution_> { protected XStream xStream; public XStreamSolutionFileIO(Class... xStreamAnnotatedClasses) { xStream = new XStream(); xStream.setMode(XStream.ID_REFERENCES); xStream.processAnnotations(xStreamAnnotatedClasses); XStream.setupDefaultSecurity(xStream); // Presume the XML file comes from a trusted source so it works out of the box. See class javadoc. xStream.addPermission(new AnyTypePermission()); } public XStream getXStream() { return xStream; } @Override public String getInputFileExtension() { return "xml"; } @Override public Solution_ read(File inputSolutionFile) { try (InputStream inputSolutionStream = Files.newInputStream(inputSolutionFile.toPath())) { return read(inputSolutionStream); } catch (Exception e) { throw new IllegalArgumentException("Failed reading inputSolutionFile (" + inputSolutionFile + ").", e); } } public Solution_ read(InputStream inputSolutionStream) {<FILL_FUNCTION_BODY>} @Override public void write(Solution_ solution, File outputSolutionFile) { try (Writer writer = new OutputStreamWriter(new FileOutputStream(outputSolutionFile), StandardCharsets.UTF_8)) { xStream.toXML(solution, writer); } catch (IOException e) { throw new IllegalArgumentException("Failed writing outputSolutionFile (" + outputSolutionFile + ").", e); } } }
// xStream.fromXml(InputStream) does not use UTF-8 try (Reader reader = new InputStreamReader(inputSolutionStream, StandardCharsets.UTF_8)) { return (Solution_) xStream.fromXML(reader); } catch (XStreamException | IOException e) { throw new IllegalArgumentException("Failed reading inputSolutionStream.", e); }
426
94
520
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-quarkus-integration/optaplanner-quarkus-benchmark/deployment/src/main/java/org/optaplanner/benchmark/quarkus/deployment/OptaPlannerBenchmarkProcessor.java
OptaPlannerBenchmarkProcessor
registerAdditionalBeans
class OptaPlannerBenchmarkProcessor { private static final Logger log = Logger.getLogger(OptaPlannerBenchmarkProcessor.class.getName()); OptaPlannerBenchmarkBuildTimeConfig optaPlannerBenchmarkBuildTimeConfig; @BuildStep FeatureBuildItem feature() { return new FeatureBuildItem("optaplanner-benchmark"); } @BuildStep HotDeploymentWatchedFileBuildItem watchSolverBenchmarkConfigXml() { String solverBenchmarkConfigXML = optaPlannerBenchmarkBuildTimeConfig.solverBenchmarkConfigXml .orElse(OptaPlannerBenchmarkBuildTimeConfig.DEFAULT_SOLVER_BENCHMARK_CONFIG_URL); return new HotDeploymentWatchedFileBuildItem(solverBenchmarkConfigXML); } @BuildStep @Record(ExecutionTime.STATIC_INIT) void registerAdditionalBeans(BuildProducer<AdditionalBeanBuildItem> additionalBeans, BuildProducer<SyntheticBeanBuildItem> syntheticBeans, BuildProducer<UnremovableBeanBuildItem> unremovableBeans, SolverConfigBuildItem solverConfigBuildItem, OptaPlannerBenchmarkRecorder recorder) {<FILL_FUNCTION_BODY>} }
if (solverConfigBuildItem.getSolverConfig() == null) { log.warn("Skipping OptaPlanner Benchmark extension because the OptaPlanner extension was skipped."); additionalBeans.produce(new AdditionalBeanBuildItem(UnavailableOptaPlannerBenchmarkBeanProvider.class)); return; } PlannerBenchmarkConfig benchmarkConfig; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (optaPlannerBenchmarkBuildTimeConfig.solverBenchmarkConfigXml.isPresent()) { String solverBenchmarkConfigXML = optaPlannerBenchmarkBuildTimeConfig.solverBenchmarkConfigXml.get(); if (classLoader.getResource(solverBenchmarkConfigXML) == null) { throw new ConfigurationException("Invalid quarkus.optaplanner.benchmark.solver-benchmark-config-xml property (" + solverBenchmarkConfigXML + "): that classpath resource does not exist."); } benchmarkConfig = PlannerBenchmarkConfig.createFromXmlResource(solverBenchmarkConfigXML); } else if (classLoader.getResource(OptaPlannerBenchmarkBuildTimeConfig.DEFAULT_SOLVER_BENCHMARK_CONFIG_URL) != null) { benchmarkConfig = PlannerBenchmarkConfig.createFromXmlResource( OptaPlannerBenchmarkBuildTimeConfig.DEFAULT_SOLVER_BENCHMARK_CONFIG_URL); } else { benchmarkConfig = null; } syntheticBeans.produce(SyntheticBeanBuildItem.configure(PlannerBenchmarkConfig.class) .supplier(recorder.benchmarkConfigSupplier(benchmarkConfig)) .done()); additionalBeans.produce(new AdditionalBeanBuildItem(OptaPlannerBenchmarkBeanProvider.class)); unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(OptaPlannerBenchmarkRuntimeConfig.class)); unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(SolverConfig.class));
333
520
853
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-quarkus-integration/optaplanner-quarkus/runtime/src/main/java/org/optaplanner/quarkus/OptaPlannerRecorder.java
OptaPlannerRecorder
solverConfigSupplier
class OptaPlannerRecorder { public Supplier<SolverConfig> solverConfigSupplier(final SolverConfig solverConfig, Map<String, RuntimeValue<MemberAccessor>> generatedGizmoMemberAccessorMap, Map<String, RuntimeValue<SolutionCloner>> generatedGizmoSolutionClonerMap) {<FILL_FUNCTION_BODY>} public Supplier<SolverManagerConfig> solverManagerConfig(final SolverManagerConfig solverManagerConfig) { return () -> { OptaPlannerRuntimeConfig optaPlannerRuntimeConfig = Arc.container().instance(OptaPlannerRuntimeConfig.class).get(); updateSolverManagerConfigWithRuntimeProperties(solverManagerConfig, optaPlannerRuntimeConfig); return solverManagerConfig; }; } private void updateSolverConfigWithRuntimeProperties(SolverConfig solverConfig, OptaPlannerRuntimeConfig optaPlannerRunTimeConfig) { TerminationConfig terminationConfig = solverConfig.getTerminationConfig(); if (terminationConfig == null) { terminationConfig = new TerminationConfig(); solverConfig.setTerminationConfig(terminationConfig); } optaPlannerRunTimeConfig.solver.termination.spentLimit.ifPresent(terminationConfig::setSpentLimit); optaPlannerRunTimeConfig.solver.termination.unimprovedSpentLimit .ifPresent(terminationConfig::setUnimprovedSpentLimit); optaPlannerRunTimeConfig.solver.termination.bestScoreLimit.ifPresent(terminationConfig::setBestScoreLimit); optaPlannerRunTimeConfig.solver.moveThreadCount.ifPresent(solverConfig::setMoveThreadCount); } private void updateSolverManagerConfigWithRuntimeProperties(SolverManagerConfig solverManagerConfig, OptaPlannerRuntimeConfig optaPlannerRunTimeConfig) { optaPlannerRunTimeConfig.solverManager.parallelSolverCount.ifPresent(solverManagerConfig::setParallelSolverCount); } }
return () -> { OptaPlannerRuntimeConfig optaPlannerRuntimeConfig = Arc.container().instance(OptaPlannerRuntimeConfig.class).get(); updateSolverConfigWithRuntimeProperties(solverConfig, optaPlannerRuntimeConfig); 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; };
508
232
740
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-quarkus-integration/optaplanner-quarkus/runtime/src/main/java/org/optaplanner/quarkus/bean/UnavailableOptaPlannerBeanProvider.java
UnavailableOptaPlannerBeanProvider
createException
class UnavailableOptaPlannerBeanProvider { @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) {<FILL_FUNCTION_BODY>} }
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).");
1,764
159
1,923
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-quarkus-integration/optaplanner-quarkus/runtime/src/main/java/org/optaplanner/quarkus/devui/OptaPlannerDevUIPropertiesSupplier.java
OptaPlannerDevUIPropertiesSupplier
getModelInfo
class OptaPlannerDevUIPropertiesSupplier implements Supplier<OptaPlannerDevUIProperties> { private String effectiveSolverConfigXml; public OptaPlannerDevUIPropertiesSupplier() { this.effectiveSolverConfigXml = null; } public OptaPlannerDevUIPropertiesSupplier(String effectiveSolverConfigXml) { this.effectiveSolverConfigXml = effectiveSolverConfigXml; } // Needed for Quarkus Dev UI serialization public String getEffectiveSolverConfigXml() { return effectiveSolverConfigXml; } public void setEffectiveSolverConfigXml(String effectiveSolverConfigXml) { this.effectiveSolverConfigXml = effectiveSolverConfigXml; } @Override public OptaPlannerDevUIProperties get() { if (effectiveSolverConfigXml != null) { // 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 return new OptaPlannerDevUIProperties(getModelInfo(), getXmlContentWithComment("Properties that can be set at runtime are not included"), getConstraintList()); } else { return new OptaPlannerDevUIProperties(getModelInfo(), "<!-- Plugin execution was skipped " + "because there are no @" + PlanningSolution.class.getSimpleName() + " or @" + PlanningEntity.class.getSimpleName() + " annotated classes. -->\n<solver />", Collections.emptyList()); } } private OptaPlannerModelProperties getModelInfo() {<FILL_FUNCTION_BODY>} private List<String> getConstraintList() { if (effectiveSolverConfigXml != null) { DefaultSolverFactory<?> solverFactory = (DefaultSolverFactory<?>) Arc.container().instance(SolverFactory.class).get(); if (solverFactory.getScoreDirectorFactory() instanceof AbstractConstraintStreamScoreDirectorFactory) { AbstractConstraintStreamScoreDirectorFactory<?, ?> scoreDirectorFactory = (AbstractConstraintStreamScoreDirectorFactory<?, ?>) solverFactory.getScoreDirectorFactory(); return Arrays.stream(scoreDirectorFactory.getConstraints()).map(Constraint::getConstraintId) .collect(Collectors.toList()); } } return Collections.emptyList(); } private String getXmlContentWithComment(String comment) { int indexOfPreambleEnd = effectiveSolverConfigXml.indexOf("?>"); if (indexOfPreambleEnd != -1) { return effectiveSolverConfigXml.substring(0, indexOfPreambleEnd + 2) + "\n<!--" + comment + "-->\n" + effectiveSolverConfigXml.substring(indexOfPreambleEnd + 2); } else { return "<!--" + comment + "-->\n" + effectiveSolverConfigXml; } } }
if (effectiveSolverConfigXml != null) { DefaultSolverFactory<?> solverFactory = (DefaultSolverFactory<?>) Arc.container().instance(SolverFactory.class).get(); SolutionDescriptor<?> solutionDescriptor = solverFactory.getScoreDirectorFactory().getSolutionDescriptor(); OptaPlannerModelProperties out = new OptaPlannerModelProperties(); out.setSolutionClass(solutionDescriptor.getSolutionClass().getName()); List<String> entityClassList = new ArrayList<>(); Map<String, List<String>> entityClassToGenuineVariableListMap = new HashMap<>(); Map<String, List<String>> entityClassToShadowVariableListMap = new HashMap<>(); for (EntityDescriptor<?> entityDescriptor : solutionDescriptor.getEntityDescriptors()) { entityClassList.add(entityDescriptor.getEntityClass().getName()); List<String> entityClassToGenuineVariableList = new ArrayList<>(); List<String> entityClassToShadowVariableList = new ArrayList<>(); for (VariableDescriptor<?> 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 OptaPlannerModelProperties(); }
769
500
1,269
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-quarkus-integration/optaplanner-quarkus/runtime/src/main/java/org/optaplanner/quarkus/nativeimage/Substitute_ConfigUtils.java
Substitute_ConfigUtils
newInstance
class Substitute_ConfigUtils { @Substitute public static <T> T newInstance(Supplier<String> ownerDescriptor, String propertyName, Class<T> clazz) {<FILL_FUNCTION_BODY>} }
T out = CDI.current().getBeanManager().createInstance().select(OptaPlannerGizmoBeanFactory.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."); }
61
116
177
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-quarkus-integration/optaplanner-quarkus/runtime/src/main/java/org/optaplanner/quarkus/nativeimage/Substitute_LambdaBeanPropertyMemberAccessor.java
Substitute_LambdaBeanPropertyMemberAccessor
createSetterFunction
class Substitute_LambdaBeanPropertyMemberAccessor { @Alias Method getterMethod; @Alias Method setterMethod; @Substitute private Function<Object, Object> createGetterFunction(MethodHandles.Lookup lookup) { return new GetterDelegationFunction(getterMethod); } @Substitute private BiConsumer<Object, Object> createSetterFunction(MethodHandles.Lookup lookup) {<FILL_FUNCTION_BODY>} private static final class GetterDelegationFunction implements Function<Object, Object> { private final Method method; public GetterDelegationFunction(Method method) { this.method = method; } @Override public Object apply(Object object) { try { return method.invoke(object); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } } private static final class SetterDelegationBiConsumer implements BiConsumer<Object, Object> { private final Method method; public SetterDelegationBiConsumer(Method method) { this.method = method; } @Override public void accept(Object object, Object value) { try { method.invoke(object, value); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } } }
if (setterMethod == null) { return null; } return new SetterDelegationBiConsumer(setterMethod);
373
39
412
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-spring-integration/optaplanner-spring-boot-autoconfigure/src/main/java/org/optaplanner/spring/boot/autoconfigure/OptaPlannerAutoConfiguration.java
OptaPlannerConstraintVerifierConfiguration
findEntityClassList
class OptaPlannerConstraintVerifierConfiguration { @Bean @SuppressWarnings("unchecked") <ConstraintProvider_ extends ConstraintProvider, SolutionClass_> ConstraintVerifier<ConstraintProvider_, SolutionClass_> constraintVerifier(SolverConfig solverConfig) { ScoreDirectorFactoryConfig scoreDirectorFactoryConfig = solverConfig.getScoreDirectorFactoryConfig(); if (scoreDirectorFactoryConfig.getConstraintProviderClass() == null) { // Return a mock ConstraintVerifier so not having ConstraintProvider doesn't crash tests // (Cannot create custom condition that checks SolverConfig, since that // requires OptaPlannerAutoConfiguration to have a no-args constructor) final String noConstraintProviderErrorMsg = "Cannot provision a ConstraintVerifier because there is no ConstraintProvider class."; return new ConstraintVerifier<>() { @Override public ConstraintVerifier<ConstraintProvider_, SolutionClass_> withConstraintStreamImplType(ConstraintStreamImplType constraintStreamImplType) { throw new UnsupportedOperationException(noConstraintProviderErrorMsg); } @Override public ConstraintVerifier<ConstraintProvider_, SolutionClass_> withDroolsAlphaNetworkCompilationEnabled(boolean droolsAlphaNetworkCompilationEnabled) { throw new UnsupportedOperationException(noConstraintProviderErrorMsg); } @Override public SingleConstraintVerification<SolutionClass_> verifyThat(BiFunction<ConstraintProvider_, ConstraintFactory, Constraint> constraintFunction) { throw new UnsupportedOperationException(noConstraintProviderErrorMsg); } @Override public MultiConstraintVerification<SolutionClass_> verifyThat() { throw new UnsupportedOperationException(noConstraintProviderErrorMsg); } }; } return ConstraintVerifier.create(solverConfig); } } private void applySolverProperties(SolverConfig solverConfig) { IncludeAbstractClassesEntityScanner entityScanner = new IncludeAbstractClassesEntityScanner(this.context); if (solverConfig.getSolutionClass() == null) { solverConfig.setSolutionClass(findSolutionClass(entityScanner)); } if (solverConfig.getEntityClassList() == null) { solverConfig.setEntityClassList(findEntityClassList(entityScanner)); } applyScoreDirectorFactoryProperties(solverConfig); SolverProperties solverProperties = optaPlannerProperties.getSolver(); if (solverProperties != null) { if (solverProperties.getEnvironmentMode() != null) { solverConfig.setEnvironmentMode(solverProperties.getEnvironmentMode()); } if (solverProperties.getDomainAccessType() != null) { solverConfig.setDomainAccessType(solverProperties.getDomainAccessType()); } if (solverProperties.getConstraintStreamImplType() != null) { solverConfig.withConstraintStreamImplType(solverProperties.getConstraintStreamImplType()); } if (solverProperties.getDaemon() != null) { solverConfig.setDaemon(solverProperties.getDaemon()); } if (solverProperties.getMoveThreadCount() != null) { solverConfig.setMoveThreadCount(solverProperties.getMoveThreadCount()); } applyTerminationProperties(solverConfig, solverProperties.getTermination()); } } private Class<?> findSolutionClass(IncludeAbstractClassesEntityScanner entityScanner) { Set<Class<?>> solutionClassSet; try { solutionClassSet = entityScanner.scan(PlanningSolution.class); } catch (ClassNotFoundException e) { throw new IllegalStateException("Scanning for @" + PlanningSolution.class.getSimpleName() + " annotations failed.", e); } if (solutionClassSet.size() > 1) { throw new IllegalStateException("Multiple classes (" + solutionClassSet + ") found with a @" + PlanningSolution.class.getSimpleName() + " annotation."); } if (solutionClassSet.isEmpty()) { throw new IllegalStateException("No classes (" + solutionClassSet + ") found with a @" + PlanningSolution.class.getSimpleName() + " annotation.\n" + "Maybe your @" + PlanningSolution.class.getSimpleName() + " annotated class " + " is not in a subpackage of your @" + SpringBootApplication.class.getSimpleName() + " annotated class's package.\n" + "Maybe move your planning solution class to your application class's (sub)package" + " (or use @" + EntityScan.class.getSimpleName() + ")."); } return solutionClassSet.iterator().next(); } private List<Class<?>> findEntityClassList(IncludeAbstractClassesEntityScanner entityScanner) {<FILL_FUNCTION_BODY>
Set<Class<?>> entityClassSet; try { entityClassSet = entityScanner.scan(PlanningEntity.class); } catch (ClassNotFoundException e) { throw new IllegalStateException("Scanning for @" + PlanningEntity.class.getSimpleName() + " failed.", e); } if (entityClassSet.isEmpty()) { throw new IllegalStateException("No classes (" + entityClassSet + ") found with a @" + PlanningEntity.class.getSimpleName() + " annotation.\n" + "Maybe your @" + PlanningEntity.class.getSimpleName() + " annotated class(es) " + " are not in a subpackage of your @" + SpringBootApplication.class.getSimpleName() + " annotated class's package.\n" + "Maybe move your planning entity classes to your application class's (sub)package" + " (or use @" + EntityScan.class.getSimpleName() + ")."); } return new ArrayList<>(entityClassSet);
1,226
250
1,476
<no_super_class>
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-spring-integration/optaplanner-spring-boot-autoconfigure/src/main/java/org/optaplanner/spring/boot/autoconfigure/OptaPlannerBenchmarkAutoConfiguration.java
OptaPlannerBenchmarkAutoConfiguration
plannerBenchmarkConfig
class OptaPlannerBenchmarkAutoConfiguration implements BeanClassLoaderAware { private final ApplicationContext context; private final OptaPlannerProperties optaPlannerProperties; private ClassLoader beanClassLoader; protected OptaPlannerBenchmarkAutoConfiguration(ApplicationContext context, OptaPlannerProperties optaPlannerProperties) { this.context = context; this.optaPlannerProperties = optaPlannerProperties; } @Bean public PlannerBenchmarkConfig plannerBenchmarkConfig(SolverConfig solverConfig) {<FILL_FUNCTION_BODY>} @Bean public PlannerBenchmarkFactory plannerBenchmarkFactory(PlannerBenchmarkConfig benchmarkConfig) { return PlannerBenchmarkFactory.create(benchmarkConfig); } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } }
PlannerBenchmarkConfig benchmarkConfig; if (optaPlannerProperties.getBenchmark() != null && optaPlannerProperties.getBenchmark().getSolverBenchmarkConfigXml() != null) { if (beanClassLoader.getResource(optaPlannerProperties.getBenchmark().getSolverBenchmarkConfigXml()) == null) { throw new IllegalStateException( "Invalid optaplanner.benchmark.solverBenchmarkConfigXml property (" + optaPlannerProperties.getBenchmark().getSolverBenchmarkConfigXml() + "): that classpath resource does not exist."); } benchmarkConfig = PlannerBenchmarkConfig .createFromXmlResource(optaPlannerProperties.getBenchmark().getSolverBenchmarkConfigXml(), beanClassLoader); } else if (beanClassLoader.getResource(BenchmarkProperties.DEFAULT_SOLVER_BENCHMARK_CONFIG_URL) != null) { benchmarkConfig = PlannerBenchmarkConfig.createFromXmlResource( OptaPlannerProperties.DEFAULT_SOLVER_BENCHMARK_CONFIG_URL, beanClassLoader); } else { benchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig); benchmarkConfig.setBenchmarkDirectory(new File(BenchmarkProperties.DEFAULT_BENCHMARK_RESULT_DIRECTORY)); } if (optaPlannerProperties.getBenchmark() != null && optaPlannerProperties.getBenchmark().getResultDirectory() != null) { benchmarkConfig.setBenchmarkDirectory(new File(optaPlannerProperties.getBenchmark().getResultDirectory())); } if (benchmarkConfig.getBenchmarkDirectory() == null) { benchmarkConfig.setBenchmarkDirectory(new File(BenchmarkProperties.DEFAULT_BENCHMARK_RESULT_DIRECTORY)); } if (optaPlannerProperties.getBenchmark() != null && optaPlannerProperties.getBenchmark().getSolver() != null) { OptaPlannerAutoConfiguration .applyTerminationProperties(benchmarkConfig.getInheritedSolverBenchmarkConfig().getSolverConfig(), optaPlannerProperties.getBenchmark().getSolver().getTermination()); } if (benchmarkConfig.getInheritedSolverBenchmarkConfig().getSolverConfig().getTerminationConfig() == null || !benchmarkConfig.getInheritedSolverBenchmarkConfig().getSolverConfig().getTerminationConfig().isConfigured()) { List<SolverBenchmarkConfig> solverBenchmarkConfigList = benchmarkConfig.getSolverBenchmarkConfigList(); List<String> unconfiguredTerminationSolverBenchmarkList = new ArrayList<>(); if (solverBenchmarkConfigList == null) { throw new IllegalStateException("At least one of the properties " + "optaplanner.benchmark.solver.termination.spent-limit, " + "optaplanner.benchmark.solver.termination.best-score-limit, " + "optaplanner.benchmark.solver.termination.unimproved-spent-limit " + "is required if termination is not configured in the " + "inherited solver benchmark config and solverBenchmarkBluePrint is used."); } for (int i = 0; i < solverBenchmarkConfigList.size(); i++) { SolverBenchmarkConfig solverBenchmarkConfig = solverBenchmarkConfigList.get(i); TerminationConfig terminationConfig = solverBenchmarkConfig.getSolverConfig().getTerminationConfig(); if (terminationConfig == null || !terminationConfig.isConfigured()) { boolean isTerminationConfiguredForAllNonConstructionHeuristicPhases = !solverBenchmarkConfig .getSolverConfig().getPhaseConfigList().isEmpty(); for (PhaseConfig<?> phaseConfig : solverBenchmarkConfig.getSolverConfig().getPhaseConfigList()) { if (!(phaseConfig instanceof ConstructionHeuristicPhaseConfig)) { if (phaseConfig.getTerminationConfig() == null || !phaseConfig.getTerminationConfig().isConfigured()) { isTerminationConfiguredForAllNonConstructionHeuristicPhases = false; break; } } } if (!isTerminationConfiguredForAllNonConstructionHeuristicPhases) { String benchmarkConfigName = solverBenchmarkConfig.getName(); if (benchmarkConfigName == null) { benchmarkConfigName = "SolverBenchmarkConfig " + i; } unconfiguredTerminationSolverBenchmarkList.add(benchmarkConfigName); } } } if (!unconfiguredTerminationSolverBenchmarkList.isEmpty()) { throw new IllegalStateException("The following " + SolverBenchmarkConfig.class.getSimpleName() + " do not " + "have termination configured: " + unconfiguredTerminationSolverBenchmarkList.stream() .collect(Collectors.joining(", ", "[", "]")) + ". " + "At least one of the properties " + "optaplanner.benchmark.solver.termination.spent-limit, " + "optaplanner.benchmark.solver.termination.best-score-limit, " + "optaplanner.benchmark.solver.termination.unimproved-spent-limit " + "is required if termination is not configured in a solver benchmark and the " + "inherited solver benchmark config."); } } return benchmarkConfig;
240
1,424
1,664
<no_super_class>
spring-io_initializr
initializr/initializr-actuator/src/main/java/io/spring/initializr/actuate/autoconfigure/InitializrStatsAutoConfiguration.java
InitializrStatsAutoConfiguration
statsRetryTemplate
class InitializrStatsAutoConfiguration { private final StatsProperties statsProperties; InitializrStatsAutoConfiguration(StatsProperties statsProperties) { this.statsProperties = statsProperties; } @Bean @ConditionalOnBean(InitializrMetadataProvider.class) ProjectGenerationStatPublisher projectRequestStatHandler(RestTemplateBuilder restTemplateBuilder) { return new ProjectGenerationStatPublisher(new ProjectRequestDocumentFactory(), this.statsProperties, restTemplateBuilder, statsRetryTemplate()); } @Bean @ConditionalOnMissingBean(name = "statsRetryTemplate") RetryTemplate statsRetryTemplate() {<FILL_FUNCTION_BODY>} static class ElasticUriCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String elasticUri = context.getEnvironment().getProperty("initializr.stats.elastic.uri"); if (StringUtils.hasText(elasticUri)) { return ConditionOutcome.match("initializr.stats.elastic.uri is set"); } return ConditionOutcome.noMatch("initializr.stats.elastic.uri is not set"); } } }
RetryTemplate retryTemplate = new RetryTemplate(); ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy(); backOffPolicy.setInitialInterval(3000L); backOffPolicy.setMultiplier(3); SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(this.statsProperties.getElastic().getMaxAttempts(), Collections.singletonMap(Exception.class, true)); retryTemplate.setBackOffPolicy(backOffPolicy); retryTemplate.setRetryPolicy(retryPolicy); return retryTemplate;
302
154
456
<no_super_class>
spring-io_initializr
initializr/initializr-actuator/src/main/java/io/spring/initializr/actuate/info/BomRangesInfoContributor.java
BomRangesInfoContributor
contribute
class BomRangesInfoContributor implements InfoContributor { private final InitializrMetadataProvider metadataProvider; public BomRangesInfoContributor(InitializrMetadataProvider metadataProvider) { this.metadataProvider = metadataProvider; } @Override public void contribute(Info.Builder builder) {<FILL_FUNCTION_BODY>} }
Map<String, Object> details = new LinkedHashMap<>(); this.metadataProvider.get().getConfiguration().getEnv().getBoms().forEach((k, v) -> { if (v.getMappings() != null && !v.getMappings().isEmpty()) { Map<String, Object> bom = new LinkedHashMap<>(); v.getMappings().forEach((it) -> { String requirement = "Spring Boot " + it.determineCompatibilityRangeRequirement(); bom.put(it.getVersion(), requirement); }); details.put(k, bom); } }); if (!details.isEmpty()) { builder.withDetail("bom-ranges", details); }
91
189
280
<no_super_class>
spring-io_initializr
initializr/initializr-actuator/src/main/java/io/spring/initializr/actuate/info/DependencyRangesInfoContributor.java
DependencyRangesInfoContributor
contribute
class DependencyRangesInfoContributor implements InfoContributor { private final InitializrMetadataProvider metadataProvider; public DependencyRangesInfoContributor(InitializrMetadataProvider metadataProvider) { this.metadataProvider = metadataProvider; } @Override public void contribute(Info.Builder builder) { Map<String, Object> details = new LinkedHashMap<>(); this.metadataProvider.get().getDependencies().getAll().forEach((dependency) -> { if (dependency.getBom() == null) { contribute(details, dependency); } }); if (!details.isEmpty()) { builder.withDetail("dependency-ranges", details); } } private void contribute(Map<String, Object> details, Dependency dependency) {<FILL_FUNCTION_BODY>} private Version getHigher(Map<String, VersionRange> dep) { Version higher = null; for (VersionRange versionRange : dep.values()) { Version candidate = versionRange.getHigherVersion(); if (higher == null) { higher = candidate; } else if (candidate.compareTo(higher) > 0) { higher = candidate; } } return higher; } }
if (!ObjectUtils.isEmpty(dependency.getMappings())) { Map<String, VersionRange> dep = new LinkedHashMap<>(); dependency.getMappings().forEach((it) -> { if (it.getRange() != null && it.getVersion() != null) { dep.put(it.getVersion(), it.getRange()); } }); if (!dep.isEmpty()) { if (dependency.getRange() == null) { boolean openRange = dep.values().stream().anyMatch((v) -> v.getHigherVersion() == null); if (!openRange) { Version higher = getHigher(dep); dep.put("managed", new VersionRange(higher)); } } Map<String, Object> depInfo = new LinkedHashMap<>(); dep.forEach((k, r) -> depInfo.put(k, "Spring Boot " + r)); details.put(dependency.getId(), depInfo); } } else if (dependency.getVersion() != null && dependency.getRange() != null) { Map<String, Object> dep = new LinkedHashMap<>(); String requirement = "Spring Boot " + dependency.getRange(); dep.put(dependency.getVersion(), requirement); details.put(dependency.getId(), dep); }
328
349
677
<no_super_class>
spring-io_initializr
initializr/initializr-actuator/src/main/java/io/spring/initializr/actuate/stat/ProjectGenerationStatPublisher.java
ProjectGenerationStatPublisher
toJson
class ProjectGenerationStatPublisher { private static final Log logger = LogFactory.getLog(ProjectGenerationStatPublisher.class); private final ProjectRequestDocumentFactory documentFactory; private final ObjectMapper objectMapper; private final RestTemplate restTemplate; private URI requestUrl; private final RetryTemplate retryTemplate; public ProjectGenerationStatPublisher(ProjectRequestDocumentFactory documentFactory, StatsProperties statsProperties, RestTemplateBuilder restTemplateBuilder, RetryTemplate retryTemplate) { this.documentFactory = documentFactory; this.objectMapper = createObjectMapper(); StatsProperties.Elastic elastic = statsProperties.getElastic(); UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUri(determineEntityUrl(elastic)); this.restTemplate = configureAuthorization(restTemplateBuilder, elastic, uriBuilder).build(); this.requestUrl = uriBuilder.userInfo(null).build().toUri(); this.retryTemplate = retryTemplate; } @EventListener @Async public void handleEvent(ProjectRequestEvent event) { String json = null; try { ProjectRequestDocument document = this.documentFactory.createDocument(event); if (logger.isDebugEnabled()) { logger.debug("Publishing " + document); } json = toJson(document); RequestEntity<String> request = RequestEntity.post(this.requestUrl) .contentType(MediaType.APPLICATION_JSON) .body(json); this.retryTemplate.execute((context) -> { this.restTemplate.exchange(request, String.class); return null; }); } catch (Exception ex) { logger.warn(String.format("Failed to publish stat to index, document follows %n%n%s%n", json), ex); } } private String toJson(ProjectRequestDocument stats) {<FILL_FUNCTION_BODY>} private static ObjectMapper createObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper; } // For testing purposes only protected RestTemplate getRestTemplate() { return this.restTemplate; } protected void updateRequestUrl(URI requestUrl) { this.requestUrl = requestUrl; } private static RestTemplateBuilder configureAuthorization(RestTemplateBuilder restTemplateBuilder, Elastic elastic, UriComponentsBuilder uriComponentsBuilder) { String userInfo = uriComponentsBuilder.build().getUserInfo(); if (StringUtils.hasText(userInfo)) { String[] credentials = userInfo.split(":"); return restTemplateBuilder.basicAuthentication(credentials[0], credentials[1]); } else if (StringUtils.hasText(elastic.getUsername())) { return restTemplateBuilder.basicAuthentication(elastic.getUsername(), elastic.getPassword()); } return restTemplateBuilder; } private static URI determineEntityUrl(Elastic elastic) { String entityUrl = elastic.getUri() + "/" + elastic.getIndexName() + "/_doc/"; try { return new URI(entityUrl); } catch (URISyntaxException ex) { throw new IllegalStateException("Cannot create entity URL: " + entityUrl, ex); } } }
try { return this.objectMapper.writeValueAsString(stats); } catch (JsonProcessingException ex) { throw new IllegalStateException("Cannot convert to JSON", ex); }
842
57
899
<no_super_class>
spring-io_initializr
initializr/initializr-actuator/src/main/java/io/spring/initializr/actuate/stat/ProjectRequestDocumentFactory.java
ProjectRequestDocumentFactory
createDocument
class ProjectRequestDocumentFactory { private static final Pattern PROJECT_TYPE_PATTERN = Pattern.compile("([a-z]*)-[a-z-]*"); public ProjectRequestDocument createDocument(ProjectRequestEvent event) {<FILL_FUNCTION_BODY>} private String determineBuildSystem(ProjectRequest request) { Matcher typeMatcher = PROJECT_TYPE_PATTERN.matcher(request.getType()); if (typeMatcher.matches()) { return typeMatcher.group(1); } return null; } private VersionInformation determineVersionInformation(ProjectRequest request) { Version version = Version.safeParse(request.getBootVersion()); if (version != null && version.getMajor() != null) { return new VersionInformation(version); } return null; } private ClientInformation determineClientInformation(ProjectRequest request) { if (request instanceof WebProjectRequest webProjectRequest) { Agent agent = determineAgent(webProjectRequest); String ip = determineIp(webProjectRequest); String country = determineCountry(webProjectRequest); if (agent != null || ip != null || country != null) { return new ClientInformation(agent, ip, country); } } return null; } private Agent determineAgent(WebProjectRequest request) { String userAgent = (String) request.getParameters().get("user-agent"); if (StringUtils.hasText(userAgent)) { return Agent.fromUserAgent(userAgent); } return null; } private String determineIp(WebProjectRequest request) { String candidate = (String) request.getParameters().get("cf-connecting-ip"); return (StringUtils.hasText(candidate)) ? candidate : (String) request.getParameters().get("x-forwarded-for"); } private String determineCountry(WebProjectRequest request) { String candidate = (String) request.getParameters().get("cf-ipcountry"); if (StringUtils.hasText(candidate) && !"xx".equalsIgnoreCase(candidate)) { return candidate; } return null; } }
InitializrMetadata metadata = event.getMetadata(); ProjectRequest request = event.getProjectRequest(); ProjectRequestDocument document = new ProjectRequestDocument(); document.setGenerationTimestamp(event.getTimestamp()); document.setGroupId(request.getGroupId()); document.setArtifactId(request.getArtifactId()); document.setPackageName(request.getPackageName()); document.setVersion(determineVersionInformation(request)); document.setClient(determineClientInformation(request)); document.setJavaVersion(request.getJavaVersion()); if (StringUtils.hasText(request.getJavaVersion()) && metadata.getJavaVersions().get(request.getJavaVersion()) == null) { document.triggerError().setJavaVersion(true); } document.setLanguage(request.getLanguage()); if (StringUtils.hasText(request.getLanguage()) && metadata.getLanguages().get(request.getLanguage()) == null) { document.triggerError().setLanguage(true); } document.setPackaging(request.getPackaging()); if (StringUtils.hasText(request.getPackaging()) && metadata.getPackagings().get(request.getPackaging()) == null) { document.triggerError().setPackaging(true); } document.setType(request.getType()); document.setBuildSystem(determineBuildSystem(request)); if (StringUtils.hasText(request.getType()) && metadata.getTypes().get(request.getType()) == null) { document.triggerError().setType(true); } // Let's not rely on the resolved dependencies here List<String> dependencies = new ArrayList<>(request.getDependencies()); List<String> validDependencies = dependencies.stream() .filter((id) -> metadata.getDependencies().get(id) != null) .collect(Collectors.toList()); document.setDependencies(new DependencyInformation(validDependencies)); List<String> invalidDependencies = dependencies.stream() .filter((id) -> (!validDependencies.contains(id))) .collect(Collectors.toList()); if (!invalidDependencies.isEmpty()) { document.triggerError().triggerInvalidDependencies(invalidDependencies); } // Let's make sure that the document is flagged as invalid no matter what if (event instanceof ProjectFailedEvent failed) { ErrorStateInformation errorState = document.triggerError(); if (failed.getCause() != null) { errorState.setMessage(failed.getCause().getMessage()); } } return document;
541
683
1,224
<no_super_class>
spring-io_initializr
initializr/initializr-actuator/src/main/java/io/spring/initializr/actuate/stat/StatsProperties.java
Elastic
cleanUri
class Elastic { /** * Elastic service uri. Overrides username and password when UserInfo is set. */ private String uri; /** * Elastic service username. */ private String username; /** * Elastic service password. */ private String password; /** * Name of the index. */ private String indexName = "initializr"; /** * Number of attempts before giving up. */ private int maxAttempts = 3; public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getIndexName() { return this.indexName; } public void setIndexName(String indexName) { this.indexName = indexName; } public int getMaxAttempts() { return this.maxAttempts; } public void setMaxAttempts(int maxAttempts) { this.maxAttempts = maxAttempts; } public String getUri() { return this.uri; } public void setUri(String uri) { this.uri = cleanUri(uri); } private static String cleanUri(String contextPath) {<FILL_FUNCTION_BODY>} }
if (StringUtils.hasText(contextPath) && contextPath.endsWith("/")) { return contextPath.substring(0, contextPath.length() - 1); } return contextPath;
403
54
457
<no_super_class>
spring-io_initializr
initializr/initializr-docs/src/main/java/io/spring/initializr/doc/generator/project/CustomProjectGenerationConfigurationExample.java
CustomProjectGenerationConfigurationExample
projectGenerationController
class CustomProjectGenerationConfigurationExample { // tag::code[] @Bean public CustomProjectGenerationController projectGenerationController(InitializrMetadataProvider metadataProvider, ApplicationContext applicationContext) {<FILL_FUNCTION_BODY>} // end::code[] static class CustomProjectRequestToDescriptionConverter implements ProjectRequestToDescriptionConverter<CustomProjectRequest> { @Override public ProjectDescription convert(CustomProjectRequest request, InitializrMetadata metadata) { return new MutableProjectDescription(); } } }
ProjectGenerationInvoker<CustomProjectRequest> projectGenerationInvoker = new ProjectGenerationInvoker<>( applicationContext, new CustomProjectRequestToDescriptionConverter()); return new CustomProjectGenerationController(metadataProvider, projectGenerationInvoker);
135
63
198
<no_super_class>
spring-io_initializr
initializr/initializr-docs/src/main/java/io/spring/initializr/doc/generator/project/CustomProjectGenerationController.java
CustomProjectGenerationController
projectRequest
class CustomProjectGenerationController extends ProjectGenerationController<CustomProjectRequest> { public CustomProjectGenerationController(InitializrMetadataProvider metadataProvider, ProjectGenerationInvoker<CustomProjectRequest> projectGenerationInvoker) { super(metadataProvider, projectGenerationInvoker); } @Override public CustomProjectRequest projectRequest(Map<String, String> headers) {<FILL_FUNCTION_BODY>} }
CustomProjectRequest request = new CustomProjectRequest(); request.getParameters().putAll(headers); request.initialize(getMetadata()); return request;
107
45
152
<methods>public void <init>(io.spring.initializr.metadata.InitializrMetadataProvider, ProjectGenerationInvoker<io.spring.initializr.doc.generator.project.CustomProjectRequest>) ,public ResponseEntity<byte[]> gradle(io.spring.initializr.doc.generator.project.CustomProjectRequest) ,public void invalidProjectRequest(HttpServletResponse, io.spring.initializr.web.project.InvalidProjectRequestException) throws java.io.IOException,public ResponseEntity<byte[]> pom(io.spring.initializr.doc.generator.project.CustomProjectRequest) ,public abstract io.spring.initializr.doc.generator.project.CustomProjectRequest projectRequest(Map<java.lang.String,java.lang.String>) ,public ResponseEntity<byte[]> springTgz(io.spring.initializr.doc.generator.project.CustomProjectRequest) throws java.io.IOException,public ResponseEntity<byte[]> springZip(io.spring.initializr.doc.generator.project.CustomProjectRequest) throws java.io.IOException<variables>private static final org.apache.commons.logging.Log logger,private final non-sealed io.spring.initializr.metadata.InitializrMetadataProvider metadataProvider,private final non-sealed ProjectGenerationInvoker<io.spring.initializr.doc.generator.project.CustomProjectRequest> projectGenerationInvoker
spring-io_initializr
initializr/initializr-docs/src/main/java/io/spring/initializr/doc/generator/project/ProjectGeneratorSetupExample.java
ProjectGeneratorSetupExample
createProjectGenerator
class ProjectGeneratorSetupExample { // tag::code[] public ProjectGenerator createProjectGenerator(ApplicationContext appContext) {<FILL_FUNCTION_BODY>} // end::code[] }
return new ProjectGenerator((context) -> { context.setParent(appContext); context.registerBean(SampleContributor.class, SampleContributor::new); });
49
51
100
<no_super_class>
spring-io_initializr
initializr/initializr-docs/src/main/java/io/spring/initializr/doc/generator/project/SampleContributor.java
SampleContributor
contribute
class SampleContributor implements ProjectContributor { @Override public void contribute(Path projectRoot) throws IOException {<FILL_FUNCTION_BODY>} }
Path file = Files.createFile(projectRoot.resolve("hello.txt")); try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(file))) { writer.println("Test"); }
43
58
101
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/BuildProjectGenerationConfiguration.java
BuildProjectGenerationConfiguration
junit5TestStarterContributor
class BuildProjectGenerationConfiguration { @Bean @ConditionalOnPlatformVersion("[2.2.0.M5,2.4.0-SNAPSHOT)") public BuildCustomizer<Build> junit5TestStarterContributor() {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnPlatformVersion("2.4.0-M1") public BuildCustomizer<Build> junitJupiterTestStarterContributor() { return (build) -> build.dependencies() .add("test", Dependency.withCoordinates("org.springframework.boot", "spring-boot-starter-test") .scope(DependencyScope.TEST_COMPILE)); } @Bean public DefaultStarterBuildCustomizer defaultStarterContributor(InitializrMetadata metadata) { return new DefaultStarterBuildCustomizer(metadata); } @Bean public DefaultMavenBuildCustomizer initializrMetadataMavenBuildCustomizer(ProjectDescription description, InitializrMetadata metadata) { return new DefaultMavenBuildCustomizer(description, metadata); } @Bean @ConditionalOnPackaging(WarPackaging.ID) public WarPackagingWebStarterBuildCustomizer warPackagingWebStarterBuildCustomizer(InitializrMetadata metadata) { return new WarPackagingWebStarterBuildCustomizer(metadata); } @Bean public DependencyManagementBuildCustomizer dependencyManagementBuildCustomizer(ProjectDescription description, InitializrMetadata metadata) { return new DependencyManagementBuildCustomizer(description, metadata); } @Bean public SimpleBuildCustomizer projectDescriptionBuildCustomizer(ProjectDescription description) { return new SimpleBuildCustomizer(description); } @Bean public SpringBootVersionRepositoriesBuildCustomizer repositoriesBuilderCustomizer(ProjectDescription description) { return new SpringBootVersionRepositoriesBuildCustomizer(description.getPlatformVersion()); } }
return (build) -> build.dependencies() .add("test", Dependency.withCoordinates("org.springframework.boot", "spring-boot-starter-test") .scope(DependencyScope.TEST_COMPILE) .exclusions(new Exclusion("org.junit.vintage", "junit-vintage-engine")));
470
88
558
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/DefaultStarterBuildCustomizer.java
DefaultStarterBuildCustomizer
customize
class DefaultStarterBuildCustomizer implements BuildCustomizer<Build> { /** * The id of the starter to use if no dependency is defined. */ static final String DEFAULT_STARTER = "root_starter"; private final BuildMetadataResolver buildResolver; DefaultStarterBuildCustomizer(InitializrMetadata metadata) { this.buildResolver = new BuildMetadataResolver(metadata); } @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } private boolean isValidStarter(Dependency dependency) { return dependency.isStarter() && Dependency.SCOPE_COMPILE.equals(dependency.getScope()); } }
boolean hasStarter = this.buildResolver.dependencies(build).anyMatch(this::isValidStarter); if (!hasStarter) { Dependency root = Dependency.createSpringBootStarter(""); root.setId(DEFAULT_STARTER); build.dependencies().add(DEFAULT_STARTER, MetadataBuildItemMapper.toDependency(root)); }
199
102
301
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/DependencyManagementBuildCustomizer.java
DependencyManagementBuildCustomizer
contributeDependencyManagement
class DependencyManagementBuildCustomizer implements BuildCustomizer<Build> { private final ProjectDescription description; private final InitializrMetadata metadata; public DependencyManagementBuildCustomizer(ProjectDescription description, InitializrMetadata metadata) { this.description = description; this.metadata = metadata; } @Override public void customize(Build build) { contributeDependencyManagement(build); } @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE - 5; } protected void contributeDependencyManagement(Build build) {<FILL_FUNCTION_BODY>} private Stream<Dependency> mapDependencies(Build build) { return build.dependencies() .ids() .map((id) -> this.metadata.getDependencies().get(id)) .filter(Objects::nonNull) .map((dependency) -> dependency.resolve(this.description.getPlatformVersion())); } private void resolveBom(Map<String, BillOfMaterials> boms, String bomId, Version requestedVersion) { if (!boms.containsKey(bomId)) { BillOfMaterials bom = this.metadata.getConfiguration() .getEnv() .getBoms() .get(bomId) .resolve(requestedVersion); bom.getAdditionalBoms().forEach((id) -> resolveBom(boms, id, requestedVersion)); boms.put(bomId, bom); } } }
Map<String, BillOfMaterials> resolvedBoms = new LinkedHashMap<>(); Map<String, Repository> repositories = new LinkedHashMap<>(); mapDependencies(build).forEach((dependency) -> { if (dependency.getBom() != null) { resolveBom(resolvedBoms, dependency.getBom(), this.description.getPlatformVersion()); } if (dependency.getRepository() != null) { String repositoryId = dependency.getRepository(); repositories.computeIfAbsent(repositoryId, (key) -> this.metadata.getConfiguration().getEnv().getRepositories().get(key)); } }); resolvedBoms.values() .forEach((bom) -> bom.getRepositories() .forEach((repositoryId) -> repositories.computeIfAbsent(repositoryId, (key) -> this.metadata.getConfiguration().getEnv().getRepositories().get(key)))); resolvedBoms.forEach((key, bom) -> { build.boms().add(key, MetadataBuildItemMapper.toBom(bom)); if (bom.getVersionProperty() != null) { build.properties().version(bom.getVersionProperty(), bom.getVersion()); } }); repositories.keySet().forEach((id) -> build.repositories().add(id));
381
362
743
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/SimpleBuildCustomizer.java
SimpleBuildCustomizer
customize
class SimpleBuildCustomizer implements BuildCustomizer<Build> { private final ProjectDescription description; public SimpleBuildCustomizer(ProjectDescription description) { this.description = description; } @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } }
build.settings() .group(this.description.getGroupId()) .artifact(this.description.getArtifactId()) .version(this.description.getVersion()); this.description.getRequestedDependencies() .forEach((id, dependency) -> build.dependencies().add(id, dependency));
102
83
185
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/SpringBootVersionRepositoriesBuildCustomizer.java
SpringBootVersionRepositoriesBuildCustomizer
getReleaseType
class SpringBootVersionRepositoriesBuildCustomizer implements BuildCustomizer<Build> { static final MavenRepository SPRING_MILESTONES = MavenRepository .withIdAndUrl("spring-milestones", "https://repo.spring.io/milestone") .name("Spring Milestones") .onlyReleases() .build(); static final MavenRepository SPRING_SNAPSHOTS = MavenRepository .withIdAndUrl("spring-snapshots", "https://repo.spring.io/snapshot") .name("Spring Snapshots") .onlySnapshots() .build(); private final Version springBootVersion; SpringBootVersionRepositoriesBuildCustomizer(Version springBootVersion) { this.springBootVersion = springBootVersion; } @Override public void customize(Build build) { build.repositories().add("maven-central"); switch (getReleaseType()) { case MILESTONE -> addMilestoneRepository(build); case SNAPSHOT -> { if (isMaintenanceRelease()) { addSnapshotRepository(build); } else { addMilestoneRepository(build); addSnapshotRepository(build); } } } } private ReleaseType getReleaseType() {<FILL_FUNCTION_BODY>} private boolean isMaintenanceRelease() { Integer patch = this.springBootVersion.getPatch(); return patch != null && patch > 0; } private void addSnapshotRepository(Build build) { build.repositories().add(SPRING_SNAPSHOTS); build.pluginRepositories().add(SPRING_SNAPSHOTS); } private void addMilestoneRepository(Build build) { build.repositories().add(SPRING_MILESTONES); build.pluginRepositories().add(SPRING_MILESTONES); } private enum ReleaseType { GA, MILESTONE, SNAPSHOT } }
Version.Qualifier qualifier = this.springBootVersion.getQualifier(); if (qualifier == null) { return ReleaseType.GA; } String id = qualifier.getId(); if ("RELEASE".equals(id)) { return ReleaseType.GA; } if (id.contains("SNAPSHOT")) { return ReleaseType.SNAPSHOT; } return ReleaseType.MILESTONE;
531
118
649
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/WarPackagingWebStarterBuildCustomizer.java
WarPackagingWebStarterBuildCustomizer
customize
class WarPackagingWebStarterBuildCustomizer implements BuildCustomizer<Build> { private final InitializrMetadata metadata; private final BuildMetadataResolver buildMetadataResolver; public WarPackagingWebStarterBuildCustomizer(InitializrMetadata metadata) { this.metadata = metadata; this.buildMetadataResolver = new BuildMetadataResolver(metadata); } @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE - 10; } private Dependency determineWebDependency(InitializrMetadata metadata) { Dependency web = metadata.getDependencies().get("web"); return (web != null) ? web : Dependency.createSpringBootStarter("web"); } }
if (!this.buildMetadataResolver.hasFacet(build, "web")) { // Need to be able to bootstrap the web app Dependency dependency = determineWebDependency(this.metadata); build.dependencies().add(dependency.getId(), MetadataBuildItemMapper.toDependency(dependency)); } // Add the tomcat starter in provided scope Dependency tomcat = Dependency.createSpringBootStarter("tomcat"); tomcat.setScope(Dependency.SCOPE_PROVIDED); build.dependencies().add("tomcat", MetadataBuildItemMapper.toDependency(tomcat));
205
155
360
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/gradle/DevelopmentOnlyDependencyGradleBuildCustomizer.java
DevelopmentOnlyDependencyGradleBuildCustomizer
customize
class DevelopmentOnlyDependencyGradleBuildCustomizer implements BuildCustomizer<GradleBuild> { private final String dependencyId; /** * Create a new instance with the identifier for the dependency. * @param dependencyId the id of the dependency */ public DevelopmentOnlyDependencyGradleBuildCustomizer(String dependencyId) { this.dependencyId = dependencyId; } @Override public void customize(GradleBuild build) {<FILL_FUNCTION_BODY>} }
Dependency dependency = build.dependencies().get(this.dependencyId); if (dependency != null) { build.dependencies() .add(this.dependencyId, GradleDependency.from(dependency).configuration("developmentOnly")); }
118
65
183
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/gradle/GradleAnnotationProcessorScopeBuildCustomizer.java
GradleAnnotationProcessorScopeBuildCustomizer
customize
class GradleAnnotationProcessorScopeBuildCustomizer implements BuildCustomizer<GradleBuild> { @Override public void customize(GradleBuild build) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } }
boolean annotationProcessorUsed = build.dependencies() .items() .anyMatch((dependency) -> dependency.getScope() == DependencyScope.ANNOTATION_PROCESSOR); if (annotationProcessorUsed) { build.configurations() .customize("compileOnly", (configuration) -> configuration.extendsFrom("annotationProcessor")); }
78
94
172
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/gradle/GradleBuildProjectContributor.java
GradleBuildProjectContributor
writeBuild
class GradleBuildProjectContributor implements BuildWriter, ProjectContributor { private final GradleBuildWriter buildWriter; private final GradleBuild build; private final IndentingWriterFactory indentingWriterFactory; private final String buildFileName; GradleBuildProjectContributor(GradleBuildWriter buildWriter, GradleBuild build, IndentingWriterFactory indentingWriterFactory, String buildFileName) { this.buildWriter = buildWriter; this.build = build; this.indentingWriterFactory = indentingWriterFactory; this.buildFileName = buildFileName; } @Override public void contribute(Path projectRoot) throws IOException { Path buildGradle = Files.createFile(projectRoot.resolve(this.buildFileName)); writeBuild(Files.newBufferedWriter(buildGradle)); } @Override public void writeBuild(Writer out) throws IOException {<FILL_FUNCTION_BODY>} }
try (IndentingWriter writer = this.indentingWriterFactory.createIndentingWriter("gradle", out)) { this.buildWriter.writeTo(writer, this.build); }
237
51
288
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/gradle/GradleConfigurationBuildCustomizer.java
GradleConfigurationBuildCustomizer
customize
class GradleConfigurationBuildCustomizer implements BuildCustomizer<GradleBuild> { @Override public void customize(GradleBuild build) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } }
boolean providedRuntimeUsed = build.dependencies() .items() .anyMatch((dependency) -> DependencyScope.PROVIDED_RUNTIME.equals(dependency.getScope())); boolean war = build.plugins().values().anyMatch((plugin) -> plugin.getId().equals("war")); if (providedRuntimeUsed && !war) { build.configurations().add("providedRuntime"); }
76
109
185
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/gradle/GradleProjectGenerationConfiguration.java
GradleProjectGenerationConfiguration
createGradleBuild
class GradleProjectGenerationConfiguration { private static final int LANGUAGE_PLUGINS_ORDER = Ordered.HIGHEST_PRECEDENCE + 5; private static final int PACKAGING_PLUGINS_ORDER = Ordered.HIGHEST_PRECEDENCE + 10; private static final int TEST_ORDER = 100; private final IndentingWriterFactory indentingWriterFactory; public GradleProjectGenerationConfiguration(IndentingWriterFactory indentingWriterFactory) { this.indentingWriterFactory = indentingWriterFactory; } @Bean public GradleBuild gradleBuild(ObjectProvider<BuildItemResolver> buildItemResolver, ObjectProvider<BuildCustomizer<?>> buildCustomizers) { return createGradleBuild(buildItemResolver.getIfAvailable(), buildCustomizers.orderedStream().collect(Collectors.toList())); } @SuppressWarnings("unchecked") private GradleBuild createGradleBuild(BuildItemResolver buildItemResolver, List<BuildCustomizer<?>> buildCustomizers) {<FILL_FUNCTION_BODY>} @Bean public BuildCustomizer<GradleBuild> defaultGradleBuildCustomizer(ProjectDescription description) { return (build) -> build.settings().sourceCompatibility(description.getLanguage().jvmVersion()); } @Bean public GradleConfigurationBuildCustomizer gradleConfigurationBuildCustomizer() { return new GradleConfigurationBuildCustomizer(); } @Bean @ConditionalOnLanguage(JavaLanguage.ID) public BuildCustomizer<GradleBuild> javaPluginContributor() { return BuildCustomizer.ordered(LANGUAGE_PLUGINS_ORDER, (build) -> build.plugins().add("java")); } @Bean @ConditionalOnLanguage(GroovyLanguage.ID) public BuildCustomizer<GradleBuild> groovyPluginContributor() { return BuildCustomizer.ordered(LANGUAGE_PLUGINS_ORDER, (build) -> build.plugins().add("groovy")); } @Bean @ConditionalOnPackaging(WarPackaging.ID) public BuildCustomizer<GradleBuild> warPluginContributor() { return BuildCustomizer.ordered(PACKAGING_PLUGINS_ORDER, (build) -> build.plugins().add("war")); } @Bean @ConditionalOnGradleVersion({ "6", "7", "8" }) BuildCustomizer<GradleBuild> springBootPluginContributor(ProjectDescription description, ObjectProvider<DependencyManagementPluginVersionResolver> versionResolver, InitializrMetadata metadata) { return new SpringBootPluginBuildCustomizer(description, versionResolver .getIfAvailable(() -> new InitializrDependencyManagementPluginVersionResolver(metadata))); } @Bean @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_GROOVY) public GradleBuildProjectContributor gradleBuildProjectContributor(GroovyDslGradleBuildWriter buildWriter, GradleBuild build) { return new GradleBuildProjectContributor(buildWriter, build, this.indentingWriterFactory, "build.gradle"); } @Bean @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_KOTLIN) public GradleBuildProjectContributor gradleKtsBuildProjectContributor(KotlinDslGradleBuildWriter buildWriter, GradleBuild build) { return new GradleBuildProjectContributor(buildWriter, build, this.indentingWriterFactory, "build.gradle.kts"); } /** * Configuration specific to projects using Gradle 6. */ @Configuration @ConditionalOnGradleVersion("6") @Deprecated static class Gradle6ProjectGenerationConfiguration { @Bean GradleWrapperContributor gradle6WrapperContributor() { return new GradleWrapperContributor("6"); } } /** * Configuration specific to projects using Gradle 7. */ @Configuration @ConditionalOnGradleVersion("7") static class Gradle7ProjectGenerationConfiguration { @Bean GradleWrapperContributor gradle7WrapperContributor() { return new GradleWrapperContributor("7"); } } /** * Configuration specific to projects using Gradle 8. */ @Configuration @ConditionalOnGradleVersion("8") static class Gradle8ProjectGenerationConfiguration { @Bean GradleWrapperContributor gradle8WrapperContributor() { return new GradleWrapperContributor("8"); } } /** * Configuration specific to projects using Gradle (Groovy DSL). */ @Configuration @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_GROOVY) @ConditionalOnGradleVersion({ "6", "7", "8" }) static class GradleGroovyProjectGenerationConfiguration { @Bean GroovyDslGradleBuildWriter gradleBuildWriter() { return new GroovyDslGradleBuildWriter(); } @Bean SettingsGradleProjectContributor settingsGradleProjectContributor(GradleBuild build, IndentingWriterFactory indentingWriterFactory) { return new SettingsGradleProjectContributor(build, indentingWriterFactory, new GroovyDslGradleSettingsWriter(), "settings.gradle"); } @Bean @ConditionalOnPlatformVersion("2.2.0.M3") BuildCustomizer<GradleBuild> testTaskContributor() { return BuildCustomizer.ordered(TEST_ORDER, (build) -> build.tasks().customize("test", (test) -> test.invoke("useJUnitPlatform"))); } @Bean GradleAnnotationProcessorScopeBuildCustomizer gradleAnnotationProcessorScopeBuildCustomizer() { return new GradleAnnotationProcessorScopeBuildCustomizer(); } } /** * Configuration specific to projects using Gradle (Kotlin DSL). */ @Configuration @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_KOTLIN) @ConditionalOnGradleVersion({ "6", "7", "8" }) static class GradleKtsProjectGenerationConfiguration { @Bean KotlinDslGradleBuildWriter gradleKtsBuildWriter() { return new KotlinDslGradleBuildWriter(); } @Bean SettingsGradleProjectContributor settingsGradleKtsProjectContributor(GradleBuild build, IndentingWriterFactory indentingWriterFactory) { return new SettingsGradleProjectContributor(build, indentingWriterFactory, new KotlinDslGradleSettingsWriter(), "settings.gradle.kts"); } @Bean @ConditionalOnPlatformVersion("2.2.0.M3") BuildCustomizer<GradleBuild> testTaskContributor() { return BuildCustomizer.ordered(TEST_ORDER, (build) -> build.tasks().customizeWithType("Test", (test) -> test.invoke("useJUnitPlatform"))); } @Bean GradleAnnotationProcessorScopeBuildCustomizer gradleAnnotationProcessorScopeBuildCustomizer() { return new GradleAnnotationProcessorScopeBuildCustomizer(); } } }
GradleBuild build = (buildItemResolver != null) ? new GradleBuild(buildItemResolver) : new GradleBuild(); LambdaSafe.callbacks(BuildCustomizer.class, buildCustomizers, build) .invoke((customizer) -> customizer.customize(build)); return build;
1,884
79
1,963
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/gradle/OnGradleVersionCondition.java
OnGradleVersionCondition
matches
class OnGradleVersionCondition extends ProjectGenerationCondition { private static final VersionRange GRADLE_6_VERSION_RANGE = VersionParser.DEFAULT .parseRange("[2.2.2.RELEASE,2.5.0-RC1)"); private static final VersionRange GRADLE_7_VERSION_RANGE = VersionParser.DEFAULT.parseRange("[2.5.0-RC1,2.7.10)"); private static final VersionRange GRADLE_8_VERSION_RANGE = VersionParser.DEFAULT.parseRange("2.7.10"); @Override protected boolean matches(ProjectDescription description, ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>} private String determineGradleGeneration(Version platformVersion) { if (platformVersion == null) { return null; } else if (GRADLE_6_VERSION_RANGE.match(platformVersion)) { return "6"; } else if (GRADLE_7_VERSION_RANGE.match(platformVersion)) { return "7"; } else if (GRADLE_8_VERSION_RANGE.match(platformVersion)) { return "8"; } else { return null; } } }
String gradleGeneration = determineGradleGeneration(description.getPlatformVersion()); if (gradleGeneration == null) { return false; } String[] values = (String[]) metadata.getAnnotationAttributes(ConditionalOnGradleVersion.class.getName()) .get("value"); return Arrays.asList(values).contains(gradleGeneration);
322
93
415
<methods>public non-sealed void <init>() ,public boolean matches(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata) <variables>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/gradle/SettingsGradleProjectContributor.java
SettingsGradleProjectContributor
contribute
class SettingsGradleProjectContributor implements ProjectContributor { private final GradleBuild build; private final IndentingWriterFactory indentingWriterFactory; private final GradleSettingsWriter settingsWriter; private final String settingsFileName; SettingsGradleProjectContributor(GradleBuild build, IndentingWriterFactory indentingWriterFactory, GradleSettingsWriter settingsWriter, String settingsFileName) { this.build = build; this.indentingWriterFactory = indentingWriterFactory; this.settingsWriter = settingsWriter; this.settingsFileName = settingsFileName; } @Override public void contribute(Path projectRoot) throws IOException {<FILL_FUNCTION_BODY>} }
Path settingsGradle = Files.createFile(projectRoot.resolve(this.settingsFileName)); try (IndentingWriter writer = this.indentingWriterFactory.createIndentingWriter("gradle", Files.newBufferedWriter(settingsGradle))) { this.settingsWriter.writeTo(writer, this.build); }
176
86
262
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/gradle/SpringBootPluginBuildCustomizer.java
SpringBootPluginBuildCustomizer
customize
class SpringBootPluginBuildCustomizer implements BuildCustomizer<GradleBuild> { /** * Order of this customizer. Runs before default customizers so that these plugins are * added at the beginning of the {@code plugins} block. */ public static final int ORDER = -100; private final ProjectDescription description; private final DependencyManagementPluginVersionResolver versionResolver; public SpringBootPluginBuildCustomizer(ProjectDescription description, DependencyManagementPluginVersionResolver versionResolver) { this.description = description; this.versionResolver = versionResolver; } @Override public void customize(GradleBuild build) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return ORDER; } }
build.plugins() .add("org.springframework.boot", (plugin) -> plugin.setVersion(this.description.getPlatformVersion().toString())); build.plugins() .add("io.spring.dependency-management", (plugin) -> plugin .setVersion(this.versionResolver.resolveDependencyManagementPluginVersion(this.description)));
187
90
277
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/maven/DefaultMavenBuildCustomizer.java
DefaultMavenBuildCustomizer
customize
class DefaultMavenBuildCustomizer implements BuildCustomizer<MavenBuild> { private final ProjectDescription description; private final InitializrMetadata metadata; public DefaultMavenBuildCustomizer(ProjectDescription description, InitializrMetadata metadata) { this.description = description; this.metadata = metadata; } @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} private boolean hasBom(MavenBuild build, BillOfMaterials bom) { return build.boms() .items() .anyMatch((candidate) -> candidate.getGroupId().equals(bom.getGroupId()) && candidate.getArtifactId().equals(bom.getArtifactId())); } }
build.settings().name(this.description.getName()).description(this.description.getDescription()); build.properties().property("java.version", this.description.getLanguage().jvmVersion()); build.plugins().add("org.springframework.boot", "spring-boot-maven-plugin"); Maven maven = this.metadata.getConfiguration().getEnv().getMaven(); String springBootVersion = this.description.getPlatformVersion().toString(); ParentPom parentPom = maven.resolveParentPom(springBootVersion); if (parentPom.isIncludeSpringBootBom()) { String versionProperty = "spring-boot.version"; BillOfMaterials springBootBom = MetadataBuildItemMapper .toBom(this.metadata.createSpringBootBom(springBootVersion, versionProperty)); if (!hasBom(build, springBootBom)) { build.properties().version(VersionProperty.of(versionProperty, true), springBootVersion); build.boms().add("spring-boot", springBootBom); } } if (!maven.isSpringBootStarterParent(parentPom)) { build.properties() .property("project.build.sourceEncoding", "UTF-8") .property("project.reporting.outputEncoding", "UTF-8"); } build.settings() .parent(parentPom.getGroupId(), parentPom.getArtifactId(), parentPom.getVersion(), parentPom.getRelativePath());
186
387
573
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/maven/MavenBuildProjectContributor.java
MavenBuildProjectContributor
writeBuild
class MavenBuildProjectContributor implements BuildWriter, ProjectContributor { private final MavenBuild build; private final IndentingWriterFactory indentingWriterFactory; private final MavenBuildWriter buildWriter; public MavenBuildProjectContributor(MavenBuild build, IndentingWriterFactory indentingWriterFactory) { this.build = build; this.indentingWriterFactory = indentingWriterFactory; this.buildWriter = new MavenBuildWriter(); } @Override public void contribute(Path projectRoot) throws IOException { Path pomFile = Files.createFile(projectRoot.resolve("pom.xml")); writeBuild(Files.newBufferedWriter(pomFile)); } @Override public void writeBuild(Writer out) throws IOException {<FILL_FUNCTION_BODY>} }
try (IndentingWriter writer = this.indentingWriterFactory.createIndentingWriter("maven", out)) { this.buildWriter.writeTo(writer, this.build); }
208
51
259
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/maven/MavenProjectGenerationConfiguration.java
MavenProjectGenerationConfiguration
createBuild
class MavenProjectGenerationConfiguration { @Bean MavenWrapperContributor mavenWrapperContributor() { return new MavenWrapperContributor("3"); } @Bean public MavenBuild mavenBuild(ObjectProvider<BuildItemResolver> buildItemResolver, ObjectProvider<BuildCustomizer<?>> buildCustomizers) { return createBuild(buildItemResolver.getIfAvailable(), buildCustomizers.orderedStream().collect(Collectors.toList())); } @SuppressWarnings("unchecked") private MavenBuild createBuild(BuildItemResolver buildItemResolver, List<BuildCustomizer<?>> buildCustomizers) {<FILL_FUNCTION_BODY>} @Bean public MavenBuildProjectContributor mavenBuildProjectContributor(MavenBuild build, IndentingWriterFactory indentingWriterFactory) { return new MavenBuildProjectContributor(build, indentingWriterFactory); } @Bean @ConditionalOnPackaging(WarPackaging.ID) public BuildCustomizer<MavenBuild> mavenWarPackagingConfigurer() { return (build) -> build.settings().packaging("war"); } }
MavenBuild build = (buildItemResolver != null) ? new MavenBuild(buildItemResolver) : new MavenBuild(); LambdaSafe.callbacks(BuildCustomizer.class, buildCustomizers, build) .invoke((customizer) -> customizer.customize(build)); return build;
294
79
373
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/build/maven/OptionalDependencyMavenBuildCustomizer.java
OptionalDependencyMavenBuildCustomizer
customize
class OptionalDependencyMavenBuildCustomizer implements BuildCustomizer<MavenBuild> { private final String dependencyId; /** * Create a new instance with the identifier for the dependency. * @param dependencyId the id of the dependency */ public OptionalDependencyMavenBuildCustomizer(String dependencyId) { this.dependencyId = dependencyId; } @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} }
Dependency dependency = build.dependencies().get(this.dependencyId); if (dependency != null) { build.dependencies().add(this.dependencyId, MavenDependency.from(dependency).optional(true)); }
116
61
177
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/MainSourceCodeProjectContributor.java
MainSourceCodeProjectContributor
customizeMainApplicationType
class MainSourceCodeProjectContributor<T extends TypeDeclaration, C extends CompilationUnit<T>, S extends SourceCode<T, C>> implements ProjectContributor { private final ProjectDescription description; private final Supplier<S> sourceFactory; private final SourceCodeWriter<S> sourceWriter; private final ObjectProvider<MainApplicationTypeCustomizer<? extends TypeDeclaration>> mainTypeCustomizers; private final ObjectProvider<MainCompilationUnitCustomizer<?, ?>> mainCompilationUnitCustomizers; private final ObjectProvider<MainSourceCodeCustomizer<?, ?, ?>> mainSourceCodeCustomizers; public MainSourceCodeProjectContributor(ProjectDescription description, Supplier<S> sourceFactory, SourceCodeWriter<S> sourceWriter, ObjectProvider<MainApplicationTypeCustomizer<?>> mainTypeCustomizers, ObjectProvider<MainCompilationUnitCustomizer<?, ?>> mainCompilationUnitCustomizers, ObjectProvider<MainSourceCodeCustomizer<?, ?, ?>> mainSourceCodeCustomizers) { this.description = description; this.sourceFactory = sourceFactory; this.sourceWriter = sourceWriter; this.mainTypeCustomizers = mainTypeCustomizers; this.mainCompilationUnitCustomizers = mainCompilationUnitCustomizers; this.mainSourceCodeCustomizers = mainSourceCodeCustomizers; } @Override public void contribute(Path projectRoot) throws IOException { S sourceCode = this.sourceFactory.get(); String applicationName = this.description.getApplicationName(); C compilationUnit = sourceCode.createCompilationUnit(this.description.getPackageName(), applicationName); T mainApplicationType = compilationUnit.createTypeDeclaration(applicationName); customizeMainApplicationType(mainApplicationType); customizeMainCompilationUnit(compilationUnit); customizeMainSourceCode(sourceCode); this.sourceWriter.writeTo( this.description.getBuildSystem().getMainSource(projectRoot, this.description.getLanguage()), sourceCode); } @SuppressWarnings("unchecked") private void customizeMainApplicationType(T mainApplicationType) {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") private void customizeMainCompilationUnit(C compilationUnit) { List<MainCompilationUnitCustomizer<?, ?>> customizers = this.mainCompilationUnitCustomizers.orderedStream() .collect(Collectors.toList()); LambdaSafe.callbacks(MainCompilationUnitCustomizer.class, customizers, compilationUnit) .invoke((customizer) -> customizer.customize(compilationUnit)); } @SuppressWarnings("unchecked") private void customizeMainSourceCode(S sourceCode) { List<MainSourceCodeCustomizer<?, ?, ?>> customizers = this.mainSourceCodeCustomizers.orderedStream() .collect(Collectors.toList()); LambdaSafe.callbacks(MainSourceCodeCustomizer.class, customizers, sourceCode) .invoke((customizer) -> customizer.customize(sourceCode)); } }
List<MainApplicationTypeCustomizer<?>> customizers = this.mainTypeCustomizers.orderedStream() .collect(Collectors.toList()); LambdaSafe.callbacks(MainApplicationTypeCustomizer.class, customizers, mainApplicationType) .invoke((customizer) -> customizer.customize(mainApplicationType));
760
84
844
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/ServletInitializerContributor.java
ServletInitializerContributor
customize
class ServletInitializerContributor implements MainSourceCodeCustomizer<TypeDeclaration, CompilationUnit<TypeDeclaration>, SourceCode<TypeDeclaration, CompilationUnit<TypeDeclaration>>> { private final String packageName; private final String initializerClassName; private final ObjectProvider<ServletInitializerCustomizer<?>> servletInitializerCustomizers; ServletInitializerContributor(String packageName, String initializerClassName, ObjectProvider<ServletInitializerCustomizer<?>> servletInitializerCustomizers) { this.packageName = packageName; this.initializerClassName = initializerClassName; this.servletInitializerCustomizers = servletInitializerCustomizers; } @Override public void customize(SourceCode<TypeDeclaration, CompilationUnit<TypeDeclaration>> sourceCode) {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") private void customizeServletInitializer(TypeDeclaration servletInitializer) { List<ServletInitializerCustomizer<?>> customizers = this.servletInitializerCustomizers.orderedStream() .collect(Collectors.toList()); LambdaSafe.callbacks(ServletInitializerCustomizer.class, customizers, servletInitializer) .invoke((customizer) -> customizer.customize(servletInitializer)); } }
CompilationUnit<TypeDeclaration> compilationUnit = sourceCode.createCompilationUnit(this.packageName, "ServletInitializer"); TypeDeclaration servletInitializer = compilationUnit.createTypeDeclaration("ServletInitializer"); servletInitializer.extend(this.initializerClassName); customizeServletInitializer(servletInitializer);
326
90
416
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/TestSourceCodeProjectContributor.java
TestSourceCodeProjectContributor
customizeTestSourceCode
class TestSourceCodeProjectContributor<T extends TypeDeclaration, C extends CompilationUnit<T>, S extends SourceCode<T, C>> implements ProjectContributor { private final ProjectDescription description; private final Supplier<S> sourceFactory; private final SourceCodeWriter<S> sourceWriter; private final ObjectProvider<TestApplicationTypeCustomizer<?>> testApplicationTypeCustomizers; private final ObjectProvider<TestSourceCodeCustomizer<?, ?, ?>> testSourceCodeCustomizers; public TestSourceCodeProjectContributor(ProjectDescription description, Supplier<S> sourceFactory, SourceCodeWriter<S> sourceWriter, ObjectProvider<TestApplicationTypeCustomizer<?>> testApplicationTypeCustomizers, ObjectProvider<TestSourceCodeCustomizer<?, ?, ?>> testSourceCodeCustomizers) { this.description = description; this.sourceFactory = sourceFactory; this.sourceWriter = sourceWriter; this.testApplicationTypeCustomizers = testApplicationTypeCustomizers; this.testSourceCodeCustomizers = testSourceCodeCustomizers; } @Override public void contribute(Path projectRoot) throws IOException { S sourceCode = this.sourceFactory.get(); String testName = this.description.getApplicationName() + "Tests"; C compilationUnit = sourceCode.createCompilationUnit(this.description.getPackageName(), testName); T testApplicationType = compilationUnit.createTypeDeclaration(testName); customizeTestApplicationType(testApplicationType); customizeTestSourceCode(sourceCode); this.sourceWriter.writeTo( this.description.getBuildSystem().getTestSource(projectRoot, this.description.getLanguage()), sourceCode); } @SuppressWarnings("unchecked") private void customizeTestApplicationType(TypeDeclaration testApplicationType) { List<TestApplicationTypeCustomizer<?>> customizers = this.testApplicationTypeCustomizers.orderedStream() .collect(Collectors.toList()); LambdaSafe.callbacks(TestApplicationTypeCustomizer.class, customizers, testApplicationType) .invoke((customizer) -> customizer.customize(testApplicationType)); } @SuppressWarnings("unchecked") private void customizeTestSourceCode(S sourceCode) {<FILL_FUNCTION_BODY>} }
List<TestSourceCodeCustomizer<?, ?, ?>> customizers = this.testSourceCodeCustomizers.orderedStream() .collect(Collectors.toList()); LambdaSafe.callbacks(TestSourceCodeCustomizer.class, customizers, sourceCode) .invoke((customizer) -> customizer.customize(sourceCode));
574
86
660
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/groovy/GroovyDependenciesConfigurer.java
GroovyDependenciesConfigurer
customize
class GroovyDependenciesConfigurer implements BuildCustomizer<Build> { private final boolean isUsingGroovy4; GroovyDependenciesConfigurer(boolean isUsingGroovy4) { this.isUsingGroovy4 = isUsingGroovy4; } @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} }
String groupId = this.isUsingGroovy4 ? "org.apache.groovy" : "org.codehaus.groovy"; build.dependencies().add("groovy", groupId, "groovy", DependencyScope.COMPILE);
104
70
174
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/groovy/GroovyMavenBuildCustomizer.java
GroovyMavenBuildCustomizer
customize
class GroovyMavenBuildCustomizer implements BuildCustomizer<MavenBuild> { @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} }
build.plugins().add("org.codehaus.gmavenplus", "gmavenplus-plugin", (groovyMavenPlugin) -> { groovyMavenPlugin.version("1.13.1"); groovyMavenPlugin.execution(null, (execution) -> execution.goal("addSources") .goal("addTestSources") .goal("generateStubs") .goal("compile") .goal("generateTestStubs") .goal("compileTests") .goal("removeStubs") .goal("removeTestStubs")); });
50
161
211
<no_super_class>
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/groovy/GroovyProjectGenerationConfiguration.java
GroovyProjectGenerationConfiguration
mainGroovySourceCodeProjectContributor
class GroovyProjectGenerationConfiguration { private final ProjectDescription description; private final IndentingWriterFactory indentingWriterFactory; public GroovyProjectGenerationConfiguration(ProjectDescription description, IndentingWriterFactory indentingWriterFactory) { this.description = description; this.indentingWriterFactory = indentingWriterFactory; } @Bean public MainSourceCodeProjectContributor<GroovyTypeDeclaration, GroovyCompilationUnit, GroovySourceCode> mainGroovySourceCodeProjectContributor( ObjectProvider<MainApplicationTypeCustomizer<?>> mainApplicationTypeCustomizers, ObjectProvider<MainCompilationUnitCustomizer<?, ?>> mainCompilationUnitCustomizers, ObjectProvider<MainSourceCodeCustomizer<?, ?, ?>> mainSourceCodeCustomizers) {<FILL_FUNCTION_BODY>} @Bean public TestSourceCodeProjectContributor<GroovyTypeDeclaration, GroovyCompilationUnit, GroovySourceCode> testGroovySourceCodeProjectContributor( ObjectProvider<TestApplicationTypeCustomizer<?>> testApplicationTypeCustomizers, ObjectProvider<TestSourceCodeCustomizer<?, ?, ?>> testSourceCodeCustomizers) { return new TestSourceCodeProjectContributor<>(this.description, GroovySourceCode::new, new GroovySourceCodeWriter(this.indentingWriterFactory), testApplicationTypeCustomizers, testSourceCodeCustomizers); } }
return new MainSourceCodeProjectContributor<>(this.description, GroovySourceCode::new, new GroovySourceCodeWriter(this.indentingWriterFactory), mainApplicationTypeCustomizers, mainCompilationUnitCustomizers, mainSourceCodeCustomizers);
366
68
434
<no_super_class>