эти две части дублированы. Вы можете сделать метод для обработки строки
try {
String template = new String(sourceTemplate);
// Substitute for %CODE%
code = new String(reqId);
template = processString(template, 6, "%CODE%", code);
// Substitute for %ALTCODE%
altcode = code.substring(0, 5) + "-" + code.substring(5, 8);
template = processString(template, 9, "%ALTCODE%", altcode);
out.print(template);
} catch (Exception e) {
}
private String processString(String template, int length, String code, String mid) {
int templateSplitBegin = template.indexOf(code);
int templateSplitEnd = templateSplitBegin + len;
String templatePartOne = new String(
template.substring(0, templateSplitBegin));
String templatePartTwo = new String(
template.substring(templateSplitEnd, template.length()));
return new String(templatePartOne + mid + templatePartTwo);
}