public static List<List<Line>> splitMessageByBoundary( final List<Line> message, final String boundary) throws BatchDeserializerException { final List<List<Line>> messageParts = new LinkedList<List<Line>>(); List<Line> currentPart = new LinkedList<Line>(); boolean isEndReached = false; final String quotedBoundary = Pattern.quote(boundary); final Pattern boundaryDelimiterPattern = Pattern.compile("--" + quotedBoundary + "--\\s*"); final Pattern boundaryPattern = Pattern.compile("--" + quotedBoundary + "\\s*"); for (Line currentLine : message) { if (boundaryDelimiterPattern.matcher(currentLine.toString()).matches()) { removeEndingCRLFFromList(currentPart); messageParts.add(currentPart); isEndReached = true; } else if (boundaryPattern.matcher(currentLine.toString()).matches()) { removeEndingCRLFFromList(currentPart); messageParts.add(currentPart); currentPart = new LinkedList<Line>(); } else { currentPart.add(currentLine); } if (isEndReached) { break; } } // Remove preamble if (messageParts.size() > 0) { messageParts.remove(0); } if (!isEndReached) { final int lineNumber = (message.size() > 0) ? message.get(0).getLineNumber() : 0; throw new BatchDeserializerException( "Missing close boundary delimiter", BatchDeserializerException.MessageKeys.MISSING_CLOSE_DELIMITER, Integer.toString(lineNumber)); } return messageParts; }