javax.mvc.engine.ViewEngine Java Examples

The following examples show how to use javax.mvc.engine.ViewEngine. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ViewEngineJspImpl.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
@Override
public void processView(ViewEngineContext viewEngineContext) throws ViewEngineException {

	String view = viewEngineContext.getView();

	String viewFolder = (String) configuration.getProperty(ViewEngine.VIEW_FOLDER);

	if (viewFolder == null) {
		viewFolder = ViewEngine.DEFAULT_VIEW_FOLDER;
	}

	String viewPath = viewFolder.concat(view);

	PortletRequestDispatcher requestDispatcher = portletContext.getRequestDispatcher(viewPath);

	try {
		requestDispatcher.include(viewEngineContext.getRequest(PortletRequest.class),
			viewEngineContext.getResponse(PortletResponse.class));
	}
	catch (Exception e) {
		throw new ViewEngineException(e);
	}
}
 
Example #2
Source File: EventDispatcher.java    From krazo with Apache License 2.0 5 votes vote down vote up
public void fireBeforeProcessViewEvent(ViewEngine engine, Viewable viewable) {
    if (KrazoCdiExtension.isEventObserved(BeforeProcessViewEvent.class)) {
        final BeforeProcessViewEventImpl event = new BeforeProcessViewEventImpl();
        event.setEngine(engine.getClass());
        event.setView(viewable.getView());
        mvcEventDispatcher.fire(event);
    }
}
 
Example #3
Source File: DefaultTrimouConfiguration.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Produces
@ViewEngineConfig
public MustacheEngine getMustacheEngine() {
    return MustacheEngineBuilder.newBuilder()
            .registerHelpers(HelpersBuilder.extra().build())
            .addTemplateLocator(ServletContextTemplateLocator.builder()
                    .setRootPath(getProperty(mvc.getConfig(),
                            ViewEngine.VIEW_FOLDER,
                            ViewEngine.DEFAULT_VIEW_FOLDER).toString())
                    .setServletContext(servletContext).build())
            .build();
}
 
Example #4
Source File: ViewEnginesProducer.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@ApplicationScoped
@Produces
@ViewEngines
public List<ViewEngine> getViewEngines(BeanManager beanManager, PortletContext portletContext,
	Configuration configuration) {

	List<ViewEngine> viewEngines = BeanUtil.getBeanInstances(beanManager, ViewEngine.class);

	viewEngines.add(new ViewEngineJspImpl(configuration, portletContext));

	Collections.sort(viewEngines, new DescendingPriorityComparator(ViewEngine.PRIORITY_APPLICATION));

	return viewEngines;
}
 
Example #5
Source File: TemplateEngineSupplierProducer.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@Override
public String get() {
	MvcContext mvcContext = beanFactory.getBean(MvcContext.class);

	javax.ws.rs.core.Configuration configuration = mvcContext.getConfig();

	String templateLocation = (String) configuration.getProperty(ViewEngine.VIEW_FOLDER);

	if (templateLocation == null) {
		templateLocation = ViewEngine.DEFAULT_VIEW_FOLDER;
	}

	return templateLocation;
}
 
Example #6
Source File: ViewEngineProducer.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@Bean
@Scope(proxyMode = ScopedProxyMode.INTERFACES, value = "portletRequest")
public ViewEngine getViewEngine(TemplateEngineSupplier templateEngineSupplier, IWebContext webContext) {
	return new ThymeleafViewEngine(templateEngineSupplier.get(), webContext,
			viewEngineContext -> {
				MimeResponse mimeResponse = viewEngineContext.getResponse(MimeResponse.class);

				try {
					return mimeResponse.getWriter();
				}
				catch (IOException e) {
					throw new ViewEngineException(e);
				}
			});
}
 
Example #7
Source File: ViewEngineProducer.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@PortletRequestScoped
@Produces
public ViewEngine getTimeleafViewEngine(TemplateEngineSupplier templateEngineSupplier, IWebContext webContext) {
	return new ThymeleafViewEngine(templateEngineSupplier.get(), webContext,
			viewEngineContext -> {
				MimeResponse mimeResponse = viewEngineContext.getResponse(MimeResponse.class);

				try {
					return mimeResponse.getWriter();
				}
				catch (IOException e) {
					throw new ViewEngineException(e);
				}
			});
}
 
Example #8
Source File: ViewEngineBaseTest.java    From ozark with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveViewCustomFolder() {
	ViewEngineContext ctx = EasyMock.createMock(ViewEngineContext.class);
	Configuration config = EasyMock.createMock(Configuration.class);
	expect(config.getProperty(eq(ViewEngine.VIEW_FOLDER))).andReturn("/somewhere/else");
	expect(ctx.getConfiguration()).andReturn(config);
	expect(ctx.getView()).andReturn("index.jsp");
	replay(ctx, config);
	assertThat(viewEngineBase.resolveView(ctx), is("/somewhere/else/index.jsp"));
	verify(ctx, config);
}
 
Example #9
Source File: ViewEngineBaseTest.java    From ozark with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveView() {
	ViewEngineContext ctx = EasyMock.createMock(ViewEngineContext.class);
	Configuration config = EasyMock.createMock(Configuration.class);
	expect(config.getProperty(eq(ViewEngine.VIEW_FOLDER))).andReturn(null);
	expect(ctx.getConfiguration()).andReturn(config);
	expect(ctx.getView()).andReturn("index.jsp");
	expect(ctx.getView()).andReturn("/somewhere/else/index.jsp");
	replay(ctx, config);
	assertThat(viewEngineBase.resolveView(ctx), is("/WEB-INF/views/index.jsp"));
	assertThat(viewEngineBase.resolveView(ctx), is("/somewhere/else/index.jsp"));
	verify(ctx, config);
}
 
Example #10
Source File: ViewEngineFinder.java    From ozark with Apache License 2.0 5 votes vote down vote up
/**
 * Finds view engine for a viewable.
 *
 * @param viewable the viewable to be used.
 * @return selected view engine or {@code null} if none found.
 */
public ViewEngine find(Viewable viewable) {
    Optional<ViewEngine> engine;
    final String view = viewable.getView();

    // If engine specified in viewable, use it
    final Class<? extends ViewEngine> engineClass = viewable.getViewEngine();
    if (engineClass != null) {
        engine = Optional.of(cdiUtils.newBean(engineClass));
    } else {
        // Check cache first
        engine = Optional.ofNullable(cache.get(view));

        if (!engine.isPresent()) {
            List<ViewEngine> engines = CdiUtils.getApplicationBeans(ViewEngine.class);

            // Gather set of candidates
            final Set<ViewEngine> candidates = engines.stream()
                    .filter(e -> e.supports(view)).collect(toSet());

            // Find candidate with highest priority
            engine = candidates.stream().max(
                    (e1, e2) -> {
                        final Priority p1 = getAnnotation(e1.getClass(), Priority.class);
                        final int v1 = p1 != null ? p1.value() : ViewEngine.PRIORITY_APPLICATION;
                        final Priority p2 = getAnnotation(e2.getClass(), Priority.class);
                        final int v2 = p2 != null ? p2.value() : ViewEngine.PRIORITY_APPLICATION;
                        return v1 - v2;
                    });
            // Update cache
            if (engine.isPresent()) {
                cache.put(view, engine.get());
            }
        }
    }
    return engine.isPresent() ? engine.get() : null;
}
 
Example #11
Source File: ViewEngineBaseTest.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveViewCustomFolder() {
	ViewEngineContext ctx = EasyMock.createMock(ViewEngineContext.class);
	Configuration config = EasyMock.createMock(Configuration.class);
	expect(config.getProperty(eq(ViewEngine.VIEW_FOLDER))).andReturn("/somewhere/else");
	expect(ctx.getConfiguration()).andReturn(config);
	expect(ctx.getView()).andReturn("index.jsp");
	replay(ctx, config);
	assertThat(viewEngineBase.resolveView(ctx), is("/somewhere/else/index.jsp"));
	verify(ctx, config);
}
 
Example #12
Source File: ViewEngineBaseTest.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveView() {
	ViewEngineContext ctx = EasyMock.createMock(ViewEngineContext.class);
	Configuration config = EasyMock.createMock(Configuration.class);
	expect(config.getProperty(eq(ViewEngine.VIEW_FOLDER))).andReturn(null);
	expect(ctx.getConfiguration()).andReturn(config);
	expect(ctx.getView()).andReturn("index.jsp");
	expect(ctx.getView()).andReturn("/somewhere/else/index.jsp");
	replay(ctx, config);
	assertThat(viewEngineBase.resolveView(ctx), is("/WEB-INF/views/index.jsp"));
	assertThat(viewEngineBase.resolveView(ctx), is("/somewhere/else/index.jsp"));
	verify(ctx, config);
}
 
Example #13
Source File: EventDispatcher.java    From krazo with Apache License 2.0 5 votes vote down vote up
public void fireAfterProcessViewEvent(ViewEngine engine, Viewable viewable) {
    if (KrazoCdiExtension.isEventObserved(AfterProcessViewEvent.class)) {
        final AfterProcessViewEventImpl event = new AfterProcessViewEventImpl();
        event.setEngine(engine.getClass());
        event.setView(viewable.getView());
        mvcEventDispatcher.fire(event);
    }
}
 
Example #14
Source File: ViewEngineFinder.java    From krazo with Apache License 2.0 5 votes vote down vote up
/**
 * Finds view engine for a viewable.
 *
 * @param viewable the viewable to be used.
 * @return selected view engine or {@code null} if none found.
 */
public ViewEngine find(Viewable viewable) {
    Optional<ViewEngine> engine;
    final String view = viewable.getView();

    // If engine specified in viewable, use it
    final Class<? extends ViewEngine> engineClass = viewable.getViewEngine();
    if (engineClass != null) {
        engine = Optional.of(cdiUtils.newBean(engineClass));
    } else {
        // Check cache first
        engine = Optional.ofNullable(cache.get(view));

        if (!engine.isPresent()) {
            List<ViewEngine> engines = CdiUtils.getApplicationBeans(ViewEngine.class);

            // Gather set of candidates
            final Set<ViewEngine> candidates = engines.stream()
                    .filter(e -> e.supports(view)).collect(toSet());

            // Find candidate with highest priority
            engine = candidates.stream().max(
                    (e1, e2) -> {
                        final Priority p1 = getAnnotation(e1.getClass(), Priority.class);
                        final int v1 = p1 != null ? p1.value() : ViewEngine.PRIORITY_APPLICATION;
                        final Priority p2 = getAnnotation(e2.getClass(), Priority.class);
                        final int v2 = p2 != null ? p2.value() : ViewEngine.PRIORITY_APPLICATION;
                        return v1 - v2;
                    });
            // Update cache
            if (engine.isPresent()) {
                cache.put(view, engine.get());
            }
        }
    }
    return engine.isPresent() ? engine.get() : null;
}
 
Example #15
Source File: BeforeProcessViewEventImpl.java    From krazo with Apache License 2.0 4 votes vote down vote up
@Override
public Class<? extends ViewEngine> getEngine() {
    return engine;
}
 
Example #16
Source File: MyApplication.java    From krazo with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, Object> getProperties() {
    final Map<String, Object> map = new HashMap<>();
    map.put(ViewEngine.VIEW_FOLDER, "/");       // overrides default /WEB-INF/
    return map;
}
 
Example #17
Source File: AfterProcessViewEventImpl.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
public AfterProcessViewEventImpl(String view, Class<? extends ViewEngine> viewEngine) {
	super(view, viewEngine);
}
 
Example #18
Source File: BeforeProcessViewEventImpl.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
public BeforeProcessViewEventImpl(String view, Class<? extends ViewEngine> viewEngine) {
	super(view, viewEngine);
}
 
Example #19
Source File: BaseProcessViewEventImpl.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
public Class<? extends ViewEngine> getEngine() {
	return viewEngine;
}
 
Example #20
Source File: BaseProcessViewEventImpl.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
public BaseProcessViewEventImpl(String view, Class<? extends ViewEngine> viewEngine) {
	this.view = view;
	this.viewEngine = viewEngine;
}
 
Example #21
Source File: ViewRendererMvcImpl.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
@Override
public void render(PortletRequest portletRequest, MimeResponse mimeResponse, PortletConfig portletConfig)
	throws PortletException {

	Map<String, Object> modelMap = models.asMap();

	for (Map.Entry<String, Object> entry : modelMap.entrySet()) {
		portletRequest.setAttribute(entry.getKey(), entry.getValue());
	}

	String viewName = (String) portletRequest.getAttribute(VIEW_NAME);

	if (viewName != null) {

		if (!viewName.contains(".")) {
			String defaultViewExtension = (String) configuration.getProperty(
					ConfigurationImpl.DEFAULT_VIEW_EXTENSION);

			viewName = viewName.concat(".").concat(defaultViewExtension);
		}

		ViewEngine supportingViewEngine = null;

		for (ViewEngine viewEngine : viewEngines) {

			if (viewEngine.supports(viewName)) {
				supportingViewEngine = viewEngine;

				break;
			}
		}

		if (supportingViewEngine == null) {
			throw new PortletException(new ViewEngineException("No ViewEngine found that supports " + viewName));
		}

		try {
			beanManager.fireEvent(new BeforeProcessViewEventImpl(viewName, supportingViewEngine.getClass()));

			supportingViewEngine.processView(new ViewEngineContextImpl(configuration, portletRequest, mimeResponse,
					models, portletRequest.getLocale()));

			beanManager.fireEvent(new AfterProcessViewEventImpl(viewName, supportingViewEngine.getClass()));
		}
		catch (ViewEngineException vee) {
			throw new PortletException(vee);
		}
	}

	if ((mutableBindingResult != null) && !mutableBindingResult.isConsulted()) {

		Set<ParamError> allErrors = mutableBindingResult.getAllErrors();

		for (ParamError paramError : allErrors) {

			if (LOG.isWarnEnabled()) {
				LOG.warn("BindingResult error not processed for " + paramError.getParamName() + ": " +
					paramError.getMessage());
			}
		}
	}
}
 
Example #22
Source File: TemplateEngineSupplierProducer.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
@ApplicationScoped
@Produces
public TemplateEngineSupplier getTemplateEngineSupplier(PortletConfig portletConfig, ServletContext servletContext,
														MvcContext mvcContext) {

	TemplateEngine templateEngine = new TemplateEngine();

	templateEngine.setMessageResolver(new PortletMessageResolver(portletConfig));

	Configuration configuration = mvcContext.getConfig();

	String templateLocation = (String) configuration.getProperty(ViewEngine.VIEW_FOLDER);

	if (templateLocation == null) {
		templateLocation = ViewEngine.DEFAULT_VIEW_FOLDER;
	}

	templateEngine.setTemplateResolver(new PortletTemplateResolver(servletContext,
			new CDITemplateLocationSupplier(templateLocation)));

	return new DefaultTemplateEngineSupplier(templateEngine);
}
 
Example #23
Source File: ViewableWriterTest.java    From ozark with Apache License 2.0 4 votes vote down vote up
/**
 * Test writeTo method.
 *
 * @throws Exception when a serious error occurs.
 */
@Test
public void testWriteTo() throws Exception {
    ViewableWriter writer = new ViewableWriter();

    Field mvcField = writer.getClass().getDeclaredField("mvc");
    mvcField.setAccessible(true);
    mvcField.set(writer, new MvcContextImpl());
    
    ViewEngineFinder finder = EasyMock.createStrictMock(ViewEngineFinder.class);
    Field finderField = writer.getClass().getDeclaredField("engineFinder");
    finderField.setAccessible(true);
    finderField.set(writer, finder);

    HttpServletRequest request = EasyMock.createStrictMock(HttpServletRequest.class);
    Field requestField = writer.getClass().getDeclaredField("injectedRequest");
    requestField.setAccessible(true);
    requestField.set(writer, request);

    Event<MvcEvent> dispatcher = EasyMock.createStrictMock(Event.class);
    Field dispatcherField = writer.getClass().getDeclaredField("dispatcher");
    dispatcherField.setAccessible(true);
    dispatcherField.set(writer, dispatcher);

    ViewEngine viewEngine = EasyMock.createStrictMock(ViewEngine.class);

    HttpServletResponse response = EasyMock.createStrictMock(HttpServletResponse.class);
    Field responseField = writer.getClass().getDeclaredField("injectedResponse");
    responseField.setAccessible(true);
    responseField.set(writer, response);

    Configuration config = EasyMock.createStrictMock(Configuration.class);
    Field configField = writer.getClass().getDeclaredField("config");
    configField.setAccessible(true);
    configField.set(writer, config);

    MultivaluedHashMap map = new MultivaluedHashMap();
    ArrayList<MediaType> contentTypes = new ArrayList<>();
    contentTypes.add(MediaType.TEXT_HTML_TYPE);
    map.put("Content-Type", contentTypes);

    Viewable viewable = new Viewable("myview");
    viewable.setModels(new ModelsImpl());

    expect(finder.find(anyObject())).andReturn(viewEngine);
    viewEngine.processView((ViewEngineContext) anyObject());

    replay(finder, request, viewEngine, response);
    writer.writeTo(viewable, null, null, new Annotation[] {}, MediaType.WILDCARD_TYPE, map, null);
    verify(finder, request, viewEngine, response);
}
 
Example #24
Source File: ViewableWriter.java    From krazo with Apache License 2.0 4 votes vote down vote up
/**
 * Searches for a suitable {@link javax.mvc.engine.ViewEngine} to process the view. If no engine
 * is found, is forwards the request back to the servlet container.
 */
@Override
public void writeTo(Viewable viewable, Class<?> aClass, Type type, Annotation[] annotations, MediaType resolvedMediaType,
                    MultivaluedMap<String, Object> headers, OutputStream out)
    throws IOException, WebApplicationException {

    // Find engine for this Viewable
    final ViewEngine engine = engineFinder.find(viewable);
    if (engine == null) {
        throw new ServerErrorException(messages.get("NoViewEngine", viewable), INTERNAL_SERVER_ERROR);
    }

    // build the full media type (including the charset) and make sure the response header is set correctly
    MediaType mediaType = buildMediaTypeWithCharset(resolvedMediaType);
    headers.putSingle(HttpHeaders.CONTENT_TYPE, mediaType);

    HttpServletRequest request = unwrapOriginalRequest(injectedRequest);
    HttpServletResponse response = unwrapOriginalResponse(injectedResponse);

    // Create wrapper for response
    final ServletOutputStream responseStream = new DelegatingServletOutputStream(out);
    final HttpServletResponse responseWrapper = new MvcHttpServletResponse(response, responseStream, mediaType, headers);

    // Pass request to view engine
    try {
        // If no models in viewable, inject via CDI
        Models models = viewable.getModels();
        if (models == null) {
            models = modelsInstance.get();
        }

        // Bind EL 'mvc' object in models
        models.put("mvc", mvc);

        // Execute the view engine
        eventDispatcher.fireBeforeProcessViewEvent(engine, viewable);
        try {

            // Process view using selected engine
            engine.processView(new ViewEngineContextImpl(viewable.getView(), models, request, responseWrapper,
                                                         headers, responseStream, mediaType, uriInfo, resourceInfo, config, mvc.getLocale()));

        } finally {
            eventDispatcher.fireAfterProcessViewEvent(engine, viewable);
        }

    } catch (ViewEngineException e) {
        throw new ServerErrorException(INTERNAL_SERVER_ERROR, e);
    } finally {
        responseWrapper.getWriter().flush();
    }
}
 
Example #25
Source File: AfterProcessViewEventImpl.java    From ozark with Apache License 2.0 4 votes vote down vote up
public void setEngine(Class<? extends ViewEngine> engine) {
    this.engine = engine;
}
 
Example #26
Source File: AfterProcessViewEventImpl.java    From ozark with Apache License 2.0 4 votes vote down vote up
public Class<? extends ViewEngine> getEngine() {
    return engine;
}
 
Example #27
Source File: BeforeProcessViewEventImpl.java    From ozark with Apache License 2.0 4 votes vote down vote up
public void setEngine(Class<? extends ViewEngine> engine) {
    this.engine = engine;
}
 
Example #28
Source File: BeforeProcessViewEventImpl.java    From ozark with Apache License 2.0 4 votes vote down vote up
@Override
public Class<? extends ViewEngine> getEngine() {
    return engine;
}
 
Example #29
Source File: BeforeProcessViewEventImpl.java    From krazo with Apache License 2.0 4 votes vote down vote up
public void setEngine(Class<? extends ViewEngine> engine) {
    this.engine = engine;
}
 
Example #30
Source File: MyApplication.java    From ozark with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, Object> getProperties() {
    final Map<String, Object> map = new HashMap<>();
    map.put(ViewEngine.VIEW_FOLDER, "/");       // overrides default /WEB-INF/
    return map;
}