GroupByParser { public static GroupBy parse(String expr) { List<GroupBy.Item> items = new ArrayList<>(); GroupBy.Item item; String[] names = Strings.split(expr, ','); for (String name : names) { String[] parts = Strings.splitWhitespaces(name); if (parts.length <= 2) { String[] join = Strings.split(parts[0], "."); if (join.length == 1) { if (parts.length == 1) { item = new GroupBy.Item(parts[0]); } else { item = new GroupBy.Item(parts[0], parts[1]); } } else if (join.length == 2) { if (parts.length == 1) { item = new GroupBy.Item(join[1], null, join[0]); } else { item = new GroupBy.Item(join[1], parts[1], join[0]); } } else { throw new BadRequestException("Invalid join item '" + parts[0] + "'"); } } else { throw new BadRequestException("Invalid select item '" + name + "'"); } items.add(item); } return new GroupBy(items.toArray(new GroupBy.Item[items.size()])); }  static GroupBy parse(String expr);  }
@Test public void testSingle() { GroupBy groupBy = GroupByParser.parse("name"); assertSingleGroupBy(groupBy, "name", null, null); groupBy = GroupByParser.parse("name n"); assertSingleGroupBy(groupBy, "name", "n", null); groupBy = GroupByParser.parse("t.name"); assertSingleGroupBy(groupBy, "name", null, "t"); groupBy = GroupByParser.parse("t.name n"); assertSingleGroupBy(groupBy, "name", "n", "t"); }
@Test public void testMulti() { GroupBy groupBy = GroupByParser.parse("id,name"); assertEquals(2, groupBy.items().length); assertGroupBy(groupBy.items()[0], "id", null, null); assertGroupBy(groupBy.items()[1], "name", null, null); groupBy = GroupByParser.parse("id i,name n"); assertGroupBy(groupBy.items()[0], "id", "i", null); assertGroupBy(groupBy.items()[1], "name", "n", null); groupBy = GroupByParser.parse("t.id i,t.name n"); assertGroupBy(groupBy.items()[0], "id", "i", "t"); assertGroupBy(groupBy.items()[1], "name", "n", "t"); }