org.glassfish.jersey.server.mvc.Viewable Java Examples

The following examples show how to use org.glassfish.jersey.server.mvc.Viewable. 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: ViewableMessageBodyWriter.java    From ameba with MIT License 6 votes vote down vote up
/**
 * Resolve given {@link org.glassfish.jersey.server.mvc.Viewable viewable}
 * for a list of {@link javax.ws.rs.core.MediaType mediaTypes} and a {@link Class resolvingClass}
 * using given {@link org.glassfish.jersey.server.mvc.spi.ViewableContext viewableContext}
 * and a set of {@link org.glassfish.jersey.server.mvc.spi.TemplateProcessor templateProcessors}
 *
 * @param viewable           viewable to be resolved.
 * @param mediaTypes         producible media types.
 * @param resolvingClass     non-null resolving class.
 * @param viewableContext    viewable context.
 * @param templateProcessors collection of available template processors.
 * @return resolved viewable or {@code null}, if the viewable cannot be resolved.
 */
private ResolvedViewable resolve(final Viewable viewable,
                                 final List<MediaType> mediaTypes,
                                 final Class<?> resolvingClass,
                                 final ViewableContext viewableContext,
                                 final Set<TemplateProcessor> templateProcessors) {
    for (TemplateProcessor templateProcessor : templateProcessors) {
        for (final MediaType mediaType : mediaTypes) {
            final ResolvedViewable resolvedViewable = viewableContext
                    .resolveViewable(viewable, mediaType, resolvingClass, templateProcessor);

            if (resolvedViewable != null) {
                return resolvedViewable;
            }
        }
    }

    return null;
}
 
Example #2
Source File: AbstractContextResource.java    From usergrid with Apache License 2.0 6 votes vote down vote up
public Viewable handleViewable(String template, Object model, OrganizationConfig orgConfig) {

        String className = this.getClass().getName().toLowerCase();
        String packageName = AbstractContextResource.class.getPackage().getName();

        String template_property = "usergrid.view" +
            StringUtils.removeEnd(className.toLowerCase(), "resource")
                .substring(packageName.length()) + "." + template.toLowerCase();

        String redirect_url = orgConfig.getProperty(template_property);

        if (StringUtils.isNotBlank(redirect_url)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Redirecting to URL: {}", redirect_url);
            }
            sendRedirect(redirect_url);
        }

        if (logger.isTraceEnabled()) {
            logger.trace("Dispatching to viewable with template: {}  property: {}", template, template_property);
        }

        return new Viewable(template, model);
    }
 
Example #3
Source File: VelocityTemplateProcessor.java    From fastquery with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(String templateReference, Viewable viewable, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
		OutputStream out) throws IOException {

	// 获取 模板引擎
	VelocityEngine velocityEngine = getVelocityEngine();

	// 实例化一个VelocityContext
	VelocityContext context = (VelocityContext) viewable.getModel();
	Enumeration<String> enums = request.getParameterNames();
	while (enums.hasMoreElements()) {
		String key = enums.nextElement();
		context.put(key, request.getParameter(key));
	}
	// 把request放进模板上下文里
	context.put("request", request);

	// 渲染并输出
	OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out);
	velocityEngine.mergeTemplate(templateReference, "utf8", context, outputStreamWriter);
	outputStreamWriter.flush();
	outputStreamWriter.close(); // 有必要关闭吗? 关闭了是否对jax-rs拦截器,servlet有影响,需要继续学习,参考jsp模板实现
}
 
Example #4
Source File: DeviceVerificationEndpoint.java    From java-oauth-server with Apache License 2.0 6 votes vote down vote up
/**
 * The verification endpoint for {@code GET} method. This method returns a
 * verification page where the end-user is asked to input her login credentials
 * (if not authenticated) and a user code.
 */
@GET
public Response get(
        @Context HttpServletRequest request,
        @Context UriInfo uriInfo)
{
    // Get user information from the existing session if present.
    User user = getUserFromSessionIfPresent(request);

    // Get the user code from the query parameters if present.
    String userCode = uriInfo.getQueryParameters().getFirst("user_code");

    // The model for rendering the verification page.
    DeviceVerificationPageModel model = new DeviceVerificationPageModel()
        .setUser(user)
        .setUserCode(userCode);

    // Create a response of "200 OK" having the verification page.
    return ok(new Viewable(TEMPLATE, model));
}
 
Example #5
Source File: StatusResources.java    From Bats with Apache License 2.0 6 votes vote down vote up
@POST
@Path("option/{optionName}")
@RolesAllowed(DrillUserPrincipal.ADMIN_ROLE)
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.TEXT_HTML)
public Viewable updateSystemOption(@FormParam("name") String name,
                                 @FormParam("value") String value,
                                 @FormParam("kind") String kind) {
  SystemOptionManager optionManager = work.getContext()
    .getOptionManager();

  try {
    optionManager.setLocalOption(OptionValue.Kind.valueOf(kind), name, value);
  } catch (Exception e) {
    logger.debug("Could not update.", e);
  }

  if (optionManager.getOptionDefinition(name).getMetaData().isInternal()) {
    return getSystemInternalOptions(null);
  } else {
    return getSystemPublicOptions(null);
  }
}
 
Example #6
Source File: ErrorPageGenerator.java    From ameba with MIT License 6 votes vote down vote up
/**
 * <p>writeViewable.</p>
 *
 * @param viewable     a {@link org.glassfish.jersey.server.mvc.Viewable} object.
 * @param mediaType    a {@link javax.ws.rs.core.MediaType} object.
 * @param httpHeaders  a {@link javax.ws.rs.core.MultivaluedMap} object.
 * @param entityStream a {@link java.io.OutputStream} object.
 * @throws java.io.IOException if any.
 */
protected void writeViewable(Viewable viewable,
                             MediaType mediaType,
                             MultivaluedMap<String, Object> httpHeaders,
                             OutputStream entityStream) throws IOException {
    MessageBodyWriter<Viewable> writer = workers.get().getMessageBodyWriter(Viewable.class, null,
            new Annotation[]{}, null);
    if (writer != null) {
        writer.writeTo(viewable,
                Viewable.class,
                Viewable.class,
                new Annotation[0],
                mediaType,
                httpHeaders,
                entityStream);
    }
}
 
Example #7
Source File: DeviceVerificationRequestHandlerSpiImpl.java    From java-oauth-server with Apache License 2.0 6 votes vote down vote up
@Override
public Response onValid(DeviceVerificationResponse info)
{
    // Ask the user to authorize the client.

    // Store some information to the user's session for later use.
    mSession.setAttribute("userCode",   mUserCode);
    mSession.setAttribute("claimNames", info.getClaimNames());
    mSession.setAttribute("acrs",       info.getAcrs());

    // The model for rendering the authorization page.
    DeviceAuthorizationPageModel model = new DeviceAuthorizationPageModel(info);

    // Create a response having the page.
    return ok(new Viewable(AUTHORIZATION_PAGE_TEMPLATE, model));
}
 
Example #8
Source File: DeviceVerificationRequestHandlerSpiImpl.java    From java-oauth-server with Apache License 2.0 6 votes vote down vote up
@Override
public Response onNotExist()
{
    // Urge the user to re-input a valid user code.

    // The user.
    User user = (User)mSession.getAttribute("user");

    // The model for rendering the verification page.
    DeviceVerificationPageModel model = new DeviceVerificationPageModel()
        .setUserCode(mUserCode)
        .setUser(user)
        .setNotification("The user code does not exist.");

    // Return a response of "404 Not Found" having the verification page and
    // urge the user to re-input a valid user code.
    return notFound(new Viewable(VERIFICATION_PAGE_TEMPLATE, model));
}
 
Example #9
Source File: QueryResources.java    From Bats with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/query")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public Viewable submitQuery(@FormParam("query") String query,
                            @FormParam("queryType") String queryType,
                            @FormParam("autoLimit") String autoLimit) throws Exception {
  try {
    final String trimmedQueryString = CharMatcher.is(';').trimTrailingFrom(query.trim());
    final QueryResult result = submitQueryJSON(new QueryWrapper(trimmedQueryString, queryType, autoLimit));
    List<Integer> rowsPerPageValues = work.getContext().getConfig().getIntList(ExecConstants.HTTP_WEB_CLIENT_RESULTSET_ROWS_PER_PAGE_VALUES);
    Collections.sort(rowsPerPageValues);
    final String rowsPerPageValuesAsStr = Joiner.on(",").join(rowsPerPageValues);
    return ViewableWithPermissions.create(authEnabled.get(), "/rest/query/result.ftl", sc, new TabularResult(result, rowsPerPageValuesAsStr));
  } catch (Exception | Error e) {
    logger.error("Query from Web UI Failed: {}", e);
    return ViewableWithPermissions.create(authEnabled.get(), "/rest/errorMessage.ftl", sc, e);
  }
}
 
Example #10
Source File: AbstractTemplateProcessor.java    From ameba with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void writeTo(T templateReference, Viewable viewable, MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders, OutputStream out) throws IOException {
    MediaType m = (MediaType) httpHeaders.getFirst(HttpHeaders.CONTENT_TYPE);
    if (m == null) m = mediaType;
    setContentType(m, httpHeaders);
    try {
        writeTemplate(templateReference, viewable, mediaType, httpHeaders, out);
    } catch (Exception e) {
        RuntimeException r;
        try {
            r = createException(e, templateReference);
        } catch (Exception ex) {
            if (ex instanceof AmebaException) {
                r = (RuntimeException) ex;
            } else {
                r = new TemplateException("create writeTo Exception error", e, -1);
            }
        }
        throw r;
    }
}
 
Example #11
Source File: ManagementResource.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@GET
@Path( "authorize" )
@Produces( MediaType.TEXT_HTML )
public Viewable showAuthorizeForm( @Context UriInfo ui, @QueryParam( "response_type" ) String response_type,
                                   @QueryParam( "client_id" ) String client_id,
                                   @QueryParam( "redirect_uri" ) String redirect_uri,
                                   @QueryParam( "scope" ) String scope, @QueryParam( "state" ) String state ) {

    responseType = response_type;
    clientId = client_id;
    redirectUri = redirect_uri;
    this.scope = scope;
    this.state = state;

    return handleViewable( "authorize_form", this );
}
 
Example #12
Source File: ProfileResource.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{queryid}")
@Produces(TEXT_HTML)
public Viewable getProfile(@PathParam("queryid") String queryId,
    @QueryParam("attempt") @DefaultValue("0") int attempt) {
  final QueryProfile profile;
  try {
    final String username = securityContext.getUserPrincipal().getName();
    QueryProfileRequest request = QueryProfileRequest.newBuilder()
      .setJobId(JobProtobuf.JobId.newBuilder()
        .setId(queryId)
        .build())
      .setAttempt(attempt)
      .setUserName(username)
      .build();
    profile = jobsService.getProfile(request);
  } catch (JobNotFoundException ignored) {
    // TODO: should this be JobResourceNotFoundException?
    throw new NotFoundException(format("Profile for JobId [%s] and Attempt [%d] not found.", queryId, attempt));
  }
  final boolean debug = projectOptionManager.getOption(ExecConstants.DEBUG_QUERY_PROFILE);
  return renderProfile(profile, debug);
}
 
Example #13
Source File: AbstractContextResource.java    From usergrid with Apache License 2.0 6 votes vote down vote up
public Viewable handleViewable(String template, Object model, UUID organizationId) {
    OrganizationConfig orgConfig;
    try {
        if (organizationId != null) {
            orgConfig = management.getOrganizationConfigByUuid(organizationId);
        } else {
            orgConfig = management.getOrganizationConfigDefaultsOnly();
        }
    }
    catch (Exception e) {
        // fall back to non-org
        if (logger.isInfoEnabled() && organizationId != null) {
            logger.info("handleViewable: unable to retrieve org config by org UUID: " + organizationId.toString());
        }
        orgConfig = management.getOrganizationConfigDefaultsOnly();
    }
    return handleViewable(template, model, orgConfig);
}
 
Example #14
Source File: AbstractContextResource.java    From usergrid with Apache License 2.0 6 votes vote down vote up
public Viewable handleViewable(String template, Object model, String organizationName) {
    OrganizationConfig orgConfig;
    try {
        if (!StringUtils.isBlank(organizationName)) {
            orgConfig = management.getOrganizationConfigByName(organizationName);
        } else {
            orgConfig = management.getOrganizationConfigDefaultsOnly();
        }
    }
    catch (Exception e) {
        // fall back to non-org
        if (logger.isInfoEnabled()) {
            logger.info("handleViewable: unable to retrieve org config by org name: " + organizationName);
        }
        orgConfig = management.getOrganizationConfigDefaultsOnly();
    }
    return handleViewable(template, model, orgConfig);
}
 
Example #15
Source File: ResolvingViewableContext.java    From ameba with MIT License 6 votes vote down vote up
/**
 * Resolve given {@link Viewable viewable} with relative template name using {@link MediaType media type},
 * {@code resolving class} and {@link TemplateProcessor template processor}.
 *
 * @param viewable          viewable to be resolved.
 * @param mediaType         media type of te output.
 * @param resolvingClass    resolving class.
 * @param templateProcessor template processor to be used.
 * @return resolved viewable or {@code null} if the viewable cannot be resolved.
 */
private ResolvedViewable resolveRelativeViewable(final Viewable viewable,
                                                 final Class<?> resolvingClass,
                                                 final MediaType mediaType,
                                                 final TemplateProcessor templateProcessor) {
    final String path = TemplateHelper.getTemplateName(viewable);

    ResolvedViewable resolvedViewable = resolveRelativeViewable(Viewables.PROTECTED_DIR + "/" + path,
            viewable, resolvingClass, mediaType, templateProcessor);

    if (resolvedViewable == null) {
        resolvedViewable = resolveRelativeViewable(path,
                viewable, resolvingClass, mediaType, templateProcessor);
    }

    return resolvedViewable;
}
 
Example #16
Source File: LogInLogOutResources.java    From Bats with Apache License 2.0 6 votes vote down vote up
@GET
@Path(WebServerConstants.FORM_LOGIN_RESOURCE_PATH)
@Produces(MediaType.TEXT_HTML)
public Viewable getLoginPage(@Context HttpServletRequest request, @Context HttpServletResponse response,
                             @Context SecurityContext sc, @Context UriInfo uriInfo,
                             @QueryParam(WebServerConstants.REDIRECT_QUERY_PARM) String redirect) throws Exception {

  if (AuthDynamicFeature.isUserLoggedIn(sc)) {
    // if the user is already login, forward the request to homepage.
    request.getRequestDispatcher(WebServerConstants.WEBSERVER_ROOT_PATH).forward(request, response);
    return null;
  }

  updateSessionRedirectInfo(redirect, request);
  return ViewableWithPermissions.createLoginPage(null);
}
 
Example #17
Source File: LogsResources.java    From Bats with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/log/{name}/content")
@Produces(MediaType.TEXT_HTML)
public Viewable getLog(@PathParam("name") String name) throws IOException {
  try {
    LogContent content = getLogJSON(name);
    return ViewableWithPermissions.create(authEnabled.get(), "/rest/logs/log.ftl", sc, content);
  } catch (Exception | Error e) {
    logger.error("Exception was thrown when fetching log {} :\n{}", name, e);
    return ViewableWithPermissions.create(authEnabled.get(), "/rest/errorMessage.ftl", sc, e);
  }
}
 
Example #18
Source File: ProfileResource.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static Viewable renderProfile(QueryProfile profile, boolean includeDebugColumns) {
  if(profile == null){
    throw new BadRequestException("Failed to get query profile.");
  }

  try {
    ProfileWrapper wrapper = new ProfileWrapper(profile, includeDebugColumns);
    return new Viewable("/rest/profile/profile.ftl", wrapper);
  } catch (Exception e){
    throw new BadRequestException("Failed to get query profile.", e);
  }
}
 
Example #19
Source File: UsersResource.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@GET
@Path( "resetpw" )
@Produces( MediaType.TEXT_HTML )
public Viewable showPasswordResetForm( @Context UriInfo ui ) {

    if ( tokens.isExternalSSOProviderEnabled() && !isServiceAdmin() ) {
        throw new IllegalArgumentException( "External SSO integration is enabled, admin users must reset password via" +
            " provider: "+ properties.getProperty(TokenServiceImpl.USERGRID_EXTERNAL_SSO_PROVIDER) );
    }

    return handleViewable( "resetpw_email_form", this );
}
 
Example #20
Source File: StatusResources.java    From Bats with Apache License 2.0 5 votes vote down vote up
@GET
@Path(StatusResources.PATH_OPTIONS)
@RolesAllowed(DrillUserPrincipal.AUTHENTICATED_ROLE)
@Produces(MediaType.TEXT_HTML)
public Viewable getSystemPublicOptions(@Context UriInfo uriInfo) {
  return getSystemOptionsHelper(false, uriInfo);
}
 
Example #21
Source File: StatusResources.java    From Bats with Apache License 2.0 5 votes vote down vote up
private Viewable getSystemOptionsHelper(boolean internal, UriInfo uriInfo) {
  List<OptionWrapper> options = getSystemOptionsJSONHelper(internal);
  List<String> fltrList = new ArrayList<>(work.getContext().getConfig().getStringList(ExecConstants.HTTP_WEB_OPTIONS_FILTERS));
  String currFilter = (uriInfo != null) ? uriInfo.getQueryParameters().getFirst(CURRENT_FILTER_PARAM) : null;
  if (currFilter == null) {
    currFilter = "";
  }

  return ViewableWithPermissions.create(authEnabled.get(),
    "/rest/options.ftl",
    sc,
    new OptionsListing(options, fltrList, currFilter));
}
 
Example #22
Source File: ErrorPageGenerator.java    From ameba with MIT License 5 votes vote down vote up
/**
 * <p>createViewable.</p>
 *
 * @param tplName      a {@link java.lang.String} object.
 * @param request      a {@link javax.ws.rs.container.ContainerRequestContext} object.
 * @param status       a int.
 * @param exception    a {@link java.lang.Throwable} object.
 * @param errorMessage a {@link ameba.message.error.ErrorMessage} object.
 * @return a {@link org.glassfish.jersey.server.mvc.Viewable} object.
 */
protected Viewable createViewable(String tplName, ContainerRequestContext request,
                                  int status, Throwable exception, ErrorMessage errorMessage) {
    Error error = new Error(
            request,
            status,
            exception,
            errorMessage);

    return Viewables.newDefaultViewable(tplName, error);
}
 
Example #23
Source File: LogInLogOutResources.java    From Bats with Apache License 2.0 5 votes vote down vote up
@GET
@Path(WebServerConstants.MAIN_LOGIN_RESOURCE_PATH)
@Produces(MediaType.TEXT_HTML)
public Viewable getMainLoginPage(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                 @Context SecurityContext sc, @Context UriInfo uriInfo,
                                 @QueryParam(WebServerConstants.REDIRECT_QUERY_PARM) String redirect) throws Exception {
  updateSessionRedirectInfo(redirect, request);
  final MainLoginPageModel model = new MainLoginPageModel(null);
  return ViewableWithPermissions.createMainLoginPage(model);
}
 
Example #24
Source File: ViewableMessageBodyWriter.java    From ameba with MIT License 5 votes vote down vote up
/**
 * Resolve the given {@link org.glassfish.jersey.server.mvc.Viewable viewable} using
 * {@link org.glassfish.jersey.server.mvc.spi.ViewableContext}.
 *
 * @param viewable viewable to be resolved.
 * @return resolved viewable or {@code null}, if the viewable cannot be resolved.
 */
private ResolvedViewable resolve(final Viewable viewable) {
    if (viewable instanceof ResolvedViewable) {
        return (ResolvedViewable) viewable;
    } else {
        final ViewableContext viewableContext = getViewableContext();
        final Set<TemplateProcessor> templateProcessors = getTemplateProcessors();

        List<MediaType> producibleMediaTypes = TemplateHelper
                .getProducibleMediaTypes(requestProvider.get(), extendedUriInfoProvider.get(), null);

        if (viewable instanceof ImplicitViewable) {
            // Template Names.
            final ImplicitViewable implicitViewable = (ImplicitViewable) viewable;

            for (final String templateName : implicitViewable.getTemplateNames()) {
                final Viewable simpleViewable = new Viewable(templateName, viewable.getModel());

                final ResolvedViewable resolvedViewable = resolve(simpleViewable, producibleMediaTypes,
                        implicitViewable.getResolvingClass(), viewableContext, templateProcessors);

                if (resolvedViewable != null) {
                    return resolvedViewable;
                }
            }
        } else {
            final Class<?> resourceClass = resourceInfoProvider.get().getResourceClass();
            return resolve(viewable, producibleMediaTypes, resourceClass, viewableContext, templateProcessors);
        }

        return null;
    }
}
 
Example #25
Source File: TestResource.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/render_external_profile")
@Produces(TEXT_HTML)
public Viewable renderExternalProfile(@FormParam("profileJsonText") String profileJsonText) throws IOException {
  QueryProfile profile = ProfileResource.SERIALIZER.deserialize(profileJsonText.getBytes());
  return ProfileResource.renderProfile(profile, true);
}
 
Example #26
Source File: TestResource.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/render_external_profile_file")
@Produces(TEXT_HTML)
public Viewable renderExternalProfileFile(@FormParam("profileJsonFile") String profileJsonFileText) throws IOException {
  java.nio.file.Path profilePath = Paths.get(profileJsonFileText);
  byte[] data = Files.readAllBytes(profilePath);
  QueryProfile profile = ProfileResource.SERIALIZER.deserialize(data);
  return ProfileResource.renderProfile(profile, true);
}
 
Example #27
Source File: AuthorizationRequestHandlerSpiImpl.java    From java-oauth-server with Apache License 2.0 5 votes vote down vote up
@Override
public Response generateAuthorizationPage(AuthorizationResponse info)
{
    // Create an HTTP session.
    HttpSession session = mRequest.getSession(true);

    // Store some variables into the session so that they can be
    // referred to later in AuthorizationDecisionEndpoint.
    session.setAttribute("params", Params.from(info));
    session.setAttribute("acrs",   info.getAcrs());
    session.setAttribute("client", info.getClient());

    mClient = info.getClient(); // update the client in case we need it with a no-interaction response

    // Clear the current user information in the session if necessary.
    clearCurrentUserInfoInSessionIfNecessary(info, session);

    // Get the user from the session if they exist.
    User user = (User)session.getAttribute("user");

    // Prepare a model object which contains information needed to
    // render the authorization page. Feel free to create a subclass
    // of AuthorizationPageModel or define another different class
    // according to what you need in the authorization page.
    AuthorizationPageModel model = new AuthorizationPageModel(info, user);

    // Create a Viewable instance that represents the authorization
    // page. Viewable is a class provided by Jersey for MVC.
    Viewable viewable = new Viewable(TEMPLATE, model);

    // Create a response that has the viewable as its content.
    return Response.ok(viewable, MEDIA_TYPE_HTML).build();
}
 
Example #28
Source File: ResolvingViewableContext.java    From ameba with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * Resolve given {@link Viewable viewable} using {@link MediaType media type}, {@code resolving class} and
 * {@link TemplateProcessor template processor}.
 */
public ResolvedViewable resolveViewable(final Viewable viewable, final MediaType mediaType,
                                        final Class<?> resourceClass, final TemplateProcessor templateProcessor) {
    if (viewable.isTemplateNameAbsolute()) {
        return resolveAbsoluteViewable(viewable, resourceClass, mediaType, templateProcessor);
    } else {
        if (resourceClass == null) {
            throw new ViewableContextException(LocalizationMessages.TEMPLATE_RESOLVING_CLASS_CANNOT_BE_NULL());
        }

        return resolveRelativeViewable(viewable, resourceClass, mediaType, templateProcessor);
    }
}
 
Example #29
Source File: TemplateMethodInterceptor.java    From ameba with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void aroundWriteTo(final WriterInterceptorContext context) throws IOException, WebApplicationException {
    final Object entity = context.getEntity();

    if (!(entity instanceof Viewable) && resourceInfoProvider.get().getResourceMethod() != null) {
        final Template template = TemplateHelper.getTemplateAnnotation(context.getAnnotations());
        if (template != null) {
            context.setType(Viewable.class);
            context.setEntity(new Viewable(template.name(), entity));
        }
    }

    context.proceed();
}
 
Example #30
Source File: ResolvingViewableContext.java    From ameba with MIT License 5 votes vote down vote up
/**
 * Resolve given {@link Viewable viewable} with absolute template name using {@link MediaType media type} and
 * {@link TemplateProcessor template processor}.
 *
 * @param viewable          viewable to be resolved.
 * @param mediaType         media type of te output.
 * @param resourceClass     resource class.
 * @param templateProcessor template processor to be used.
 * @return resolved viewable or {@code null} if the viewable cannot be resolved.
 */
@SuppressWarnings("unchecked")
private ResolvedViewable resolveAbsoluteViewable(final Viewable viewable, Class<?> resourceClass,
                                                 final MediaType mediaType,
                                                 final TemplateProcessor templateProcessor) {
    final Object resolvedTemplateObject = templateProcessor.resolve(viewable.getTemplateName(), mediaType);

    if (resolvedTemplateObject != null) {
        return new ResolvedViewable(templateProcessor, resolvedTemplateObject, viewable, resourceClass, mediaType);
    }

    return null;
}