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.bean.swagger.ui;
018
019import static java.util.Collections.*;
020import static org.apache.juneau.bean.html5.HtmlBuilder.*;
021import static org.apache.juneau.bean.html5.HtmlBuilder.a;
022import static org.apache.juneau.common.utils.Utils.*;
023
024import java.util.*;
025
026import org.apache.juneau.*;
027import org.apache.juneau.bean.html5.*;
028import org.apache.juneau.bean.swagger.*;
029import org.apache.juneau.collections.*;
030import org.apache.juneau.common.utils.*;
031import org.apache.juneau.cp.*;
032import org.apache.juneau.swap.*;
033
034/**
035 * Generates a Swagger-UI interface from a Swagger document.
036 *
037 * <h5 class='section'>See Also:</h5><ul>
038 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauBeanSwagger2">juneau-bean-swagger-v2</a>
039 * </ul>
040 */
041public class SwaggerUI extends ObjectSwap<Swagger,Div> {
042
043   static final FileFinder RESOURCES = FileFinder
044      .create(BeanStore.INSTANCE)
045      .cp(SwaggerUI.class, null, true)
046      .dir(",")
047      .caching(Boolean.getBoolean("RestContext.disableClasspathResourceCaching.b") ? -1 : 1_000_000)
048      .build();
049
050   private static final Set<String> STANDARD_METHODS = set("get", "put", "post", "delete", "options");
051
052   /**
053    * This UI applies to HTML requests only.
054    */
055   @Override
056   public MediaType[] forMediaTypes() {
057      return new MediaType[] {MediaType.HTML};
058   }
059
060   private static class Session {
061      final int resolveRefsMaxDepth;
062      final Swagger swagger;
063
064      Session(Swagger swagger) {
065         this.swagger = swagger.copy();
066         this.resolveRefsMaxDepth = 1;
067      }
068   }
069
070   @Override
071   public Div swap(BeanSession beanSession, Swagger swagger) throws Exception {
072
073      var s = new Session(swagger);
074
075      var css = RESOURCES.getString("files/htdocs/styles/SwaggerUI.css", null).orElse(null);
076      if (css == null)
077         css = RESOURCES.getString("SwaggerUI.css", null).orElse(null);
078
079      var outer = div(
080         style(css),
081         script("text/javascript", RESOURCES.getString("SwaggerUI.js", null).orElse(null)),
082         header(s)
083      )._class("swagger-ui");
084
085      // Operations without tags are rendered first.
086      outer.child(div()._class("tag-block tag-block-open").children(tagBlockContents(s, null)));
087
088      if (s.swagger.getTags() != null) {
089         s.swagger.getTags().forEach(x -> {
090            var tagBlock = div()._class("tag-block tag-block-open").children(
091               tagBlockSummary(x),
092               tagBlockContents(s, x)
093            );
094            outer.child(tagBlock);
095         });
096      }
097
098      if (s.swagger.getDefinitions() != null) {
099         var modelBlock = div()._class("tag-block").children(
100            modelsBlockSummary(),
101            modelsBlockContents(s)
102         );
103         outer.child(modelBlock);
104      }
105
106      return outer;
107   }
108
109   // Creates the informational summary before the ops.
110   private Table header(Session s) {
111      var table = table()._class("header");
112
113      var info = s.swagger.getInfo();
114      if (info != null) {
115
116         if (info.getDescription() != null)
117            table.child(tr(th("Description:"),td(toBRL(info.getDescription()))));
118
119         if (info.getVersion() != null)
120            table.child(tr(th("Version:"),td(info.getVersion())));
121
122         var c = info.getContact();
123         if (c != null) {
124            var t2 = table();
125
126            if (c.getName() != null)
127               t2.child(tr(th("Name:"),td(c.getName())));
128            if (c.getUrl() != null)
129               t2.child(tr(th("URL:"),td(a(c.getUrl(), c.getUrl()))));
130            if (c.getEmail() != null)
131               t2.child(tr(th("Email:"),td(a("mailto:"+ c.getEmail(), c.getEmail()))));
132
133            table.child(tr(th("Contact:"),td(t2)));
134         }
135
136         var l = info.getLicense();
137         if (l != null) {
138            var content = l.getName() != null ? l.getName() : l.getUrl();
139            var child = l.getUrl() != null ? a(l.getUrl(), content) : l.getName();
140            table.child(tr(th("License:"),td(child)));
141         }
142
143         ExternalDocumentation ed = s.swagger.getExternalDocs();
144         if (ed != null) {
145            var content = ed.getDescription() != null ? ed.getDescription() : ed.getUrl();
146            var child = ed.getUrl() != null ? a(ed.getUrl(), content) : ed.getDescription();
147            table.child(tr(th("Docs:"),td(child)));
148         }
149
150         if (info.getTermsOfService() != null) {
151            var tos = info.getTermsOfService();
152            var child = StringUtils.isUri(tos) ? a(tos, tos) : tos;
153            table.child(tr(th("Terms of Service:"),td(child)));
154         }
155      }
156
157      return table;
158   }
159
160   // Creates the "pet  Everything about your Pets  ext-link" header.
161   private HtmlElement tagBlockSummary(Tag t) {
162      var ed = t.getExternalDocs();
163
164      var children = new ArrayList<HtmlElement>();
165      children.add(span(t.getName())._class("name"));
166      children.add(span(toBRL(t.getDescription()))._class("description"));
167
168      if (ed != null) {
169         var content = ed.getDescription() != null ? ed.getDescription() : ed.getUrl();
170         children.add(span(a(ed.getUrl(), content))._class("extdocs"));
171      }
172
173      return div()._class("tag-block-summary").children(children).onclick("toggleTagBlock(this)");
174   }
175
176   // Creates the contents under the "pet  Everything about your Pets  ext-link" header.
177   private Div tagBlockContents(Session s, Tag t) {
178      var tagBlockContents = div()._class("tag-block-contents");
179
180      if (s.swagger.getPaths() != null) {
181         s.swagger.getPaths().forEach((path,v) ->
182            v.forEach((opName,op) -> {
183               if ((t == null && op.getTags() == null) || (t != null && op.getTags() != null && op.getTags() != null && op.getTags().contains(t.getName())))
184                  tagBlockContents.child(opBlock(s, path, opName, op));
185            })
186         );
187      }
188
189      return tagBlockContents;
190   }
191
192   private Div opBlock(Session s, String path, String opName, Operation op) {
193
194      var opClass = op.isDeprecated() ? "deprecated" : opName.toLowerCase();
195      if (! op.isDeprecated() && ! STANDARD_METHODS.contains(opClass))
196         opClass = "other";
197
198      return div()._class("op-block op-block-closed " + opClass).children(
199         opBlockSummary(path, opName, op),
200         div(tableContainer(s, op))._class("op-block-contents")
201      );
202   }
203
204   private HtmlElement opBlockSummary(String path, String opName, Operation op) {
205      return div()._class("op-block-summary").children(
206         span(opName.toUpperCase())._class("method-button"),
207         span(path)._class("path"),
208         op.getSummary() != null ? span(op.getSummary())._class("summary") : null
209      ).onclick("toggleOpBlock(this)");
210   }
211
212   private Div tableContainer(Session s, Operation op) {
213      var tableContainer = div()._class("table-container");
214
215      if (op.getDescription() != null)
216         tableContainer.child(div(toBRL(op.getDescription()))._class("op-block-description"));
217
218      if (op.getParameters() != null) {
219         tableContainer.child(div(h4("Parameters")._class("title"))._class("op-block-section-header"));
220
221         var parameters = table(tr(th("Name")._class("parameter-key"), th("Description")._class("parameter-key")))._class("parameters");
222
223         op.getParameters().forEach(x -> {
224            var piName = "body".equals(x.getIn()) ? "body" : x.getName();
225            var required = x.getRequired() != null && x.getRequired();
226
227            var parameterKey = td(
228               div(piName)._class("name" + (required ? " required" : "")),
229               required ? div("required")._class("requiredlabel") : null,
230               div(x.getType())._class("type"),
231               div('(' + x.getIn() + ')')._class("in")
232            )._class("parameter-key");
233
234            var parameterValue = td(
235               div(toBRL(x.getDescription()))._class("description"),
236               examples(s, x)
237            )._class("parameter-value");
238
239            parameters.child(tr(parameterKey, parameterValue));
240         });
241
242         tableContainer.child(parameters);
243      }
244
245      if (op.getResponses() != null) {
246         tableContainer.child(div(h4("Responses")._class("title"))._class("op-block-section-header"));
247
248         var responses = table(tr(th("Code")._class("response-key"), th("Description")._class("response-key")))._class("responses");
249         tableContainer.child(responses);
250
251         op.getResponses().forEach((k,v) -> {
252            var code = td(k)._class("response-key");
253
254            var codeValue = td(
255               div(toBRL(v.getDescription()))._class("description"),
256               examples(s, v),
257               headers(v)
258            )._class("response-value");
259
260            responses.child(tr(code, codeValue));
261         });
262      }
263
264      return tableContainer;
265   }
266
267   private Div headers(ResponseInfo ri) {
268      if (ri.getHeaders() == null)
269         return null;
270
271      var sectionTable = table(tr(th("Name"),th("Description"),th("Schema")))._class("section-table");
272
273      var headers = div(
274         div("Headers:")._class("section-name"),
275         sectionTable
276      )._class("headers");
277
278      ri.getHeaders().forEach((k,v) ->
279         sectionTable.child(
280            tr(
281               td(k)._class("name"),
282               td(toBRL(v.getDescription()))._class("description"),
283               td(v.asMap().keepAll("type","format","items","collectionFormat","default","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","maxItems","minItems","uniqueItems","enum","multipleOf"))
284            )
285         )
286      );
287
288      return headers;
289   }
290
291   private Div examples(Session s, ParameterInfo pi) {
292      var isBody = "body".equals(pi.getIn());
293
294      var m = new JsonMap();
295
296      try {
297         if (isBody) {
298            var si = pi.getSchema();
299            if (si != null)
300               m.put("model", si.copy().resolveRefs(s.swagger, new ArrayDeque<>(), s.resolveRefsMaxDepth));
301         } else {
302            var m2 = pi
303               .copy()
304               .resolveRefs(s.swagger, new ArrayDeque<>(), s.resolveRefsMaxDepth)
305               .asMap()
306               .keepAll("format","pattern","collectionFormat","maximum","minimum","multipleOf","maxLength","minLength","maxItems","minItems","allowEmptyValue","exclusiveMaximum","exclusiveMinimum","uniqueItems","items","default","enum");
307            m.put("model", m2.isEmpty() ? i("none") : m2);
308         }
309
310      } catch (Exception e) {
311         e.printStackTrace();
312      }
313
314      if (m.isEmpty())
315         return null;
316
317      return examplesDiv(m);
318   }
319
320   private Div examples(Session s, ResponseInfo ri) {
321      var si = ri.getSchema();
322
323      var m = new JsonMap();
324      try {
325         if (si != null) {
326            si = si.copy().resolveRefs(s.swagger, new ArrayDeque<>(), s.resolveRefsMaxDepth);
327            m.put("model", si);
328         }
329
330         var examples = ri.getExamples();
331         if (examples != null)
332            examples.forEach(m::put);
333      } catch (Exception e) {
334         e.printStackTrace();
335      }
336
337      if (m.isEmpty())
338         return null;
339
340      return examplesDiv(m);
341   }
342
343   private Div examplesDiv(JsonMap m) {
344      if (m.isEmpty())
345         return null;
346
347      Select select = null;
348      if (m.size() > 1) {
349         select = select().onchange("selectExample(this)")._class("example-select");
350      }
351
352      var div = div(select)._class("examples");
353
354      if (select != null)
355         select.child(option("model","model"));
356      div.child(div(m.remove("model"))._class("model active").attr("data-name", "model"));
357
358      var select2 = select;
359      m.forEach((k,v) -> {
360         if (select2 != null)
361            select2.child(option(k, k));
362         div.child(div(v.toString().replace("\\n", "\n"))._class("example").attr("data-name", k));
363      });
364
365      return div;
366   }
367
368   // Creates the "Model" header.
369   private HtmlElement modelsBlockSummary() {
370      return div()._class("tag-block-summary").children(span("Models")._class("name")).onclick("toggleTagBlock(this)");
371   }
372
373   // Creates the contents under the "Model" header.
374   private Div modelsBlockContents(Session s) {
375      var modelBlockContents = div()._class("tag-block-contents");
376      s.swagger.getDefinitions().forEach((k,v) -> modelBlockContents.child(modelBlock(k,v)));
377      return modelBlockContents;
378   }
379
380   private Div modelBlock(String modelName, JsonMap model) {
381      return div()._class("op-block op-block-closed model").children(
382         modelBlockSummary(modelName, model),
383         div(model)._class("op-block-contents")
384      );
385   }
386
387   private HtmlElement modelBlockSummary(String modelName, JsonMap model) {
388      return div()._class("op-block-summary").children(
389         span(modelName)._class("method-button"),
390         model.containsKey("description") ? span(toBRL(model.remove("description").toString()))._class("summary") : null
391      ).onclick("toggleOpBlock(this)");
392   }
393
394   /**
395    * Replaces newlines with <br> elements.
396    */
397   private static List<Object> toBRL(String s) {
398      if (s == null)
399         return null;  // NOSONAR - Intentionally returning null.
400      if (s.indexOf(',') == -1)
401         return singletonList(s);
402      var l = Utils.list();
403      var sa = s.split("\n");
404      for (var i = 0; i < sa.length; i++) {
405         if (i > 0)
406            l.add(br());
407         l.add(sa[i]);
408      }
409      return l;
410   }
411}