1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.any23.extractor.xpath;
19
20 import org.eclipse.rdf4j.model.Value;
21
22 import java.util.Locale;
23 import java.util.Map;
24
25 /**
26 * Represents a generic template term.
27 *
28 * @author Michele Mostarda (mostarda@fbk.eu)
29 */
30 public abstract class Term<T extends Value> {
31
32 /**
33 * Internal value.
34 */
35 private final String internalValue;
36
37 /**
38 * if true the #internalValue is a variable name, otherwise is a constant.
39 */
40 private final boolean isVar;
41
42 /**
43 * Constructor.
44 *
45 * @param internalValue
46 * internal term value.
47 * @param isVar
48 * if true the <code>internalValue</code> is a variable name, otherwise is a constant.
49 */
50 protected Term(String internalValue, boolean isVar) {
51 this.internalValue = internalValue;
52 this.isVar = isVar;
53 }
54
55 /**
56 * @return the internal value.
57 */
58 public String getInternalValue() {
59 return internalValue;
60 }
61
62 /**
63 * @return the isVar flag value.
64 */
65 public boolean isVar() {
66 return isVar;
67 }
68
69 /**
70 * Returns the value represented by this {@link Term} given the <code>varMapping</code>, the #isVar and
71 * #internalValue parameters.
72 *
73 * @param varMapping
74 * a map representing values of variables.
75 *
76 * @return the value for this term.
77 */
78 public T getValue(Map<String, String> varMapping) {
79 final String value;
80 if (isVar) {
81 value = varMapping.get(internalValue);
82 if (value == null) {
83 throw new IllegalStateException(
84 String.format(Locale.ROOT, "Cannot find a valid value for variable '%s'", internalValue));
85 }
86 } else {
87 value = internalValue;
88 }
89 return getValueInternal(value);
90 }
91
92 protected abstract T getValueInternal(String value);
93
94 @Override
95 public String toString() {
96 return isVar ? ("?" + internalValue) : internalValue;
97 }
98 }