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

Qute - deprecate Results.Result enum and introduce Results.NotFound #18110

Merged
merged 1 commit into from
Jun 24, 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
Expand Up @@ -818,7 +818,7 @@ private void implementResolve(String defaultBundleImpl, ClassCreator bundleCreat
BytecodeCreator success = throwableIsNull.trueBranch();

// Return if the name is null or NOT_FOUND
ResultHandle resultNotFound = success.readStaticField(Descriptors.RESULT_NOT_FOUND);
ResultHandle resultNotFound = success.invokeStaticInterfaceMethod(Descriptors.NOT_FOUND_FROM_EC, whenEvalContext);
BytecodeCreator nameIsNull = success.ifNull(whenComplete.getMethodParam(0)).trueBranch();
nameIsNull.invokeVirtualMethod(Descriptors.COMPLETABLE_FUTURE_COMPLETE, whenRet,
resultNotFound);
Expand Down Expand Up @@ -893,7 +893,7 @@ private void implementResolve(String defaultBundleImpl, ClassCreator bundleCreat
MethodDescriptor.ofMethod(defaultBundleImpl, "resolve", CompletionStage.class, EvalContext.class),
resolve.getThis(), evalContext));
} else {
resolve.returnValue(resolve.readStaticField(Descriptors.RESULTS_NOT_FOUND));
resolve.returnValue(resolve.invokeStaticMethod(Descriptors.RESULTS_NOT_FOUND_EC, evalContext));
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package io.quarkus.qute.deployment;

import static org.junit.jupiter.api.Assertions.assertEquals;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateException;
import io.quarkus.test.QuarkusDevModeTest;
import io.quarkus.vertx.web.Route;
import io.restassured.RestAssured;

public class PropertyNotFoundDevModeTest {

@RegisterExtension
static final QuarkusDevModeTest testConfig = new QuarkusDevModeTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClass(Routes.class)
.addAsResource(new StringAsset("{foo.surname}"), "templates/foo.html")
.addAsResource(new StringAsset("{bar.name}"), "templates/bar.html"));

@Test
public void testExceptionIsThrown() {
assertEquals("Property \"foo\" not found in expression {foo.surname} in template foo on line 1",
RestAssured.get("test-foo").then().statusCode(200).extract().body().asString());
assertEquals(
"Property \"name\" not found on base object \"java.lang.String\" in expression {bar.name} in template bar on line 1",
RestAssured.get("test-bar").then().statusCode(200).extract().body().asString());
}

@Singleton
public static class Routes {

@Inject
Template foo;

@Route(produces = "text/plain")
String testFoo() {
try {
return foo.render();
} catch (TemplateException e) {
return e.getMessage();
}
}

@Inject
Template bar;

@Route(produces = "text/plain")
String testBar() {
try {
return bar.data("bar", "alpha").render();
} catch (TemplateException e) {
return e.getMessage();
}
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,14 @@
import io.quarkus.qute.NamespaceResolver;
import io.quarkus.qute.ReflectionValueResolver;
import io.quarkus.qute.Resolver;
import io.quarkus.qute.Results.Result;
import io.quarkus.qute.Results;
import io.quarkus.qute.TemplateLocator.TemplateLocation;
import io.quarkus.qute.UserTagSectionHelper;
import io.quarkus.qute.ValueResolver;
import io.quarkus.qute.ValueResolvers;
import io.quarkus.qute.Variant;
import io.quarkus.qute.runtime.QuteRecorder.QuteContext;
import io.quarkus.runtime.LaunchMode;
import io.quarkus.runtime.Startup;

@Startup(Interceptor.Priority.PLATFORM_BEFORE)
Expand All @@ -52,7 +53,7 @@ public class EngineProducer {
private final String tagPath;

public EngineProducer(QuteContext context, QuteConfig config, QuteRuntimeConfig runtimeConfig,
Event<EngineBuilder> builderReady, Event<Engine> engineReady, ContentTypes contentTypes) {
Event<EngineBuilder> builderReady, Event<Engine> engineReady, ContentTypes contentTypes, LaunchMode launchMode) {
this.contentTypes = contentTypes;
this.suffixes = config.suffixes;
this.basePath = "templates/";
Expand Down Expand Up @@ -82,19 +83,26 @@ public EngineProducer(QuteContext context, QuteConfig config, QuteRuntimeConfig
builder.addValueResolver(ValueResolvers.arrayResolver());

// If needed use a specific result mapper for the selected strategy
switch (runtimeConfig.propertyNotFoundStrategy) {
case THROW_EXCEPTION:
if (runtimeConfig.propertyNotFoundStrategy.isPresent()) {
switch (runtimeConfig.propertyNotFoundStrategy.get()) {
case THROW_EXCEPTION:
builder.addResultMapper(new PropertyNotFoundThrowException());
break;
case NOOP:
builder.addResultMapper(new PropertyNotFoundNoop());
break;
case OUTPUT_ORIGINAL:
builder.addResultMapper(new PropertyNotFoundOutputOriginal());
break;
default:
// Use the default strategy
break;
}
} else {
// Throw an expection in the development mode
if (launchMode == LaunchMode.DEVELOPMENT) {
builder.addResultMapper(new PropertyNotFoundThrowException());
break;
case NOOP:
builder.addResultMapper(new PropertyNotFoundNoop());
break;
case OUTPUT_ORIGINAL:
builder.addResultMapper(new PropertyNotFoundOutputOriginal());
break;
default:
// Use the default strategy
break;
}
}

// Escape some characters for HTML templates
Expand All @@ -112,7 +120,7 @@ public EngineProducer(QuteContext context, QuteConfig config, QuteRuntimeConfig
// Resolve @Named beans
builder.addNamespaceResolver(NamespaceResolver.builder(INJECT_NAMESPACE).resolve(ctx -> {
InstanceHandle<Object> bean = Arc.container().instance(ctx.getName());
return bean.isAvailable() ? bean.get() : Result.NOT_FOUND;
return bean.isAvailable() ? bean.get() : Results.NotFound.from(ctx);
}).build());

// Add generated resolvers
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import io.quarkus.qute.Expression;
import io.quarkus.qute.ResultMapper;
import io.quarkus.qute.Results.Result;
import io.quarkus.qute.Results;
import io.quarkus.qute.TemplateNode.Origin;

class PropertyNotFoundNoop implements ResultMapper {
Expand All @@ -14,7 +14,7 @@ public int getPriority() {

@Override
public boolean appliesTo(Origin origin, Object result) {
return result.equals(Result.NOT_FOUND);
return Results.isNotFound(result);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import io.quarkus.qute.Expression;
import io.quarkus.qute.ResultMapper;
import io.quarkus.qute.Results.Result;
import io.quarkus.qute.Results;
import io.quarkus.qute.TemplateNode.Origin;

class PropertyNotFoundOutputOriginal implements ResultMapper {
Expand All @@ -14,7 +14,7 @@ public int getPriority() {

@Override
public boolean appliesTo(Origin origin, Object result) {
return result.equals(Result.NOT_FOUND);
return Results.isNotFound(result);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import io.quarkus.qute.Expression;
import io.quarkus.qute.ResultMapper;
import io.quarkus.qute.Results.Result;
import io.quarkus.qute.Results;
import io.quarkus.qute.Results.NotFound;
import io.quarkus.qute.TemplateException;
import io.quarkus.qute.TemplateNode.Origin;

Expand All @@ -15,13 +16,19 @@ public int getPriority() {

@Override
public boolean appliesTo(Origin origin, Object result) {
return result.equals(Result.NOT_FOUND);
return Results.isNotFound(result);
}

@Override
public String map(Object result, Expression expression) {
String propertyMessage;
if (result instanceof NotFound) {
propertyMessage = ((NotFound) result).asMessage();
} else {
propertyMessage = "Property not found";
}
throw new TemplateException(expression.getOrigin(),
String.format("Property not found in expression {%s} in template %s on line %s", expression.toOriginalString(),
String.format("%s in expression {%s} in template %s on line %s", propertyMessage, expression.toOriginalString(),
expression.getOrigin().getTemplateId(), expression.getOrigin().getLine()));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package io.quarkus.qute.runtime;

import java.util.Optional;

import io.quarkus.qute.TemplateException;
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
Expand All @@ -13,9 +15,12 @@ public class QuteRuntimeConfig {
* <p>
* This strategy is not used when evaluating an expression that is used in a section parameter, e.g.
* <code>{#if foo.name}</code>. In such case, it's the responsibility of the section to handle this situation appropriately.
* <p>
* By default, the {@code NOT_FOUND} constant is written to the output. However, in the development mode the
* {@link PropertyNotFoundStrategy#THROW_EXCEPTION} is used by default, i.e. when the strategy is not specified.
*/
@ConfigItem(defaultValue = "default")
public PropertyNotFoundStrategy propertyNotFoundStrategy;
@ConfigItem
public Optional<PropertyNotFoundStrategy> propertyNotFoundStrategy;
/**
* Specify whether the parser should remove standalone lines from the output. A standalone line is a line that contains at
* least one section tag, parameter declaration, or comment but no expression and no non-whitespace character.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import javax.enterprise.inject.Vetoed;

import io.quarkus.qute.Results.Result;
import io.quarkus.qute.Results;
import io.quarkus.qute.TemplateExtension;

@Vetoed // Make sure no bean is created from this class
Expand All @@ -23,7 +23,7 @@ static <T> T getByIndex(List<T> list, String index) {
int idx = Integer.parseInt(index);
if (idx >= list.size()) {
// Be consistent with property resolvers
return (T) Result.NOT_FOUND;
return (T) Results.NotFound.from(index);
}
return list.get(idx);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import org.eclipse.microprofile.config.ConfigProvider;

import io.quarkus.qute.Results.Result;
import io.quarkus.qute.Results;
import io.quarkus.qute.TemplateExtension;

@Vetoed // Make sure no bean is created from this class
Expand All @@ -27,7 +27,7 @@ static Object getConfigProperty(String propertyName) {
@TemplateExtension(namespace = CONFIG, priority = DEFAULT_PRIORITY + 1)
static Object property(String propertyName) {
Optional<String> val = ConfigProvider.getConfig().getOptionalValue(propertyName, String.class);
return val.isPresent() ? val.get() : Result.NOT_FOUND;
return val.isPresent() ? val.get() : Results.NotFound.from(propertyName);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import javax.enterprise.inject.Vetoed;

import io.quarkus.qute.Results.Result;
import io.quarkus.qute.Results;
import io.quarkus.qute.TemplateExtension;

@Vetoed // Make sure no bean is created from this class
Expand All @@ -31,7 +31,7 @@ static Object map(Map map, String name) {
default:
Object val = map.get(name);
if (val == null) {
return map.containsKey(name) ? null : Result.NOT_FOUND;
return map.containsKey(name) ? null : Results.NotFound.from(name);
}
return val;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@
import io.quarkus.qute.ReflectionValueResolver;
import io.quarkus.qute.ResultMapper;
import io.quarkus.qute.Results;
import io.quarkus.qute.Results.Result;
import io.quarkus.qute.TemplateException;
import io.quarkus.qute.TemplateLocator;
import io.quarkus.qute.TemplateNode.Origin;
Expand Down Expand Up @@ -428,14 +427,14 @@ private Engine buildEngine(List<DevTemplatePathBuildItem> devTemplatePaths,
.addNamespaceResolver(NamespaceResolver.builder("info").resolve(ctx -> {
String ext = DevConsole.currentExtension.get();
if (ext == null) {
return Results.Result.NOT_FOUND;
return Results.NotFound.from(ctx);
}
Map<String, Object> map = DevConsoleManager.getTemplateInfo().get(ext);
if (map == null) {
return Results.Result.NOT_FOUND;
return Results.NotFound.from(ctx);
}
Object result = map.get(ctx.getName());
return result == null ? Results.Result.NOT_FOUND : result;
return result == null ? Results.NotFound.from(ctx) : result;
}).build());

// Create map of resolved paths
Expand All @@ -454,17 +453,17 @@ private Engine buildEngine(List<DevTemplatePathBuildItem> devTemplatePaths,
builder.addNamespaceResolver(NamespaceResolver.builder("config").resolveAsync(ctx -> {
List<Expression> params = ctx.getParams();
if (params.size() != 1 || (!ctx.getName().equals("property") && !ctx.getName().equals("http-path"))) {
return Results.NOT_FOUND;
return Results.notFound(ctx);
}
if (ctx.getName().equals("http-path")) {
return ctx.evaluate(params.get(0)).thenCompose(propertyName -> {
String value = resolvedPaths.get(propertyName.toString());
return CompletableFuture.completedFuture(value != null ? value : Result.NOT_FOUND);
return CompletableFuture.completedFuture(value != null ? value : Results.NotFound.from(ctx));
});
} else {
return ctx.evaluate(params.get(0)).thenCompose(propertyName -> {
Optional<String> val = ConfigProvider.getConfig().getOptionalValue(propertyName.toString(), String.class);
return CompletableFuture.completedFuture(val.isPresent() ? val.get() : Result.NOT_FOUND);
return CompletableFuture.completedFuture(val.isPresent() ? val.get() : Results.NotFound.from(ctx));
});
}
}).build());
Expand Down Expand Up @@ -493,7 +492,7 @@ public int getPriority() {

@Override
public boolean appliesTo(Origin origin, Object result) {
return result.equals(Result.NOT_FOUND);
return Results.isNotFound(result);
}

@Override
Expand Down Expand Up @@ -790,7 +789,7 @@ public Object apply(EvalContext ctx) {
}
return "/io.quarkus.quarkus-vertx-http/openInIDE";
}
return Results.Result.NOT_FOUND;
return Results.notFound(ctx);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public CompletionStage<Object> resolve(EvalContext context) {
default:
return jsonObject.containsKey(context.getName())
? CompletableFuture.completedFuture(jsonObject.getValue(context.getName()))
: Results.NOT_FOUND;
: Results.notFound(context);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public CompletionStage<Object> resolve(EvalContext context) {
default:
return multiMap.contains(context.getName())
? CompletableFuture.completedFuture(multiMap.get(context.getName()))
: Results.NOT_FOUND;
: Results.notFound(context);
}
}

Expand Down
Loading