2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.dbquery.internal.dbimpl;
15 import java.util.regex.Pattern;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.binding.dbquery.internal.domain.QueryParameters;
21 * Provides a parser to substitute query parameters for database like InfluxDB that doesn't support that in it's client.
22 * It's not ideal because it's subject to query injection attacks but it does the work if params are from trusted
25 * @author Joan Pujol - Initial contribution
28 public class StringSubstitutionParamsParser {
29 private final Pattern paramPattern = Pattern.compile("\\$\\{([\\w_]*?)}");
30 private final String query;
32 public StringSubstitutionParamsParser(String query) {
36 public String getQueryWithParametersReplaced(QueryParameters queryParameters) {
37 var matcher = paramPattern.matcher(query);
39 StringBuilder substitutedQuery = new StringBuilder();
40 while (matcher.find()) {
41 String nonParametersPart = query.substring(idx, matcher.start());
42 String parameterName = matcher.group(1);
43 substitutedQuery.append(nonParametersPart);
44 substitutedQuery.append(parameterValue(parameterName, queryParameters));
47 if (idx < query.length()) {
48 substitutedQuery.append(query.substring(idx));
51 return substitutedQuery.toString();
54 private String parameterValue(String parameterName, QueryParameters queryParameters) {
55 var parameter = queryParameters.getParameter(parameterName);
56 if (parameter != null) {
57 return parameter.toString();