下面列出了怎么用org.glassfish.jersey.server.mvc.Viewable的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
@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 );
}
@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);
}
}
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);
}
@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);
}
}
@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);
}
@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);
}
@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模板实现
}
/**
* 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));
}
@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));
}
@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));
}
/**
* <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);
}
}
/**
* 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;
}
/** {@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;
}
}
/**
* 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;
}
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);
}
@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 );
}
@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);
}
@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);
}
}
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));
}
@GET
@Path(StatusResources.PATH_OPTIONS)
@RolesAllowed(DrillUserPrincipal.AUTHENTICATED_ROLE)
@Produces(MediaType.TEXT_HTML)
public Viewable getSystemPublicOptions(@Context UriInfo uriInfo) {
return getSystemOptionsHelper(false, uriInfo);
}
@GET
@Path(StatusResources.PATH_INTERNAL_OPTIONS)
@RolesAllowed(DrillUserPrincipal.AUTHENTICATED_ROLE)
@Produces(MediaType.TEXT_HTML)
public Viewable getSystemInternalOptions(@Context UriInfo uriInfo) {
return getSystemOptionsHelper(true, uriInfo);
}
@GET
@Path("/profiles")
@Produces(MediaType.TEXT_HTML)
public Viewable getProfiles(@Context UriInfo uriInfo) {
QProfiles profiles = getProfilesJSON(uriInfo);
return ViewableWithPermissions.create(authEnabled.get(), "/rest/profile/list.ftl", sc, profiles);
}
@GET
@Path("/profiles/{queryid}")
@Produces(MediaType.TEXT_HTML)
public Viewable getProfile(@PathParam("queryid") String queryId){
try {
ProfileWrapper wrapper = new ProfileWrapper(getQueryProfile(queryId), work.getContext().getConfig());
return ViewableWithPermissions.create(authEnabled.get(), "/rest/profile/profile.ftl", sc, wrapper);
} catch (Exception | Error e) {
logger.error("Exception was thrown when fetching profile {} :\n{}", queryId, e);
return ViewableWithPermissions.create(authEnabled.get(), "/rest/errorMessage.ftl", sc, e);
}
}
@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 MainLoginPageModel model = new MainLoginPageModel(errorString);
return ViewableWithPermissions.createMainLoginPage(model);
}
@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);
}
@GET
@Path("/storage")
@Produces(MediaType.TEXT_HTML)
public Viewable getPlugins() {
List<PluginConfigWrapper> list = getPluginsJSON();
return ViewableWithPermissions.create(authEnabled.get(), "/rest/storage/list.ftl", sc, list);
}
@GET
@Path("/storage/{name}")
@Produces(MediaType.TEXT_HTML)
public Viewable getPlugin(@PathParam("name") String name) {
return ViewableWithPermissions.create(authEnabled.get(), "/rest/storage/update.ftl", sc,
getPluginConfig(name));
}
@GET
@Path("/{queryid}/reflection/{reflectionId}")
@Produces(TEXT_HTML)
public Viewable getReflectionJobProfile(@PathParam("queryid") String queryId,
@QueryParam("attempt") @DefaultValue("0") int attempt,
@PathParam("reflectionId") String reflectionId) {
if (Strings.isNullOrEmpty(reflectionId)) {
throw UserException.validationError()
.message("reflectionId cannot be null or empty")
.build();
}
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();
ReflectionJobProfileRequest.Builder builder = ReflectionJobProfileRequest.newBuilder().setQueryProfileRequest(request)
.setReflectionId(reflectionId);
profile = jobsService.getReflectionJobProfile(builder.build());
} catch (JobNotFoundException ignored) {
// TODO: should this be JobResourceNotFoundException?
throw new NotFoundException(format("Profile for JobId [%s] and Attempt [%d] not found.", queryId, attempt));
} catch (ReflectionJobValidationException e) {
throw new InvalidReflectionJobException(e.getJobId().getId(), e.getReflectionId());
}
final boolean debug = projectOptionManager.getOption(ExecConstants.DEBUG_QUERY_PROFILE);
return renderProfile(profile, debug);
}
@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);
}
}