]> git.basschouten.com Git - openhab-addons.git/blob
c7502f28ac9d486eb1d05ffb09113fa011e0f7c2
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.dbquery.internal.dbimpl;
14
15 import java.util.regex.Pattern;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.binding.dbquery.internal.domain.QueryParameters;
19
20 /**
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
23  * sources.
24  *
25  * @author Joan Pujol - Initial contribution
26  */
27 @NonNullByDefault
28 public class StringSubstitutionParamsParser {
29     private final Pattern paramPattern = Pattern.compile("\\$\\{([\\w_]*?)}");
30     private final String query;
31
32     public StringSubstitutionParamsParser(String query) {
33         this.query = query;
34     }
35
36     public String getQueryWithParametersReplaced(QueryParameters queryParameters) {
37         var matcher = paramPattern.matcher(query);
38         int idx = 0;
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));
45             idx = matcher.end();
46         }
47         if (idx < query.length()) {
48             substitutedQuery.append(query.substring(idx));
49         }
50
51         return substitutedQuery.toString();
52     }
53
54     private String parameterValue(String parameterName, QueryParameters queryParameters) {
55         var parameter = queryParameters.getParameter(parameterName);
56         if (parameter != null) {
57             return parameter.toString();
58         } else {
59             return "";
60         }
61     }
62 }