本文整理匯總了Java中play.mvc.Controller類的典型用法代碼示例。如果您正苦於以下問題:Java Controller類的具體用法?Java Controller怎麽用?Java Controller使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Controller類屬於play.mvc包,在下文中一共展示了Controller類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: renderFormField
import play.mvc.Controller; //導入依賴的package包/類
@Override
public Html renderFormField(II18nMessagesPlugin i18nMessagesPlugin, IUserSessionManagerPlugin userSessionManagerPlugin,
IImplementationDefinedObjectService implementationDefinedObjectService, Field field, boolean displayDescription) {
String description = "";
if (displayDescription) {
description = Msg.get(customAttributeDefinition.description);
}
String uid = userSessionManagerPlugin.getUserSessionId(Controller.ctx());
return views.html.framework_views.parts.checkboxlist.render(field, Msg.get(customAttributeDefinition.name), description,
customAttributeDefinition.getValueHoldersCollectionFromNameForDynamicMultiItemCustomAttribute(i18nMessagesPlugin, uid), true, false,
customAttributeDefinition.isRequired());
}
示例2: save
import play.mvc.Controller; //導入依賴的package包/類
@Transactional
@BodyParser.Of(BodyParser.Json.class)
public Result save() {
Cidadao cidadao = daoCidadao
.find(UUID.fromString(request().username()));
if (!cidadao.isFuncionario()) {
return unauthorized("Cidadão não autorizado");
}
Form<Mensagem> form = formFactory.form(Mensagem.class).bindFromRequest();
if (form.hasErrors()) {
String recebido = Controller.request().body().asJson().toString();
if (recebido.length() > 30) {
recebido = recebido.substring(0, 30) + "...";
}
Logger.debug("Submissão com erros: " + recebido + "; Erros: " + form.errorsAsJson());
return badRequest(form.errorsAsJson());
}
Mensagem mensagem = daoMensagem.create(form.get());
mensagem.setAutor(cidadao.getMinisterioDeAfiliacao());
return created(toJson(mensagem));
}
示例3: logAndReturnUnexpectedError
import play.mvc.Controller; //導入依賴的package包/類
/**
* Log the exception and return a generic error message.
*
* @param e
* an exception
* @param message
* a specific message to be added to the error log
* @param log
* a log instance
* @param configuration
* the Play configuration service
* @param messagePlugin
* the i18n messages service
*/
public static Result logAndReturnUnexpectedError(Exception e, String message, Logger.ALogger log, Configuration configuration,
II18nMessagesPlugin messagePlugin) {
try {
String uuid = UUID.randomUUID().toString();
log.error("Unexpected error with uuid " + uuid + (message != null ? " from " + message : ""), e);
if (configuration.getBoolean("maf.unexpected.error.trace")) {
String stackTrace = Utilities.getExceptionAsString(e);
return Controller.internalServerError(
views.html.error.unexpected_error_with_stacktrace.render(messagePlugin.get("unexpected.error.title"), uuid, stackTrace));
}
return Controller.internalServerError(views.html.error.unexpected_error.render(messagePlugin.get("unexpected.error.title"), uuid));
} catch (Exception exp) {
System.err.println("Unexpected error in logAndReturnUnexpectedError : prevent looping");
return Controller.internalServerError("Unexpected error");
}
}
示例4: renderFormField
import play.mvc.Controller; //導入依賴的package包/類
@Override
public Html renderFormField(II18nMessagesPlugin i18nMessagesPlugin, IUserSessionManagerPlugin userSessionManagerPlugin,
IImplementationDefinedObjectService implementationDefinedObjectService, Field field, boolean displayDescription) {
String description = "";
if (displayDescription) {
description = Msg.get(customAttributeDefinition.description);
}
if (!customAttributeDefinition.isAutoComplete()) {
String uid = userSessionManagerPlugin.getUserSessionId(Controller.ctx());
return views.html.framework_views.parts.dropdownlist.render(field, Msg.get(customAttributeDefinition.name),
customAttributeDefinition.getValueHoldersCollectionFromNameForDynamicSingleItemCustomAttribute(i18nMessagesPlugin, "%", uid), description,
true, customAttributeDefinition.isRequired(), false, false);
}
return views.html.framework_views.parts.autocomplete.render(field, Msg.get(customAttributeDefinition.name), description,
implementationDefinedObjectService.getRouteForDynamicSingleCustomAttributeApi().url(),
customAttributeDefinition.getContextParametersForDynamicApi());
}
示例5: getInitialValueResponse
import play.mvc.Controller; //導入依賴的package包/類
/**
* Return the response to a request for the initial values to be displayed
*
* @return a JSON response
*/
public Result getInitialValueResponse(JsonNode json) {
ObjectNode result = Json.newObject();
// Get the values passed as parameters
ArrayList<T> values = new ArrayList<T>();
JsonNode valuesNode = json.get("values");
if (valuesNode != null) {
for (JsonNode node : valuesNode) {
values.add(convertNodeToT(node));
}
}
// Get context parameters
HashMap<String, String> context = extractContextFromJsonRequest(json);
// Create the return structure
ISelectableValueHolderCollection<T> valueHolders = getHandle().getInitialValueHolders(values, context);
valueHolderCollectionToJson(result, valueHolders);
return Controller.ok(result);
}
示例6: downloadFileAttachment
import play.mvc.Controller; //導入依賴的package包/類
/**
* This method is to be integrated within a controller.<br/>
* It looks for the specified attachment and returns it if the user is
* allowed to access it.
*
* @param attachmentId
* the id of an attachment
* @param attachmentManagerPlugin
* the service which is managing attachments
* @param sessionManagerPlugin
* the service which is managing user sessions
* @return the attachment as a stream
*/
public static Result downloadFileAttachment(Long attachmentId, IAttachmentManagerPlugin attachmentManagerPlugin,
IUserSessionManagerPlugin sessionManagerPlugin) {
@SuppressWarnings("unchecked")
Set<Long> allowedIds = (Set<Long>) Cache
.get(IFrameworkConstants.ATTACHMENT_READ_AUTHZ_CACHE_PREFIX + sessionManagerPlugin.getUserSessionId(Controller.ctx()));
if (allowedIds != null && allowedIds.contains(attachmentId)) {
try {
Attachment attachment = attachmentManagerPlugin.getAttachmentFromId(attachmentId);
if (attachment.mimeType.equals(FileAttachmentHelper.FileType.URL.name())) {
return Controller.redirect(attachment.path);
} else {
Controller.response().setHeader("Content-Disposition", "attachment; filename=\"" + attachment.name + "\"");
return Controller.ok(attachmentManagerPlugin.getAttachmentContent(attachmentId));
}
} catch (IOException e) {
log.error("Error while retreiving the attachment content for " + attachmentId);
return Controller.badRequest();
}
}
return Controller.badRequest();
}
示例7: deleteFileAttachment
import play.mvc.Controller; //導入依賴的package包/類
/**
* This method is to be integrated within a controller.<br/>
* It looks for the specified attachment and delete it if the user is
* allowed to erase it.<br/>
* It is to be called by an AJAX GET with a single attribute : the id of the
* attachment.
*
* @param attachmentId
* the id of an attachment
* @param attachmentManagerPlugin
* the service which is managing attachments
* @param sessionManagerPlugin
* the service which is managing user sessions
* @return the result
*/
public static Result deleteFileAttachment(Long attachmentId, IAttachmentManagerPlugin attachmentManagerPlugin,
IUserSessionManagerPlugin sessionManagerPlugin) {
@SuppressWarnings("unchecked")
Set<Long> allowedIds = (Set<Long>) Cache
.get(IFrameworkConstants.ATTACHMENT_WRITE_AUTHZ_CACHE_PREFIX + sessionManagerPlugin.getUserSessionId(Controller.ctx()));
if (allowedIds != null && allowedIds.contains(attachmentId)) {
try {
attachmentManagerPlugin.deleteAttachment(attachmentId);
return Controller.ok();
} catch (IOException e) {
log.error("Error while deleting the attachment content for " + attachmentId);
return Controller.badRequest();
}
}
return Controller.badRequest();
}
示例8: getJsonResponse
import play.mvc.Controller; //導入依賴的package包/類
@Override
public Result getJsonResponse(Object obj, int code, Response response) {
StringWriter w = new StringWriter();
try {
getMapper().writeValue(w, obj);
} catch (Exception e) {
String message = "Error while marshalling the application response";
ApiLog.log.error(message, e);
try {
getMapper().writeValue(w, new ApiError(message));
} catch (Exception exp) {
throw new RuntimeException("Unexpected error while mashalling an ApiError message");
}
code = ERROR_API_RESPONSE_CODE;
}
response.setContentType("application/json");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", authorizedHeaders);
return Controller.status(code, w.toString());
}
示例9: execute
import play.mvc.Controller; //導入依賴的package包/類
@Override
public Promise<Result> execute(String path, Context ctx) {
for (WebCommand webCommand : webCommands) {
if (webCommand.isCompatible(path, ctx)) {
try {
return webCommand.call(path, ctx);
} catch (Exception e) {
log.error("Error while calling the web command", e);
return Promise.promise(() -> Controller.badRequest());
}
}
}
log.info("No compatible command found for path " + path);
if (log.isDebugEnabled()) {
log.debug("No compatible command found for path " + path);
}
return Promise.promise(() -> Controller.badRequest());
}
示例10: get
import play.mvc.Controller; //導入依賴的package包/類
public static ObjectType get(Class<? extends Controller> controllerClass) {
Class<? extends Model> entityClass = getEntityClassForController(controllerClass);
if (entityClass == null || !Model.class.isAssignableFrom(entityClass)) {
return null;
}
ObjectType type;
try {
type = (ObjectType) Java.invokeStaticOrParent(controllerClass, "createObjectType", entityClass);
} catch (Exception e) {
Logger.error(e, "Couldn't create an ObjectType. Use default one.");
type = new ObjectType(entityClass);
}
type.name = controllerClass.getSimpleName().replace("$", "");
type.controllerName = controllerClass.getSimpleName().toLowerCase().replace("$", "");
type.controllerClass = controllerClass;
return type;
}
示例11: getEntityClassForController
import play.mvc.Controller; //導入依賴的package包/類
@SuppressWarnings("unchecked")
public static Class<? extends Model> getEntityClassForController(Class<? extends Controller> controllerClass) {
if (controllerClass.isAnnotationPresent(For.class)) {
return controllerClass.getAnnotation(For.class).value();
}
for(Type it : controllerClass.getGenericInterfaces()) {
if(it instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType)it;
if (((Class<?>)type.getRawType()).getSimpleName().equals("CRUDWrapper")) {
return (Class<? extends Model>)type.getActualTypeArguments()[0];
}
}
}
String name = controllerClass.getSimpleName().replace("$", "");
name = "models." + name.substring(0, name.length() - 1);
try {
return (Class<? extends Model>) Play.classloader.loadClass(name);
} catch (ClassNotFoundException e) {
return null;
}
}
示例12: getStudent
import play.mvc.Controller; //導入依賴的package包/類
/**
* Get the Student that is currently logged in.
*
* @return The currently logged in student or null if no one is logged in.
*/
public static Student getStudent() {
String studentId = Controller.session().get("connected");
if (studentId == null) {
return null;
}
// Note this is an ugly hack to get around needing to be logged in during testing.
// In the tests, a session variable is passed with the value test, this should return
// a valid student so that controllers believe that a student is logged in.
if (studentId.equals("_tester")) {
return new Student("_tester", "firstName", "lastName", "[email protected]");
}
return Student.find().where().eq("studentId", studentId).findUnique();
}
示例13: getResponse
import play.mvc.Controller; //導入依賴的package包/類
public <T extends BaseDTO> Result getResponse(T result) {
Result status = Controller.status(result.getStatus());
if (result != null) {
status = Controller.status(result.getStatus(), Json.toJson(result));
}
return status;
}
示例14: getResponses
import play.mvc.Controller; //導入依賴的package包/類
public <T extends BaseDTO> Result getResponses(List<T> results, Class<T> type) {
Integer status = HttpStatus.SC_OK;
Optional<T> result = results.stream().findAny();
if (result.isPresent()) {
status = result.get().getStatus();
}
return Controller.status(status, Json.toJson(wrapListForJson(results, type)));
}
示例15: onClientError
import play.mvc.Controller; //導入依賴的package包/類
@Override
public Promise<Result> onClientError(RequestHeader requestHeader, int statusCode, String error) {
injectCommonServicesIncontext(Http.Context.current());
if (statusCode == play.mvc.Http.Status.NOT_FOUND) {
return Promise.promise(new Function0<Result>() {
public Result apply() throws Throwable {
if (requestHeader.path().startsWith(AbstractApiController.STANDARD_API_ROOT_URI)) {
return getApiControllerUtilsService().getJsonErrorResponse(new ApiError(404, "Not found"), Controller.ctx().response());
} else {
return play.mvc.Results.notFound(views.html.error.not_found.render(requestHeader.uri()));
}
}
});
}
if (statusCode == play.mvc.Http.Status.BAD_REQUEST) {
injectCommonServicesIncontext(Http.Context.current());
return Promise.promise(new Function0<Result>() {
public Result apply() throws Throwable {
if (requestHeader.path().startsWith(AbstractApiController.STANDARD_API_ROOT_URI)) {
return getApiControllerUtilsService().getJsonErrorResponse(new ApiError(400, error), Controller.ctx().response());
} else {
return play.mvc.Results.badRequest(views.html.error.bad_request.render());
}
}
});
}
return Promise.<Result> pure(play.mvc.Results.status(statusCode, "an unexpected error occured: " + error));
}