1 /*
2 * The contents of this file are subject to the terms of the Common Development and
3 * Distribution License (the License). You may not use this file except in compliance with the
4 * License.
5 *
6 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
7 * specific language governing permission and limitations under the License.
8 *
9 * When distributing Covered Software, include this CDDL Header Notice in each file and include
10 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
11 * Header, with the fields enclosed by brackets [] replaced by your own identifying
12 * information: "Portions copyright [year] [name of copyright owner]".
13 *
14 * Copyright 2015-2016 ForgeRock AS.
15 */
16 package org.forgerock.audit.handlers.jdbc;
17
18 import java.util.LinkedList;
19 import java.util.List;
20 import java.util.regex.Matcher;
21 import java.util.regex.Pattern;
22
23 /**
24 * Parses an sql statement containing named parameters into a sql string, and a list of named parameters.
25 */
26 class SqlStatementParser {
27
28 private String sqlStatement;
29 private final List<String> namedParameters = new LinkedList<>();
30
31 /** Pattern matches alphanumeric strings that may contain _ and / surrounded by ${}. */
32 private static final Pattern PATTERN = Pattern.compile("\\$\\{([a-zA-Z0-9/_]+)\\}");
33
34 /**
35 * Creates a SQLStatementParser given a sql string.
36 * @param sql A sql string that contains some named parameters.
37 */
38 public SqlStatementParser(final String sql) {
39 final StringBuffer stringBuffer = new StringBuffer();
40 Matcher m = PATTERN.matcher(sql);
41 while (m.find()) {
42 final String parameter = m.group(1);
43 m.appendReplacement(stringBuffer, "?");
44 namedParameters.add(parameter);
45 }
46 m.appendTail(stringBuffer);
47 sqlStatement = stringBuffer.toString();
48 }
49
50 /**
51 * Gets the sql string with the named parameters replaced with ?.
52 * @return The sql string.
53 */
54 public String getSqlStatement() {
55 return sqlStatement;
56 }
57
58 /**
59 * Gets the named parameters.
60 * @return The list of named parameters.
61 */
62 public List<String> getNamedParameters() {
63 return namedParameters;
64 }
65 }