/** if s is wrapped in single or double quotes containing no unescaped quotes of that type */ public static boolean isWrappedInMatchingQuotes(String s) { return isWrappedInDoubleQuotes(s) || isWrappedInSingleQuotes(s); }
@Test public void testEscapeSql() { Assert.assertEquals(StringEscapes.escapeSql("I've never been to Brooklyn"), "I''ve never been to Brooklyn"); }
/** 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); }
private void initializeNewDatabase() { String createUserCommand = String.format( "\"CREATE USER %s WITH PASSWORD '%s'; \"", StringEscapes.escapeSql(getUsername()), StringEscapes.escapeSql(getUserPassword()) ); String createDatabaseCommand = String.format( "\"CREATE DATABASE %s OWNER %s\"", StringEscapes.escapeSql(getDatabaseName()), StringEscapes.escapeSql(getUsername())); String createRolesAdditionalCommand = ""; if (entity.getConfig(PostgreSqlNode.ROLES) != null && !entity.getConfig(PostgreSqlNode.ROLES).isEmpty()) { String createRolesQuery = buildCreateRolesQuery(); createRolesAdditionalCommand = sudoAsUser("postgres", getInstallDir() + "/bin/psql -p " + entity.getAttribute(PostgreSqlNode.POSTGRESQL_PORT) + " --command="+ createRolesQuery); } newScript("initializing user and database") .body.append( "cd " + getInstallDir(), callPgctl("start", true), sudoAsUser("postgres", getInstallDir() + "/bin/psql -p " + entity.getAttribute(PostgreSqlNode.POSTGRESQL_PORT) + " --command="+ createUserCommand), sudoAsUser("postgres", getInstallDir() + "/bin/psql -p " + entity.getAttribute(PostgreSqlNode.POSTGRESQL_PORT) + " --command="+ createDatabaseCommand), createRolesAdditionalCommand, callPgctl("stop", true)) .failOnNonZeroResultCode().execute(); }
/** 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; } }