@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)); }
/** * 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"); } }
@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()); }
@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()); }
/** * 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); }
/** * 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(); }
/** * 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(); }
@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()); }
@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()); }
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; }
@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; } }
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; }
public <T extends BaseDTO> Result getResponse(T result, Class<T> type) { Result status = Controller.status(result.getStatus()); if (result != null) { status = Controller.status(result.getStatus(), Json.toJson(wrapObjectForJson(result,type))); } return status; }
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))); }
@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)); }
public Result handle(Request request) { JsonNode json = request.body().asJson(); String requestType = json.get("requestType").asText(); switch (RequestType.valueOf(requestType)) { case CONFIG: return getConfigResponse(); case INIT: return getInitialValueResponse(json); case SEARCH: return getSearchResponse(json); } return Controller.badRequest(); }
/** * Return the response to the initial configuration * * @return a JSON response */ public Result getConfigResponse() { ObjectNode result = Json.newObject(); Map<PickerHandler.Parameters, String> configParameters = getHandle().config(getParameters()); if (configParameters != null) { for (Parameters configParameterName : configParameters.keySet()) { if (configParameterName.name().endsWith(I18N_PARAMETER_SUFFIX)) { result.put(configParameterName.name(), Msg.get(configParameters.get(configParameterName))); } else { result.put(configParameterName.name(), configParameters.get(configParameterName)); } } } return Controller.ok(result); }
/** * Return the response to a request for the initial values to be displayed * * @return a JSON response */ public Result getSearchResponse(JsonNode json) { ObjectNode result = Json.newObject(); // Get context parameters HashMap<String, String> context = extractContextFromJsonRequest(json); ISelectableValueHolderCollection<T> valueHolders = getHandle().getFoundValueHolders(json.get("searchString").asText(), context); valueHolderCollectionToJson(result, valueHolders); return Controller.ok(result); }
/** * Return true if the specified form contains a valid file field. * * @param fieldName * the field name * * @return a boolean */ public static boolean hasFileField(String fieldName) { boolean r = false; MultipartFormData body = Controller.request().body().asMultipartFormData(); if (body != null) { FileType fileType = getFileType(fieldName); String fileFieldName = getFileInputName(fieldName, fileType); switch (fileType) { case UPLOAD: if (body.getFile(fileFieldName) != null) { r = true; } break; case URL: if (body.asFormUrlEncoded().get(fileFieldName)[0] != null && !body.asFormUrlEncoded().get(fileFieldName)[0].equals("")) { r = true; } break; } } return r; }
/** * Get the file part of the attachment for UPLOAD type. * * @param fieldName * the field name */ public static FilePart getFilePart(String fieldName) { FileType fileType = getFileType(fieldName); if (fileType.equals(FileType.UPLOAD)) { MultipartFormData body = Controller.request().body().asMultipartFormData(); FilePart filePart = body.getFile(getFileInputName(fieldName, fileType)); return filePart; } return null; }
/** * Return a list of attachments for display or update. * * @param objectClass * the class of the object to which the attachment belong * @param objectId * the id of the object to which the attachment belong * @param canUpdate * true if the update authorization should be allocated * @param attachmentManagerPlugin * the service which is managing attachments * @param sessionManagerPlugin * the service which is managing user sessions */ private static List<Attachment> getFileAttachmentsForUpdateOrDisplay(Class<?> objectClass, Long objectId, boolean canUpdate, IAttachmentManagerPlugin attachmentManagerPlugin, IUserSessionManagerPlugin sessionManagerPlugin) { List<Attachment> attachments = attachmentManagerPlugin.getAttachmentsFromObjectTypeAndObjectId(objectClass, objectId, false); Set<Long> allowedIds = new HashSet<Long>(); for (Attachment attachment : attachments) { allowedIds.add(attachment.id); } String uid = sessionManagerPlugin.getUserSessionId(Controller.ctx()); allocateReadAuthorization(allowedIds, uid); if (canUpdate) { allocateUpdateAuthorization(allowedIds, uid); } return attachments; }
public String getCurrentStatementLanguage() { String lang = Controller.session("currentStatementLanguage"); if (lang == null) { return "en-US"; } return lang; }
@Override public F.Promise<Result> onError(Http.RequestHeader request, Throwable throwable) { if (throwable.getCause() instanceof AccessDeniedException) { return F.Promise.pure(Controller.unauthorized("UNAUTHORIZED")); } return super.onError(request, throwable); }
/** * Register the given user as the current user. (As part of logging in or switching to another user.) * Admin roles are not automatically active. Use {@link #setAdmin(java.util.Set)} for that. * @param user partially filled in user object */ public static void set (UserHeader user, Set<UserRole> roleSet) { Controller.session("id", Integer.toString(user.getId())); Controller.session("email", user.getEmail()); Controller.session("fullName", user.getFullName()); clearAdmin(roleSet); Controller.session("status", user.getStatus().name()); Controller.session("pa", Boolean.toString(isAdmin(roleSet))); // can this user promote to admin }
/** * Reset the roles to the restricted set. */ public static void clearAdmin (Set<UserRole> roleSet) { EnumSet<UserRole> es = EnumSet.copyOf(RESTRICTED_ROLES); es.retainAll(roleSet); if (roleSet.contains(UserRole.SUPER_USER)) { es.add(UserRole.CAR_USER); // to avoid problems with super users that are not members } Controller.session("roles", UserRole.toString(es)); }
/** * Retrieve the display name of the current user. Format: FirstName Name */ public static String getDisplayName() { String fullName = Controller.session("fullName"); if (fullName == null) { return null; } else { int pos = fullName.indexOf(','); return fullName.substring(pos + 2) + fullName.substring (0, pos); } }
public static Result getFileStreamResult(FileDAO dao, int fileId) { be.ugent.degage.db.models.File file = dao.getFile(fileId); if (file != null) { try { FileInputStream is = new FileInputStream(Paths.get(UPLOAD_FOLDER, file.getPath()).toFile()); //TODO: this cannot be sent with a Try-with-resources (stream already closed), check if Play disposes properly return file.getContentType() != null && !file.getContentType().isEmpty() ? Controller.ok(is).as(file.getContentType()) : Controller.ok(is); } catch (FileNotFoundException e) { Logger.error("Missing file: " + file.getPath()); return Controller.notFound(); } } else { return Controller.notFound(); } }
public String rss() throws IOException, FeedException { SyndFeed feed = new SyndFeedImpl(); feed.setTitle("hiscores.shmup.com"); feed.setFeedType("rss_2.0"); feed.setDescription("hiscores.shmup.com"); feed.setLink("http://hiscores.shmup.com"); List entries = new ArrayList(); feed.setEntries(entries); for (Score score : scores) { SyndEntry entry = new SyndEntryImpl(); entry.setTitle(score.getGameTitle()); entry.setAuthor(score.player.name); entry.setLink("http://hiscores.shmup.com/score/" + score.id); SyndContentImpl content = new SyndContentImpl(); content.setValue(score.tweet()); entry.setDescription(content); entry.setPublishedDate(score.getCreatedAt()); entry.setUpdatedDate(score.getCreatedAt()); SyndEnclosureImpl enclosure = new SyndEnclosureImpl(); enclosure.setUrl(score.game.cover); enclosure.setType(score.game.getCoverType()); entry.setEnclosures(Lists.newArrayList(enclosure)); entries.add(entry); } Writer writer = new StringWriter(); SyndFeedOutput output = new SyndFeedOutput(); output.output(feed, writer); writer.close(); Controller.response().setContentType("application/rss+xml"); return writer.toString(); }
public <M> Result getInvalidJsonMessage(M model) { return Controller.status(HttpStatus.SC_BAD_REQUEST, Json.toJson(model)) .withHeader("Access-Control-Allow-Origin", "*"); }
@Override public Result displayAccessForbidden() { return Controller.badRequest(views.html.error.access_forbidden.render(getMessagesPlugins().get("forbidden.access.title"))); }
public void fill(T entity) { entity.updatedBy = ActorDao.getActorByUid(this.userSessionManagerPlugin.getUserSessionId(Controller.ctx())); this.fillEntity(entity); }
/** * Whether the current user is logged in and has the given role. */ public static boolean hasRole (Role role) { String roleString = Controller.session("role"); return roleString != null && Role.valueOf(roleString) == role; }
/** * Whether the current user is logged in */ public static boolean isLoggedOut () { return Controller.session("id") == null; }
@Override public Result trend(Context ctx) { String uid = ctx.request().getQueryString("kpiUid"); Long objectId = Long.valueOf(ctx.request().getQueryString("objectId")); Kpi kpi = getKpi(uid); Date startDate = null; Date endDate = null; Triple<List<KpiData>, List<KpiData>, List<KpiData>> datas = kpi.getTrendData(objectId); Pair<String, List<KpiData>> staticTrendLine = kpi.getKpiRunner().getStaticTrendLine(this.getPreferenceManagerPlugin(), getScriptService(), kpi, objectId); SeriesContainer<TimeValueItem> seriesContainer = null; if (staticTrendLine != null || (datas.getLeft() != null && datas.getLeft().size() > 0) || (datas.getMiddle() != null && datas.getMiddle().size() > 0) || (datas.getRight() != null && datas.getRight().size() > 0)) { seriesContainer = new SeriesContainer<TimeValueItem>(); if (datas.getLeft() != null && datas.getLeft().size() > 0) { addTrendSerieAndValues(seriesContainer, kpi, DataType.MAIN, datas.getLeft()); } if (datas.getMiddle() != null && datas.getMiddle().size() > 0) { addTrendSerieAndValues(seriesContainer, kpi, DataType.ADDITIONAL1, datas.getMiddle()); } if (datas.getRight() != null && datas.getRight().size() > 0) { addTrendSerieAndValues(seriesContainer, kpi, DataType.ADDITIONAL2, datas.getRight()); } if (staticTrendLine != null) { framework.highcharts.data.Serie<TimeValueItem> timeSerie = new framework.highcharts.data.Serie<TimeValueItem>( getMessagesPlugin().get(staticTrendLine.getLeft())); seriesContainer.addSerie(timeSerie); for (KpiData kpiData : staticTrendLine.getRight()) { timeSerie.add(new TimeValueItem(HighchartsUtils.convertToUTCAndClean(kpiData.timestamp), kpiData.value.doubleValue())); } } Pair<Date, Date> period = kpi.getKpiRunner().getTrendPeriod(this.getPreferenceManagerPlugin(), getScriptService(), kpi, objectId); if (period != null) { startDate = period.getLeft(); endDate = period.getRight(); } } return Controller.ok(views.html.framework_views.parts.kpi.display_kpi_trend.render(uid, seriesContainer, startDate, endDate)); }
@Override public User getUser() { return userService .getUserByApiUser(Controller.request().getQueryString(SecuredApi.API_USER)); }
@Override public User getUser() { return this.userService .getUserByApiUser(Controller.request().getQueryString(SecuredApi.API_USER)); }
public void setCurrentStatementLanguage(String languageCode) { Controller.session("currentStatementLanguage", languageCode); }
public void establishContestWithPasswordCookie(String contestPassword) { Controller.response().setCookie(contestPassword, "true", (int) TimeUnit.SECONDS.convert(5, TimeUnit.HOURS)); }
public boolean hasEstablishedContestWithPasswordCookie(String contestPassword) { return Controller.request().cookie(contestPassword) != null; }