001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.commons.svl;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.io.*;
022
023/**
024 * Abstract superclass of all Simple Var Language variables.
025 *
026 * <p>
027 * Vars are used to convert simple variables of the form <js>"$varName{varKey}"</js> into something else by the
028 * {@link VarResolver} class.
029 *
030 * <p>
031 * Subclasses must implement one of the following two methods:
032 * <ul class='javatree'>
033 *    <li class='jm'>{@link #resolve(VarResolverSession,String)} - For simple vars.
034 *    <li class='jm'>{@link #resolveTo(VarResolverSession,Writer,String)} - For streamed vars.
035 * </ul>
036 *
037 * <p>
038 * Subclasses MUST implement a no-arg constructor so that class names can be passed to the
039 * {@link VarResolver.Builder#vars(Class...)} method.
040 * <br><b>They must also be thread safe!</b>
041 *
042 * <p>
043 * Two direct abstract subclasses are provided to differentiated between simple and streamed vars:
044 * <ul class='javatree'>
045 *    <li class='jac'>{@link SimpleVar}
046 *    <li class='jac'>{@link StreamedVar}
047 * </ul>
048 *
049 * <h5 class='section'>See Also:</h5><ul>
050 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/MarshallSimpleVariableLanguage">Marshall Simple Variable Language</a>
051 * </ul>
052 */
053@SuppressWarnings({
054   "java:S112", // throws Exception intentional - callback/lifecycle method
055   "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants
056   "java:S1452" // Wildcard may appear in subclass method signatures
057})
058public abstract class Var {
059
060   private final String name;
061   final boolean streamed;
062
063   /**
064    * Constructor.
065    *
066    * @param name The name of this variable.  Must not be <jk>null</jk>.
067    * @param streamed
068    *    Whether this variable is 'streamed', meaning the {@link #resolveTo(VarResolverSession, Writer, String)} method
069    *    is implemented.
070    *    If <jk>false</jk>, then the {@link #resolve(VarResolverSession, String)} method is implemented.
071    */
072   protected Var(String name, boolean streamed) {
073      reqnn("name", name);
074      this.name = name;
075      this.streamed = streamed;
076
077      for (var i = 0; i < name.length(); i++) {
078         // Need to make sure only ASCII characters are used.
079         var c = name.charAt(i);
080         if (c < 'A' || c > 'z' || (c > 'Z' && c < 'a'))
081            throw iaex("Invalid var name.  Must consist of only uppercase and lowercase ASCII letters.");
082      }
083   }
084
085   /**
086    * The interface that needs to be implemented for subclasses of {@link SimpleVar}.
087    *
088    * @param session The session object used for a single instance of a var resolution.
089    * @param arg The inside argument of the variable.
090    * @return The resolved value.
091    * @throws Exception Any exception can be thrown.
092    */
093   public abstract String resolve(VarResolverSession session, String arg) throws Exception;
094
095   /**
096    * The interface that needs to be implemented for subclasses of {@link StreamedVar}.
097    *
098    * @param session The session object used for a single instance of a var resolution.
099    * @param w The writer to send the resolved value to.
100    * @param arg The inside argument of the variable.
101    * @throws Exception Any exception can be thrown.
102    */
103   public abstract void resolveTo(VarResolverSession session, Writer w, String arg) throws Exception;
104
105   /**
106    * Returns whether nested variables are supported by this variable.
107    *
108    * <p>
109    * For example, in <js>"$X{$Y{xxx}}"</js>, $Y is a nested variable that will be resolved if this method returns
110    * <jk>true</jk>.
111    *
112    * <p>
113    * The default implementation of this method always returns <jk>true</jk>.
114    * Subclasses can override this method to override the default behavior.
115    *
116    * @return <jk>true</jk> if nested variables are supported by this variable.
117    */
118   protected boolean allowNested() {
119      return true;
120   }
121
122   /**
123    * Returns whether variables in the resolved contents of this variable should also be resolved.
124    *
125    * <p>
126    * For example, if <js>"$X{xxx}"</js> resolves to <js>"$Y{xxx}"</js>, then the $Y variable will be recursively
127    * resolved if this method returns <jk>true</jk>.
128    *
129    * <p>
130    * The default implementation of this method always returns <jk>true</jk>.
131    * <br>Subclasses can override this method to override the default behavior.
132    *
133    * <div class='warn'>
134    * As a general rule, variables that resolve user-entered data should not be recursively resolved as this may
135    * cause a security hole.
136    * </div>
137    *
138    * @return <jk>true</jk> if resolved variables should be recursively resolved.
139    */
140   protected boolean allowRecurse() {
141      return true;
142   }
143
144   /**
145    * Returns <jk>true</jk> if this variable can be resolved in the specified session.
146    *
147    * <p>
148    * For example, some variable cannot resolve unless specific context or session objects are available.
149    *
150    * @param session The current session.
151    * @return <jk>true</jk> if this variable can be resolved in the specified session.
152    */
153   protected boolean canResolve(VarResolverSession session) {
154      return true;
155   }
156
157   /**
158    * Returns {@code true} if this variable's resolved value is stable for the lifetime of the
159    * resolver — same body produces the same output regardless of when (or in what session) it
160    * is resolved.
161    *
162    * <p>
163    * Stable vars opt in to <b>compile-time folding</b> by {@link VarTemplateCompiler}: rather
164    * than producing a {@link VarRefSegment} that dispatches at resolve time, the compiler
165    * resolves the var <i>once</i> at compile time and stores a {@link LiteralSegment} carrying
166    * the resolved value. This eliminates the per-resolve dispatch cost for hot paths like
167    * {@code @Value("${HOSTNAME:localhost}")} where the underlying var (env / system property
168    * / etc.) is treated as a build-time constant by the application.
169    *
170    * <p>
171    * Default: {@code false}. Vars that read mutable session-scoped state (request beans, args,
172    * config files) <b>must</b> leave this {@code false} — folding would cache an arbitrary
173    * resolution as a literal and break per-session correctness.
174    *
175    * <p>
176    * Common opt-ins:
177    * <ul>
178    *    <li>{@link org.apache.juneau.commons.svl.vars.SystemPropertiesVar SystemPropertiesVar} — system
179    *       properties are mutable in principle (via {@link System#setProperty}) but treated as
180    *       stable in normal application code; if a deployment relies on post-resolver mutations,
181    *       opt-out by sub-classing.
182    *    <li>{@link org.apache.juneau.commons.svl.vars.EnvVariablesVar EnvVariablesVar} — process
183    *       environment is immutable.
184    *    <li>{@link org.apache.juneau.commons.svl.vars.DotenvVar DotenvVar} /
185    *       {@link org.apache.juneau.commons.svl.vars.EnvFileVar EnvFileVar} — .env files are read
186    *       once at startup.
187    * </ul>
188    *
189    * <h5 class='section'>Folding contract:</h5>
190    * <p>
191    * When a {@link Var} returns {@code true} here, the compiler invokes
192    * {@link #doResolve(VarResolverSession, String)} on a no-bean session at compile time.
193    * Implementations must not throw on absent session beans during stable folding; if the
194    * stable resolution would itself depend on session state (i.e. it isn't really stable),
195    * either return {@code false} from this method or throw a {@link VarResolverException}
196    * from {@link #doResolve(VarResolverSession, String)} which the compiler treats as
197    * "cannot fold; emit a normal {@link VarRefSegment}".
198    *
199    * @return {@code true} if this variable's resolution is invariant across sessions.
200    */
201   protected boolean isStable() {
202      return false;
203   }
204
205   /**
206    * The method called from {@link VarResolver}.
207    *
208    * <p>
209    * Can be overridden to intercept the request and do special handling.
210    * <br>Default implementation simply calls resolve(String).
211    *
212    * @param session The session object used for a single instance of a string resolution.
213    * @param arg The inside argument of the variable.
214    * @return The resolved value.
215    * @throws Exception Any exception can be thrown.
216    */
217   protected String doResolve(VarResolverSession session, String arg) throws Exception {
218      return resolve(session, arg);
219   }
220
221   /**
222    * Return the name of this variable.
223    *
224    * <p>
225    * For example, the system property variable returns <js>"S"</js> since the format of the variable is
226    * <js>"$S{system.property}"</js>.
227    *
228    * @return The name of this variable.
229    */
230   protected String getName() { return name; }
231}