Skip to content

Method: getValue()

1: /*
2: * JOPA
3: * Copyright (C) 2024 Czech Technical University in Prague
4: *
5: * This library is free software; you can redistribute it and/or
6: * modify it under the terms of the GNU Lesser General Public
7: * License as published by the Free Software Foundation; either
8: * version 3.0 of the License, or (at your option) any later version.
9: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library.
17: */
18: package cz.cvut.kbss.jopa.query.parameter;
19:
20: import cz.cvut.kbss.ontodriver.model.LangString;
21:
22: import java.util.Objects;
23:
24: class StringParameterValue extends AbstractParameterValue {
25:
26: private final String value;
27: private final String language;
28:
29: StringParameterValue(String value) {
30: this.value = Objects.requireNonNull(value);
31: this.language = null;
32: }
33:
34: StringParameterValue(String value, String language) {
35: this.value = Objects.requireNonNull(value);
36: this.language = language;
37: }
38:
39: StringParameterValue(LangString langString) {
40: Objects.requireNonNull(langString);
41: this.value = langString.getValue();
42: this.language = langString.getLanguage().orElse(null);
43: }
44:
45: @Override
46: public String getValue() {
47: return value;
48: }
49:
50: public String getLanguage() {
51: return language;
52: }
53:
54: @Override
55: public String getQueryString() {
56: return "\"" + getEscapedValue() + "\"" + (language != null ? ("@" + language) : "");
57: }
58:
59: /**
60: * Escapes string characters according to SPARQL spec.
61: *
62: * @return Escaped value
63: * @see <a href="https://www.w3.org/TR/sparql11-query/#grammarEscapes" target="_top">
64: * https://www.w3.org/TR/sparql11-query/#grammarEscapes</a>
65: */
66: private String getEscapedValue() {
67: final StringBuilder sb = new StringBuilder(value.length());
68: char c;
69: for (int i = 0; i < value.length(); i++) {
70: c = value.charAt(i);
71: switch (c) {
72: case '\t':
73: sb.append("\\t");
74: break;
75: case '\n':
76: sb.append("\\n");
77: break;
78: case '\r':
79: sb.append("\\r");
80: break;
81: case '\b':
82: sb.append("\\b");
83: break;
84: case '\f':
85: sb.append("\\f");
86: break;
87: case '\'':
88: sb.append("\\'");
89: break;
90: case '\"':
91: sb.append("\\\"");
92: break;
93: case '\\':
94: sb.append("\\\\");
95: break;
96: default:
97: sb.append(c);
98: }
99: }
100: return sb.toString();
101: }
102: }