ConstraintSerialization { public Predicate<?> toPredicateFromJson(Object o) { if (o instanceof Collection) { @SuppressWarnings({ "rawtypes", "unchecked" }) Predicate<?> result2 = and((List)toPredicateListFromJsonList((Collection<?>)o)); return result2; } String key; List<Object> args; if (o instanceof String) { key = (String)o; if (key.indexOf("(")>=0) { StringConstraintParser parser = StringConstraintParser.forConstraint(this, key); if (!parser.parse()) throw new IllegalStateException("cannot match: "+key); return toPredicateFromJson(parser.result); } args = MutableList.of(); } else if (o instanceof Map) { if (((Map<?,?>)o).size()!=1) { throw new IllegalArgumentException("Unsupported constraint; map input should have a single key: "+o); } key = (String) Iterables.getOnlyElement( ((Map<?,?>)o).keySet() ); Object v = Iterables.getOnlyElement( ((Map<?,?>)o).values() ); if (v instanceof Iterable) { args = MutableList.copyOf((Iterable<?>)v); } else { args = Collections.singletonList(v); } } else if (o instanceof Predicate) { return (Predicate<?>)o; } else { throw new IllegalArgumentException("Unsupported constraint; constraint should be string, list, or single-key map: "+o); } Function<List<?>, Predicate<?>> constructor = predicatePreferredNameToConstructor.get(key); if (constructor==null) { String preferredName = predicateToStringToPreferredName.get(key); if (preferredName!=null) { constructor = predicatePreferredNameToConstructor.get(preferredName); if (constructor==null) { throw new IllegalArgumentException("Incomplete constraint: "+key+", maps to "+preferredName+", but no constructor known"); } } else { throw new IllegalArgumentException("Unsupported constraint: "+key); } } return constructor.apply(args); } private  ConstraintSerialization(); List<Object> toJsonList(ConfigKey<?> config); List<Object> toJsonList(Predicate<?> constraint); @SuppressWarnings({ "unchecked", "rawtypes" }) List<Object> toExactJsonList(Predicate<?> constraint); Predicate<?> toPredicateFromJson(Object o); List<Predicate<?>> toPredicateListFromJsonList(Collection<?> o); final static ConstraintSerialization INSTANCE; }
@Test public void testAcceptsMap() { Predicate<String> p = StringPredicates.matchesGlob("???*"); assertSamePredicate(ConstraintSerialization.INSTANCE.toPredicateFromJson(MutableMap.of("matchesGlob", "???*")), p); }
@Test public void testAcceptsForbiddenIfMap() { Predicate<Object> p = ConfigConstraints.forbiddenIf("x"); assertSamePredicate(ConstraintSerialization.INSTANCE.toPredicateFromJson(MutableMap.of("forbiddenIf", "x")), p); }
@Test public void testAcceptsString() { Predicate<String> p = StringPredicates.matchesGlob("???*"); assertSamePredicate(ConstraintSerialization.INSTANCE.toPredicateFromJson("matchesGlob(\"???*\")"), p); }
@Test public void testFlattens() { assertSamePredicate(ConstraintSerialization.INSTANCE.toPredicateFromJson(MutableList.of("required", "required")), ConfigConstraints.required()); }