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.rest.vars;
018
019import org.apache.juneau.http.response.*;
020import org.apache.juneau.rest.*;
021import org.apache.juneau.svl.*;
022
023/**
024 * Request header variable resolver.
025 *
026 * <p>
027 * The format for this var is <js>"$RH{key1[,key2...]}"</js>.
028 *
029 * <p>
030 * Used to resolve values returned by {@link RestRequest#getHeader(String)}.
031 * <br>When multiple keys are used, returns the first non-null/empty value.
032 *
033 * <h5 class='section'>Example:</h5>
034 * <p class='bjava'>
035 *    String <jv>foo</jv> = <jv>restRequest</jv>.getVarResolver().resolve(<js>"$RH{foo}"</js>);
036 *    String <jv>fooOrBar</jv> = <jv>restRequest</jv>.getVarResolver().resolve(<js>"$RH{foo,bar}"</js>);
037 * </p>
038 *
039 * <h5 class='section'>Notes:</h5><ul>
040 *    <li class='note'>
041 *       This variable resolver requires that a {@link RestRequest} bean be available in the session bean store.
042 *    <li class='note'>
043 *       For security reasons, nested and recursive variables are not resolved.
044 * </ul>
045 *
046 * <h5 class='section'>See Also:</h5><ul>
047 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestServerSvlVariables">SVL Variables</a>
048 * </ul>
049 */
050public class RequestHeaderVar extends MultipartResolvingVar {
051
052   /** The name of this variable. */
053   public static final String NAME = "RH";
054
055   /**
056    * Constructor.
057    */
058   public RequestHeaderVar() {
059      super(NAME);
060   }
061
062   @Override /* Var */
063   protected boolean allowNested() {
064      return false;
065   }
066
067   @Override /* Var */
068   protected boolean allowRecurse() {
069      return false;
070   }
071
072   @Override /* Var */
073   public String resolve(VarResolverSession session, String key) {
074      return session.getBean(RestRequest.class).orElseThrow(InternalServerError::new).getHeaderParam(key).orElse(null);
075   }
076
077   @Override /* Var */
078   public boolean canResolve(VarResolverSession session) {
079      return session.getBean(RestRequest.class).isPresent();
080   }
081}