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.marshall.html;
018
019import org.apache.juneau.commons.svl.*;
020
021/**
022 * HTML widget variable resolver.
023 *
024 * <p>
025 * The format for this var is <js>"$W{widgetName}"</js>.
026 *
027 * <p>
028 * Widgets are simple class that produce some sort of string based on a passed-in HTTP request.
029 *
030 * <p>
031 * They're registered via the following mechanisms:
032 * <ul>
033 *    <li>{@link HtmlDocConfig#widgets() @HtmlDocConfig(widgets)}
034 * </ul>
035 *
036 * <h5 class='section'>See Also:</h5><ul>
037 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/HtmlWidgets">Widgets</a>
038 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/HtmlSupport">HTML</a>
039 * </ul>
040 */
041public class HtmlWidgetVar extends SimpleVar {
042
043   /**
044    * The name of this variable.
045    */
046   public static final String NAME = "W";
047
048   /**
049    * Constructor.
050    */
051   public HtmlWidgetVar() {
052      super(NAME);
053   }
054
055   @Override
056   public boolean canResolve(VarResolverSession session) {
057      return session.getBean(HtmlWidgetMap.class).isPresent();
058   }
059
060   @Override /* Overridden from Parameter */
061   public String resolve(VarResolverSession session, String key) throws Exception {
062      HtmlWidgetMap m = session.getBean(HtmlWidgetMap.class).orElseThrow(RuntimeException::new);
063
064      HtmlWidget w = m.get(key);
065      if (w == null)
066         return "unknown-widget-" + key;
067
068      try {
069         return w.getHtml(session);
070      } catch (@SuppressWarnings("unused") Exception e) {
071         // Defensive per-widget degradation: an individual widget's render failure must not propagate out of
072         // var resolution, since that would abort the whole enclosing string and blank the surrounding page.
073         // Degrade to an empty fragment so the navlink renders empty and the rest of the page is unaffected.
074         // Only Exception is caught so JVM Errors (OOM, etc.) still propagate.
075         return "";
076      }
077   }
078}