/** * Render method will write the rendered output utilizing the * properties on the views class and the template specified by the * views to the provided outputstream * @param view * @param locale * @param outputStream * @throws IOException */ public void render(View view, Locale locale, OutputStream outputStream) throws IOException { logger.debug("rendering jade views {}", view); final Map<String, Object> model = Try.of(() -> convert(view)) .recover(this::recoverFromObjectMapping) .orElseThrow(Throwables::propagate); logger.debug("views class converted into the following model {}", model); Try.of(() -> cache.get(view.getClass())) .andThen((config) -> { logger.debug("rendering template with name {} and model {}", view.getTemplateName(), model); final String rendered = config.renderTemplate(config.getTemplate(view.getTemplateName()), model); outputStream.write( rendered.getBytes(view.getCharset().or(Charset.defaultCharset()))); }) .onFailure(Throwables::propagate); }
/** * Show the functions defined for the collection. */ @GET @Path("/{collection}/functions") public View getActiveView( @PathParam("collection") String collection, @DefaultValue("false") @QueryParam("hideInactive") boolean hideInactive) throws Exception { ThirdEyeAnomalyDetectionConfiguration config = collectionToConfigMap.get(collection); switch (config.getMode()) { case GENERIC: return getActiveGenericView(config, hideInactive); case RULEBASED: return getActiveRuleBasedView(config, hideInactive); default: throw new IllegalStateException(); } }
/** * Add function view for the collection. */ @GET @Path("/{collection}/functions/add") public View getAddView(@PathParam("collection") String collection) throws Exception { ThirdEyeAnomalyDetectionConfiguration config = collectionToConfigMap.get(collection); switch (config.getMode()) { case GENERIC: return new AddGenericView(config.getAnomalyDatabaseConfig().getUrl(), config.getAnomalyDatabaseConfig().getFunctionTableName(), config.getCollectionName(), SLASH.join("", collection, "functions", "add")); case RULEBASED: return new AddRuleBasedView(config.getAnomalyDatabaseConfig().getUrl(), config.getAnomalyDatabaseConfig().getFunctionTableName(), config.getCollectionName(), SLASH.join("", collection, "functions", "add")); default: throw new IllegalStateException(); } }
/** * JadeViewRenderer constructor that allows you to provide an instance * of the object mapper. * @param objectMapper */ private JadeViewRenderer(ObjectMapper objectMapper) { this.mapper = objectMapper; this.cache = CacheBuilder.newBuilder() .build(new CacheLoader<Class<? extends View>, JadeConfiguration>() { @Override public JadeConfiguration load(Class<? extends View> aClass) throws Exception { logger.debug("building new JadeConfiguration for views class {}", aClass); JadeConfiguration config = new JadeConfiguration(); config.setTemplateLoader(new JadeTemplateLoader(aClass)); return config; } }); }
@Test public void testRender() throws IOException { View view = new TestView("assertion"); ByteArrayOutputStream output = new ByteArrayOutputStream(); renderer.render(view, Locale.US, output); assertThat(output.toString(), equalTo(TemplateUtil.renderedRawFileToString(view))); }
@Test public void testNoProps() throws IOException { View view = new TestNoPropsView(); ByteArrayOutputStream output = new ByteArrayOutputStream(); renderer.render(view, Locale.US, output); assertThat(output.toString(), equalTo(TemplateUtil.renderedRawFileToString(view))); }
@Test public void testGetLastModified() throws IOException { final View view = view("assertion"); final long actual = new File(view.getClass().getResource(view.getTemplateName()).getFile()) .lastModified(); assertThat(loader.getLastModified(view.getTemplateName()), equalTo(actual)); }
@GET @Path("/preview-records/{media-type}") @Produces(ExtraMediaType.TEXT_HTML) @Timed public View jsonPreview(@PathParam("media-type") final String mediaType) { final int limit = register.getTotalRecords() > IndexSizePagination.ENTRY_LIMIT ? IndexSizePagination.ENTRY_LIMIT : register.getTotalRecords(); final List<Record> records = register.getRecords(limit, DEFAULT_OFFSET); return viewFactory.previewRecordsPageView(records, null, ExtraMediaType.transform(mediaType)); }
@GET @Path("/preview-records/{media-type}/{record-key}") @Produces(ExtraMediaType.TEXT_HTML) @Timed public View jsonByKeyPreview(@PathParam("media-type") final String mediaType, @PathParam("record-key") final String key) { final List<Record> records = Collections.singletonList(register.getRecord(key) .orElseThrow(() -> new NotFoundException("No records found with key: " + key))); return viewFactory.previewRecordsPageView(records, key, ExtraMediaType.transform(mediaType)); }
@GET @Path("/preview-items/{media-type}/sha-256:{item-hash}") @Produces(ExtraMediaType.TEXT_HTML) @Timed public View jsonByKeyPreview(@PathParam("media-type") final String mediaType, @PathParam("item-hash") final String itemHash) { final HashValue hash = new HashValue(HashingAlgorithm.SHA256, itemHash); final Item item = register.getItemBySha256(hash) .orElseThrow(() -> new NotFoundException("No item found with item hash: " + itemHash)); return viewFactory.previewItemPageView(item, itemHash, ExtraMediaType.transform(mediaType)); }
@GET @Path("/preview-entries/{media-type}") @Produces(ExtraMediaType.TEXT_HTML) @Timed public View preview(@PathParam("media-type") final String mediaType) { final int limit = register.getTotalEntries() > IndexSizePagination.ENTRY_LIMIT ? IndexSizePagination.ENTRY_LIMIT : register.getTotalEntries(); final Collection<Entry> entries = register.getEntries(START, limit); return viewFactory.previewEntriesPageView(entries, null, ExtraMediaType.transform(mediaType)); }
@GET @Path("/preview-entries/{media-type}/{entry-key}") @Produces(ExtraMediaType.TEXT_HTML) @Timed public View jsonByKeyPreview(@PathParam("media-type") final String mediaType, @PathParam("entry-key") final int key) { final Collection<Entry> entries = Collections.singletonList(register.getEntry(key).orElseThrow(NotFoundException::new)); return viewFactory.previewEntriesPageView(entries, key, ExtraMediaType.transform(mediaType)); }
@GET @Produces({ExtraMediaType.TEXT_HTML}) @Timed public View home() { return viewFactory.homePageView( register.getTotalRecords(), register.getTotalEntries(), register.getLastUpdatedTime(), register.getCustodianName() ); }
@GET @Path("/download") @Produces(ExtraMediaType.TEXT_HTML) @Timed public View download() { return viewFactory.downloadPageView(resourceConfiguration.getEnableDownloadResource()); }
@Override public void render(View view, Locale locale, OutputStream output) throws IOException, WebApplicationException { ThymeleafContext context = new ThymeleafContext((ThymeleafView) view); OutputStreamWriter writer = new OutputStreamWriter(output, StandardCharsets.UTF_8); engine.process(view.getTemplateName(), context, writer); writer.flush(); }
protected void writeOutput(View view, OutputStream output, Function<String,String> renderer) throws IOException { try ( final Writer writer = new PrintWriter(output); ) { final String template = templateCache.get(view.getTemplateName()); writer.write(renderer.apply(template)); } catch (ExecutionException exc) { if (FileNotFoundException.class.equals(exc.getCause().getClass())) { throw new FileNotFoundException(view.getTemplateName()); } throw new IOException(exc); } }
@GET @Path("{path:.*}") public View getIndex( @PathParam("path") String path ) { return indexView; }
@PermitAll @GET @Path("/view/recent_events/{num}") @Produces(MediaType.TEXT_HTML) public View getRecentEventsView(@Context UriInfo uriInfo, @PathParam("num") long num) { return new EventsView(database.getRecentEvents(num), uriInfo); }
@PermitAll @GET @Path("/view/recent_events/") @Produces(MediaType.TEXT_HTML) public View getRecentEventsView(@Context UriInfo uriInfo) { EventsView eventsView = new EventsView(database.getRecentEvents(30), uriInfo); return eventsView; }
@PermitAll @GET @Path("/view/recent_events/image") @Produces(MediaType.TEXT_HTML) public View getRecentEventsViewImage(@Context UriInfo uriInfo) { EventsView eventsView = new EventsView(database.getRecentEvents(30), uriInfo); eventsView.setDisplayImage(true); return eventsView; }
@GET @Timed @Produces(MediaType.TEXT_HTML) public View render(@PathParam("service") String serviceName) { final ServiceId serviceId = ServiceId.from(serviceName); final Optional<String> firstDependencyKey = FluentIterable .from(tenacityPropertyKeysStore.tenacityPropertyKeysFor(Instances.propertyKeyUris(serviceId))) .first(); if (firstDependencyKey.isPresent()) { return create(serviceId, DependencyId.from(firstDependencyKey.get()), Optional.<Long>absent()); } else { return new NoPropertyKeysView(serviceId); } }
@GET @Path("/dashboard/{collection}/{metricFunction}/{metricViewType}/{dimensionViewType}/{baselineOffsetMillis}") public View getDashboardView(@PathParam("collection") String collection, @PathParam("metricFunction") String metricFunction, @PathParam("metricViewType") MetricViewType metricViewType, @PathParam("dimensionViewType") DimensionViewType dimensionViewType, @PathParam("baselineOffsetMillis") Long baselineOffsetMillis, @Context UriInfo uriInfo) throws Exception { // Get segment metadata List<SegmentDescriptor> segments = dataCache.getSegmentDescriptors(serverUri, collection); if (segments.isEmpty()) { throw new NotFoundException("No data loaded in server for " + collection); } // Find the latest and earliest data times DateTime earliestDataTime = null; DateTime latestDataTime = null; for (SegmentDescriptor segment : segments) { if (segment.getStartDataTime() != null && (earliestDataTime == null || segment.getStartDataTime().compareTo(earliestDataTime) < 0)) { earliestDataTime = segment.getStartDataTime(); } if (segment.getEndDataTime() != null && (latestDataTime == null || segment.getEndDataTime().compareTo(latestDataTime) > 0)) { latestDataTime = segment.getEndDataTime(); } } if (earliestDataTime == null || latestDataTime == null) { throw new NotFoundException("No data loaded in server for " + collection); } return getDashboardView(collection, metricFunction, metricViewType, dimensionViewType, latestDataTime.getMillis() - baselineOffsetMillis, latestDataTime.getMillis(), uriInfo); }
@GET @Path("/metric/{collection}/{metricFunction}/{metricViewType}/{baselineMillis}/{currentMillis}") public View getMetricView(@PathParam("collection") String collection, @PathParam("metricFunction") String metricFunction, @PathParam("metricViewType") MetricViewType metricViewType, @PathParam("baselineMillis") Long baselineMillis, @PathParam("currentMillis") Long currentMillis, @Context UriInfo uriInfo) throws Exception { MultivaluedMap<String, String> dimensionValues = uriInfo.getQueryParameters(); CollectionSchema schema = dataCache.getCollectionSchema(serverUri, collection); // Metric view switch (metricViewType) { case INTRA_DAY: long intraPeriod = getIntraPeriod(metricFunction); // Dimension groups Map<String, Map<String, List<String>>> dimensionGroups = null; DimensionGroupSpec dimensionGroupSpec = configCache.getDimensionGroupSpec(collection); if (dimensionGroupSpec != null) { dimensionGroups = dimensionGroupSpec.getReverseMapping(); } String sql = SqlUtils.getSql(metricFunction, collection, new DateTime(baselineMillis - intraPeriod), new DateTime(currentMillis), dimensionValues, dimensionGroups); LOGGER.info("Generated SQL for {}: {}", uriInfo.getRequestUri(), sql); QueryResult result = queryCache.getQueryResult(serverUri, sql); return new MetricViewTabular(schema, objectMapper, result, currentMillis, currentMillis - baselineMillis, intraPeriod); case TIME_SERIES_FULL: case TIME_SERIES_OVERLAY: case FUNNEL: // n.b. will query /flot resource async return new MetricViewTimeSeries(schema, ViewUtils.flattenDisjunctions(dimensionValues)); default: throw new NotFoundException("No metric view implementation for " + metricViewType); } }
@Path("startRegistration") @GET public View startRegistration(@QueryParam("username") String username) throws U2fBadConfigurationException, U2fBadInputException { RegisterRequestData registerRequestData = u2f.startRegistration(APP_ID, getRegistrations(username)); requestStorage.put(registerRequestData.getRequestId(), registerRequestData.toJson()); return new RegistrationView(registerRequestData.toJson(), username); }
@Path("finishRegistration") @POST public View finishRegistration(@FormParam("tokenResponse") String response, @FormParam("username") String username) throws CertificateException, U2fBadInputException, U2fRegistrationException { RegisterResponse registerResponse = RegisterResponse.fromJson(response); RegisterRequestData registerRequestData = RegisterRequestData.fromJson(requestStorage.remove(registerResponse.getRequestId())); DeviceRegistration registration = u2f.finishRegistration(registerRequestData, registerResponse); Attestation attestation = metadataService.getAttestation(registration.getAttestationCertificate()); addRegistration(username, registration); return new FinishRegistrationView(attestation, registration); }
@Path("startAuthentication") @GET public View startAuthentication(@QueryParam("username") String username) throws U2fBadConfigurationException, U2fBadInputException { try { SignRequestData signRequestData = u2f.startSignature(APP_ID, getRegistrations(username)); requestStorage.put(signRequestData.getRequestId(), signRequestData.toJson()); return new AuthenticationView(signRequestData, username); } catch (NoEligibleDevicesException e) { return new AuthenticationView(new SignRequestData(APP_ID, "", Collections.<SignRequest>emptyList()), username); } }
@GET @Produces("text/html;charset=UTF-8") @Path("/utf8.ftl") public View freemarkerUTF8() { return new View("/views/ftl/utf8.ftl", Charsets.UTF_8) { }; }
@GET @Produces("text/html;charset=ISO-8859-1") @Path("/iso88591.ftl") public View freemarkerISO88591() { return new View("/views/ftl/iso88591.ftl", Charsets.ISO_8859_1) { }; }
@GET @Produces("text/html;charset=UTF-8") @Path("/utf8.mustache") public View mustacheUTF8() { return new View("/views/mustache/utf8.mustache", Charsets.UTF_8) { }; }
@GET @Produces("text/html;charset=ISO-8859-1") @Path("/iso88591.mustache") public View mustacheISO88591() { return new View("/views/mustache/iso88591.mustache", Charsets.ISO_8859_1) { }; }
public DropWizardContext(View view) { super(); checkNotNull(view, "view can not be null."); try { initVariableFromViewProperties(view); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | IntrospectionException e) { checkArgument(false, "failure to create DropwizardContext.view setting is wrong."); } }
@Override public void render(View view, Locale locale, OutputStream output) throws IOException, WebApplicationException { DropWizardContext context = new DropWizardContext(view); OutputStreamWriter writer = new OutputStreamWriter(output); engine.process(view.getTemplateName(), context, writer); writer.flush(); }
@Override public void render(View view, Locale locale, OutputStream output) throws IOException, WebApplicationException { try (Writer writer = new OutputStreamWriter(output, view.getCharset().or(Charsets.UTF_8))) { compilationCache.get(view.getTemplateName()).apply(view, writer); } catch (FileNotFoundException | ExecutionException e) { throw new FileNotFoundException("Template " + view.getTemplateName() + " not found."); } }
@Override public void render(View view, Locale locale, OutputStream output) throws IOException, WebApplicationException { Mustache template = null; if (hasLocalizedTemplates && locale != null) { // First try the Locale template = engine.getMustache(getLocalizedTemplateName(view.getTemplateName(), locale.toString())); if (template == null) { // Then only the language template = engine.getMustache(getLocalizedTemplateName(view.getTemplateName(), locale.getLanguage())); } } if (template == null) { template = engine.getMustache(view.getTemplateName()); } if (template == null) { throw new FileNotFoundException("Template not found: " + view.getTemplateName()); } final Writer writer = new OutputStreamWriter(output, engine.getConfiguration().getStringPropertyValue(EngineConfigurationKey.DEFAULT_FILE_ENCODING)); try { template.render(writer, view); } catch (MustacheException e) { throw new IOException(e); } finally { writer.flush(); } }
@GET @Produces(MediaType.TEXT_HTML) public View getShowsDatabase() throws IOException { final List<Episode> episodes = Lists.newArrayList(shows.getAllEpisodes()); Collections.sort(episodes); return new ShowsView(episodes); }