Java 类org.glassfish.jersey.server.mvc.Viewable 实例源码

项目:QDrill    文件:StatusResources.java   
@POST
@Path("/option/{optionName}")
@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) {
  try {
    work.getContext()
      .getOptionManager()
      .setOption(OptionValue.createOption(
        OptionValue.Kind.valueOf(kind),
        OptionValue.OptionType.SYSTEM,
        name,
        value));
  } catch (Exception e) {
    logger.debug("Could not update.", e);
  }
  return getSystemOptions();
}
项目:redirector    文件:RedirectorOfflineUI.java   
@GET
@Produces(MediaType.TEXT_HTML)
public Response defaultPage(@Context UriInfo ui) throws URISyntaxException {
    /*
    * This redirect is required due to change of "Jersey" version from "1.17" to "2.13".
    * The "1.*" version of jersey has property "FEATURE_REDIRECT".
    * For example, when making request "localhost:8888/context/dev", Jersey checks whether "FEATURE_REDIRECT" is set to "true" in ServletContainer and request does not end with '/'.
    * If so, trailing slash is added and redirect is occurred to "localhost:8888/context/dev/"
    *
    * Jersey "2.*" does not contain property "FEATURE_REDIRECT".
    * The code that made redirect in "1.*" jersey is commented out in ServletContainer.java:504
    * Jersey "2.*" resolves request even if '/' was not present in the end.
    * But all links in our *.jsp and *.html to *.js and *.css are relative. So without adding '/' in the end, files can not be opened.
    * To solve it, we introduced this redirect
    */
    if (!ui.getAbsolutePath().toString().endsWith("/")) {
        return Response.temporaryRedirect(new URI(ui.getAbsolutePath().toString() + "/")).build();
    } else {
        return Response.ok(new Viewable("/index.jsp", new HashMap<String, Object>())).build();
    }
}
项目:redirector    文件:DeciderUI.java   
@GET
@Produces(MediaType.TEXT_HTML)
public Response defaultPage(@Context UriInfo ui) throws URISyntaxException {
    /*
    * This redirect is required due to change of "Jersey" version from "1.17" to "2.13".
    * The "1.*" version of jersey has property "FEATURE_REDIRECT".
    * For example, when making request "localhost:8888/context/dev", Jersey checks whether "FEATURE_REDIRECT" is set to "true" in ServletContainer and request does not end with '/'.
    * If so, trailing slash is added and redirect is occurred to "localhost:8888/context/dev/"
    *
    * Jersey "2.*" does not contain property "FEATURE_REDIRECT".
    * The code that made redirect in "1.*" jersey is commented out in ServletContainer.java:504
    * Jersey "2.*" resolves request even if '/' was not present in the end.
    * But all links in our *.jsp and *.html to *.js and *.css are relative. So without adding '/' in the end, files can not be opened.
    * To solve it, we introduced this redirect
    */
    if (!ui.getAbsolutePath().toString().endsWith("/")) {
        return Response.temporaryRedirect(new URI(ui.getAbsolutePath().toString() + "/")).build();
    } else {
        return Response.ok(new Viewable("/index.jsp", new HashMap<String, Object>())).build();
    }
}
项目:redirector    文件:RedirectorUI.java   
@GET
@Produces(MediaType.TEXT_HTML)
public Response defaultPage(@Context UriInfo ui) throws URISyntaxException {
    /*
    * This redirect is required due to change of "Jersey" version from "1.17" to "2.13".
    * The "1.*" version of jersey has property "FEATURE_REDIRECT".
    * For example, when making request "localhost:8888/context/dev", Jersey checks whether "FEATURE_REDIRECT" is set to "true" in ServletContainer and request does not end with '/'.
    * If so, trailing slash is added and redirect is occurred to "localhost:8888/context/dev/"
    *
    * Jersey "2.*" does not contain property "FEATURE_REDIRECT".
    * The code that made redirect in "1.*" jersey is commented out in ServletContainer.java:504
    * Jersey "2.*" resolves request even if '/' was not present in the end.
    * But all links in our *.jsp and *.html to *.js and *.css are relative. So without adding '/' in the end, files can not be opened.
    * To solve it, we introduced this redirect
    */
    if (!ui.getAbsolutePath().toString().endsWith("/")) {
        return Response.temporaryRedirect(new URI(ui.getAbsolutePath().toString() + "/")).build();
    } else {
        return Response.ok(new Viewable("/index.jsp", new HashMap<String, Object>())).build();
    }
}
项目:fastquery    文件:VelocityTemplateProcessor.java   
@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模板实现
}
项目:rabbitframework    文件:FreemarkerViewProcessor.java   
@Override
public void writeTo(final Template template, final Viewable viewable, final MediaType mediaType,
                    final MultivaluedMap<String, Object> httpHeaders, final OutputStream out) throws IOException {
    try {
        Object model = viewable.getModel();
        if (!(model instanceof Map)) {
            model = new HashMap<String, Object>() {{
                put("model", viewable.getModel());
            }};
        }
        Charset encoding = setContentType(mediaType, httpHeaders);

        template.process(model, new OutputStreamWriter(out, encoding));
    } catch (TemplateException te) {
        throw new ContainerException(te);
    }
}
项目:drill    文件:StatusResources.java   
@SuppressWarnings("resource")
@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();
  } else {
    return getSystemPublicOptions();
  }
}
项目:drill    文件:QueryResources.java   
@POST
@Path("/query")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public Viewable submitQuery(@FormParam("query") String query,
                            @FormParam("queryType") String queryType) throws Exception {
  try {
    final String trimmedQueryString = CharMatcher.is(';').trimTrailingFrom(query.trim());
    final QueryResult result = submitQueryJSON(new QueryWrapper(trimmedQueryString, queryType));

    return ViewableWithPermissions.create(authEnabled.get(), "/rest/query/result.ftl", sc, new TabularResult(result));
  } catch (Exception | Error e) {
    logger.error("Query from Web UI Failed", e);
    return ViewableWithPermissions.create(authEnabled.get(), "/rest/query/errorMessage.ftl", sc, e);
  }
}
项目:drill    文件:LogInLogOutResources.java   
@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);
}
项目:drill    文件:LogInLogOutResources.java   
@GET
@Path(WebServerConstants.SPENGO_LOGIN_RESOURCE_PATH)
@Produces(MediaType.TEXT_HTML)
public Viewable getSpnegoLogin(@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)) {
    request.getRequestDispatcher(WebServerConstants.WEBSERVER_ROOT_PATH).forward(request, response);
    return null;
  }

  final String errorString = "Invalid SPNEGO credentials or SPNEGO is not configured";
  final DrillConfig drillConfig = workManager.getContext().getConfig();
  MainLoginPageModel model = new MainLoginPageModel(errorString, drillConfig);
  return ViewableWithPermissions.createMainLoginPage(model);
}
项目:oauth-service    文件:LoginResource.java   
@GET
public Response doLogin(@PathParam("code") final String code) {
    final Validation v = commonValidation(code);
    if (v.getError() != null) {
        return v.getError();
    }

    final LoginCode loginCode = v.getLoginCode();

    final List<UserClientScope> userClientScopes = getUserClientScopes(loginCode);

    if (!loginCode.getClient().isShowPromptNoScopes() &&
            (userClientScopes.isEmpty() || userClientScopes.stream().allMatch(ucs -> ucs.getAcceptedScope() != null))) {
        return acceptPermissions(code, "ok", new MultivaluedHashMap<>());
    }

    return Response.ok(
            new Viewable("/templates/Permissions.ftl", new PermissionsModel(loginCode, userClientScopes))
    ).build();
}
项目:XaaSPackager    文件:MainResource.java   
@GET
@Produces(MediaType.TEXT_HTML)
public Response root() {
    LOG.info("Mainpage is requested");

    List<DeploymentArtifactTopology> dats = new ArrayList<DeploymentArtifactTopology>();

    try {
        dats.addAll(new DATopologyDataSource().getDATs());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return Response.ok(
            new Viewable("index", new MainResourceDAO(Configuration
                    .getInstance(), dats))).build();
}
项目:git-webapp    文件:UserHtmlResource.java   
@GET
@Path("{userName}")
@Produces(MediaType.TEXT_HTML)
public Viewable index(@PathParam("userName") String userName, @QueryParam("tab") final String tab) {
  Account account = userService.findAccount(userName);

  MapViewable viewable = new MapViewable("/user/main.ftl").add("account", account).add("tab", tab);

  if ("activity".equals(tab)) {

  } else {
    viewable.add("repositories", repositoryService.getByOwner(userName));
  }

  return viewable;
}
项目:jersey-mvc-jasper    文件:JasperViewProcessor.java   
@Override
public void writeTo(JasperReport jr, Viewable vwbl, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream outputStream) throws IOException {
    JasperModel jasperModel = null;
    try{
        jasperModel = findJasperModel(vwbl);
    }catch(JRException e){
        throw new IllegalStateException("Cannot load jasper model", e);
    }
    try {
        JasperPrint print = getJasperFactory().getJasperProxy().fillReport(jr,
                jasperModel.getParameters(),
                jasperModel.getListModels());
        factory.getJasperProxy().exportReportToPDFStream(print, outputStream);
    } catch (JRException jre) {
        throw new IOException("Houve um problema ao gerar a ficha do snapshot/processo", jre);
    }
}
项目:ameba    文件:ErrorPageGenerator.java   
/**
 * <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);
    }
}
项目:ameba    文件:ResolvingViewableContext.java   
/**
 * 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;
}
项目:ameba    文件:AbstractTemplateProcessor.java   
/** {@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;
    }
}
项目:ameba    文件:ViewableMessageBodyWriter.java   
/**
 * 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;
}
项目:splinter    文件:UserDataInterceptor.java   
@Override
public void aroundWriteTo(final WriterInterceptorContext context) throws IOException, WebApplicationException {
    final Object entity = context.getEntity();
    if (entity instanceof Viewable) {
        User user = (User) securityContext.getUserPrincipal();

        if ( ((Viewable) entity).getModel() instanceof ViewData) {
            ViewData model = ((ViewData) ((Viewable) entity).getModel());
            model.set("authUser", user);
            String templateName = ((Viewable) entity).getTemplateName();
            context.setEntity(new Viewable(templateName, model.getData()));
        }
    }

    context.proceed();
}
项目:ameba-dev    文件:DevErrorPageGenerator.java   
@Override
public void writeTo(ErrorMessage errorMessage,
                    Class<?> type, Type genericType,
                    Annotation[] annotations, MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream) throws IOException, WebApplicationException {
    ContainerRequestContext request = requestProvider.get();
    int status = errorMessage.getStatus();

    if (status >= 500 && application.getMode().isDev()) {
        //开发模式,显示详细错误信息
        Error error = new Error(
                request,
                status,
                errorMessage.getThrowable(),
                errorMessage);

        Viewable viewable = Viewables.newDefaultViewable(DEFAULT_5XX_DEV_ERROR_PAGE, error);
        writeViewable(viewable, mediaType, httpHeaders, entityStream);
    } else {
        super.writeTo(errorMessage, type, genericType, annotations, mediaType, httpHeaders, entityStream);
    }
}
项目:usergrid    文件:AbstractContextResource.java   
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);
}
项目:usergrid    文件:AbstractContextResource.java   
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);
}
项目:usergrid    文件:AbstractContextResource.java   
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);
    }
项目:usergrid    文件:ManagementResource.java   
@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 );
}
项目:QDrill    文件:StatusResources.java   
@GET
@Path("/status")
@Produces(MediaType.TEXT_HTML)
public Viewable getStatus() {
  String status = "Running!";
  return new Viewable("/rest/status.ftl", status);
}
项目:QDrill    文件:ProfileResources.java   
@GET
@Path("/profiles")
@Produces(MediaType.TEXT_HTML)
public Viewable getProfiles() {
  QProfiles profiles = getProfilesJSON();
  return new Viewable("/rest/profile/list.ftl", profiles);
}
项目:QDrill    文件:ProfileResources.java   
@GET
@Path("/profiles/{queryid}")
@Produces(MediaType.TEXT_HTML)
public Viewable getProfile(@PathParam("queryid") String queryId) {
  ProfileWrapper wrapper = new ProfileWrapper(getQueryProfile(queryId));

  return new Viewable("/rest/profile/profile.ftl", wrapper);

}
项目:QDrill    文件:QueryResources.java   
@POST
@Path("/query")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public Viewable submitQuery(@FormParam("query") String query, @FormParam("queryType") String queryType) throws Exception {
  try {
    String trimmedQueryString = CharMatcher.is(';').trimTrailingFrom(query.trim());
    final QueryWrapper.QueryResult result = submitQueryJSON(new QueryWrapper(trimmedQueryString, queryType));
    return new Viewable("/rest/query/result.ftl", new TabularResult(result));
  } catch(Exception | Error e) {
    logger.error("Query from Web UI Failed", e);
    return new Viewable("/rest/query/errorMessage.ftl", e);
  }
}
项目:QDrill    文件:StorageResources.java   
@GET
@Path("/storage")
@Produces(MediaType.TEXT_HTML)
public Viewable getStoragePlugins() {
  List<PluginConfigWrapper> list = getStoragePluginsJSON();
  return new Viewable("/rest/storage/list.ftl", list);
}
项目:QDrill    文件:StorageResources.java   
@GET
@Path("/storage/{name}")
@Produces(MediaType.TEXT_HTML)
public Viewable getStoragePlugin(@PathParam("name") String name) {
  PluginConfigWrapper plugin = getStoragePluginJSON(name);
  return new Viewable("/rest/storage/update.ftl", plugin);
}
项目:dremio-oss    文件:ProfileResource.java   
@GET
@Path("/{queryid}")
@Produces(TEXT_HTML)
public Viewable getProfile(@PathParam("queryid") String queryId,
    @QueryParam("attempt") @DefaultValue("0") int attempt) {
  final QueryProfile profile;
  try {
    profile = jobsService.getProfile(new JobId(queryId), attempt);
  } 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 = context.getOptionManager().getOption(ExecConstants.DEBUG_QUERY_PROFILE);
  return renderProfile(profile, debug);
}
项目:dremio-oss    文件:ProfileResource.java   
@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);
  }
}
项目:dremio-oss    文件:TestResource.java   
@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);
}
项目:dremio-oss    文件:TestResource.java   
@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);
}
项目:protox-webapp-archetype    文件:ViewResource.java   
@GET
public Viewable index() throws SQLException {
    transaction.markRollback();
    LOGGER.info("{}", transaction);
    ResultSet rs = connection.createStatement().executeQuery("select 1;");
    while (rs.next()) {
        System.out.println(rs.getInt(1));
    }
    return new Viewable("/index", new TreeMap<String, Object>() {{
        put("name", name);
    }});
}
项目:java-oauth-server    文件:AuthorizationRequestHandlerSpiImpl.java   
@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("ticket",       info.getTicket());
    session.setAttribute("claimNames",   info.getClaims());
    session.setAttribute("claimLocales", info.getClaimsLocales());

    // 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();
}
项目:jersey-mvc-velocity    文件:VelocityViewProcessor.java   
@Override
@SuppressWarnings("unchecked")
public void writeTo(final Template template, final Viewable viewable, final MediaType mediaType,
                    final MultivaluedMap<String, Object> httpHeaders, final OutputStream out) throws IOException {
    try {
        Object model = viewable.getModel();
        if (!(model instanceof Map)) {
            model = new HashMap<String, Object>() {{
                put("model", viewable.getModel());
            }};
        }

        VelocityContext velocityContext = new VelocityContext();
        for (String key : ((Map<String, Object>) model).keySet()) {
            velocityContext.put(key, ((Map<String, Object>) model).get(key));
        }

        Charset encoding = setContentType(mediaType, httpHeaders);

        VelocityWriter writer = new VelocityWriter(new OutputStreamWriter(out, encoding));

        template.merge(velocityContext, writer);
        writer.flush();

    } catch (VelocityException te) {
        throw new ContainerException(te);
    }
}
项目:drill    文件:LogsResources.java   
@GET
@Path("/logs")
@Produces(MediaType.TEXT_HTML)
public Viewable getLogs() {
  Set<Log> logs = getLogsJSON();
  return ViewableWithPermissions.create(authEnabled.get(), "/rest/logs/list.ftl", sc, logs);
}
项目:drill    文件:LogsResources.java   
@GET
@Path("/log/{name}/content")
@Produces(MediaType.TEXT_HTML)
public Viewable getLog(@PathParam("name") String name) throws IOException {
  LogContent content = getLogJSON(name);
  return ViewableWithPermissions.create(authEnabled.get(), "/rest/logs/log.ftl", sc, content);
}
项目:drill    文件:StatusResources.java   
@GET
@Path(StatusResources.PATH_OPTIONS)
@RolesAllowed(DrillUserPrincipal.AUTHENTICATED_ROLE)
@Produces(MediaType.TEXT_HTML)
public Viewable getSystemPublicOptions() {
  return getSystemOptionsHelper(false);
}