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.petstore.console.dev; 018 019import static java.nio.charset.StandardCharsets.*; 020 021import java.io.*; 022import java.util.*; 023 024import org.apache.juneau.http.*; 025import org.apache.juneau.http.response.*; 026import org.apache.juneau.marshall.collections.*; 027import org.apache.juneau.petstore.console.*; 028import org.apache.juneau.petstore.console.pages.*; 029import org.apache.juneau.petstore.dto.*; 030import org.apache.juneau.rest.server.*; 031import org.apache.juneau.rest.server.view.*; 032import org.apache.juneau.rest.server.view.freemarker.*; 033 034/** 035 * The Custom cards page, which shows how an adopter writes a card type, and the feeds its cards read. 036 * 037 * <p> 038 * The page has a JSON-only card type ({@code kpi}), a Java-validated one ({@code inventory-gauge}, see 039 * {@link InventoryGaugeCardType}) and two charts: the stock bands and the zoomable prices. 040 * 041 * <p> 042 * Both JS card classes live in {@code petstore-cards.js}, served beside this class, which also shows the card API 043 * ({@code JuneauConsole.refreshCard}, {@code JuneauConsole.cardApi}) and the {@code juneau:card-mounted} event. 044 * 045 * <h2 class='section'>Example:</h2> 046 * <p class='bjs'> 047 * class KpiCard extends JuneauConsole.Card { 048 * render() { ... } 049 * } 050 * (window.JuneauConsoleCards = window.JuneauConsoleCards || []).push([<js>'kpi'</js>, KpiCard]); 051 * </p> 052 * <p class='bcode'> 053 * GET /console/dev/cards the page 054 * GET /console/dev/cards/stats/available {label, value} for the kpi card 055 * GET /console/dev/cards/inventory?species= {species, available, pending, sold} for the gauge 056 * GET /console/dev/cards/inventory/all one gauge row per species, for the stock bands chart 057 * GET /console/dev/cards/prices {id, price} per pet, for the prices chart 058 * GET /console/dev/cards/petstore-cards.js the page script 059 * </p> 060 */ 061@Rest(path="/cards", title="Custom cards") 062@SuppressWarnings({ 063 "java:S110", // Inheritance depth comes from the BasicRestServlet hierarchy, not this page. 064 "resource" // The response writer is owned by the servlet container; Eclipse JDT @Owning warning is by design. 065}) 066public class CustomCardsRest extends PetstoreConsolePage { 067 068 private static final long serialVersionUID = 1L; 069 070 /** 071 * The Custom cards page. 072 * 073 * @param req The request; {@code ?builder} renders the builder twin. 074 * @return The page. 075 */ 076 @RestGet(path="/") 077 public View page(RestRequest req) { 078 return builder(req) ? twin(req, DevPageBuilders.cards()) : FreemarkerView.of("cards.ftlh"); 079 } 080 081 /** @return The Card API controls as a chrome-free fragment. */ 082 @RestGet(path="/fragments/toolbar") 083 public View toolbar() { 084 return FreemarkerView.of("fragments/cards-toolbar.ftlh"); 085 } 086 087 /** @return The card-type notes as a chrome-free fragment. */ 088 @RestGet(path="/fragments/how") 089 public View how() { 090 return FreemarkerView.of("fragments/cards-how.ftlh"); 091 } 092 093 /** @return The kpi card's number: how many pets are available. */ 094 @RestGet(path="/stats/available") 095 public JsonMap available() { 096 var n = store().getPets().stream().filter(p -> p.getStatus() == PetStatus.AVAILABLE).count(); 097 return new JsonMap().append("label", "Pets available").append("value", n); 098 } 099 100 /** 101 * Counts one species' pets by status, for the gauge. 102 * 103 * @param species The species name, case-insensitive. 104 * @return {@code {species, available, pending, sold}}. 105 * @throws BadRequest If the species is missing or unknown. 106 */ 107 @RestGet(path="/inventory") 108 public JsonMap inventory(@Query("species") String species) { 109 if (species == null) 110 throw new BadRequest("Missing 'species'"); 111 Species s; 112 try { 113 s = Species.valueOf(species.toUpperCase(Locale.ROOT)); 114 } catch (IllegalArgumentException e) { 115 throw new BadRequest(e, "Unknown species '%s'", species); 116 } 117 var counts = new EnumMap<PetStatus,Long>(PetStatus.class); 118 for (var st : PetStatus.values()) 119 counts.put(st, 0L); 120 store().getPets().stream().filter(p -> p.getSpecies() == s).forEach(p -> counts.merge(p.getStatus(), 1L, Long::sum)); 121 return new JsonMap().append("species", s.name()) 122 .append("available", counts.get(PetStatus.AVAILABLE)) 123 .append("pending", counts.get(PetStatus.PENDING)) 124 .append("sold", counts.get(PetStatus.SOLD)); 125 } 126 127 /** @return One {@link #inventory(String)} row per species, in enum order, for the stock bands chart. */ 128 @RestGet(path="/inventory/all") 129 public JsonList inventoryAll() { 130 var rows = new JsonList(); 131 Arrays.stream(Species.values()).forEach(s -> rows.add(inventory(s.name()))); 132 return rows; 133 } 134 135 /** @return One row {@code {id, price}} per pet, by id, for the zoomable prices chart. */ 136 @RestGet(path="/prices") 137 public JsonList prices() { 138 var rows = new JsonList(); 139 store().getPets().stream().sorted(Comparator.comparingLong(Pet::getId)) 140 .forEach(p -> rows.add(new JsonMap().append("id", p.getId()).append("price", p.getPrice()))); 141 return rows; 142 } 143 144 /** 145 * Serves the page-local script. 146 * 147 * @param res The response. 148 * @throws IOException If the bundled script can't be read. 149 */ 150 @RestGet(path="/petstore-cards.js") 151 public void script(RestResponse res) throws IOException { 152 try (var in = CustomCardsRest.class.getResourceAsStream("petstore-cards.js")) { 153 if (in == null) 154 throw new IllegalStateException("Missing classpath resource 'petstore-cards.js' beside " + CustomCardsRest.class.getName()); 155 res.setContentType("text/javascript;charset=utf-8"); 156 res.getWriter().write(new String(in.readAllBytes(), UTF_8)); 157 } 158 } 159}