public static PortRange fromIterable(Iterable<?> c) { List<PortRange> l = new ArrayList<PortRange>(); for (Object o: c) { if (o instanceof Integer) l.add(fromInteger((Integer)o)); else if (o instanceof String) for (String string : JavaStringEscapes.unwrapJsonishListIfPossible((String)o)) l.add(fromString(string)); else if (o instanceof Iterable) l.add(fromIterable((Iterable<?>)o)); else if (o instanceof int[]) l.add(fromIterable(Ints.asList((int[])o))); else if (o instanceof String[]) for (String string : (String[])o) l.add(fromString(string)); else if (o instanceof Object[]) for (Object object : (Object[])o) if (object instanceof Integer) l.add(fromInteger((Integer)object)); else if (object instanceof String) l.add(fromString((String)object)); else throw new IllegalArgumentException("'" + object + "' must be of type Integer or String"); else l.add(TypeCoercions.coerce(o, PortRange.class)); } return new AggregatePortRange(l); }
return (T) wrappedType.getMethod("valueOf", String.class).invoke(null, value); } catch (Exception e) { ClassCoercionException tothrow = new ClassCoercionException("Cannot coerce "+JavaStringEscapes.wrapJavaString(value)+" to "+targetType.getCanonicalName()+" ("+value+"): adapting failed"); tothrow.initCause(e); throw tothrow;
/** as {@link #unwrapJsonishListIfPossible(String)} but throwing errors * if something which looks like a string or set of brackets is not well-formed * (this does the work for that method) * @throws IllegalArgumentException if looks to have quoted list or surrounding brackets but they are not syntactically valid */ public static List<String> unwrapOptionallyQuotedJavaStringList(String input) { if (input==null) return null; MutableList<String> result = MutableList.of(); String i1 = input.trim(); boolean inBrackets = (i1.startsWith("[") && i1.endsWith("]")); if (inBrackets) i1 = i1.substring(1, i1.length()-1).trim(); QuotedStringTokenizer qst = new QuotedStringTokenizer(i1, "\"", true, ",", false); while (qst.hasMoreTokens()) { String t = qst.nextToken().trim(); if (isWrappedInDoubleQuotes(t)) result.add(unwrapJavaString(t)); else { if (inBrackets && (t.indexOf('[')>=0 || t.indexOf(']')>=0)) throw new IllegalArgumentException("Literal square brackets must be quoted, in element '"+t+"'"); result.add(t.trim()); } } return result; } }
List<String> catalogsAdd = Strings.isBlank(catalogAdd) ? ImmutableList.<String>of() : JavaStringEscapes.unwrapJsonishListIfPossible(catalogAdd); CatalogInitialization catInit = new CatalogInitialization(catalogInitial, catalogReset, catalogsAdd, catalogForce); catInit.addPopulationCallback(new Function<CatalogInitialization,Void>() {
for (String targetSpec : JavaStringEscapes.unwrapJsonishListIfPossible((String)targetSpecs)) { targets.add(managementContext.getLocationRegistry().getLocationSpec(targetSpec, ImmutableMap.of()).get());
.ignoreWebErrors(startupContinueOnWebErrors) .ignoreAppErrors(!startupFailOnManagedAppsErrors) .locations(Strings.isBlank(locations) ? ImmutableList.<String>of() : JavaStringEscapes.unwrapJsonishListIfPossible(locations));
return JavaStringEscapes.wrapJavaString((String)focus);
@Test public void testJavaLists() { Assert.assertEquals(MutableList.of("hello", "world"), JavaStringEscapes.unwrapQuotedJavaStringList("\"hello\", \"world\"", ",")); try { JavaStringEscapes.unwrapQuotedJavaStringList("\"hello\", world", ","); Assert.fail("Should have thrown"); } catch (Exception e) { /* expected */ } JavaStringEscapes.unwrapJsonishListIfPossible("\"hello\", \"world\"")); Assert.assertEquals(MutableList.of("hello"), JavaStringEscapes.unwrapJsonishListIfPossible("hello")); Assert.assertEquals(MutableList.of("hello", "world"), JavaStringEscapes.unwrapJsonishListIfPossible("hello, world")); Assert.assertEquals(MutableList.of("hello", "world"), JavaStringEscapes.unwrapJsonishListIfPossible("\"hello\", world")); Assert.assertEquals(MutableList.of("hello", "world"), JavaStringEscapes.unwrapJsonishListIfPossible("[ \"hello\", world ]")); JavaStringEscapes.unwrapJsonishListIfPossible("hello\", \"world\"")); Assert.assertEquals(MutableList.of(), JavaStringEscapes.unwrapJsonishListIfPossible(" ")); Assert.assertEquals(MutableList.of(""), JavaStringEscapes.unwrapJsonishListIfPossible("\"\"")); Assert.assertEquals(MutableList.of("x"), JavaStringEscapes.unwrapJsonishListIfPossible(",,x,")); Assert.assertEquals(MutableList.of("","x",""), JavaStringEscapes.unwrapJsonishListIfPossible("\"\",,x,\"\""));
/** returns an object which jersey will handle nicely, converting to json, * sometimes wrapping in quotes if needed (for outermost json return types); * if json is not preferred, this simply applies a toString-style rendering */ public static Object getValueForDisplay(ObjectMapper mapper, Object value, boolean preferJson, boolean isJerseyReturnValue) { if (preferJson) { if (value==null) return null; Object result = value; // no serialization checks required, with new smart-mapper which does toString // (note there is more sophisticated logic in git history however) result = value; if (isJerseyReturnValue) { if (result instanceof String) { // Jersey does not do json encoding if the return type is a string, // expecting the returner to do the json encoding himself // cf discussion at https://github.com/dropwizard/dropwizard/issues/231 result = JavaStringEscapes.wrapJavaString((String)result); } } return result; } else { if (value==null) return ""; return value.toString(); } }
@Test public void testJavaUnwrap() { Assert.assertEquals(JavaStringEscapes.unwrapJavaString("\"Hello World\""), "Hello World"); Assert.assertEquals(JavaStringEscapes.unwrapJavaString("\"Hello \\\"Bob\\\"\""), "Hello \"Bob\""); try { JavaStringEscapes.unwrapJavaString("Hello World"); Assert.fail("Should have thrown"); } catch (Exception e) { /* expected */ } try { // missing final quote JavaStringEscapes.unwrapJavaString("\"Hello \\\"Bob\\\""); Assert.fail("Should have thrown"); } catch (Exception e) { /* expected */ } Assert.assertEquals(JavaStringEscapes.unwrapJavaStringIfWrapped("\"Hello World\""), "Hello World"); Assert.assertEquals(JavaStringEscapes.unwrapJavaStringIfWrapped("\"Hello \\\"Bob\\\"\""), "Hello \"Bob\""); Assert.assertEquals(JavaStringEscapes.unwrapJavaStringIfWrapped("Hello World"), "Hello World"); try { // missing final quote JavaStringEscapes.unwrapJavaStringIfWrapped("\"Hello \\\"Bob\\\""); Assert.fail("Should have thrown"); } catch (Exception e) { /* expected */ } }
/** * Unwraps a sequence of quoted java strings, that are each separated by the given separator. * @param trimmedArg * @return */ public static List<String> unwrapQuotedJavaStringList(String s, String separator) { List<String> result = new ArrayList<String>(); String remaining = s.trim(); while (remaining.length() > 0) { int endIndex = findNextClosingQuoteOf(remaining); result.add(unwrapJavaString(remaining.substring(0, endIndex+1))); remaining = remaining.substring(endIndex+1).trim(); if (remaining.startsWith(separator)) { remaining = remaining.substring(separator.length()).trim(); } else if (remaining.length() > 0) { throw new IllegalArgumentException("String '"+s+"' has invalid separators, should be '"+separator+"'"); } } return result; } private static int findNextClosingQuoteOf(String s) {
@SuppressWarnings("unchecked") @Test public void testRegistryCommaResolution() throws NoMachinesAvailableException { List<Location> l; l = getLocationResolver().getListOfLocationsManaged(JavaStringEscapes.unwrapJsonishListIfPossible("localhost,localhost,localhost")); assertEquals(l.size(), 3, "l="+l); assertTrue(l.get(0) instanceof LocalhostMachineProvisioningLocation, "l="+l); assertTrue(l.get(1) instanceof LocalhostMachineProvisioningLocation, "l="+l); assertTrue(l.get(2) instanceof LocalhostMachineProvisioningLocation, "l="+l); // And check works if comma in brackets l = getLocationResolver().getListOfLocationsManaged(JavaStringEscapes.unwrapJsonishListIfPossible( "[ \"byon:(hosts=\\\"192.168.0.1\\\",user=bob)\", \"byon:(hosts=\\\"192.168.0.2\\\",user=bob2)\" ]")); assertEquals(l.size(), 2, "l="+l); assertTrue(l.get(0) instanceof FixedListMachineProvisioningLocation, "l="+l); assertTrue(l.get(1) instanceof FixedListMachineProvisioningLocation, "l="+l); assertEquals(((FixedListMachineProvisioningLocation<SshMachineLocation>)l.get(0)).obtain().getUser(), "bob"); assertEquals(((FixedListMachineProvisioningLocation<SshMachineLocation>)l.get(1)).obtain().getUser(), "bob2"); }
@Test public void testWithEntityLocationsAndStartInLocation() throws Exception { Entity app = createAndStartApplication(loadYaml("test-entity-basic-template.yaml", " location: localhost:(name=localhost name)"), // must pass as JSON list because otherwise the comma confuses the list parser MutableMap.of("locations", "[ "+JavaStringEscapes.wrapJavaString( "byon:(hosts=\"1.1.1.1\", name=\"byon name\")")+" ]") ); waitForApplicationTasks(app); Assert.assertEquals(app.getLocations().size(), 1); Assert.assertEquals(app.getChildren().size(), 1); Entity entity = app.getChildren().iterator().next(); Assert.assertEquals(entity.getLocations().size(), 2); Iterator<Location> entityLocationIterator = entity.getLocations().iterator(); Assert.assertEquals(entityLocationIterator.next().getDisplayName(), "localhost name"); Assert.assertEquals(entityLocationIterator.next().getDisplayName(), "byon name"); Location appLocation = app.getLocations().iterator().next(); Assert.assertEquals(appLocation.getDisplayName(), "byon name"); }
public void testParseString() { assertEquals(new DslParser("\"hello world\"").parse(), new QuotedString(JavaStringEscapes.wrapJavaString("hello world"))); }
@Test public void testJavaEscape() { Assert.assertEquals(JavaStringEscapes.wrapJavaString("Hello \"World\""), "\"Hello \\\"World\\\"\""); }
@Override public Set<String> apply(final String input) { return MutableSet.copyOf(JavaStringEscapes.unwrapJsonishListIfPossible(input)).asUnmodifiable(); } });
/** converts normal string to java escaped for double-quotes and wrapped in those double quotes */ public static String wrapJavaString(String value) { StringBuilder out = new StringBuilder(); try { wrapJavaString(value, out); } catch (IOException e) { //shouldn't happen for string builder throw Exceptions.propagate(e); } return out.toString(); } public static List<String> wrapJavaStrings(Iterable<String> values) {
@Override public List<Location> getListOfLocationsManaged(Object l) { if (l==null) l = Collections.emptyList(); if (l instanceof String) l = JavaStringEscapes.unwrapJsonishListIfPossible((String)l); if (l instanceof Iterable) return getFromIterableListOfLocationsManaged((Iterable<?>)l); throw new IllegalArgumentException("Location list must be supplied as a collection or a string, not "+ JavaClassNames.simpleClassName(l)+"/"+l); }
/** as {@link #unwrapJavaString(String)} if the given string is wrapped in double quotes; * otherwise just returns the given string */ public static String unwrapJavaStringIfWrapped(String s) { if (!StringEscapes.isWrappedInDoubleQuotes(s)) return s; return unwrapJavaString(s); }
/** converts normal string to java escaped for double-quotes and wrapped in those double quotes */ public static void wrapJavaString(String value, Appendable out) throws IOException { if (value==null) { out.append("null"); } else { out.append('"'); escapeJavaString(value, out); out.append('"'); } }