1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.kuali.student.enrollment.class2.courseoffering.service.impl;
18
19 import org.apache.commons.lang.StringUtils;
20 import org.kuali.student.enrollment.class2.courseoffering.service.CourseOfferingCodeGenerator;
21 import org.kuali.student.enrollment.courseoffering.dto.CourseOfferingInfo;
22
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.Comparator;
26 import java.util.List;
27 import java.util.Map;
28
29
30
31
32
33
34 public class CourseOfferingCodeGeneratorImpl implements CourseOfferingCodeGenerator {
35
36
37 @Override
38 public String generateActivityOfferingCode(Map<String, Object> generationProperties) {
39
40 List<String> existingActivityOfferings = (List<String>)generationProperties.get(CourseOfferingCodeGenerator.ACTIVITY_OFFERING_CODE_LIST_KEY);
41
42
43 if (existingActivityOfferings == null || existingActivityOfferings.isEmpty()) {
44 return "A";
45 }
46
47 List<String> aoCodes = new ArrayList<String>();
48 for (String aoCode : existingActivityOfferings) {
49 aoCodes.add(aoCode);
50 }
51
52 return calculateNextCode(aoCodes);
53 }
54
55 @Override
56 public String generateCourseOfferingInternalCode(List<CourseOfferingInfo> existingCourseOfferings) {
57
58
59 if (existingCourseOfferings == null || existingCourseOfferings.isEmpty()) {
60 return "A";
61 }
62
63 List<String> internalCodes = new ArrayList<String>();
64 for (CourseOfferingInfo coInfo : existingCourseOfferings) {
65 if (coInfo.getCourseNumberSuffix() != null) {
66 internalCodes.add(coInfo.getCourseNumberSuffix());
67 }
68 }
69
70 return calculateNextCode(internalCodes);
71 }
72
73 public String calculateNextCode(List<String> codes){
74
75 if (!codes.contains("A")) {
76 return "A";
77 }
78
79
80 Collections.sort(codes, new Comparator<String>() {
81 @Override
82 public int compare(String o1, String o2) {
83 if (o1.length() == o2.length()) {
84 return o1.compareTo(o2);
85 } else {
86 return o1.length() - o2.length();
87 }
88 }
89 });
90
91
92 for (String s : codes) {
93
94 String nextCode = getNextCode(s);
95 if (!codes.contains(nextCode)) {
96 return nextCode;
97 }
98 }
99
100
101 throw new RuntimeException("Error generating codes");
102 }
103
104
105
106
107
108
109
110
111 public String getNextCode(String source){
112 if (StringUtils.isEmpty(source)) {
113 return "A";
114 } else if (StringUtils.endsWithIgnoreCase(source, "Z")) {
115 return getNextCode(StringUtils.substringBeforeLast(source, "Z")) + "A";
116 } else {
117 char lastLetter = source.charAt(source.length() - 1);
118 return StringUtils.substringBeforeLast(source, "" + lastLetter) + ++lastLetter;
119 }
120 }
121 }