Search in sources :

Example 1 with Variant

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);
        }
    });
}
Also used : Variant(io.quarkus.qute.Variant) TemplateLocator(io.quarkus.qute.TemplateLocator) Optional(java.util.Optional) StringReader(java.io.StringReader) Reader(java.io.Reader) StringReader(java.io.StringReader) RawString(io.quarkus.qute.RawString)

Example 2 with 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");
    }
}
Also used : ArrayList(java.util.ArrayList) Variant(io.quarkus.qute.Variant) Uni(io.smallrye.mutiny.Uni) Mail(io.quarkus.mailer.Mail) ArrayList(java.util.ArrayList) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage)

Example 3 with Variant

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;
            }
        });
    }
}
Also used : Locale(java.util.Locale) ArcContainer(io.quarkus.arc.ArcContainer) Resolver(io.quarkus.qute.Resolver) NamespaceResolver(io.quarkus.qute.NamespaceResolver) HashMap(java.util.HashMap) EvalContext(io.quarkus.qute.EvalContext) Variant(io.quarkus.qute.Variant) NamespaceResolver(io.quarkus.qute.NamespaceResolver) HashMap(java.util.HashMap) Map(java.util.Map) CompletionStage(java.util.concurrent.CompletionStage)

Example 4 with Variant

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);
        }
    }
}
Also used : Locale(java.util.Locale) ArrayList(java.util.ArrayList) SuspendableContainerResponseContext(org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerResponseContext) TemplateInstance(io.quarkus.qute.TemplateInstance) Variant(io.quarkus.qute.Variant) MediaType(javax.ws.rs.core.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) Engine(io.quarkus.qute.Engine)

Example 5 with Variant

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();
    });
}
Also used : Locale(java.util.Locale) TemplateException(io.quarkus.qute.TemplateException) ArrayList(java.util.ArrayList) TemplateInstance(io.quarkus.qute.TemplateInstance) Variant(io.quarkus.qute.Variant) MediaType(javax.ws.rs.core.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) ServerResponseFilter(org.jboss.resteasy.reactive.server.ServerResponseFilter)

Aggregations

Variant (io.quarkus.qute.Variant)5 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Locale (java.util.Locale)3 Engine (io.quarkus.qute.Engine)2 TemplateInstance (io.quarkus.qute.TemplateInstance)2 CompletionStage (java.util.concurrent.CompletionStage)2 MediaType (javax.ws.rs.core.MediaType)2 ArcContainer (io.quarkus.arc.ArcContainer)1 AdditionalBeanBuildItem (io.quarkus.arc.deployment.AdditionalBeanBuildItem)1 BeanArchiveIndexBuildItem (io.quarkus.arc.deployment.BeanArchiveIndexBuildItem)1 BeanDiscoveryFinishedBuildItem (io.quarkus.arc.deployment.BeanDiscoveryFinishedBuildItem)1 QualifierRegistrarBuildItem (io.quarkus.arc.deployment.QualifierRegistrarBuildItem)1 SyntheticBeanBuildItem (io.quarkus.arc.deployment.SyntheticBeanBuildItem)1 ValidationPhaseBuildItem (io.quarkus.arc.deployment.ValidationPhaseBuildItem)1 ValidationErrorBuildItem (io.quarkus.arc.deployment.ValidationPhaseBuildItem.ValidationErrorBuildItem)1 Annotations (io.quarkus.arc.processor.Annotations)1 BeanInfo (io.quarkus.arc.processor.BeanInfo)1 DotNames (io.quarkus.arc.processor.DotNames)1 InjectionPointInfo (io.quarkus.arc.processor.InjectionPointInfo)1