Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev UI - qute - improve the "render preview" page #20548

Merged
merged 1 commit into from
Oct 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package io.quarkus.qute.deployment;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.quarkus.deployment.annotations.ExecutionTime.STATIC_INIT;
import static java.util.stream.Collectors.toMap;

Expand All @@ -9,7 +8,6 @@
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Modifier;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
Expand All @@ -27,7 +25,6 @@
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Pattern;
Expand Down Expand Up @@ -78,8 +75,6 @@
import io.quarkus.deployment.builditem.nativeimage.NativeImageResourceBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.util.JandexUtil;
import io.quarkus.dev.console.DevConsoleManager;
import io.quarkus.devconsole.spi.DevConsoleRouteBuildItem;
import io.quarkus.gizmo.ClassOutput;
import io.quarkus.panache.common.deployment.PanacheEntityClassesBuildItem;
import io.quarkus.qute.CheckedTemplate;
Expand Down Expand Up @@ -116,20 +111,12 @@
import io.quarkus.qute.runtime.QuteRecorder;
import io.quarkus.qute.runtime.QuteRecorder.QuteContext;
import io.quarkus.qute.runtime.TemplateProducer;
import io.quarkus.qute.runtime.devmode.QuteDevConsoleRecorder;
import io.quarkus.qute.runtime.extensions.CollectionTemplateExtensions;
import io.quarkus.qute.runtime.extensions.ConfigTemplateExtensions;
import io.quarkus.qute.runtime.extensions.MapTemplateExtensions;
import io.quarkus.qute.runtime.extensions.NumberTemplateExtensions;
import io.quarkus.qute.runtime.extensions.StringTemplateExtensions;
import io.quarkus.qute.runtime.extensions.TimeTemplateExtensions;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;

public class QuteProcessor {

Expand Down Expand Up @@ -1235,54 +1222,6 @@ void initialize(BuildProducer<SyntheticBeanBuildItem> syntheticBeans, QuteRecord
.done());
}

@BuildStep
@Record(value = STATIC_INIT, optional = true)
DevConsoleRouteBuildItem invokeEndpoint(QuteDevConsoleRecorder recorder) {
recorder.setupRenderer();
return new DevConsoleRouteBuildItem("preview", "POST", new Handler<RoutingContext>() {
@Override
public void handle(RoutingContext context) {
context.request().setExpectMultipart(true);
context.request().endHandler(new Handler<Void>() {
@Override
public void handle(Void ignore) {
MultiMap form = context.request().formAttributes();
String templatePath = form.get("template-path");
String testJsonData = form.get("template-data");
String contentType = null;
String fileName = templatePath;
int slashIdx = fileName.lastIndexOf('/');
if (slashIdx != -1) {
fileName = fileName.substring(slashIdx, fileName.length());
}
int dotIdx = fileName.lastIndexOf('.');
if (dotIdx != -1) {
String suffix = fileName.substring(dotIdx + 1, fileName.length());
if (suffix.equalsIgnoreCase("json")) {
contentType = Variant.APPLICATION_JSON;
} else {
contentType = URLConnection.getFileNameMap().getContentTypeFor(fileName);
}
}
try {
BiFunction<String, Object, String> renderer = DevConsoleManager
.getGlobal(QuteDevConsoleRecorder.RENDER_HANDLER);
Object testData = Json.decodeValue(testJsonData);
testData = translate(testData); //translate it to JDK types
context.response().setStatusCode(200).putHeader(CONTENT_TYPE, contentType)
.end(renderer.apply(templatePath, testData));
} catch (DecodeException e) {
context.response().setStatusCode(500).putHeader(CONTENT_TYPE, "text/plain; charset=UTF-8")
.end("Failed to parse JSON: " + e.getMessage());
} catch (Throwable e) {
context.fail(e);
}
}
});
}
});
}

@BuildStep
QualifierRegistrarBuildItem turnLocationIntoQualifier() {
return new QualifierRegistrarBuildItem(new QualifierRegistrar() {
Expand All @@ -1294,38 +1233,6 @@ public Map<DotName, Set<String>> getAdditionalQualifiers() {
});
}

/**
* translates Json types to JDK types
*
* @param testData
* @return
*/
private Object translate(Object testData) {
if (testData instanceof JsonArray) {
return translate((JsonArray) testData);
} else if (testData instanceof JsonObject) {
return translate((JsonObject) testData);
}
return testData;
}

private Object translate(JsonArray testData) {
List<Object> ret = new ArrayList<>();
for (Object i : testData.getList()) {
ret.add(translate(i));
}
return ret;
}

private Object translate(JsonObject testData) {
Map<String, Object> map = new HashMap<>();
Map<String, Object> data = testData.getMap();
for (String i : testData.fieldNames()) {
map.put(i, translate(data.get(i)));
}
return map;
}

private static Type resolveType(AnnotationTarget member, Match match, IndexView index,
TemplateExtensionMethodBuildItem extensionMethod) {
Type matchType;
Expand All @@ -1339,9 +1246,11 @@ private static Type resolveType(AnnotationTarget member, Match match, IndexView
// If needed attempt to resolve the type variables using the declaring type
if (Types.containsTypeVariable(matchType)) {
// First get the type closure of the current match type
Set<Type> closure = Types.getTypeClosure(match.clazz, Types.buildResolvedMap(
match.getParameterizedTypeArguments(), match.getTypeParameters(),
new HashMap<>(), index), index);
Set<Type> closure = Types.getTypeClosure(match.clazz,
Types.buildResolvedMap(
match.getParameterizedTypeArguments(), match.getTypeParameters(),
new HashMap<>(), index),
index);

DotName declaringClassName = null;
Type extensionMatchBase = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public List<TemplateAnalysis> getAnalysis() {
/**
* Analysis of a particular template found in the given path.
*/
static class TemplateAnalysis {
public static final class TemplateAnalysis {

// A user-defined id; may be null
public final String id;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package io.quarkus.qute.deployment.devconsole;

import java.util.List;
import java.util.Map;

public class DevQuteTemplateInfo implements Comparable<DevQuteTemplateInfo> {

private final String path;
private final List<String> variants;
// variant -> source
private final Map<String, String> variants;
private final String methodInfo;
private final Map<String, String> parameters;

public DevQuteTemplateInfo(String path, List<String> variants, String methodInfo, Map<String, String> parameters) {
public DevQuteTemplateInfo(String path, Map<String, String> variants, String methodInfo,
Map<String, String> parameters) {
this.path = path;
this.variants = variants;
this.methodInfo = methodInfo;
Expand All @@ -25,7 +26,7 @@ public String getPath() {
return path;
}

public List<String> getVariants() {
public Map<String, String> getVariants() {
return variants;
}

Expand All @@ -37,4 +38,5 @@ public String getMethodInfo() {
public int compareTo(DevQuteTemplateInfo o) {
return path.compareTo(o.path);
}

}
Original file line number Diff line number Diff line change
@@ -1,38 +1,115 @@
package io.quarkus.qute.deployment.devconsole;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.quarkus.deployment.annotations.ExecutionTime.STATIC_INIT;

import java.io.IOException;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.BiFunction;

import org.jboss.logging.Logger;

import io.quarkus.deployment.IsDevelopment;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.dev.console.DevConsoleManager;
import io.quarkus.devconsole.spi.DevConsoleRouteBuildItem;
import io.quarkus.devconsole.spi.DevConsoleTemplateInfoBuildItem;
import io.quarkus.qute.Variant;
import io.quarkus.qute.deployment.CheckedTemplateBuildItem;
import io.quarkus.qute.deployment.TemplatePathBuildItem;
import io.quarkus.qute.deployment.TemplateVariantsBuildItem;
import io.quarkus.qute.runtime.devmode.QuteDevConsoleRecorder;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;

public class QuteDevConsoleProcessor {

private static final Logger LOG = Logger.getLogger(QuteDevConsoleProcessor.class);

@BuildStep
@Record(value = STATIC_INIT, optional = true)
DevConsoleRouteBuildItem invokeEndpoint(QuteDevConsoleRecorder recorder) {
recorder.setupRenderer();
return new DevConsoleRouteBuildItem("preview", "POST", new Handler<RoutingContext>() {
@Override
public void handle(RoutingContext context) {
context.request().setExpectMultipart(true);
context.request().endHandler(new Handler<Void>() {
@Override
public void handle(Void ignore) {
MultiMap form = context.request().formAttributes();
String templatePath = form.get("template-select");
String testJsonData = form.get("template-data");
String contentType = null;
String fileName = templatePath;
int slashIdx = fileName.lastIndexOf('/');
if (slashIdx != -1) {
fileName = fileName.substring(slashIdx, fileName.length());
}
int dotIdx = fileName.lastIndexOf('.');
if (dotIdx != -1) {
String suffix = fileName.substring(dotIdx + 1, fileName.length());
if (suffix.equalsIgnoreCase("json")) {
contentType = Variant.APPLICATION_JSON;
} else {
contentType = URLConnection.getFileNameMap().getContentTypeFor(fileName);
}
}
try {
BiFunction<String, Object, String> renderer = DevConsoleManager
.getGlobal(QuteDevConsoleRecorder.RENDER_HANDLER);
Object testData = Json.decodeValue(testJsonData);
testData = translate(testData); //translate it to JDK types
context.response().setStatusCode(200).putHeader(CONTENT_TYPE, contentType)
.end(renderer.apply(templatePath, testData));
} catch (DecodeException e) {
context.response().setStatusCode(500).putHeader(CONTENT_TYPE, "text/plain; charset=UTF-8")
.end("Failed to parse JSON: " + e.getMessage());
} catch (Throwable e) {
context.fail(e);
}
}
});
}
});
}

@BuildStep(onlyIf = IsDevelopment.class)
public DevConsoleTemplateInfoBuildItem collectTemplateInfo(
List<TemplatePathBuildItem> templatePaths,
List<CheckedTemplateBuildItem> checkedTemplates,
TemplateVariantsBuildItem variants) {

DevQuteInfos quteInfos = new DevQuteInfos();

for (Entry<String, List<String>> entry : variants.getVariants().entrySet()) {
CheckedTemplateBuildItem checkedTemplate = findCheckedTemplate(entry.getKey(), checkedTemplates);
if (checkedTemplate != null) {
quteInfos.addQuteTemplateInfo(new DevQuteTemplateInfo(checkedTemplate.templateId,
entry.getValue(),
processVariants(templatePaths, entry.getValue()),
checkedTemplate.method.declaringClass().name() + "." + checkedTemplate.method.name() + "()",
checkedTemplate.bindings));
} else {
quteInfos.addQuteTemplateInfo(new DevQuteTemplateInfo(entry.getKey(),
entry.getValue(),
processVariants(templatePaths, entry.getValue()),
null, null));
}
}
return new DevConsoleTemplateInfoBuildItem("devQuteInfos", quteInfos);

}

private CheckedTemplateBuildItem findCheckedTemplate(String basePath, List<CheckedTemplateBuildItem> checkedTemplates) {
Expand All @@ -44,4 +121,57 @@ private CheckedTemplateBuildItem findCheckedTemplate(String basePath, List<Check
return null;
}

private Map<String, String> processVariants(List<TemplatePathBuildItem> templatePaths, List<String> variants) {
Map<String, String> variantsMap = new HashMap<>();
for (String variant : variants) {
String source = "";
Path sourcePath = templatePaths.stream().filter(p -> p.getPath().equals(variant))
.map(TemplatePathBuildItem::getFullPath).findFirst()
.orElse(null);
if (sourcePath != null) {
try {
byte[] content = Files.readAllBytes(sourcePath);
source = new String(content, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.warn("Unable to read the template from path: " + sourcePath, e);
}
}
source = source.replace("\n", "\\n");
variantsMap.put(variant, source);
}
return variantsMap;
}

/**
* translates Json types to JDK types
*
* @param testData
* @return
*/
private Object translate(Object testData) {
if (testData instanceof JsonArray) {
return translate((JsonArray) testData);
} else if (testData instanceof JsonObject) {
return translate((JsonObject) testData);
}
return testData;
}

private Object translate(JsonArray testData) {
List<Object> ret = new ArrayList<>();
for (Object i : testData.getList()) {
ret.add(translate(i));
}
return ret;
}

private Object translate(JsonObject testData) {
Map<String, Object> map = new HashMap<>();
Map<String, Object> data = testData.getMap();
for (String i : testData.fieldNames()) {
map.put(i, translate(data.get(i)));
}
return map;
}

}
Loading