private Map parse(String text) {
String clean = text.replaceAll("(?m)#.*$", "");
Map result = new LinkedHashMap<>();
int position = 0;
while (position < clean.length()) {
int equals = clean.indexOf('=', position);
if (equals < 0) {
break;
}
int lineStart = clean.lastIndexOf('\n', equals);
String alias = clean.substring(lineStart + 1, equals).trim();
int start = equals + 1;
while (start < clean.length() && Character.isWhitespace(clean.charAt(start))) {
start++;
}
// Ignore non-TNS lines such as IFILE=value.
if (!alias.matches("[A-Za-z0-9_.-]+")
|| start >= clean.length()
|| clean.charAt(start) != '(') {
position = equals + 1;
continue;
}
int depth = 0;
boolean quoted = false;
int end = start;
while (end < clean.length()) {
char c = clean.charAt(end);
if (c == '"') {
quoted = !quoted;
}
if (!quoted) {
if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
if (depth == 0) {
end++;
break;
}
}
}
end++;
}
if (depth != 0) {
throw new IllegalArgumentException("Unbalanced TNS description for alias: " + alias);
}
if (result.putIfAbsent(alias, clean.substring(start, end)) != null) {
throw new IllegalArgumentException("Duplicate TNS alias: " + alias);
}
position = end;
}
if (result.isEmpty()) {
throw new IllegalArgumentException("No valid TNS aliases were found.");
}
return result;
}
Top comments (0)