From: Niki Roo Date: Fri, 10 May 2019 16:25:40 +0000 (+0200) Subject: bundle: new get/setList X-Git-Url: http://git.nikiroo.be/?p=nikiroo-utils.git;a=commitdiff_plain;h=7c192d3ccc7966cc26625f79cf7e97d565506f77 bundle: new get/setList --- diff --git a/src/be/nikiroo/utils/resources/Bundle.java b/src/be/nikiroo/utils/resources/Bundle.java index 92b02eb..f01aa44 100644 --- a/src/be/nikiroo/utils/resources/Bundle.java +++ b/src/be/nikiroo/utils/resources/Bundle.java @@ -387,6 +387,101 @@ public class Bundle> { setString(id, "#" + rs + gs + bs + as); } + /** + * Return the value associated to the given id as a list of values if it is + * found and can be parsed. + * + * @param id + * the id of the value to get + * + * @return the associated list, empty if the value is empty, NULL if it is + * not found or cannot be parsed as a list + */ + public List getList(E id) { + List list = new ArrayList(); + String raw = getString(id); + try { + boolean inQuote = false; + boolean prevIsBackSlash = false; + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < raw.length(); i++) { + char car = raw.charAt(i); + + if (prevIsBackSlash) { + builder.append(car); + prevIsBackSlash = false; + } else { + switch (car) { + case '"': + if (inQuote) { + list.add(builder.toString()); + builder.setLength(0); + } + + inQuote = !inQuote; + break; + case '\\': + prevIsBackSlash = true; + break; + case ' ': + case '\n': + case '\r': + if (inQuote) { + builder.append(car); + } + break; + + case ',': + if (!inQuote) { + break; + } + // continue to default + default: + if (!inQuote) { + // Bad format! + return null; + } + + builder.append(car); + break; + } + } + } + + if (inQuote || prevIsBackSlash) { + // Bad format! + return null; + } + + } catch (Exception e) { + return null; + } + + return list; + } + + /** + * Set the value associated to the given id as a list of values. + * + * @param id + * the id of the value to set + * @param list + * the new list of values + */ + public void setList(E id, List list) { + StringBuilder builder = new StringBuilder(); + for (String item : list) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append('"')// + .append(item.replace("\\", "\\\\").replace("\"", "\\\""))// + .append('"'); + } + + setString(id, builder.toString()); + } + /** * Create/update the .properties file. *