use of io.quarkus.qute.Variant in project quarkus by quarkusio.
the class DevConsoleProcessor method locateTemplate.
private static Optional<TemplateLocator.TemplateLocation> locateTemplate(String id, Map<String, String> templates) {
String template = templates.get(id);
if (template == null) {
// Try path with suffixes
for (String suffix : suffixes) {
id = id + "." + suffix;
template = templates.get(id);
if (template != null) {
break;
}
}
}
if (template == null)
return Optional.empty();
String templateName = id;
String finalTemplate = template;
return Optional.of(new TemplateLocator.TemplateLocation() {
@Override
public Reader read() {
return new StringReader(finalTemplate);
}
@Override
public Optional<Variant> getVariant() {
Variant variant = null;
String fileName = templateName;
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")) {
variant = Variant.forContentType(Variant.APPLICATION_JSON);
} else {
String contentType = URLConnection.getFileNameMap().getContentTypeFor(fileName);
if (contentType != null) {
variant = Variant.forContentType(contentType);
}
}
}
return Optional.ofNullable(variant);
}
});
}
use of io.quarkus.qute.Variant in project quarkus by quarkusio.
the class MailTemplateInstanceImpl method send.
@Override
public Uni<Void> send() {
Object variantsAttr = templateInstance.getAttribute(TemplateInstance.VARIANTS);
if (variantsAttr != null) {
List<Result> results = new ArrayList<>();
@SuppressWarnings("unchecked") List<Variant> variants = (List<Variant>) variantsAttr;
for (Variant variant : variants) {
if (variant.getContentType().equals(Variant.TEXT_HTML) || variant.getContentType().equals(Variant.TEXT_PLAIN)) {
results.add(new Result(variant, Uni.createFrom().completionStage(new Supplier<CompletionStage<? extends String>>() {
@Override
public CompletionStage<? extends String> get() {
return templateInstance.setAttribute(TemplateInstance.SELECTED_VARIANT, variant).renderAsync();
}
})));
}
}
if (results.isEmpty()) {
throw new IllegalStateException("No suitable template variant found");
}
List<Uni<String>> unis = results.stream().map(Result::resolve).collect(Collectors.toList());
return Uni.combine().all().unis(unis).combinedWith(combine(results)).chain(new Function<Mail, Uni<? extends Void>>() {
@Override
public Uni<? extends Void> apply(Mail m) {
return mailer.send(m);
}
});
} else {
throw new IllegalStateException("No template variant found");
}
}
use of io.quarkus.qute.Variant in project quarkus by quarkusio.
the class MessageBundles method setupNamespaceResolvers.
static void setupNamespaceResolvers(@Observes EngineBuilder builder, BundleContext context) {
// Avoid injecting "Instance<Object> instance" which prevents unused beans removal
ArcContainer container = Arc.container();
// For every bundle register a new resolver
for (Entry<String, Map<String, Class<?>>> entry : context.getBundleInterfaces().entrySet()) {
final String bundle = entry.getKey();
final Map<String, Resolver> interfaces = new HashMap<>();
Resolver resolver = null;
for (Entry<String, Class<?>> locEntry : entry.getValue().entrySet()) {
if (locEntry.getKey().equals(DEFAULT_LOCALE)) {
resolver = (Resolver) container.select(locEntry.getValue(), Default.Literal.INSTANCE).get();
continue;
}
Instance<?> found = container.select(locEntry.getValue(), new Localized.Literal(locEntry.getKey()));
if (found.isUnsatisfied()) {
throw new IllegalStateException(Qute.fmt("Bean not found for localized interface [{e.value}] and locale [{e.key}]").data("e", locEntry).render());
}
if (found.isAmbiguous()) {
throw new IllegalStateException(Qute.fmt("Multiple beans found for localized interface [{e.value}] and locale [{e.key}]").data("e", locEntry).render());
}
interfaces.put(locEntry.getKey(), (Resolver) found.get());
}
final Resolver defaultResolver = resolver;
builder.addNamespaceResolver(new NamespaceResolver() {
@Override
public CompletionStage<Object> resolve(EvalContext context) {
Object locale = context.getAttribute(ATTRIBUTE_LOCALE);
if (locale == null) {
Object selectedVariant = context.getAttribute(TemplateInstance.SELECTED_VARIANT);
if (selectedVariant != null) {
locale = ((Variant) selectedVariant).getLocale();
}
if (locale == null) {
return defaultResolver.resolve(context);
}
}
// First try the exact match
Resolver localeResolver = interfaces.get(locale instanceof Locale ? ((Locale) locale).toLanguageTag() : locale.toString());
if (localeResolver == null && locale instanceof Locale) {
// Next try the language
localeResolver = interfaces.get(((Locale) locale).getLanguage());
}
return localeResolver != null ? localeResolver.resolve(context) : defaultResolver.resolve(context);
}
@Override
public String getNamespace() {
return bundle;
}
});
}
}
use of io.quarkus.qute.Variant in project quarkus by quarkusio.
the class TemplateResponseFilter method filter.
@SuppressWarnings("unchecked")
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
Object entity = responseContext.getEntity();
if (entity instanceof TemplateInstance) {
SuspendableContainerResponseContext ctx = (SuspendableContainerResponseContext) responseContext;
ctx.suspend();
MediaType mediaType;
TemplateInstance instance = (TemplateInstance) entity;
Object variantsAttr = instance.getAttribute(TemplateInstance.VARIANTS);
if (variantsAttr != null) {
List<javax.ws.rs.core.Variant> variants = new ArrayList<>();
for (Variant variant : (List<Variant>) variantsAttr) {
variants.add(new javax.ws.rs.core.Variant(MediaType.valueOf(variant.getMediaType()), variant.getLocale(), variant.getEncoding()));
}
javax.ws.rs.core.Variant selected = requestContext.getRequest().selectVariant(variants);
if (selected != null) {
Locale selectedLocale = selected.getLanguage();
if (selectedLocale == null) {
List<Locale> acceptableLocales = requestContext.getAcceptableLanguages();
if (!acceptableLocales.isEmpty()) {
selectedLocale = acceptableLocales.get(0);
}
}
instance.setAttribute(TemplateInstance.SELECTED_VARIANT, new Variant(selectedLocale, selected.getMediaType().toString(), selected.getEncoding()));
mediaType = selected.getMediaType();
} else {
mediaType = responseContext.getMediaType();
}
} else {
mediaType = responseContext.getMediaType();
}
CompletionStage<String> cs = instance.renderAsync();
if (!Arc.container().instance(Engine.class).get().useAsyncTimeout()) {
// Make sure the timeout is always used
long timeout = instance.getTimeout();
cs = cs.toCompletableFuture().orTimeout(timeout, TimeUnit.MILLISECONDS);
}
try {
cs.whenComplete((r, t) -> {
if (t == null) {
// an NPE further down
if (mediaType != null) {
ctx.setEntity(r, null, mediaType);
} else {
ctx.setEntity(r);
}
ctx.resume();
} else {
ctx.resume(t);
}
});
} catch (Throwable t) {
ctx.resume(t);
}
}
}
use of io.quarkus.qute.Variant in project quarkus by quarkusio.
the class TemplateResponseFilter method filter.
@SuppressWarnings("unchecked")
@ServerResponseFilter
public Uni<Void> filter(ResteasyReactiveContainerRequestContext requestContext, ContainerResponseContext responseContext) {
Object entity = responseContext.getEntity();
if (!(entity instanceof TemplateInstance)) {
return null;
}
MediaType mediaType;
TemplateInstance instance = (TemplateInstance) entity;
Object variantsAttr = instance.getAttribute(TemplateInstance.VARIANTS);
if (variantsAttr != null) {
List<javax.ws.rs.core.Variant> variants = new ArrayList<>();
for (Variant variant : (List<Variant>) variantsAttr) {
variants.add(new javax.ws.rs.core.Variant(MediaType.valueOf(variant.getMediaType()), variant.getLocale(), variant.getEncoding()));
}
javax.ws.rs.core.Variant selected = requestContext.getRequest().selectVariant(variants);
if (selected != null) {
Locale selectedLocale = selected.getLanguage();
if (selectedLocale == null) {
List<Locale> acceptableLocales = requestContext.getAcceptableLanguages();
if (!acceptableLocales.isEmpty()) {
selectedLocale = acceptableLocales.get(0);
}
}
instance.setAttribute(TemplateInstance.SELECTED_VARIANT, new Variant(selectedLocale, selected.getMediaType().toString(), selected.getEncoding()));
mediaType = selected.getMediaType();
} else {
mediaType = responseContext.getMediaType();
}
} else {
mediaType = responseContext.getMediaType();
}
Uni<String> uni = instance.createUni();
if (!engine.useAsyncTimeout()) {
// Make sure the timeout is always used
long timeout = instance.getTimeout();
uni = uni.ifNoItem().after(Duration.ofMillis(timeout)).failWith(() -> new TemplateException(instance + " rendering timeout [" + timeout + "ms] occured"));
}
return uni.chain(r -> {
if (mediaType != null) {
responseContext.setEntity(r, null, mediaType);
} else {
responseContext.setEntity(r);
}
return Uni.createFrom().nullItem();
});
}
Aggregations